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