OSDN Git Service

* ipa-struct-reorg.c (update_cgraph_with_malloc_call): Fix profile
[pf3gnuchains/gcc-fork.git] / gcc / cgraphunit.c
1 /* Callgraph based interprocedural optimizations.
2    Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009
3    Free Software Foundation, Inc.
4    Contributed by Jan Hubicka
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* This module implements main driver of compilation process as well as
23    few basic interprocedural optimizers.
24
25    The main scope of this file is to act as an interface in between
26    tree based frontends and the backend (and middle end)
27
28    The front-end is supposed to use following functionality:
29
30     - cgraph_finalize_function
31
32       This function is called once front-end has parsed whole body of function
33       and it is certain that the function body nor the declaration will change.
34
35       (There is one exception needed for implementing GCC extern inline
36         function.)
37
38     - varpool_finalize_variable
39
40       This function has same behavior as the above but is used for static
41       variables.
42
43     - cgraph_finalize_compilation_unit
44
45       This function is called once (source level) compilation unit is finalized
46       and it will no longer change.
47
48       In the the call-graph construction and local function
49       analysis takes place here.  Bodies of unreachable functions are released
50       to conserve memory usage.
51
52       The function can be called multiple times when multiple source level
53       compilation units are combined (such as in C frontend)
54
55     - cgraph_optimize
56
57       In this unit-at-a-time compilation the intra procedural analysis takes
58       place here.  In particular the static functions whose address is never
59       taken are marked as local.  Backend can then use this information to
60       modify calling conventions, do better inlining or similar optimizations.
61
62     - cgraph_mark_needed_node
63     - varpool_mark_needed_node
64
65       When function or variable is referenced by some hidden way the call-graph
66       data structure must be updated accordingly by this function.
67       There should be little need to call this function and all the references
68       should be made explicit to cgraph code.  At present these functions are
69       used by C++ frontend to explicitly mark the keyed methods.
70
71     - analyze_expr callback
72
73       This function is responsible for lowering tree nodes not understood by
74       generic code into understandable ones or alternatively marking
75       callgraph and varpool nodes referenced by the as needed.
76
77       ??? On the tree-ssa genericizing should take place here and we will avoid
78       need for these hooks (replacing them by genericizing hook)
79
80         Analyzing of all functions is deferred
81         to cgraph_finalize_compilation_unit and expansion into cgraph_optimize.
82
83         In cgraph_finalize_compilation_unit the reachable functions are
84         analyzed.  During analysis the call-graph edges from reachable
85         functions are constructed and their destinations are marked as
86         reachable.  References to functions and variables are discovered too
87         and variables found to be needed output to the assembly file.  Via
88         mark_referenced call in assemble_variable functions referenced by
89         static variables are noticed too.
90
91         The intra-procedural information is produced and its existence
92         indicated by global_info_ready.  Once this flag is set it is impossible
93         to change function from !reachable to reachable and thus
94         assemble_variable no longer call mark_referenced.
95
96         Finally the call-graph is topologically sorted and all reachable functions
97         that has not been completely inlined or are not external are output.
98
99         ??? It is possible that reference to function or variable is optimized
100         out.  We can not deal with this nicely because topological order is not
101         suitable for it.  For tree-ssa we may consider another pass doing
102         optimization and re-discovering reachable functions.
103
104         ??? Reorganize code so variables are output very last and only if they
105         really has been referenced by produced code, so we catch more cases
106         where reference has been optimized out.  */
107
108
109 #include "config.h"
110 #include "system.h"
111 #include "coretypes.h"
112 #include "tm.h"
113 #include "tree.h"
114 #include "rtl.h"
115 #include "tree-flow.h"
116 #include "tree-inline.h"
117 #include "langhooks.h"
118 #include "pointer-set.h"
119 #include "toplev.h"
120 #include "flags.h"
121 #include "ggc.h"
122 #include "debug.h"
123 #include "target.h"
124 #include "cgraph.h"
125 #include "diagnostic.h"
126 #include "timevar.h"
127 #include "params.h"
128 #include "fibheap.h"
129 #include "intl.h"
130 #include "function.h"
131 #include "ipa-prop.h"
132 #include "gimple.h"
133 #include "tree-iterator.h"
134 #include "tree-pass.h"
135 #include "tree-dump.h"
136 #include "output.h"
137 #include "coverage.h"
138
139 static void cgraph_expand_all_functions (void);
140 static void cgraph_mark_functions_to_output (void);
141 static void cgraph_expand_function (struct cgraph_node *);
142 static void cgraph_output_pending_asms (void);
143 static void cgraph_analyze_function (struct cgraph_node *);
144
145 static FILE *cgraph_dump_file;
146
147 /* A vector of FUNCTION_DECLs declared as static constructors.  */
148 static GTY (()) VEC(tree, gc) *static_ctors;
149 /* A vector of FUNCTION_DECLs declared as static destructors.  */
150 static GTY (()) VEC(tree, gc) *static_dtors;
151
152 /* When target does not have ctors and dtors, we call all constructor
153    and destructor by special initialization/destruction function
154    recognized by collect2.  
155    
156    When we are going to build this function, collect all constructors and
157    destructors and turn them into normal functions.  */
158
159 static void
160 record_cdtor_fn (tree fndecl)
161 {
162   struct cgraph_node *node;
163   if (targetm.have_ctors_dtors
164       || (!DECL_STATIC_CONSTRUCTOR (fndecl)
165           && !DECL_STATIC_DESTRUCTOR (fndecl)))
166     return;
167
168   if (DECL_STATIC_CONSTRUCTOR (fndecl))
169     {
170       VEC_safe_push (tree, gc, static_ctors, fndecl);
171       DECL_STATIC_CONSTRUCTOR (fndecl) = 0;
172     }
173   if (DECL_STATIC_DESTRUCTOR (fndecl))
174     {
175       VEC_safe_push (tree, gc, static_dtors, fndecl);
176       DECL_STATIC_DESTRUCTOR (fndecl) = 0;
177     }
178   node = cgraph_node (fndecl);
179   node->local.disregard_inline_limits = 1;
180   cgraph_mark_reachable_node (node);
181 }
182
183 /* Define global constructors/destructor functions for the CDTORS, of
184    which they are LEN.  The CDTORS are sorted by initialization
185    priority.  If CTOR_P is true, these are constructors; otherwise,
186    they are destructors.  */
187
188 static void
189 build_cdtor (bool ctor_p, tree *cdtors, size_t len)
190 {
191   size_t i;
192
193   i = 0;
194   while (i < len)
195     {
196       tree body;
197       tree fn;
198       priority_type priority;
199
200       priority = 0;
201       body = NULL_TREE;
202       /* Find the next batch of constructors/destructors with the same
203          initialization priority.  */
204       do
205         {
206           priority_type p;
207           fn = cdtors[i];
208           p = ctor_p ? DECL_INIT_PRIORITY (fn) : DECL_FINI_PRIORITY (fn);
209           if (!body)
210             priority = p;
211           else if (p != priority)
212             break;
213           append_to_statement_list (build_function_call_expr (UNKNOWN_LOCATION,
214                                                               fn, 0),
215                                     &body);
216           ++i;
217         }
218       while (i < len);
219       gcc_assert (body != NULL_TREE);
220       /* Generate a function to call all the function of like
221          priority.  */
222       cgraph_build_static_cdtor (ctor_p ? 'I' : 'D', body, priority);
223     }
224 }
225
226 /* Comparison function for qsort.  P1 and P2 are actually of type
227    "tree *" and point to static constructors.  DECL_INIT_PRIORITY is
228    used to determine the sort order.  */
229
230 static int
231 compare_ctor (const void *p1, const void *p2)
232 {
233   tree f1;
234   tree f2;
235   int priority1;
236   int priority2;
237
238   f1 = *(const tree *)p1;
239   f2 = *(const tree *)p2;
240   priority1 = DECL_INIT_PRIORITY (f1);
241   priority2 = DECL_INIT_PRIORITY (f2);
242   
243   if (priority1 < priority2)
244     return -1;
245   else if (priority1 > priority2)
246     return 1;
247   else
248     /* Ensure a stable sort.  */
249     return (const tree *)p1 - (const tree *)p2;
250 }
251
252 /* Comparison function for qsort.  P1 and P2 are actually of type
253    "tree *" and point to static destructors.  DECL_FINI_PRIORITY is
254    used to determine the sort order.  */
255
256 static int
257 compare_dtor (const void *p1, const void *p2)
258 {
259   tree f1;
260   tree f2;
261   int priority1;
262   int priority2;
263
264   f1 = *(const tree *)p1;
265   f2 = *(const tree *)p2;
266   priority1 = DECL_FINI_PRIORITY (f1);
267   priority2 = DECL_FINI_PRIORITY (f2);
268   
269   if (priority1 < priority2)
270     return -1;
271   else if (priority1 > priority2)
272     return 1;
273   else
274     /* Ensure a stable sort.  */
275     return (const tree *)p1 - (const tree *)p2;
276 }
277
278 /* Generate functions to call static constructors and destructors
279    for targets that do not support .ctors/.dtors sections.  These
280    functions have magic names which are detected by collect2.  */
281
282 static void
283 cgraph_build_cdtor_fns (void)
284 {
285   if (!VEC_empty (tree, static_ctors))
286     {
287       gcc_assert (!targetm.have_ctors_dtors);
288       qsort (VEC_address (tree, static_ctors),
289              VEC_length (tree, static_ctors), 
290              sizeof (tree),
291              compare_ctor);
292       build_cdtor (/*ctor_p=*/true,
293                    VEC_address (tree, static_ctors),
294                    VEC_length (tree, static_ctors)); 
295       VEC_truncate (tree, static_ctors, 0);
296     }
297
298   if (!VEC_empty (tree, static_dtors))
299     {
300       gcc_assert (!targetm.have_ctors_dtors);
301       qsort (VEC_address (tree, static_dtors),
302              VEC_length (tree, static_dtors), 
303              sizeof (tree),
304              compare_dtor);
305       build_cdtor (/*ctor_p=*/false,
306                    VEC_address (tree, static_dtors),
307                    VEC_length (tree, static_dtors)); 
308       VEC_truncate (tree, static_dtors, 0);
309     }
310 }
311
312 /* Determine if function DECL is needed.  That is, visible to something
313    either outside this translation unit, something magic in the system
314    configury.  */
315
316 bool
317 cgraph_decide_is_function_needed (struct cgraph_node *node, tree decl)
318 {
319   /* If the user told us it is used, then it must be so.  */
320   if (node->local.externally_visible)
321     return true;
322
323   /* ??? If the assembler name is set by hand, it is possible to assemble
324      the name later after finalizing the function and the fact is noticed
325      in assemble_name then.  This is arguably a bug.  */
326   if (DECL_ASSEMBLER_NAME_SET_P (decl)
327       && TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)))
328     return true;
329
330   /* With -fkeep-inline-functions we are keeping all inline functions except
331      for extern inline ones.  */
332   if (flag_keep_inline_functions
333       && DECL_DECLARED_INLINE_P (decl)
334       && !DECL_EXTERNAL (decl)
335       && !lookup_attribute ("always_inline", DECL_ATTRIBUTES (decl)))
336      return true;
337
338   /* If we decided it was needed before, but at the time we didn't have
339      the body of the function available, then it's still needed.  We have
340      to go back and re-check its dependencies now.  */
341   if (node->needed)
342     return true;
343
344   /* Externally visible functions must be output.  The exception is
345      COMDAT functions that must be output only when they are needed.
346
347      When not optimizing, also output the static functions. (see
348      PR24561), but don't do so for always_inline functions, functions
349      declared inline and nested functions.  These was optimized out
350      in the original implementation and it is unclear whether we want
351      to change the behavior here.  */
352   if (((TREE_PUBLIC (decl)
353         || (!optimize && !node->local.disregard_inline_limits
354             && !DECL_DECLARED_INLINE_P (decl)
355             && !node->origin))
356        && !flag_whole_program
357        && !flag_lto
358        && !flag_whopr)
359       && !DECL_COMDAT (decl) && !DECL_EXTERNAL (decl))
360     return true;
361
362   /* Constructors and destructors are reachable from the runtime by
363      some mechanism.  */
364   if (DECL_STATIC_CONSTRUCTOR (decl) || DECL_STATIC_DESTRUCTOR (decl))
365     return true;
366
367   return false;
368 }
369
370 /* Process CGRAPH_NEW_FUNCTIONS and perform actions necessary to add these
371    functions into callgraph in a way so they look like ordinary reachable
372    functions inserted into callgraph already at construction time.  */
373
374 bool
375 cgraph_process_new_functions (void)
376 {
377   bool output = false;
378   tree fndecl;
379   struct cgraph_node *node;
380
381   /*  Note that this queue may grow as its being processed, as the new
382       functions may generate new ones.  */
383   while (cgraph_new_nodes)
384     {
385       node = cgraph_new_nodes;
386       fndecl = node->decl;
387       cgraph_new_nodes = cgraph_new_nodes->next_needed;
388       switch (cgraph_state)
389         {
390         case CGRAPH_STATE_CONSTRUCTION:
391           /* At construction time we just need to finalize function and move
392              it into reachable functions list.  */
393
394           node->next_needed = NULL;
395           cgraph_finalize_function (fndecl, false);
396           cgraph_mark_reachable_node (node);
397           output = true;
398           break;
399
400         case CGRAPH_STATE_IPA:
401         case CGRAPH_STATE_IPA_SSA:
402           /* When IPA optimization already started, do all essential
403              transformations that has been already performed on the whole
404              cgraph but not on this function.  */
405
406           gimple_register_cfg_hooks ();
407           if (!node->analyzed)
408             cgraph_analyze_function (node);
409           push_cfun (DECL_STRUCT_FUNCTION (fndecl));
410           current_function_decl = fndecl;
411           compute_inline_parameters (node);
412           if ((cgraph_state == CGRAPH_STATE_IPA_SSA
413               && !gimple_in_ssa_p (DECL_STRUCT_FUNCTION (fndecl)))
414               /* When not optimizing, be sure we run early local passes anyway
415                  to expand OMP.  */
416               || !optimize)
417             execute_pass_list (pass_early_local_passes.pass.sub);
418           free_dominance_info (CDI_POST_DOMINATORS);
419           free_dominance_info (CDI_DOMINATORS);
420           pop_cfun ();
421           current_function_decl = NULL;
422           break;
423
424         case CGRAPH_STATE_EXPANSION:
425           /* Functions created during expansion shall be compiled
426              directly.  */
427           node->process = 0;
428           cgraph_expand_function (node);
429           break;
430
431         default:
432           gcc_unreachable ();
433           break;
434         }
435       cgraph_call_function_insertion_hooks (node);
436     }
437   return output;
438 }
439
440 /* As an GCC extension we allow redefinition of the function.  The
441    semantics when both copies of bodies differ is not well defined.
442    We replace the old body with new body so in unit at a time mode
443    we always use new body, while in normal mode we may end up with
444    old body inlined into some functions and new body expanded and
445    inlined in others.
446
447    ??? It may make more sense to use one body for inlining and other
448    body for expanding the function but this is difficult to do.  */
449
450 static void
451 cgraph_reset_node (struct cgraph_node *node)
452 {
453   /* If node->process is set, then we have already begun whole-unit analysis.
454      This is *not* testing for whether we've already emitted the function.
455      That case can be sort-of legitimately seen with real function redefinition
456      errors.  I would argue that the front end should never present us with
457      such a case, but don't enforce that for now.  */
458   gcc_assert (!node->process);
459
460   /* Reset our data structures so we can analyze the function again.  */
461   memset (&node->local, 0, sizeof (node->local));
462   memset (&node->global, 0, sizeof (node->global));
463   memset (&node->rtl, 0, sizeof (node->rtl));
464   node->analyzed = false;
465   node->local.redefined_extern_inline = true;
466   node->local.finalized = false;
467
468   cgraph_node_remove_callees (node);
469
470   /* We may need to re-queue the node for assembling in case
471      we already proceeded it and ignored as not needed or got
472      a re-declaration in IMA mode.  */
473   if (node->reachable)
474     {
475       struct cgraph_node *n;
476
477       for (n = cgraph_nodes_queue; n; n = n->next_needed)
478         if (n == node)
479           break;
480       if (!n)
481         node->reachable = 0;
482     }
483 }
484
485 static void
486 cgraph_lower_function (struct cgraph_node *node)
487 {
488   if (node->lowered)
489     return;
490
491   if (node->nested)
492     lower_nested_functions (node->decl);
493   gcc_assert (!node->nested);
494
495   tree_lowering_passes (node->decl);
496   node->lowered = true;
497 }
498
499 /* DECL has been parsed.  Take it, queue it, compile it at the whim of the
500    logic in effect.  If NESTED is true, then our caller cannot stand to have
501    the garbage collector run at the moment.  We would need to either create
502    a new GC context, or just not compile right now.  */
503
504 void
505 cgraph_finalize_function (tree decl, bool nested)
506 {
507   struct cgraph_node *node = cgraph_node (decl);
508
509   if (node->local.finalized)
510     cgraph_reset_node (node);
511
512   node->pid = cgraph_max_pid ++;
513   notice_global_symbol (decl);
514   node->local.finalized = true;
515   node->lowered = DECL_STRUCT_FUNCTION (decl)->cfg != NULL;
516   node->finalized_by_frontend = true;
517   record_cdtor_fn (node->decl);
518
519   if (cgraph_decide_is_function_needed (node, decl))
520     cgraph_mark_needed_node (node);
521
522   /* Since we reclaim unreachable nodes at the end of every language
523      level unit, we need to be conservative about possible entry points
524      there.  */
525   if ((TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_EXTERNAL (decl)))
526     cgraph_mark_reachable_node (node);
527
528   /* If we've not yet emitted decl, tell the debug info about it.  */
529   if (!TREE_ASM_WRITTEN (decl))
530     (*debug_hooks->deferred_inline_function) (decl);
531
532   /* Possibly warn about unused parameters.  */
533   if (warn_unused_parameter)
534     do_warn_unused_parameter (decl);
535
536   if (!nested)
537     ggc_collect ();
538 }
539
540 /* C99 extern inline keywords allow changing of declaration after function
541    has been finalized.  We need to re-decide if we want to mark the function as
542    needed then.   */
543
544 void
545 cgraph_mark_if_needed (tree decl)
546 {
547   struct cgraph_node *node = cgraph_node (decl);
548   if (node->local.finalized && cgraph_decide_is_function_needed (node, decl))
549     cgraph_mark_needed_node (node);
550 }
551
552 /* Return TRUE if NODE2 is equivalent to NODE or its clone.  */
553 static bool
554 clone_of_p (struct cgraph_node *node, struct cgraph_node *node2)
555 {
556   while (node != node2 && node2)
557     node2 = node2->clone_of;
558   return node2 != NULL;
559 }
560
561 /* Verify cgraph nodes of given cgraph node.  */
562 void
563 verify_cgraph_node (struct cgraph_node *node)
564 {
565   struct cgraph_edge *e;
566   struct function *this_cfun = DECL_STRUCT_FUNCTION (node->decl);
567   struct function *saved_cfun = cfun;
568   basic_block this_block;
569   gimple_stmt_iterator gsi;
570   bool error_found = false;
571
572   if (errorcount || sorrycount)
573     return;
574
575   timevar_push (TV_CGRAPH_VERIFY);
576   /* debug_generic_stmt needs correct cfun */
577   set_cfun (this_cfun);
578   for (e = node->callees; e; e = e->next_callee)
579     if (e->aux)
580       {
581         error ("aux field set for edge %s->%s",
582                identifier_to_locale (cgraph_node_name (e->caller)),
583                identifier_to_locale (cgraph_node_name (e->callee)));
584         error_found = true;
585       }
586   if (node->count < 0)
587     {
588       error ("Execution count is negative");
589       error_found = true;
590     }
591   if (node->global.inlined_to && node->local.externally_visible)
592     {
593       error ("Externally visible inline clone");
594       error_found = true;
595     }
596   if (node->global.inlined_to && node->address_taken)
597     {
598       error ("Inline clone with address taken");
599       error_found = true;
600     }
601   if (node->global.inlined_to && node->needed)
602     {
603       error ("Inline clone is needed");
604       error_found = true;
605     }
606   for (e = node->callers; e; e = e->next_caller)
607     {
608       if (e->count < 0)
609         {
610           error ("caller edge count is negative");
611           error_found = true;
612         }
613       if (e->frequency < 0)
614         {
615           error ("caller edge frequency is negative");
616           error_found = true;
617         }
618       if (e->frequency > CGRAPH_FREQ_MAX)
619         {
620           error ("caller edge frequency is too large");
621           error_found = true;
622         }
623       if (gimple_has_body_p (e->caller->decl)
624           && !e->caller->global.inlined_to
625           && (e->frequency
626               != compute_call_stmt_bb_frequency (e->caller->decl,
627                                                  gimple_bb (e->call_stmt))))
628         {
629           error ("caller edge frequency %i does not match BB freqency %i",
630                  e->frequency,
631                  compute_call_stmt_bb_frequency (e->caller->decl,
632                                                  gimple_bb (e->call_stmt)));
633           error_found = true;
634         }
635       if (!e->inline_failed)
636         {
637           if (node->global.inlined_to
638               != (e->caller->global.inlined_to
639                   ? e->caller->global.inlined_to : e->caller))
640             {
641               error ("inlined_to pointer is wrong");
642               error_found = true;
643             }
644           if (node->callers->next_caller)
645             {
646               error ("multiple inline callers");
647               error_found = true;
648             }
649         }
650       else
651         if (node->global.inlined_to)
652           {
653             error ("inlined_to pointer set for noninline callers");
654             error_found = true;
655           }
656     }
657   if (!node->callers && node->global.inlined_to)
658     {
659       error ("inlined_to pointer is set but no predecessors found");
660       error_found = true;
661     }
662   if (node->global.inlined_to == node)
663     {
664       error ("inlined_to pointer refers to itself");
665       error_found = true;
666     }
667
668   if (!cgraph_node (node->decl))
669     {
670       error ("node not found in cgraph_hash");
671       error_found = true;
672     }
673
674   if (node->clone_of)
675     {
676       struct cgraph_node *n;
677       for (n = node->clone_of->clones; n; n = n->next_sibling_clone)
678         if (n == node)
679           break;
680       if (!n)
681         {
682           error ("node has wrong clone_of");
683           error_found = true;
684         }
685     }
686   if (node->clones)
687     {
688       struct cgraph_node *n;
689       for (n = node->clones; n; n = n->next_sibling_clone)
690         if (n->clone_of != node)
691           break;
692       if (n)
693         {
694           error ("node has wrong clone list");
695           error_found = true;
696         }
697     }
698   if ((node->prev_sibling_clone || node->next_sibling_clone) && !node->clone_of)
699     {
700        error ("node is in clone list but it is not clone");
701        error_found = true;
702     }
703   if (!node->prev_sibling_clone && node->clone_of && node->clone_of->clones != node)
704     {
705       error ("node has wrong prev_clone pointer");
706       error_found = true;
707     }
708   if (node->prev_sibling_clone && node->prev_sibling_clone->next_sibling_clone != node)
709     {
710       error ("double linked list of clones corrupted");
711       error_found = true;
712     }
713
714   if (node->analyzed && gimple_has_body_p (node->decl)
715       && !TREE_ASM_WRITTEN (node->decl)
716       && (!DECL_EXTERNAL (node->decl) || node->global.inlined_to)
717       && !flag_wpa)
718     {
719       if (this_cfun->cfg)
720         {
721           /* The nodes we're interested in are never shared, so walk
722              the tree ignoring duplicates.  */
723           struct pointer_set_t *visited_nodes = pointer_set_create ();
724           /* Reach the trees by walking over the CFG, and note the
725              enclosing basic-blocks in the call edges.  */
726           FOR_EACH_BB_FN (this_block, this_cfun)
727             for (gsi = gsi_start_bb (this_block);
728                  !gsi_end_p (gsi);
729                  gsi_next (&gsi))
730               {
731                 gimple stmt = gsi_stmt (gsi);
732                 tree decl;
733                 if (is_gimple_call (stmt) && (decl = gimple_call_fndecl (stmt)))
734                   {
735                     struct cgraph_edge *e = cgraph_edge (node, stmt);
736                     if (e)
737                       {
738                         if (e->aux)
739                           {
740                             error ("shared call_stmt:");
741                             debug_gimple_stmt (stmt);
742                             error_found = true;
743                           }
744                         if (!clone_of_p (cgraph_node (decl), e->callee)
745                             && !e->callee->global.inlined_to)
746                           {
747                             error ("edge points to wrong declaration:");
748                             debug_tree (e->callee->decl);
749                             fprintf (stderr," Instead of:");
750                             debug_tree (decl);
751                           }
752                         e->aux = (void *)1;
753                       }
754                     else
755                       {
756                         error ("missing callgraph edge for call stmt:");
757                         debug_gimple_stmt (stmt);
758                         error_found = true;
759                       }
760                   }
761               }
762           pointer_set_destroy (visited_nodes);
763         }
764       else
765         /* No CFG available?!  */
766         gcc_unreachable ();
767
768       for (e = node->callees; e; e = e->next_callee)
769         {
770           if (!e->aux && !e->indirect_call)
771             {
772               error ("edge %s->%s has no corresponding call_stmt",
773                      identifier_to_locale (cgraph_node_name (e->caller)),
774                      identifier_to_locale (cgraph_node_name (e->callee)));
775               debug_gimple_stmt (e->call_stmt);
776               error_found = true;
777             }
778           e->aux = 0;
779         }
780     }
781   if (error_found)
782     {
783       dump_cgraph_node (stderr, node);
784       internal_error ("verify_cgraph_node failed");
785     }
786   set_cfun (saved_cfun);
787   timevar_pop (TV_CGRAPH_VERIFY);
788 }
789
790 /* Verify whole cgraph structure.  */
791 void
792 verify_cgraph (void)
793 {
794   struct cgraph_node *node;
795
796   if (sorrycount || errorcount)
797     return;
798
799   for (node = cgraph_nodes; node; node = node->next)
800     verify_cgraph_node (node);
801 }
802
803 /* Output all asm statements we have stored up to be output.  */
804
805 static void
806 cgraph_output_pending_asms (void)
807 {
808   struct cgraph_asm_node *can;
809
810   if (errorcount || sorrycount)
811     return;
812
813   for (can = cgraph_asm_nodes; can; can = can->next)
814     assemble_asm (can->asm_str);
815   cgraph_asm_nodes = NULL;
816 }
817
818 /* Analyze the function scheduled to be output.  */
819 static void
820 cgraph_analyze_function (struct cgraph_node *node)
821 {
822   tree save = current_function_decl;
823   tree decl = node->decl;
824
825   current_function_decl = decl;
826   push_cfun (DECL_STRUCT_FUNCTION (decl));
827
828   /* Make sure to gimplify bodies only once.  During analyzing a
829      function we lower it, which will require gimplified nested
830      functions, so we can end up here with an already gimplified
831      body.  */
832   if (!gimple_body (decl))
833     gimplify_function_tree (decl);
834   dump_function (TDI_generic, decl);
835
836   cgraph_lower_function (node);
837   node->analyzed = true;
838
839   pop_cfun ();
840   current_function_decl = save;
841 }
842
843 /* Look for externally_visible and used attributes and mark cgraph nodes
844    accordingly.
845
846    We cannot mark the nodes at the point the attributes are processed (in
847    handle_*_attribute) because the copy of the declarations available at that
848    point may not be canonical.  For example, in:
849
850     void f();
851     void f() __attribute__((used));
852
853    the declaration we see in handle_used_attribute will be the second
854    declaration -- but the front end will subsequently merge that declaration
855    with the original declaration and discard the second declaration.
856
857    Furthermore, we can't mark these nodes in cgraph_finalize_function because:
858
859     void f() {}
860     void f() __attribute__((externally_visible));
861
862    is valid.
863
864    So, we walk the nodes at the end of the translation unit, applying the
865    attributes at that point.  */
866
867 static void
868 process_function_and_variable_attributes (struct cgraph_node *first,
869                                           struct varpool_node *first_var)
870 {
871   struct cgraph_node *node;
872   struct varpool_node *vnode;
873
874   for (node = cgraph_nodes; node != first; node = node->next)
875     {
876       tree decl = node->decl;
877       if (lookup_attribute ("used", DECL_ATTRIBUTES (decl)))
878         {
879           mark_decl_referenced (decl);
880           if (node->local.finalized)
881              cgraph_mark_needed_node (node);
882         }
883       if (lookup_attribute ("externally_visible", DECL_ATTRIBUTES (decl)))
884         {
885           if (! TREE_PUBLIC (node->decl))
886             warning_at (DECL_SOURCE_LOCATION (node->decl), OPT_Wattributes,
887                         "%<externally_visible%>"
888                         " attribute have effect only on public objects");
889           else if (node->local.finalized)
890              cgraph_mark_needed_node (node);
891         }
892     }
893   for (vnode = varpool_nodes; vnode != first_var; vnode = vnode->next)
894     {
895       tree decl = vnode->decl;
896       if (lookup_attribute ("used", DECL_ATTRIBUTES (decl)))
897         {
898           mark_decl_referenced (decl);
899           vnode->force_output = true;
900           if (vnode->finalized)
901             varpool_mark_needed_node (vnode);
902         }
903       if (lookup_attribute ("externally_visible", DECL_ATTRIBUTES (decl)))
904         {
905           if (! TREE_PUBLIC (vnode->decl))
906             warning_at (DECL_SOURCE_LOCATION (vnode->decl), OPT_Wattributes,
907                         "%<externally_visible%>"
908                         " attribute have effect only on public objects");
909           else if (vnode->finalized)
910             varpool_mark_needed_node (vnode);
911         }
912     }
913 }
914
915 /* Process CGRAPH_NODES_NEEDED queue, analyze each function (and transitively
916    each reachable functions) and build cgraph.
917    The function can be called multiple times after inserting new nodes
918    into beginning of queue.  Just the new part of queue is re-scanned then.  */
919
920 static void
921 cgraph_analyze_functions (void)
922 {
923   /* Keep track of already processed nodes when called multiple times for
924      intermodule optimization.  */
925   static struct cgraph_node *first_analyzed;
926   struct cgraph_node *first_processed = first_analyzed;
927   static struct varpool_node *first_analyzed_var;
928   struct cgraph_node *node, *next;
929
930   process_function_and_variable_attributes (first_processed,
931                                             first_analyzed_var);
932   first_processed = cgraph_nodes;
933   first_analyzed_var = varpool_nodes;
934   varpool_analyze_pending_decls ();
935   if (cgraph_dump_file)
936     {
937       fprintf (cgraph_dump_file, "Initial entry points:");
938       for (node = cgraph_nodes; node != first_analyzed; node = node->next)
939         if (node->needed)
940           fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
941       fprintf (cgraph_dump_file, "\n");
942     }
943   cgraph_process_new_functions ();
944
945   /* Propagate reachability flag and lower representation of all reachable
946      functions.  In the future, lowering will introduce new functions and
947      new entry points on the way (by template instantiation and virtual
948      method table generation for instance).  */
949   while (cgraph_nodes_queue)
950     {
951       struct cgraph_edge *edge;
952       tree decl = cgraph_nodes_queue->decl;
953
954       node = cgraph_nodes_queue;
955       cgraph_nodes_queue = cgraph_nodes_queue->next_needed;
956       node->next_needed = NULL;
957
958       /* ??? It is possible to create extern inline function and later using
959          weak alias attribute to kill its body. See
960          gcc.c-torture/compile/20011119-1.c  */
961       if (!DECL_STRUCT_FUNCTION (decl))
962         {
963           cgraph_reset_node (node);
964           continue;
965         }
966
967       if (!node->analyzed)
968         cgraph_analyze_function (node);
969
970       for (edge = node->callees; edge; edge = edge->next_callee)
971         if (!edge->callee->reachable)
972           cgraph_mark_reachable_node (edge->callee);
973
974       /* If decl is a clone of an abstract function, mark that abstract
975          function so that we don't release its body. The DECL_INITIAL() of that
976          abstract function declaration will be later needed to output debug info.  */
977       if (DECL_ABSTRACT_ORIGIN (decl))
978         {
979           struct cgraph_node *origin_node = cgraph_node (DECL_ABSTRACT_ORIGIN (decl));
980           origin_node->abstract_and_needed = true;
981         }
982
983       /* We finalize local static variables during constructing callgraph
984          edges.  Process their attributes too.  */
985       process_function_and_variable_attributes (first_processed,
986                                                 first_analyzed_var);
987       first_processed = cgraph_nodes;
988       first_analyzed_var = varpool_nodes;
989       varpool_analyze_pending_decls ();
990       cgraph_process_new_functions ();
991     }
992
993   /* Collect entry points to the unit.  */
994   if (cgraph_dump_file)
995     {
996       fprintf (cgraph_dump_file, "Unit entry points:");
997       for (node = cgraph_nodes; node != first_analyzed; node = node->next)
998         if (node->needed)
999           fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
1000       fprintf (cgraph_dump_file, "\n\nInitial ");
1001       dump_cgraph (cgraph_dump_file);
1002     }
1003
1004   if (cgraph_dump_file)
1005     fprintf (cgraph_dump_file, "\nReclaiming functions:");
1006
1007   for (node = cgraph_nodes; node != first_analyzed; node = next)
1008     {
1009       tree decl = node->decl;
1010       next = node->next;
1011
1012       if (node->local.finalized && !gimple_has_body_p (decl))
1013         cgraph_reset_node (node);
1014
1015       if (!node->reachable && gimple_has_body_p (decl))
1016         {
1017           if (cgraph_dump_file)
1018             fprintf (cgraph_dump_file, " %s", cgraph_node_name (node));
1019           cgraph_remove_node (node);
1020           continue;
1021         }
1022       else
1023         node->next_needed = NULL;
1024       gcc_assert (!node->local.finalized || gimple_has_body_p (decl));
1025       gcc_assert (node->analyzed == node->local.finalized);
1026     }
1027   if (cgraph_dump_file)
1028     {
1029       fprintf (cgraph_dump_file, "\n\nReclaimed ");
1030       dump_cgraph (cgraph_dump_file);
1031     }
1032   first_analyzed = cgraph_nodes;
1033   ggc_collect ();
1034 }
1035
1036
1037 /* Emit thunks for every node in the cgraph.
1038    FIXME: We really ought to emit thunks only for functions that are needed.  */
1039
1040 static void
1041 cgraph_emit_thunks (void)
1042 {
1043   struct cgraph_node *n;
1044
1045   for (n = cgraph_nodes; n; n = n->next)
1046     {
1047       /* Only emit thunks on functions defined in this TU.
1048          Note that this may emit more thunks than strictly necessary.
1049          During optimization some nodes may disappear.  It would be
1050          nice to only emit thunks only for the functions that will be
1051          emitted, but we cannot know that until the inliner and other
1052          IPA passes have run (see the sequencing of the call to
1053          cgraph_mark_functions_to_output in cgraph_optimize).  */
1054       if (n->reachable
1055           && !DECL_EXTERNAL (n->decl))
1056         lang_hooks.callgraph.emit_associated_thunks (n->decl);
1057     }
1058 }
1059
1060
1061 /* Analyze the whole compilation unit once it is parsed completely.  */
1062
1063 void
1064 cgraph_finalize_compilation_unit (void)
1065 {
1066   timevar_push (TV_CGRAPH);
1067
1068   /* Do not skip analyzing the functions if there were errors, we
1069      miss diagnostics for following functions otherwise.  */
1070
1071   /* Emit size functions we didn't inline.  */
1072   finalize_size_functions ();
1073
1074   /* Call functions declared with the "constructor" or "destructor"
1075      attribute.  */
1076   cgraph_build_cdtor_fns ();
1077
1078   /* Mark alias targets necessary and emit diagnostics.  */
1079   finish_aliases_1 ();
1080
1081   if (!quiet_flag)
1082     {
1083       fprintf (stderr, "\nAnalyzing compilation unit\n");
1084       fflush (stderr);
1085     }
1086
1087   /* Gimplify and lower all functions, compute reachability and
1088      remove unreachable nodes.  */
1089   cgraph_analyze_functions ();
1090
1091   /* Emit thunks for reachable nodes, if needed.  */
1092   if (lang_hooks.callgraph.emit_associated_thunks)
1093     cgraph_emit_thunks ();
1094
1095   /* Mark alias targets necessary and emit diagnostics.  */
1096   finish_aliases_1 ();
1097
1098   /* Gimplify and lower thunks.  */
1099   cgraph_analyze_functions ();
1100
1101   /* Finally drive the pass manager.  */
1102   cgraph_optimize ();
1103
1104   timevar_pop (TV_CGRAPH);
1105 }
1106
1107
1108 /* Figure out what functions we want to assemble.  */
1109
1110 static void
1111 cgraph_mark_functions_to_output (void)
1112 {
1113   struct cgraph_node *node;
1114
1115   for (node = cgraph_nodes; node; node = node->next)
1116     {
1117       tree decl = node->decl;
1118       struct cgraph_edge *e;
1119
1120       gcc_assert (!node->process);
1121
1122       for (e = node->callers; e; e = e->next_caller)
1123         if (e->inline_failed)
1124           break;
1125
1126       /* We need to output all local functions that are used and not
1127          always inlined, as well as those that are reachable from
1128          outside the current compilation unit.  */
1129       if (node->analyzed
1130           && !node->global.inlined_to
1131           && (node->needed
1132               || (e && node->reachable))
1133           && !TREE_ASM_WRITTEN (decl)
1134           && !DECL_EXTERNAL (decl))
1135         node->process = 1;
1136       else
1137         {
1138           /* We should've reclaimed all functions that are not needed.  */
1139 #ifdef ENABLE_CHECKING
1140           if (!node->global.inlined_to
1141               && gimple_has_body_p (decl)
1142               && !DECL_EXTERNAL (decl))
1143             {
1144               dump_cgraph_node (stderr, node);
1145               internal_error ("failed to reclaim unneeded function");
1146             }
1147 #endif
1148           gcc_assert (node->global.inlined_to
1149                       || !gimple_has_body_p (decl)
1150                       || DECL_EXTERNAL (decl));
1151
1152         }
1153
1154     }
1155 }
1156
1157 /* Expand function specified by NODE.  */
1158
1159 static void
1160 cgraph_expand_function (struct cgraph_node *node)
1161 {
1162   tree decl = node->decl;
1163
1164   /* We ought to not compile any inline clones.  */
1165   gcc_assert (!node->global.inlined_to);
1166
1167   announce_function (decl);
1168   node->process = 0;
1169
1170   gcc_assert (node->lowered);
1171
1172   /* Generate RTL for the body of DECL.  */
1173   tree_rest_of_compilation (decl);
1174
1175   /* Make sure that BE didn't give up on compiling.  */
1176   gcc_assert (TREE_ASM_WRITTEN (decl));
1177   current_function_decl = NULL;
1178   gcc_assert (!cgraph_preserve_function_body_p (decl));
1179   cgraph_release_function_body (node);
1180   /* Eliminate all call edges.  This is important so the GIMPLE_CALL no longer
1181      points to the dead function body.  */
1182   cgraph_node_remove_callees (node);
1183
1184   cgraph_function_flags_ready = true;
1185 }
1186
1187 /* Return true when CALLER_DECL should be inlined into CALLEE_DECL.  */
1188
1189 bool
1190 cgraph_inline_p (struct cgraph_edge *e, cgraph_inline_failed_t *reason)
1191 {
1192   *reason = e->inline_failed;
1193   return !e->inline_failed;
1194 }
1195
1196
1197
1198 /* Expand all functions that must be output.
1199
1200    Attempt to topologically sort the nodes so function is output when
1201    all called functions are already assembled to allow data to be
1202    propagated across the callgraph.  Use a stack to get smaller distance
1203    between a function and its callees (later we may choose to use a more
1204    sophisticated algorithm for function reordering; we will likely want
1205    to use subsections to make the output functions appear in top-down
1206    order).  */
1207
1208 static void
1209 cgraph_expand_all_functions (void)
1210 {
1211   struct cgraph_node *node;
1212   struct cgraph_node **order = XCNEWVEC (struct cgraph_node *, cgraph_n_nodes);
1213   int order_pos, new_order_pos = 0;
1214   int i;
1215
1216   order_pos = cgraph_postorder (order);
1217   gcc_assert (order_pos == cgraph_n_nodes);
1218
1219   /* Garbage collector may remove inline clones we eliminate during
1220      optimization.  So we must be sure to not reference them.  */
1221   for (i = 0; i < order_pos; i++)
1222     if (order[i]->process)
1223       order[new_order_pos++] = order[i];
1224
1225   for (i = new_order_pos - 1; i >= 0; i--)
1226     {
1227       node = order[i];
1228       if (node->process)
1229         {
1230           gcc_assert (node->reachable);
1231           node->process = 0;
1232           cgraph_expand_function (node);
1233         }
1234     }
1235   cgraph_process_new_functions ();
1236
1237   free (order);
1238
1239 }
1240
1241 /* This is used to sort the node types by the cgraph order number.  */
1242
1243 enum cgraph_order_sort_kind
1244 {
1245   ORDER_UNDEFINED = 0,
1246   ORDER_FUNCTION,
1247   ORDER_VAR,
1248   ORDER_ASM
1249 };
1250
1251 struct cgraph_order_sort
1252 {
1253   enum cgraph_order_sort_kind kind;
1254   union
1255   {
1256     struct cgraph_node *f;
1257     struct varpool_node *v;
1258     struct cgraph_asm_node *a;
1259   } u;
1260 };
1261
1262 /* Output all functions, variables, and asm statements in the order
1263    according to their order fields, which is the order in which they
1264    appeared in the file.  This implements -fno-toplevel-reorder.  In
1265    this mode we may output functions and variables which don't really
1266    need to be output.  */
1267
1268 static void
1269 cgraph_output_in_order (void)
1270 {
1271   int max;
1272   size_t size;
1273   struct cgraph_order_sort *nodes;
1274   int i;
1275   struct cgraph_node *pf;
1276   struct varpool_node *pv;
1277   struct cgraph_asm_node *pa;
1278
1279   max = cgraph_order;
1280   size = max * sizeof (struct cgraph_order_sort);
1281   nodes = (struct cgraph_order_sort *) alloca (size);
1282   memset (nodes, 0, size);
1283
1284   varpool_analyze_pending_decls ();
1285
1286   for (pf = cgraph_nodes; pf; pf = pf->next)
1287     {
1288       if (pf->process)
1289         {
1290           i = pf->order;
1291           gcc_assert (nodes[i].kind == ORDER_UNDEFINED);
1292           nodes[i].kind = ORDER_FUNCTION;
1293           nodes[i].u.f = pf;
1294         }
1295     }
1296
1297   for (pv = varpool_nodes_queue; pv; pv = pv->next_needed)
1298     {
1299       i = pv->order;
1300       gcc_assert (nodes[i].kind == ORDER_UNDEFINED);
1301       nodes[i].kind = ORDER_VAR;
1302       nodes[i].u.v = pv;
1303     }
1304
1305   for (pa = cgraph_asm_nodes; pa; pa = pa->next)
1306     {
1307       i = pa->order;
1308       gcc_assert (nodes[i].kind == ORDER_UNDEFINED);
1309       nodes[i].kind = ORDER_ASM;
1310       nodes[i].u.a = pa;
1311     }
1312
1313   /* In toplevel reorder mode we output all statics; mark them as needed.  */
1314   for (i = 0; i < max; ++i)
1315     {
1316       if (nodes[i].kind == ORDER_VAR)
1317         {
1318           varpool_mark_needed_node (nodes[i].u.v);
1319         }
1320     }
1321   varpool_empty_needed_queue ();
1322
1323   for (i = 0; i < max; ++i)
1324     {
1325       switch (nodes[i].kind)
1326         {
1327         case ORDER_FUNCTION:
1328           nodes[i].u.f->process = 0;
1329           cgraph_expand_function (nodes[i].u.f);
1330           break;
1331
1332         case ORDER_VAR:
1333           varpool_assemble_decl (nodes[i].u.v);
1334           break;
1335
1336         case ORDER_ASM:
1337           assemble_asm (nodes[i].u.a->asm_str);
1338           break;
1339
1340         case ORDER_UNDEFINED:
1341           break;
1342
1343         default:
1344           gcc_unreachable ();
1345         }
1346     }
1347
1348   cgraph_asm_nodes = NULL;
1349 }
1350
1351 /* Return true when function body of DECL still needs to be kept around
1352    for later re-use.  */
1353 bool
1354 cgraph_preserve_function_body_p (tree decl)
1355 {
1356   struct cgraph_node *node;
1357
1358   gcc_assert (cgraph_global_info_ready);
1359   /* Look if there is any clone around.  */
1360   node = cgraph_node (decl);
1361   if (node->clones)
1362     return true;
1363   return false;
1364 }
1365
1366 static void
1367 ipa_passes (void)
1368 {
1369   set_cfun (NULL);
1370   current_function_decl = NULL;
1371   gimple_register_cfg_hooks ();
1372   bitmap_obstack_initialize (NULL);
1373
1374   if (!in_lto_p)
1375     execute_ipa_pass_list (all_small_ipa_passes);
1376
1377   /* If pass_all_early_optimizations was not scheduled, the state of
1378      the cgraph will not be properly updated.  Update it now.  */
1379   if (cgraph_state < CGRAPH_STATE_IPA_SSA)
1380     cgraph_state = CGRAPH_STATE_IPA_SSA;
1381
1382   if (!in_lto_p)
1383     {
1384       /* Generate coverage variables and constructors.  */
1385       coverage_finish ();
1386
1387       /* Process new functions added.  */
1388       set_cfun (NULL);
1389       current_function_decl = NULL;
1390       cgraph_process_new_functions ();
1391
1392       execute_ipa_summary_passes ((struct ipa_opt_pass_d *) all_regular_ipa_passes);
1393     }
1394   execute_ipa_summary_passes ((struct ipa_opt_pass_d *) all_lto_gen_passes);
1395
1396   if (!in_lto_p)
1397     ipa_write_summaries ();
1398
1399   if (!flag_ltrans)
1400     execute_ipa_pass_list (all_regular_ipa_passes);
1401
1402   bitmap_obstack_release (NULL);
1403 }
1404
1405
1406 /* Perform simple optimizations based on callgraph.  */
1407
1408 void
1409 cgraph_optimize (void)
1410 {
1411   if (errorcount || sorrycount)
1412     return;
1413
1414 #ifdef ENABLE_CHECKING
1415   verify_cgraph ();
1416 #endif
1417
1418   /* Frontend may output common variables after the unit has been finalized.
1419      It is safe to deal with them here as they are always zero initialized.  */
1420   varpool_analyze_pending_decls ();
1421
1422   timevar_push (TV_CGRAPHOPT);
1423   if (pre_ipa_mem_report)
1424     {
1425       fprintf (stderr, "Memory consumption before IPA\n");
1426       dump_memory_report (false);
1427     }
1428   if (!quiet_flag)
1429     fprintf (stderr, "Performing interprocedural optimizations\n");
1430   cgraph_state = CGRAPH_STATE_IPA;
1431
1432   /* Don't run the IPA passes if there was any error or sorry messages.  */
1433   if (errorcount == 0 && sorrycount == 0)
1434     ipa_passes ();
1435
1436   /* Do nothing else if any IPA pass found errors.  */
1437   if (errorcount || sorrycount)
1438     {
1439       timevar_pop (TV_CGRAPHOPT);
1440       return;
1441     }
1442
1443   /* This pass remove bodies of extern inline functions we never inlined.
1444      Do this later so other IPA passes see what is really going on.  */
1445   cgraph_remove_unreachable_nodes (false, dump_file);
1446   cgraph_global_info_ready = true;
1447   if (cgraph_dump_file)
1448     {
1449       fprintf (cgraph_dump_file, "Optimized ");
1450       dump_cgraph (cgraph_dump_file);
1451       dump_varpool (cgraph_dump_file);
1452     }
1453   if (post_ipa_mem_report)
1454     {
1455       fprintf (stderr, "Memory consumption after IPA\n");
1456       dump_memory_report (false);
1457     }
1458   timevar_pop (TV_CGRAPHOPT);
1459
1460   /* Output everything.  */
1461   (*debug_hooks->assembly_start) ();
1462   if (!quiet_flag)
1463     fprintf (stderr, "Assembling functions:\n");
1464 #ifdef ENABLE_CHECKING
1465   verify_cgraph ();
1466 #endif
1467
1468   cgraph_materialize_all_clones ();
1469   cgraph_mark_functions_to_output ();
1470
1471   cgraph_state = CGRAPH_STATE_EXPANSION;
1472   if (!flag_toplevel_reorder)
1473     cgraph_output_in_order ();
1474   else
1475     {
1476       cgraph_output_pending_asms ();
1477
1478       cgraph_expand_all_functions ();
1479       varpool_remove_unreferenced_decls ();
1480
1481       varpool_assemble_pending_decls ();
1482     }
1483   cgraph_process_new_functions ();
1484   cgraph_state = CGRAPH_STATE_FINISHED;
1485
1486   if (cgraph_dump_file)
1487     {
1488       fprintf (cgraph_dump_file, "\nFinal ");
1489       dump_cgraph (cgraph_dump_file);
1490     }
1491 #ifdef ENABLE_CHECKING
1492   verify_cgraph ();
1493   /* Double check that all inline clones are gone and that all
1494      function bodies have been released from memory.  */
1495   if (!(sorrycount || errorcount))
1496     {
1497       struct cgraph_node *node;
1498       bool error_found = false;
1499
1500       for (node = cgraph_nodes; node; node = node->next)
1501         if (node->analyzed
1502             && (node->global.inlined_to
1503                 || gimple_has_body_p (node->decl)))
1504           {
1505             error_found = true;
1506             dump_cgraph_node (stderr, node);
1507           }
1508       if (error_found)
1509         internal_error ("nodes with unreleased memory found");
1510     }
1511 #endif
1512 }
1513
1514
1515 /* Generate and emit a static constructor or destructor.  WHICH must
1516    be one of 'I' (for a constructor) or 'D' (for a destructor).  BODY
1517    is a STATEMENT_LIST containing GENERIC statements.  PRIORITY is the
1518    initialization priority for this constructor or destructor.  */
1519
1520 void
1521 cgraph_build_static_cdtor (char which, tree body, int priority)
1522 {
1523   static int counter = 0;
1524   char which_buf[16];
1525   tree decl, name, resdecl;
1526
1527   /* The priority is encoded in the constructor or destructor name.
1528      collect2 will sort the names and arrange that they are called at
1529      program startup.  */
1530   sprintf (which_buf, "%c_%.5d_%d", which, priority, counter++);
1531   name = get_file_function_name (which_buf);
1532
1533   decl = build_decl (input_location, FUNCTION_DECL, name,
1534                      build_function_type (void_type_node, void_list_node));
1535   current_function_decl = decl;
1536
1537   resdecl = build_decl (input_location,
1538                         RESULT_DECL, NULL_TREE, void_type_node);
1539   DECL_ARTIFICIAL (resdecl) = 1;
1540   DECL_RESULT (decl) = resdecl;
1541   DECL_CONTEXT (resdecl) = decl;
1542
1543   allocate_struct_function (decl, false);
1544
1545   TREE_STATIC (decl) = 1;
1546   TREE_USED (decl) = 1;
1547   DECL_ARTIFICIAL (decl) = 1;
1548   DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl) = 1;
1549   DECL_SAVED_TREE (decl) = body;
1550   TREE_PUBLIC (decl) = ! targetm.have_ctors_dtors;
1551   DECL_UNINLINABLE (decl) = 1;
1552
1553   DECL_INITIAL (decl) = make_node (BLOCK);
1554   TREE_USED (DECL_INITIAL (decl)) = 1;
1555
1556   DECL_SOURCE_LOCATION (decl) = input_location;
1557   cfun->function_end_locus = input_location;
1558
1559   switch (which)
1560     {
1561     case 'I':
1562       DECL_STATIC_CONSTRUCTOR (decl) = 1;
1563       decl_init_priority_insert (decl, priority);
1564       break;
1565     case 'D':
1566       DECL_STATIC_DESTRUCTOR (decl) = 1;
1567       decl_fini_priority_insert (decl, priority);
1568       break;
1569     default:
1570       gcc_unreachable ();
1571     }
1572
1573   gimplify_function_tree (decl);
1574
1575   cgraph_add_new_function (decl, false);
1576   cgraph_mark_needed_node (cgraph_node (decl));
1577   set_cfun (NULL);
1578 }
1579
1580 void
1581 init_cgraph (void)
1582 {
1583   cgraph_dump_file = dump_begin (TDI_cgraph, NULL);
1584 }
1585
1586 /* The edges representing the callers of the NEW_VERSION node were
1587    fixed by cgraph_function_versioning (), now the call_expr in their
1588    respective tree code should be updated to call the NEW_VERSION.  */
1589
1590 static void
1591 update_call_expr (struct cgraph_node *new_version)
1592 {
1593   struct cgraph_edge *e;
1594
1595   gcc_assert (new_version);
1596
1597   /* Update the call expr on the edges to call the new version.  */
1598   for (e = new_version->callers; e; e = e->next_caller)
1599     {
1600       struct function *inner_function = DECL_STRUCT_FUNCTION (e->caller->decl);
1601       gimple_call_set_fndecl (e->call_stmt, new_version->decl);
1602       maybe_clean_eh_stmt_fn (inner_function, e->call_stmt);
1603     }
1604 }
1605
1606
1607 /* Create a new cgraph node which is the new version of
1608    OLD_VERSION node.  REDIRECT_CALLERS holds the callers
1609    edges which should be redirected to point to
1610    NEW_VERSION.  ALL the callees edges of OLD_VERSION
1611    are cloned to the new version node.  Return the new
1612    version node.  */
1613
1614 static struct cgraph_node *
1615 cgraph_copy_node_for_versioning (struct cgraph_node *old_version,
1616                                  tree new_decl,
1617                                  VEC(cgraph_edge_p,heap) *redirect_callers)
1618  {
1619    struct cgraph_node *new_version;
1620    struct cgraph_edge *e, *new_e;
1621    struct cgraph_edge *next_callee;
1622    unsigned i;
1623
1624    gcc_assert (old_version);
1625
1626    new_version = cgraph_node (new_decl);
1627
1628    new_version->analyzed = true;
1629    new_version->local = old_version->local;
1630    new_version->global = old_version->global;
1631    new_version->rtl = new_version->rtl;
1632    new_version->reachable = true;
1633    new_version->count = old_version->count;
1634
1635    /* Clone the old node callees.  Recursive calls are
1636       also cloned.  */
1637    for (e = old_version->callees;e; e=e->next_callee)
1638      {
1639        new_e = cgraph_clone_edge (e, new_version, e->call_stmt,
1640                                   e->lto_stmt_uid, 0, e->frequency,
1641                                   e->loop_nest, true);
1642        new_e->count = e->count;
1643      }
1644    /* Fix recursive calls.
1645       If OLD_VERSION has a recursive call after the
1646       previous edge cloning, the new version will have an edge
1647       pointing to the old version, which is wrong;
1648       Redirect it to point to the new version. */
1649    for (e = new_version->callees ; e; e = next_callee)
1650      {
1651        next_callee = e->next_callee;
1652        if (e->callee == old_version)
1653          cgraph_redirect_edge_callee (e, new_version);
1654
1655        if (!next_callee)
1656          break;
1657      }
1658    for (i = 0; VEC_iterate (cgraph_edge_p, redirect_callers, i, e); i++)
1659      {
1660        /* Redirect calls to the old version node to point to its new
1661           version.  */
1662        cgraph_redirect_edge_callee (e, new_version);
1663      }
1664
1665    return new_version;
1666  }
1667
1668  /* Perform function versioning.
1669     Function versioning includes copying of the tree and
1670     a callgraph update (creating a new cgraph node and updating
1671     its callees and callers).
1672
1673     REDIRECT_CALLERS varray includes the edges to be redirected
1674     to the new version.
1675
1676     TREE_MAP is a mapping of tree nodes we want to replace with
1677     new ones (according to results of prior analysis).
1678     OLD_VERSION_NODE is the node that is versioned.
1679     It returns the new version's cgraph node. 
1680     ARGS_TO_SKIP lists arguments to be omitted from functions
1681     */
1682
1683 struct cgraph_node *
1684 cgraph_function_versioning (struct cgraph_node *old_version_node,
1685                             VEC(cgraph_edge_p,heap) *redirect_callers,
1686                             VEC (ipa_replace_map_p,gc)* tree_map,
1687                             bitmap args_to_skip)
1688 {
1689   tree old_decl = old_version_node->decl;
1690   struct cgraph_node *new_version_node = NULL;
1691   tree new_decl;
1692
1693   if (!tree_versionable_function_p (old_decl))
1694     return NULL;
1695
1696   /* Make a new FUNCTION_DECL tree node for the
1697      new version. */
1698   if (!args_to_skip)
1699     new_decl = copy_node (old_decl);
1700   else
1701     new_decl = build_function_decl_skip_args (old_decl, args_to_skip);
1702
1703   /* Create the new version's call-graph node.
1704      and update the edges of the new node. */
1705   new_version_node =
1706     cgraph_copy_node_for_versioning (old_version_node, new_decl,
1707                                      redirect_callers);
1708
1709   /* Copy the OLD_VERSION_NODE function tree to the new version.  */
1710   tree_function_versioning (old_decl, new_decl, tree_map, false, args_to_skip);
1711
1712   /* Update the new version's properties.
1713      Make The new version visible only within this translation unit.  Make sure
1714      that is not weak also.
1715      ??? We cannot use COMDAT linkage because there is no
1716      ABI support for this.  */
1717   DECL_EXTERNAL (new_version_node->decl) = 0;
1718   DECL_COMDAT_GROUP (new_version_node->decl) = NULL_TREE;
1719   TREE_PUBLIC (new_version_node->decl) = 0;
1720   DECL_COMDAT (new_version_node->decl) = 0;
1721   DECL_WEAK (new_version_node->decl) = 0;
1722   DECL_VIRTUAL_P (new_version_node->decl) = 0;
1723   new_version_node->local.externally_visible = 0;
1724   new_version_node->local.local = 1;
1725   new_version_node->lowered = true;
1726
1727   /* Update the call_expr on the edges to call the new version node. */
1728   update_call_expr (new_version_node);
1729   
1730   cgraph_call_function_insertion_hooks (new_version_node);
1731   return new_version_node;
1732 }
1733
1734 /* Produce separate function body for inline clones so the offline copy can be
1735    modified without affecting them.  */
1736 struct cgraph_node *
1737 save_inline_function_body (struct cgraph_node *node)
1738 {
1739   struct cgraph_node *first_clone, *n;
1740
1741   gcc_assert (node == cgraph_node (node->decl));
1742
1743   cgraph_lower_function (node);
1744
1745   first_clone = node->clones;
1746
1747   first_clone->decl = copy_node (node->decl);
1748   cgraph_insert_node_to_hashtable (first_clone);
1749   gcc_assert (first_clone == cgraph_node (first_clone->decl));
1750   if (first_clone->next_sibling_clone)
1751     {
1752       for (n = first_clone->next_sibling_clone; n->next_sibling_clone; n = n->next_sibling_clone)
1753         n->clone_of = first_clone;
1754       n->clone_of = first_clone;
1755       n->next_sibling_clone = first_clone->clones;
1756       if (first_clone->clones)
1757         first_clone->clones->prev_sibling_clone = n;
1758       first_clone->clones = first_clone->next_sibling_clone;
1759       first_clone->next_sibling_clone->prev_sibling_clone = NULL;
1760       first_clone->next_sibling_clone = NULL;
1761       gcc_assert (!first_clone->prev_sibling_clone);
1762     }
1763   first_clone->clone_of = NULL;
1764   node->clones = NULL;
1765
1766   if (first_clone->clones)
1767     for (n = first_clone->clones; n != first_clone;)
1768       {
1769         gcc_assert (n->decl == node->decl);
1770         n->decl = first_clone->decl;
1771         if (n->clones)
1772           n = n->clones;
1773         else if (n->next_sibling_clone)
1774           n = n->next_sibling_clone;
1775         else
1776           {
1777             while (n != first_clone && !n->next_sibling_clone)
1778               n = n->clone_of;
1779             if (n != first_clone)
1780               n = n->next_sibling_clone;
1781           }
1782       }
1783
1784   /* Copy the OLD_VERSION_NODE function tree to the new version.  */
1785   tree_function_versioning (node->decl, first_clone->decl, NULL, true, NULL);
1786
1787   DECL_EXTERNAL (first_clone->decl) = 0;
1788   DECL_COMDAT_GROUP (first_clone->decl) = NULL_TREE;
1789   TREE_PUBLIC (first_clone->decl) = 0;
1790   DECL_COMDAT (first_clone->decl) = 0;
1791   VEC_free (ipa_opt_pass, heap,
1792             first_clone->ipa_transforms_to_apply);
1793   first_clone->ipa_transforms_to_apply = NULL;
1794
1795 #ifdef ENABLE_CHECKING
1796   verify_cgraph_node (first_clone);
1797 #endif
1798   return first_clone;
1799 }
1800
1801 /* Given virtual clone, turn it into actual clone.  */
1802 static void
1803 cgraph_materialize_clone (struct cgraph_node *node)
1804 {
1805   bitmap_obstack_initialize (NULL);
1806   /* Copy the OLD_VERSION_NODE function tree to the new version.  */
1807   tree_function_versioning (node->clone_of->decl, node->decl,
1808                             node->clone.tree_map, true,
1809                             node->clone.args_to_skip);
1810   if (cgraph_dump_file)
1811     {
1812       dump_function_to_file (node->clone_of->decl, cgraph_dump_file, dump_flags);
1813       dump_function_to_file (node->decl, cgraph_dump_file, dump_flags);
1814     }
1815
1816   /* Function is no longer clone.  */
1817   if (node->next_sibling_clone)
1818     node->next_sibling_clone->prev_sibling_clone = node->prev_sibling_clone;
1819   if (node->prev_sibling_clone)
1820     node->prev_sibling_clone->next_sibling_clone = node->next_sibling_clone;
1821   else
1822     node->clone_of->clones = node->next_sibling_clone;
1823   node->next_sibling_clone = NULL;
1824   node->prev_sibling_clone = NULL;
1825   if (!node->clone_of->analyzed && !node->clone_of->clones)
1826     cgraph_remove_node (node->clone_of);
1827   node->clone_of = NULL;
1828   bitmap_obstack_release (NULL);
1829 }
1830
1831 /* Once all functions from compilation unit are in memory, produce all clones
1832    and update all calls.
1833    We might also do this on demand if we don't want to bring all functions to
1834    memory prior compilation, but current WHOPR implementation does that and it is
1835    is bit easier to keep everything right in this order.  */
1836 void
1837 cgraph_materialize_all_clones (void)
1838 {
1839   struct cgraph_node *node;
1840   bool stabilized = false;
1841
1842   if (cgraph_dump_file)
1843     fprintf (cgraph_dump_file, "Materializing clones\n");
1844 #ifdef ENABLE_CHECKING
1845   verify_cgraph ();
1846 #endif
1847
1848   /* We can also do topological order, but number of iterations should be
1849      bounded by number of IPA passes since single IPA pass is probably not
1850      going to create clones of clones it created itself.  */
1851   while (!stabilized)
1852     {
1853       stabilized = true;
1854       for (node = cgraph_nodes; node; node = node->next)
1855         {
1856           if (node->clone_of && node->decl != node->clone_of->decl
1857               && !gimple_has_body_p (node->decl))
1858             {
1859               if (gimple_has_body_p (node->clone_of->decl))
1860                 {
1861                   if (cgraph_dump_file)
1862                     {
1863                       fprintf (cgraph_dump_file, "clonning %s to %s\n",
1864                                cgraph_node_name (node->clone_of),
1865                                cgraph_node_name (node));
1866                       if (node->clone.tree_map)
1867                         {
1868                           unsigned int i;
1869                           fprintf (cgraph_dump_file, "   replace map: ");
1870                           for (i = 0; i < VEC_length (ipa_replace_map_p,
1871                                                       node->clone.tree_map);
1872                                                       i++)
1873                             {
1874                               struct ipa_replace_map *replace_info;
1875                               replace_info = VEC_index (ipa_replace_map_p,
1876                                                         node->clone.tree_map,
1877                                                         i);
1878                               print_generic_expr (cgraph_dump_file, replace_info->old_tree, 0);
1879                               fprintf (cgraph_dump_file, " -> ");
1880                               print_generic_expr (cgraph_dump_file, replace_info->new_tree, 0);
1881                               fprintf (cgraph_dump_file, "%s%s;",
1882                                        replace_info->replace_p ? "(replace)":"",
1883                                        replace_info->ref_p ? "(ref)":"");
1884                             }
1885                           fprintf (cgraph_dump_file, "\n");
1886                         }
1887                       if (node->clone.args_to_skip)
1888                         {
1889                           fprintf (cgraph_dump_file, "   args_to_skip: ");
1890                           dump_bitmap (cgraph_dump_file, node->clone.args_to_skip);
1891                         }
1892                       if (node->clone.args_to_skip)
1893                         {
1894                           fprintf (cgraph_dump_file, "   combined_args_to_skip:");
1895                           dump_bitmap (cgraph_dump_file, node->clone.combined_args_to_skip);
1896                         }
1897                     }
1898                   cgraph_materialize_clone (node);
1899                 }
1900               else
1901                 stabilized = false;
1902             }
1903         }
1904     }
1905   if (cgraph_dump_file)
1906     fprintf (cgraph_dump_file, "Updating call sites\n");
1907   for (node = cgraph_nodes; node; node = node->next)
1908     if (node->analyzed && gimple_has_body_p (node->decl)
1909         && (!node->clone_of || node->clone_of->decl != node->decl))
1910       {
1911         struct cgraph_edge *e;
1912
1913         current_function_decl = node->decl;
1914         push_cfun (DECL_STRUCT_FUNCTION (node->decl));
1915         for (e = node->callees; e; e = e->next_callee)
1916           {
1917             tree decl = gimple_call_fndecl (e->call_stmt);
1918             /* When function gets inlined, indirect inlining might've invented
1919                new edge for orginally indirect stmt.  Since we are not
1920                preserving clones in the original form, we must not update here
1921                since other inline clones don't need to contain call to the same
1922                call.  Inliner will do the substitution for us later.  */
1923             if (decl && decl != e->callee->decl)
1924               {
1925                 gimple new_stmt;
1926                 gimple_stmt_iterator gsi;
1927                 
1928                 if (cgraph_dump_file)
1929                   {
1930                     fprintf (cgraph_dump_file, "updating call of %s in %s:",
1931                              cgraph_node_name (node),
1932                              cgraph_node_name (e->callee));
1933                     print_gimple_stmt (cgraph_dump_file, e->call_stmt, 0, dump_flags);
1934                   }
1935
1936                 if (e->callee->clone.combined_args_to_skip)
1937                   new_stmt = gimple_call_copy_skip_args (e->call_stmt,
1938                                                          e->callee->clone.combined_args_to_skip);
1939                 else
1940                   new_stmt = e->call_stmt;
1941                 if (gimple_vdef (new_stmt)
1942                     && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
1943                   SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
1944                 gimple_call_set_fndecl (new_stmt, e->callee->decl);
1945
1946                 gsi = gsi_for_stmt (e->call_stmt);
1947                 gsi_replace (&gsi, new_stmt, true);
1948
1949                 /* Update EH information too, just in case.  */
1950                 maybe_clean_or_replace_eh_stmt (e->call_stmt, new_stmt);
1951
1952                 cgraph_set_call_stmt_including_clones (node, e->call_stmt, new_stmt);
1953
1954                 if (cgraph_dump_file)
1955                   {
1956                     fprintf (cgraph_dump_file, "  updated to:");
1957                     print_gimple_stmt (cgraph_dump_file, e->call_stmt, 0, dump_flags);
1958                   }
1959               }
1960           }
1961         pop_cfun ();
1962         current_function_decl = NULL;
1963 #ifdef ENABLE_CHECKING
1964         verify_cgraph_node (node);
1965 #endif
1966       }
1967 #ifdef ENABLE_CHECKING
1968   verify_cgraph ();
1969 #endif
1970   cgraph_remove_unreachable_nodes (false, cgraph_dump_file);
1971 }
1972
1973 #include "gt-cgraphunit.h"