re PR tree-optimization/41008 (ICE in vect_is_simple_reduction, at tree-vect-loop...
[platform/upstream/gcc.git] / gcc / tree-inline.c
1 /* Tree inlining.
2    Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
3    Free Software Foundation, Inc.
4    Contributed by Alexandre Oliva <aoliva@redhat.com>
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License 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 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "toplev.h"
27 #include "tree.h"
28 #include "tree-inline.h"
29 #include "rtl.h"
30 #include "expr.h"
31 #include "flags.h"
32 #include "params.h"
33 #include "input.h"
34 #include "insn-config.h"
35 #include "hashtab.h"
36 #include "langhooks.h"
37 #include "basic-block.h"
38 #include "tree-iterator.h"
39 #include "cgraph.h"
40 #include "intl.h"
41 #include "tree-mudflap.h"
42 #include "tree-flow.h"
43 #include "function.h"
44 #include "ggc.h"
45 #include "tree-flow.h"
46 #include "diagnostic.h"
47 #include "except.h"
48 #include "debug.h"
49 #include "pointer-set.h"
50 #include "ipa-prop.h"
51 #include "value-prof.h"
52 #include "tree-pass.h"
53 #include "target.h"
54 #include "integrate.h"
55
56 /* I'm not real happy about this, but we need to handle gimple and
57    non-gimple trees.  */
58 #include "gimple.h"
59
60 /* Inlining, Cloning, Versioning, Parallelization
61
62    Inlining: a function body is duplicated, but the PARM_DECLs are
63    remapped into VAR_DECLs, and non-void RETURN_EXPRs become
64    MODIFY_EXPRs that store to a dedicated returned-value variable.
65    The duplicated eh_region info of the copy will later be appended
66    to the info for the caller; the eh_region info in copied throwing
67    statements and RESX_EXPRs is adjusted accordingly.
68
69    Cloning: (only in C++) We have one body for a con/de/structor, and
70    multiple function decls, each with a unique parameter list.
71    Duplicate the body, using the given splay tree; some parameters
72    will become constants (like 0 or 1).
73
74    Versioning: a function body is duplicated and the result is a new
75    function rather than into blocks of an existing function as with
76    inlining.  Some parameters will become constants.
77
78    Parallelization: a region of a function is duplicated resulting in
79    a new function.  Variables may be replaced with complex expressions
80    to enable shared variable semantics.
81
82    All of these will simultaneously lookup any callgraph edges.  If
83    we're going to inline the duplicated function body, and the given
84    function has some cloned callgraph nodes (one for each place this
85    function will be inlined) those callgraph edges will be duplicated.
86    If we're cloning the body, those callgraph edges will be
87    updated to point into the new body.  (Note that the original
88    callgraph node and edge list will not be altered.)
89
90    See the CALL_EXPR handling case in copy_tree_body_r ().  */
91
92 /* To Do:
93
94    o In order to make inlining-on-trees work, we pessimized
95      function-local static constants.  In particular, they are now
96      always output, even when not addressed.  Fix this by treating
97      function-local static constants just like global static
98      constants; the back-end already knows not to output them if they
99      are not needed.
100
101    o Provide heuristics to clamp inlining of recursive template
102      calls?  */
103
104
105 /* Weights that estimate_num_insns uses for heuristics in inlining.  */
106
107 eni_weights eni_inlining_weights;
108
109 /* Weights that estimate_num_insns uses to estimate the size of the
110    produced code.  */
111
112 eni_weights eni_size_weights;
113
114 /* Weights that estimate_num_insns uses to estimate the time necessary
115    to execute the produced code.  */
116
117 eni_weights eni_time_weights;
118
119 /* Prototypes.  */
120
121 static tree declare_return_variable (copy_body_data *, tree, tree, tree *);
122 static void remap_block (tree *, copy_body_data *);
123 static void copy_bind_expr (tree *, int *, copy_body_data *);
124 static tree mark_local_for_remap_r (tree *, int *, void *);
125 static void unsave_expr_1 (tree);
126 static tree unsave_r (tree *, int *, void *);
127 static void declare_inline_vars (tree, tree);
128 static void remap_save_expr (tree *, void *, int *);
129 static void prepend_lexical_block (tree current_block, tree new_block);
130 static tree copy_decl_to_var (tree, copy_body_data *);
131 static tree copy_result_decl_to_var (tree, copy_body_data *);
132 static tree copy_decl_maybe_to_var (tree, copy_body_data *);
133 static gimple remap_gimple_stmt (gimple, copy_body_data *);
134 static bool delete_unreachable_blocks_update_callgraph (copy_body_data *id);
135
136 /* Insert a tree->tree mapping for ID.  Despite the name suggests
137    that the trees should be variables, it is used for more than that.  */
138
139 void
140 insert_decl_map (copy_body_data *id, tree key, tree value)
141 {
142   *pointer_map_insert (id->decl_map, key) = value;
143
144   /* Always insert an identity map as well.  If we see this same new
145      node again, we won't want to duplicate it a second time.  */
146   if (key != value)
147     *pointer_map_insert (id->decl_map, value) = value;
148 }
149
150 /* Construct new SSA name for old NAME. ID is the inline context.  */
151
152 static tree
153 remap_ssa_name (tree name, copy_body_data *id)
154 {
155   tree new_tree;
156   tree *n;
157
158   gcc_assert (TREE_CODE (name) == SSA_NAME);
159
160   n = (tree *) pointer_map_contains (id->decl_map, name);
161   if (n)
162     return unshare_expr (*n);
163
164   /* Do not set DEF_STMT yet as statement is not copied yet. We do that
165      in copy_bb.  */
166   new_tree = remap_decl (SSA_NAME_VAR (name), id);
167
168   /* We might've substituted constant or another SSA_NAME for
169      the variable. 
170
171      Replace the SSA name representing RESULT_DECL by variable during
172      inlining:  this saves us from need to introduce PHI node in a case
173      return value is just partly initialized.  */
174   if ((TREE_CODE (new_tree) == VAR_DECL || TREE_CODE (new_tree) == PARM_DECL)
175       && (TREE_CODE (SSA_NAME_VAR (name)) != RESULT_DECL
176           || !id->transform_return_to_modify))
177     {
178       new_tree = make_ssa_name (new_tree, NULL);
179       insert_decl_map (id, name, new_tree);
180       SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_tree)
181         = SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name);
182       TREE_TYPE (new_tree) = TREE_TYPE (SSA_NAME_VAR (new_tree));
183       if (gimple_nop_p (SSA_NAME_DEF_STMT (name)))
184         {
185           /* By inlining function having uninitialized variable, we might
186              extend the lifetime (variable might get reused).  This cause
187              ICE in the case we end up extending lifetime of SSA name across
188              abnormal edge, but also increase register pressure.
189
190              We simply initialize all uninitialized vars by 0 except
191              for case we are inlining to very first BB.  We can avoid
192              this for all BBs that are not inside strongly connected
193              regions of the CFG, but this is expensive to test.  */
194           if (id->entry_bb
195               && is_gimple_reg (SSA_NAME_VAR (name))
196               && TREE_CODE (SSA_NAME_VAR (name)) != PARM_DECL
197               && (id->entry_bb != EDGE_SUCC (ENTRY_BLOCK_PTR, 0)->dest
198                   || EDGE_COUNT (id->entry_bb->preds) != 1))
199             {
200               gimple_stmt_iterator gsi = gsi_last_bb (id->entry_bb);
201               gimple init_stmt;
202               
203               init_stmt = gimple_build_assign (new_tree,
204                                                fold_convert (TREE_TYPE (new_tree),
205                                                             integer_zero_node));
206               gsi_insert_after (&gsi, init_stmt, GSI_NEW_STMT);
207               SSA_NAME_IS_DEFAULT_DEF (new_tree) = 0;
208             }
209           else
210             {
211               SSA_NAME_DEF_STMT (new_tree) = gimple_build_nop ();
212               if (gimple_default_def (id->src_cfun, SSA_NAME_VAR (name))
213                   == name)
214                 set_default_def (SSA_NAME_VAR (new_tree), new_tree);
215             }
216         }
217     }
218   else
219     insert_decl_map (id, name, new_tree);
220   return new_tree;
221 }
222
223 /* Remap DECL during the copying of the BLOCK tree for the function.  */
224
225 tree
226 remap_decl (tree decl, copy_body_data *id)
227 {
228   tree *n;
229   tree fn;
230
231   /* We only remap local variables in the current function.  */
232   fn = id->src_fn;
233
234   /* See if we have remapped this declaration.  */
235
236   n = (tree *) pointer_map_contains (id->decl_map, decl);
237
238   /* If we didn't already have an equivalent for this declaration,
239      create one now.  */
240   if (!n)
241     {
242       /* Make a copy of the variable or label.  */
243       tree t = id->copy_decl (decl, id);
244      
245       /* Remember it, so that if we encounter this local entity again
246          we can reuse this copy.  Do this early because remap_type may
247          need this decl for TYPE_STUB_DECL.  */
248       insert_decl_map (id, decl, t);
249
250       if (!DECL_P (t))
251         return t;
252
253       /* Remap types, if necessary.  */
254       TREE_TYPE (t) = remap_type (TREE_TYPE (t), id);
255       if (TREE_CODE (t) == TYPE_DECL)
256         DECL_ORIGINAL_TYPE (t) = remap_type (DECL_ORIGINAL_TYPE (t), id);
257
258       /* Remap sizes as necessary.  */
259       walk_tree (&DECL_SIZE (t), copy_tree_body_r, id, NULL);
260       walk_tree (&DECL_SIZE_UNIT (t), copy_tree_body_r, id, NULL);
261
262       /* If fields, do likewise for offset and qualifier.  */
263       if (TREE_CODE (t) == FIELD_DECL)
264         {
265           walk_tree (&DECL_FIELD_OFFSET (t), copy_tree_body_r, id, NULL);
266           if (TREE_CODE (DECL_CONTEXT (t)) == QUAL_UNION_TYPE)
267             walk_tree (&DECL_QUALIFIER (t), copy_tree_body_r, id, NULL);
268         }
269
270       if (cfun && gimple_in_ssa_p (cfun)
271           && (TREE_CODE (t) == VAR_DECL
272               || TREE_CODE (t) == RESULT_DECL || TREE_CODE (t) == PARM_DECL))
273         {
274           tree def = gimple_default_def (id->src_cfun, decl);
275           get_var_ann (t);
276           if (TREE_CODE (decl) != PARM_DECL && def)
277             {
278               tree map = remap_ssa_name (def, id);
279               /* Watch out RESULT_DECLs whose SSA names map directly
280                  to them.  */
281               if (TREE_CODE (map) == SSA_NAME
282                   && gimple_nop_p (SSA_NAME_DEF_STMT (map)))
283                 set_default_def (t, map);
284             }
285           add_referenced_var (t);
286         }
287       return t;
288     }
289
290   if (id->do_not_unshare)
291     return *n;
292   else
293     return unshare_expr (*n);
294 }
295
296 static tree
297 remap_type_1 (tree type, copy_body_data *id)
298 {
299   tree new_tree, t;
300
301   /* We do need a copy.  build and register it now.  If this is a pointer or
302      reference type, remap the designated type and make a new pointer or
303      reference type.  */
304   if (TREE_CODE (type) == POINTER_TYPE)
305     {
306       new_tree = build_pointer_type_for_mode (remap_type (TREE_TYPE (type), id),
307                                          TYPE_MODE (type),
308                                          TYPE_REF_CAN_ALIAS_ALL (type));
309       insert_decl_map (id, type, new_tree);
310       return new_tree;
311     }
312   else if (TREE_CODE (type) == REFERENCE_TYPE)
313     {
314       new_tree = build_reference_type_for_mode (remap_type (TREE_TYPE (type), id),
315                                             TYPE_MODE (type),
316                                             TYPE_REF_CAN_ALIAS_ALL (type));
317       insert_decl_map (id, type, new_tree);
318       return new_tree;
319     }
320   else
321     new_tree = copy_node (type);
322
323   insert_decl_map (id, type, new_tree);
324
325   /* This is a new type, not a copy of an old type.  Need to reassociate
326      variants.  We can handle everything except the main variant lazily.  */
327   t = TYPE_MAIN_VARIANT (type);
328   if (type != t)
329     {
330       t = remap_type (t, id);
331       TYPE_MAIN_VARIANT (new_tree) = t;
332       TYPE_NEXT_VARIANT (new_tree) = TYPE_NEXT_VARIANT (t);
333       TYPE_NEXT_VARIANT (t) = new_tree;
334     }
335   else
336     {
337       TYPE_MAIN_VARIANT (new_tree) = new_tree;
338       TYPE_NEXT_VARIANT (new_tree) = NULL;
339     }
340
341   if (TYPE_STUB_DECL (type))
342     TYPE_STUB_DECL (new_tree) = remap_decl (TYPE_STUB_DECL (type), id);
343
344   /* Lazily create pointer and reference types.  */
345   TYPE_POINTER_TO (new_tree) = NULL;
346   TYPE_REFERENCE_TO (new_tree) = NULL;
347
348   switch (TREE_CODE (new_tree))
349     {
350     case INTEGER_TYPE:
351     case REAL_TYPE:
352     case FIXED_POINT_TYPE:
353     case ENUMERAL_TYPE:
354     case BOOLEAN_TYPE:
355       t = TYPE_MIN_VALUE (new_tree);
356       if (t && TREE_CODE (t) != INTEGER_CST)
357         walk_tree (&TYPE_MIN_VALUE (new_tree), copy_tree_body_r, id, NULL);
358
359       t = TYPE_MAX_VALUE (new_tree);
360       if (t && TREE_CODE (t) != INTEGER_CST)
361         walk_tree (&TYPE_MAX_VALUE (new_tree), copy_tree_body_r, id, NULL);
362       return new_tree;
363
364     case FUNCTION_TYPE:
365       TREE_TYPE (new_tree) = remap_type (TREE_TYPE (new_tree), id);
366       walk_tree (&TYPE_ARG_TYPES (new_tree), copy_tree_body_r, id, NULL);
367       return new_tree;
368
369     case ARRAY_TYPE:
370       TREE_TYPE (new_tree) = remap_type (TREE_TYPE (new_tree), id);
371       TYPE_DOMAIN (new_tree) = remap_type (TYPE_DOMAIN (new_tree), id);
372       break;
373
374     case RECORD_TYPE:
375     case UNION_TYPE:
376     case QUAL_UNION_TYPE:
377       {
378         tree f, nf = NULL;
379
380         for (f = TYPE_FIELDS (new_tree); f ; f = TREE_CHAIN (f))
381           {
382             t = remap_decl (f, id);
383             DECL_CONTEXT (t) = new_tree;
384             TREE_CHAIN (t) = nf;
385             nf = t;
386           }
387         TYPE_FIELDS (new_tree) = nreverse (nf);
388       }
389       break;
390
391     case OFFSET_TYPE:
392     default:
393       /* Shouldn't have been thought variable sized.  */
394       gcc_unreachable ();
395     }
396
397   walk_tree (&TYPE_SIZE (new_tree), copy_tree_body_r, id, NULL);
398   walk_tree (&TYPE_SIZE_UNIT (new_tree), copy_tree_body_r, id, NULL);
399
400   return new_tree;
401 }
402
403 tree
404 remap_type (tree type, copy_body_data *id)
405 {
406   tree *node;
407   tree tmp;
408
409   if (type == NULL)
410     return type;
411
412   /* See if we have remapped this type.  */
413   node = (tree *) pointer_map_contains (id->decl_map, type);
414   if (node)
415     return *node;
416
417   /* The type only needs remapping if it's variably modified.  */
418   if (! variably_modified_type_p (type, id->src_fn))
419     {
420       insert_decl_map (id, type, type);
421       return type;
422     }
423
424   id->remapping_type_depth++;
425   tmp = remap_type_1 (type, id);
426   id->remapping_type_depth--;
427
428   return tmp;
429 }
430
431 /* Return previously remapped type of TYPE in ID.  Return NULL if TYPE
432    is NULL or TYPE has not been remapped before.  */
433
434 static tree
435 remapped_type (tree type, copy_body_data *id)
436 {
437   tree *node;
438
439   if (type == NULL)
440     return type;
441
442   /* See if we have remapped this type.  */
443   node = (tree *) pointer_map_contains (id->decl_map, type);
444   if (node)
445     return *node;
446   else
447     return NULL;
448 }
449
450   /* The type only needs remapping if it's variably modified.  */
451 /* Decide if DECL can be put into BLOCK_NONLOCAL_VARs.  */
452   
453 static bool
454 can_be_nonlocal (tree decl, copy_body_data *id)
455 {
456   /* We can not duplicate function decls.  */
457   if (TREE_CODE (decl) == FUNCTION_DECL)
458     return true;
459
460   /* Local static vars must be non-local or we get multiple declaration
461      problems.  */
462   if (TREE_CODE (decl) == VAR_DECL
463       && !auto_var_in_fn_p (decl, id->src_fn))
464     return true;
465
466   /* At the moment dwarf2out can handle only these types of nodes.  We
467      can support more later.  */
468   if (TREE_CODE (decl) != VAR_DECL && TREE_CODE (decl) != PARM_DECL)
469     return false;
470
471   /* We must use global type.  We call remapped_type instead of
472      remap_type since we don't want to remap this type here if it
473      hasn't been remapped before.  */
474   if (TREE_TYPE (decl) != remapped_type (TREE_TYPE (decl), id))
475     return false;
476
477   /* Wihtout SSA we can't tell if variable is used.  */
478   if (!gimple_in_ssa_p (cfun))
479     return false;
480
481   /* Live variables must be copied so we can attach DECL_RTL.  */
482   if (var_ann (decl))
483     return false;
484
485   return true;
486 }
487
488 static tree
489 remap_decls (tree decls, VEC(tree,gc) **nonlocalized_list, copy_body_data *id)
490 {
491   tree old_var;
492   tree new_decls = NULL_TREE;
493
494   /* Remap its variables.  */
495   for (old_var = decls; old_var; old_var = TREE_CHAIN (old_var))
496     {
497       tree new_var;
498       tree origin_var = DECL_ORIGIN (old_var);
499
500       if (can_be_nonlocal (old_var, id))
501         {
502           if (TREE_CODE (old_var) == VAR_DECL
503               && (var_ann (old_var) || !gimple_in_ssa_p (cfun)))
504             cfun->local_decls = tree_cons (NULL_TREE, old_var,
505                                                    cfun->local_decls);
506           if ((!optimize || debug_info_level > DINFO_LEVEL_TERSE)
507               && !DECL_IGNORED_P (old_var)
508               && nonlocalized_list)
509             VEC_safe_push (tree, gc, *nonlocalized_list, origin_var);
510           continue;
511         }
512
513       /* Remap the variable.  */
514       new_var = remap_decl (old_var, id);
515
516       /* If we didn't remap this variable, we can't mess with its
517          TREE_CHAIN.  If we remapped this variable to the return slot, it's
518          already declared somewhere else, so don't declare it here.  */
519       
520       if (new_var == id->retvar)
521         ;
522       else if (!new_var)
523         {
524           if ((!optimize || debug_info_level > DINFO_LEVEL_TERSE)
525               && !DECL_IGNORED_P (old_var)
526               && nonlocalized_list)
527             VEC_safe_push (tree, gc, *nonlocalized_list, origin_var);
528         }
529       else
530         {
531           gcc_assert (DECL_P (new_var));
532           TREE_CHAIN (new_var) = new_decls;
533           new_decls = new_var;
534         }
535     }
536
537   return nreverse (new_decls);
538 }
539
540 /* Copy the BLOCK to contain remapped versions of the variables
541    therein.  And hook the new block into the block-tree.  */
542
543 static void
544 remap_block (tree *block, copy_body_data *id)
545 {
546   tree old_block;
547   tree new_block;
548   tree fn;
549
550   /* Make the new block.  */
551   old_block = *block;
552   new_block = make_node (BLOCK);
553   TREE_USED (new_block) = TREE_USED (old_block);
554   BLOCK_ABSTRACT_ORIGIN (new_block) = old_block;
555   BLOCK_SOURCE_LOCATION (new_block) = BLOCK_SOURCE_LOCATION (old_block);
556   BLOCK_NONLOCALIZED_VARS (new_block)
557     = VEC_copy (tree, gc, BLOCK_NONLOCALIZED_VARS (old_block));
558   *block = new_block;
559
560   /* Remap its variables.  */
561   BLOCK_VARS (new_block) = remap_decls (BLOCK_VARS (old_block),
562                                         &BLOCK_NONLOCALIZED_VARS (new_block),
563                                         id);
564
565   fn = id->dst_fn;
566
567   if (id->transform_lang_insert_block)
568     id->transform_lang_insert_block (new_block);
569
570   /* Remember the remapped block.  */
571   insert_decl_map (id, old_block, new_block);
572 }
573
574 /* Copy the whole block tree and root it in id->block.  */
575 static tree
576 remap_blocks (tree block, copy_body_data *id)
577 {
578   tree t;
579   tree new_tree = block;
580
581   if (!block)
582     return NULL;
583
584   remap_block (&new_tree, id);
585   gcc_assert (new_tree != block);
586   for (t = BLOCK_SUBBLOCKS (block); t ; t = BLOCK_CHAIN (t))
587     prepend_lexical_block (new_tree, remap_blocks (t, id));
588   /* Blocks are in arbitrary order, but make things slightly prettier and do
589      not swap order when producing a copy.  */
590   BLOCK_SUBBLOCKS (new_tree) = blocks_nreverse (BLOCK_SUBBLOCKS (new_tree));
591   return new_tree;
592 }
593
594 static void
595 copy_statement_list (tree *tp)
596 {
597   tree_stmt_iterator oi, ni;
598   tree new_tree;
599
600   new_tree = alloc_stmt_list ();
601   ni = tsi_start (new_tree);
602   oi = tsi_start (*tp);
603   *tp = new_tree;
604
605   for (; !tsi_end_p (oi); tsi_next (&oi))
606     {
607       tree stmt = tsi_stmt (oi);
608       if (TREE_CODE (stmt) == STATEMENT_LIST)
609         copy_statement_list (&stmt);
610       tsi_link_after (&ni, stmt, TSI_CONTINUE_LINKING);
611     }
612 }
613
614 static void
615 copy_bind_expr (tree *tp, int *walk_subtrees, copy_body_data *id)
616 {
617   tree block = BIND_EXPR_BLOCK (*tp);
618   /* Copy (and replace) the statement.  */
619   copy_tree_r (tp, walk_subtrees, NULL);
620   if (block)
621     {
622       remap_block (&block, id);
623       BIND_EXPR_BLOCK (*tp) = block;
624     }
625
626   if (BIND_EXPR_VARS (*tp))
627     /* This will remap a lot of the same decls again, but this should be
628        harmless.  */
629     BIND_EXPR_VARS (*tp) = remap_decls (BIND_EXPR_VARS (*tp), NULL, id);
630 }
631
632
633 /* Create a new gimple_seq by remapping all the statements in BODY
634    using the inlining information in ID.  */
635
636 gimple_seq
637 remap_gimple_seq (gimple_seq body, copy_body_data *id)
638 {
639   gimple_stmt_iterator si;
640   gimple_seq new_body = NULL;
641
642   for (si = gsi_start (body); !gsi_end_p (si); gsi_next (&si))
643     {
644       gimple new_stmt = remap_gimple_stmt (gsi_stmt (si), id);
645       gimple_seq_add_stmt (&new_body, new_stmt);
646     }
647
648   return new_body;
649 }
650
651
652 /* Copy a GIMPLE_BIND statement STMT, remapping all the symbols in its
653    block using the mapping information in ID.  */
654
655 static gimple
656 copy_gimple_bind (gimple stmt, copy_body_data *id)
657 {
658   gimple new_bind;
659   tree new_block, new_vars;
660   gimple_seq body, new_body;
661
662   /* Copy the statement.  Note that we purposely don't use copy_stmt
663      here because we need to remap statements as we copy.  */
664   body = gimple_bind_body (stmt);
665   new_body = remap_gimple_seq (body, id);
666
667   new_block = gimple_bind_block (stmt);
668   if (new_block)
669     remap_block (&new_block, id);
670
671   /* This will remap a lot of the same decls again, but this should be
672      harmless.  */
673   new_vars = gimple_bind_vars (stmt);
674   if (new_vars)
675     new_vars = remap_decls (new_vars, NULL, id);
676
677   new_bind = gimple_build_bind (new_vars, new_body, new_block);
678
679   return new_bind;
680 }
681
682
683 /* Remap the GIMPLE operand pointed to by *TP.  DATA is really a
684    'struct walk_stmt_info *'.  DATA->INFO is a 'copy_body_data *'.
685    WALK_SUBTREES is used to indicate walk_gimple_op whether to keep
686    recursing into the children nodes of *TP.  */
687
688 static tree
689 remap_gimple_op_r (tree *tp, int *walk_subtrees, void *data)
690 {
691   struct walk_stmt_info *wi_p = (struct walk_stmt_info *) data;
692   copy_body_data *id = (copy_body_data *) wi_p->info;
693   tree fn = id->src_fn;
694
695   if (TREE_CODE (*tp) == SSA_NAME)
696     {
697       *tp = remap_ssa_name (*tp, id);
698       *walk_subtrees = 0;
699       return NULL;
700     }
701   else if (auto_var_in_fn_p (*tp, fn))
702     {
703       /* Local variables and labels need to be replaced by equivalent
704          variables.  We don't want to copy static variables; there's
705          only one of those, no matter how many times we inline the
706          containing function.  Similarly for globals from an outer
707          function.  */
708       tree new_decl;
709
710       /* Remap the declaration.  */
711       new_decl = remap_decl (*tp, id);
712       gcc_assert (new_decl);
713       /* Replace this variable with the copy.  */
714       STRIP_TYPE_NOPS (new_decl);
715       /* ???  The C++ frontend uses void * pointer zero to initialize
716          any other type.  This confuses the middle-end type verification.
717          As cloned bodies do not go through gimplification again the fixup
718          there doesn't trigger.  */
719       if (TREE_CODE (new_decl) == INTEGER_CST
720           && !useless_type_conversion_p (TREE_TYPE (*tp), TREE_TYPE (new_decl)))
721         new_decl = fold_convert (TREE_TYPE (*tp), new_decl);
722       *tp = new_decl;
723       *walk_subtrees = 0;
724     }
725   else if (TREE_CODE (*tp) == STATEMENT_LIST)
726     gcc_unreachable ();
727   else if (TREE_CODE (*tp) == SAVE_EXPR)
728     gcc_unreachable ();
729   else if (TREE_CODE (*tp) == LABEL_DECL
730            && (!DECL_CONTEXT (*tp)
731                || decl_function_context (*tp) == id->src_fn))
732     /* These may need to be remapped for EH handling.  */
733     *tp = remap_decl (*tp, id);
734   else if (TYPE_P (*tp))
735     /* Types may need remapping as well.  */
736     *tp = remap_type (*tp, id);
737   else if (CONSTANT_CLASS_P (*tp))
738     {
739       /* If this is a constant, we have to copy the node iff the type
740          will be remapped.  copy_tree_r will not copy a constant.  */
741       tree new_type = remap_type (TREE_TYPE (*tp), id);
742
743       if (new_type == TREE_TYPE (*tp))
744         *walk_subtrees = 0;
745
746       else if (TREE_CODE (*tp) == INTEGER_CST)
747         *tp = build_int_cst_wide (new_type, TREE_INT_CST_LOW (*tp),
748                                   TREE_INT_CST_HIGH (*tp));
749       else
750         {
751           *tp = copy_node (*tp);
752           TREE_TYPE (*tp) = new_type;
753         }
754     }
755   else
756     {
757       /* Otherwise, just copy the node.  Note that copy_tree_r already
758          knows not to copy VAR_DECLs, etc., so this is safe.  */
759       if (TREE_CODE (*tp) == INDIRECT_REF)
760         {
761           /* Get rid of *& from inline substitutions that can happen when a
762              pointer argument is an ADDR_EXPR.  */
763           tree decl = TREE_OPERAND (*tp, 0);
764           tree *n;
765
766           n = (tree *) pointer_map_contains (id->decl_map, decl);
767           if (n)
768             {
769               tree type, new_tree, old;
770
771               /* If we happen to get an ADDR_EXPR in n->value, strip
772                  it manually here as we'll eventually get ADDR_EXPRs
773                  which lie about their types pointed to.  In this case
774                  build_fold_indirect_ref wouldn't strip the
775                  INDIRECT_REF, but we absolutely rely on that.  As
776                  fold_indirect_ref does other useful transformations,
777                  try that first, though.  */
778               type = TREE_TYPE (TREE_TYPE (*n));
779               new_tree = unshare_expr (*n);
780               old = *tp;
781               *tp = gimple_fold_indirect_ref (new_tree);
782               if (!*tp)
783                 {
784                   if (TREE_CODE (new_tree) == ADDR_EXPR)
785                     {
786                       *tp = fold_indirect_ref_1 (EXPR_LOCATION (new_tree),
787                                                  type, new_tree);
788                       /* ???  We should either assert here or build
789                          a VIEW_CONVERT_EXPR instead of blindly leaking
790                          incompatible types to our IL.  */
791                       if (! *tp)
792                         *tp = TREE_OPERAND (new_tree, 0);
793                     }
794                   else
795                     {
796                       *tp = build1 (INDIRECT_REF, type, new_tree);
797                       TREE_THIS_VOLATILE (*tp) = TREE_THIS_VOLATILE (old);
798                       TREE_NO_WARNING (*tp) = TREE_NO_WARNING (old);
799                     }
800                 }
801               *walk_subtrees = 0;
802               return NULL;
803             }
804         }
805
806       /* Here is the "usual case".  Copy this tree node, and then
807          tweak some special cases.  */
808       copy_tree_r (tp, walk_subtrees, NULL);
809
810       /* Global variables we haven't seen yet need to go into referenced
811          vars.  If not referenced from types only.  */
812       if (gimple_in_ssa_p (cfun)
813           && TREE_CODE (*tp) == VAR_DECL
814           && id->remapping_type_depth == 0)
815         add_referenced_var (*tp);
816
817       /* We should never have TREE_BLOCK set on non-statements.  */
818       if (EXPR_P (*tp))
819         gcc_assert (!TREE_BLOCK (*tp));
820
821       if (TREE_CODE (*tp) != OMP_CLAUSE)
822         TREE_TYPE (*tp) = remap_type (TREE_TYPE (*tp), id);
823
824       if (TREE_CODE (*tp) == TARGET_EXPR && TREE_OPERAND (*tp, 3))
825         {
826           /* The copied TARGET_EXPR has never been expanded, even if the
827              original node was expanded already.  */
828           TREE_OPERAND (*tp, 1) = TREE_OPERAND (*tp, 3);
829           TREE_OPERAND (*tp, 3) = NULL_TREE;
830         }
831       else if (TREE_CODE (*tp) == ADDR_EXPR)
832         {
833           /* Variable substitution need not be simple.  In particular,
834              the INDIRECT_REF substitution above.  Make sure that
835              TREE_CONSTANT and friends are up-to-date.  But make sure
836              to not improperly set TREE_BLOCK on some sub-expressions.  */
837           int invariant = is_gimple_min_invariant (*tp);
838           tree block = id->block;
839           id->block = NULL_TREE;
840           walk_tree (&TREE_OPERAND (*tp, 0), copy_tree_body_r, id, NULL);
841           id->block = block;
842
843           /* Handle the case where we substituted an INDIRECT_REF
844              into the operand of the ADDR_EXPR.  */
845           if (TREE_CODE (TREE_OPERAND (*tp, 0)) == INDIRECT_REF)
846             *tp = TREE_OPERAND (TREE_OPERAND (*tp, 0), 0);
847           else
848             recompute_tree_invariant_for_addr_expr (*tp);
849
850           /* If this used to be invariant, but is not any longer,
851              then regimplification is probably needed.  */
852           if (invariant && !is_gimple_min_invariant (*tp))
853             id->regimplify = true;
854
855           *walk_subtrees = 0;
856         }
857     }
858
859   /* Keep iterating.  */
860   return NULL_TREE;
861 }
862
863
864 /* Called from copy_body_id via walk_tree.  DATA is really a
865    `copy_body_data *'.  */
866
867 tree
868 copy_tree_body_r (tree *tp, int *walk_subtrees, void *data)
869 {
870   copy_body_data *id = (copy_body_data *) data;
871   tree fn = id->src_fn;
872   tree new_block;
873
874   /* Begin by recognizing trees that we'll completely rewrite for the
875      inlining context.  Our output for these trees is completely
876      different from out input (e.g. RETURN_EXPR is deleted, and morphs
877      into an edge).  Further down, we'll handle trees that get
878      duplicated and/or tweaked.  */
879
880   /* When requested, RETURN_EXPRs should be transformed to just the
881      contained MODIFY_EXPR.  The branch semantics of the return will
882      be handled elsewhere by manipulating the CFG rather than a statement.  */
883   if (TREE_CODE (*tp) == RETURN_EXPR && id->transform_return_to_modify)
884     {
885       tree assignment = TREE_OPERAND (*tp, 0);
886
887       /* If we're returning something, just turn that into an
888          assignment into the equivalent of the original RESULT_DECL.
889          If the "assignment" is just the result decl, the result
890          decl has already been set (e.g. a recent "foo (&result_decl,
891          ...)"); just toss the entire RETURN_EXPR.  */
892       if (assignment && TREE_CODE (assignment) == MODIFY_EXPR)
893         {
894           /* Replace the RETURN_EXPR with (a copy of) the
895              MODIFY_EXPR hanging underneath.  */
896           *tp = copy_node (assignment);
897         }
898       else /* Else the RETURN_EXPR returns no value.  */
899         {
900           *tp = NULL;
901           return (tree) (void *)1;
902         }
903     }
904   else if (TREE_CODE (*tp) == SSA_NAME)
905     {
906       *tp = remap_ssa_name (*tp, id);
907       *walk_subtrees = 0;
908       return NULL;
909     }
910
911   /* Local variables and labels need to be replaced by equivalent
912      variables.  We don't want to copy static variables; there's only
913      one of those, no matter how many times we inline the containing
914      function.  Similarly for globals from an outer function.  */
915   else if (auto_var_in_fn_p (*tp, fn))
916     {
917       tree new_decl;
918
919       /* Remap the declaration.  */
920       new_decl = remap_decl (*tp, id);
921       gcc_assert (new_decl);
922       /* Replace this variable with the copy.  */
923       STRIP_TYPE_NOPS (new_decl);
924       *tp = new_decl;
925       *walk_subtrees = 0;
926     }
927   else if (TREE_CODE (*tp) == STATEMENT_LIST)
928     copy_statement_list (tp);
929   else if (TREE_CODE (*tp) == SAVE_EXPR
930            || TREE_CODE (*tp) == TARGET_EXPR)
931     remap_save_expr (tp, id->decl_map, walk_subtrees);
932   else if (TREE_CODE (*tp) == LABEL_DECL
933            && (! DECL_CONTEXT (*tp)
934                || decl_function_context (*tp) == id->src_fn))
935     /* These may need to be remapped for EH handling.  */
936     *tp = remap_decl (*tp, id);
937   else if (TREE_CODE (*tp) == BIND_EXPR)
938     copy_bind_expr (tp, walk_subtrees, id);
939   /* Types may need remapping as well.  */
940   else if (TYPE_P (*tp))
941     *tp = remap_type (*tp, id);
942
943   /* If this is a constant, we have to copy the node iff the type will be
944      remapped.  copy_tree_r will not copy a constant.  */
945   else if (CONSTANT_CLASS_P (*tp))
946     {
947       tree new_type = remap_type (TREE_TYPE (*tp), id);
948
949       if (new_type == TREE_TYPE (*tp))
950         *walk_subtrees = 0;
951
952       else if (TREE_CODE (*tp) == INTEGER_CST)
953         *tp = build_int_cst_wide (new_type, TREE_INT_CST_LOW (*tp),
954                                   TREE_INT_CST_HIGH (*tp));
955       else
956         {
957           *tp = copy_node (*tp);
958           TREE_TYPE (*tp) = new_type;
959         }
960     }
961
962   /* Otherwise, just copy the node.  Note that copy_tree_r already
963      knows not to copy VAR_DECLs, etc., so this is safe.  */
964   else
965     {
966       /* Here we handle trees that are not completely rewritten.
967          First we detect some inlining-induced bogosities for
968          discarding.  */
969       if (TREE_CODE (*tp) == MODIFY_EXPR
970           && TREE_OPERAND (*tp, 0) == TREE_OPERAND (*tp, 1)
971           && (auto_var_in_fn_p (TREE_OPERAND (*tp, 0), fn)))
972         {
973           /* Some assignments VAR = VAR; don't generate any rtl code
974              and thus don't count as variable modification.  Avoid
975              keeping bogosities like 0 = 0.  */
976           tree decl = TREE_OPERAND (*tp, 0), value;
977           tree *n;
978
979           n = (tree *) pointer_map_contains (id->decl_map, decl);
980           if (n)
981             {
982               value = *n;
983               STRIP_TYPE_NOPS (value);
984               if (TREE_CONSTANT (value) || TREE_READONLY (value))
985                 {
986                   *tp = build_empty_stmt (EXPR_LOCATION (*tp));
987                   return copy_tree_body_r (tp, walk_subtrees, data);
988                 }
989             }
990         }
991       else if (TREE_CODE (*tp) == INDIRECT_REF)
992         {
993           /* Get rid of *& from inline substitutions that can happen when a
994              pointer argument is an ADDR_EXPR.  */
995           tree decl = TREE_OPERAND (*tp, 0);
996           tree *n;
997
998           n = (tree *) pointer_map_contains (id->decl_map, decl);
999           if (n)
1000             {
1001               tree new_tree;
1002               tree old;
1003               /* If we happen to get an ADDR_EXPR in n->value, strip
1004                  it manually here as we'll eventually get ADDR_EXPRs
1005                  which lie about their types pointed to.  In this case
1006                  build_fold_indirect_ref wouldn't strip the INDIRECT_REF,
1007                  but we absolutely rely on that.  As fold_indirect_ref
1008                  does other useful transformations, try that first, though.  */
1009               tree type = TREE_TYPE (TREE_TYPE (*n));
1010               if (id->do_not_unshare)
1011                 new_tree = *n;
1012               else
1013                 new_tree = unshare_expr (*n);
1014               old = *tp;
1015               *tp = gimple_fold_indirect_ref (new_tree);
1016               if (! *tp)
1017                 {
1018                   if (TREE_CODE (new_tree) == ADDR_EXPR)
1019                     {
1020                       *tp = fold_indirect_ref_1 (EXPR_LOCATION (new_tree),
1021                                                  type, new_tree);
1022                       /* ???  We should either assert here or build
1023                          a VIEW_CONVERT_EXPR instead of blindly leaking
1024                          incompatible types to our IL.  */
1025                       if (! *tp)
1026                         *tp = TREE_OPERAND (new_tree, 0);
1027                     }
1028                   else
1029                     {
1030                       *tp = build1 (INDIRECT_REF, type, new_tree);
1031                       TREE_THIS_VOLATILE (*tp) = TREE_THIS_VOLATILE (old);
1032                       TREE_SIDE_EFFECTS (*tp) = TREE_SIDE_EFFECTS (old);
1033                     }
1034                 }
1035               *walk_subtrees = 0;
1036               return NULL;
1037             }
1038         }
1039
1040       /* Here is the "usual case".  Copy this tree node, and then
1041          tweak some special cases.  */
1042       copy_tree_r (tp, walk_subtrees, NULL);
1043
1044       /* Global variables we haven't seen yet needs to go into referenced
1045          vars.  If not referenced from types only.  */
1046       if (gimple_in_ssa_p (cfun)
1047           && TREE_CODE (*tp) == VAR_DECL
1048           && id->remapping_type_depth == 0)
1049         add_referenced_var (*tp);
1050        
1051       /* If EXPR has block defined, map it to newly constructed block.
1052          When inlining we want EXPRs without block appear in the block
1053          of function call.  */
1054       if (EXPR_P (*tp))
1055         {
1056           new_block = id->block;
1057           if (TREE_BLOCK (*tp))
1058             {
1059               tree *n;
1060               n = (tree *) pointer_map_contains (id->decl_map,
1061                                                  TREE_BLOCK (*tp));
1062               gcc_assert (n);
1063               new_block = *n;
1064             }
1065           TREE_BLOCK (*tp) = new_block;
1066         }
1067
1068       if (TREE_CODE (*tp) == RESX_EXPR && id->eh_region_offset)
1069         TREE_OPERAND (*tp, 0) =
1070           build_int_cst (NULL_TREE,
1071                          id->eh_region_offset
1072                          + TREE_INT_CST_LOW (TREE_OPERAND (*tp, 0)));
1073
1074       if (TREE_CODE (*tp) != OMP_CLAUSE)
1075         TREE_TYPE (*tp) = remap_type (TREE_TYPE (*tp), id);
1076
1077       /* The copied TARGET_EXPR has never been expanded, even if the
1078          original node was expanded already.  */
1079       if (TREE_CODE (*tp) == TARGET_EXPR && TREE_OPERAND (*tp, 3))
1080         {
1081           TREE_OPERAND (*tp, 1) = TREE_OPERAND (*tp, 3);
1082           TREE_OPERAND (*tp, 3) = NULL_TREE;
1083         }
1084
1085       /* Variable substitution need not be simple.  In particular, the
1086          INDIRECT_REF substitution above.  Make sure that TREE_CONSTANT
1087          and friends are up-to-date.  */
1088       else if (TREE_CODE (*tp) == ADDR_EXPR)
1089         {
1090           int invariant = is_gimple_min_invariant (*tp);
1091           walk_tree (&TREE_OPERAND (*tp, 0), copy_tree_body_r, id, NULL);
1092
1093           /* Handle the case where we substituted an INDIRECT_REF
1094              into the operand of the ADDR_EXPR.  */
1095           if (TREE_CODE (TREE_OPERAND (*tp, 0)) == INDIRECT_REF)
1096             *tp = TREE_OPERAND (TREE_OPERAND (*tp, 0), 0);
1097           else
1098             recompute_tree_invariant_for_addr_expr (*tp);
1099
1100           /* If this used to be invariant, but is not any longer,
1101              then regimplification is probably needed.  */
1102           if (invariant && !is_gimple_min_invariant (*tp))
1103             id->regimplify = true;
1104
1105           *walk_subtrees = 0;
1106         }
1107     }
1108
1109   /* Keep iterating.  */
1110   return NULL_TREE;
1111 }
1112
1113
1114 /* Helper for copy_bb.  Remap statement STMT using the inlining
1115    information in ID.  Return the new statement copy.  */
1116
1117 static gimple
1118 remap_gimple_stmt (gimple stmt, copy_body_data *id)
1119 {
1120   gimple copy = NULL;
1121   struct walk_stmt_info wi;
1122   tree new_block;
1123   bool skip_first = false;
1124
1125   /* Begin by recognizing trees that we'll completely rewrite for the
1126      inlining context.  Our output for these trees is completely
1127      different from out input (e.g. RETURN_EXPR is deleted, and morphs
1128      into an edge).  Further down, we'll handle trees that get
1129      duplicated and/or tweaked.  */
1130
1131   /* When requested, GIMPLE_RETURNs should be transformed to just the
1132      contained GIMPLE_ASSIGN.  The branch semantics of the return will
1133      be handled elsewhere by manipulating the CFG rather than the
1134      statement.  */
1135   if (gimple_code (stmt) == GIMPLE_RETURN && id->transform_return_to_modify)
1136     {
1137       tree retval = gimple_return_retval (stmt);
1138
1139       /* If we're returning something, just turn that into an
1140          assignment into the equivalent of the original RESULT_DECL.
1141          If RETVAL is just the result decl, the result decl has
1142          already been set (e.g. a recent "foo (&result_decl, ...)");
1143          just toss the entire GIMPLE_RETURN.  */
1144       if (retval && TREE_CODE (retval) != RESULT_DECL)
1145         {
1146           copy = gimple_build_assign (id->retvar, retval);
1147           /* id->retvar is already substituted.  Skip it on later remapping.  */
1148           skip_first = true;
1149         }
1150       else
1151         return gimple_build_nop ();
1152     }
1153   else if (gimple_has_substatements (stmt))
1154     {
1155       gimple_seq s1, s2;
1156
1157       /* When cloning bodies from the C++ front end, we will be handed bodies
1158          in High GIMPLE form.  Handle here all the High GIMPLE statements that
1159          have embedded statements.  */
1160       switch (gimple_code (stmt))
1161         {
1162         case GIMPLE_BIND:
1163           copy = copy_gimple_bind (stmt, id);
1164           break;
1165
1166         case GIMPLE_CATCH:
1167           s1 = remap_gimple_seq (gimple_catch_handler (stmt), id);
1168           copy = gimple_build_catch (gimple_catch_types (stmt), s1);
1169           break;
1170
1171         case GIMPLE_EH_FILTER:
1172           s1 = remap_gimple_seq (gimple_eh_filter_failure (stmt), id);
1173           copy = gimple_build_eh_filter (gimple_eh_filter_types (stmt), s1);
1174           break;
1175
1176         case GIMPLE_TRY:
1177           s1 = remap_gimple_seq (gimple_try_eval (stmt), id);
1178           s2 = remap_gimple_seq (gimple_try_cleanup (stmt), id);
1179           copy = gimple_build_try (s1, s2, gimple_try_kind (stmt)); 
1180           break;
1181
1182         case GIMPLE_WITH_CLEANUP_EXPR:
1183           s1 = remap_gimple_seq (gimple_wce_cleanup (stmt), id);
1184           copy = gimple_build_wce (s1);
1185           break;
1186
1187         case GIMPLE_OMP_PARALLEL:
1188           s1 = remap_gimple_seq (gimple_omp_body (stmt), id);
1189           copy = gimple_build_omp_parallel
1190                    (s1,
1191                     gimple_omp_parallel_clauses (stmt),
1192                     gimple_omp_parallel_child_fn (stmt),
1193                     gimple_omp_parallel_data_arg (stmt));
1194           break;
1195
1196         case GIMPLE_OMP_TASK:
1197           s1 = remap_gimple_seq (gimple_omp_body (stmt), id);
1198           copy = gimple_build_omp_task
1199                    (s1,
1200                     gimple_omp_task_clauses (stmt),
1201                     gimple_omp_task_child_fn (stmt),
1202                     gimple_omp_task_data_arg (stmt),
1203                     gimple_omp_task_copy_fn (stmt),
1204                     gimple_omp_task_arg_size (stmt),
1205                     gimple_omp_task_arg_align (stmt));
1206           break;
1207
1208         case GIMPLE_OMP_FOR:
1209           s1 = remap_gimple_seq (gimple_omp_body (stmt), id);
1210           s2 = remap_gimple_seq (gimple_omp_for_pre_body (stmt), id);
1211           copy = gimple_build_omp_for (s1, gimple_omp_for_clauses (stmt),
1212                                        gimple_omp_for_collapse (stmt), s2);
1213           {
1214             size_t i;
1215             for (i = 0; i < gimple_omp_for_collapse (stmt); i++)
1216               {
1217                 gimple_omp_for_set_index (copy, i,
1218                                           gimple_omp_for_index (stmt, i));
1219                 gimple_omp_for_set_initial (copy, i,
1220                                             gimple_omp_for_initial (stmt, i));
1221                 gimple_omp_for_set_final (copy, i,
1222                                           gimple_omp_for_final (stmt, i));
1223                 gimple_omp_for_set_incr (copy, i,
1224                                          gimple_omp_for_incr (stmt, i));
1225                 gimple_omp_for_set_cond (copy, i,
1226                                          gimple_omp_for_cond (stmt, i));
1227               }
1228           }
1229           break;
1230
1231         case GIMPLE_OMP_MASTER:
1232           s1 = remap_gimple_seq (gimple_omp_body (stmt), id);
1233           copy = gimple_build_omp_master (s1);
1234           break;
1235
1236         case GIMPLE_OMP_ORDERED:
1237           s1 = remap_gimple_seq (gimple_omp_body (stmt), id);
1238           copy = gimple_build_omp_ordered (s1);
1239           break;
1240
1241         case GIMPLE_OMP_SECTION:
1242           s1 = remap_gimple_seq (gimple_omp_body (stmt), id);
1243           copy = gimple_build_omp_section (s1);
1244           break;
1245
1246         case GIMPLE_OMP_SECTIONS:
1247           s1 = remap_gimple_seq (gimple_omp_body (stmt), id);
1248           copy = gimple_build_omp_sections
1249                    (s1, gimple_omp_sections_clauses (stmt));
1250           break;
1251
1252         case GIMPLE_OMP_SINGLE:
1253           s1 = remap_gimple_seq (gimple_omp_body (stmt), id);
1254           copy = gimple_build_omp_single
1255                    (s1, gimple_omp_single_clauses (stmt));
1256           break;
1257
1258         case GIMPLE_OMP_CRITICAL:
1259           s1 = remap_gimple_seq (gimple_omp_body (stmt), id);
1260           copy
1261             = gimple_build_omp_critical (s1, gimple_omp_critical_name (stmt));
1262           break;
1263
1264         default:
1265           gcc_unreachable ();
1266         }
1267     }
1268   else
1269     {
1270       if (gimple_assign_copy_p (stmt)
1271           && gimple_assign_lhs (stmt) == gimple_assign_rhs1 (stmt)
1272           && auto_var_in_fn_p (gimple_assign_lhs (stmt), id->src_fn))
1273         {
1274           /* Here we handle statements that are not completely rewritten.
1275              First we detect some inlining-induced bogosities for
1276              discarding.  */
1277
1278           /* Some assignments VAR = VAR; don't generate any rtl code
1279              and thus don't count as variable modification.  Avoid
1280              keeping bogosities like 0 = 0.  */
1281           tree decl = gimple_assign_lhs (stmt), value;
1282           tree *n;
1283
1284           n = (tree *) pointer_map_contains (id->decl_map, decl);
1285           if (n)
1286             {
1287               value = *n;
1288               STRIP_TYPE_NOPS (value);
1289               if (TREE_CONSTANT (value) || TREE_READONLY (value))
1290                 return gimple_build_nop ();
1291             }
1292         }
1293
1294       /* Create a new deep copy of the statement.  */
1295       copy = gimple_copy (stmt);
1296     }
1297
1298   /* If STMT has a block defined, map it to the newly constructed
1299      block.  When inlining we want statements without a block to
1300      appear in the block of the function call.  */
1301   new_block = id->block;
1302   if (gimple_block (copy))
1303     {
1304       tree *n;
1305       n = (tree *) pointer_map_contains (id->decl_map, gimple_block (copy));
1306       gcc_assert (n);
1307       new_block = *n;
1308     }
1309
1310   gimple_set_block (copy, new_block);
1311
1312   /* Remap all the operands in COPY.  */
1313   memset (&wi, 0, sizeof (wi));
1314   wi.info = id;
1315   if (skip_first)
1316     walk_tree (gimple_op_ptr (copy, 1), remap_gimple_op_r, &wi, NULL);
1317   else
1318     walk_gimple_op (copy, remap_gimple_op_r, &wi); 
1319
1320   /* Clear the copied virtual operands.  We are not remapping them here
1321      but are going to recreate them from scratch.  */
1322   if (gimple_has_mem_ops (copy))
1323     {
1324       gimple_set_vdef (copy, NULL_TREE);
1325       gimple_set_vuse (copy, NULL_TREE);
1326     }
1327
1328   /* We have to handle EH region remapping of GIMPLE_RESX specially because
1329      the region number is not an operand.  */
1330   if (gimple_code (stmt) == GIMPLE_RESX && id->eh_region_offset)
1331     {
1332       gimple_resx_set_region (copy, gimple_resx_region (stmt) + id->eh_region_offset);
1333     }
1334   return copy;
1335 }
1336
1337
1338 /* Copy basic block, scale profile accordingly.  Edges will be taken care of
1339    later  */
1340
1341 static basic_block
1342 copy_bb (copy_body_data *id, basic_block bb, int frequency_scale,
1343          gcov_type count_scale)
1344 {
1345   gimple_stmt_iterator gsi, copy_gsi, seq_gsi;
1346   basic_block copy_basic_block;
1347   tree decl;
1348
1349   /* create_basic_block() will append every new block to
1350      basic_block_info automatically.  */
1351   copy_basic_block = create_basic_block (NULL, (void *) 0,
1352                                          (basic_block) bb->prev_bb->aux);
1353   copy_basic_block->count = bb->count * count_scale / REG_BR_PROB_BASE;
1354
1355   /* We are going to rebuild frequencies from scratch.  These values
1356      have just small importance to drive canonicalize_loop_headers.  */
1357   copy_basic_block->frequency = ((gcov_type)bb->frequency
1358                                  * frequency_scale / REG_BR_PROB_BASE);
1359
1360   if (copy_basic_block->frequency > BB_FREQ_MAX)
1361     copy_basic_block->frequency = BB_FREQ_MAX;
1362
1363   copy_gsi = gsi_start_bb (copy_basic_block);
1364
1365   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1366     {
1367       gimple stmt = gsi_stmt (gsi);
1368       gimple orig_stmt = stmt;
1369
1370       id->regimplify = false;
1371       stmt = remap_gimple_stmt (stmt, id);
1372       if (gimple_nop_p (stmt))
1373         continue;
1374
1375       gimple_duplicate_stmt_histograms (cfun, stmt, id->src_cfun, orig_stmt);
1376       seq_gsi = copy_gsi;
1377
1378       /* With return slot optimization we can end up with
1379          non-gimple (foo *)&this->m, fix that here.  */
1380       if (is_gimple_assign (stmt)
1381           && gimple_assign_rhs_code (stmt) == NOP_EXPR
1382           && !is_gimple_val (gimple_assign_rhs1 (stmt)))
1383         {
1384           tree new_rhs;
1385           new_rhs = force_gimple_operand_gsi (&seq_gsi,
1386                                               gimple_assign_rhs1 (stmt),
1387                                               true, NULL, false, GSI_NEW_STMT);
1388           gimple_assign_set_rhs1 (stmt, new_rhs);
1389           id->regimplify = false;
1390         }
1391
1392       gsi_insert_after (&seq_gsi, stmt, GSI_NEW_STMT);
1393
1394       if (id->regimplify)
1395         gimple_regimplify_operands (stmt, &seq_gsi);
1396
1397       /* If copy_basic_block has been empty at the start of this iteration,
1398          call gsi_start_bb again to get at the newly added statements.  */
1399       if (gsi_end_p (copy_gsi))
1400         copy_gsi = gsi_start_bb (copy_basic_block);
1401       else
1402         gsi_next (&copy_gsi);
1403
1404       /* Process the new statement.  The call to gimple_regimplify_operands
1405          possibly turned the statement into multiple statements, we
1406          need to process all of them.  */
1407       do
1408         {
1409           tree fn;
1410
1411           stmt = gsi_stmt (copy_gsi);
1412           if (is_gimple_call (stmt)
1413               && gimple_call_va_arg_pack_p (stmt)
1414               && id->gimple_call)
1415             {
1416               /* __builtin_va_arg_pack () should be replaced by
1417                  all arguments corresponding to ... in the caller.  */
1418               tree p;
1419               gimple new_call;
1420               VEC(tree, heap) *argarray;
1421               size_t nargs = gimple_call_num_args (id->gimple_call);
1422               size_t n;
1423
1424               for (p = DECL_ARGUMENTS (id->src_fn); p; p = TREE_CHAIN (p))
1425                 nargs--;
1426
1427               /* Create the new array of arguments.  */
1428               n = nargs + gimple_call_num_args (stmt);
1429               argarray = VEC_alloc (tree, heap, n);
1430               VEC_safe_grow (tree, heap, argarray, n);
1431
1432               /* Copy all the arguments before '...'  */
1433               memcpy (VEC_address (tree, argarray),
1434                       gimple_call_arg_ptr (stmt, 0),
1435                       gimple_call_num_args (stmt) * sizeof (tree));
1436
1437               /* Append the arguments passed in '...'  */
1438               memcpy (VEC_address(tree, argarray) + gimple_call_num_args (stmt),
1439                       gimple_call_arg_ptr (id->gimple_call, 0)
1440                         + (gimple_call_num_args (id->gimple_call) - nargs),
1441                       nargs * sizeof (tree));
1442
1443               new_call = gimple_build_call_vec (gimple_call_fn (stmt),
1444                                                 argarray);
1445
1446               VEC_free (tree, heap, argarray);
1447
1448               /* Copy all GIMPLE_CALL flags, location and block, except
1449                  GF_CALL_VA_ARG_PACK.  */
1450               gimple_call_copy_flags (new_call, stmt);
1451               gimple_call_set_va_arg_pack (new_call, false);
1452               gimple_set_location (new_call, gimple_location (stmt));
1453               gimple_set_block (new_call, gimple_block (stmt));
1454               gimple_call_set_lhs (new_call, gimple_call_lhs (stmt));
1455
1456               gsi_replace (&copy_gsi, new_call, false);
1457               gimple_set_bb (stmt, NULL);
1458               stmt = new_call;
1459             }
1460           else if (is_gimple_call (stmt)
1461                    && id->gimple_call
1462                    && (decl = gimple_call_fndecl (stmt))
1463                    && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
1464                    && DECL_FUNCTION_CODE (decl) == BUILT_IN_VA_ARG_PACK_LEN)
1465             {
1466               /* __builtin_va_arg_pack_len () should be replaced by
1467                  the number of anonymous arguments.  */
1468               size_t nargs = gimple_call_num_args (id->gimple_call);
1469               tree count, p;
1470               gimple new_stmt;
1471
1472               for (p = DECL_ARGUMENTS (id->src_fn); p; p = TREE_CHAIN (p))
1473                 nargs--;
1474
1475               count = build_int_cst (integer_type_node, nargs);
1476               new_stmt = gimple_build_assign (gimple_call_lhs (stmt), count);
1477               gsi_replace (&copy_gsi, new_stmt, false);
1478               stmt = new_stmt;
1479             }
1480
1481           /* Statements produced by inlining can be unfolded, especially
1482              when we constant propagated some operands.  We can't fold
1483              them right now for two reasons:
1484              1) folding require SSA_NAME_DEF_STMTs to be correct
1485              2) we can't change function calls to builtins.
1486              So we just mark statement for later folding.  We mark
1487              all new statements, instead just statements that has changed
1488              by some nontrivial substitution so even statements made
1489              foldable indirectly are updated.  If this turns out to be
1490              expensive, copy_body can be told to watch for nontrivial
1491              changes.  */
1492           if (id->statements_to_fold)
1493             pointer_set_insert (id->statements_to_fold, stmt);
1494
1495           /* We're duplicating a CALL_EXPR.  Find any corresponding
1496              callgraph edges and update or duplicate them.  */
1497           if (is_gimple_call (stmt))
1498             {
1499               struct cgraph_edge *edge;
1500               int flags;
1501
1502               switch (id->transform_call_graph_edges)
1503                 {
1504                 case CB_CGE_DUPLICATE:
1505                   edge = cgraph_edge (id->src_node, orig_stmt);
1506                   if (edge)
1507                     edge = cgraph_clone_edge (edge, id->dst_node, stmt,
1508                                               REG_BR_PROB_BASE, 1,
1509                                               edge->frequency, true);
1510                   break;
1511
1512                 case CB_CGE_MOVE_CLONES:
1513                   cgraph_set_call_stmt_including_clones (id->dst_node,
1514                                                          orig_stmt, stmt);
1515                   edge = cgraph_edge (id->dst_node, stmt);
1516                   break;
1517
1518                 case CB_CGE_MOVE:
1519                   edge = cgraph_edge (id->dst_node, orig_stmt);
1520                   if (edge)
1521                     cgraph_set_call_stmt (edge, stmt);
1522                   break;
1523
1524                 default:
1525                   gcc_unreachable ();
1526                 }
1527
1528               /* Constant propagation on argument done during inlining
1529                  may create new direct call.  Produce an edge for it.  */
1530               if ((!edge 
1531                    || (edge->indirect_call
1532                        && id->transform_call_graph_edges == CB_CGE_MOVE_CLONES))
1533                   && is_gimple_call (stmt)
1534                   && (fn = gimple_call_fndecl (stmt)) != NULL)
1535                 {
1536                   struct cgraph_node *dest = cgraph_node (fn);
1537
1538                   /* We have missing edge in the callgraph.  This can happen
1539                      when previous inlining turned an indirect call into a
1540                      direct call by constant propagating arguments.  In all
1541                      other cases we hit a bug (incorrect node sharing is the
1542                      most common reason for missing edges).  */
1543                   gcc_assert (dest->needed || !dest->analyzed);
1544                   if (id->transform_call_graph_edges == CB_CGE_MOVE_CLONES)
1545                     cgraph_create_edge_including_clones
1546                       (id->dst_node, dest, stmt, bb->count,
1547                        compute_call_stmt_bb_frequency (id->dst_node->decl, bb),
1548                        bb->loop_depth, CIF_ORIGINALLY_INDIRECT_CALL);
1549                   else
1550                     cgraph_create_edge (id->dst_node, dest, stmt,
1551                                         bb->count, CGRAPH_FREQ_BASE,
1552                                         bb->loop_depth)->inline_failed
1553                       = CIF_ORIGINALLY_INDIRECT_CALL;
1554                   if (dump_file)
1555                     {
1556                       fprintf (dump_file, "Created new direct edge to %s",
1557                                cgraph_node_name (dest));
1558                     }
1559                 }
1560
1561               flags = gimple_call_flags (stmt);
1562               if (flags & ECF_MAY_BE_ALLOCA)
1563                 cfun->calls_alloca = true;
1564               if (flags & ECF_RETURNS_TWICE)
1565                 cfun->calls_setjmp = true;
1566             }
1567
1568           /* If you think we can abort here, you are wrong.
1569              There is no region 0 in gimple.  */
1570           gcc_assert (lookup_stmt_eh_region_fn (id->src_cfun, orig_stmt) != 0);
1571
1572           if (stmt_could_throw_p (stmt)
1573               /* When we are cloning for inlining, we are supposed to
1574                  construct a clone that calls precisely the same functions
1575                  as original.  However IPA optimizers might've proved
1576                  earlier some function calls as non-trapping that might
1577                  render some basic blocks dead that might become
1578                  unreachable.
1579
1580                  We can't update SSA with unreachable blocks in CFG and thus
1581                  we prevent the scenario by preserving even the "dead" eh
1582                  edges until the point they are later removed by
1583                  fixup_cfg pass.  */
1584               || (id->transform_call_graph_edges == CB_CGE_MOVE_CLONES
1585                   && lookup_stmt_eh_region_fn (id->src_cfun, orig_stmt) > 0))
1586             {
1587               int region = lookup_stmt_eh_region_fn (id->src_cfun, orig_stmt);
1588
1589               /* Add an entry for the copied tree in the EH hashtable.
1590                  When cloning or versioning, use the hashtable in
1591                  cfun, and just copy the EH number.  When inlining, use the
1592                  hashtable in the caller, and adjust the region number.  */
1593               if (region > 0)
1594                 add_stmt_to_eh_region (stmt, region + id->eh_region_offset);
1595
1596               /* If this tree doesn't have a region associated with it,
1597                  and there is a "current region,"
1598                  then associate this tree with the current region
1599                  and add edges associated with this region.  */
1600               if (lookup_stmt_eh_region_fn (id->src_cfun, orig_stmt) <= 0
1601                   && id->eh_region > 0
1602                   && stmt_could_throw_p (stmt))
1603                 add_stmt_to_eh_region (stmt, id->eh_region);
1604             }
1605
1606           if (gimple_in_ssa_p (cfun))
1607             {
1608               ssa_op_iter i;
1609               tree def;
1610
1611               find_new_referenced_vars (gsi_stmt (copy_gsi));
1612               FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
1613                 if (TREE_CODE (def) == SSA_NAME)
1614                   SSA_NAME_DEF_STMT (def) = stmt;
1615             }
1616
1617           gsi_next (&copy_gsi);
1618         }
1619       while (!gsi_end_p (copy_gsi));
1620
1621       copy_gsi = gsi_last_bb (copy_basic_block);
1622     }
1623
1624   return copy_basic_block;
1625 }
1626
1627 /* Inserting Single Entry Multiple Exit region in SSA form into code in SSA
1628    form is quite easy, since dominator relationship for old basic blocks does
1629    not change.
1630
1631    There is however exception where inlining might change dominator relation
1632    across EH edges from basic block within inlined functions destinating
1633    to landing pads in function we inline into.
1634
1635    The function fills in PHI_RESULTs of such PHI nodes if they refer
1636    to gimple regs.  Otherwise, the function mark PHI_RESULT of such
1637    PHI nodes for renaming.  For non-gimple regs, renaming is safe: the
1638    EH edges are abnormal and SSA_NAME_OCCURS_IN_ABNORMAL_PHI must be
1639    set, and this means that there will be no overlapping live ranges
1640    for the underlying symbol.
1641
1642    This might change in future if we allow redirecting of EH edges and
1643    we might want to change way build CFG pre-inlining to include
1644    all the possible edges then.  */
1645 static void
1646 update_ssa_across_abnormal_edges (basic_block bb, basic_block ret_bb,
1647                                   bool can_throw, bool nonlocal_goto)
1648 {
1649   edge e;
1650   edge_iterator ei;
1651
1652   FOR_EACH_EDGE (e, ei, bb->succs)
1653     if (!e->dest->aux
1654         || ((basic_block)e->dest->aux)->index == ENTRY_BLOCK)
1655       {
1656         gimple phi;
1657         gimple_stmt_iterator si;
1658
1659         if (!nonlocal_goto)
1660           gcc_assert (e->flags & EDGE_EH);
1661
1662         if (!can_throw)
1663           gcc_assert (!(e->flags & EDGE_EH));
1664
1665         for (si = gsi_start_phis (e->dest); !gsi_end_p (si); gsi_next (&si))
1666           {
1667             edge re;
1668
1669             phi = gsi_stmt (si);
1670
1671             /* There shouldn't be any PHI nodes in the ENTRY_BLOCK.  */
1672             gcc_assert (!e->dest->aux);
1673
1674             gcc_assert ((e->flags & EDGE_EH)
1675                         || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)));
1676
1677             if (!is_gimple_reg (PHI_RESULT (phi)))
1678               {
1679                 mark_sym_for_renaming (SSA_NAME_VAR (PHI_RESULT (phi)));
1680                 continue;
1681               }
1682
1683             re = find_edge (ret_bb, e->dest);
1684             gcc_assert (re);
1685             gcc_assert ((re->flags & (EDGE_EH | EDGE_ABNORMAL))
1686                         == (e->flags & (EDGE_EH | EDGE_ABNORMAL)));
1687
1688             SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (phi, e),
1689                      USE_FROM_PTR (PHI_ARG_DEF_PTR_FROM_EDGE (phi, re)));
1690           }
1691       }
1692 }
1693
1694
1695 /* Copy edges from BB into its copy constructed earlier, scale profile
1696    accordingly.  Edges will be taken care of later.  Assume aux
1697    pointers to point to the copies of each BB.  */
1698
1699 static void
1700 copy_edges_for_bb (basic_block bb, gcov_type count_scale, basic_block ret_bb)
1701 {
1702   basic_block new_bb = (basic_block) bb->aux;
1703   edge_iterator ei;
1704   edge old_edge;
1705   gimple_stmt_iterator si;
1706   int flags;
1707
1708   /* Use the indices from the original blocks to create edges for the
1709      new ones.  */
1710   FOR_EACH_EDGE (old_edge, ei, bb->succs)
1711     if (!(old_edge->flags & EDGE_EH))
1712       {
1713         edge new_edge;
1714
1715         flags = old_edge->flags;
1716
1717         /* Return edges do get a FALLTHRU flag when the get inlined.  */
1718         if (old_edge->dest->index == EXIT_BLOCK && !old_edge->flags
1719             && old_edge->dest->aux != EXIT_BLOCK_PTR)
1720           flags |= EDGE_FALLTHRU;
1721         new_edge = make_edge (new_bb, (basic_block) old_edge->dest->aux, flags);
1722         new_edge->count = old_edge->count * count_scale / REG_BR_PROB_BASE;
1723         new_edge->probability = old_edge->probability;
1724       }
1725
1726   if (bb->index == ENTRY_BLOCK || bb->index == EXIT_BLOCK)
1727     return;
1728
1729   for (si = gsi_start_bb (new_bb); !gsi_end_p (si);)
1730     {
1731       gimple copy_stmt;
1732       bool can_throw, nonlocal_goto;
1733
1734       copy_stmt = gsi_stmt (si);
1735       update_stmt (copy_stmt);
1736       if (gimple_in_ssa_p (cfun))
1737         mark_symbols_for_renaming (copy_stmt);
1738
1739       /* Do this before the possible split_block.  */
1740       gsi_next (&si);
1741
1742       /* If this tree could throw an exception, there are two
1743          cases where we need to add abnormal edge(s): the
1744          tree wasn't in a region and there is a "current
1745          region" in the caller; or the original tree had
1746          EH edges.  In both cases split the block after the tree,
1747          and add abnormal edge(s) as needed; we need both
1748          those from the callee and the caller.
1749          We check whether the copy can throw, because the const
1750          propagation can change an INDIRECT_REF which throws
1751          into a COMPONENT_REF which doesn't.  If the copy
1752          can throw, the original could also throw.  */
1753       can_throw = stmt_can_throw_internal (copy_stmt);
1754       nonlocal_goto = stmt_can_make_abnormal_goto (copy_stmt);
1755
1756       if (can_throw || nonlocal_goto)
1757         {
1758           if (!gsi_end_p (si))
1759             /* Note that bb's predecessor edges aren't necessarily
1760                right at this point; split_block doesn't care.  */
1761             {
1762               edge e = split_block (new_bb, copy_stmt);
1763
1764               new_bb = e->dest;
1765               new_bb->aux = e->src->aux;
1766               si = gsi_start_bb (new_bb);
1767             }
1768         }
1769
1770       if (can_throw)
1771         make_eh_edges (copy_stmt);
1772
1773       if (nonlocal_goto)
1774         make_abnormal_goto_edges (gimple_bb (copy_stmt), true);
1775
1776       if ((can_throw || nonlocal_goto)
1777           && gimple_in_ssa_p (cfun))
1778         update_ssa_across_abnormal_edges (gimple_bb (copy_stmt), ret_bb,
1779                                           can_throw, nonlocal_goto);
1780     }
1781 }
1782
1783 /* Copy the PHIs.  All blocks and edges are copied, some blocks
1784    was possibly split and new outgoing EH edges inserted.
1785    BB points to the block of original function and AUX pointers links
1786    the original and newly copied blocks.  */
1787
1788 static void
1789 copy_phis_for_bb (basic_block bb, copy_body_data *id)
1790 {
1791   basic_block const new_bb = (basic_block) bb->aux;
1792   edge_iterator ei;
1793   gimple phi;
1794   gimple_stmt_iterator si;
1795
1796   for (si = gsi_start (phi_nodes (bb)); !gsi_end_p (si); gsi_next (&si))
1797     {
1798       tree res, new_res;
1799       gimple new_phi;
1800       edge new_edge;
1801
1802       phi = gsi_stmt (si);
1803       res = PHI_RESULT (phi);
1804       new_res = res;
1805       if (is_gimple_reg (res))
1806         {
1807           walk_tree (&new_res, copy_tree_body_r, id, NULL);
1808           SSA_NAME_DEF_STMT (new_res)
1809             = new_phi = create_phi_node (new_res, new_bb);
1810           FOR_EACH_EDGE (new_edge, ei, new_bb->preds)
1811             {
1812               edge const old_edge
1813                 = find_edge ((basic_block) new_edge->src->aux, bb);
1814               tree arg = PHI_ARG_DEF_FROM_EDGE (phi, old_edge);
1815               tree new_arg = arg;
1816               tree block = id->block;
1817               id->block = NULL_TREE;
1818               walk_tree (&new_arg, copy_tree_body_r, id, NULL);
1819               id->block = block;
1820               gcc_assert (new_arg);
1821               /* With return slot optimization we can end up with
1822                  non-gimple (foo *)&this->m, fix that here.  */
1823               if (TREE_CODE (new_arg) != SSA_NAME
1824                   && TREE_CODE (new_arg) != FUNCTION_DECL
1825                   && !is_gimple_val (new_arg))
1826                 {
1827                   gimple_seq stmts = NULL;
1828                   new_arg = force_gimple_operand (new_arg, &stmts, true, NULL);
1829                   gsi_insert_seq_on_edge_immediate (new_edge, stmts);
1830                 }
1831               add_phi_arg (new_phi, new_arg, new_edge, 
1832                            gimple_phi_arg_location_from_edge (phi, old_edge));
1833             }
1834         }
1835     }
1836 }
1837
1838
1839 /* Wrapper for remap_decl so it can be used as a callback.  */
1840
1841 static tree
1842 remap_decl_1 (tree decl, void *data)
1843 {
1844   return remap_decl (decl, (copy_body_data *) data);
1845 }
1846
1847 /* Build struct function and associated datastructures for the new clone
1848    NEW_FNDECL to be build.  CALLEE_FNDECL is the original */
1849
1850 static void
1851 initialize_cfun (tree new_fndecl, tree callee_fndecl, gcov_type count,
1852                  int frequency)
1853 {
1854   struct function *src_cfun = DECL_STRUCT_FUNCTION (callee_fndecl);
1855   gcov_type count_scale, frequency_scale;
1856
1857   if (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count)
1858     count_scale = (REG_BR_PROB_BASE * count
1859                    / ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count);
1860   else
1861     count_scale = 1;
1862
1863   if (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency)
1864     frequency_scale = (REG_BR_PROB_BASE * frequency
1865                        /
1866                        ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency);
1867   else
1868     frequency_scale = count_scale;
1869
1870   /* Register specific tree functions.  */
1871   gimple_register_cfg_hooks ();
1872
1873   /* Get clean struct function.  */
1874   push_struct_function (new_fndecl);
1875
1876   /* We will rebuild these, so just sanity check that they are empty.  */
1877   gcc_assert (VALUE_HISTOGRAMS (cfun) == NULL);
1878   gcc_assert (cfun->local_decls == NULL);
1879   gcc_assert (cfun->cfg == NULL);
1880   gcc_assert (cfun->decl == new_fndecl);
1881
1882   /* Copy items we preserve during clonning.  */
1883   cfun->static_chain_decl = src_cfun->static_chain_decl;
1884   cfun->nonlocal_goto_save_area = src_cfun->nonlocal_goto_save_area;
1885   cfun->function_end_locus = src_cfun->function_end_locus;
1886   cfun->curr_properties = src_cfun->curr_properties;
1887   cfun->last_verified = src_cfun->last_verified;
1888   if (src_cfun->ipa_transforms_to_apply)
1889     cfun->ipa_transforms_to_apply = VEC_copy (ipa_opt_pass, heap,
1890                                               src_cfun->ipa_transforms_to_apply);
1891   cfun->va_list_gpr_size = src_cfun->va_list_gpr_size;
1892   cfun->va_list_fpr_size = src_cfun->va_list_fpr_size;
1893   cfun->function_frequency = src_cfun->function_frequency;
1894   cfun->has_nonlocal_label = src_cfun->has_nonlocal_label;
1895   cfun->stdarg = src_cfun->stdarg;
1896   cfun->dont_save_pending_sizes_p = src_cfun->dont_save_pending_sizes_p;
1897   cfun->after_inlining = src_cfun->after_inlining;
1898   cfun->returns_struct = src_cfun->returns_struct;
1899   cfun->returns_pcc_struct = src_cfun->returns_pcc_struct;
1900   cfun->after_tree_profile = src_cfun->after_tree_profile;
1901
1902   init_empty_tree_cfg ();
1903
1904   ENTRY_BLOCK_PTR->count =
1905     (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count * count_scale /
1906      REG_BR_PROB_BASE);
1907   ENTRY_BLOCK_PTR->frequency =
1908     (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency *
1909      frequency_scale / REG_BR_PROB_BASE);
1910   EXIT_BLOCK_PTR->count =
1911     (EXIT_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count * count_scale /
1912      REG_BR_PROB_BASE);
1913   EXIT_BLOCK_PTR->frequency =
1914     (EXIT_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency *
1915      frequency_scale / REG_BR_PROB_BASE);
1916   if (src_cfun->eh)
1917     init_eh_for_function ();
1918
1919   if (src_cfun->gimple_df)
1920     {
1921       init_tree_ssa (cfun);
1922       cfun->gimple_df->in_ssa_p = true;
1923       init_ssa_operands ();
1924     }
1925   pop_cfun ();
1926 }
1927
1928 /* Make a copy of the body of FN so that it can be inserted inline in
1929    another function.  Walks FN via CFG, returns new fndecl.  */
1930
1931 static tree
1932 copy_cfg_body (copy_body_data * id, gcov_type count, int frequency,
1933                basic_block entry_block_map, basic_block exit_block_map)
1934 {
1935   tree callee_fndecl = id->src_fn;
1936   /* Original cfun for the callee, doesn't change.  */
1937   struct function *src_cfun = DECL_STRUCT_FUNCTION (callee_fndecl);
1938   struct function *cfun_to_copy;
1939   basic_block bb;
1940   tree new_fndecl = NULL;
1941   gcov_type count_scale, frequency_scale;
1942   int last;
1943
1944   if (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count)
1945     count_scale = (REG_BR_PROB_BASE * count
1946                    / ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->count);
1947   else
1948     count_scale = 1;
1949
1950   if (ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency)
1951     frequency_scale = (REG_BR_PROB_BASE * frequency
1952                        /
1953                        ENTRY_BLOCK_PTR_FOR_FUNCTION (src_cfun)->frequency);
1954   else
1955     frequency_scale = count_scale;
1956
1957   /* Register specific tree functions.  */
1958   gimple_register_cfg_hooks ();
1959
1960   /* Must have a CFG here at this point.  */
1961   gcc_assert (ENTRY_BLOCK_PTR_FOR_FUNCTION
1962               (DECL_STRUCT_FUNCTION (callee_fndecl)));
1963
1964   cfun_to_copy = id->src_cfun = DECL_STRUCT_FUNCTION (callee_fndecl);
1965
1966   ENTRY_BLOCK_PTR_FOR_FUNCTION (cfun_to_copy)->aux = entry_block_map;
1967   EXIT_BLOCK_PTR_FOR_FUNCTION (cfun_to_copy)->aux = exit_block_map;
1968   entry_block_map->aux = ENTRY_BLOCK_PTR_FOR_FUNCTION (cfun_to_copy);
1969   exit_block_map->aux = EXIT_BLOCK_PTR_FOR_FUNCTION (cfun_to_copy);
1970
1971   /* Duplicate any exception-handling regions.  */
1972   if (cfun->eh)
1973     {
1974       id->eh_region_offset
1975         = duplicate_eh_regions (cfun_to_copy, remap_decl_1, id,
1976                                 0, id->eh_region);
1977     }
1978
1979   /* Use aux pointers to map the original blocks to copy.  */
1980   FOR_EACH_BB_FN (bb, cfun_to_copy)
1981     {
1982       basic_block new_bb = copy_bb (id, bb, frequency_scale, count_scale);
1983       bb->aux = new_bb;
1984       new_bb->aux = bb;
1985     }
1986
1987   last = last_basic_block;
1988
1989   /* Now that we've duplicated the blocks, duplicate their edges.  */
1990   FOR_ALL_BB_FN (bb, cfun_to_copy)
1991     copy_edges_for_bb (bb, count_scale, exit_block_map);
1992
1993   if (gimple_in_ssa_p (cfun))
1994     FOR_ALL_BB_FN (bb, cfun_to_copy)
1995       copy_phis_for_bb (bb, id);
1996
1997   FOR_ALL_BB_FN (bb, cfun_to_copy)
1998     {
1999       ((basic_block)bb->aux)->aux = NULL;
2000       bb->aux = NULL;
2001     }
2002
2003   /* Zero out AUX fields of newly created block during EH edge
2004      insertion. */
2005   for (; last < last_basic_block; last++)
2006     BASIC_BLOCK (last)->aux = NULL;
2007   entry_block_map->aux = NULL;
2008   exit_block_map->aux = NULL;
2009
2010   return new_fndecl;
2011 }
2012
2013 /* Make a copy of the body of SRC_FN so that it can be inserted inline in
2014    another function.  */
2015
2016 static tree
2017 copy_tree_body (copy_body_data *id)
2018 {
2019   tree fndecl = id->src_fn;
2020   tree body = DECL_SAVED_TREE (fndecl);
2021
2022   walk_tree (&body, copy_tree_body_r, id, NULL);
2023
2024   return body;
2025 }
2026
2027 static tree
2028 copy_body (copy_body_data *id, gcov_type count, int frequency,
2029            basic_block entry_block_map, basic_block exit_block_map)
2030 {
2031   tree fndecl = id->src_fn;
2032   tree body;
2033
2034   /* If this body has a CFG, walk CFG and copy.  */
2035   gcc_assert (ENTRY_BLOCK_PTR_FOR_FUNCTION (DECL_STRUCT_FUNCTION (fndecl)));
2036   body = copy_cfg_body (id, count, frequency, entry_block_map, exit_block_map);
2037
2038   return body;
2039 }
2040
2041 /* Return true if VALUE is an ADDR_EXPR of an automatic variable
2042    defined in function FN, or of a data member thereof.  */
2043
2044 static bool
2045 self_inlining_addr_expr (tree value, tree fn)
2046 {
2047   tree var;
2048
2049   if (TREE_CODE (value) != ADDR_EXPR)
2050     return false;
2051
2052   var = get_base_address (TREE_OPERAND (value, 0));
2053
2054   return var && auto_var_in_fn_p (var, fn);
2055 }
2056
2057 static void
2058 insert_init_stmt (basic_block bb, gimple init_stmt)
2059 {
2060   /* If VAR represents a zero-sized variable, it's possible that the
2061      assignment statement may result in no gimple statements.  */
2062   if (init_stmt)
2063     {
2064       gimple_stmt_iterator si = gsi_last_bb (bb);
2065
2066       /* We can end up with init statements that store to a non-register
2067          from a rhs with a conversion.  Handle that here by forcing the
2068          rhs into a temporary.  gimple_regimplify_operands is not
2069          prepared to do this for us.  */
2070       if (!is_gimple_reg (gimple_assign_lhs (init_stmt))
2071           && is_gimple_reg_type (TREE_TYPE (gimple_assign_lhs (init_stmt)))
2072           && gimple_assign_rhs_class (init_stmt) == GIMPLE_UNARY_RHS)
2073         {
2074           tree rhs = build1 (gimple_assign_rhs_code (init_stmt),
2075                              gimple_expr_type (init_stmt),
2076                              gimple_assign_rhs1 (init_stmt));
2077           rhs = force_gimple_operand_gsi (&si, rhs, true, NULL_TREE, false,
2078                                           GSI_NEW_STMT);
2079           gimple_assign_set_rhs_code (init_stmt, TREE_CODE (rhs));
2080           gimple_assign_set_rhs1 (init_stmt, rhs);
2081         }
2082       gsi_insert_after (&si, init_stmt, GSI_NEW_STMT);
2083       gimple_regimplify_operands (init_stmt, &si);
2084       mark_symbols_for_renaming (init_stmt);
2085     }
2086 }
2087
2088 /* Initialize parameter P with VALUE.  If needed, produce init statement
2089    at the end of BB.  When BB is NULL, we return init statement to be
2090    output later.  */
2091 static gimple
2092 setup_one_parameter (copy_body_data *id, tree p, tree value, tree fn,
2093                      basic_block bb, tree *vars)
2094 {
2095   gimple init_stmt = NULL;
2096   tree var;
2097   tree rhs = value;
2098   tree def = (gimple_in_ssa_p (cfun)
2099               ? gimple_default_def (id->src_cfun, p) : NULL);
2100
2101   if (value
2102       && value != error_mark_node
2103       && !useless_type_conversion_p (TREE_TYPE (p), TREE_TYPE (value)))
2104     {
2105       if (fold_convertible_p (TREE_TYPE (p), value))
2106         rhs = fold_build1 (NOP_EXPR, TREE_TYPE (p), value);
2107       else
2108         /* ???  For valid (GIMPLE) programs we should not end up here.
2109            Still if something has gone wrong and we end up with truly
2110            mismatched types here, fall back to using a VIEW_CONVERT_EXPR
2111            to not leak invalid GIMPLE to the following passes.  */
2112         rhs = fold_build1 (VIEW_CONVERT_EXPR, TREE_TYPE (p), value);
2113     }
2114
2115   /* If the parameter is never assigned to, has no SSA_NAMEs created,
2116      we may not need to create a new variable here at all.  Instead, we may
2117      be able to just use the argument value.  */
2118   if (TREE_READONLY (p)
2119       && !TREE_ADDRESSABLE (p)
2120       && value && !TREE_SIDE_EFFECTS (value)
2121       && !def)
2122     {
2123       /* We may produce non-gimple trees by adding NOPs or introduce
2124          invalid sharing when operand is not really constant.
2125          It is not big deal to prohibit constant propagation here as
2126          we will constant propagate in DOM1 pass anyway.  */
2127       if (is_gimple_min_invariant (value)
2128           && useless_type_conversion_p (TREE_TYPE (p),
2129                                                  TREE_TYPE (value))
2130           /* We have to be very careful about ADDR_EXPR.  Make sure
2131              the base variable isn't a local variable of the inlined
2132              function, e.g., when doing recursive inlining, direct or
2133              mutually-recursive or whatever, which is why we don't
2134              just test whether fn == current_function_decl.  */
2135           && ! self_inlining_addr_expr (value, fn))
2136         {
2137           insert_decl_map (id, p, value);
2138           return NULL;
2139         }
2140     }
2141
2142   /* Make an equivalent VAR_DECL.  Note that we must NOT remap the type
2143      here since the type of this decl must be visible to the calling
2144      function.  */
2145   var = copy_decl_to_var (p, id);
2146   if (gimple_in_ssa_p (cfun) && TREE_CODE (var) == VAR_DECL)
2147     {
2148       get_var_ann (var);
2149       add_referenced_var (var);
2150     }
2151
2152   /* Register the VAR_DECL as the equivalent for the PARM_DECL;
2153      that way, when the PARM_DECL is encountered, it will be
2154      automatically replaced by the VAR_DECL.  */
2155   insert_decl_map (id, p, var);
2156
2157   /* Declare this new variable.  */
2158   TREE_CHAIN (var) = *vars;
2159   *vars = var;
2160
2161   /* Make gimplifier happy about this variable.  */
2162   DECL_SEEN_IN_BIND_EXPR_P (var) = 1;
2163
2164   /* Even if P was TREE_READONLY, the new VAR should not be.
2165      In the original code, we would have constructed a
2166      temporary, and then the function body would have never
2167      changed the value of P.  However, now, we will be
2168      constructing VAR directly.  The constructor body may
2169      change its value multiple times as it is being
2170      constructed.  Therefore, it must not be TREE_READONLY;
2171      the back-end assumes that TREE_READONLY variable is
2172      assigned to only once.  */
2173   if (TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (p)))
2174     TREE_READONLY (var) = 0;
2175
2176   /* If there is no setup required and we are in SSA, take the easy route
2177      replacing all SSA names representing the function parameter by the
2178      SSA name passed to function.
2179
2180      We need to construct map for the variable anyway as it might be used
2181      in different SSA names when parameter is set in function.
2182
2183      Do replacement at -O0 for const arguments replaced by constant.
2184      This is important for builtin_constant_p and other construct requiring
2185      constant argument to be visible in inlined function body.
2186
2187      FIXME: This usually kills the last connection in between inlined
2188      function parameter and the actual value in debug info.  Can we do
2189      better here?  If we just inserted the statement, copy propagation
2190      would kill it anyway as it always did in older versions of GCC.
2191
2192      We might want to introduce a notion that single SSA_NAME might
2193      represent multiple variables for purposes of debugging. */
2194   if (gimple_in_ssa_p (cfun) && rhs && def && is_gimple_reg (p)
2195       && (optimize
2196           || (TREE_READONLY (p)
2197               && is_gimple_min_invariant (rhs)))
2198       && (TREE_CODE (rhs) == SSA_NAME
2199           || is_gimple_min_invariant (rhs))
2200       && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def))
2201     {
2202       insert_decl_map (id, def, rhs);
2203       return NULL;
2204     }
2205
2206   /* If the value of argument is never used, don't care about initializing
2207      it.  */
2208   if (optimize && gimple_in_ssa_p (cfun) && !def && is_gimple_reg (p))
2209     {
2210       gcc_assert (!value || !TREE_SIDE_EFFECTS (value));
2211       return NULL;
2212     }
2213
2214   /* Initialize this VAR_DECL from the equivalent argument.  Convert
2215      the argument to the proper type in case it was promoted.  */
2216   if (value)
2217     {
2218       if (rhs == error_mark_node)
2219         {
2220           insert_decl_map (id, p, var);
2221           return NULL;
2222         }
2223
2224       STRIP_USELESS_TYPE_CONVERSION (rhs);
2225
2226       /* We want to use MODIFY_EXPR, not INIT_EXPR here so that we
2227          keep our trees in gimple form.  */
2228       if (def && gimple_in_ssa_p (cfun) && is_gimple_reg (p))
2229         {
2230           def = remap_ssa_name (def, id);
2231           init_stmt = gimple_build_assign (def, rhs);
2232           SSA_NAME_IS_DEFAULT_DEF (def) = 0;
2233           set_default_def (var, NULL);
2234         }
2235       else
2236         init_stmt = gimple_build_assign (var, rhs);
2237
2238       if (bb && init_stmt)
2239         insert_init_stmt (bb, init_stmt);
2240     }
2241   return init_stmt;
2242 }
2243
2244 /* Generate code to initialize the parameters of the function at the
2245    top of the stack in ID from the GIMPLE_CALL STMT.  */
2246
2247 static void
2248 initialize_inlined_parameters (copy_body_data *id, gimple stmt,
2249                                tree fn, basic_block bb)
2250 {
2251   tree parms;
2252   size_t i;
2253   tree p;
2254   tree vars = NULL_TREE;
2255   tree static_chain = gimple_call_chain (stmt);
2256
2257   /* Figure out what the parameters are.  */
2258   parms = DECL_ARGUMENTS (fn);
2259
2260   /* Loop through the parameter declarations, replacing each with an
2261      equivalent VAR_DECL, appropriately initialized.  */
2262   for (p = parms, i = 0; p; p = TREE_CHAIN (p), i++)
2263     {
2264       tree val;
2265       val = i < gimple_call_num_args (stmt) ? gimple_call_arg (stmt, i) : NULL;
2266       setup_one_parameter (id, p, val, fn, bb, &vars);
2267     }
2268
2269   /* Initialize the static chain.  */
2270   p = DECL_STRUCT_FUNCTION (fn)->static_chain_decl;
2271   gcc_assert (fn != current_function_decl);
2272   if (p)
2273     {
2274       /* No static chain?  Seems like a bug in tree-nested.c.  */
2275       gcc_assert (static_chain);
2276
2277       setup_one_parameter (id, p, static_chain, fn, bb, &vars);
2278     }
2279
2280   declare_inline_vars (id->block, vars);
2281 }
2282
2283
2284 /* Declare a return variable to replace the RESULT_DECL for the
2285    function we are calling.  An appropriate DECL_STMT is returned.
2286    The USE_STMT is filled to contain a use of the declaration to
2287    indicate the return value of the function.
2288
2289    RETURN_SLOT, if non-null is place where to store the result.  It
2290    is set only for CALL_EXPR_RETURN_SLOT_OPT.  MODIFY_DEST, if non-null,
2291    was the LHS of the MODIFY_EXPR to which this call is the RHS.
2292
2293    The return value is a (possibly null) value that is the result of the
2294    function as seen by the callee.  *USE_P is a (possibly null) value that
2295    holds the result as seen by the caller.  */
2296
2297 static tree
2298 declare_return_variable (copy_body_data *id, tree return_slot, tree modify_dest,
2299                          tree *use_p)
2300 {
2301   tree callee = id->src_fn;
2302   tree caller = id->dst_fn;
2303   tree result = DECL_RESULT (callee);
2304   tree callee_type = TREE_TYPE (result);
2305   tree caller_type = TREE_TYPE (TREE_TYPE (callee));
2306   tree var, use;
2307
2308   /* We don't need to do anything for functions that don't return
2309      anything.  */
2310   if (!result || VOID_TYPE_P (callee_type))
2311     {
2312       *use_p = NULL_TREE;
2313       return NULL_TREE;
2314     }
2315
2316   /* If there was a return slot, then the return value is the
2317      dereferenced address of that object.  */
2318   if (return_slot)
2319     {
2320       /* The front end shouldn't have used both return_slot and
2321          a modify expression.  */
2322       gcc_assert (!modify_dest);
2323       if (DECL_BY_REFERENCE (result))
2324         {
2325           tree return_slot_addr = build_fold_addr_expr (return_slot);
2326           STRIP_USELESS_TYPE_CONVERSION (return_slot_addr);
2327
2328           /* We are going to construct *&return_slot and we can't do that
2329              for variables believed to be not addressable. 
2330
2331              FIXME: This check possibly can match, because values returned
2332              via return slot optimization are not believed to have address
2333              taken by alias analysis.  */
2334           gcc_assert (TREE_CODE (return_slot) != SSA_NAME);
2335           if (gimple_in_ssa_p (cfun))
2336             {
2337               HOST_WIDE_INT bitsize;
2338               HOST_WIDE_INT bitpos;
2339               tree offset;
2340               enum machine_mode mode;
2341               int unsignedp;
2342               int volatilep;
2343               tree base;
2344               base = get_inner_reference (return_slot, &bitsize, &bitpos,
2345                                           &offset,
2346                                           &mode, &unsignedp, &volatilep,
2347                                           false);
2348               if (TREE_CODE (base) == INDIRECT_REF)
2349                 base = TREE_OPERAND (base, 0);
2350               if (TREE_CODE (base) == SSA_NAME)
2351                 base = SSA_NAME_VAR (base);
2352               mark_sym_for_renaming (base);
2353             }
2354           var = return_slot_addr;
2355         }
2356       else
2357         {
2358           var = return_slot;
2359           gcc_assert (TREE_CODE (var) != SSA_NAME);
2360           TREE_ADDRESSABLE (var) |= TREE_ADDRESSABLE (result);
2361         }
2362       if ((TREE_CODE (TREE_TYPE (result)) == COMPLEX_TYPE
2363            || TREE_CODE (TREE_TYPE (result)) == VECTOR_TYPE)
2364           && !DECL_GIMPLE_REG_P (result)
2365           && DECL_P (var))
2366         DECL_GIMPLE_REG_P (var) = 0;
2367       use = NULL;
2368       goto done;
2369     }
2370
2371   /* All types requiring non-trivial constructors should have been handled.  */
2372   gcc_assert (!TREE_ADDRESSABLE (callee_type));
2373
2374   /* Attempt to avoid creating a new temporary variable.  */
2375   if (modify_dest
2376       && TREE_CODE (modify_dest) != SSA_NAME)
2377     {
2378       bool use_it = false;
2379
2380       /* We can't use MODIFY_DEST if there's type promotion involved.  */
2381       if (!useless_type_conversion_p (callee_type, caller_type))
2382         use_it = false;
2383
2384       /* ??? If we're assigning to a variable sized type, then we must
2385          reuse the destination variable, because we've no good way to
2386          create variable sized temporaries at this point.  */
2387       else if (TREE_CODE (TYPE_SIZE_UNIT (caller_type)) != INTEGER_CST)
2388         use_it = true;
2389
2390       /* If the callee cannot possibly modify MODIFY_DEST, then we can
2391          reuse it as the result of the call directly.  Don't do this if
2392          it would promote MODIFY_DEST to addressable.  */
2393       else if (TREE_ADDRESSABLE (result))
2394         use_it = false;
2395       else
2396         {
2397           tree base_m = get_base_address (modify_dest);
2398
2399           /* If the base isn't a decl, then it's a pointer, and we don't
2400              know where that's going to go.  */
2401           if (!DECL_P (base_m))
2402             use_it = false;
2403           else if (is_global_var (base_m))
2404             use_it = false;
2405           else if ((TREE_CODE (TREE_TYPE (result)) == COMPLEX_TYPE
2406                     || TREE_CODE (TREE_TYPE (result)) == VECTOR_TYPE)
2407                    && !DECL_GIMPLE_REG_P (result)
2408                    && DECL_GIMPLE_REG_P (base_m))
2409             use_it = false;
2410           else if (!TREE_ADDRESSABLE (base_m))
2411             use_it = true;
2412         }
2413
2414       if (use_it)
2415         {
2416           var = modify_dest;
2417           use = NULL;
2418           goto done;
2419         }
2420     }
2421
2422   gcc_assert (TREE_CODE (TYPE_SIZE_UNIT (callee_type)) == INTEGER_CST);
2423
2424   var = copy_result_decl_to_var (result, id);
2425   if (gimple_in_ssa_p (cfun))
2426     {
2427       get_var_ann (var);
2428       add_referenced_var (var);
2429     }
2430
2431   DECL_SEEN_IN_BIND_EXPR_P (var) = 1;
2432   DECL_STRUCT_FUNCTION (caller)->local_decls
2433     = tree_cons (NULL_TREE, var,
2434                  DECL_STRUCT_FUNCTION (caller)->local_decls);
2435
2436   /* Do not have the rest of GCC warn about this variable as it should
2437      not be visible to the user.  */
2438   TREE_NO_WARNING (var) = 1;
2439
2440   declare_inline_vars (id->block, var);
2441
2442   /* Build the use expr.  If the return type of the function was
2443      promoted, convert it back to the expected type.  */
2444   use = var;
2445   if (!useless_type_conversion_p (caller_type, TREE_TYPE (var)))
2446     use = fold_convert (caller_type, var);
2447     
2448   STRIP_USELESS_TYPE_CONVERSION (use);
2449
2450   if (DECL_BY_REFERENCE (result))
2451     {
2452       TREE_ADDRESSABLE (var) = 1;
2453       var = build_fold_addr_expr (var);
2454     }
2455
2456  done:
2457   /* Register the VAR_DECL as the equivalent for the RESULT_DECL; that
2458      way, when the RESULT_DECL is encountered, it will be
2459      automatically replaced by the VAR_DECL.  */
2460   insert_decl_map (id, result, var);
2461
2462   /* Remember this so we can ignore it in remap_decls.  */
2463   id->retvar = var;
2464
2465   *use_p = use;
2466   return var;
2467 }
2468
2469 /* Callback through walk_tree.  Determine if a DECL_INITIAL makes reference
2470    to a local label.  */
2471
2472 static tree
2473 has_label_address_in_static_1 (tree *nodep, int *walk_subtrees, void *fnp)
2474 {
2475   tree node = *nodep;
2476   tree fn = (tree) fnp;
2477
2478   if (TREE_CODE (node) == LABEL_DECL && DECL_CONTEXT (node) == fn)
2479     return node;
2480
2481   if (TYPE_P (node))
2482     *walk_subtrees = 0;
2483
2484   return NULL_TREE;
2485 }
2486
2487 /* Callback through walk_tree.  Determine if we've got an aggregate
2488    type that we can't support; return non-null if so.  */
2489
2490 static tree
2491 cannot_copy_type_1 (tree *nodep, int *walk_subtrees ATTRIBUTE_UNUSED,
2492                     void *data ATTRIBUTE_UNUSED)
2493 {
2494   tree t, node = *nodep;
2495
2496   if (TREE_CODE (node) == RECORD_TYPE || TREE_CODE (node) == UNION_TYPE)
2497     {
2498       /* We cannot inline a function of the form
2499
2500            void F (int i) { struct S { int ar[i]; } s; }
2501
2502          Attempting to do so produces a catch-22.
2503          If walk_tree examines the TYPE_FIELDS chain of RECORD_TYPE/
2504          UNION_TYPE nodes, then it goes into infinite recursion on a
2505          structure containing a pointer to its own type.  If it doesn't,
2506          then the type node for S doesn't get adjusted properly when
2507          F is inlined. 
2508
2509          ??? This is likely no longer true, but it's too late in the 4.0
2510          cycle to try to find out.  This should be checked for 4.1.  */
2511       for (t = TYPE_FIELDS (node); t; t = TREE_CHAIN (t))
2512         if (variably_modified_type_p (TREE_TYPE (t), NULL))
2513           return node;
2514     }
2515
2516   return NULL_TREE;
2517 }
2518
2519
2520 /* Determine if the function can be copied.  If so return NULL.  If
2521    not return a string describng the reason for failure.  */
2522
2523 static const char *
2524 copy_forbidden (struct function *fun, tree fndecl)
2525 {
2526   const char *reason = fun->cannot_be_copied_reason;
2527   tree step;
2528
2529   /* Only examine the function once.  */
2530   if (fun->cannot_be_copied_set)
2531     return reason;
2532
2533   /* We cannot copy a function that receives a non-local goto
2534      because we cannot remap the destination label used in the
2535      function that is performing the non-local goto.  */
2536   /* ??? Actually, this should be possible, if we work at it.
2537      No doubt there's just a handful of places that simply
2538      assume it doesn't happen and don't substitute properly.  */
2539   if (fun->has_nonlocal_label)
2540     {
2541       reason = G_("function %q+F can never be copied "
2542                   "because it receives a non-local goto");
2543       goto fail;
2544     }
2545
2546   for (step = fun->local_decls; step; step = TREE_CHAIN (step))
2547     {
2548       tree decl = TREE_VALUE (step);
2549
2550       if (TREE_CODE (decl) == VAR_DECL
2551           && TREE_STATIC (decl)
2552           && !DECL_EXTERNAL (decl)
2553           && DECL_INITIAL (decl)
2554           && walk_tree_without_duplicates (&DECL_INITIAL (decl),
2555                                            has_label_address_in_static_1,
2556                                            fndecl))
2557         {
2558           reason = G_("function %q+F can never be copied because it saves "
2559                       "address of local label in a static variable");
2560           goto fail;
2561         }
2562
2563       if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl)
2564           && variably_modified_type_p (TREE_TYPE (decl), NULL)
2565           && walk_tree_without_duplicates (&TREE_TYPE (decl),
2566                                            cannot_copy_type_1, NULL))
2567         {
2568           reason = G_("function %q+F can never be copied "
2569                       "because it uses variable sized variables");
2570           goto fail;
2571         }
2572     }
2573
2574  fail:
2575   fun->cannot_be_copied_reason = reason;
2576   fun->cannot_be_copied_set = true;
2577   return reason;
2578 }
2579
2580
2581 static const char *inline_forbidden_reason;
2582
2583 /* A callback for walk_gimple_seq to handle statements.  Returns non-null
2584    iff a function can not be inlined.  Also sets the reason why. */
2585
2586 static tree
2587 inline_forbidden_p_stmt (gimple_stmt_iterator *gsi, bool *handled_ops_p,
2588                          struct walk_stmt_info *wip)
2589 {
2590   tree fn = (tree) wip->info;
2591   tree t;
2592   gimple stmt = gsi_stmt (*gsi);
2593
2594   switch (gimple_code (stmt))
2595     {
2596     case GIMPLE_CALL:
2597       /* Refuse to inline alloca call unless user explicitly forced so as
2598          this may change program's memory overhead drastically when the
2599          function using alloca is called in loop.  In GCC present in
2600          SPEC2000 inlining into schedule_block cause it to require 2GB of
2601          RAM instead of 256MB.  */
2602       if (gimple_alloca_call_p (stmt)
2603           && !lookup_attribute ("always_inline", DECL_ATTRIBUTES (fn)))
2604         {
2605           inline_forbidden_reason
2606             = G_("function %q+F can never be inlined because it uses "
2607                  "alloca (override using the always_inline attribute)");
2608           *handled_ops_p = true;
2609           return fn;
2610         }
2611
2612       t = gimple_call_fndecl (stmt);
2613       if (t == NULL_TREE)
2614         break;
2615
2616       /* We cannot inline functions that call setjmp.  */
2617       if (setjmp_call_p (t))
2618         {
2619           inline_forbidden_reason
2620             = G_("function %q+F can never be inlined because it uses setjmp");
2621           *handled_ops_p = true;
2622           return t;
2623         }
2624
2625       if (DECL_BUILT_IN_CLASS (t) == BUILT_IN_NORMAL)
2626         switch (DECL_FUNCTION_CODE (t))
2627           {
2628             /* We cannot inline functions that take a variable number of
2629                arguments.  */
2630           case BUILT_IN_VA_START:
2631           case BUILT_IN_NEXT_ARG:
2632           case BUILT_IN_VA_END:
2633             inline_forbidden_reason
2634               = G_("function %q+F can never be inlined because it "
2635                    "uses variable argument lists");
2636             *handled_ops_p = true;
2637             return t;
2638
2639           case BUILT_IN_LONGJMP:
2640             /* We can't inline functions that call __builtin_longjmp at
2641                all.  The non-local goto machinery really requires the
2642                destination be in a different function.  If we allow the
2643                function calling __builtin_longjmp to be inlined into the
2644                function calling __builtin_setjmp, Things will Go Awry.  */
2645             inline_forbidden_reason
2646               = G_("function %q+F can never be inlined because "
2647                    "it uses setjmp-longjmp exception handling");
2648             *handled_ops_p = true;
2649             return t;
2650
2651           case BUILT_IN_NONLOCAL_GOTO:
2652             /* Similarly.  */
2653             inline_forbidden_reason
2654               = G_("function %q+F can never be inlined because "
2655                    "it uses non-local goto");
2656             *handled_ops_p = true;
2657             return t;
2658
2659           case BUILT_IN_RETURN:
2660           case BUILT_IN_APPLY_ARGS:
2661             /* If a __builtin_apply_args caller would be inlined,
2662                it would be saving arguments of the function it has
2663                been inlined into.  Similarly __builtin_return would
2664                return from the function the inline has been inlined into.  */
2665             inline_forbidden_reason
2666               = G_("function %q+F can never be inlined because "
2667                    "it uses __builtin_return or __builtin_apply_args");
2668             *handled_ops_p = true;
2669             return t;
2670
2671           default:
2672             break;
2673           }
2674       break;
2675
2676     case GIMPLE_GOTO:
2677       t = gimple_goto_dest (stmt);
2678
2679       /* We will not inline a function which uses computed goto.  The
2680          addresses of its local labels, which may be tucked into
2681          global storage, are of course not constant across
2682          instantiations, which causes unexpected behavior.  */
2683       if (TREE_CODE (t) != LABEL_DECL)
2684         {
2685           inline_forbidden_reason
2686             = G_("function %q+F can never be inlined "
2687                  "because it contains a computed goto");
2688           *handled_ops_p = true;
2689           return t;
2690         }
2691       break;
2692
2693     default:
2694       break;
2695     }
2696
2697   *handled_ops_p = false;
2698   return NULL_TREE;
2699 }
2700
2701 /* Return true if FNDECL is a function that cannot be inlined into
2702    another one.  */
2703
2704 static bool
2705 inline_forbidden_p (tree fndecl)
2706 {
2707   struct function *fun = DECL_STRUCT_FUNCTION (fndecl);
2708   struct walk_stmt_info wi;
2709   struct pointer_set_t *visited_nodes;
2710   basic_block bb;
2711   bool forbidden_p = false;
2712
2713   /* First check for shared reasons not to copy the code.  */
2714   inline_forbidden_reason = copy_forbidden (fun, fndecl);
2715   if (inline_forbidden_reason != NULL)
2716     return true;
2717
2718   /* Next, walk the statements of the function looking for
2719      constraucts we can't handle, or are non-optimal for inlining.  */
2720   visited_nodes = pointer_set_create ();
2721   memset (&wi, 0, sizeof (wi));
2722   wi.info = (void *) fndecl;
2723   wi.pset = visited_nodes;
2724
2725   FOR_EACH_BB_FN (bb, fun)
2726     {
2727       gimple ret;
2728       gimple_seq seq = bb_seq (bb);
2729       ret = walk_gimple_seq (seq, inline_forbidden_p_stmt, NULL, &wi);
2730       forbidden_p = (ret != NULL);
2731       if (forbidden_p)
2732         break;
2733     }
2734
2735   pointer_set_destroy (visited_nodes);
2736   return forbidden_p;
2737 }
2738
2739 /* Returns nonzero if FN is a function that does not have any
2740    fundamental inline blocking properties.  */
2741
2742 bool
2743 tree_inlinable_function_p (tree fn)
2744 {
2745   bool inlinable = true;
2746   bool do_warning;
2747   tree always_inline;
2748
2749   /* If we've already decided this function shouldn't be inlined,
2750      there's no need to check again.  */
2751   if (DECL_UNINLINABLE (fn))
2752     return false;
2753
2754   /* We only warn for functions declared `inline' by the user.  */
2755   do_warning = (warn_inline
2756                 && DECL_DECLARED_INLINE_P (fn)
2757                 && !DECL_NO_INLINE_WARNING_P (fn)
2758                 && !DECL_IN_SYSTEM_HEADER (fn));
2759
2760   always_inline = lookup_attribute ("always_inline", DECL_ATTRIBUTES (fn));
2761
2762   if (flag_no_inline
2763       && always_inline == NULL)
2764     {
2765       if (do_warning)
2766         warning (OPT_Winline, "function %q+F can never be inlined because it "
2767                  "is suppressed using -fno-inline", fn);
2768       inlinable = false;
2769     }
2770
2771   /* Don't auto-inline anything that might not be bound within
2772      this unit of translation.  */
2773   else if (!DECL_DECLARED_INLINE_P (fn)
2774            && DECL_REPLACEABLE_P (fn))
2775     inlinable = false;
2776
2777   else if (!function_attribute_inlinable_p (fn))
2778     {
2779       if (do_warning)
2780         warning (OPT_Winline, "function %q+F can never be inlined because it "
2781                  "uses attributes conflicting with inlining", fn);
2782       inlinable = false;
2783     }
2784
2785   else if (inline_forbidden_p (fn))
2786     {
2787       /* See if we should warn about uninlinable functions.  Previously,
2788          some of these warnings would be issued while trying to expand
2789          the function inline, but that would cause multiple warnings
2790          about functions that would for example call alloca.  But since
2791          this a property of the function, just one warning is enough.
2792          As a bonus we can now give more details about the reason why a
2793          function is not inlinable.  */
2794       if (always_inline)
2795         sorry (inline_forbidden_reason, fn);
2796       else if (do_warning)
2797         warning (OPT_Winline, inline_forbidden_reason, fn);
2798
2799       inlinable = false;
2800     }
2801
2802   /* Squirrel away the result so that we don't have to check again.  */
2803   DECL_UNINLINABLE (fn) = !inlinable;
2804
2805   return inlinable;
2806 }
2807
2808 /* Estimate the cost of a memory move.  Use machine dependent
2809    word size and take possible memcpy call into account.  */
2810
2811 int
2812 estimate_move_cost (tree type)
2813 {
2814   HOST_WIDE_INT size;
2815
2816   gcc_assert (!VOID_TYPE_P (type));
2817
2818   size = int_size_in_bytes (type);
2819
2820   if (size < 0 || size > MOVE_MAX_PIECES * MOVE_RATIO (!optimize_size))
2821     /* Cost of a memcpy call, 3 arguments and the call.  */
2822     return 4;
2823   else
2824     return ((size + MOVE_MAX_PIECES - 1) / MOVE_MAX_PIECES);
2825 }
2826
2827 /* Returns cost of operation CODE, according to WEIGHTS  */
2828
2829 static int
2830 estimate_operator_cost (enum tree_code code, eni_weights *weights,
2831                         tree op1 ATTRIBUTE_UNUSED, tree op2)
2832 {
2833   switch (code)
2834     {
2835     /* These are "free" conversions, or their presumed cost
2836        is folded into other operations.  */
2837     case RANGE_EXPR:
2838     CASE_CONVERT:
2839     case COMPLEX_EXPR:
2840     case PAREN_EXPR:
2841       return 0;
2842
2843     /* Assign cost of 1 to usual operations.
2844        ??? We may consider mapping RTL costs to this.  */
2845     case COND_EXPR:
2846     case VEC_COND_EXPR:
2847
2848     case PLUS_EXPR:
2849     case POINTER_PLUS_EXPR:
2850     case MINUS_EXPR:
2851     case MULT_EXPR:
2852
2853     case FIXED_CONVERT_EXPR:
2854     case FIX_TRUNC_EXPR:
2855
2856     case NEGATE_EXPR:
2857     case FLOAT_EXPR:
2858     case MIN_EXPR:
2859     case MAX_EXPR:
2860     case ABS_EXPR:
2861
2862     case LSHIFT_EXPR:
2863     case RSHIFT_EXPR:
2864     case LROTATE_EXPR:
2865     case RROTATE_EXPR:
2866     case VEC_LSHIFT_EXPR:
2867     case VEC_RSHIFT_EXPR:
2868
2869     case BIT_IOR_EXPR:
2870     case BIT_XOR_EXPR:
2871     case BIT_AND_EXPR:
2872     case BIT_NOT_EXPR:
2873
2874     case TRUTH_ANDIF_EXPR:
2875     case TRUTH_ORIF_EXPR:
2876     case TRUTH_AND_EXPR:
2877     case TRUTH_OR_EXPR:
2878     case TRUTH_XOR_EXPR:
2879     case TRUTH_NOT_EXPR:
2880
2881     case LT_EXPR:
2882     case LE_EXPR:
2883     case GT_EXPR:
2884     case GE_EXPR:
2885     case EQ_EXPR:
2886     case NE_EXPR:
2887     case ORDERED_EXPR:
2888     case UNORDERED_EXPR:
2889
2890     case UNLT_EXPR:
2891     case UNLE_EXPR:
2892     case UNGT_EXPR:
2893     case UNGE_EXPR:
2894     case UNEQ_EXPR:
2895     case LTGT_EXPR:
2896
2897     case CONJ_EXPR:
2898
2899     case PREDECREMENT_EXPR:
2900     case PREINCREMENT_EXPR:
2901     case POSTDECREMENT_EXPR:
2902     case POSTINCREMENT_EXPR:
2903
2904     case REALIGN_LOAD_EXPR:
2905
2906     case REDUC_MAX_EXPR:
2907     case REDUC_MIN_EXPR:
2908     case REDUC_PLUS_EXPR:
2909     case WIDEN_SUM_EXPR:
2910     case WIDEN_MULT_EXPR:
2911     case DOT_PROD_EXPR:
2912
2913     case VEC_WIDEN_MULT_HI_EXPR:
2914     case VEC_WIDEN_MULT_LO_EXPR:
2915     case VEC_UNPACK_HI_EXPR:
2916     case VEC_UNPACK_LO_EXPR:
2917     case VEC_UNPACK_FLOAT_HI_EXPR:
2918     case VEC_UNPACK_FLOAT_LO_EXPR:
2919     case VEC_PACK_TRUNC_EXPR:
2920     case VEC_PACK_SAT_EXPR:
2921     case VEC_PACK_FIX_TRUNC_EXPR:
2922     case VEC_EXTRACT_EVEN_EXPR:
2923     case VEC_EXTRACT_ODD_EXPR:
2924     case VEC_INTERLEAVE_HIGH_EXPR:
2925     case VEC_INTERLEAVE_LOW_EXPR:
2926
2927       return 1;
2928
2929     /* Few special cases of expensive operations.  This is useful
2930        to avoid inlining on functions having too many of these.  */
2931     case TRUNC_DIV_EXPR:
2932     case CEIL_DIV_EXPR:
2933     case FLOOR_DIV_EXPR:
2934     case ROUND_DIV_EXPR:
2935     case EXACT_DIV_EXPR:
2936     case TRUNC_MOD_EXPR:
2937     case CEIL_MOD_EXPR:
2938     case FLOOR_MOD_EXPR:
2939     case ROUND_MOD_EXPR:
2940     case RDIV_EXPR:
2941       if (TREE_CODE (op2) != INTEGER_CST)
2942         return weights->div_mod_cost;
2943       return 1;
2944
2945     default:
2946       /* We expect a copy assignment with no operator.  */
2947       gcc_assert (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS);
2948       return 0;
2949     }
2950 }
2951
2952
2953 /* Estimate number of instructions that will be created by expanding
2954    the statements in the statement sequence STMTS.
2955    WEIGHTS contains weights attributed to various constructs.  */
2956
2957 static
2958 int estimate_num_insns_seq (gimple_seq stmts, eni_weights *weights)
2959 {
2960   int cost;
2961   gimple_stmt_iterator gsi;
2962
2963   cost = 0;
2964   for (gsi = gsi_start (stmts); !gsi_end_p (gsi); gsi_next (&gsi))
2965     cost += estimate_num_insns (gsi_stmt (gsi), weights);
2966
2967   return cost;
2968 }
2969
2970
2971 /* Estimate number of instructions that will be created by expanding STMT.
2972    WEIGHTS contains weights attributed to various constructs.  */
2973
2974 int
2975 estimate_num_insns (gimple stmt, eni_weights *weights)
2976 {
2977   unsigned cost, i;
2978   enum gimple_code code = gimple_code (stmt);
2979   tree lhs;
2980   tree rhs;
2981
2982   switch (code)
2983     {
2984     case GIMPLE_ASSIGN:
2985       /* Try to estimate the cost of assignments.  We have three cases to
2986          deal with:
2987          1) Simple assignments to registers;
2988          2) Stores to things that must live in memory.  This includes
2989             "normal" stores to scalars, but also assignments of large
2990             structures, or constructors of big arrays;
2991
2992          Let us look at the first two cases, assuming we have "a = b + C":
2993          <GIMPLE_ASSIGN <var_decl "a">
2994                 <plus_expr <var_decl "b"> <constant C>>
2995          If "a" is a GIMPLE register, the assignment to it is free on almost
2996          any target, because "a" usually ends up in a real register.  Hence
2997          the only cost of this expression comes from the PLUS_EXPR, and we
2998          can ignore the GIMPLE_ASSIGN.
2999          If "a" is not a GIMPLE register, the assignment to "a" will most
3000          likely be a real store, so the cost of the GIMPLE_ASSIGN is the cost
3001          of moving something into "a", which we compute using the function
3002          estimate_move_cost.  */
3003       lhs = gimple_assign_lhs (stmt);
3004       rhs = gimple_assign_rhs1 (stmt);
3005
3006       /* EH magic stuff is most probably going to be optimized out.
3007          We rarely really need to save EH info for unwinding
3008          nested exceptions.  */
3009       if (TREE_CODE (lhs) == FILTER_EXPR
3010           || TREE_CODE (lhs) == EXC_PTR_EXPR
3011           || TREE_CODE (rhs) == FILTER_EXPR
3012           || TREE_CODE (rhs) == EXC_PTR_EXPR)
3013         return 0;
3014       if (is_gimple_reg (lhs))
3015         cost = 0;
3016       else
3017         cost = estimate_move_cost (TREE_TYPE (lhs));
3018
3019       if (!is_gimple_reg (rhs) && !is_gimple_min_invariant (rhs))
3020         cost += estimate_move_cost (TREE_TYPE (rhs));
3021
3022       cost += estimate_operator_cost (gimple_assign_rhs_code (stmt), weights,
3023                                       gimple_assign_rhs1 (stmt),
3024                                       get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
3025                                       == GIMPLE_BINARY_RHS
3026                                       ? gimple_assign_rhs2 (stmt) : NULL);
3027       break;
3028
3029     case GIMPLE_COND:
3030       cost = 1 + estimate_operator_cost (gimple_cond_code (stmt), weights,
3031                                          gimple_op (stmt, 0),
3032                                          gimple_op (stmt, 1));
3033       break;
3034
3035     case GIMPLE_SWITCH:
3036       /* Take into account cost of the switch + guess 2 conditional jumps for
3037          each case label.  
3038
3039          TODO: once the switch expansion logic is sufficiently separated, we can
3040          do better job on estimating cost of the switch.  */
3041       if (weights->time_based)
3042         cost = floor_log2 (gimple_switch_num_labels (stmt)) * 2;
3043       else
3044         cost = gimple_switch_num_labels (stmt) * 2;
3045       break;
3046
3047     case GIMPLE_CALL:
3048       {
3049         tree decl = gimple_call_fndecl (stmt);
3050         tree addr = gimple_call_fn (stmt);
3051         tree funtype = TREE_TYPE (addr);
3052
3053         if (POINTER_TYPE_P (funtype))
3054           funtype = TREE_TYPE (funtype);
3055
3056         if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
3057           cost = weights->target_builtin_call_cost;
3058         else
3059           cost = weights->call_cost;
3060         
3061         if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
3062           switch (DECL_FUNCTION_CODE (decl))
3063             {
3064             case BUILT_IN_CONSTANT_P:
3065               return 0;
3066             case BUILT_IN_EXPECT:
3067               return 0;
3068
3069             /* Prefetch instruction is not expensive.  */
3070             case BUILT_IN_PREFETCH:
3071               cost = weights->target_builtin_call_cost;
3072               break;
3073
3074             default:
3075               break;
3076             }
3077
3078         if (decl)
3079           funtype = TREE_TYPE (decl);
3080
3081         if (!VOID_TYPE_P (TREE_TYPE (funtype)))
3082           cost += estimate_move_cost (TREE_TYPE (funtype));
3083         /* Our cost must be kept in sync with
3084            cgraph_estimate_size_after_inlining that does use function
3085            declaration to figure out the arguments.  */
3086         if (decl && DECL_ARGUMENTS (decl))
3087           {
3088             tree arg;
3089             for (arg = DECL_ARGUMENTS (decl); arg; arg = TREE_CHAIN (arg))
3090               if (!VOID_TYPE_P (TREE_TYPE (arg)))
3091                 cost += estimate_move_cost (TREE_TYPE (arg));
3092           }
3093         else if (funtype && prototype_p (funtype))
3094           {
3095             tree t;
3096             for (t = TYPE_ARG_TYPES (funtype); t && t != void_list_node;
3097                  t = TREE_CHAIN (t))
3098               if (!VOID_TYPE_P (TREE_VALUE (t)))
3099                 cost += estimate_move_cost (TREE_VALUE (t));
3100           }
3101         else
3102           {
3103             for (i = 0; i < gimple_call_num_args (stmt); i++)
3104               {
3105                 tree arg = gimple_call_arg (stmt, i);
3106                 if (!VOID_TYPE_P (TREE_TYPE (arg)))
3107                   cost += estimate_move_cost (TREE_TYPE (arg));
3108               }
3109           }
3110
3111         break;
3112       }
3113
3114     case GIMPLE_GOTO:
3115     case GIMPLE_LABEL:
3116     case GIMPLE_NOP:
3117     case GIMPLE_PHI:
3118     case GIMPLE_RETURN:
3119     case GIMPLE_PREDICT:
3120       return 0;
3121
3122     case GIMPLE_ASM:
3123     case GIMPLE_RESX:
3124       return 1;
3125
3126     case GIMPLE_BIND:
3127       return estimate_num_insns_seq (gimple_bind_body (stmt), weights);
3128
3129     case GIMPLE_EH_FILTER:
3130       return estimate_num_insns_seq (gimple_eh_filter_failure (stmt), weights);
3131
3132     case GIMPLE_CATCH:
3133       return estimate_num_insns_seq (gimple_catch_handler (stmt), weights);
3134
3135     case GIMPLE_TRY:
3136       return (estimate_num_insns_seq (gimple_try_eval (stmt), weights)
3137               + estimate_num_insns_seq (gimple_try_cleanup (stmt), weights));
3138
3139     /* OpenMP directives are generally very expensive.  */
3140
3141     case GIMPLE_OMP_RETURN:
3142     case GIMPLE_OMP_SECTIONS_SWITCH:
3143     case GIMPLE_OMP_ATOMIC_STORE:
3144     case GIMPLE_OMP_CONTINUE:
3145       /* ...except these, which are cheap.  */
3146       return 0;
3147
3148     case GIMPLE_OMP_ATOMIC_LOAD:
3149       return weights->omp_cost;
3150
3151     case GIMPLE_OMP_FOR:
3152       return (weights->omp_cost
3153               + estimate_num_insns_seq (gimple_omp_body (stmt), weights)
3154               + estimate_num_insns_seq (gimple_omp_for_pre_body (stmt), weights));
3155
3156     case GIMPLE_OMP_PARALLEL:
3157     case GIMPLE_OMP_TASK:
3158     case GIMPLE_OMP_CRITICAL:
3159     case GIMPLE_OMP_MASTER:
3160     case GIMPLE_OMP_ORDERED:
3161     case GIMPLE_OMP_SECTION:
3162     case GIMPLE_OMP_SECTIONS:
3163     case GIMPLE_OMP_SINGLE:
3164       return (weights->omp_cost
3165               + estimate_num_insns_seq (gimple_omp_body (stmt), weights));
3166
3167     default:
3168       gcc_unreachable ();
3169     }
3170
3171   return cost;
3172 }
3173
3174 /* Estimate number of instructions that will be created by expanding
3175    function FNDECL.  WEIGHTS contains weights attributed to various
3176    constructs.  */
3177
3178 int
3179 estimate_num_insns_fn (tree fndecl, eni_weights *weights)
3180 {
3181   struct function *my_function = DECL_STRUCT_FUNCTION (fndecl);
3182   gimple_stmt_iterator bsi;
3183   basic_block bb;
3184   int n = 0;
3185
3186   gcc_assert (my_function && my_function->cfg);
3187   FOR_EACH_BB_FN (bb, my_function)
3188     {
3189       for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
3190         n += estimate_num_insns (gsi_stmt (bsi), weights);
3191     }
3192
3193   return n;
3194 }
3195
3196
3197 /* Initializes weights used by estimate_num_insns.  */
3198
3199 void
3200 init_inline_once (void)
3201 {
3202   eni_size_weights.call_cost = 1;
3203   eni_size_weights.target_builtin_call_cost = 1;
3204   eni_size_weights.div_mod_cost = 1;
3205   eni_size_weights.omp_cost = 40;
3206   eni_size_weights.time_based = false;
3207
3208   /* Estimating time for call is difficult, since we have no idea what the
3209      called function does.  In the current uses of eni_time_weights,
3210      underestimating the cost does less harm than overestimating it, so
3211      we choose a rather small value here.  */
3212   eni_time_weights.call_cost = 10;
3213   eni_time_weights.target_builtin_call_cost = 10;
3214   eni_time_weights.div_mod_cost = 10;
3215   eni_time_weights.omp_cost = 40;
3216   eni_time_weights.time_based = true;
3217 }
3218
3219 /* Estimate the number of instructions in a gimple_seq. */
3220
3221 int
3222 count_insns_seq (gimple_seq seq, eni_weights *weights)
3223 {
3224   gimple_stmt_iterator gsi;
3225   int n = 0;
3226   for (gsi = gsi_start (seq); !gsi_end_p (gsi); gsi_next (&gsi))
3227     n += estimate_num_insns (gsi_stmt (gsi), weights);
3228
3229   return n;
3230 }
3231
3232
3233 /* Install new lexical TREE_BLOCK underneath 'current_block'.  */
3234
3235 static void
3236 prepend_lexical_block (tree current_block, tree new_block)
3237 {
3238   BLOCK_CHAIN (new_block) = BLOCK_SUBBLOCKS (current_block);
3239   BLOCK_SUBBLOCKS (current_block) = new_block;
3240   BLOCK_SUPERCONTEXT (new_block) = current_block;
3241 }
3242
3243 /* Fetch callee declaration from the call graph edge going from NODE and
3244    associated with STMR call statement.  Return NULL_TREE if not found.  */
3245 static tree
3246 get_indirect_callee_fndecl (struct cgraph_node *node, gimple stmt)
3247 {
3248   struct cgraph_edge *cs;
3249
3250   cs = cgraph_edge (node, stmt);
3251   if (cs)
3252     return cs->callee->decl;
3253
3254   return NULL_TREE;
3255 }
3256
3257 /* If STMT is a GIMPLE_CALL, replace it with its inline expansion.  */
3258
3259 static bool
3260 expand_call_inline (basic_block bb, gimple stmt, copy_body_data *id)
3261 {
3262   tree retvar, use_retvar;
3263   tree fn;
3264   struct pointer_map_t *st;
3265   tree return_slot;
3266   tree modify_dest;
3267   location_t saved_location;
3268   struct cgraph_edge *cg_edge;
3269   cgraph_inline_failed_t reason;
3270   basic_block return_block;
3271   edge e;
3272   gimple_stmt_iterator gsi, stmt_gsi;
3273   bool successfully_inlined = FALSE;
3274   bool purge_dead_abnormal_edges;
3275   tree t_step;
3276   tree var;
3277
3278   /* Set input_location here so we get the right instantiation context
3279      if we call instantiate_decl from inlinable_function_p.  */
3280   saved_location = input_location;
3281   if (gimple_has_location (stmt))
3282     input_location = gimple_location (stmt);
3283
3284   /* From here on, we're only interested in CALL_EXPRs.  */
3285   if (gimple_code (stmt) != GIMPLE_CALL)
3286     goto egress;
3287
3288   /* First, see if we can figure out what function is being called.
3289      If we cannot, then there is no hope of inlining the function.  */
3290   fn = gimple_call_fndecl (stmt);
3291   if (!fn)
3292     {
3293       fn = get_indirect_callee_fndecl (id->dst_node, stmt);
3294       if (!fn)
3295         goto egress;
3296     }
3297
3298   /* Turn forward declarations into real ones.  */
3299   fn = cgraph_node (fn)->decl;
3300
3301   /* If FN is a declaration of a function in a nested scope that was
3302      globally declared inline, we don't set its DECL_INITIAL.
3303      However, we can't blindly follow DECL_ABSTRACT_ORIGIN because the
3304      C++ front-end uses it for cdtors to refer to their internal
3305      declarations, that are not real functions.  Fortunately those
3306      don't have trees to be saved, so we can tell by checking their
3307      gimple_body.  */
3308   if (!DECL_INITIAL (fn)
3309       && DECL_ABSTRACT_ORIGIN (fn)
3310       && gimple_has_body_p (DECL_ABSTRACT_ORIGIN (fn)))
3311     fn = DECL_ABSTRACT_ORIGIN (fn);
3312
3313   /* Objective C and fortran still calls tree_rest_of_compilation directly.
3314      Kill this check once this is fixed.  */
3315   if (!id->dst_node->analyzed)
3316     goto egress;
3317
3318   cg_edge = cgraph_edge (id->dst_node, stmt);
3319
3320   /* Don't try to inline functions that are not well-suited to
3321      inlining.  */
3322   if (!cgraph_inline_p (cg_edge, &reason))
3323     {
3324       /* If this call was originally indirect, we do not want to emit any
3325          inlining related warnings or sorry messages because there are no
3326          guarantees regarding those.  */
3327       if (cg_edge->indirect_call)
3328         goto egress;
3329
3330       if (lookup_attribute ("always_inline", DECL_ATTRIBUTES (fn))
3331           /* Avoid warnings during early inline pass. */
3332           && cgraph_global_info_ready)
3333         {
3334           sorry ("inlining failed in call to %q+F: %s", fn,
3335                  cgraph_inline_failed_string (reason));
3336           sorry ("called from here");
3337         }
3338       else if (warn_inline && DECL_DECLARED_INLINE_P (fn)
3339                && !DECL_IN_SYSTEM_HEADER (fn)
3340                && reason != CIF_UNSPECIFIED
3341                && !lookup_attribute ("noinline", DECL_ATTRIBUTES (fn))
3342                /* Avoid warnings during early inline pass. */
3343                && cgraph_global_info_ready)
3344         {
3345           warning (OPT_Winline, "inlining failed in call to %q+F: %s",
3346                    fn, cgraph_inline_failed_string (reason));
3347           warning (OPT_Winline, "called from here");
3348         }
3349       goto egress;
3350     }
3351   fn = cg_edge->callee->decl;
3352
3353 #ifdef ENABLE_CHECKING
3354   if (cg_edge->callee->decl != id->dst_node->decl)
3355     verify_cgraph_node (cg_edge->callee);
3356 #endif
3357
3358   /* We will be inlining this callee.  */
3359   id->eh_region = lookup_stmt_eh_region (stmt);
3360
3361   /* Split the block holding the GIMPLE_CALL.  */
3362   e = split_block (bb, stmt);
3363   bb = e->src;
3364   return_block = e->dest;
3365   remove_edge (e);
3366
3367   /* split_block splits after the statement; work around this by
3368      moving the call into the second block manually.  Not pretty,
3369      but seems easier than doing the CFG manipulation by hand
3370      when the GIMPLE_CALL is in the last statement of BB.  */
3371   stmt_gsi = gsi_last_bb (bb);
3372   gsi_remove (&stmt_gsi, false);
3373
3374   /* If the GIMPLE_CALL was in the last statement of BB, it may have
3375      been the source of abnormal edges.  In this case, schedule
3376      the removal of dead abnormal edges.  */
3377   gsi = gsi_start_bb (return_block);
3378   if (gsi_end_p (gsi))
3379     {
3380       gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
3381       purge_dead_abnormal_edges = true;
3382     }
3383   else
3384     {
3385       gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
3386       purge_dead_abnormal_edges = false;
3387     }
3388
3389   stmt_gsi = gsi_start_bb (return_block);
3390
3391   /* Build a block containing code to initialize the arguments, the
3392      actual inline expansion of the body, and a label for the return
3393      statements within the function to jump to.  The type of the
3394      statement expression is the return type of the function call.  */
3395   id->block = make_node (BLOCK);
3396   BLOCK_ABSTRACT_ORIGIN (id->block) = fn;
3397   BLOCK_SOURCE_LOCATION (id->block) = input_location;
3398   prepend_lexical_block (gimple_block (stmt), id->block);
3399
3400   /* Local declarations will be replaced by their equivalents in this
3401      map.  */
3402   st = id->decl_map;
3403   id->decl_map = pointer_map_create ();
3404
3405   /* Record the function we are about to inline.  */
3406   id->src_fn = fn;
3407   id->src_node = cg_edge->callee;
3408   id->src_cfun = DECL_STRUCT_FUNCTION (fn);
3409   id->gimple_call = stmt;
3410
3411   gcc_assert (!id->src_cfun->after_inlining);
3412
3413   id->entry_bb = bb;
3414   if (lookup_attribute ("cold", DECL_ATTRIBUTES (fn)))
3415     {
3416       gimple_stmt_iterator si = gsi_last_bb (bb);
3417       gsi_insert_after (&si, gimple_build_predict (PRED_COLD_FUNCTION,
3418                                                    NOT_TAKEN),
3419                         GSI_NEW_STMT);
3420     }
3421   initialize_inlined_parameters (id, stmt, fn, bb);
3422
3423   if (DECL_INITIAL (fn))
3424     prepend_lexical_block (id->block, remap_blocks (DECL_INITIAL (fn), id));
3425
3426   /* Return statements in the function body will be replaced by jumps
3427      to the RET_LABEL.  */
3428   gcc_assert (DECL_INITIAL (fn));
3429   gcc_assert (TREE_CODE (DECL_INITIAL (fn)) == BLOCK);
3430
3431   /* Find the LHS to which the result of this call is assigned.  */
3432   return_slot = NULL;
3433   if (gimple_call_lhs (stmt))
3434     {
3435       modify_dest = gimple_call_lhs (stmt);
3436
3437       /* The function which we are inlining might not return a value,
3438          in which case we should issue a warning that the function
3439          does not return a value.  In that case the optimizers will
3440          see that the variable to which the value is assigned was not
3441          initialized.  We do not want to issue a warning about that
3442          uninitialized variable.  */
3443       if (DECL_P (modify_dest))
3444         TREE_NO_WARNING (modify_dest) = 1;
3445
3446       if (gimple_call_return_slot_opt_p (stmt))
3447         {
3448           return_slot = modify_dest;
3449           modify_dest = NULL;
3450         }
3451     }
3452   else
3453     modify_dest = NULL;
3454
3455   /* If we are inlining a call to the C++ operator new, we don't want
3456      to use type based alias analysis on the return value.  Otherwise
3457      we may get confused if the compiler sees that the inlined new
3458      function returns a pointer which was just deleted.  See bug
3459      33407.  */
3460   if (DECL_IS_OPERATOR_NEW (fn))
3461     {
3462       return_slot = NULL;
3463       modify_dest = NULL;
3464     }
3465
3466   /* Declare the return variable for the function.  */
3467   retvar = declare_return_variable (id, return_slot, modify_dest, &use_retvar);
3468
3469   /* Add local vars in this inlined callee to caller.  */
3470   t_step = id->src_cfun->local_decls;
3471   for (; t_step; t_step = TREE_CHAIN (t_step))
3472     {
3473       var = TREE_VALUE (t_step);
3474       if (TREE_STATIC (var) && !TREE_ASM_WRITTEN (var))
3475         {
3476           if (var_ann (var) && add_referenced_var (var))
3477             cfun->local_decls = tree_cons (NULL_TREE, var,
3478                                            cfun->local_decls);
3479         }
3480       else if (!can_be_nonlocal (var, id))
3481         cfun->local_decls = tree_cons (NULL_TREE, remap_decl (var, id),
3482                                        cfun->local_decls);
3483     }
3484
3485   /* This is it.  Duplicate the callee body.  Assume callee is
3486      pre-gimplified.  Note that we must not alter the caller
3487      function in any way before this point, as this CALL_EXPR may be
3488      a self-referential call; if we're calling ourselves, we need to
3489      duplicate our body before altering anything.  */
3490   copy_body (id, bb->count, bb->frequency, bb, return_block);
3491
3492   /* Reset the escaped and callused solutions.  */
3493   if (cfun->gimple_df)
3494     {
3495       pt_solution_reset (&cfun->gimple_df->escaped);
3496       pt_solution_reset (&cfun->gimple_df->callused);
3497     }
3498
3499   /* Clean up.  */
3500   pointer_map_destroy (id->decl_map);
3501   id->decl_map = st;
3502
3503   /* Unlink the calls virtual operands before replacing it.  */
3504   unlink_stmt_vdef (stmt);
3505
3506   /* If the inlined function returns a result that we care about,
3507      substitute the GIMPLE_CALL with an assignment of the return
3508      variable to the LHS of the call.  That is, if STMT was
3509      'a = foo (...)', substitute the call with 'a = USE_RETVAR'.  */
3510   if (use_retvar && gimple_call_lhs (stmt))
3511     {
3512       gimple old_stmt = stmt;
3513       stmt = gimple_build_assign (gimple_call_lhs (stmt), use_retvar);
3514       gsi_replace (&stmt_gsi, stmt, false);
3515       if (gimple_in_ssa_p (cfun))
3516         mark_symbols_for_renaming (stmt);
3517       maybe_clean_or_replace_eh_stmt (old_stmt, stmt);
3518     }
3519   else
3520     {
3521       /* Handle the case of inlining a function with no return
3522          statement, which causes the return value to become undefined.  */
3523       if (gimple_call_lhs (stmt)
3524           && TREE_CODE (gimple_call_lhs (stmt)) == SSA_NAME)
3525         {
3526           tree name = gimple_call_lhs (stmt);
3527           tree var = SSA_NAME_VAR (name);
3528           tree def = gimple_default_def (cfun, var);
3529
3530           if (def)
3531             {
3532               /* If the variable is used undefined, make this name
3533                  undefined via a move.  */
3534               stmt = gimple_build_assign (gimple_call_lhs (stmt), def);
3535               gsi_replace (&stmt_gsi, stmt, true);
3536             }
3537           else
3538             {
3539               /* Otherwise make this variable undefined.  */
3540               gsi_remove (&stmt_gsi, true);
3541               set_default_def (var, name);
3542               SSA_NAME_DEF_STMT (name) = gimple_build_nop ();
3543             }
3544         }
3545       else
3546         gsi_remove (&stmt_gsi, true);
3547     }
3548
3549   if (purge_dead_abnormal_edges)
3550     gimple_purge_dead_abnormal_call_edges (return_block);
3551
3552   /* If the value of the new expression is ignored, that's OK.  We
3553      don't warn about this for CALL_EXPRs, so we shouldn't warn about
3554      the equivalent inlined version either.  */
3555   if (is_gimple_assign (stmt))
3556     {
3557       gcc_assert (gimple_assign_single_p (stmt)
3558                   || CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt)));
3559       TREE_USED (gimple_assign_rhs1 (stmt)) = 1;
3560     }
3561
3562   /* Output the inlining info for this abstract function, since it has been
3563      inlined.  If we don't do this now, we can lose the information about the
3564      variables in the function when the blocks get blown away as soon as we
3565      remove the cgraph node.  */
3566   (*debug_hooks->outlining_inline_function) (cg_edge->callee->decl);
3567
3568   /* Update callgraph if needed.  */
3569   cgraph_remove_node (cg_edge->callee);
3570
3571   id->block = NULL_TREE;
3572   successfully_inlined = TRUE;
3573
3574  egress:
3575   input_location = saved_location;
3576   return successfully_inlined;
3577 }
3578
3579 /* Expand call statements reachable from STMT_P.
3580    We can only have CALL_EXPRs as the "toplevel" tree code or nested
3581    in a MODIFY_EXPR.  See tree-gimple.c:get_call_expr_in().  We can
3582    unfortunately not use that function here because we need a pointer
3583    to the CALL_EXPR, not the tree itself.  */
3584
3585 static bool
3586 gimple_expand_calls_inline (basic_block bb, copy_body_data *id)
3587 {
3588   gimple_stmt_iterator gsi;
3589
3590   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3591     {
3592       gimple stmt = gsi_stmt (gsi);
3593
3594       if (is_gimple_call (stmt)
3595           && expand_call_inline (bb, stmt, id))
3596         return true;
3597     }
3598
3599   return false;
3600 }
3601
3602
3603 /* Walk all basic blocks created after FIRST and try to fold every statement
3604    in the STATEMENTS pointer set.  */
3605
3606 static void
3607 fold_marked_statements (int first, struct pointer_set_t *statements)
3608 {
3609   for (; first < n_basic_blocks; first++)
3610     if (BASIC_BLOCK (first))
3611       {
3612         gimple_stmt_iterator gsi;
3613
3614         for (gsi = gsi_start_bb (BASIC_BLOCK (first));
3615              !gsi_end_p (gsi);
3616              gsi_next (&gsi))
3617           if (pointer_set_contains (statements, gsi_stmt (gsi)))
3618             {
3619               gimple old_stmt = gsi_stmt (gsi);
3620               tree old_decl = is_gimple_call (old_stmt) ? gimple_call_fndecl (old_stmt) : 0;
3621
3622               if (fold_stmt (&gsi))
3623                 {
3624                   /* Re-read the statement from GSI as fold_stmt() may
3625                      have changed it.  */
3626                   gimple new_stmt = gsi_stmt (gsi);
3627                   update_stmt (new_stmt);
3628
3629                   if (is_gimple_call (old_stmt)
3630                       || is_gimple_call (new_stmt))
3631                     cgraph_update_edges_for_call_stmt (old_stmt, old_decl, new_stmt);
3632
3633                   if (maybe_clean_or_replace_eh_stmt (old_stmt, new_stmt))
3634                     gimple_purge_dead_eh_edges (BASIC_BLOCK (first));
3635                 }
3636             }
3637       }
3638 }
3639
3640 /* Return true if BB has at least one abnormal outgoing edge.  */
3641
3642 static inline bool
3643 has_abnormal_outgoing_edge_p (basic_block bb)
3644 {
3645   edge e;
3646   edge_iterator ei;
3647
3648   FOR_EACH_EDGE (e, ei, bb->succs)
3649     if (e->flags & EDGE_ABNORMAL)
3650       return true;
3651
3652   return false;
3653 }
3654
3655 /* Expand calls to inline functions in the body of FN.  */
3656
3657 unsigned int
3658 optimize_inline_calls (tree fn)
3659 {
3660   copy_body_data id;
3661   tree prev_fn;
3662   basic_block bb;
3663   int last = n_basic_blocks;
3664   struct gimplify_ctx gctx;
3665
3666   /* There is no point in performing inlining if errors have already
3667      occurred -- and we might crash if we try to inline invalid
3668      code.  */
3669   if (errorcount || sorrycount)
3670     return 0;
3671
3672   /* Clear out ID.  */
3673   memset (&id, 0, sizeof (id));
3674
3675   id.src_node = id.dst_node = cgraph_node (fn);
3676   id.dst_fn = fn;
3677   /* Or any functions that aren't finished yet.  */
3678   prev_fn = NULL_TREE;
3679   if (current_function_decl)
3680     {
3681       id.dst_fn = current_function_decl;
3682       prev_fn = current_function_decl;
3683     }
3684
3685   id.copy_decl = copy_decl_maybe_to_var;
3686   id.transform_call_graph_edges = CB_CGE_DUPLICATE;
3687   id.transform_new_cfg = false;
3688   id.transform_return_to_modify = true;
3689   id.transform_lang_insert_block = NULL;
3690   id.statements_to_fold = pointer_set_create ();
3691
3692   push_gimplify_context (&gctx);
3693
3694   /* We make no attempts to keep dominance info up-to-date.  */
3695   free_dominance_info (CDI_DOMINATORS);
3696   free_dominance_info (CDI_POST_DOMINATORS);
3697
3698   /* Register specific gimple functions.  */
3699   gimple_register_cfg_hooks ();
3700
3701   /* Reach the trees by walking over the CFG, and note the
3702      enclosing basic-blocks in the call edges.  */
3703   /* We walk the blocks going forward, because inlined function bodies
3704      will split id->current_basic_block, and the new blocks will
3705      follow it; we'll trudge through them, processing their CALL_EXPRs
3706      along the way.  */
3707   FOR_EACH_BB (bb)
3708     gimple_expand_calls_inline (bb, &id);
3709
3710   pop_gimplify_context (NULL);
3711
3712 #ifdef ENABLE_CHECKING
3713     {
3714       struct cgraph_edge *e;
3715
3716       verify_cgraph_node (id.dst_node);
3717
3718       /* Double check that we inlined everything we are supposed to inline.  */
3719       for (e = id.dst_node->callees; e; e = e->next_callee)
3720         gcc_assert (e->inline_failed);
3721     }
3722 #endif
3723   
3724   /* Fold the statements before compacting/renumbering the basic blocks.  */
3725   fold_marked_statements (last, id.statements_to_fold);
3726   pointer_set_destroy (id.statements_to_fold);
3727   
3728   /* Renumber the (code) basic_blocks consecutively.  */
3729   compact_blocks ();
3730   /* Renumber the lexical scoping (non-code) blocks consecutively.  */
3731   number_blocks (fn);
3732
3733   fold_cond_expr_cond ();
3734   delete_unreachable_blocks_update_callgraph (&id);
3735 #ifdef ENABLE_CHECKING
3736   verify_cgraph_node (id.dst_node);
3737 #endif
3738
3739   /* It would be nice to check SSA/CFG/statement consistency here, but it is
3740      not possible yet - the IPA passes might make various functions to not
3741      throw and they don't care to proactively update local EH info.  This is
3742      done later in fixup_cfg pass that also execute the verification.  */
3743   return (TODO_update_ssa
3744           | TODO_cleanup_cfg
3745           | (gimple_in_ssa_p (cfun) ? TODO_remove_unused_locals : 0)
3746           | (profile_status != PROFILE_ABSENT ? TODO_rebuild_frequencies : 0));
3747 }
3748
3749 /* Passed to walk_tree.  Copies the node pointed to, if appropriate.  */
3750
3751 tree
3752 copy_tree_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
3753 {
3754   enum tree_code code = TREE_CODE (*tp);
3755   enum tree_code_class cl = TREE_CODE_CLASS (code);
3756
3757   /* We make copies of most nodes.  */
3758   if (IS_EXPR_CODE_CLASS (cl)
3759       || code == TREE_LIST
3760       || code == TREE_VEC
3761       || code == TYPE_DECL
3762       || code == OMP_CLAUSE)
3763     {
3764       /* Because the chain gets clobbered when we make a copy, we save it
3765          here.  */
3766       tree chain = NULL_TREE, new_tree;
3767
3768       chain = TREE_CHAIN (*tp);
3769
3770       /* Copy the node.  */
3771       new_tree = copy_node (*tp);
3772
3773       /* Propagate mudflap marked-ness.  */
3774       if (flag_mudflap && mf_marked_p (*tp))
3775         mf_mark (new_tree);
3776
3777       *tp = new_tree;
3778
3779       /* Now, restore the chain, if appropriate.  That will cause
3780          walk_tree to walk into the chain as well.  */
3781       if (code == PARM_DECL
3782           || code == TREE_LIST
3783           || code == OMP_CLAUSE)
3784         TREE_CHAIN (*tp) = chain;
3785
3786       /* For now, we don't update BLOCKs when we make copies.  So, we
3787          have to nullify all BIND_EXPRs.  */
3788       if (TREE_CODE (*tp) == BIND_EXPR)
3789         BIND_EXPR_BLOCK (*tp) = NULL_TREE;
3790     }
3791   else if (code == CONSTRUCTOR)
3792     {
3793       /* CONSTRUCTOR nodes need special handling because
3794          we need to duplicate the vector of elements.  */
3795       tree new_tree;
3796
3797       new_tree = copy_node (*tp);
3798
3799       /* Propagate mudflap marked-ness.  */
3800       if (flag_mudflap && mf_marked_p (*tp))
3801         mf_mark (new_tree);
3802
3803       CONSTRUCTOR_ELTS (new_tree) = VEC_copy (constructor_elt, gc,
3804                                          CONSTRUCTOR_ELTS (*tp));
3805       *tp = new_tree;
3806     }
3807   else if (TREE_CODE_CLASS (code) == tcc_type)
3808     *walk_subtrees = 0;
3809   else if (TREE_CODE_CLASS (code) == tcc_declaration)
3810     *walk_subtrees = 0;
3811   else if (TREE_CODE_CLASS (code) == tcc_constant)
3812     *walk_subtrees = 0;
3813   else
3814     gcc_assert (code != STATEMENT_LIST);
3815   return NULL_TREE;
3816 }
3817
3818 /* The SAVE_EXPR pointed to by TP is being copied.  If ST contains
3819    information indicating to what new SAVE_EXPR this one should be mapped,
3820    use that one.  Otherwise, create a new node and enter it in ST.  FN is
3821    the function into which the copy will be placed.  */
3822
3823 static void
3824 remap_save_expr (tree *tp, void *st_, int *walk_subtrees)
3825 {
3826   struct pointer_map_t *st = (struct pointer_map_t *) st_;
3827   tree *n;
3828   tree t;
3829
3830   /* See if we already encountered this SAVE_EXPR.  */
3831   n = (tree *) pointer_map_contains (st, *tp);
3832
3833   /* If we didn't already remap this SAVE_EXPR, do so now.  */
3834   if (!n)
3835     {
3836       t = copy_node (*tp);
3837
3838       /* Remember this SAVE_EXPR.  */
3839       *pointer_map_insert (st, *tp) = t;
3840       /* Make sure we don't remap an already-remapped SAVE_EXPR.  */
3841       *pointer_map_insert (st, t) = t;
3842     }
3843   else
3844     {
3845       /* We've already walked into this SAVE_EXPR; don't do it again.  */
3846       *walk_subtrees = 0;
3847       t = *n;
3848     }
3849
3850   /* Replace this SAVE_EXPR with the copy.  */
3851   *tp = t;
3852 }
3853
3854 /* Called via walk_tree.  If *TP points to a DECL_STMT for a local label,
3855    copies the declaration and enters it in the splay_tree in DATA (which is
3856    really an `copy_body_data *').  */
3857
3858 static tree
3859 mark_local_for_remap_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
3860                         void *data)
3861 {
3862   copy_body_data *id = (copy_body_data *) data;
3863
3864   /* Don't walk into types.  */
3865   if (TYPE_P (*tp))
3866     *walk_subtrees = 0;
3867
3868   else if (TREE_CODE (*tp) == LABEL_EXPR)
3869     {
3870       tree decl = TREE_OPERAND (*tp, 0);
3871
3872       /* Copy the decl and remember the copy.  */
3873       insert_decl_map (id, decl, id->copy_decl (decl, id));
3874     }
3875
3876   return NULL_TREE;
3877 }
3878
3879 /* Perform any modifications to EXPR required when it is unsaved.  Does
3880    not recurse into EXPR's subtrees.  */
3881
3882 static void
3883 unsave_expr_1 (tree expr)
3884 {
3885   switch (TREE_CODE (expr))
3886     {
3887     case TARGET_EXPR:
3888       /* Don't mess with a TARGET_EXPR that hasn't been expanded.
3889          It's OK for this to happen if it was part of a subtree that
3890          isn't immediately expanded, such as operand 2 of another
3891          TARGET_EXPR.  */
3892       if (TREE_OPERAND (expr, 1))
3893         break;
3894
3895       TREE_OPERAND (expr, 1) = TREE_OPERAND (expr, 3);
3896       TREE_OPERAND (expr, 3) = NULL_TREE;
3897       break;
3898
3899     default:
3900       break;
3901     }
3902 }
3903
3904 /* Called via walk_tree when an expression is unsaved.  Using the
3905    splay_tree pointed to by ST (which is really a `splay_tree'),
3906    remaps all local declarations to appropriate replacements.  */
3907
3908 static tree
3909 unsave_r (tree *tp, int *walk_subtrees, void *data)
3910 {
3911   copy_body_data *id = (copy_body_data *) data;
3912   struct pointer_map_t *st = id->decl_map;
3913   tree *n;
3914
3915   /* Only a local declaration (variable or label).  */
3916   if ((TREE_CODE (*tp) == VAR_DECL && !TREE_STATIC (*tp))
3917       || TREE_CODE (*tp) == LABEL_DECL)
3918     {
3919       /* Lookup the declaration.  */
3920       n = (tree *) pointer_map_contains (st, *tp);
3921
3922       /* If it's there, remap it.  */
3923       if (n)
3924         *tp = *n;
3925     }
3926
3927   else if (TREE_CODE (*tp) == STATEMENT_LIST)
3928     gcc_unreachable ();
3929   else if (TREE_CODE (*tp) == BIND_EXPR)
3930     copy_bind_expr (tp, walk_subtrees, id);
3931   else if (TREE_CODE (*tp) == SAVE_EXPR
3932            || TREE_CODE (*tp) == TARGET_EXPR)
3933     remap_save_expr (tp, st, walk_subtrees);
3934   else
3935     {
3936       copy_tree_r (tp, walk_subtrees, NULL);
3937
3938       /* Do whatever unsaving is required.  */
3939       unsave_expr_1 (*tp);
3940     }
3941
3942   /* Keep iterating.  */
3943   return NULL_TREE;
3944 }
3945
3946 /* Copies everything in EXPR and replaces variables, labels
3947    and SAVE_EXPRs local to EXPR.  */
3948
3949 tree
3950 unsave_expr_now (tree expr)
3951 {
3952   copy_body_data id;
3953
3954   /* There's nothing to do for NULL_TREE.  */
3955   if (expr == 0)
3956     return expr;
3957
3958   /* Set up ID.  */
3959   memset (&id, 0, sizeof (id));
3960   id.src_fn = current_function_decl;
3961   id.dst_fn = current_function_decl;
3962   id.decl_map = pointer_map_create ();
3963
3964   id.copy_decl = copy_decl_no_change;
3965   id.transform_call_graph_edges = CB_CGE_DUPLICATE;
3966   id.transform_new_cfg = false;
3967   id.transform_return_to_modify = false;
3968   id.transform_lang_insert_block = NULL;
3969
3970   /* Walk the tree once to find local labels.  */
3971   walk_tree_without_duplicates (&expr, mark_local_for_remap_r, &id);
3972
3973   /* Walk the tree again, copying, remapping, and unsaving.  */
3974   walk_tree (&expr, unsave_r, &id, NULL);
3975
3976   /* Clean up.  */
3977   pointer_map_destroy (id.decl_map);
3978
3979   return expr;
3980 }
3981
3982 /* Called via walk_gimple_seq.  If *GSIP points to a GIMPLE_LABEL for a local
3983    label, copies the declaration and enters it in the splay_tree in DATA (which
3984    is really a 'copy_body_data *'.  */
3985
3986 static tree
3987 mark_local_labels_stmt (gimple_stmt_iterator *gsip,
3988                         bool *handled_ops_p ATTRIBUTE_UNUSED,
3989                         struct walk_stmt_info *wi)
3990 {
3991   copy_body_data *id = (copy_body_data *) wi->info;
3992   gimple stmt = gsi_stmt (*gsip);
3993
3994   if (gimple_code (stmt) == GIMPLE_LABEL)
3995     {
3996       tree decl = gimple_label_label (stmt);
3997
3998       /* Copy the decl and remember the copy.  */
3999       insert_decl_map (id, decl, id->copy_decl (decl, id));
4000     }
4001
4002   return NULL_TREE;
4003 }
4004
4005
4006 /* Called via walk_gimple_seq by copy_gimple_seq_and_replace_local.
4007    Using the splay_tree pointed to by ST (which is really a `splay_tree'),
4008    remaps all local declarations to appropriate replacements in gimple
4009    operands. */
4010
4011 static tree
4012 replace_locals_op (tree *tp, int *walk_subtrees, void *data)
4013 {
4014   struct walk_stmt_info *wi = (struct walk_stmt_info*) data;
4015   copy_body_data *id = (copy_body_data *) wi->info;
4016   struct pointer_map_t *st = id->decl_map;
4017   tree *n;
4018   tree expr = *tp;
4019
4020   /* Only a local declaration (variable or label).  */
4021   if ((TREE_CODE (expr) == VAR_DECL
4022        && !TREE_STATIC (expr))
4023       || TREE_CODE (expr) == LABEL_DECL)
4024     {
4025       /* Lookup the declaration.  */
4026       n = (tree *) pointer_map_contains (st, expr);
4027
4028       /* If it's there, remap it.  */
4029       if (n)
4030         *tp = *n;
4031       *walk_subtrees = 0;
4032     }
4033   else if (TREE_CODE (expr) == STATEMENT_LIST
4034            || TREE_CODE (expr) == BIND_EXPR
4035            || TREE_CODE (expr) == SAVE_EXPR)
4036     gcc_unreachable ();
4037   else if (TREE_CODE (expr) == TARGET_EXPR)
4038     {
4039       /* Don't mess with a TARGET_EXPR that hasn't been expanded.
4040          It's OK for this to happen if it was part of a subtree that
4041          isn't immediately expanded, such as operand 2 of another
4042          TARGET_EXPR.  */
4043       if (!TREE_OPERAND (expr, 1))
4044         {
4045           TREE_OPERAND (expr, 1) = TREE_OPERAND (expr, 3);
4046           TREE_OPERAND (expr, 3) = NULL_TREE;
4047         }
4048     }
4049
4050   /* Keep iterating.  */
4051   return NULL_TREE;
4052 }
4053
4054
4055 /* Called via walk_gimple_seq by copy_gimple_seq_and_replace_local.
4056    Using the splay_tree pointed to by ST (which is really a `splay_tree'),
4057    remaps all local declarations to appropriate replacements in gimple
4058    statements. */
4059
4060 static tree
4061 replace_locals_stmt (gimple_stmt_iterator *gsip,
4062                      bool *handled_ops_p ATTRIBUTE_UNUSED,
4063                      struct walk_stmt_info *wi)
4064 {
4065   copy_body_data *id = (copy_body_data *) wi->info;
4066   gimple stmt = gsi_stmt (*gsip);
4067
4068   if (gimple_code (stmt) == GIMPLE_BIND)
4069     {
4070       tree block = gimple_bind_block (stmt);
4071
4072       if (block)
4073         {
4074           remap_block (&block, id);
4075           gimple_bind_set_block (stmt, block);
4076         }
4077
4078       /* This will remap a lot of the same decls again, but this should be
4079          harmless.  */
4080       if (gimple_bind_vars (stmt))
4081         gimple_bind_set_vars (stmt, remap_decls (gimple_bind_vars (stmt), NULL, id));
4082     }
4083
4084   /* Keep iterating.  */
4085   return NULL_TREE;
4086 }
4087
4088
4089 /* Copies everything in SEQ and replaces variables and labels local to
4090    current_function_decl.  */
4091
4092 gimple_seq
4093 copy_gimple_seq_and_replace_locals (gimple_seq seq)
4094 {
4095   copy_body_data id;
4096   struct walk_stmt_info wi;
4097   struct pointer_set_t *visited;
4098   gimple_seq copy;
4099
4100   /* There's nothing to do for NULL_TREE.  */
4101   if (seq == NULL)
4102     return seq;
4103
4104   /* Set up ID.  */
4105   memset (&id, 0, sizeof (id));
4106   id.src_fn = current_function_decl;
4107   id.dst_fn = current_function_decl;
4108   id.decl_map = pointer_map_create ();
4109
4110   id.copy_decl = copy_decl_no_change;
4111   id.transform_call_graph_edges = CB_CGE_DUPLICATE;
4112   id.transform_new_cfg = false;
4113   id.transform_return_to_modify = false;
4114   id.transform_lang_insert_block = NULL;
4115
4116   /* Walk the tree once to find local labels.  */
4117   memset (&wi, 0, sizeof (wi));
4118   visited = pointer_set_create ();
4119   wi.info = &id;
4120   wi.pset = visited;
4121   walk_gimple_seq (seq, mark_local_labels_stmt, NULL, &wi);
4122   pointer_set_destroy (visited);
4123
4124   copy = gimple_seq_copy (seq);
4125
4126   /* Walk the copy, remapping decls.  */
4127   memset (&wi, 0, sizeof (wi));
4128   wi.info = &id;
4129   walk_gimple_seq (copy, replace_locals_stmt, replace_locals_op, &wi);
4130
4131   /* Clean up.  */
4132   pointer_map_destroy (id.decl_map);
4133
4134   return copy;
4135 }
4136
4137
4138 /* Allow someone to determine if SEARCH is a child of TOP from gdb.  */
4139
4140 static tree
4141 debug_find_tree_1 (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED, void *data)
4142 {
4143   if (*tp == data)
4144     return (tree) data;
4145   else
4146     return NULL;
4147 }
4148
4149 bool
4150 debug_find_tree (tree top, tree search)
4151 {
4152   return walk_tree_without_duplicates (&top, debug_find_tree_1, search) != 0;
4153 }
4154
4155
4156 /* Declare the variables created by the inliner.  Add all the variables in
4157    VARS to BIND_EXPR.  */
4158
4159 static void
4160 declare_inline_vars (tree block, tree vars)
4161 {
4162   tree t;
4163   for (t = vars; t; t = TREE_CHAIN (t))
4164     {
4165       DECL_SEEN_IN_BIND_EXPR_P (t) = 1;
4166       gcc_assert (!TREE_STATIC (t) && !TREE_ASM_WRITTEN (t));
4167       cfun->local_decls = tree_cons (NULL_TREE, t, cfun->local_decls);
4168     }
4169
4170   if (block)
4171     BLOCK_VARS (block) = chainon (BLOCK_VARS (block), vars);
4172 }
4173
4174 /* Copy NODE (which must be a DECL).  The DECL originally was in the FROM_FN,
4175    but now it will be in the TO_FN.  PARM_TO_VAR means enable PARM_DECL to
4176    VAR_DECL translation.  */
4177
4178 static tree
4179 copy_decl_for_dup_finish (copy_body_data *id, tree decl, tree copy)
4180 {
4181   /* Don't generate debug information for the copy if we wouldn't have
4182      generated it for the copy either.  */
4183   DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (decl);
4184   DECL_IGNORED_P (copy) = DECL_IGNORED_P (decl);
4185
4186   /* Set the DECL_ABSTRACT_ORIGIN so the debugging routines know what
4187      declaration inspired this copy.  */ 
4188   DECL_ABSTRACT_ORIGIN (copy) = DECL_ORIGIN (decl);
4189
4190   /* The new variable/label has no RTL, yet.  */
4191   if (CODE_CONTAINS_STRUCT (TREE_CODE (copy), TS_DECL_WRTL)
4192       && !TREE_STATIC (copy) && !DECL_EXTERNAL (copy))
4193     SET_DECL_RTL (copy, NULL_RTX);
4194   
4195   /* These args would always appear unused, if not for this.  */
4196   TREE_USED (copy) = 1;
4197
4198   /* Set the context for the new declaration.  */
4199   if (!DECL_CONTEXT (decl))
4200     /* Globals stay global.  */
4201     ;
4202   else if (DECL_CONTEXT (decl) != id->src_fn)
4203     /* Things that weren't in the scope of the function we're inlining
4204        from aren't in the scope we're inlining to, either.  */
4205     ;
4206   else if (TREE_STATIC (decl))
4207     /* Function-scoped static variables should stay in the original
4208        function.  */
4209     ;
4210   else
4211     /* Ordinary automatic local variables are now in the scope of the
4212        new function.  */
4213     DECL_CONTEXT (copy) = id->dst_fn;
4214
4215   return copy;
4216 }
4217
4218 static tree
4219 copy_decl_to_var (tree decl, copy_body_data *id)
4220 {
4221   tree copy, type;
4222
4223   gcc_assert (TREE_CODE (decl) == PARM_DECL
4224               || TREE_CODE (decl) == RESULT_DECL);
4225
4226   type = TREE_TYPE (decl);
4227
4228   copy = build_decl (DECL_SOURCE_LOCATION (id->dst_fn),
4229                      VAR_DECL, DECL_NAME (decl), type);
4230   TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (decl);
4231   TREE_READONLY (copy) = TREE_READONLY (decl);
4232   TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (decl);
4233   DECL_GIMPLE_REG_P (copy) = DECL_GIMPLE_REG_P (decl);
4234
4235   return copy_decl_for_dup_finish (id, decl, copy);
4236 }
4237
4238 /* Like copy_decl_to_var, but create a return slot object instead of a
4239    pointer variable for return by invisible reference.  */
4240
4241 static tree
4242 copy_result_decl_to_var (tree decl, copy_body_data *id)
4243 {
4244   tree copy, type;
4245
4246   gcc_assert (TREE_CODE (decl) == PARM_DECL
4247               || TREE_CODE (decl) == RESULT_DECL);
4248
4249   type = TREE_TYPE (decl);
4250   if (DECL_BY_REFERENCE (decl))
4251     type = TREE_TYPE (type);
4252
4253   copy = build_decl (DECL_SOURCE_LOCATION (id->dst_fn),
4254                      VAR_DECL, DECL_NAME (decl), type);
4255   TREE_READONLY (copy) = TREE_READONLY (decl);
4256   TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (decl);
4257   if (!DECL_BY_REFERENCE (decl))
4258     {
4259       TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (decl);
4260       DECL_GIMPLE_REG_P (copy) = DECL_GIMPLE_REG_P (decl);
4261     }
4262
4263   return copy_decl_for_dup_finish (id, decl, copy);
4264 }
4265
4266 tree
4267 copy_decl_no_change (tree decl, copy_body_data *id)
4268 {
4269   tree copy;
4270
4271   copy = copy_node (decl);
4272
4273   /* The COPY is not abstract; it will be generated in DST_FN.  */
4274   DECL_ABSTRACT (copy) = 0;
4275   lang_hooks.dup_lang_specific_decl (copy);
4276
4277   /* TREE_ADDRESSABLE isn't used to indicate that a label's address has
4278      been taken; it's for internal bookkeeping in expand_goto_internal.  */
4279   if (TREE_CODE (copy) == LABEL_DECL)
4280     {
4281       TREE_ADDRESSABLE (copy) = 0;
4282       LABEL_DECL_UID (copy) = -1;
4283     }
4284
4285   return copy_decl_for_dup_finish (id, decl, copy);
4286 }
4287
4288 static tree
4289 copy_decl_maybe_to_var (tree decl, copy_body_data *id)
4290 {
4291   if (TREE_CODE (decl) == PARM_DECL || TREE_CODE (decl) == RESULT_DECL)
4292     return copy_decl_to_var (decl, id);
4293   else
4294     return copy_decl_no_change (decl, id);
4295 }
4296
4297 /* Return a copy of the function's argument tree.  */
4298 static tree
4299 copy_arguments_for_versioning (tree orig_parm, copy_body_data * id,
4300                                bitmap args_to_skip, tree *vars)
4301 {
4302   tree arg, *parg;
4303   tree new_parm = NULL;
4304   int i = 0;
4305
4306   parg = &new_parm;
4307
4308   for (arg = orig_parm; arg; arg = TREE_CHAIN (arg), i++)
4309     if (!args_to_skip || !bitmap_bit_p (args_to_skip, i))
4310       {
4311         tree new_tree = remap_decl (arg, id);
4312         lang_hooks.dup_lang_specific_decl (new_tree);
4313         *parg = new_tree;
4314         parg = &TREE_CHAIN (new_tree);
4315       }
4316     else if (!pointer_map_contains (id->decl_map, arg))
4317       {
4318         /* Make an equivalent VAR_DECL.  If the argument was used
4319            as temporary variable later in function, the uses will be
4320            replaced by local variable.  */
4321         tree var = copy_decl_to_var (arg, id);
4322         get_var_ann (var);
4323         add_referenced_var (var);
4324         insert_decl_map (id, arg, var);
4325         /* Declare this new variable.  */
4326         TREE_CHAIN (var) = *vars;
4327         *vars = var;
4328       }
4329   return new_parm;
4330 }
4331
4332 /* Return a copy of the function's static chain.  */
4333 static tree
4334 copy_static_chain (tree static_chain, copy_body_data * id)
4335 {
4336   tree *chain_copy, *pvar;
4337
4338   chain_copy = &static_chain;
4339   for (pvar = chain_copy; *pvar; pvar = &TREE_CHAIN (*pvar))
4340     {
4341       tree new_tree = remap_decl (*pvar, id);
4342       lang_hooks.dup_lang_specific_decl (new_tree);
4343       TREE_CHAIN (new_tree) = TREE_CHAIN (*pvar);
4344       *pvar = new_tree;
4345     }
4346   return static_chain;
4347 }
4348
4349 /* Return true if the function is allowed to be versioned.
4350    This is a guard for the versioning functionality.  */
4351
4352 bool
4353 tree_versionable_function_p (tree fndecl)
4354 {
4355   return (!lookup_attribute ("noclone", DECL_ATTRIBUTES (fndecl))
4356           && copy_forbidden (DECL_STRUCT_FUNCTION (fndecl), fndecl) == NULL);
4357 }
4358
4359 /* Delete all unreachable basic blocks and update callgraph.
4360    Doing so is somewhat nontrivial because we need to update all clones and
4361    remove inline function that become unreachable.  */
4362
4363 static bool
4364 delete_unreachable_blocks_update_callgraph (copy_body_data *id)
4365 {
4366   bool changed = false;
4367   basic_block b, next_bb;
4368
4369   find_unreachable_blocks ();
4370
4371   /* Delete all unreachable basic blocks.  */
4372
4373   for (b = ENTRY_BLOCK_PTR->next_bb; b != EXIT_BLOCK_PTR; b = next_bb)
4374     {
4375       next_bb = b->next_bb;
4376
4377       if (!(b->flags & BB_REACHABLE))
4378         {
4379           gimple_stmt_iterator bsi;
4380
4381           for (bsi = gsi_start_bb (b); !gsi_end_p (bsi); gsi_next (&bsi))
4382             if (gimple_code (gsi_stmt (bsi)) == GIMPLE_CALL)
4383               {
4384                 struct cgraph_edge *e;
4385                 struct cgraph_node *node;
4386
4387                 if ((e = cgraph_edge (id->dst_node, gsi_stmt (bsi))) != NULL)
4388                   {
4389                     if (!e->inline_failed)
4390                       cgraph_remove_node_and_inline_clones (e->callee);
4391                     else
4392                       cgraph_remove_edge (e);
4393                   }
4394                 if (id->transform_call_graph_edges == CB_CGE_MOVE_CLONES
4395                     && id->dst_node->clones)
4396                   for (node = id->dst_node->clones; node != id->dst_node;)
4397                     {
4398                       if ((e = cgraph_edge (node, gsi_stmt (bsi))) != NULL)
4399                         {
4400                           if (!e->inline_failed)
4401                             cgraph_remove_node_and_inline_clones (e->callee);
4402                           else
4403                             cgraph_remove_edge (e);
4404                         }
4405                        
4406                       if (node->clones)
4407                         node = node->clones;
4408                       else if (node->next_sibling_clone)
4409                         node = node->next_sibling_clone;
4410                       else
4411                         {
4412                           while (node != id->dst_node && !node->next_sibling_clone)
4413                             node = node->clone_of;
4414                           if (node != id->dst_node)
4415                             node = node->next_sibling_clone;
4416                         }
4417                     }
4418               }
4419           delete_basic_block (b);
4420           changed = true;
4421         }
4422     }
4423
4424   if (changed)
4425     tidy_fallthru_edges ();
4426 #ifdef ENABLE_CHECKING0
4427   verify_cgraph_node (id->dst_node);
4428   if (id->transform_call_graph_edges == CB_CGE_MOVE_CLONES
4429       && id->dst_node->clones)
4430     {
4431       struct cgraph_node *node;
4432       for (node = id->dst_node->clones; node != id->dst_node;)
4433         {
4434           verify_cgraph_node (node);
4435            
4436           if (node->clones)
4437             node = node->clones;
4438           else if (node->next_sibling_clone)
4439             node = node->next_sibling_clone;
4440           else
4441             {
4442               while (node != id->dst_node && !node->next_sibling_clone)
4443                 node = node->clone_of;
4444               if (node != id->dst_node)
4445                 node = node->next_sibling_clone;
4446             }
4447         }
4448      }
4449 #endif
4450   return changed;
4451 }
4452
4453 /* Update clone info after duplication.  */
4454
4455 static void
4456 update_clone_info (copy_body_data * id)
4457 {
4458   struct cgraph_node *node;
4459   if (!id->dst_node->clones)
4460     return;
4461   for (node = id->dst_node->clones; node != id->dst_node;)
4462     {
4463       /* First update replace maps to match the new body.  */
4464       if (node->clone.tree_map)
4465         {
4466           unsigned int i;
4467           for (i = 0; i < VEC_length (ipa_replace_map_p, node->clone.tree_map); i++)
4468             {
4469               struct ipa_replace_map *replace_info;
4470               replace_info = VEC_index (ipa_replace_map_p, node->clone.tree_map, i);
4471               walk_tree (&replace_info->old_tree, copy_tree_body_r, id, NULL);
4472               walk_tree (&replace_info->new_tree, copy_tree_body_r, id, NULL);
4473             }
4474         }
4475       if (node->clones)
4476         node = node->clones;
4477       else if (node->next_sibling_clone)
4478         node = node->next_sibling_clone;
4479       else
4480         {
4481           while (node != id->dst_node && !node->next_sibling_clone)
4482             node = node->clone_of;
4483           if (node != id->dst_node)
4484             node = node->next_sibling_clone;
4485         }
4486     }
4487 }
4488
4489 /* Create a copy of a function's tree.
4490    OLD_DECL and NEW_DECL are FUNCTION_DECL tree nodes
4491    of the original function and the new copied function
4492    respectively.  In case we want to replace a DECL 
4493    tree with another tree while duplicating the function's 
4494    body, TREE_MAP represents the mapping between these 
4495    trees. If UPDATE_CLONES is set, the call_stmt fields
4496    of edges of clones of the function will be updated.  */
4497 void
4498 tree_function_versioning (tree old_decl, tree new_decl,
4499                           VEC(ipa_replace_map_p,gc)* tree_map,
4500                           bool update_clones, bitmap args_to_skip)
4501 {
4502   struct cgraph_node *old_version_node;
4503   struct cgraph_node *new_version_node;
4504   copy_body_data id;
4505   tree p;
4506   unsigned i;
4507   struct ipa_replace_map *replace_info;
4508   basic_block old_entry_block;
4509   VEC (gimple, heap) *init_stmts = VEC_alloc (gimple, heap, 10);
4510
4511   tree t_step;
4512   tree old_current_function_decl = current_function_decl;
4513   tree vars = NULL_TREE;
4514
4515   gcc_assert (TREE_CODE (old_decl) == FUNCTION_DECL
4516               && TREE_CODE (new_decl) == FUNCTION_DECL);
4517   DECL_POSSIBLY_INLINED (old_decl) = 1;
4518
4519   old_version_node = cgraph_node (old_decl);
4520   new_version_node = cgraph_node (new_decl);
4521
4522   /* Output the inlining info for this abstract function, since it has been
4523      inlined.  If we don't do this now, we can lose the information about the
4524      variables in the function when the blocks get blown away as soon as we
4525      remove the cgraph node.  */
4526   (*debug_hooks->outlining_inline_function) (old_decl);
4527
4528   DECL_ARTIFICIAL (new_decl) = 1;
4529   DECL_ABSTRACT_ORIGIN (new_decl) = DECL_ORIGIN (old_decl);
4530
4531   /* Prepare the data structures for the tree copy.  */
4532   memset (&id, 0, sizeof (id));
4533
4534   /* Generate a new name for the new version. */
4535   id.statements_to_fold = pointer_set_create ();
4536   
4537   id.decl_map = pointer_map_create ();
4538   id.src_fn = old_decl;
4539   id.dst_fn = new_decl;
4540   id.src_node = old_version_node;
4541   id.dst_node = new_version_node;
4542   id.src_cfun = DECL_STRUCT_FUNCTION (old_decl);
4543   
4544   id.copy_decl = copy_decl_no_change;
4545   id.transform_call_graph_edges
4546     = update_clones ? CB_CGE_MOVE_CLONES : CB_CGE_MOVE;
4547   id.transform_new_cfg = true;
4548   id.transform_return_to_modify = false;
4549   id.transform_lang_insert_block = NULL;
4550
4551   current_function_decl = new_decl;
4552   old_entry_block = ENTRY_BLOCK_PTR_FOR_FUNCTION
4553     (DECL_STRUCT_FUNCTION (old_decl));
4554   initialize_cfun (new_decl, old_decl,
4555                    old_entry_block->count,
4556                    old_entry_block->frequency);
4557   push_cfun (DECL_STRUCT_FUNCTION (new_decl));
4558   
4559   /* Copy the function's static chain.  */
4560   p = DECL_STRUCT_FUNCTION (old_decl)->static_chain_decl;
4561   if (p)
4562     DECL_STRUCT_FUNCTION (new_decl)->static_chain_decl =
4563       copy_static_chain (DECL_STRUCT_FUNCTION (old_decl)->static_chain_decl,
4564                          &id);
4565   
4566   /* If there's a tree_map, prepare for substitution.  */
4567   if (tree_map)
4568     for (i = 0; i < VEC_length (ipa_replace_map_p, tree_map); i++)
4569       {
4570         gimple init;
4571         replace_info = VEC_index (ipa_replace_map_p, tree_map, i);
4572         if (replace_info->replace_p)
4573           {
4574             tree op = replace_info->new_tree;
4575
4576             STRIP_NOPS (op);
4577
4578             if (TREE_CODE (op) == VIEW_CONVERT_EXPR)
4579               op = TREE_OPERAND (op, 0);
4580             
4581             if (TREE_CODE (op) == ADDR_EXPR)
4582               {
4583                 op = TREE_OPERAND (op, 0);
4584                 while (handled_component_p (op))
4585                   op = TREE_OPERAND (op, 0);
4586                 if (TREE_CODE (op) == VAR_DECL)
4587                   add_referenced_var (op);
4588               }
4589             gcc_assert (TREE_CODE (replace_info->old_tree) == PARM_DECL);
4590             init = setup_one_parameter (&id, replace_info->old_tree,
4591                                         replace_info->new_tree, id.src_fn,
4592                                         NULL,
4593                                         &vars);
4594             if (init)
4595               VEC_safe_push (gimple, heap, init_stmts, init);
4596           }
4597       }
4598   /* Copy the function's arguments.  */
4599   if (DECL_ARGUMENTS (old_decl) != NULL_TREE)
4600     DECL_ARGUMENTS (new_decl) =
4601       copy_arguments_for_versioning (DECL_ARGUMENTS (old_decl), &id,
4602                                      args_to_skip, &vars);
4603   
4604   DECL_INITIAL (new_decl) = remap_blocks (DECL_INITIAL (id.src_fn), &id);
4605   
4606   /* Renumber the lexical scoping (non-code) blocks consecutively.  */
4607   number_blocks (id.dst_fn);
4608   
4609   declare_inline_vars (DECL_INITIAL (new_decl), vars);
4610
4611   if (DECL_STRUCT_FUNCTION (old_decl)->local_decls != NULL_TREE)
4612     /* Add local vars.  */
4613     for (t_step = DECL_STRUCT_FUNCTION (old_decl)->local_decls;
4614          t_step; t_step = TREE_CHAIN (t_step))
4615       {
4616         tree var = TREE_VALUE (t_step);
4617         if (TREE_STATIC (var) && !TREE_ASM_WRITTEN (var))
4618           cfun->local_decls = tree_cons (NULL_TREE, var, cfun->local_decls);
4619         else if (!can_be_nonlocal (var, &id))
4620           cfun->local_decls =
4621             tree_cons (NULL_TREE, remap_decl (var, &id),
4622                        cfun->local_decls);
4623       }
4624   
4625   /* Copy the Function's body.  */
4626   copy_body (&id, old_entry_block->count, old_entry_block->frequency,
4627              ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR);
4628   
4629   if (DECL_RESULT (old_decl) != NULL_TREE)
4630     {
4631       tree *res_decl = &DECL_RESULT (old_decl);
4632       DECL_RESULT (new_decl) = remap_decl (*res_decl, &id);
4633       lang_hooks.dup_lang_specific_decl (DECL_RESULT (new_decl));
4634     }
4635   
4636   /* Renumber the lexical scoping (non-code) blocks consecutively.  */
4637   number_blocks (new_decl);
4638
4639   if (VEC_length (gimple, init_stmts))
4640     {
4641       basic_block bb = split_edge (single_succ_edge (ENTRY_BLOCK_PTR));
4642       while (VEC_length (gimple, init_stmts))
4643         insert_init_stmt (bb, VEC_pop (gimple, init_stmts));
4644     }
4645   update_clone_info (&id);
4646
4647   /* Remap the nonlocal_goto_save_area, if any.  */
4648   if (cfun->nonlocal_goto_save_area)
4649     {
4650       struct walk_stmt_info wi;
4651
4652       memset (&wi, 0, sizeof (wi));
4653       wi.info = &id;
4654       walk_tree (&cfun->nonlocal_goto_save_area, remap_gimple_op_r, &wi, NULL);
4655     }
4656
4657   /* Clean up.  */
4658   pointer_map_destroy (id.decl_map);
4659   free_dominance_info (CDI_DOMINATORS);
4660   free_dominance_info (CDI_POST_DOMINATORS);
4661
4662   fold_marked_statements (0, id.statements_to_fold);
4663   pointer_set_destroy (id.statements_to_fold);
4664   fold_cond_expr_cond ();
4665   delete_unreachable_blocks_update_callgraph (&id);
4666   update_ssa (TODO_update_ssa);
4667   free_dominance_info (CDI_DOMINATORS);
4668   free_dominance_info (CDI_POST_DOMINATORS);
4669
4670   VEC_free (gimple, heap, init_stmts);
4671   pop_cfun ();
4672   current_function_decl = old_current_function_decl;
4673   gcc_assert (!current_function_decl
4674               || DECL_STRUCT_FUNCTION (current_function_decl) == cfun);
4675   return;
4676 }
4677
4678 /* EXP is CALL_EXPR present in a GENERIC expression tree.  Try to integrate
4679    the callee and return the inlined body on success.  */
4680
4681 tree
4682 maybe_inline_call_in_expr (tree exp)
4683 {
4684   tree fn = get_callee_fndecl (exp);
4685
4686   /* We can only try to inline "const" functions.  */
4687   if (fn && TREE_READONLY (fn) && DECL_SAVED_TREE (fn))
4688     {
4689       struct pointer_map_t *decl_map = pointer_map_create ();
4690       call_expr_arg_iterator iter;
4691       copy_body_data id;
4692       tree param, arg, t;
4693
4694       /* Remap the parameters.  */
4695       for (param = DECL_ARGUMENTS (fn), arg = first_call_expr_arg (exp, &iter);
4696            param;
4697            param = TREE_CHAIN (param), arg = next_call_expr_arg (&iter))
4698         *pointer_map_insert (decl_map, param) = arg;
4699
4700       memset (&id, 0, sizeof (id));
4701       id.src_fn = fn;
4702       id.dst_fn = current_function_decl;
4703       id.src_cfun = DECL_STRUCT_FUNCTION (fn);
4704       id.decl_map = decl_map;
4705
4706       id.copy_decl = copy_decl_no_change;
4707       id.transform_call_graph_edges = CB_CGE_DUPLICATE;
4708       id.transform_new_cfg = false;
4709       id.transform_return_to_modify = true;
4710       id.transform_lang_insert_block = false;
4711
4712       /* Make sure not to unshare trees behind the front-end's back
4713          since front-end specific mechanisms may rely on sharing.  */
4714       id.regimplify = false;
4715       id.do_not_unshare = true;
4716
4717       /* We're not inside any EH region.  */
4718       id.eh_region = -1;
4719
4720       t = copy_tree_body (&id);
4721       pointer_map_destroy (decl_map);
4722
4723       /* We can only return something suitable for use in a GENERIC
4724          expression tree.  */
4725       if (TREE_CODE (t) == MODIFY_EXPR)
4726         return TREE_OPERAND (t, 1);
4727     }
4728
4729    return NULL_TREE;
4730 }
4731
4732 /* Duplicate a type, fields and all.  */
4733
4734 tree
4735 build_duplicate_type (tree type)
4736 {
4737   struct copy_body_data id;
4738
4739   memset (&id, 0, sizeof (id));
4740   id.src_fn = current_function_decl;
4741   id.dst_fn = current_function_decl;
4742   id.src_cfun = cfun;
4743   id.decl_map = pointer_map_create ();
4744   id.copy_decl = copy_decl_no_change;
4745
4746   type = remap_type_1 (type, &id);
4747
4748   pointer_map_destroy (id.decl_map);
4749
4750   TYPE_CANONICAL (type) = type;
4751
4752   return type;
4753 }
4754
4755 /* Return whether it is safe to inline a function because it used different
4756    target specific options or different optimization options.  */
4757 bool
4758 tree_can_inline_p (tree caller, tree callee)
4759 {
4760 #if 0
4761   /* This causes a regression in SPEC in that it prevents a cold function from
4762      inlining a hot function.  Perhaps this should only apply to functions
4763      that the user declares hot/cold/optimize explicitly.  */
4764
4765   /* Don't inline a function with a higher optimization level than the
4766      caller, or with different space constraints (hot/cold functions).  */
4767   tree caller_tree = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (caller);
4768   tree callee_tree = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (callee);
4769
4770   if (caller_tree != callee_tree)
4771     {
4772       struct cl_optimization *caller_opt
4773         = TREE_OPTIMIZATION ((caller_tree)
4774                              ? caller_tree
4775                              : optimization_default_node);
4776
4777       struct cl_optimization *callee_opt
4778         = TREE_OPTIMIZATION ((callee_tree)
4779                              ? callee_tree
4780                              : optimization_default_node);
4781
4782       if ((caller_opt->optimize > callee_opt->optimize)
4783           || (caller_opt->optimize_size != callee_opt->optimize_size))
4784         return false;
4785     }
4786 #endif
4787
4788   /* Allow the backend to decide if inlining is ok.  */
4789   return targetm.target_option.can_inline_p (caller, callee);
4790 }