OSDN Git Service

* fixlib.c (load_file_data): Use XRESIZVEC in lieu of xrealloc.
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-copy.c
1 /* Copy propagation and SSA_NAME replacement support routines.
2    Copyright (C) 2004, 2005 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING.  If not, write to
18 the Free Software Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "flags.h"
27 #include "rtl.h"
28 #include "tm_p.h"
29 #include "ggc.h"
30 #include "basic-block.h"
31 #include "output.h"
32 #include "errors.h"
33 #include "expr.h"
34 #include "function.h"
35 #include "diagnostic.h"
36 #include "timevar.h"
37 #include "tree-dump.h"
38 #include "tree-flow.h"
39 #include "tree-pass.h"
40 #include "tree-ssa-propagate.h"
41 #include "langhooks.h"
42
43 /* This file implements the copy propagation pass and provides a
44    handful of interfaces for performing const/copy propagation and
45    simple expression replacement which keep variable annotations
46    up-to-date.
47
48    We require that for any copy operation where the RHS and LHS have
49    a non-null memory tag the memory tag be the same.   It is OK
50    for one or both of the memory tags to be NULL.
51
52    We also require tracking if a variable is dereferenced in a load or
53    store operation.
54
55    We enforce these requirements by having all copy propagation and
56    replacements of one SSA_NAME with a different SSA_NAME to use the
57    APIs defined in this file.  */
58
59 /* Return true if we may propagate ORIG into DEST, false otherwise.  */
60
61 bool
62 may_propagate_copy (tree dest, tree orig)
63 {
64   tree type_d = TREE_TYPE (dest);
65   tree type_o = TREE_TYPE (orig);
66
67   /* Do not copy between types for which we *do* need a conversion.  */
68   if (!tree_ssa_useless_type_conversion_1 (type_d, type_o))
69     return false;
70
71   /* FIXME.  GIMPLE is allowing pointer assignments and comparisons of
72      pointers that have different alias sets.  This means that these
73      pointers will have different memory tags associated to them.
74
75      If we allow copy propagation in these cases, statements de-referencing
76      the new pointer will now have a reference to a different memory tag
77      with potentially incorrect SSA information.
78
79      This was showing up in libjava/java/util/zip/ZipFile.java with code
80      like:
81
82         struct java.io.BufferedInputStream *T.660;
83         struct java.io.BufferedInputStream *T.647;
84         struct java.io.InputStream *is;
85         struct java.io.InputStream *is.662;
86         [ ... ]
87         T.660 = T.647;
88         is = T.660;     <-- This ought to be type-casted
89         is.662 = is;
90
91      Also, f/name.c exposed a similar problem with a COND_EXPR predicate
92      that was causing DOM to generate and equivalence with two pointers of
93      alias-incompatible types:
94
95         struct _ffename_space *n;
96         struct _ffename *ns;
97         [ ... ]
98         if (n == ns)
99           goto lab;
100         ...
101         lab:
102         return n;
103
104      I think that GIMPLE should emit the appropriate type-casts.  For the
105      time being, blocking copy-propagation in these cases is the safe thing
106      to do.  */
107   if (TREE_CODE (dest) == SSA_NAME
108       && TREE_CODE (orig) == SSA_NAME
109       && POINTER_TYPE_P (type_d)
110       && POINTER_TYPE_P (type_o))
111     {
112       tree mt_dest = var_ann (SSA_NAME_VAR (dest))->type_mem_tag;
113       tree mt_orig = var_ann (SSA_NAME_VAR (orig))->type_mem_tag;
114       if (mt_dest && mt_orig && mt_dest != mt_orig)
115         return false;
116       else if (!lang_hooks.types_compatible_p (type_d, type_o))
117         return false;
118       else if (get_alias_set (TREE_TYPE (type_d)) != 
119                get_alias_set (TREE_TYPE (type_o)))
120         return false;
121     }
122
123   /* If the destination is a SSA_NAME for a virtual operand, then we have
124      some special cases to handle.  */
125   if (TREE_CODE (dest) == SSA_NAME && !is_gimple_reg (dest))
126     {
127       /* If both operands are SSA_NAMEs referring to virtual operands, then
128          we can always propagate.  */
129       if (TREE_CODE (orig) == SSA_NAME
130           && !is_gimple_reg (orig))
131         return true;
132
133       /* We have a "copy" from something like a constant into a virtual
134          operand.  Reject these.  */
135       return false;
136     }
137
138   /* If ORIG flows in from an abnormal edge, it cannot be propagated.  */
139   if (TREE_CODE (orig) == SSA_NAME
140       && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (orig))
141     return false;
142
143   /* If DEST is an SSA_NAME that flows from an abnormal edge, then it
144      cannot be replaced.  */
145   if (TREE_CODE (dest) == SSA_NAME
146       && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (dest))
147     return false;
148
149   /* Anything else is OK.  */
150   return true;
151 }
152
153 /* Similarly, but we know that we're propagating into an ASM_EXPR.  */
154
155 bool
156 may_propagate_copy_into_asm (tree dest)
157 {
158   /* Hard register operands of asms are special.  Do not bypass.  */
159   return !(TREE_CODE (dest) == SSA_NAME
160            && TREE_CODE (SSA_NAME_VAR (dest)) == VAR_DECL
161            && DECL_HARD_REGISTER (SSA_NAME_VAR (dest)));
162 }
163
164
165 /* Given two SSA_NAMEs pointers ORIG and NEW such that we are copy
166    propagating NEW into ORIG, consolidate aliasing information so that
167    they both share the same memory tags.  */
168
169 static void
170 merge_alias_info (tree orig, tree new)
171 {
172   tree new_sym = SSA_NAME_VAR (new);
173   tree orig_sym = SSA_NAME_VAR (orig);
174   var_ann_t new_ann = var_ann (new_sym);
175   var_ann_t orig_ann = var_ann (orig_sym);
176
177   gcc_assert (POINTER_TYPE_P (TREE_TYPE (orig)));
178   gcc_assert (POINTER_TYPE_P (TREE_TYPE (new)));
179
180 #if defined ENABLE_CHECKING
181   gcc_assert (lang_hooks.types_compatible_p (TREE_TYPE (orig),
182                                              TREE_TYPE (new)));
183
184   /* If the pointed-to alias sets are different, these two pointers
185      would never have the same memory tag.  In this case, NEW should
186      not have been propagated into ORIG.  */
187   gcc_assert (get_alias_set (TREE_TYPE (TREE_TYPE (new_sym)))
188               == get_alias_set (TREE_TYPE (TREE_TYPE (orig_sym))));
189 #endif
190
191   /* Synchronize the type tags.  If both pointers had a tag and they
192      are different, then something has gone wrong.  */
193   if (new_ann->type_mem_tag == NULL_TREE)
194     new_ann->type_mem_tag = orig_ann->type_mem_tag;
195   else if (orig_ann->type_mem_tag == NULL_TREE)
196     orig_ann->type_mem_tag = new_ann->type_mem_tag;
197   else
198     gcc_assert (new_ann->type_mem_tag == orig_ann->type_mem_tag);
199
200   /* Synchronize the name tags.  If NEW did not have a name tag, get
201      it from ORIG.  This happens when NEW is a compiler generated
202      temporary which still hasn't had its points-to information filled
203      in.  */
204   if (SSA_NAME_PTR_INFO (orig))
205     {
206       struct ptr_info_def *orig_ptr_info = SSA_NAME_PTR_INFO (orig);
207       struct ptr_info_def *new_ptr_info = SSA_NAME_PTR_INFO (new);
208
209       if (new_ptr_info == NULL)
210         duplicate_ssa_name_ptr_info (new, orig_ptr_info);
211       else if (orig_ptr_info->name_mem_tag
212                && new_ptr_info->name_mem_tag
213                && orig_ptr_info->pt_vars
214                && new_ptr_info->pt_vars)
215         {
216           /* Note that pointer NEW may actually have a different set
217              of pointed-to variables.  However, since NEW is being
218              copy-propagated into ORIG, it must always be true that
219              the pointed-to set for pointer NEW is the same, or a
220              subset, of the pointed-to set for pointer ORIG.  If this
221              isn't the case, we shouldn't have been able to do the
222              propagation of NEW into ORIG.  */
223           gcc_assert (bitmap_intersect_p (new_ptr_info->pt_vars,
224                 orig_ptr_info->pt_vars));
225         }
226     }
227 }   
228
229
230 /* Common code for propagate_value and replace_exp.
231
232    Replace use operand OP_P with VAL.  FOR_PROPAGATION indicates if the
233    replacement is done to propagate a value or not.  */
234
235 static void
236 replace_exp_1 (use_operand_p op_p, tree val,
237                bool for_propagation ATTRIBUTE_UNUSED)
238 {
239   tree op = USE_FROM_PTR (op_p);
240
241 #if defined ENABLE_CHECKING
242   gcc_assert (!(for_propagation
243                 && TREE_CODE (op) == SSA_NAME
244                 && TREE_CODE (val) == SSA_NAME
245                 && !may_propagate_copy (op, val)));
246 #endif
247
248   if (TREE_CODE (val) == SSA_NAME)
249     {
250       if (TREE_CODE (op) == SSA_NAME && POINTER_TYPE_P (TREE_TYPE (op)))
251         merge_alias_info (op, val);
252       SET_USE (op_p, val);
253     }
254   else
255     SET_USE (op_p, unsave_expr_now (val));
256 }
257
258
259 /* Propagate the value VAL (assumed to be a constant or another SSA_NAME)
260    into the operand pointed by OP_P.
261
262    Use this version for const/copy propagation as it will perform additional
263    checks to ensure validity of the const/copy propagation.  */
264
265 void
266 propagate_value (use_operand_p op_p, tree val)
267 {
268   replace_exp_1 (op_p, val, true);
269 }
270
271
272 /* Propagate the value VAL (assumed to be a constant or another SSA_NAME)
273    into the tree pointed by OP_P.
274
275    Use this version for const/copy propagation when SSA operands are not
276    available.  It will perform the additional checks to ensure validity of
277    the const/copy propagation, but will not update any operand information.
278    Be sure to mark the stmt as modified.  */
279
280 void
281 propagate_tree_value (tree *op_p, tree val)
282 {
283 #if defined ENABLE_CHECKING
284   gcc_assert (!(TREE_CODE (val) == SSA_NAME
285                 && TREE_CODE (*op_p) == SSA_NAME
286                 && !may_propagate_copy (*op_p, val)));
287 #endif
288
289   if (TREE_CODE (val) == SSA_NAME)
290     {
291       if (TREE_CODE (*op_p) == SSA_NAME && POINTER_TYPE_P (TREE_TYPE (*op_p)))
292         merge_alias_info (*op_p, val);
293       *op_p = val;
294     }
295   else
296     *op_p = unsave_expr_now (val);
297 }
298
299
300 /* Replace *OP_P with value VAL (assumed to be a constant or another SSA_NAME).
301
302    Use this version when not const/copy propagating values.  For example,
303    PRE uses this version when building expressions as they would appear
304    in specific blocks taking into account actions of PHI nodes.  */
305
306 void
307 replace_exp (use_operand_p op_p, tree val)
308 {
309   replace_exp_1 (op_p, val, false);
310 }
311
312
313 /*---------------------------------------------------------------------------
314                                 Copy propagation
315 ---------------------------------------------------------------------------*/
316 /* During propagation, we keep chains of variables that are copies of
317    one another.  If variable X_i is a copy of X_j and X_j is a copy of
318    X_k, COPY_OF will contain:
319
320         COPY_OF[i].VALUE = X_j
321         COPY_OF[j].VALUE = X_k
322         COPY_OF[k].VALUE = X_k
323
324    After propagation, the copy-of value for each variable X_i is
325    converted into the final value by walking the copy-of chains and
326    updating COPY_OF[i].VALUE to be the last element of the chain.  */
327 static prop_value_t *copy_of;
328
329 /* Used in set_copy_of_val to determine if the last link of a copy-of
330    chain has changed.  */
331 static tree *cached_last_copy_of;
332
333 /* True if we are doing copy propagation on loads and stores.  */
334 static bool do_store_copy_prop;
335
336
337 /* Return true if this statement may generate a useful copy.  */
338
339 static bool
340 stmt_may_generate_copy (tree stmt)
341 {
342   tree lhs, rhs;
343   stmt_ann_t ann;
344
345   if (TREE_CODE (stmt) == PHI_NODE)
346     return !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (stmt));
347
348   if (TREE_CODE (stmt) != MODIFY_EXPR)
349     return false;
350
351   lhs = TREE_OPERAND (stmt, 0);
352   rhs = TREE_OPERAND (stmt, 1);
353   ann = stmt_ann (stmt);
354
355   /* If the statement has volatile operands, it won't generate a
356      useful copy.  */
357   if (ann->has_volatile_ops)
358     return false;
359
360   /* If we are not doing store copy-prop, statements with loads and/or
361      stores will never generate a useful copy.  */
362   if (!do_store_copy_prop
363       && !ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
364     return false;
365
366   /* Otherwise, the only statements that generate useful copies are
367      assignments whose RHS is just an SSA name that doesn't flow
368      through abnormal edges.  */
369   return TREE_CODE (rhs) == SSA_NAME && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs);
370 }
371
372
373 /* Return the copy-of value for VAR.  */
374
375 static inline prop_value_t *
376 get_copy_of_val (tree var)
377 {
378   prop_value_t *val = &copy_of[SSA_NAME_VERSION (var)];
379
380   if (val->value == NULL_TREE
381       && !stmt_may_generate_copy (SSA_NAME_DEF_STMT (var)))
382     {
383       /* If the variable will never generate a useful copy relation,
384          make it its own copy.  */
385       val->value = var;
386       val->mem_ref = NULL_TREE;
387     }
388
389   return val;
390 }
391
392
393 /* Return last link in the copy-of chain for VAR.  */
394
395 static tree
396 get_last_copy_of (tree var)
397 {
398   tree last;
399   int i;
400
401   /* Traverse COPY_OF starting at VAR until we get to the last
402      link in the chain.  Since it is possible to have cycles in PHI
403      nodes, the copy-of chain may also contain cycles.
404      
405      To avoid infinite loops and to avoid traversing lengthy copy-of
406      chains, we artificially limit the maximum number of chains we are
407      willing to traverse.
408
409      The value 5 was taken from a compiler and runtime library
410      bootstrap and a mixture of C and C++ code from various sources.
411      More than 82% of all copy-of chains were shorter than 5 links.  */
412 #define LIMIT   5
413
414   last = var;
415   for (i = 0; i < LIMIT; i++)
416     {
417       tree copy = copy_of[SSA_NAME_VERSION (last)].value;
418       if (copy == NULL_TREE || copy == last)
419         break;
420       last = copy;
421     }
422
423   /* If we have reached the limit, then we are either in a copy-of
424      cycle or the copy-of chain is too long.  In this case, just
425      return VAR so that it is not considered a copy of anything.  */
426   return (i < LIMIT ? last : var);
427 }
428
429
430 /* Set FIRST to be the first variable in the copy-of chain for DEST.
431    If DEST's copy-of value or its copy-of chain has changed, return
432    true.
433
434    MEM_REF is the memory reference where FIRST is stored.  This is
435    used when DEST is a non-register and we are copy propagating loads
436    and stores.  */
437
438 static inline bool
439 set_copy_of_val (tree dest, tree first, tree mem_ref)
440 {
441   unsigned int dest_ver = SSA_NAME_VERSION (dest);
442   tree old_first, old_last, new_last;
443   
444   /* Set FIRST to be the first link in COPY_OF[DEST].  If that
445      changed, return true.  */
446   old_first = copy_of[dest_ver].value;
447   copy_of[dest_ver].value = first;
448   copy_of[dest_ver].mem_ref = mem_ref;
449
450   if (old_first != first)
451     return true;
452
453   /* If FIRST and OLD_FIRST are the same, we need to check whether the
454      copy-of chain starting at FIRST ends in a different variable.  If
455      the copy-of chain starting at FIRST ends up in a different
456      variable than the last cached value we had for DEST, then return
457      true because DEST is now a copy of a different variable.
458
459      This test is necessary because even though the first link in the
460      copy-of chain may not have changed, if any of the variables in
461      the copy-of chain changed its final value, DEST will now be the
462      copy of a different variable, so we have to do another round of
463      propagation for everything that depends on DEST.  */
464   old_last = cached_last_copy_of[dest_ver];
465   new_last = get_last_copy_of (dest);
466   cached_last_copy_of[dest_ver] = new_last;
467
468   return (old_last != new_last);
469 }
470
471
472 /* Dump the copy-of value for variable VAR to DUMP_FILE.  */
473
474 static void
475 dump_copy_of (FILE *dump_file, tree var)
476 {
477   tree val;
478
479   print_generic_expr (dump_file, var, dump_flags);
480
481   if (TREE_CODE (var) != SSA_NAME)
482     return;
483
484   fprintf (dump_file, " copy-of chain: ");
485
486   val = var;
487   print_generic_expr (dump_file, val, 0);
488   fprintf (dump_file, " ");
489   while (copy_of[SSA_NAME_VERSION (val)].value
490          && copy_of[SSA_NAME_VERSION (val)].value != val)
491     {
492       fprintf (dump_file, "-> ");
493       val = copy_of[SSA_NAME_VERSION (val)].value;
494       print_generic_expr (dump_file, val, 0);
495       fprintf (dump_file, " ");
496     }
497
498   val = get_copy_of_val (var)->value;
499   if (val == NULL_TREE)
500     fprintf (dump_file, "[UNDEFINED]");
501   else if (val != var)
502     fprintf (dump_file, "[COPY]");
503   else
504     fprintf (dump_file, "[NOT A COPY]");
505 }
506
507
508 /* Evaluate the RHS of STMT.  If it produces a valid copy, set the LHS
509    value and store the LHS into *RESULT_P.  If STMT generates more
510    than one name (i.e., STMT is an aliased store), it is enough to
511    store the first name in the V_MAY_DEF list into *RESULT_P.  After
512    all, the names generated will be VUSEd in the same statements.  */
513
514 static enum ssa_prop_result
515 copy_prop_visit_assignment (tree stmt, tree *result_p)
516 {
517   tree lhs, rhs;
518   prop_value_t *rhs_val;
519
520   lhs = TREE_OPERAND (stmt, 0);
521   rhs = TREE_OPERAND (stmt, 1);
522
523   gcc_assert (TREE_CODE (rhs) == SSA_NAME);
524
525   rhs_val = get_copy_of_val (rhs);
526
527   if (TREE_CODE (lhs) == SSA_NAME)
528     {
529       /* Straight copy between two SSA names.  First, make sure that
530          we can propagate the RHS into uses of LHS.  */
531       if (!may_propagate_copy (lhs, rhs))
532         return SSA_PROP_VARYING;
533
534       /* Avoid copy propagation from an inner into an outer loop.
535          Otherwise, this may move loop variant variables outside of
536          their loops and prevent coalescing opportunities.  If the
537          value was loop invariant, it will be hoisted by LICM and
538          exposed for copy propagation.  */
539       if (loop_depth_of_name (rhs) > loop_depth_of_name (lhs))
540         return SSA_PROP_VARYING;
541
542       /* Notice that in the case of assignments, we make the LHS be a
543          copy of RHS's value, not of RHS itself.  This avoids keeping
544          unnecessary copy-of chains (assignments cannot be in a cycle
545          like PHI nodes), speeding up the propagation process.
546          This is different from what we do in copy_prop_visit_phi_node. 
547          In those cases, we are interested in the copy-of chains.  */
548       *result_p = lhs;
549       if (set_copy_of_val (*result_p, rhs_val->value, rhs_val->mem_ref))
550         return SSA_PROP_INTERESTING;
551       else
552         return SSA_PROP_NOT_INTERESTING;
553     }
554   else if (stmt_makes_single_store (stmt))
555     {
556       /* Otherwise, set the names in V_MAY_DEF/V_MUST_DEF operands
557          to be a copy of RHS.  */
558       ssa_op_iter i;
559       tree vdef;
560       bool changed;
561
562       /* This should only be executed when doing store copy-prop.  */
563       gcc_assert (do_store_copy_prop);
564
565       /* Set the value of every VDEF to RHS_VAL.  */
566       changed = false;
567       FOR_EACH_SSA_TREE_OPERAND (vdef, stmt, i, SSA_OP_VIRTUAL_DEFS)
568         changed |= set_copy_of_val (vdef, rhs_val->value, lhs);
569       
570       /* Note that for propagation purposes, we are only interested in
571          visiting statements that load the exact same memory reference
572          stored here.  Those statements will have the exact same list
573          of virtual uses, so it is enough to set the output of this
574          statement to be its first virtual definition.  */
575       *result_p = first_vdef (stmt);
576
577       if (changed)
578         return SSA_PROP_INTERESTING;
579       else
580         return SSA_PROP_NOT_INTERESTING;
581     }
582
583
584   return SSA_PROP_VARYING;
585 }
586
587
588 /* Visit the COND_EXPR STMT.  Return SSA_PROP_INTERESTING
589    if it can determine which edge will be taken.  Otherwise, return
590    SSA_PROP_VARYING.  */
591
592 static enum ssa_prop_result
593 copy_prop_visit_cond_stmt (tree stmt, edge *taken_edge_p)
594 {
595   enum ssa_prop_result retval;
596   tree cond;
597   use_operand_p use_p;
598   ssa_op_iter iter;
599   unsigned num;
600
601
602   cond = COND_EXPR_COND (stmt);
603   retval = SSA_PROP_VARYING;
604   num = NUM_SSA_OPERANDS (stmt, SSA_OP_USE);
605
606   /* The only conditionals that we may be able to compute statically
607      are predicates involving at least one SSA_NAME.  */
608   if (COMPARISON_CLASS_P (cond)
609       && num >= 1)
610     {
611       unsigned i;
612       tree *orig;
613
614       /* Save the original operands.  */
615       orig = xmalloc (sizeof (tree) * num);
616       i = 0;
617       FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
618         {
619           tree use = USE_FROM_PTR (use_p);
620           orig[i++] = use;
621           SET_USE (use_p, get_last_copy_of (use));
622         }
623
624       /* See if we can determine the predicate's value.  */
625       if (dump_file && (dump_flags & TDF_DETAILS))
626         {
627           fprintf (dump_file, "Trying to determine truth value of ");
628           fprintf (dump_file, "predicate ");
629           print_generic_stmt (dump_file, cond, 0);
630         }
631
632       /* We can fold COND only and get a useful result only when we
633          have the same SSA_NAME on both sides of a comparison
634          operator.  */
635       if (TREE_CODE (TREE_OPERAND (cond, 0)) == SSA_NAME
636           && TREE_OPERAND (cond, 0) == TREE_OPERAND (cond, 1))
637         {
638           *taken_edge_p = find_taken_edge (bb_for_stmt (stmt), fold (cond));
639           if (*taken_edge_p)
640             retval = SSA_PROP_INTERESTING;
641         }
642
643       /* Restore the original operands.  */
644       i = 0;
645       FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
646         SET_USE (use_p, orig[i++]);
647       free (orig);
648     }
649
650   if (dump_file && (dump_flags & TDF_DETAILS) && *taken_edge_p)
651     fprintf (dump_file, "\nConditional will always take edge %d->%d\n",
652              (*taken_edge_p)->src->index, (*taken_edge_p)->dest->index);
653
654   return retval;
655 }
656
657
658 /* Evaluate statement STMT.  If the statement produces a new output
659    value, return SSA_PROP_INTERESTING and store the SSA_NAME holding
660    the new value in *RESULT_P.
661
662    If STMT is a conditional branch and we can determine its truth
663    value, set *TAKEN_EDGE_P accordingly.
664
665    If the new value produced by STMT is varying, return
666    SSA_PROP_VARYING.  */
667
668 static enum ssa_prop_result
669 copy_prop_visit_stmt (tree stmt, edge *taken_edge_p, tree *result_p)
670 {
671   stmt_ann_t ann;
672   enum ssa_prop_result retval;
673
674   if (dump_file && (dump_flags & TDF_DETAILS))
675     {
676       fprintf (dump_file, "\nVisiting statement:\n");
677       print_generic_stmt (dump_file, stmt, dump_flags);
678       fprintf (dump_file, "\n");
679     }
680
681   ann = stmt_ann (stmt);
682
683   if (TREE_CODE (stmt) == MODIFY_EXPR
684       && TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME
685       && (do_store_copy_prop
686           || TREE_CODE (TREE_OPERAND (stmt, 0)) == SSA_NAME))
687     {
688       /* If the statement is a copy assignment, evaluate its RHS to
689          see if the lattice value of its output has changed.  */
690       retval = copy_prop_visit_assignment (stmt, result_p);
691     }
692   else if (TREE_CODE (stmt) == COND_EXPR)
693     {
694       /* See if we can determine which edge goes out of a conditional
695          jump.  */
696       retval = copy_prop_visit_cond_stmt (stmt, taken_edge_p);
697     }
698   else
699     retval = SSA_PROP_VARYING;
700
701   if (retval == SSA_PROP_VARYING)
702     {
703       tree def;
704       ssa_op_iter i;
705
706       /* Any other kind of statement is not interesting for constant
707          propagation and, therefore, not worth simulating.  */
708       if (dump_file && (dump_flags & TDF_DETAILS))
709         fprintf (dump_file, "No interesting values produced.\n");
710
711       /* The assignment is not a copy operation.  Don't visit this
712          statement again and mark all the definitions in the statement
713          to be copies of nothing.  */
714       FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_ALL_DEFS)
715         set_copy_of_val (def, def, NULL_TREE);
716     }
717
718   return retval;
719 }
720
721
722 /* Visit PHI node PHI.  If all the arguments produce the same value,
723    set it to be the value of the LHS of PHI.  */
724
725 static enum ssa_prop_result
726 copy_prop_visit_phi_node (tree phi)
727 {
728   enum ssa_prop_result retval;
729   int i;
730   tree lhs;
731   prop_value_t phi_val = { 0, NULL_TREE, NULL_TREE };
732
733   lhs = PHI_RESULT (phi);
734
735   if (dump_file && (dump_flags & TDF_DETAILS))
736     {
737       fprintf (dump_file, "\nVisiting PHI node: ");
738       print_generic_expr (dump_file, phi, dump_flags);
739       fprintf (dump_file, "\n\n");
740     }
741
742   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
743     {
744       prop_value_t *arg_val;
745       tree arg = PHI_ARG_DEF (phi, i);
746       edge e = PHI_ARG_EDGE (phi, i);
747
748       /* We don't care about values flowing through non-executable
749          edges.  */
750       if (!(e->flags & EDGE_EXECUTABLE))
751         continue;
752
753       /* Constants in the argument list never generate a useful copy.
754          Similarly, names that flow through abnormal edges cannot be
755          used to derive copies.  */
756       if (TREE_CODE (arg) != SSA_NAME || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (arg))
757         {
758           phi_val.value = lhs;
759           break;
760         }
761
762       /* Avoid copy propagation from an inner into an outer loop.
763          Otherwise, this may move loop variant variables outside of
764          their loops and prevent coalescing opportunities.  If the
765          value was loop invariant, it will be hoisted by LICM and
766          exposed for copy propagation.  */
767       if (loop_depth_of_name (arg) > loop_depth_of_name (lhs))
768         {
769           phi_val.value = lhs;
770           break;
771         }
772
773       /* If the LHS appears in the argument list, ignore it.  It is
774          irrelevant as a copy.  */
775       if (arg == lhs || get_last_copy_of (arg) == lhs)
776         continue;
777
778       if (dump_file && (dump_flags & TDF_DETAILS))
779         {
780           fprintf (dump_file, "\tArgument #%d: ", i);
781           dump_copy_of (dump_file, arg);
782           fprintf (dump_file, "\n");
783         }
784
785       arg_val = get_copy_of_val (arg);
786
787       /* If the LHS didn't have a value yet, make it a copy of the
788          first argument we find.  Notice that while we make the LHS be
789          a copy of the argument itself, we take the memory reference
790          from the argument's value so that we can compare it to the
791          memory reference of all the other arguments.  */
792       if (phi_val.value == NULL_TREE)
793         {
794           phi_val.value = arg;
795           phi_val.mem_ref = arg_val->mem_ref;
796           continue;
797         }
798
799       /* If PHI_VAL and ARG don't have a common copy-of chain, then
800          this PHI node cannot be a copy operation.  Also, if we are
801          copy propagating stores and these two arguments came from
802          different memory references, they cannot be considered
803          copies.  */
804       if (get_last_copy_of (phi_val.value) != get_last_copy_of (arg)
805           || (do_store_copy_prop
806               && phi_val.mem_ref
807               && arg_val->mem_ref
808               && simple_cst_equal (phi_val.mem_ref, arg_val->mem_ref) != 1))
809         {
810           phi_val.value = lhs;
811           break;
812         }
813     }
814
815   if (phi_val.value && set_copy_of_val (lhs, phi_val.value, phi_val.mem_ref))
816     retval = (phi_val.value != lhs) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
817   else
818     retval = SSA_PROP_NOT_INTERESTING;
819
820   if (dump_file && (dump_flags & TDF_DETAILS))
821     {
822       fprintf (dump_file, "\nPHI node ");
823       dump_copy_of (dump_file, lhs);
824       fprintf (dump_file, "\nTelling the propagator to ");
825       if (retval == SSA_PROP_INTERESTING)
826         fprintf (dump_file, "add SSA edges out of this PHI and continue.");
827       else if (retval == SSA_PROP_VARYING)
828         fprintf (dump_file, "add SSA edges out of this PHI and never visit again.");
829       else
830         fprintf (dump_file, "do nothing with SSA edges and keep iterating.");
831       fprintf (dump_file, "\n\n");
832     }
833
834   return retval;
835 }
836
837
838 /* Initialize structures used for copy propagation.  */
839
840 static void
841 init_copy_prop (void)
842 {
843   basic_block bb;
844
845   copy_of = xmalloc (num_ssa_names * sizeof (*copy_of));
846   memset (copy_of, 0, num_ssa_names * sizeof (*copy_of));
847
848   cached_last_copy_of = xmalloc (num_ssa_names * sizeof (*cached_last_copy_of));
849   memset (cached_last_copy_of, 0, num_ssa_names * sizeof (*cached_last_copy_of));
850
851   FOR_EACH_BB (bb)
852     {
853       block_stmt_iterator si;
854       tree phi;
855
856       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
857         {
858           tree stmt = bsi_stmt (si);
859
860           /* The only statements that we care about are those that may
861              generate useful copies.  We also need to mark conditional
862              jumps so that their outgoing edges are added to the work
863              lists of the propagator.  */
864           if (stmt_ends_bb_p (stmt))
865             DONT_SIMULATE_AGAIN (stmt) = false;
866           else if (stmt_may_generate_copy (stmt))
867             DONT_SIMULATE_AGAIN (stmt) = false;
868           else
869             {
870               tree def;
871               ssa_op_iter iter;
872
873               /* No need to simulate this statement anymore.  */
874               DONT_SIMULATE_AGAIN (stmt) = true;
875
876               /* Mark all the outputs of this statement as not being
877                  the copy of anything.  */
878               FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
879                 set_copy_of_val (def, def, NULL_TREE);
880             }
881         }
882
883       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
884         DONT_SIMULATE_AGAIN (phi) = false;
885     }
886 }
887
888
889 /* Deallocate memory used in copy propagation and do final
890    substitution.  */
891
892 static void
893 fini_copy_prop (void)
894 {
895   size_t i;
896   
897   /* Set the final copy-of value for each variable by traversing the
898      copy-of chains.  */
899   for (i = 1; i < num_ssa_names; i++)
900     {
901       tree var = ssa_name (i);
902       if (var && copy_of[i].value && copy_of[i].value != var)
903         copy_of[i].value = get_last_copy_of (var);
904     }
905
906   substitute_and_fold (copy_of);
907
908   free (cached_last_copy_of);
909   free (copy_of);
910 }
911
912
913 /* Main entry point to the copy propagator.  The algorithm propagates
914    the value COPY-OF using ssa_propagate.  For every variable X_i,
915    COPY-OF(X_i) indicates which variable is X_i created from.  The
916    following example shows how the algorithm proceeds at a high level:
917
918             1   a_24 = x_1
919             2   a_2 = PHI <a_24, x_1>
920             3   a_5 = PHI <a_2>
921             4   x_1 = PHI <x_298, a_5, a_2>
922
923    The end result should be that a_2, a_5, a_24 and x_1 are a copy of
924    x_298.  Propagation proceeds as follows.
925
926    Visit #1: a_24 is copy-of x_1.  Value changed.
927    Visit #2: a_2 is copy-of x_1.  Value changed.
928    Visit #3: a_5 is copy-of x_1.  Value changed.
929    Visit #4: x_1 is copy-of x_298.  Value changed.
930    Visit #1: a_24 is copy-of x_298.  Value changed.
931    Visit #2: a_2 is copy-of x_298.  Value changed.
932    Visit #3: a_5 is copy-of x_298.  Value changed.
933    Visit #4: x_1 is copy-of x_298.  Stable state reached.
934    
935    When visiting PHI nodes, we only consider arguments that flow
936    through edges marked executable by the propagation engine.  So,
937    when visiting statement #2 for the first time, we will only look at
938    the first argument (a_24) and optimistically assume that its value
939    is the copy of a_24 (x_1).
940
941    The problem with this approach is that it may fail to discover copy
942    relations in PHI cycles.  Instead of propagating copy-of
943    values, we actually propagate copy-of chains.  For instance:
944
945                 A_3 = B_1;
946                 C_9 = A_3;
947                 D_4 = C_9;
948                 X_i = D_4;
949
950    In this code fragment, COPY-OF (X_i) = { D_4, C_9, A_3, B_1 }.
951    Obviously, we are only really interested in the last value of the
952    chain, however the propagator needs to access the copy-of chain
953    when visiting PHI nodes.
954
955    To represent the copy-of chain, we use the array COPY_CHAINS, which
956    holds the first link in the copy-of chain for every variable.
957    If variable X_i is a copy of X_j, which in turn is a copy of X_k,
958    the array will contain:
959
960                 COPY_CHAINS[i] = X_j
961                 COPY_CHAINS[j] = X_k
962                 COPY_CHAINS[k] = X_k
963
964    Keeping copy-of chains instead of copy-of values directly becomes
965    important when visiting PHI nodes.  Suppose that we had the
966    following PHI cycle, such that x_52 is already considered a copy of
967    x_53:
968
969             1   x_54 = PHI <x_53, x_52>
970             2   x_53 = PHI <x_898, x_54>
971    
972    Visit #1: x_54 is copy-of x_53 (because x_52 is copy-of x_53)
973    Visit #2: x_53 is copy-of x_898 (because x_54 is a copy of x_53,
974                                     so it is considered irrelevant
975                                     as a copy).
976    Visit #1: x_54 is copy-of nothing (x_53 is a copy-of x_898 and
977                                       x_52 is a copy of x_53, so
978                                       they don't match)
979    Visit #2: x_53 is copy-of nothing
980
981    This problem is avoided by keeping a chain of copies, instead of
982    the final copy-of value.  Propagation will now only keep the first
983    element of a variable's copy-of chain.  When visiting PHI nodes,
984    arguments are considered equal if their copy-of chains end in the
985    same variable.  So, as long as their copy-of chains overlap, we
986    know that they will be a copy of the same variable, regardless of
987    which variable that may be).
988    
989    Propagation would then proceed as follows (the notation a -> b
990    means that a is a copy-of b):
991
992    Visit #1: x_54 = PHI <x_53, x_52>
993                 x_53 -> x_53
994                 x_52 -> x_53
995                 Result: x_54 -> x_53.  Value changed.  Add SSA edges.
996
997    Visit #1: x_53 = PHI <x_898, x_54>
998                 x_898 -> x_898
999                 x_54 -> x_53
1000                 Result: x_53 -> x_898.  Value changed.  Add SSA edges.
1001
1002    Visit #2: x_54 = PHI <x_53, x_52>
1003                 x_53 -> x_898
1004                 x_52 -> x_53 -> x_898
1005                 Result: x_54 -> x_898.  Value changed.  Add SSA edges.
1006
1007    Visit #2: x_53 = PHI <x_898, x_54>
1008                 x_898 -> x_898
1009                 x_54 -> x_898
1010                 Result: x_53 -> x_898.  Value didn't change.  Stable state
1011
1012    Once the propagator stabilizes, we end up with the desired result
1013    x_53 and x_54 are both copies of x_898.  */
1014
1015 static void
1016 execute_copy_prop (bool store_copy_prop)
1017 {
1018   do_store_copy_prop = store_copy_prop;
1019   init_copy_prop ();
1020   ssa_propagate (copy_prop_visit_stmt, copy_prop_visit_phi_node);
1021   fini_copy_prop ();
1022 }
1023
1024
1025 static bool
1026 gate_copy_prop (void)
1027 {
1028   return flag_tree_copy_prop != 0;
1029 }
1030
1031 static void
1032 do_copy_prop (void)
1033 {
1034   execute_copy_prop (false);
1035 }
1036
1037 struct tree_opt_pass pass_copy_prop =
1038 {
1039   "copyprop",                           /* name */
1040   gate_copy_prop,                       /* gate */
1041   do_copy_prop,                         /* execute */
1042   NULL,                                 /* sub */
1043   NULL,                                 /* next */
1044   0,                                    /* static_pass_number */
1045   TV_TREE_COPY_PROP,                    /* tv_id */
1046   PROP_ssa | PROP_alias | PROP_cfg,     /* properties_required */
1047   0,                                    /* properties_provided */
1048   0,                                    /* properties_destroyed */
1049   0,                                    /* todo_flags_start */
1050   TODO_cleanup_cfg
1051     | TODO_dump_func
1052     | TODO_ggc_collect
1053     | TODO_verify_ssa
1054     | TODO_update_ssa,                  /* todo_flags_finish */
1055   0                                     /* letter */
1056 };
1057
1058
1059 static bool
1060 gate_store_copy_prop (void)
1061 {
1062   /* STORE-COPY-PROP is enabled only with -ftree-store-copy-prop, but
1063      when -fno-tree-store-copy-prop is specified, we should run
1064      regular COPY-PROP. That's why the pass is enabled with either
1065      flag.  */
1066   return flag_tree_store_copy_prop != 0 || flag_tree_copy_prop != 0;
1067 }
1068
1069 static void
1070 store_copy_prop (void)
1071 {
1072   /* If STORE-COPY-PROP is not enabled, we just run regular COPY-PROP.  */
1073   execute_copy_prop (flag_tree_store_copy_prop != 0);
1074 }
1075
1076 struct tree_opt_pass pass_store_copy_prop =
1077 {
1078   "store_copyprop",                     /* name */
1079   gate_store_copy_prop,                 /* gate */
1080   store_copy_prop,                      /* execute */
1081   NULL,                                 /* sub */
1082   NULL,                                 /* next */
1083   0,                                    /* static_pass_number */
1084   TV_TREE_STORE_COPY_PROP,              /* tv_id */
1085   PROP_ssa | PROP_alias | PROP_cfg,     /* properties_required */
1086   0,                                    /* properties_provided */
1087   0,                                    /* properties_destroyed */
1088   0,                                    /* todo_flags_start */
1089   TODO_dump_func
1090     | TODO_cleanup_cfg
1091     | TODO_ggc_collect
1092     | TODO_verify_ssa
1093     | TODO_update_ssa,                  /* todo_flags_finish */
1094   0                                     /* letter */
1095 };