OSDN Git Service

contrib/
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-pre.c
1 /* SSA-PRE for trees.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007
3    Free Software Foundation, Inc.
4    Contributed by Daniel Berlin <dan@dberlin.org> and Steven Bosscher
5    <stevenb@suse.de>
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "ggc.h"
28 #include "tree.h"
29 #include "basic-block.h"
30 #include "diagnostic.h"
31 #include "tree-inline.h"
32 #include "tree-flow.h"
33 #include "tree-gimple.h"
34 #include "tree-dump.h"
35 #include "timevar.h"
36 #include "fibheap.h"
37 #include "hashtab.h"
38 #include "tree-iterator.h"
39 #include "real.h"
40 #include "alloc-pool.h"
41 #include "obstack.h"
42 #include "tree-pass.h"
43 #include "flags.h"
44 #include "bitmap.h"
45 #include "langhooks.h"
46 #include "cfgloop.h"
47 #include "tree-ssa-sccvn.h"
48 #include "params.h"
49 #include "dbgcnt.h"
50
51 /* TODO:
52
53    1. Avail sets can be shared by making an avail_find_leader that
54       walks up the dominator tree and looks in those avail sets.
55       This might affect code optimality, it's unclear right now.
56    2. Strength reduction can be performed by anticipating expressions
57       we can repair later on.
58    3. We can do back-substitution or smarter value numbering to catch
59       commutative expressions split up over multiple statements.
60 */
61
62 /* For ease of terminology, "expression node" in the below refers to
63    every expression node but GIMPLE_MODIFY_STMT, because GIMPLE_MODIFY_STMT's
64    represent the actual statement containing the expressions we care about,
65    and we cache the value number by putting it in the expression.  */
66
67 /* Basic algorithm
68
69    First we walk the statements to generate the AVAIL sets, the
70    EXP_GEN sets, and the tmp_gen sets.  EXP_GEN sets represent the
71    generation of values/expressions by a given block.  We use them
72    when computing the ANTIC sets.  The AVAIL sets consist of
73    SSA_NAME's that represent values, so we know what values are
74    available in what blocks.  AVAIL is a forward dataflow problem.  In
75    SSA, values are never killed, so we don't need a kill set, or a
76    fixpoint iteration, in order to calculate the AVAIL sets.  In
77    traditional parlance, AVAIL sets tell us the downsafety of the
78    expressions/values.
79
80    Next, we generate the ANTIC sets.  These sets represent the
81    anticipatable expressions.  ANTIC is a backwards dataflow
82    problem.  An expression is anticipatable in a given block if it could
83    be generated in that block.  This means that if we had to perform
84    an insertion in that block, of the value of that expression, we
85    could.  Calculating the ANTIC sets requires phi translation of
86    expressions, because the flow goes backwards through phis.  We must
87    iterate to a fixpoint of the ANTIC sets, because we have a kill
88    set.  Even in SSA form, values are not live over the entire
89    function, only from their definition point onwards.  So we have to
90    remove values from the ANTIC set once we go past the definition
91    point of the leaders that make them up.
92    compute_antic/compute_antic_aux performs this computation.
93
94    Third, we perform insertions to make partially redundant
95    expressions fully redundant.
96
97    An expression is partially redundant (excluding partial
98    anticipation) if:
99
100    1. It is AVAIL in some, but not all, of the predecessors of a
101       given block.
102    2. It is ANTIC in all the predecessors.
103
104    In order to make it fully redundant, we insert the expression into
105    the predecessors where it is not available, but is ANTIC.
106
107    For the partial anticipation case, we only perform insertion if it
108    is partially anticipated in some block, and fully available in all
109    of the predecessors.
110
111    insert/insert_aux/do_regular_insertion/do_partial_partial_insertion
112    performs these steps.
113
114    Fourth, we eliminate fully redundant expressions.
115    This is a simple statement walk that replaces redundant
116    calculations with the now available values.  */
117
118 /* Representations of value numbers:
119
120    Value numbers are represented by a representative SSA_NAME.  We
121    will create fake SSA_NAME's in situations where we need a
122    representative but do not have one (because it is a complex
123    expression).  In order to facilitate storing the value numbers in
124    bitmaps, and keep the number of wasted SSA_NAME's down, we also
125    associate a value_id with each value number, and create full blown
126    ssa_name's only where we actually need them (IE in operands of
127    existing expressions).
128
129    Theoretically you could replace all the value_id's with
130    SSA_NAME_VERSION, but this would allocate a large number of
131    SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
132    It would also require an additional indirection at each point we
133    use the value id.  */
134
135 /* Representation of expressions on value numbers:
136
137    Expressions consisting of  value numbers are represented the same
138    way as our VN internally represents them, with an additional
139    "pre_expr" wrapping around them in order to facilitate storing all
140    of the expressions in the same sets.  */
141
142 /* Representation of sets:
143
144    The dataflow sets do not need to be sorted in any particular order
145    for the majority of their lifetime, are simply represented as two
146    bitmaps, one that keeps track of values present in the set, and one
147    that keeps track of expressions present in the set.
148
149    When we need them in topological order, we produce it on demand by
150    transforming the bitmap into an array and sorting it into topo
151    order.  */
152
153 /* Type of expression, used to know which member of the PRE_EXPR union
154    is valid.  */
155
156 enum pre_expr_kind
157 {
158     NAME,
159     NARY,
160     REFERENCE,
161     CONSTANT
162 };
163
164 typedef union pre_expr_union_d
165 {
166   tree name;
167   tree constant;
168   vn_nary_op_t nary;
169   vn_reference_t reference;
170 } pre_expr_union;
171
172 typedef struct pre_expr_d
173 {
174   enum pre_expr_kind kind;
175   unsigned int id;
176   pre_expr_union u;
177 } *pre_expr;
178
179 #define PRE_EXPR_NAME(e) (e)->u.name
180 #define PRE_EXPR_NARY(e) (e)->u.nary
181 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
182 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
183
184 static int
185 pre_expr_eq (const void *p1, const void *p2)
186 {
187   const struct pre_expr_d *e1 = (const struct pre_expr_d *) p1;
188   const struct pre_expr_d *e2 = (const struct pre_expr_d *) p2;
189
190   if (e1->kind != e2->kind)
191     return false;
192
193   switch (e1->kind)
194     {
195     case CONSTANT:
196       return expressions_equal_p (PRE_EXPR_CONSTANT (e1),
197                                   PRE_EXPR_CONSTANT (e2));
198     case NAME:
199       return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
200     case NARY:
201       return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
202     case REFERENCE:
203       return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
204                               PRE_EXPR_REFERENCE (e2));
205     default:
206       abort();
207     }
208 }
209
210 static hashval_t
211 pre_expr_hash (const void *p1)
212 {
213   const struct pre_expr_d *e = (const struct pre_expr_d *) p1;
214   switch (e->kind)
215     {
216     case CONSTANT:
217       return iterative_hash_expr (PRE_EXPR_CONSTANT (e), 0);
218     case NAME:
219       return iterative_hash_expr (PRE_EXPR_NAME (e), 0);
220     case NARY:
221       return vn_nary_op_compute_hash (PRE_EXPR_NARY (e));
222     case REFERENCE:
223       return vn_reference_compute_hash (PRE_EXPR_REFERENCE (e));
224     default:
225       abort ();
226     }
227 }
228
229
230 /* Next global expression id number.  */
231 static unsigned int next_expression_id;
232
233 /* Mapping from expression to id number we can use in bitmap sets.  */
234 DEF_VEC_P (pre_expr);
235 DEF_VEC_ALLOC_P (pre_expr, heap);
236 static VEC(pre_expr, heap) *expressions;
237 static htab_t expression_to_id;
238
239 /* Allocate an expression id for EXPR.  */
240
241 static inline unsigned int
242 alloc_expression_id (pre_expr expr)
243 {
244   void **slot;
245   /* Make sure we won't overflow. */
246   gcc_assert (next_expression_id + 1 > next_expression_id);
247   expr->id = next_expression_id++;
248   VEC_safe_push (pre_expr, heap, expressions, expr);
249   slot = htab_find_slot (expression_to_id, expr, INSERT);
250   gcc_assert (!*slot);
251   *slot = expr;
252   return next_expression_id - 1;
253 }
254
255 /* Return the expression id for tree EXPR.  */
256
257 static inline unsigned int
258 get_expression_id (const pre_expr expr)
259 {
260   return expr->id;
261 }
262
263 static inline unsigned int
264 lookup_expression_id (const pre_expr expr)
265 {
266   void **slot;
267
268   slot = htab_find_slot (expression_to_id, expr, NO_INSERT);
269   if (!slot)
270     return 0;
271   return ((pre_expr)*slot)->id;
272 }
273
274 /* Return the existing expression id for EXPR, or create one if one
275    does not exist yet.  */
276
277 static inline unsigned int
278 get_or_alloc_expression_id (pre_expr expr)
279 {
280   unsigned int id = lookup_expression_id (expr);
281   if (id == 0)
282     return alloc_expression_id (expr);
283   return expr->id = id;
284 }
285
286 /* Return the expression that has expression id ID */
287
288 static inline pre_expr
289 expression_for_id (unsigned int id)
290 {
291   return VEC_index (pre_expr, expressions, id);
292 }
293
294 /* Free the expression id field in all of our expressions,
295    and then destroy the expressions array.  */
296
297 static void
298 clear_expression_ids (void)
299 {
300   VEC_free (pre_expr, heap, expressions);
301 }
302
303 static alloc_pool pre_expr_pool;
304
305 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it.  */
306
307 static pre_expr
308 get_or_alloc_expr_for_name (tree name)
309 {
310   pre_expr result = (pre_expr) pool_alloc (pre_expr_pool);
311   unsigned int result_id;
312
313   result->kind = NAME;
314   result->id = 0;
315   PRE_EXPR_NAME (result) = name;
316   result_id = lookup_expression_id (result);
317   if (result_id != 0)
318     {
319       pool_free (pre_expr_pool, result);
320       result = expression_for_id (result_id);
321       return result;
322     }
323   get_or_alloc_expression_id (result);
324   return result;
325 }
326
327 static bool in_fre = false;
328
329 /* An unordered bitmap set.  One bitmap tracks values, the other,
330    expressions.  */
331 typedef struct bitmap_set
332 {
333   bitmap expressions;
334   bitmap values;
335 } *bitmap_set_t;
336
337 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi)            \
338   EXECUTE_IF_SET_IN_BITMAP((set)->expressions, 0, (id), (bi))
339
340 /* Mapping from value id to expressions with that value_id.  */
341 DEF_VEC_P (bitmap_set_t);
342 DEF_VEC_ALLOC_P (bitmap_set_t, heap);
343 static VEC(bitmap_set_t, heap) *value_expressions;
344
345 /* Sets that we need to keep track of.  */
346 typedef struct bb_bitmap_sets
347 {
348   /* The EXP_GEN set, which represents expressions/values generated in
349      a basic block.  */
350   bitmap_set_t exp_gen;
351
352   /* The PHI_GEN set, which represents PHI results generated in a
353      basic block.  */
354   bitmap_set_t phi_gen;
355
356   /* The TMP_GEN set, which represents results/temporaries generated
357      in a basic block. IE the LHS of an expression.  */
358   bitmap_set_t tmp_gen;
359
360   /* The AVAIL_OUT set, which represents which values are available in
361      a given basic block.  */
362   bitmap_set_t avail_out;
363
364   /* The ANTIC_IN set, which represents which values are anticipatable
365      in a given basic block.  */
366   bitmap_set_t antic_in;
367
368   /* The PA_IN set, which represents which values are
369      partially anticipatable in a given basic block.  */
370   bitmap_set_t pa_in;
371
372   /* The NEW_SETS set, which is used during insertion to augment the
373      AVAIL_OUT set of blocks with the new insertions performed during
374      the current iteration.  */
375   bitmap_set_t new_sets;
376
377   /* True if we have visited this block during ANTIC calculation.  */
378   unsigned int visited:1;
379
380   /* True we have deferred processing this block during ANTIC
381      calculation until its successor is processed.  */
382   unsigned int deferred : 1;
383 } *bb_value_sets_t;
384
385 #define EXP_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->exp_gen
386 #define PHI_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->phi_gen
387 #define TMP_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->tmp_gen
388 #define AVAIL_OUT(BB)   ((bb_value_sets_t) ((BB)->aux))->avail_out
389 #define ANTIC_IN(BB)    ((bb_value_sets_t) ((BB)->aux))->antic_in
390 #define PA_IN(BB)       ((bb_value_sets_t) ((BB)->aux))->pa_in
391 #define NEW_SETS(BB)    ((bb_value_sets_t) ((BB)->aux))->new_sets
392 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
393 #define BB_DEFERRED(BB) ((bb_value_sets_t) ((BB)->aux))->deferred
394
395
396 /* Maximal set of values, used to initialize the ANTIC problem, which
397    is an intersection problem.  */
398 static bitmap_set_t maximal_set;
399
400 /* Basic block list in postorder.  */
401 static int *postorder;
402
403 /* This structure is used to keep track of statistics on what
404    optimization PRE was able to perform.  */
405 static struct
406 {
407   /* The number of RHS computations eliminated by PRE.  */
408   int eliminations;
409
410   /* The number of new expressions/temporaries generated by PRE.  */
411   int insertions;
412
413   /* The number of inserts found due to partial anticipation  */
414   int pa_insert;
415
416   /* The number of new PHI nodes added by PRE.  */
417   int phis;
418
419   /* The number of values found constant.  */
420   int constified;
421
422 } pre_stats;
423
424 static bool do_partial_partial;
425 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int , tree);
426 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
427 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
428 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
429 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
430 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
431 static void bitmap_insert_into_set_1 (bitmap_set_t, pre_expr, bool);
432 static bitmap_set_t bitmap_set_new (void);
433 static tree create_expression_by_pieces (basic_block, pre_expr, tree, tree,
434                                          tree);
435 static tree find_or_generate_expression (basic_block, pre_expr, tree, tree);
436
437 /* We can add and remove elements and entries to and from sets
438    and hash tables, so we use alloc pools for them.  */
439
440 static alloc_pool bitmap_set_pool;
441 static bitmap_obstack grand_bitmap_obstack;
442
443 /* To avoid adding 300 temporary variables when we only need one, we
444    only create one temporary variable, on demand, and build ssa names
445    off that.  We do have to change the variable if the types don't
446    match the current variable's type.  */
447 static tree pretemp;
448 static tree storetemp;
449 static tree prephitemp;
450
451 /* Set of blocks with statements that have had its EH information
452    cleaned up.  */
453 static bitmap need_eh_cleanup;
454
455 /* Which expressions have been seen during a given phi translation.  */
456 static bitmap seen_during_translate;
457
458 /* The phi_translate_table caches phi translations for a given
459    expression and predecessor.  */
460
461 static htab_t phi_translate_table;
462
463 /* A three tuple {e, pred, v} used to cache phi translations in the
464    phi_translate_table.  */
465
466 typedef struct expr_pred_trans_d
467 {
468   /* The expression.  */
469   pre_expr e;
470
471   /* The predecessor block along which we translated the expression.  */
472   basic_block pred;
473
474   /* The value that resulted from the translation.  */
475   pre_expr v;
476
477   /* The hashcode for the expression, pred pair. This is cached for
478      speed reasons.  */
479   hashval_t hashcode;
480 } *expr_pred_trans_t;
481 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
482
483 /* Return the hash value for a phi translation table entry.  */
484
485 static hashval_t
486 expr_pred_trans_hash (const void *p)
487 {
488   const_expr_pred_trans_t const ve = (const_expr_pred_trans_t) p;
489   return ve->hashcode;
490 }
491
492 /* Return true if two phi translation table entries are the same.
493    P1 and P2 should point to the expr_pred_trans_t's to be compared.*/
494
495 static int
496 expr_pred_trans_eq (const void *p1, const void *p2)
497 {
498   const_expr_pred_trans_t const ve1 = (const_expr_pred_trans_t) p1;
499   const_expr_pred_trans_t const ve2 = (const_expr_pred_trans_t) p2;
500   basic_block b1 = ve1->pred;
501   basic_block b2 = ve2->pred;
502
503   /* If they are not translations for the same basic block, they can't
504      be equal.  */
505   if (b1 != b2)
506     return false;
507   return pre_expr_eq (ve1->e, ve2->e);
508 }
509
510 /* Search in the phi translation table for the translation of
511    expression E in basic block PRED.
512    Return the translated value, if found, NULL otherwise.  */
513
514 static inline pre_expr
515 phi_trans_lookup (pre_expr e, basic_block pred)
516 {
517   void **slot;
518   struct expr_pred_trans_d ept;
519
520   ept.e = e;
521   ept.pred = pred;
522   ept.hashcode = iterative_hash_hashval_t (pre_expr_hash (e), pred->index);
523   slot = htab_find_slot_with_hash (phi_translate_table, &ept, ept.hashcode,
524                                    NO_INSERT);
525   if (!slot)
526     return NULL;
527   else
528     return ((expr_pred_trans_t) *slot)->v;
529 }
530
531
532 /* Add the tuple mapping from {expression E, basic block PRED} to
533    value V, to the phi translation table.  */
534
535 static inline void
536 phi_trans_add (pre_expr e, pre_expr v, basic_block pred)
537 {
538   void **slot;
539   expr_pred_trans_t new_pair = XNEW (struct expr_pred_trans_d);
540   new_pair->e = e;
541   new_pair->pred = pred;
542   new_pair->v = v;
543   new_pair->hashcode = iterative_hash_hashval_t (pre_expr_hash (e),
544                                                  pred->index);
545
546   slot = htab_find_slot_with_hash (phi_translate_table, new_pair,
547                                    new_pair->hashcode, INSERT);
548   if (*slot)
549     free (*slot);
550   *slot = (void *) new_pair;
551 }
552
553
554 /* Add expression E to the expression set of value id V.  */
555
556 void
557 add_to_value (unsigned int v, pre_expr e)
558 {
559   bitmap_set_t set;
560
561   if (v >= VEC_length (bitmap_set_t, value_expressions))
562     {
563       VEC_safe_grow_cleared (bitmap_set_t, heap, value_expressions,
564                              v + 1);
565     }
566
567   set = VEC_index (bitmap_set_t, value_expressions, v);
568   if (!set)
569     {
570       set = bitmap_set_new ();
571       VEC_replace (bitmap_set_t, value_expressions, v, set);
572     }
573
574   bitmap_insert_into_set_1 (set, e, true);
575 }
576
577 /* Create a new bitmap set and return it.  */
578
579 static bitmap_set_t
580 bitmap_set_new (void)
581 {
582   bitmap_set_t ret = (bitmap_set_t) pool_alloc (bitmap_set_pool);
583   ret->expressions = BITMAP_ALLOC (&grand_bitmap_obstack);
584   ret->values = BITMAP_ALLOC (&grand_bitmap_obstack);
585   return ret;
586 }
587
588 /* Return the value id for a PRE expression EXPR.  */
589
590 static unsigned int
591 get_expr_value_id (pre_expr expr)
592 {
593   switch (expr->kind)
594     {
595     case CONSTANT:
596       return get_or_alloc_constant_value_id (PRE_EXPR_CONSTANT (expr));
597     case NAME:
598       return VN_INFO (PRE_EXPR_NAME (expr))->value_id;
599     case NARY:
600       return PRE_EXPR_NARY (expr)->value_id;
601     case REFERENCE:
602       return PRE_EXPR_REFERENCE (expr)->value_id;
603     default:
604       gcc_unreachable ();
605     }
606 }
607
608 /* Remove an expression EXPR from a bitmapped set.  */
609
610 static void
611 bitmap_remove_from_set (bitmap_set_t set, pre_expr expr)
612 {
613   unsigned int val  = get_expr_value_id (expr);
614   if (!value_id_constant_p (val))
615     {
616       bitmap_clear_bit (set->values, val);
617       bitmap_clear_bit (set->expressions, get_expression_id (expr));
618     }
619 }
620
621 static void
622 bitmap_insert_into_set_1 (bitmap_set_t set, pre_expr expr,
623                           bool allow_constants)
624 {
625   unsigned int val  = get_expr_value_id (expr);
626   if (allow_constants || !value_id_constant_p (val))
627     {
628       /* We specifically expect this and only this function to be able to
629          insert constants into a set.  */
630       bitmap_set_bit (set->values, val);
631       bitmap_set_bit (set->expressions, get_or_alloc_expression_id (expr));
632     }
633 }
634
635 /* Insert an expression EXPR into a bitmapped set.  */
636
637 static void
638 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
639 {
640   bitmap_insert_into_set_1 (set, expr, false);
641 }
642
643 /* Copy a bitmapped set ORIG, into bitmapped set DEST.  */
644
645 static void
646 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
647 {
648   bitmap_copy (dest->expressions, orig->expressions);
649   bitmap_copy (dest->values, orig->values);
650 }
651
652
653 /* Free memory used up by SET.  */
654 static void
655 bitmap_set_free (bitmap_set_t set)
656 {
657   BITMAP_FREE (set->expressions);
658   BITMAP_FREE (set->values);
659 }
660
661
662 /* A comparison function for use in qsort to top sort a bitmap set.  Simply
663    subtracts value ids, since they are created with leaves before
664    their parent users (IE topological order).  */
665
666 static int
667 value_id_compare (const void *pa, const void *pb)
668 {
669   const unsigned int vha = get_expr_value_id (*((const pre_expr *)pa));
670   const unsigned int vhb = get_expr_value_id (*((const pre_expr *)pb));
671
672   return vha - vhb;
673 }
674
675 /* Generate an topological-ordered array of bitmap set SET.  */
676
677 static VEC(pre_expr, heap) *
678 sorted_array_from_bitmap_set (bitmap_set_t set)
679 {
680   unsigned int i;
681   bitmap_iterator bi;
682   VEC(pre_expr, heap) *result = NULL;
683
684   FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
685     VEC_safe_push (pre_expr, heap, result, expression_for_id (i));
686
687   qsort (VEC_address (pre_expr, result), VEC_length (pre_expr, result),
688          sizeof (pre_expr), value_id_compare);
689
690   return result;
691 }
692
693 /* Perform bitmapped set operation DEST &= ORIG.  */
694
695 static void
696 bitmap_set_and (bitmap_set_t dest, bitmap_set_t orig)
697 {
698   bitmap_iterator bi;
699   unsigned int i;
700
701   if (dest != orig)
702     {
703       bitmap temp = BITMAP_ALLOC (&grand_bitmap_obstack);
704
705       bitmap_and_into (dest->values, orig->values);
706       bitmap_copy (temp, dest->expressions);
707       EXECUTE_IF_SET_IN_BITMAP (temp, 0, i, bi)
708         {
709           pre_expr expr = expression_for_id (i);
710           unsigned int value_id = get_expr_value_id (expr);
711           if (!bitmap_bit_p (dest->values, value_id))
712             bitmap_clear_bit (dest->expressions, i);
713         }
714       BITMAP_FREE (temp);
715     }
716 }
717
718 /* Subtract all values and expressions contained in ORIG from DEST.  */
719
720 static bitmap_set_t
721 bitmap_set_subtract (bitmap_set_t dest, bitmap_set_t orig)
722 {
723   bitmap_set_t result = bitmap_set_new ();
724   bitmap_iterator bi;
725   unsigned int i;
726
727   bitmap_and_compl (result->expressions, dest->expressions,
728                     orig->expressions);
729
730   FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
731     {
732       pre_expr expr = expression_for_id (i);
733       unsigned int value_id = get_expr_value_id (expr);
734       bitmap_set_bit (result->values, value_id);
735     }
736
737   return result;
738 }
739
740 /* Subtract all the values in bitmap set B from bitmap set A.  */
741
742 static void
743 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
744 {
745   unsigned int i;
746   bitmap_iterator bi;
747   bitmap temp = BITMAP_ALLOC (&grand_bitmap_obstack);
748
749   bitmap_copy (temp, a->expressions);
750   EXECUTE_IF_SET_IN_BITMAP (temp, 0, i, bi)
751     {
752       pre_expr expr = expression_for_id (i);
753       if (bitmap_set_contains_value (b, get_expr_value_id (expr)))
754         bitmap_remove_from_set (a, expr);
755     }
756   BITMAP_FREE (temp);
757 }
758
759
760 /* Return true if bitmapped set SET contains the value VALUE_ID.  */
761
762 static bool
763 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
764 {
765   if (value_id_constant_p (value_id))
766     return true;
767
768   if (!set || bitmap_empty_p (set->expressions))
769     return false;
770
771   return bitmap_bit_p (set->values, value_id);
772 }
773
774 static inline bool
775 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
776 {
777   return bitmap_bit_p (set->expressions, get_expression_id (expr));
778 }
779
780 /* Replace an instance of value LOOKFOR with expression EXPR in SET.  */
781
782 static void
783 bitmap_set_replace_value (bitmap_set_t set, unsigned int lookfor,
784                           const pre_expr expr)
785 {
786   bitmap_set_t exprset;
787   unsigned int i;
788   bitmap_iterator bi;
789
790   if (value_id_constant_p (lookfor))
791     return;
792
793   if (!bitmap_set_contains_value (set, lookfor))
794     return;
795
796   /* The number of expressions having a given value is usually
797      significantly less than the total number of expressions in SET.
798      Thus, rather than check, for each expression in SET, whether it
799      has the value LOOKFOR, we walk the reverse mapping that tells us
800      what expressions have a given value, and see if any of those
801      expressions are in our set.  For large testcases, this is about
802      5-10x faster than walking the bitmap.  If this is somehow a
803      significant lose for some cases, we can choose which set to walk
804      based on the set size.  */
805   exprset = VEC_index (bitmap_set_t, value_expressions, lookfor);
806   FOR_EACH_EXPR_ID_IN_SET (exprset, i, bi)
807     {
808       if (bitmap_bit_p (set->expressions, i))
809         {
810           bitmap_clear_bit (set->expressions, i);
811           bitmap_set_bit (set->expressions, get_expression_id (expr));
812           return;
813         }
814     }
815 }
816
817 /* Return true if two bitmap sets are equal.  */
818
819 static bool
820 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
821 {
822   return bitmap_equal_p (a->values, b->values);
823 }
824
825 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
826    and add it otherwise.  */
827
828 static void
829 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
830 {
831   unsigned int val = get_expr_value_id (expr);
832
833   if (bitmap_set_contains_value (set, val))
834     bitmap_set_replace_value (set, val, expr);
835   else
836     bitmap_insert_into_set (set, expr);
837 }
838
839 /* Insert EXPR into SET if EXPR's value is not already present in
840    SET.  */
841
842 static void
843 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
844 {
845   unsigned int val = get_expr_value_id (expr);
846
847   if (value_id_constant_p (val))
848     return;
849
850   if (!bitmap_set_contains_value (set, val))
851     bitmap_insert_into_set (set, expr);
852 }
853
854 /* Print out EXPR to outfile.  */
855
856 static void
857 print_pre_expr (FILE *outfile, const pre_expr expr)
858 {
859   switch (expr->kind)
860     {
861     case CONSTANT:
862       print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr), 0);
863       break;
864     case NAME:
865       print_generic_expr (outfile, PRE_EXPR_NAME (expr), 0);
866       break;
867     case NARY:
868       {
869         unsigned int i;
870         vn_nary_op_t nary = PRE_EXPR_NARY (expr);
871         fprintf (outfile, "{%s,", tree_code_name [nary->opcode]);
872         for (i = 0; i < nary->length; i++)
873           {
874             print_generic_expr (outfile, nary->op[i], 0);
875             if (i != (unsigned) nary->length - 1)
876               fprintf (outfile, ",");
877           }
878         fprintf (outfile, "}");
879       }
880       break;
881
882     case REFERENCE:
883       {
884         vn_reference_op_t vro;
885         unsigned int i;
886         vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
887         fprintf (outfile, "{");
888         for (i = 0;
889              VEC_iterate (vn_reference_op_s, ref->operands, i, vro);
890              i++)
891           {
892             if (vro->opcode != SSA_NAME
893                 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
894               fprintf (outfile, "%s ", tree_code_name [vro->opcode]);
895             if (vro->op0)
896               {
897                 if (vro->op1)
898                   fprintf (outfile, "<");
899                 print_generic_expr (outfile, vro->op0, 0);
900                 if (vro->op1)
901                   {
902                     fprintf (outfile, ",");
903                     print_generic_expr (outfile, vro->op1, 0);
904                   }
905                 if (vro->op1)
906                   fprintf (outfile, ">");
907               }
908             if (i != VEC_length (vn_reference_op_s, ref->operands) - 1)
909               fprintf (outfile, ",");
910           }
911         fprintf (outfile, "}");
912       }
913       break;
914     }
915 }
916 void debug_pre_expr (pre_expr);
917
918 /* Like print_pre_expr but always prints to stderr.  */
919 void
920 debug_pre_expr (pre_expr e)
921 {
922   print_pre_expr (stderr, e);
923   fprintf (stderr, "\n");
924 }
925
926 /* Print out SET to OUTFILE.  */
927
928 static void
929 print_bitmap_set (FILE *outfile, bitmap_set_t set,
930                   const char *setname, int blockindex)
931 {
932   fprintf (outfile, "%s[%d] := { ", setname, blockindex);
933   if (set)
934     {
935       bool first = true;
936       unsigned i;
937       bitmap_iterator bi;
938
939       FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
940         {
941           const pre_expr expr = expression_for_id (i);
942
943           if (!first)
944             fprintf (outfile, ", ");
945           first = false;
946           print_pre_expr (outfile, expr);
947
948           fprintf (outfile, " (%04d)", get_expr_value_id (expr));
949         }
950     }
951   fprintf (outfile, " }\n");
952 }
953
954 void debug_bitmap_set (bitmap_set_t);
955
956 void
957 debug_bitmap_set (bitmap_set_t set)
958 {
959   print_bitmap_set (stderr, set, "debug", 0);
960 }
961
962 /* Print out the expressions that have VAL to OUTFILE.  */
963
964 void
965 print_value_expressions (FILE *outfile, unsigned int val)
966 {
967   bitmap_set_t set = VEC_index (bitmap_set_t, value_expressions, val);
968   if (set)
969     {
970       char s[10];
971       sprintf (s, "%04d", val);
972       print_bitmap_set (outfile, set, s, 0);
973     }
974 }
975
976
977 void
978 debug_value_expressions (unsigned int val)
979 {
980   print_value_expressions (stderr, val);
981 }
982
983 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
984    represent it.  */
985
986 static pre_expr
987 get_or_alloc_expr_for_constant (tree constant)
988 {
989   unsigned int result_id;
990   unsigned int value_id;
991   pre_expr newexpr = (pre_expr) pool_alloc (pre_expr_pool);
992   newexpr->kind = CONSTANT;
993   PRE_EXPR_CONSTANT (newexpr) = constant;
994   result_id = lookup_expression_id (newexpr);
995   if (result_id != 0)
996     {
997       pool_free (pre_expr_pool, newexpr);
998       newexpr = expression_for_id (result_id);
999       return newexpr;
1000     }
1001   value_id = get_or_alloc_constant_value_id (constant);
1002   get_or_alloc_expression_id (newexpr);
1003   add_to_value (value_id, newexpr);
1004   return newexpr;
1005 }
1006
1007 /* Given a value id V, find the actual tree representing the constant
1008    value if there is one, and return it. Return NULL if we can't find
1009    a constant.  */
1010
1011 static tree
1012 get_constant_for_value_id (unsigned int v)
1013 {
1014   if (value_id_constant_p (v))
1015     {
1016       unsigned int i;
1017       bitmap_iterator bi;
1018       bitmap_set_t exprset = VEC_index (bitmap_set_t, value_expressions, v);
1019
1020       FOR_EACH_EXPR_ID_IN_SET (exprset, i, bi)
1021         {
1022           pre_expr expr = expression_for_id (i);
1023           if (expr->kind == CONSTANT)
1024             return PRE_EXPR_CONSTANT (expr);
1025         }
1026     }
1027   return NULL;
1028 }
1029
1030 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1031    Currently only supports constants and SSA_NAMES.  */
1032 static pre_expr
1033 get_or_alloc_expr_for (tree t)
1034 {
1035   if (TREE_CODE (t) == SSA_NAME)
1036     return get_or_alloc_expr_for_name (t);
1037   else if (is_gimple_min_invariant (t))
1038     return get_or_alloc_expr_for_constant (t);
1039   return NULL;
1040 }
1041
1042 /* Return the folded version of T if T, when folded, is a gimple
1043    min_invariant.  Otherwise, return T.  */
1044
1045 static pre_expr
1046 fully_constant_expression (pre_expr e)
1047 {
1048   switch (e->kind)
1049     {
1050     case CONSTANT:
1051       return e;
1052     case NARY:
1053       {
1054         vn_nary_op_t nary = PRE_EXPR_NARY (e);
1055         switch (TREE_CODE_CLASS (nary->opcode))
1056           {
1057           case tcc_binary:
1058             {
1059               /* We have to go from trees to pre exprs to value ids to
1060                  constants.  */
1061               tree naryop0 = nary->op[0];
1062               tree naryop1 = nary->op[1];
1063               pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1064               pre_expr rep1 = get_or_alloc_expr_for (naryop1);
1065               unsigned int vrep0 = get_expr_value_id (rep0);
1066               unsigned int vrep1 = get_expr_value_id (rep1);
1067               tree const0 = get_constant_for_value_id (vrep0);
1068               tree const1 = get_constant_for_value_id (vrep1);
1069               tree result = NULL;
1070               if (const0 && const1)
1071                 {
1072                   tree type1 = TREE_TYPE (nary->op[0]);
1073                   tree type2 = TREE_TYPE (nary->op[1]);
1074                   const0 = fold_convert (type1, const0);
1075                   const1 = fold_convert (type2, const1);
1076                   result = fold_binary (nary->opcode, nary->type, const0,
1077                                         const1);
1078                 }
1079               if (result && is_gimple_min_invariant (result))
1080                 return get_or_alloc_expr_for_constant (result);
1081               return e;
1082             }
1083           case tcc_unary:
1084             {
1085             /* We have to go from trees to pre exprs to value ids to
1086                constants.  */
1087               tree naryop0 = nary->op[0];
1088               pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1089               unsigned int vrep0 = get_expr_value_id (rep0);
1090               tree const0 = get_constant_for_value_id (vrep0);
1091               tree result = NULL;
1092               if (const0)
1093                 {
1094                   tree type1 = TREE_TYPE (nary->op[0]);
1095                   const0 = fold_convert (type1, const0);
1096                   result = fold_unary (nary->opcode, nary->type, const0);
1097                 }
1098               
1099               if (result && is_gimple_min_invariant (result))
1100                 return get_or_alloc_expr_for_constant (result);
1101               return e;
1102             }
1103           default:
1104             return e;
1105           }
1106       }
1107     default:
1108       return e;
1109     }
1110   return e;
1111 }
1112
1113 /* Translate the vuses in the VUSES vector backwards through phi nodes
1114    in PHIBLOCK, so that they have the value they would have in
1115    BLOCK. */
1116
1117 static VEC(tree, gc) *
1118 translate_vuses_through_block (VEC (tree, gc) *vuses,
1119                                basic_block phiblock,
1120                                basic_block block)
1121 {
1122   tree oldvuse;
1123   VEC(tree, gc) *result = NULL;
1124   int i;
1125
1126   for (i = 0; VEC_iterate (tree, vuses, i, oldvuse); i++)
1127     {
1128       tree phi = SSA_NAME_DEF_STMT (oldvuse);
1129       if (TREE_CODE (phi) == PHI_NODE
1130           && bb_for_stmt (phi) == phiblock)
1131         {
1132           edge e = find_edge (block, bb_for_stmt (phi));
1133           if (e)
1134             {
1135               tree def = PHI_ARG_DEF (phi, e->dest_idx);
1136               if (def != oldvuse)
1137                 {
1138                   if (!result)
1139                     result = VEC_copy (tree, gc, vuses);
1140                   VEC_replace (tree, result, i, def);
1141                 }
1142             }
1143         }
1144     }
1145
1146   /* We avoid creating a new copy of the vuses unless something
1147      actually changed, so result can be NULL.  */
1148   if (result)
1149     {
1150       sort_vuses (result);
1151       return result;
1152     }
1153   return vuses;
1154
1155 }
1156
1157 /* Like find_leader, but checks for the value existing in SET1 *or*
1158    SET2.  This is used to avoid making a set consisting of the union
1159    of PA_IN and ANTIC_IN during insert.  */
1160
1161 static inline pre_expr
1162 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2)
1163 {
1164   pre_expr result;
1165
1166   result = bitmap_find_leader (set1, val, NULL_TREE);
1167   if (!result && set2)
1168     result = bitmap_find_leader (set2, val, NULL_TREE);
1169   return result;
1170 }
1171
1172 /* Get the tree type for our PRE expression e.  */
1173
1174 static tree
1175 get_expr_type (const pre_expr e)
1176 {
1177   switch (e->kind)
1178     {
1179     case NAME:
1180       return TREE_TYPE (PRE_EXPR_NAME (e));
1181     case CONSTANT:
1182       return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1183     case REFERENCE:
1184       {
1185         vn_reference_op_t vro;
1186
1187         gcc_assert (PRE_EXPR_REFERENCE (e)->operands);
1188         vro = VEC_index (vn_reference_op_s,
1189                          PRE_EXPR_REFERENCE (e)->operands,
1190                          0);
1191         /* We don't store type along with COMPONENT_REF because it is
1192            always the same as FIELD_DECL's type.  */
1193         if (!vro->type)
1194           {
1195             gcc_assert (vro->opcode == COMPONENT_REF);
1196             return TREE_TYPE (vro->op0);
1197           }
1198         return vro->type;
1199       }
1200
1201     case NARY:
1202       return PRE_EXPR_NARY (e)->type;
1203     }
1204   gcc_unreachable();
1205 }
1206
1207 /* Get a representative SSA_NAME for a given expression.
1208    Since all of our sub-expressions are treated as values, we require
1209    them to be SSA_NAME's for simplicity.
1210    Prior versions of GVNPRE used to use "value handles" here, so that
1211    an expression would be VH.11 + VH.10 instead of d_3 + e_6.  In
1212    either case, the operands are really values (IE we do not expect
1213    them to be usable without finding leaders).  */
1214
1215 static tree
1216 get_representative_for (const pre_expr e)
1217 {
1218   tree exprtype;
1219   tree name;
1220   unsigned int value_id = get_expr_value_id (e);
1221
1222   switch (e->kind)
1223     {
1224     case NAME:
1225       return PRE_EXPR_NAME (e);
1226     case CONSTANT:
1227     case NARY:
1228     case REFERENCE:
1229       {
1230         /* Go through all of the expressions representing this value
1231            and pick out an SSA_NAME.  */
1232         unsigned int i;
1233         bitmap_iterator bi;
1234         bitmap_set_t exprs = VEC_index (bitmap_set_t, value_expressions,
1235                                         value_id);
1236         FOR_EACH_EXPR_ID_IN_SET (exprs, i, bi)
1237           {
1238             pre_expr rep = expression_for_id (i);
1239             if (rep->kind == NAME)
1240               return PRE_EXPR_NAME (rep);
1241           }
1242       }
1243       break;
1244     }
1245   /* If we reached here we couldn't find an SSA_NAME.  This can
1246      happen when we've discovered a value that has never appeared in
1247      the program as set to an SSA_NAME, most likely as the result of
1248      phi translation.  */
1249   if (dump_file)
1250     {
1251       fprintf (dump_file,
1252                "Could not find SSA_NAME representative for expression:");
1253       print_pre_expr (dump_file, e);
1254       fprintf (dump_file, "\n");
1255     }
1256
1257   exprtype = get_expr_type (e);
1258
1259   /* Build and insert the assignment of the end result to the temporary
1260      that we will return.  */
1261   if (!pretemp || exprtype != TREE_TYPE (pretemp))
1262     {
1263       pretemp = create_tmp_var (exprtype, "pretmp");
1264       get_var_ann (pretemp);
1265     }
1266
1267   name = make_ssa_name (pretemp, build_empty_stmt ());
1268   VN_INFO_GET (name)->value_id = value_id;
1269   if (e->kind == CONSTANT)
1270     VN_INFO (name)->valnum = PRE_EXPR_CONSTANT (e);
1271   else
1272     VN_INFO (name)->valnum = name;
1273
1274   add_to_value (value_id, get_or_alloc_expr_for_name (name));
1275   if (dump_file)
1276     {
1277       fprintf (dump_file, "Created SSA_NAME representative ");
1278       print_generic_expr (dump_file, name, 0);
1279       fprintf (dump_file, " for expression:");
1280       print_pre_expr (dump_file, e);
1281       fprintf (dump_file, "\n");
1282     }
1283
1284   return name;
1285 }
1286
1287
1288
1289
1290 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1291    the phis in PRED.  SEEN is a bitmap saying which expression we have
1292    translated since we started translation of the toplevel expression.
1293    Return NULL if we can't find a leader for each part of the
1294    translated expression.  */
1295
1296 static pre_expr
1297 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1298                  basic_block pred, basic_block phiblock, bitmap seen)
1299 {
1300   pre_expr oldexpr = expr;
1301   pre_expr phitrans;
1302
1303   if (!expr)
1304     return NULL;
1305
1306   if (value_id_constant_p (get_expr_value_id (expr)))
1307     return expr;
1308
1309   phitrans = phi_trans_lookup (expr, pred);
1310   if (phitrans)
1311     return phitrans;
1312
1313   /* Prevent cycles when we have recursively dependent leaders.  This
1314      can only happen when phi translating the maximal set.  */
1315   if (seen)
1316     {
1317       unsigned int expr_id = get_expression_id (expr);
1318       if (bitmap_bit_p (seen, expr_id))
1319         return NULL;
1320       bitmap_set_bit (seen, expr_id);
1321     }
1322
1323   switch (expr->kind)
1324     {
1325       /* Constants contain no values that need translation.  */
1326     case CONSTANT:
1327       return expr;
1328
1329     case NARY:
1330       {
1331         unsigned int i;
1332         bool changed = false;
1333         vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1334         struct vn_nary_op_s newnary;
1335         /* The NARY structure is only guaranteed to have been
1336            allocated to the nary->length operands.  */
1337         memcpy (&newnary, nary, (sizeof (struct vn_nary_op_s)
1338                                  - sizeof (tree) * (4 - nary->length)));
1339
1340         for (i = 0; i < newnary.length; i++)
1341           {
1342             if (TREE_CODE (newnary.op[i]) != SSA_NAME)
1343               continue;
1344             else
1345               {
1346                 unsigned int op_val_id = VN_INFO (newnary.op[i])->value_id;
1347                 pre_expr leader = find_leader_in_sets (op_val_id, set1, set2);
1348                 pre_expr result = phi_translate_1 (leader, set1, set2,
1349                                                    pred, phiblock, seen);
1350                 if (result && result != leader)
1351                   {
1352                     tree name = get_representative_for (result);
1353                     if (!name)
1354                       return NULL;
1355                     newnary.op[i] = name;
1356                   }
1357                 else if (!result)
1358                   return NULL;
1359
1360                 changed |= newnary.op[i] != nary->op[i];
1361               }
1362           }
1363         if (changed)
1364           {
1365             pre_expr constant;
1366
1367             tree result = vn_nary_op_lookup_pieces (newnary.length,
1368                                                     newnary.opcode,
1369                                                     newnary.type,
1370                                                     newnary.op[0],
1371                                                     newnary.op[1],
1372                                                     newnary.op[2],
1373                                                     newnary.op[3],
1374                                                     &nary);
1375             unsigned int new_val_id;
1376
1377             expr = (pre_expr) pool_alloc (pre_expr_pool);
1378             expr->kind = NARY;
1379             expr->id = 0;
1380             if (result && is_gimple_min_invariant (result))
1381               return get_or_alloc_expr_for_constant (result);
1382
1383
1384             if (nary)
1385               {
1386                 PRE_EXPR_NARY (expr) = nary;
1387                 constant = fully_constant_expression (expr);
1388                 if (constant != expr)
1389                   return constant;
1390
1391                 new_val_id = nary->value_id;
1392                 get_or_alloc_expression_id (expr);
1393               }
1394             else
1395               {
1396                 new_val_id = get_next_value_id ();
1397                 VEC_safe_grow_cleared (bitmap_set_t, heap,
1398                                        value_expressions,
1399                                        get_max_value_id() + 1);
1400                 nary = vn_nary_op_insert_pieces (newnary.length,
1401                                                  newnary.opcode,
1402                                                  newnary.type,
1403                                                  newnary.op[0],
1404                                                  newnary.op[1],
1405                                                  newnary.op[2],
1406                                                  newnary.op[3],
1407                                                  result, new_val_id);
1408                 PRE_EXPR_NARY (expr) = nary;
1409                 constant = fully_constant_expression (expr);
1410                 if (constant != expr)
1411                   return constant;
1412                 get_or_alloc_expression_id (expr);
1413               }
1414             add_to_value (new_val_id, expr);
1415           }
1416         phi_trans_add (oldexpr, expr, pred);
1417         return expr;
1418       }
1419       break;
1420     case REFERENCE:
1421       {
1422         vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1423         VEC (vn_reference_op_s, heap) *operands = ref->operands;
1424         VEC (tree, gc) *vuses = ref->vuses;
1425         VEC (tree, gc) *newvuses = vuses;
1426         VEC (vn_reference_op_s, heap) *newoperands = NULL;
1427         bool changed = false;
1428         unsigned int i;
1429         vn_reference_op_t operand;
1430         vn_reference_t newref;
1431
1432         for (i = 0; VEC_iterate (vn_reference_op_s, operands, i, operand); i++)
1433           {
1434             pre_expr opresult;
1435             pre_expr leader;
1436             tree oldop0 = operand->op0;
1437             tree oldop1 = operand->op1;
1438             tree oldop2 = operand->op2;
1439             tree op0 = oldop0;
1440             tree op1 = oldop1;
1441             tree op2 = oldop2;
1442             tree type = operand->type;
1443             vn_reference_op_s newop = *operand;
1444
1445             if (op0 && TREE_CODE (op0) == SSA_NAME)
1446               {
1447                 unsigned int op_val_id = VN_INFO (op0)->value_id;
1448                 leader = find_leader_in_sets (op_val_id, set1, set2);
1449                 opresult = phi_translate_1 (leader, set1, set2,
1450                                             pred, phiblock, seen);
1451                 if (opresult && opresult != leader)
1452                   {
1453                     tree name = get_representative_for (opresult);
1454                     if (!name)
1455                       return NULL;
1456                     op0 = name;
1457                   }
1458                 else if (!opresult)
1459                   return NULL;
1460               }
1461             changed |= op0 != oldop0;
1462
1463             if (op1 && TREE_CODE (op1) == SSA_NAME)
1464               {
1465                 unsigned int op_val_id = VN_INFO (op1)->value_id;
1466                 leader = find_leader_in_sets (op_val_id, set1, set2);
1467                 opresult = phi_translate_1 (leader, set1, set2,
1468                                             pred, phiblock, seen);
1469                 if (opresult && opresult != leader)
1470                   {
1471                     tree name = get_representative_for (opresult);
1472                     if (!name)
1473                       return NULL;
1474                     op1 = name;
1475                   }
1476                 else if (!opresult)
1477                   return NULL;
1478               }
1479             changed |= op1 != oldop1;
1480             if (op2 && TREE_CODE (op2) == SSA_NAME)
1481               {
1482                 unsigned int op_val_id = VN_INFO (op2)->value_id;
1483                 leader = find_leader_in_sets (op_val_id, set1, set2);
1484                 opresult = phi_translate_1 (leader, set1, set2,
1485                                             pred, phiblock, seen);
1486                 if (opresult && opresult != leader)
1487                   {
1488                     tree name = get_representative_for (opresult);
1489                     if (!name)
1490                       return NULL;
1491                     op2 = name;
1492                   }
1493                 else if (!opresult)
1494                   return NULL;
1495               }
1496             changed |= op2 != oldop2;
1497
1498             if (!newoperands)
1499               newoperands = VEC_copy (vn_reference_op_s, heap, operands);
1500             /* We may have changed from an SSA_NAME to a constant */
1501             if (newop.opcode == SSA_NAME && TREE_CODE (op0) != SSA_NAME)
1502               newop.opcode = TREE_CODE (op0);
1503             newop.type = type;
1504             newop.op0 = op0;
1505             newop.op1 = op1;
1506             newop.op2 = op2;
1507             VEC_replace (vn_reference_op_s, newoperands, i, &newop);
1508           }
1509
1510         newvuses = translate_vuses_through_block (vuses, phiblock, pred);
1511         changed |= newvuses != vuses;
1512
1513         if (changed)
1514           {
1515             tree result = vn_reference_lookup_pieces (newvuses,
1516                                                       newoperands,
1517                                                       &newref);
1518             unsigned int new_val_id;
1519
1520             if (newref)
1521               VEC_free (vn_reference_op_s, heap, newoperands);
1522
1523             if (result && is_gimple_min_invariant (result))
1524               return get_or_alloc_expr_for_constant (result);
1525
1526             expr = (pre_expr) pool_alloc (pre_expr_pool);
1527             expr->kind = REFERENCE;
1528             expr->id = 0;
1529
1530             if (newref)
1531               {
1532                 PRE_EXPR_REFERENCE (expr) = newref;
1533                 new_val_id = newref->value_id;
1534                 get_or_alloc_expression_id (expr);
1535               }
1536             else
1537               {
1538                 new_val_id = get_next_value_id ();
1539                 VEC_safe_grow_cleared (bitmap_set_t, heap, value_expressions,
1540                                        get_max_value_id() + 1);
1541                 newref = vn_reference_insert_pieces (newvuses,
1542                                                      newoperands,
1543                                                      result, new_val_id);
1544                 PRE_EXPR_REFERENCE (expr) = newref;
1545                 get_or_alloc_expression_id (expr);
1546               }
1547             add_to_value (new_val_id, expr);
1548           }
1549         phi_trans_add (oldexpr, expr, pred);
1550         return expr;
1551       }
1552       break;
1553     case NAME:
1554       {
1555         tree phi = NULL;
1556         edge e;
1557         tree def_stmt;
1558         tree name = PRE_EXPR_NAME (expr);
1559
1560         def_stmt = SSA_NAME_DEF_STMT (name);
1561         if (TREE_CODE (def_stmt) == PHI_NODE
1562             && bb_for_stmt (def_stmt) == phiblock)
1563           phi = def_stmt;
1564         else
1565           return expr;
1566
1567         e = find_edge (pred, bb_for_stmt (phi));
1568         if (e)
1569           {
1570             tree def = PHI_ARG_DEF (phi, e->dest_idx);
1571             pre_expr newexpr;
1572
1573             /* Handle constant. */
1574             if (is_gimple_min_invariant (def))
1575               return get_or_alloc_expr_for_constant (def);
1576
1577             if (TREE_CODE (def) == SSA_NAME && ssa_undefined_value_p (def))
1578               return NULL;
1579
1580             newexpr = get_or_alloc_expr_for_name (def);
1581             return newexpr;
1582           }
1583       }
1584       return expr;
1585
1586     default:
1587       gcc_unreachable ();
1588     }
1589 }
1590
1591 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1592    the phis in PRED.
1593    Return NULL if we can't find a leader for each part of the
1594    translated expression.  */
1595
1596 static pre_expr
1597 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1598                basic_block pred, basic_block phiblock)
1599 {
1600   bitmap_clear (seen_during_translate);
1601   return phi_translate_1 (expr, set1, set2, pred, phiblock,
1602                           seen_during_translate);
1603 }
1604
1605 /* For each expression in SET, translate the values through phi nodes
1606    in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1607    expressions in DEST.  */
1608
1609 static void
1610 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1611                    basic_block phiblock)
1612 {
1613   VEC (pre_expr, heap) *exprs;
1614   pre_expr expr;
1615   int i;
1616
1617   if (!phi_nodes (phiblock))
1618     {
1619       bitmap_set_copy (dest, set);
1620       return;
1621     }
1622
1623   exprs = sorted_array_from_bitmap_set (set);
1624   for (i = 0; VEC_iterate (pre_expr, exprs, i, expr); i++)
1625     {
1626       pre_expr translated;
1627       translated = phi_translate (expr, set, NULL, pred, phiblock);
1628
1629       /* Don't add constants or empty translations to the cache, since
1630          we won't look them up that way, or use the result, anyway.  */
1631       if (translated && !value_id_constant_p (get_expr_value_id (translated)))
1632         phi_trans_add (expr, translated, pred);
1633
1634       if (translated != NULL)
1635         bitmap_value_insert_into_set (dest, translated);
1636     }
1637   VEC_free (pre_expr, heap, exprs);
1638 }
1639
1640 /* Find the leader for a value (i.e., the name representing that
1641    value) in a given set, and return it.  If STMT is non-NULL it
1642    makes sure the defining statement for the leader dominates it.
1643    Return NULL if no leader is found.  */
1644
1645 static pre_expr
1646 bitmap_find_leader (bitmap_set_t set, unsigned int val, tree stmt)
1647 {
1648   if (value_id_constant_p (val))
1649     {
1650       unsigned int i;
1651       bitmap_iterator bi;
1652       bitmap_set_t exprset = VEC_index (bitmap_set_t, value_expressions, val);
1653
1654       FOR_EACH_EXPR_ID_IN_SET (exprset, i, bi)
1655         {
1656           pre_expr expr = expression_for_id (i);
1657           if (expr->kind == CONSTANT)
1658             return expr;
1659         }
1660     }
1661   if (bitmap_set_contains_value (set, val))
1662     {
1663       /* Rather than walk the entire bitmap of expressions, and see
1664          whether any of them has the value we are looking for, we look
1665          at the reverse mapping, which tells us the set of expressions
1666          that have a given value (IE value->expressions with that
1667          value) and see if any of those expressions are in our set.
1668          The number of expressions per value is usually significantly
1669          less than the number of expressions in the set.  In fact, for
1670          large testcases, doing it this way is roughly 5-10x faster
1671          than walking the bitmap.
1672          If this is somehow a significant lose for some cases, we can
1673          choose which set to walk based on which set is smaller.  */
1674       unsigned int i;
1675       bitmap_iterator bi;
1676       bitmap_set_t exprset = VEC_index (bitmap_set_t, value_expressions, val);
1677
1678       EXECUTE_IF_AND_IN_BITMAP (exprset->expressions,
1679                                 set->expressions, 0, i, bi)
1680         {
1681           pre_expr val = expression_for_id (i);
1682           /* At the point where stmt is not null, there should always
1683              be an SSA_NAME first in the list of expressions.  */
1684           if (stmt)
1685             {
1686               tree def_stmt = SSA_NAME_DEF_STMT (PRE_EXPR_NAME (val));
1687               if (TREE_CODE (def_stmt) != PHI_NODE
1688                   && bb_for_stmt (def_stmt) == bb_for_stmt (stmt)
1689                   && stmt_ann (def_stmt)->uid >= stmt_ann (stmt)->uid)
1690                 continue;
1691             }
1692           return val;
1693         }
1694     }
1695   return NULL;
1696 }
1697
1698 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1699    BLOCK by seeing if it is not killed in the block.  Note that we are
1700    only determining whether there is a store that kills it.  Because
1701    of the order in which clean iterates over values, we are guaranteed
1702    that altered operands will have caused us to be eliminated from the
1703    ANTIC_IN set already.  */
1704
1705 static bool
1706 value_dies_in_block_x (pre_expr expr, basic_block block)
1707 {
1708   int i;
1709   tree vuse;
1710   VEC (tree, gc) *vuses = PRE_EXPR_REFERENCE (expr)->vuses;
1711
1712   /* Conservatively, a value dies if it's vuses are defined in this
1713      block, unless they come from phi nodes (which are merge operations,
1714      rather than stores.  */
1715   for (i = 0; VEC_iterate (tree, vuses, i, vuse); i++)
1716     {
1717       tree def = SSA_NAME_DEF_STMT (vuse);
1718
1719       if (bb_for_stmt (def) != block)
1720         continue;
1721       if (TREE_CODE (def) == PHI_NODE)
1722         continue;
1723       return true;
1724     }
1725   return false;
1726 }
1727
1728
1729 #define union_contains_value(SET1, SET2, VAL)                   \
1730   (bitmap_set_contains_value ((SET1), (VAL))                    \
1731    || ((SET2) && bitmap_set_contains_value ((SET2), (VAL))))
1732
1733 /* Determine if vn_reference_op_t VRO is legal in SET1 U SET2.
1734  */
1735 static bool
1736 vro_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2,
1737                    vn_reference_op_t vro)
1738 {
1739   if (vro->op0 && TREE_CODE (vro->op0) == SSA_NAME)
1740     {
1741       struct pre_expr_d temp;
1742       temp.kind = NAME;
1743       temp.id = 0;
1744       PRE_EXPR_NAME (&temp) = vro->op0;
1745       temp.id = lookup_expression_id (&temp);
1746       if (temp.id == 0)
1747         return false;
1748       if (!union_contains_value (set1, set2,
1749                                  get_expr_value_id (&temp)))
1750         return false;
1751     }
1752   if (vro->op1 && TREE_CODE (vro->op1) == SSA_NAME)
1753     {
1754       struct pre_expr_d temp;
1755       temp.kind = NAME;
1756       temp.id = 0;
1757       PRE_EXPR_NAME (&temp) = vro->op1;
1758       temp.id = lookup_expression_id (&temp);
1759       if (temp.id == 0)
1760         return false;
1761       if (!union_contains_value (set1, set2,
1762                                  get_expr_value_id (&temp)))
1763         return false;
1764     }
1765
1766   if (vro->op2 && TREE_CODE (vro->op2) == SSA_NAME)
1767     {
1768       struct pre_expr_d temp;
1769       temp.kind = NAME;
1770       temp.id = 0;
1771       PRE_EXPR_NAME (&temp) = vro->op2;
1772       temp.id = lookup_expression_id (&temp);
1773       if (temp.id == 0)
1774         return false;
1775       if (!union_contains_value (set1, set2,
1776                                  get_expr_value_id (&temp)))
1777         return false;
1778     }
1779
1780   return true;
1781 }
1782
1783 /* Determine if the expression EXPR is valid in SET1 U SET2.
1784    ONLY SET2 CAN BE NULL.
1785    This means that we have a leader for each part of the expression
1786    (if it consists of values), or the expression is an SSA_NAME.
1787    For loads/calls, we also see if the vuses are killed in this block.
1788 */
1789
1790 static bool
1791 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr,
1792                basic_block block)
1793 {
1794   switch (expr->kind)
1795     {
1796     case NAME:
1797       return bitmap_set_contains_expr (AVAIL_OUT (block), expr);
1798     case NARY:
1799       {
1800         unsigned int i;
1801         vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1802         for (i = 0; i < nary->length; i++)
1803           {
1804             if (TREE_CODE (nary->op[i]) == SSA_NAME)
1805               {
1806                 struct pre_expr_d temp;
1807                 temp.kind = NAME;
1808                 temp.id = 0;
1809                 PRE_EXPR_NAME (&temp) = nary->op[i];
1810                 temp.id = lookup_expression_id (&temp);
1811                 if (temp.id == 0)
1812                   return false;
1813                 if (!union_contains_value (set1, set2,
1814                                            get_expr_value_id (&temp)))
1815                   return false;
1816               }
1817           }
1818         return true;
1819       }
1820       break;
1821     case REFERENCE:
1822       {
1823         vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1824         vn_reference_op_t vro;
1825         unsigned int i;
1826
1827         for (i = 0; VEC_iterate (vn_reference_op_s, ref->operands, i, vro); i++)
1828           {
1829             if (!vro_valid_in_sets (set1, set2, vro))
1830               return false;
1831           }
1832         return !value_dies_in_block_x (expr, block);
1833       }
1834     default:
1835       gcc_unreachable ();
1836     }
1837 }
1838
1839 /* Clean the set of expressions that are no longer valid in SET1 or
1840    SET2.  This means expressions that are made up of values we have no
1841    leaders for in SET1 or SET2.  This version is used for partial
1842    anticipation, which means it is not valid in either ANTIC_IN or
1843    PA_IN.  */
1844
1845 static void
1846 dependent_clean (bitmap_set_t set1, bitmap_set_t set2, basic_block block)
1847 {
1848   VEC (pre_expr, heap) *exprs = sorted_array_from_bitmap_set (set1);
1849   pre_expr expr;
1850   int i;
1851
1852   for (i = 0; VEC_iterate (pre_expr, exprs, i, expr); i++)
1853     {
1854       if (!valid_in_sets (set1, set2, expr, block))
1855         bitmap_remove_from_set (set1, expr);
1856     }
1857   VEC_free (pre_expr, heap, exprs);
1858 }
1859
1860 /* Clean the set of expressions that are no longer valid in SET.  This
1861    means expressions that are made up of values we have no leaders for
1862    in SET.  */
1863
1864 static void
1865 clean (bitmap_set_t set, basic_block block)
1866 {
1867   VEC (pre_expr, heap) *exprs = sorted_array_from_bitmap_set (set);
1868   pre_expr expr;
1869   int i;
1870
1871   for (i = 0; VEC_iterate (pre_expr, exprs, i, expr); i++)
1872     {
1873       if (!valid_in_sets (set, NULL, expr, block))
1874         bitmap_remove_from_set (set, expr);
1875     }
1876   VEC_free (pre_expr, heap, exprs);
1877 }
1878
1879 static sbitmap has_abnormal_preds;
1880
1881 /* List of blocks that may have changed during ANTIC computation and
1882    thus need to be iterated over.  */
1883
1884 static sbitmap changed_blocks;
1885
1886 /* Decide whether to defer a block for a later iteration, or PHI
1887    translate SOURCE to DEST using phis in PHIBLOCK.  Return false if we
1888    should defer the block, and true if we processed it.  */
1889
1890 static bool
1891 defer_or_phi_translate_block (bitmap_set_t dest, bitmap_set_t source,
1892                               basic_block block, basic_block phiblock)
1893 {
1894   if (!BB_VISITED (phiblock))
1895     {
1896       SET_BIT (changed_blocks, block->index);
1897       BB_VISITED (block) = 0;
1898       BB_DEFERRED (block) = 1;
1899       return false;
1900     }
1901   else
1902     phi_translate_set (dest, source, block, phiblock);
1903   return true;
1904 }
1905
1906 /* Compute the ANTIC set for BLOCK.
1907
1908    If succs(BLOCK) > 1 then
1909      ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
1910    else if succs(BLOCK) == 1 then
1911      ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
1912
1913    ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
1914 */
1915
1916 static bool
1917 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
1918 {
1919   bool changed = false;
1920   bitmap_set_t S, old, ANTIC_OUT;
1921   bitmap_iterator bi;
1922   unsigned int bii;
1923   edge e;
1924   edge_iterator ei;
1925
1926   old = ANTIC_OUT = S = NULL;
1927   BB_VISITED (block) = 1;
1928
1929   /* If any edges from predecessors are abnormal, antic_in is empty,
1930      so do nothing.  */
1931   if (block_has_abnormal_pred_edge)
1932     goto maybe_dump_sets;
1933
1934   old = ANTIC_IN (block);
1935   ANTIC_OUT = bitmap_set_new ();
1936
1937   /* If the block has no successors, ANTIC_OUT is empty.  */
1938   if (EDGE_COUNT (block->succs) == 0)
1939     ;
1940   /* If we have one successor, we could have some phi nodes to
1941      translate through.  */
1942   else if (single_succ_p (block))
1943     {
1944       basic_block succ_bb = single_succ (block);
1945
1946       /* We trade iterations of the dataflow equations for having to
1947          phi translate the maximal set, which is incredibly slow
1948          (since the maximal set often has 300+ members, even when you
1949          have a small number of blocks).
1950          Basically, we defer the computation of ANTIC for this block
1951          until we have processed it's successor, which will inevitably
1952          have a *much* smaller set of values to phi translate once
1953          clean has been run on it.
1954          The cost of doing this is that we technically perform more
1955          iterations, however, they are lower cost iterations.
1956
1957          Timings for PRE on tramp3d-v4:
1958          without maximal set fix: 11 seconds
1959          with maximal set fix/without deferring: 26 seconds
1960          with maximal set fix/with deferring: 11 seconds
1961      */
1962
1963       if (!defer_or_phi_translate_block (ANTIC_OUT, ANTIC_IN (succ_bb),
1964                                         block, succ_bb))
1965         {
1966           changed = true;
1967           goto maybe_dump_sets;
1968         }
1969     }
1970   /* If we have multiple successors, we take the intersection of all of
1971      them.  Note that in the case of loop exit phi nodes, we may have
1972      phis to translate through.  */
1973   else
1974     {
1975       VEC(basic_block, heap) * worklist;
1976       size_t i;
1977       basic_block bprime, first;
1978
1979       worklist = VEC_alloc (basic_block, heap, EDGE_COUNT (block->succs));
1980       FOR_EACH_EDGE (e, ei, block->succs)
1981         VEC_quick_push (basic_block, worklist, e->dest);
1982       first = VEC_index (basic_block, worklist, 0);
1983
1984       if (phi_nodes (first))
1985         {
1986           bitmap_set_t from = ANTIC_IN (first);
1987
1988           if (!BB_VISITED (first))
1989             from = maximal_set;
1990           phi_translate_set (ANTIC_OUT, from, block, first);
1991         }
1992       else
1993         {
1994           if (!BB_VISITED (first))
1995             bitmap_set_copy (ANTIC_OUT, maximal_set);
1996           else
1997             bitmap_set_copy (ANTIC_OUT, ANTIC_IN (first));
1998         }
1999
2000       for (i = 1; VEC_iterate (basic_block, worklist, i, bprime); i++)
2001         {
2002           if (phi_nodes (bprime))
2003             {
2004               bitmap_set_t tmp = bitmap_set_new ();
2005               bitmap_set_t from = ANTIC_IN (bprime);
2006
2007               if (!BB_VISITED (bprime))
2008                 from = maximal_set;
2009               phi_translate_set (tmp, from, block, bprime);
2010               bitmap_set_and (ANTIC_OUT, tmp);
2011               bitmap_set_free (tmp);
2012             }
2013           else
2014             {
2015               if (!BB_VISITED (bprime))
2016                 bitmap_set_and (ANTIC_OUT, maximal_set);
2017               else
2018                 bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2019             }
2020         }
2021       VEC_free (basic_block, heap, worklist);
2022     }
2023
2024   /* Generate ANTIC_OUT - TMP_GEN.  */
2025   S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2026
2027   /* Start ANTIC_IN with EXP_GEN - TMP_GEN.  */
2028   ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2029                                           TMP_GEN (block));
2030
2031   /* Then union in the ANTIC_OUT - TMP_GEN values,
2032      to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2033   FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2034     bitmap_value_insert_into_set (ANTIC_IN (block),
2035                                   expression_for_id (bii));
2036
2037   clean (ANTIC_IN (block), block);
2038
2039   /* !old->expressions can happen when we deferred a block.  */
2040   if (!old->expressions || !bitmap_set_equal (old, ANTIC_IN (block)))
2041     {
2042       changed = true;
2043       SET_BIT (changed_blocks, block->index);
2044       FOR_EACH_EDGE (e, ei, block->preds)
2045         SET_BIT (changed_blocks, e->src->index);
2046     }
2047   else
2048     RESET_BIT (changed_blocks, block->index);
2049
2050  maybe_dump_sets:
2051   if (dump_file && (dump_flags & TDF_DETAILS))
2052     {
2053       if (!BB_DEFERRED (block) || BB_VISITED (block))
2054         {
2055           if (ANTIC_OUT)
2056             print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2057
2058           print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2059                             block->index);
2060
2061           if (S)
2062             print_bitmap_set (dump_file, S, "S", block->index);
2063         }
2064       else
2065         {
2066           fprintf (dump_file,
2067                    "Block %d was deferred for a future iteration.\n",
2068                    block->index);
2069         }
2070     }
2071   if (old)
2072     bitmap_set_free (old);
2073   if (S)
2074     bitmap_set_free (S);
2075   if (ANTIC_OUT)
2076     bitmap_set_free (ANTIC_OUT);
2077   return changed;
2078 }
2079
2080 /* Compute PARTIAL_ANTIC for BLOCK.
2081
2082    If succs(BLOCK) > 1 then
2083      PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2084      in ANTIC_OUT for all succ(BLOCK)
2085    else if succs(BLOCK) == 1 then
2086      PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2087
2088    PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2089                                   - ANTIC_IN[BLOCK])
2090
2091 */
2092 static bool
2093 compute_partial_antic_aux (basic_block block,
2094                            bool block_has_abnormal_pred_edge)
2095 {
2096   bool changed = false;
2097   bitmap_set_t old_PA_IN;
2098   bitmap_set_t PA_OUT;
2099   edge e;
2100   edge_iterator ei;
2101   unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2102
2103   old_PA_IN = PA_OUT = NULL;
2104
2105   /* If any edges from predecessors are abnormal, antic_in is empty,
2106      so do nothing.  */
2107   if (block_has_abnormal_pred_edge)
2108     goto maybe_dump_sets;
2109
2110   /* If there are too many partially anticipatable values in the
2111      block, phi_translate_set can take an exponential time: stop
2112      before the translation starts.  */
2113   if (max_pa
2114       && single_succ_p (block)
2115       && bitmap_count_bits (PA_IN (single_succ (block))->values) > max_pa)
2116     goto maybe_dump_sets;
2117
2118   old_PA_IN = PA_IN (block);
2119   PA_OUT = bitmap_set_new ();
2120
2121   /* If the block has no successors, ANTIC_OUT is empty.  */
2122   if (EDGE_COUNT (block->succs) == 0)
2123     ;
2124   /* If we have one successor, we could have some phi nodes to
2125      translate through.  Note that we can't phi translate across DFS
2126      back edges in partial antic, because it uses a union operation on
2127      the successors.  For recurrences like IV's, we will end up
2128      generating a new value in the set on each go around (i + 3 (VH.1)
2129      VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever.  */
2130   else if (single_succ_p (block))
2131     {
2132       basic_block succ = single_succ (block);
2133       if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2134         phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2135     }
2136   /* If we have multiple successors, we take the union of all of
2137      them.  */
2138   else
2139     {
2140       VEC(basic_block, heap) * worklist;
2141       size_t i;
2142       basic_block bprime;
2143
2144       worklist = VEC_alloc (basic_block, heap, EDGE_COUNT (block->succs));
2145       FOR_EACH_EDGE (e, ei, block->succs)
2146         {
2147           if (e->flags & EDGE_DFS_BACK)
2148             continue;
2149           VEC_quick_push (basic_block, worklist, e->dest);
2150         }
2151       if (VEC_length (basic_block, worklist) > 0)
2152         {
2153           for (i = 0; VEC_iterate (basic_block, worklist, i, bprime); i++)
2154             {
2155               unsigned int i;
2156               bitmap_iterator bi;
2157
2158               FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2159                 bitmap_value_insert_into_set (PA_OUT,
2160                                               expression_for_id (i));
2161               if (phi_nodes (bprime))
2162                 {
2163                   bitmap_set_t pa_in = bitmap_set_new ();
2164                   phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2165                   FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2166                     bitmap_value_insert_into_set (PA_OUT,
2167                                                   expression_for_id (i));
2168                   bitmap_set_free (pa_in);
2169                 }
2170               else
2171                 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2172                   bitmap_value_insert_into_set (PA_OUT,
2173                                                 expression_for_id (i));
2174             }
2175         }
2176       VEC_free (basic_block, heap, worklist);
2177     }
2178
2179   /* PA_IN starts with PA_OUT - TMP_GEN.
2180      Then we subtract things from ANTIC_IN.  */
2181   PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2182
2183   /* For partial antic, we want to put back in the phi results, since
2184      we will properly avoid making them partially antic over backedges.  */
2185   bitmap_ior_into (PA_IN (block)->values, PHI_GEN (block)->values);
2186   bitmap_ior_into (PA_IN (block)->expressions, PHI_GEN (block)->expressions);
2187
2188   /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2189   bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2190
2191   dependent_clean (PA_IN (block), ANTIC_IN (block), block);
2192
2193   if (!bitmap_set_equal (old_PA_IN, PA_IN (block)))
2194     {
2195       changed = true;
2196       SET_BIT (changed_blocks, block->index);
2197       FOR_EACH_EDGE (e, ei, block->preds)
2198         SET_BIT (changed_blocks, e->src->index);
2199     }
2200   else
2201     RESET_BIT (changed_blocks, block->index);
2202
2203  maybe_dump_sets:
2204   if (dump_file && (dump_flags & TDF_DETAILS))
2205     {
2206       if (PA_OUT)
2207         print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2208
2209       print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2210     }
2211   if (old_PA_IN)
2212     bitmap_set_free (old_PA_IN);
2213   if (PA_OUT)
2214     bitmap_set_free (PA_OUT);
2215   return changed;
2216 }
2217
2218 /* Compute ANTIC and partial ANTIC sets.  */
2219
2220 static void
2221 compute_antic (void)
2222 {
2223   bool changed = true;
2224   int num_iterations = 0;
2225   basic_block block;
2226   int i;
2227
2228   /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2229      We pre-build the map of blocks with incoming abnormal edges here.  */
2230   has_abnormal_preds = sbitmap_alloc (last_basic_block);
2231   sbitmap_zero (has_abnormal_preds);
2232
2233   FOR_EACH_BB (block)
2234     {
2235       edge_iterator ei;
2236       edge e;
2237
2238       FOR_EACH_EDGE (e, ei, block->preds)
2239         {
2240           e->flags &= ~EDGE_DFS_BACK;
2241           if (e->flags & EDGE_ABNORMAL)
2242             {
2243               SET_BIT (has_abnormal_preds, block->index);
2244               break;
2245             }
2246         }
2247
2248       BB_VISITED (block) = 0;
2249       BB_DEFERRED (block) = 0;
2250       /* While we are here, give empty ANTIC_IN sets to each block.  */
2251       ANTIC_IN (block) = bitmap_set_new ();
2252       PA_IN (block) = bitmap_set_new ();
2253     }
2254
2255   /* At the exit block we anticipate nothing.  */
2256   ANTIC_IN (EXIT_BLOCK_PTR) = bitmap_set_new ();
2257   BB_VISITED (EXIT_BLOCK_PTR) = 1;
2258   PA_IN (EXIT_BLOCK_PTR) = bitmap_set_new ();
2259
2260   changed_blocks = sbitmap_alloc (last_basic_block + 1);
2261   sbitmap_ones (changed_blocks);
2262   while (changed)
2263     {
2264       if (dump_file && (dump_flags & TDF_DETAILS))
2265         fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2266       num_iterations++;
2267       changed = false;
2268       for (i = 0; i < last_basic_block - NUM_FIXED_BLOCKS; i++)
2269         {
2270           if (TEST_BIT (changed_blocks, postorder[i]))
2271             {
2272               basic_block block = BASIC_BLOCK (postorder[i]);
2273               changed |= compute_antic_aux (block,
2274                                             TEST_BIT (has_abnormal_preds,
2275                                                       block->index));
2276             }
2277         }
2278 #ifdef ENABLE_CHECKING
2279       /* Theoretically possible, but *highly* unlikely.  */
2280       gcc_assert (num_iterations < 500);
2281 #endif
2282     }
2283
2284   statistics_histogram_event (cfun, "compute_antic iterations",
2285                               num_iterations);
2286
2287   if (do_partial_partial)
2288     {
2289       sbitmap_ones (changed_blocks);
2290       mark_dfs_back_edges ();
2291       num_iterations = 0;
2292       changed = true;
2293       while (changed)
2294         {
2295           if (dump_file && (dump_flags & TDF_DETAILS))
2296             fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2297           num_iterations++;
2298           changed = false;
2299           for (i = 0; i < last_basic_block - NUM_FIXED_BLOCKS; i++)
2300             {
2301               if (TEST_BIT (changed_blocks, postorder[i]))
2302                 {
2303                   basic_block block = BASIC_BLOCK (postorder[i]);
2304                   changed
2305                     |= compute_partial_antic_aux (block,
2306                                                   TEST_BIT (has_abnormal_preds,
2307                                                             block->index));
2308                 }
2309             }
2310 #ifdef ENABLE_CHECKING
2311           /* Theoretically possible, but *highly* unlikely.  */
2312           gcc_assert (num_iterations < 500);
2313 #endif
2314         }
2315       statistics_histogram_event (cfun, "compute_partial_antic iterations",
2316                                   num_iterations);
2317     }
2318   sbitmap_free (has_abnormal_preds);
2319   sbitmap_free (changed_blocks);
2320 }
2321
2322 /* Return true if we can value number the call in STMT.  This is true
2323    if we have a pure or constant call.  */
2324
2325 static bool
2326 can_value_number_call (tree stmt)
2327 {
2328   tree call = get_call_expr_in (stmt);
2329
2330   if (call_expr_flags (call) & (ECF_PURE | ECF_CONST))
2331     return true;
2332   return false;
2333 }
2334
2335 /* Return true if OP is an exception handler related operation, such as
2336    FILTER_EXPR or EXC_PTR_EXPR.  */
2337
2338 static bool
2339 is_exception_related (tree op)
2340 {
2341   return TREE_CODE (op) == FILTER_EXPR || TREE_CODE (op) == EXC_PTR_EXPR;
2342 }
2343
2344 /* Return true if OP is a tree which we can perform PRE on
2345    on.  This may not match the operations we can value number, but in
2346    a perfect world would.  */
2347
2348 static bool
2349 can_PRE_operation (tree op)
2350 {
2351   return UNARY_CLASS_P (op)
2352     || BINARY_CLASS_P (op)
2353     || COMPARISON_CLASS_P (op)
2354     || TREE_CODE (op) == INDIRECT_REF
2355     || TREE_CODE (op) == COMPONENT_REF
2356     || TREE_CODE (op) == VIEW_CONVERT_EXPR
2357     || TREE_CODE (op) == CALL_EXPR
2358     || TREE_CODE (op) == ARRAY_REF;
2359 }
2360
2361
2362 /* Inserted expressions are placed onto this worklist, which is used
2363    for performing quick dead code elimination of insertions we made
2364    that didn't turn out to be necessary.   */
2365 static VEC(tree,heap) *inserted_exprs;
2366
2367 /* Pool allocated fake store expressions are placed onto this
2368    worklist, which, after performing dead code elimination, is walked
2369    to see which expressions need to be put into GC'able memory  */
2370 static VEC(tree, heap) *need_creation;
2371
2372 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2373    COMPONENT_REF or INDIRECT_REF or ARRAY_REF portion, because we'd end up with
2374    trying to rename aggregates into ssa form directly, which is a no
2375    no.
2376
2377    Thus, this routine doesn't create temporaries, it just builds a
2378    single access expression for the array, calling
2379    find_or_generate_expression to build the innermost pieces.
2380
2381    This function is a subroutine of create_expression_by_pieces, and
2382    should not be called on it's own unless you really know what you
2383    are doing.
2384 */
2385 static tree
2386 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2387                                 unsigned int operand,
2388                                 tree stmts,
2389                                 tree domstmt,
2390                                 bool in_call)
2391 {
2392   vn_reference_op_t currop = VEC_index (vn_reference_op_s, ref->operands,
2393                                         operand);
2394   tree genop;
2395   switch (currop->opcode)
2396     {
2397     case CALL_EXPR:
2398       {
2399         tree folded;
2400         unsigned int i;
2401         vn_reference_op_t declop = VEC_index (vn_reference_op_s,
2402                                               ref->operands, 1);
2403         unsigned int nargs = VEC_length (vn_reference_op_s, ref->operands) - 2;
2404         tree *args = XNEWVEC (tree, nargs);
2405
2406         for (i = 0; i < nargs; i++)
2407           {
2408             args[i] = create_component_ref_by_pieces (block, ref,
2409                                                       operand + 2 + i, stmts,
2410                                                       domstmt, true);
2411           }
2412         folded = build_call_array (currop->type, declop->op0, nargs, args);
2413         free (args);
2414         return folded;
2415       }
2416       break;
2417     case REALPART_EXPR:
2418     case IMAGPART_EXPR:
2419     case VIEW_CONVERT_EXPR:
2420       {
2421         tree folded;
2422         tree genop0 = create_component_ref_by_pieces (block, ref,
2423                                                       operand + 1,
2424                                                       stmts, domstmt,
2425                                                       in_call);
2426         if (!genop0)
2427           return NULL_TREE;
2428         folded = fold_build1 (currop->opcode, currop->type,
2429                               genop0);
2430         return folded;
2431       }
2432       break;
2433     case ALIGN_INDIRECT_REF:
2434     case MISALIGNED_INDIRECT_REF:
2435     case INDIRECT_REF:
2436       {
2437         /* Inside a CALL_EXPR op0 is the actual indirect_ref.  */
2438         if (in_call)
2439           {
2440             tree folded;
2441             tree op0 = TREE_OPERAND (currop->op0, 0);
2442             pre_expr op0expr = get_or_alloc_expr_for (op0);
2443             tree genop0 = find_or_generate_expression (block, op0expr, stmts,
2444                                                        domstmt);
2445             if (!genop0)
2446               return NULL_TREE;
2447             folded = fold_build1 (currop->opcode, currop->type,
2448                                   genop0);
2449             return folded;
2450           }
2451         else
2452           {
2453
2454             tree folded;
2455             tree genop1 = create_component_ref_by_pieces (block, ref,
2456                                                           operand + 1,
2457                                                           stmts, domstmt,
2458                                                           in_call);
2459             if (!genop1)
2460               return NULL_TREE;
2461             genop1 = fold_convert (build_pointer_type (currop->type),
2462                                    genop1);
2463
2464             folded = fold_build1 (currop->opcode, currop->type,
2465                                   genop1);
2466             return folded;
2467           }
2468       }
2469       break;
2470     case BIT_FIELD_REF:
2471       {
2472         tree folded;
2473         tree genop0 = create_component_ref_by_pieces (block, ref, operand + 1,
2474                                                       stmts, domstmt,
2475                                                       in_call);
2476         pre_expr op1expr = get_or_alloc_expr_for (currop->op0);
2477         pre_expr op2expr = get_or_alloc_expr_for (currop->op1);
2478         tree genop1;
2479         tree genop2;
2480
2481         if (!genop0)
2482           return NULL_TREE;
2483         genop1 = find_or_generate_expression (block, op1expr, stmts, domstmt);
2484         if (!genop1)
2485           return NULL_TREE;
2486         genop2 = find_or_generate_expression (block, op2expr, stmts, domstmt);
2487         if (!genop2)
2488           return NULL_TREE;
2489         folded = fold_build3 (BIT_FIELD_REF, currop->type, genop0, genop1,
2490                               genop2);
2491         return folded;
2492       }
2493
2494       /* For array ref vn_reference_op's, operand 1 of the array ref
2495          is op0 of the reference op and operand 3 of the array ref is
2496          op1.  */
2497     case ARRAY_RANGE_REF:
2498     case ARRAY_REF:
2499       {
2500         vn_reference_op_t op0expr;
2501         tree genop0;
2502         tree genop1 = currop->op0;
2503         pre_expr op1expr;
2504         tree genop2 = currop->op1;
2505         pre_expr op2expr;
2506         tree genop3;
2507         op0expr = VEC_index (vn_reference_op_s, ref->operands, operand + 1);
2508         genop0 = create_component_ref_by_pieces (block, ref, operand + 1,
2509                                                  stmts, domstmt,
2510                                                  in_call);
2511         if (!genop0)
2512           return NULL_TREE;
2513         op1expr = get_or_alloc_expr_for (genop1);
2514         genop1 = find_or_generate_expression (block, op1expr, stmts, domstmt);
2515         if (!genop1)
2516           return NULL_TREE;
2517         if (genop2)
2518           {
2519             op2expr = get_or_alloc_expr_for (genop2);
2520             genop2 = find_or_generate_expression (block, op2expr, stmts,
2521                                                   domstmt);
2522             if (!genop2)
2523               return NULL_TREE;
2524           }
2525
2526         genop3 = currop->op2;
2527         return build4 (currop->opcode, currop->type, genop0, genop1,
2528                        genop2, genop3);
2529       }
2530     case COMPONENT_REF:
2531       {
2532         tree op0;
2533         tree op1;
2534         tree genop2 = currop->op1;
2535         pre_expr op2expr;
2536         op0 = create_component_ref_by_pieces (block, ref, operand + 1,
2537                                               stmts, domstmt, in_call);
2538         if (!op0)
2539           return NULL_TREE;
2540         /* op1 should be a FIELD_DECL, which are represented by
2541            themselves.  */
2542         op1 = currop->op0;
2543         if (genop2)
2544           {
2545             op2expr = get_or_alloc_expr_for (genop2);
2546             genop2 = find_or_generate_expression (block, op2expr, stmts,
2547                                                   domstmt);
2548             if (!genop2)
2549               return NULL_TREE;
2550           }
2551
2552         return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1,
2553                             genop2);
2554       }
2555       break;
2556     case SSA_NAME:
2557       {
2558         pre_expr op0expr = get_or_alloc_expr_for (currop->op0);
2559         genop = find_or_generate_expression (block, op0expr, stmts, domstmt);
2560         return genop;
2561       }
2562     case STRING_CST:
2563     case INTEGER_CST:
2564     case COMPLEX_CST:
2565     case VECTOR_CST:
2566     case REAL_CST:
2567     case CONSTRUCTOR:
2568     case VAR_DECL:
2569     case PARM_DECL:
2570     case CONST_DECL:
2571     case RESULT_DECL:
2572     case FUNCTION_DECL:
2573       /* For ADDR_EXPR in a CALL_EXPR, op0 is actually the entire
2574          ADDR_EXPR, not just it's operand.  */
2575     case ADDR_EXPR:
2576       if (currop->opcode == ADDR_EXPR)
2577         gcc_assert (currop->op0 != NULL);
2578       return currop->op0;
2579
2580     default:
2581       gcc_unreachable ();
2582     }
2583 }
2584
2585 /* Find a leader for an expression, or generate one using
2586    create_expression_by_pieces if it's ANTIC but
2587    complex.
2588    BLOCK is the basic_block we are looking for leaders in.
2589    EXPR is the expression to find a leader or generate for.
2590    STMTS is the statement list to put the inserted expressions on.
2591    Returns the SSA_NAME of the LHS of the generated expression or the
2592    leader.
2593    DOMSTMT if non-NULL is a statement that should be dominated by
2594    all uses in the generated expression.  If DOMSTMT is non-NULL this
2595    routine can fail and return NULL_TREE.  Otherwise it will assert
2596    on failure.  */
2597
2598 static tree
2599 find_or_generate_expression (basic_block block, pre_expr expr, tree stmts,
2600                              tree domstmt)
2601 {
2602   pre_expr leader = bitmap_find_leader (AVAIL_OUT (block),
2603                                         get_expr_value_id (expr), domstmt);
2604   tree genop = NULL;
2605   if (leader)
2606     {
2607       if (leader->kind == NAME)
2608         genop = PRE_EXPR_NAME (leader);
2609       else if (leader->kind == CONSTANT)
2610         genop = PRE_EXPR_CONSTANT (leader);
2611     }
2612
2613   /* If it's still NULL, it must be a complex expression, so generate
2614      it recursively.  */
2615   if (genop == NULL)
2616     {
2617       bitmap_set_t exprset;
2618       unsigned int lookfor = get_expr_value_id (expr);
2619       bool handled = false;
2620       bitmap_iterator bi;
2621       unsigned int i;
2622
2623       exprset = VEC_index (bitmap_set_t, value_expressions, lookfor);
2624       FOR_EACH_EXPR_ID_IN_SET (exprset, i, bi)
2625         {
2626           pre_expr temp = expression_for_id (i);
2627           if (temp->kind != NAME)
2628             {
2629               handled = true;
2630               genop = create_expression_by_pieces (block, temp, stmts,
2631                                                    domstmt,
2632                                                    get_expr_type (expr));
2633               break;
2634             }
2635         }
2636       if (!handled && domstmt)
2637         return NULL_TREE;
2638
2639       gcc_assert (handled);
2640     }
2641   return genop;
2642 }
2643
2644 #define NECESSARY(stmt)         stmt->base.asm_written_flag
2645
2646 /* Create an expression in pieces, so that we can handle very complex
2647    expressions that may be ANTIC, but not necessary GIMPLE.
2648    BLOCK is the basic block the expression will be inserted into,
2649    EXPR is the expression to insert (in value form)
2650    STMTS is a statement list to append the necessary insertions into.
2651
2652    This function will die if we hit some value that shouldn't be
2653    ANTIC but is (IE there is no leader for it, or its components).
2654    This function may also generate expressions that are themselves
2655    partially or fully redundant.  Those that are will be either made
2656    fully redundant during the next iteration of insert (for partially
2657    redundant ones), or eliminated by eliminate (for fully redundant
2658    ones).
2659
2660    If DOMSTMT is non-NULL then we make sure that all uses in the
2661    expressions dominate that statement.  In this case the function
2662    can return NULL_TREE to signal failure.  */
2663
2664 static tree
2665 create_expression_by_pieces (basic_block block, pre_expr expr, tree stmts,
2666                              tree domstmt,
2667                              tree type)
2668 {
2669   tree temp, name;
2670   tree folded, forced_stmts, newexpr;
2671   unsigned int value_id;
2672   tree_stmt_iterator tsi;
2673   tree exprtype = type ? type : get_expr_type (expr);
2674   pre_expr nameexpr;
2675
2676   switch (expr->kind)
2677     {
2678       /* We may hit the NAME/CONSTANT case if we have to convert types
2679          that value numbering saw through.  */
2680     case NAME:
2681       folded = PRE_EXPR_NAME (expr);
2682       break;
2683     case CONSTANT:
2684       folded = PRE_EXPR_CONSTANT (expr);
2685       break;
2686     case REFERENCE:
2687       {
2688         vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2689         folded = create_component_ref_by_pieces (block, ref, 0, stmts,
2690                                                  domstmt, false);
2691       }
2692       break;
2693     case NARY:
2694       {
2695         vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2696         switch (nary->length)
2697           {
2698           case 2:
2699             {
2700               pre_expr op1 = get_or_alloc_expr_for (nary->op[0]);
2701               pre_expr op2 = get_or_alloc_expr_for (nary->op[1]);
2702               tree genop1 = find_or_generate_expression (block, op1,
2703                                                          stmts, domstmt);
2704               tree genop2 = find_or_generate_expression (block, op2,
2705                                                          stmts, domstmt);
2706               if (!genop1 || !genop2)
2707                 return NULL_TREE;
2708               genop1 = fold_convert (TREE_TYPE (nary->op[0]),
2709                                      genop1);
2710               /* Ensure op2 is a sizetype for POINTER_PLUS_EXPR.  It
2711                  may be a constant with the wrong type.  */
2712               if (nary->opcode == POINTER_PLUS_EXPR)
2713                 genop2 = fold_convert (sizetype, genop2);
2714               else
2715                 genop2 = fold_convert (TREE_TYPE (nary->op[1]), genop2);
2716               
2717               folded = fold_build2 (nary->opcode, nary->type,
2718                                     genop1, genop2);
2719             }
2720             break;
2721           case 1:
2722             {
2723               pre_expr op1 = get_or_alloc_expr_for (nary->op[0]);
2724               tree genop1 = find_or_generate_expression (block, op1,
2725                                                          stmts, domstmt);
2726               if (!genop1)
2727                 return NULL_TREE;
2728               genop1 = fold_convert (TREE_TYPE (nary->op[0]), genop1);
2729
2730               folded = fold_build1 (nary->opcode, nary->type,
2731                                     genop1);
2732             }
2733             break;
2734           default:
2735             return NULL_TREE;
2736           }
2737       }
2738       break;
2739     default:
2740       return NULL_TREE;
2741     }
2742   folded = fold_convert (exprtype, folded);
2743   /* Force the generated expression to be a sequence of GIMPLE
2744      statements.
2745      We have to call unshare_expr because force_gimple_operand may
2746      modify the tree we pass to it.  */
2747   newexpr = force_gimple_operand (unshare_expr (folded), &forced_stmts,
2748                                   false, NULL);
2749
2750   /* If we have any intermediate expressions to the value sets, add them
2751      to the value sets and chain them in the instruction stream.  */
2752   if (forced_stmts)
2753     {
2754       tsi = tsi_start (forced_stmts);
2755       for (; !tsi_end_p (tsi); tsi_next (&tsi))
2756         {
2757           tree stmt = tsi_stmt (tsi);
2758           tree forcedname = GIMPLE_STMT_OPERAND (stmt, 0);
2759           pre_expr nameexpr;
2760
2761           VEC_safe_push (tree, heap, inserted_exprs, stmt);
2762           if (TREE_CODE (forcedname) == SSA_NAME)
2763             {
2764               VN_INFO_GET (forcedname)->valnum = forcedname;
2765               VN_INFO (forcedname)->value_id = get_next_value_id ();
2766               nameexpr = get_or_alloc_expr_for_name (forcedname);
2767               add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2768               bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2769               bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2770             }
2771           mark_symbols_for_renaming (stmt);
2772         }
2773       tsi = tsi_last (stmts);
2774       tsi_link_after (&tsi, forced_stmts, TSI_CONTINUE_LINKING);
2775     }
2776
2777   /* Build and insert the assignment of the end result to the temporary
2778      that we will return.  */
2779   if (!pretemp || exprtype != TREE_TYPE (pretemp))
2780     {
2781       pretemp = create_tmp_var (exprtype, "pretmp");
2782       get_var_ann (pretemp);
2783     }
2784
2785   temp = pretemp;
2786   add_referenced_var (temp);
2787
2788   if (TREE_CODE (exprtype) == COMPLEX_TYPE
2789       || TREE_CODE (exprtype) == VECTOR_TYPE)
2790     DECL_GIMPLE_REG_P (temp) = 1;
2791
2792   newexpr = build_gimple_modify_stmt (temp, newexpr);
2793   name = make_ssa_name (temp, newexpr);
2794   GIMPLE_STMT_OPERAND (newexpr, 0) = name;
2795   NECESSARY (newexpr) = 0;
2796
2797   tsi = tsi_last (stmts);
2798   tsi_link_after (&tsi, newexpr, TSI_CONTINUE_LINKING);
2799   VEC_safe_push (tree, heap, inserted_exprs, newexpr);
2800
2801   /* All the symbols in NEWEXPR should be put into SSA form.  */
2802   mark_symbols_for_renaming (newexpr);
2803
2804   /* Add a value number to the temporary.
2805      The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2806      we are creating the expression by pieces, and this particular piece of
2807      the expression may have been represented.  There is no harm in replacing
2808      here.  */
2809   VN_INFO_GET (name)->valnum = name;
2810   value_id = get_expr_value_id (expr);
2811   VN_INFO (name)->value_id = value_id;
2812   nameexpr = get_or_alloc_expr_for_name (name);
2813   add_to_value (value_id, nameexpr);
2814   if (!in_fre)
2815     bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2816   bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2817
2818   pre_stats.insertions++;
2819   if (dump_file && (dump_flags & TDF_DETAILS))
2820     {
2821       fprintf (dump_file, "Inserted ");
2822       print_generic_expr (dump_file, newexpr, 0);
2823       fprintf (dump_file, " in predecessor %d\n", block->index);
2824     }
2825
2826   return name;
2827 }
2828
2829
2830 /* Insert the to-be-made-available values of expression EXPRNUM for each
2831    predecessor, stored in AVAIL, into the predecessors of BLOCK, and
2832    merge the result with a phi node, given the same value number as
2833    NODE.  Return true if we have inserted new stuff.  */
2834
2835 static bool
2836 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
2837                             pre_expr *avail)
2838 {
2839   pre_expr expr = expression_for_id (exprnum);
2840   pre_expr newphi;
2841   unsigned int val = get_expr_value_id (expr);
2842   edge pred;
2843   bool insertions = false;
2844   bool nophi = false;
2845   basic_block bprime;
2846   pre_expr eprime;
2847   edge_iterator ei;
2848   tree type = get_expr_type (expr);
2849   tree temp;
2850
2851   if (dump_file && (dump_flags & TDF_DETAILS))
2852     {
2853       fprintf (dump_file, "Found partial redundancy for expression ");
2854       print_pre_expr (dump_file, expr);
2855       fprintf (dump_file, " (%04d)\n", val);
2856     }
2857
2858   /* Make sure we aren't creating an induction variable.  */
2859   if (block->loop_depth > 0 && EDGE_COUNT (block->preds) == 2
2860       && expr->kind != REFERENCE)
2861     {
2862       bool firstinsideloop = false;
2863       bool secondinsideloop = false;
2864       firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
2865                                                EDGE_PRED (block, 0)->src);
2866       secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
2867                                                 EDGE_PRED (block, 1)->src);
2868       /* Induction variables only have one edge inside the loop.  */
2869       if (firstinsideloop ^ secondinsideloop)
2870         {
2871           if (dump_file && (dump_flags & TDF_DETAILS))
2872             fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
2873           nophi = true;
2874         }
2875     }
2876
2877
2878   /* Make the necessary insertions.  */
2879   FOR_EACH_EDGE (pred, ei, block->preds)
2880     {
2881       tree stmts = alloc_stmt_list ();
2882       tree builtexpr;
2883       bprime = pred->src;
2884       eprime = avail[bprime->index];
2885
2886       if (eprime->kind != NAME && eprime->kind != CONSTANT)
2887         {
2888           builtexpr = create_expression_by_pieces (bprime,
2889                                                    eprime,
2890                                                    stmts, NULL_TREE,
2891                                                    type);
2892           gcc_assert (!(pred->flags & EDGE_ABNORMAL));
2893           bsi_insert_on_edge (pred, stmts);
2894           avail[bprime->index] = get_or_alloc_expr_for_name (builtexpr);
2895           insertions = true;
2896         }
2897       else if (eprime->kind == CONSTANT)
2898         {
2899           /* Constants may not have the right type, fold_convert
2900              should give us back a constant with the right type.
2901           */
2902           tree constant = PRE_EXPR_CONSTANT (eprime);
2903           if (TREE_TYPE (constant) != type)
2904             {
2905               tree builtexpr = fold_convert (type, constant);
2906               if (is_gimple_min_invariant (builtexpr))
2907                 {
2908                   PRE_EXPR_CONSTANT (eprime) = builtexpr;
2909                 }
2910               else
2911                 {
2912                   tree forcedexpr = force_gimple_operand (builtexpr,
2913                                                           &stmts, true,
2914                                                           NULL);
2915                   if (is_gimple_min_invariant (forcedexpr))
2916                     {
2917                       PRE_EXPR_CONSTANT (eprime) = forcedexpr;
2918                     }
2919                   else
2920                     {
2921                       if (forcedexpr != builtexpr)
2922                         {
2923                           VN_INFO_GET (forcedexpr)->valnum = PRE_EXPR_CONSTANT (eprime);
2924                           VN_INFO (forcedexpr)->value_id = get_expr_value_id (eprime);
2925                         }
2926                       if (stmts)
2927                         {
2928                           tree_stmt_iterator tsi;
2929                           tsi = tsi_start (stmts);
2930                           for (; !tsi_end_p (tsi); tsi_next (&tsi))
2931                             {
2932                               tree stmt = tsi_stmt (tsi);
2933                               tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
2934                               VEC_safe_push (tree, heap, inserted_exprs, stmt);
2935                               NECESSARY (lhs) = 0;
2936                             }
2937                           bsi_insert_on_edge (pred, stmts);
2938                         }
2939                       NECESSARY (forcedexpr) = 0;
2940                       avail[bprime->index] = get_or_alloc_expr_for_name (forcedexpr);
2941                     }
2942                 }
2943             }
2944         }
2945       else if (eprime->kind == NAME)
2946         {
2947           /* We may have to do a conversion because our value
2948              numbering can look through types in certain cases, but
2949              our IL requires all operands of a phi node have the same
2950              type.  */
2951           tree name = PRE_EXPR_NAME (eprime);
2952           if (!useless_type_conversion_p (type, TREE_TYPE (name)))
2953             {
2954               tree builtexpr;
2955               tree forcedexpr;
2956               builtexpr = fold_convert (type, name);
2957               forcedexpr = force_gimple_operand (builtexpr,
2958                                                  &stmts, true,
2959                                                  NULL);
2960
2961               if (forcedexpr != name)
2962                 {
2963                   VN_INFO_GET (forcedexpr)->valnum = VN_INFO (name)->valnum;
2964                   VN_INFO (forcedexpr)->value_id = VN_INFO (name)->value_id;
2965                 }
2966
2967               if (stmts)
2968                 {
2969                   tree_stmt_iterator tsi;
2970                   tsi = tsi_start (stmts);
2971                   for (; !tsi_end_p (tsi); tsi_next (&tsi))
2972                     {
2973                       tree stmt = tsi_stmt (tsi);
2974                       tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
2975                       VEC_safe_push (tree, heap, inserted_exprs, stmt);
2976                       NECESSARY (lhs) = 0;
2977                     }
2978                   bsi_insert_on_edge (pred, stmts);
2979                 }
2980               NECESSARY (forcedexpr) = 0;
2981               avail[bprime->index] = get_or_alloc_expr_for_name (forcedexpr);
2982             }
2983         }
2984     }
2985   /* If we didn't want a phi node, and we made insertions, we still have
2986      inserted new stuff, and thus return true.  If we didn't want a phi node,
2987      and didn't make insertions, we haven't added anything new, so return
2988      false.  */
2989   if (nophi && insertions)
2990     return true;
2991   else if (nophi && !insertions)
2992     return false;
2993
2994   /* Now build a phi for the new variable.  */
2995   if (!prephitemp || TREE_TYPE (prephitemp) != type)
2996     {
2997       prephitemp = create_tmp_var (type, "prephitmp");
2998       get_var_ann (prephitemp);
2999     }
3000
3001   temp = prephitemp;
3002   add_referenced_var (temp);
3003
3004   if (TREE_CODE (type) == COMPLEX_TYPE
3005       || TREE_CODE (type) == VECTOR_TYPE)
3006     DECL_GIMPLE_REG_P (temp) = 1;
3007   temp = create_phi_node (temp, block);
3008
3009   NECESSARY (temp) = 0;
3010   VN_INFO_GET (PHI_RESULT (temp))->valnum = PHI_RESULT (temp);
3011   VN_INFO (PHI_RESULT (temp))->value_id = val;
3012   VEC_safe_push (tree, heap, inserted_exprs, temp);
3013   FOR_EACH_EDGE (pred, ei, block->preds)
3014     {
3015       pre_expr ae = avail[pred->src->index];
3016       gcc_assert (get_expr_type (ae) == type
3017                   || useless_type_conversion_p (type, get_expr_type (ae)));
3018       if (ae->kind == CONSTANT)
3019         add_phi_arg (temp, PRE_EXPR_CONSTANT (ae), pred);
3020       else
3021         add_phi_arg (temp, PRE_EXPR_NAME (avail[pred->src->index]), pred);
3022     }
3023
3024   newphi = get_or_alloc_expr_for_name (PHI_RESULT (temp));
3025   add_to_value (val, newphi);
3026
3027   /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3028      this insertion, since we test for the existence of this value in PHI_GEN
3029      before proceeding with the partial redundancy checks in insert_aux.
3030
3031      The value may exist in AVAIL_OUT, in particular, it could be represented
3032      by the expression we are trying to eliminate, in which case we want the
3033      replacement to occur.  If it's not existing in AVAIL_OUT, we want it
3034      inserted there.
3035
3036      Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3037      this block, because if it did, it would have existed in our dominator's
3038      AVAIL_OUT, and would have been skipped due to the full redundancy check.
3039   */
3040
3041   bitmap_insert_into_set (PHI_GEN (block), newphi);
3042   bitmap_value_replace_in_set (AVAIL_OUT (block),
3043                                newphi);
3044   bitmap_insert_into_set (NEW_SETS (block),
3045                           newphi);
3046
3047   if (dump_file && (dump_flags & TDF_DETAILS))
3048     {
3049       fprintf (dump_file, "Created phi ");
3050       print_generic_expr (dump_file, temp, 0);
3051       fprintf (dump_file, " in block %d\n", block->index);
3052     }
3053   pre_stats.phis++;
3054   return true;
3055 }
3056
3057
3058
3059 /* Perform insertion of partially redundant values.
3060    For BLOCK, do the following:
3061    1.  Propagate the NEW_SETS of the dominator into the current block.
3062    If the block has multiple predecessors,
3063        2a. Iterate over the ANTIC expressions for the block to see if
3064            any of them are partially redundant.
3065        2b. If so, insert them into the necessary predecessors to make
3066            the expression fully redundant.
3067        2c. Insert a new PHI merging the values of the predecessors.
3068        2d. Insert the new PHI, and the new expressions, into the
3069            NEW_SETS set.
3070    3. Recursively call ourselves on the dominator children of BLOCK.
3071
3072    Steps 1, 2a, and 3 are done by insert_aux. 2b, 2c and 2d are done by
3073    do_regular_insertion and do_partial_insertion.
3074
3075 */
3076
3077 static bool
3078 do_regular_insertion (basic_block block, basic_block dom)
3079 {
3080   bool new_stuff = false;
3081   VEC (pre_expr, heap) *exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3082   pre_expr expr;
3083   int i;
3084
3085   for (i = 0; VEC_iterate (pre_expr, exprs, i, expr); i++)
3086     {
3087       if (expr->kind != NAME)
3088         {
3089           pre_expr *avail;
3090           unsigned int val;
3091           bool by_some = false;
3092           bool cant_insert = false;
3093           bool all_same = true;
3094           pre_expr first_s = NULL;
3095           edge pred;
3096           basic_block bprime;
3097           pre_expr eprime = NULL;
3098           edge_iterator ei;
3099
3100           val = get_expr_value_id (expr);
3101           if (bitmap_set_contains_value (PHI_GEN (block), val))
3102             continue;
3103           if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3104             {
3105               if (dump_file && (dump_flags & TDF_DETAILS))
3106                 fprintf (dump_file, "Found fully redundant value\n");
3107               continue;
3108             }
3109
3110           avail = XCNEWVEC (pre_expr, last_basic_block);
3111           FOR_EACH_EDGE (pred, ei, block->preds)
3112             {
3113               unsigned int vprime;
3114               pre_expr edoubleprime;
3115
3116               /* This can happen in the very weird case
3117                  that our fake infinite loop edges have caused a
3118                  critical edge to appear.  */
3119               if (EDGE_CRITICAL_P (pred))
3120                 {
3121                   cant_insert = true;
3122                   break;
3123                 }
3124               bprime = pred->src;
3125               eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3126                                       bprime, block);
3127
3128               /* eprime will generally only be NULL if the
3129                  value of the expression, translated
3130                  through the PHI for this predecessor, is
3131                  undefined.  If that is the case, we can't
3132                  make the expression fully redundant,
3133                  because its value is undefined along a
3134                  predecessor path.  We can thus break out
3135                  early because it doesn't matter what the
3136                  rest of the results are.  */
3137               if (eprime == NULL)
3138                 {
3139                   cant_insert = true;
3140                   break;
3141                 }
3142
3143               eprime = fully_constant_expression (eprime);
3144               vprime = get_expr_value_id (eprime);
3145               edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3146                                                  vprime, NULL_TREE);
3147               if (edoubleprime == NULL)
3148                 {
3149                   avail[bprime->index] = eprime;
3150                   all_same = false;
3151                 }
3152               else
3153                 {
3154                   avail[bprime->index] = edoubleprime;
3155                   by_some = true;
3156                   if (first_s == NULL)
3157                     first_s = edoubleprime;
3158                   else if (!pre_expr_eq (first_s, edoubleprime))
3159                     all_same = false;
3160                 }
3161             }
3162           /* If we can insert it, it's not the same value
3163              already existing along every predecessor, and
3164              it's defined by some predecessor, it is
3165              partially redundant.  */
3166           if (!cant_insert && !all_same && by_some && dbg_cnt (treepre_insert))
3167             {
3168               if (insert_into_preds_of_block (block, get_expression_id (expr),
3169                                               avail))
3170                 new_stuff = true;
3171             }
3172           /* If all edges produce the same value and that value is
3173              an invariant, then the PHI has the same value on all
3174              edges.  Note this.  */
3175           else if (!cant_insert && all_same && eprime
3176                    && eprime->kind == CONSTANT
3177                    && !value_id_constant_p (val))
3178             {
3179               unsigned int j;
3180               bitmap_iterator bi;
3181               bitmap_set_t exprset = VEC_index (bitmap_set_t,
3182                                                 value_expressions, val);
3183
3184               unsigned int new_val = get_expr_value_id (eprime);
3185               FOR_EACH_EXPR_ID_IN_SET (exprset, j, bi)
3186                 {
3187                   pre_expr expr = expression_for_id (j);
3188
3189                   if (expr->kind == NAME)
3190                     {
3191                       vn_ssa_aux_t info = VN_INFO (PRE_EXPR_NAME (expr));
3192                       /* Just reset the value id and valnum so it is
3193                          the same as the constant we have discovered.  */
3194                       info->valnum = PRE_EXPR_CONSTANT (eprime);
3195                       info->value_id = new_val;
3196                       pre_stats.constified++;
3197                     }
3198                 }
3199             }
3200           free (avail);
3201         }
3202     }
3203
3204   VEC_free (pre_expr, heap, exprs);
3205   return new_stuff;
3206 }
3207
3208
3209 /* Perform insertion for partially anticipatable expressions.  There
3210    is only one case we will perform insertion for these.  This case is
3211    if the expression is partially anticipatable, and fully available.
3212    In this case, we know that putting it earlier will enable us to
3213    remove the later computation.  */
3214
3215
3216 static bool
3217 do_partial_partial_insertion (basic_block block, basic_block dom)
3218 {
3219   bool new_stuff = false;
3220   VEC (pre_expr, heap) *exprs = sorted_array_from_bitmap_set (PA_IN (block));
3221   pre_expr expr;
3222   int i;
3223
3224   for (i = 0; VEC_iterate (pre_expr, exprs, i, expr); i++)
3225     {
3226       if (expr->kind != NAME)
3227         {
3228           pre_expr *avail;
3229           unsigned int val;
3230           bool by_all = true;
3231           bool cant_insert = false;
3232           edge pred;
3233           basic_block bprime;
3234           pre_expr eprime = NULL;
3235           edge_iterator ei;
3236
3237           val = get_expr_value_id (expr);
3238           if (bitmap_set_contains_value (PHI_GEN (block), val))
3239             continue;
3240           if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3241             continue;
3242
3243           avail = XCNEWVEC (pre_expr, last_basic_block);
3244           FOR_EACH_EDGE (pred, ei, block->preds)
3245             {
3246               unsigned int vprime;
3247               pre_expr edoubleprime;
3248
3249               /* This can happen in the very weird case
3250                  that our fake infinite loop edges have caused a
3251                  critical edge to appear.  */
3252               if (EDGE_CRITICAL_P (pred))
3253                 {
3254                   cant_insert = true;
3255                   break;
3256                 }
3257               bprime = pred->src;
3258               eprime = phi_translate (expr, ANTIC_IN (block),
3259                                       PA_IN (block),
3260                                       bprime, block);
3261
3262               /* eprime will generally only be NULL if the
3263                  value of the expression, translated
3264                  through the PHI for this predecessor, is
3265                  undefined.  If that is the case, we can't
3266                  make the expression fully redundant,
3267                  because its value is undefined along a
3268                  predecessor path.  We can thus break out
3269                  early because it doesn't matter what the
3270                  rest of the results are.  */
3271               if (eprime == NULL)
3272                 {
3273                   cant_insert = true;
3274                   break;
3275                 }
3276
3277               eprime = fully_constant_expression (eprime);
3278               vprime = get_expr_value_id (eprime);
3279               edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3280                                                  vprime, NULL_TREE);
3281               if (edoubleprime == NULL)
3282                 {
3283                   by_all = false;
3284                   break;
3285                 }
3286               else
3287                 avail[bprime->index] = edoubleprime;
3288
3289             }
3290
3291           /* If we can insert it, it's not the same value
3292              already existing along every predecessor, and
3293              it's defined by some predecessor, it is
3294              partially redundant.  */
3295           if (!cant_insert && by_all && dbg_cnt (treepre_insert))
3296             {
3297               pre_stats.pa_insert++;
3298               if (insert_into_preds_of_block (block, get_expression_id (expr),
3299                                               avail))
3300                 new_stuff = true;
3301             }
3302           free (avail);
3303         }
3304     }
3305
3306   VEC_free (pre_expr, heap, exprs);
3307   return new_stuff;
3308 }
3309
3310 static bool
3311 insert_aux (basic_block block)
3312 {
3313   basic_block son;
3314   bool new_stuff = false;
3315
3316   if (block)
3317     {
3318       basic_block dom;
3319       dom = get_immediate_dominator (CDI_DOMINATORS, block);
3320       if (dom)
3321         {
3322           unsigned i;
3323           bitmap_iterator bi;
3324           bitmap_set_t newset = NEW_SETS (dom);
3325           if (newset)
3326             {
3327               /* Note that we need to value_replace both NEW_SETS, and
3328                  AVAIL_OUT. For both the case of NEW_SETS, the value may be
3329                  represented by some non-simple expression here that we want
3330                  to replace it with.  */
3331               FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3332                 {
3333                   pre_expr expr = expression_for_id (i);
3334                   bitmap_value_replace_in_set (NEW_SETS (block), expr);
3335                   bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3336                 }
3337             }
3338           if (!single_pred_p (block))
3339             {
3340               new_stuff |= do_regular_insertion (block, dom);
3341               if (do_partial_partial)
3342                 new_stuff |= do_partial_partial_insertion (block, dom);
3343             }
3344         }
3345     }
3346   for (son = first_dom_son (CDI_DOMINATORS, block);
3347        son;
3348        son = next_dom_son (CDI_DOMINATORS, son))
3349     {
3350       new_stuff |= insert_aux (son);
3351     }
3352
3353   return new_stuff;
3354 }
3355
3356 /* Perform insertion of partially redundant values.  */
3357
3358 static void
3359 insert (void)
3360 {
3361   bool new_stuff = true;
3362   basic_block bb;
3363   int num_iterations = 0;
3364
3365   FOR_ALL_BB (bb)
3366     NEW_SETS (bb) = bitmap_set_new ();
3367
3368   while (new_stuff)
3369     {
3370       num_iterations++;
3371       new_stuff = insert_aux (ENTRY_BLOCK_PTR);
3372     }
3373   statistics_histogram_event (cfun, "insert iterations", num_iterations);
3374 }
3375
3376
3377 /* Add OP to EXP_GEN (block), and possibly to the maximal set if it is
3378    not defined by a phi node.
3379    PHI nodes can't go in the maximal sets because they are not in
3380    TMP_GEN, so it is possible to get into non-monotonic situations
3381    during ANTIC calculation, because it will *add* bits.  */
3382
3383 static void
3384 add_to_exp_gen (basic_block block, tree op)
3385 {
3386   if (!in_fre)
3387     {
3388       pre_expr result;
3389       if (TREE_CODE (op) == SSA_NAME && ssa_undefined_value_p (op))
3390         return;
3391       result = get_or_alloc_expr_for_name (op);
3392       bitmap_value_insert_into_set (EXP_GEN (block), result);
3393       if (TREE_CODE (op) != SSA_NAME
3394           || TREE_CODE (SSA_NAME_DEF_STMT (op)) != PHI_NODE)
3395         bitmap_value_insert_into_set (maximal_set, result);
3396     }
3397 }
3398
3399 /* For each real store operation of the form
3400    *a = <value> that we see, create a corresponding fake store of the
3401    form storetmp_<version> = *a.
3402
3403    This enables AVAIL computation to mark the results of stores as
3404    available.  Without this, you'd need to do some computation to
3405    mark the result of stores as ANTIC and AVAIL at all the right
3406    points.
3407    To save memory, we keep the store
3408    statements pool allocated until we decide whether they are
3409    necessary or not.  */
3410
3411 static void
3412 insert_fake_stores (void)
3413 {
3414   basic_block block;
3415
3416   FOR_ALL_BB (block)
3417     {
3418       block_stmt_iterator bsi;
3419       for (bsi = bsi_start (block); !bsi_end_p (bsi); bsi_next (&bsi))
3420         {
3421           tree stmt = bsi_stmt (bsi);
3422
3423           /* We can't generate SSA names for stores that are complex
3424              or aggregate.  We also want to ignore things whose
3425              virtual uses occur in abnormal phis.  */
3426
3427           if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
3428               && (TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 0)) == INDIRECT_REF
3429                   || handled_component_p (GIMPLE_STMT_OPERAND (stmt, 0)))
3430               && !AGGREGATE_TYPE_P (TREE_TYPE (GIMPLE_STMT_OPERAND (stmt, 0))))
3431             {
3432               ssa_op_iter iter;
3433               def_operand_p defp;
3434               tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
3435               tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
3436               tree new_tree, new_lhs;
3437               bool notokay = false;
3438
3439               FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_VIRTUAL_DEFS)
3440                 {
3441                   tree defvar = DEF_FROM_PTR (defp);
3442                   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (defvar))
3443                     {
3444                       notokay = true;
3445                       break;
3446                     }
3447                 }
3448
3449               if (notokay)
3450                 continue;
3451
3452               if (!storetemp || TREE_TYPE (rhs) != TREE_TYPE (storetemp))
3453                 {
3454                   storetemp = create_tmp_var (TREE_TYPE (rhs), "storetmp");
3455                   if (TREE_CODE (TREE_TYPE (storetemp)) == VECTOR_TYPE
3456                       || TREE_CODE (TREE_TYPE (storetemp)) == COMPLEX_TYPE)
3457                     DECL_GIMPLE_REG_P (storetemp) = 1;
3458                   get_var_ann (storetemp);
3459                 }
3460
3461               new_tree = build_gimple_modify_stmt (NULL_TREE, lhs);
3462               new_lhs = make_ssa_name (storetemp, new_tree);
3463               GIMPLE_STMT_OPERAND (new_tree, 0) = new_lhs;
3464               create_ssa_artificial_load_stmt (new_tree, stmt, false);
3465
3466               NECESSARY (new_tree) = 0;
3467               VEC_safe_push (tree, heap, inserted_exprs, new_tree);
3468               VEC_safe_push (tree, heap, need_creation, new_tree);
3469               bsi_insert_after (&bsi, new_tree, BSI_NEW_STMT);
3470             }
3471         }
3472     }
3473 }
3474
3475 /* Turn the pool allocated fake stores that we created back into real
3476    GC allocated ones if they turned out to be necessary to PRE some
3477    expressions.  */
3478
3479 static void
3480 realify_fake_stores (void)
3481 {
3482   unsigned int i;
3483   tree stmt;
3484
3485   for (i = 0; VEC_iterate (tree, need_creation, i, stmt); i++)
3486     {
3487       if (NECESSARY (stmt))
3488         {
3489           block_stmt_iterator bsi, bsi2;
3490           tree rhs;
3491
3492           /* Mark the temp variable as referenced */
3493           add_referenced_var (SSA_NAME_VAR (GIMPLE_STMT_OPERAND (stmt, 0)));
3494
3495           /* Put the statement before the store in the IR stream
3496              as a plain ssa name copy.  */
3497           bsi = bsi_for_stmt (stmt);
3498           bsi_prev (&bsi);
3499           rhs = GIMPLE_STMT_OPERAND (bsi_stmt (bsi), 1);
3500           GIMPLE_STMT_OPERAND (stmt, 1) = rhs;
3501           bsi2 = bsi_for_stmt (stmt);
3502           bsi_remove (&bsi2, true);
3503           bsi_insert_before (&bsi, stmt, BSI_SAME_STMT);
3504         }
3505       else
3506         release_defs (stmt);
3507     }
3508 }
3509
3510 /* Create value ids for PHI in BLOCK.  */
3511
3512 static void
3513 make_values_for_phi (tree phi, basic_block block)
3514 {
3515   tree result = PHI_RESULT (phi);
3516   /* We have no need for virtual phis, as they don't represent
3517      actual computations.  */
3518   if (is_gimple_reg (result))
3519     {
3520       pre_expr e = get_or_alloc_expr_for_name (result);
3521       add_to_value (get_expr_value_id (e), e);
3522       bitmap_insert_into_set (PHI_GEN (block), e);
3523       bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3524     }
3525 }
3526
3527 /* Compute the AVAIL set for all basic blocks.
3528
3529    This function performs value numbering of the statements in each basic
3530    block.  The AVAIL sets are built from information we glean while doing
3531    this value numbering, since the AVAIL sets contain only one entry per
3532    value.
3533
3534    AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3535    AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK].  */
3536
3537 static void
3538 compute_avail (void)
3539 {
3540
3541   basic_block block, son;
3542   basic_block *worklist;
3543   size_t sp = 0;
3544   tree param;
3545
3546   /* For arguments with default definitions, we pretend they are
3547      defined in the entry block.  */
3548   for (param = DECL_ARGUMENTS (current_function_decl);
3549        param;
3550        param = TREE_CHAIN (param))
3551     {
3552       if (gimple_default_def (cfun, param) != NULL)
3553         {
3554           tree def = gimple_default_def (cfun, param);
3555           pre_expr e = get_or_alloc_expr_for_name (def);
3556
3557           add_to_value (get_expr_value_id (e), e);
3558           if (!in_fre)
3559             {
3560               bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR), e);
3561               bitmap_value_insert_into_set (maximal_set, e);
3562             }
3563           bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR), e);
3564         }
3565     }
3566
3567   /* Likewise for the static chain decl. */
3568   if (cfun->static_chain_decl)
3569     {
3570       param = cfun->static_chain_decl;
3571       if (gimple_default_def (cfun, param) != NULL)
3572         {
3573           tree def = gimple_default_def (cfun, param);
3574           pre_expr e = get_or_alloc_expr_for_name (def);
3575
3576           add_to_value (get_expr_value_id (e), e);
3577           if (!in_fre)
3578             {
3579               bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR), e);
3580               bitmap_value_insert_into_set (maximal_set, e);
3581             }
3582           bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR), e);
3583         }
3584     }
3585
3586   /* Allocate the worklist.  */
3587   worklist = XNEWVEC (basic_block, n_basic_blocks);
3588
3589   /* Seed the algorithm by putting the dominator children of the entry
3590      block on the worklist.  */
3591   for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR);
3592        son;
3593        son = next_dom_son (CDI_DOMINATORS, son))
3594     worklist[sp++] = son;
3595
3596   /* Loop until the worklist is empty.  */
3597   while (sp)
3598     {
3599       block_stmt_iterator bsi;
3600       tree stmt, phi;
3601       basic_block dom;
3602       unsigned int stmt_uid = 1;
3603
3604       /* Pick a block from the worklist.  */
3605       block = worklist[--sp];
3606
3607       /* Initially, the set of available values in BLOCK is that of
3608          its immediate dominator.  */
3609       dom = get_immediate_dominator (CDI_DOMINATORS, block);
3610       if (dom)
3611         bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3612
3613       /* Generate values for PHI nodes.  */
3614       for (phi = phi_nodes (block); phi; phi = PHI_CHAIN (phi))
3615         make_values_for_phi (phi, block);
3616
3617       /* Now compute value numbers and populate value sets with all
3618          the expressions computed in BLOCK.  */
3619       for (bsi = bsi_start (block); !bsi_end_p (bsi); bsi_next (&bsi))
3620         {
3621           stmt_ann_t ann;
3622           ssa_op_iter iter;
3623           tree op;
3624
3625           stmt = bsi_stmt (bsi);
3626           ann = stmt_ann (stmt);
3627
3628           set_gimple_stmt_uid (stmt, stmt_uid++);
3629
3630           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3631             {
3632               pre_expr e = get_or_alloc_expr_for_name (op);
3633
3634               add_to_value (get_expr_value_id (e), e);
3635               if (!in_fre)
3636                 {
3637                   bitmap_insert_into_set (TMP_GEN (block), e);
3638                   bitmap_value_insert_into_set (maximal_set, e);
3639                 }
3640               bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3641             }
3642
3643           switch (TREE_CODE (stmt))
3644             {
3645             case RETURN_EXPR:
3646               if (!ann->has_volatile_ops)
3647                 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3648                   add_to_exp_gen (block, op);
3649               continue;
3650             case GIMPLE_MODIFY_STMT:
3651               {
3652                 tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
3653                 if (!ann->has_volatile_ops
3654                     && !tree_could_throw_p (stmt))
3655                   {
3656                     pre_expr result = NULL;
3657                     switch (TREE_CODE_CLASS (TREE_CODE (rhs)))
3658                       {
3659                       case tcc_unary:
3660                         if (is_exception_related (rhs))
3661                           continue;
3662                       case tcc_binary:
3663                         {
3664                           vn_nary_op_t nary;
3665                           unsigned int i;
3666
3667                           vn_nary_op_lookup (rhs, &nary);
3668
3669                           if (!nary)
3670                             continue;
3671
3672                           for (i = 0; i < nary->length; i++)
3673                             if (TREE_CODE (nary->op[i]) == SSA_NAME)
3674                               add_to_exp_gen (block, nary->op[i]);
3675
3676                           result = (pre_expr) pool_alloc (pre_expr_pool);
3677                           result->kind = NARY;
3678                           result->id = 0;
3679                           PRE_EXPR_NARY (result) = nary;
3680                         }
3681                         break;
3682                       case tcc_vl_exp:
3683                         if (!can_value_number_call (rhs))
3684                           continue;
3685
3686                       case tcc_declaration:
3687                       case tcc_reference:
3688                         {
3689                           vn_reference_t ref;
3690                           unsigned int i;
3691                           vn_reference_op_t vro;
3692
3693                           vn_reference_lookup (rhs,
3694                                                shared_vuses_from_stmt (stmt),
3695                                                true, &ref);
3696                           if (!ref)
3697                             continue;
3698
3699                           for (i = 0; VEC_iterate (vn_reference_op_s,
3700                                                    ref->operands, i,
3701                                                    vro); i++)
3702                             {
3703                               if (vro->op0 && TREE_CODE (vro->op0) == SSA_NAME)
3704                                 add_to_exp_gen (block, vro->op0);
3705                               if (vro->op1 && TREE_CODE (vro->op1) == SSA_NAME)
3706                                 add_to_exp_gen (block, vro->op1);
3707                             }
3708                           result = (pre_expr) pool_alloc (pre_expr_pool);
3709                           result->kind = REFERENCE;
3710                           result->id = 0;
3711                           PRE_EXPR_REFERENCE (result) = ref;
3712                         }
3713                         break;
3714                       default:
3715                         {
3716                           /* For any other statement that we don't
3717                              recognize, simply add all referenced
3718                              SSA_NAMEs to EXP_GEN.  */
3719                           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3720                             add_to_exp_gen (block, op);
3721                           continue;
3722                         }
3723                       }
3724                     get_or_alloc_expression_id (result);
3725                     add_to_value (get_expr_value_id (result), result);
3726                     if (!in_fre)
3727                       {
3728                         bitmap_value_insert_into_set (EXP_GEN (block),
3729                                                       result);
3730                         bitmap_value_insert_into_set (maximal_set, result);
3731                       }
3732
3733                   }
3734                 continue;
3735               }
3736             default:
3737               break;
3738
3739             }
3740
3741
3742         }
3743       /* Put the dominator children of BLOCK on the worklist of blocks
3744          to compute available sets for.  */
3745       for (son = first_dom_son (CDI_DOMINATORS, block);
3746            son;
3747            son = next_dom_son (CDI_DOMINATORS, son))
3748         worklist[sp++] = son;
3749     }
3750
3751   free (worklist);
3752 }
3753
3754 /* Insert the expression for SSA_VN that SCCVN thought would be simpler
3755    than the available expressions for it.  The insertion point is
3756    right before the first use in STMT.  Returns the SSA_NAME that should
3757    be used for replacement.  */
3758
3759 static tree
3760 do_SCCVN_insertion (tree stmt, tree ssa_vn)
3761 {
3762   basic_block bb = bb_for_stmt (stmt);
3763   block_stmt_iterator bsi;
3764   tree expr, stmts;
3765   pre_expr e;
3766
3767   /* First create a value expression from the expression we want
3768      to insert and associate it with the value handle for SSA_VN.  */
3769
3770   /* TODO: Handle complex expressions.  */
3771   e = get_or_alloc_expr_for (VN_INFO (ssa_vn)->expr);
3772   if (e == NULL)
3773     return NULL_TREE;
3774
3775 /* Then use create_expression_by_pieces to generate a valid
3776      expression to insert at this point of the IL stream.  */
3777   stmts = alloc_stmt_list ();
3778   expr = create_expression_by_pieces (bb, e, stmts, stmt,
3779                                       NULL);
3780   if (expr == NULL_TREE)
3781     return NULL_TREE;
3782   bsi = bsi_for_stmt (stmt);
3783   bsi_insert_before (&bsi, stmts, BSI_SAME_STMT);
3784
3785   return expr;
3786 }
3787
3788 /* Eliminate fully redundant computations.  */
3789
3790 static unsigned int
3791 eliminate (void)
3792 {
3793   basic_block b;
3794   unsigned int todo = 0;
3795
3796   FOR_EACH_BB (b)
3797     {
3798       block_stmt_iterator i;
3799
3800       for (i = bsi_start (b); !bsi_end_p (i); bsi_next (&i))
3801         {
3802           tree stmt = bsi_stmt (i);
3803
3804           /* Lookup the RHS of the expression, see if we have an
3805              available computation for it.  If so, replace the RHS with
3806              the available computation.  */
3807           if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
3808               && TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 0)) == SSA_NAME
3809               && TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) != SSA_NAME
3810               && !is_gimple_min_invariant (GIMPLE_STMT_OPERAND (stmt, 1))
3811               && !stmt_ann (stmt)->has_volatile_ops)
3812             {
3813               tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
3814               tree *rhs_p = &GIMPLE_STMT_OPERAND (stmt, 1);
3815               tree sprime = NULL;
3816               pre_expr lhsexpr = get_or_alloc_expr_for_name (lhs);
3817               pre_expr sprimeexpr;
3818
3819               sprimeexpr = bitmap_find_leader (AVAIL_OUT (b),
3820                                                get_expr_value_id (lhsexpr),
3821                                                NULL_TREE);
3822
3823               if (sprimeexpr)
3824                 {
3825                   if (sprimeexpr->kind == CONSTANT)
3826                     sprime = PRE_EXPR_CONSTANT (sprimeexpr);
3827                   else if (sprimeexpr->kind == NAME)
3828                     sprime = PRE_EXPR_NAME (sprimeexpr);
3829                   else
3830                     gcc_unreachable ();
3831                 }
3832
3833               /* If there is no existing leader but SCCVN knows this
3834                  value is constant, use that constant.  */
3835               if (!sprime && is_gimple_min_invariant (VN_INFO (lhs)->valnum))
3836                 {
3837                   sprime = fold_convert (TREE_TYPE (lhs),
3838                                          VN_INFO (lhs)->valnum);
3839
3840                   if (dump_file && (dump_flags & TDF_DETAILS))
3841                     {
3842                       fprintf (dump_file, "Replaced ");
3843                       print_generic_expr (dump_file, *rhs_p, 0);
3844                       fprintf (dump_file, " with ");
3845                       print_generic_expr (dump_file, sprime, 0);
3846                       fprintf (dump_file, " in ");
3847                       print_generic_stmt (dump_file, stmt, 0);
3848                     }
3849                   pre_stats.eliminations++;
3850                   propagate_tree_value (rhs_p, sprime);
3851                   update_stmt (stmt);
3852                   continue;
3853                 }
3854
3855               /* If there is no existing usable leader but SCCVN thinks
3856                  it has an expression it wants to use as replacement,
3857                  insert that.  */
3858               if (!sprime || sprime == lhs)
3859                 {
3860                   tree val = VN_INFO (lhs)->valnum;
3861                   if (val != VN_TOP
3862                       && TREE_CODE (val) == SSA_NAME
3863                       && VN_INFO (val)->needs_insertion
3864                       && can_PRE_operation (VN_INFO (val)->expr))
3865                     sprime = do_SCCVN_insertion (stmt, val);
3866                 }
3867               if (sprime
3868                   && sprime != lhs
3869                   && (TREE_CODE (*rhs_p) != SSA_NAME
3870                       || may_propagate_copy (*rhs_p, sprime)))
3871                 {
3872                   gcc_assert (sprime != *rhs_p);
3873
3874                   if (dump_file && (dump_flags & TDF_DETAILS))
3875                     {
3876                       fprintf (dump_file, "Replaced ");
3877                       print_generic_expr (dump_file, *rhs_p, 0);
3878                       fprintf (dump_file, " with ");
3879                       print_generic_expr (dump_file, sprime, 0);
3880                       fprintf (dump_file, " in ");
3881                       print_generic_stmt (dump_file, stmt, 0);
3882                     }
3883
3884                   if (TREE_CODE (sprime) == SSA_NAME)
3885                     NECESSARY (SSA_NAME_DEF_STMT (sprime)) = 1;
3886                   /* We need to make sure the new and old types actually match,
3887                      which may require adding a simple cast, which fold_convert
3888                      will do for us.  */
3889                   if (TREE_CODE (*rhs_p) != SSA_NAME
3890                       && !useless_type_conversion_p (TREE_TYPE (*rhs_p),
3891                                                     TREE_TYPE (sprime)))
3892                     sprime = fold_convert (TREE_TYPE (*rhs_p), sprime);
3893
3894                   pre_stats.eliminations++;
3895                   propagate_tree_value (rhs_p, sprime);
3896                   update_stmt (stmt);
3897
3898                   /* If we removed EH side effects from the statement, clean
3899                      its EH information.  */
3900                   if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
3901                     {
3902                       bitmap_set_bit (need_eh_cleanup,
3903                                       bb_for_stmt (stmt)->index);
3904                       if (dump_file && (dump_flags & TDF_DETAILS))
3905                         fprintf (dump_file, "  Removed EH side effects.\n");
3906                     }
3907                 }
3908             }
3909           /* Visit COND_EXPRs and fold the comparison with the
3910              available value-numbers.  */
3911           else if (TREE_CODE (stmt) == COND_EXPR
3912                    && COMPARISON_CLASS_P (COND_EXPR_COND (stmt)))
3913             {
3914               tree cond = COND_EXPR_COND (stmt);
3915               tree op0 = TREE_OPERAND (cond, 0);
3916               tree op1 = TREE_OPERAND (cond, 1);
3917               tree result;
3918
3919               if (TREE_CODE (op0) == SSA_NAME)
3920                 op0 = VN_INFO (op0)->valnum;
3921               if (TREE_CODE (op1) == SSA_NAME)
3922                 op1 = VN_INFO (op1)->valnum;
3923               result = fold_binary (TREE_CODE (cond), TREE_TYPE (cond),
3924                                     op0, op1);
3925               if (result && TREE_CODE (result) == INTEGER_CST)
3926                 {
3927                   COND_EXPR_COND (stmt) = result;
3928                   update_stmt (stmt);
3929                   todo = TODO_cleanup_cfg;
3930                 }
3931             }
3932           else if (TREE_CODE (stmt) == COND_EXPR
3933                    && TREE_CODE (COND_EXPR_COND (stmt)) == SSA_NAME)
3934             {
3935               tree op = COND_EXPR_COND (stmt);
3936               op = VN_INFO (op)->valnum;
3937               if (TREE_CODE (op) == INTEGER_CST)
3938                 {
3939                   COND_EXPR_COND (stmt) = integer_zerop (op)
3940                     ? boolean_false_node : boolean_true_node;
3941                   update_stmt (stmt);
3942                   todo = TODO_cleanup_cfg;
3943                 }
3944             }
3945         }
3946     }
3947
3948   return todo;
3949 }
3950
3951 /* Borrow a bit of tree-ssa-dce.c for the moment.
3952    XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
3953    this may be a bit faster, and we may want critical edges kept split.  */
3954
3955 /* If OP's defining statement has not already been determined to be necessary,
3956    mark that statement necessary. Return the stmt, if it is newly
3957    necessary.  */
3958
3959 static inline tree
3960 mark_operand_necessary (tree op)
3961 {
3962   tree stmt;
3963
3964   gcc_assert (op);
3965
3966   if (TREE_CODE (op) != SSA_NAME)
3967     return NULL;
3968
3969   stmt = SSA_NAME_DEF_STMT (op);
3970   gcc_assert (stmt);
3971
3972   if (NECESSARY (stmt)
3973       || IS_EMPTY_STMT (stmt))
3974     return NULL;
3975
3976   NECESSARY (stmt) = 1;
3977   return stmt;
3978 }
3979
3980 /* Because we don't follow exactly the standard PRE algorithm, and decide not
3981    to insert PHI nodes sometimes, and because value numbering of casts isn't
3982    perfect, we sometimes end up inserting dead code.   This simple DCE-like
3983    pass removes any insertions we made that weren't actually used.  */
3984
3985 static void
3986 remove_dead_inserted_code (void)
3987 {
3988   VEC(tree,heap) *worklist = NULL;
3989   int i;
3990   tree t;
3991
3992   worklist = VEC_alloc (tree, heap, VEC_length (tree, inserted_exprs));
3993   for (i = 0; VEC_iterate (tree, inserted_exprs, i, t); i++)
3994     {
3995       if (NECESSARY (t))
3996         VEC_quick_push (tree, worklist, t);
3997     }
3998   while (VEC_length (tree, worklist) > 0)
3999     {
4000       t = VEC_pop (tree, worklist);
4001
4002       /* PHI nodes are somewhat special in that each PHI alternative has
4003          data and control dependencies.  All the statements feeding the
4004          PHI node's arguments are always necessary. */
4005       if (TREE_CODE (t) == PHI_NODE)
4006         {
4007           int k;
4008
4009           VEC_reserve (tree, heap, worklist, PHI_NUM_ARGS (t));
4010           for (k = 0; k < PHI_NUM_ARGS (t); k++)
4011             {
4012               tree arg = PHI_ARG_DEF (t, k);
4013               if (TREE_CODE (arg) == SSA_NAME)
4014                 {
4015                   arg = mark_operand_necessary (arg);
4016                   if (arg)
4017                     VEC_quick_push (tree, worklist, arg);
4018                 }
4019             }
4020         }
4021       else
4022         {
4023           /* Propagate through the operands.  Examine all the USE, VUSE and
4024              VDEF operands in this statement.  Mark all the statements
4025              which feed this statement's uses as necessary.  */
4026           ssa_op_iter iter;
4027           tree use;
4028
4029           /* The operands of VDEF expressions are also needed as they
4030              represent potential definitions that may reach this
4031              statement (VDEF operands allow us to follow def-def
4032              links).  */
4033
4034           FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
4035             {
4036               tree n = mark_operand_necessary (use);
4037               if (n)
4038                 VEC_safe_push (tree, heap, worklist, n);
4039             }
4040         }
4041     }
4042
4043   for (i = 0; VEC_iterate (tree, inserted_exprs, i, t); i++)
4044     {
4045       if (!NECESSARY (t))
4046         {
4047           block_stmt_iterator bsi;
4048
4049           if (dump_file && (dump_flags & TDF_DETAILS))
4050             {
4051               fprintf (dump_file, "Removing unnecessary insertion:");
4052               print_generic_stmt (dump_file, t, 0);
4053             }
4054
4055           if (TREE_CODE (t) == PHI_NODE)
4056             {
4057               remove_phi_node (t, NULL_TREE, true);
4058             }
4059           else
4060             {
4061               bsi = bsi_for_stmt (t);
4062               bsi_remove (&bsi, true);
4063               release_defs (t);
4064             }
4065         }
4066     }
4067   VEC_free (tree, heap, worklist);
4068 }
4069
4070 /* Initialize data structures used by PRE.  */
4071
4072 static void
4073 init_pre (bool do_fre)
4074 {
4075   basic_block bb;
4076
4077   next_expression_id = 1;
4078   expressions = NULL;
4079   VEC_safe_push (pre_expr, heap, expressions, NULL);
4080   value_expressions = VEC_alloc (bitmap_set_t, heap, get_max_value_id () + 1);
4081   VEC_safe_grow_cleared (bitmap_set_t, heap, value_expressions,
4082                          get_max_value_id() + 1);
4083
4084   in_fre = do_fre;
4085
4086   inserted_exprs = NULL;
4087   need_creation = NULL;
4088   pretemp = NULL_TREE;
4089   storetemp = NULL_TREE;
4090   prephitemp = NULL_TREE;
4091
4092   connect_infinite_loops_to_exit ();
4093   memset (&pre_stats, 0, sizeof (pre_stats));
4094
4095
4096   postorder = XNEWVEC (int, n_basic_blocks - NUM_FIXED_BLOCKS);
4097   post_order_compute (postorder, false, false);
4098
4099   FOR_ALL_BB (bb)
4100     bb->aux = XCNEWVEC (struct bb_bitmap_sets, 1);
4101
4102   calculate_dominance_info (CDI_POST_DOMINATORS);
4103   calculate_dominance_info (CDI_DOMINATORS);
4104
4105   bitmap_obstack_initialize (&grand_bitmap_obstack);
4106   phi_translate_table = htab_create (5110, expr_pred_trans_hash,
4107                                      expr_pred_trans_eq, free);
4108   expression_to_id = htab_create (num_ssa_names * 3,
4109                                   pre_expr_hash,
4110                                   pre_expr_eq, NULL);
4111   seen_during_translate = BITMAP_ALLOC (&grand_bitmap_obstack);
4112   bitmap_set_pool = create_alloc_pool ("Bitmap sets",
4113                                        sizeof (struct bitmap_set), 30);
4114   pre_expr_pool = create_alloc_pool ("pre_expr nodes",
4115                                      sizeof (struct pre_expr_d), 30);
4116   FOR_ALL_BB (bb)
4117     {
4118       EXP_GEN (bb) = bitmap_set_new ();
4119       PHI_GEN (bb) = bitmap_set_new ();
4120       TMP_GEN (bb) = bitmap_set_new ();
4121       AVAIL_OUT (bb) = bitmap_set_new ();
4122     }
4123   maximal_set = in_fre ? NULL : bitmap_set_new ();
4124
4125   need_eh_cleanup = BITMAP_ALLOC (NULL);
4126 }
4127
4128
4129 /* Deallocate data structures used by PRE.  */
4130
4131 static void
4132 fini_pre (void)
4133 {
4134   basic_block bb;
4135
4136   free (postorder);
4137   VEC_free (bitmap_set_t, heap, value_expressions);
4138   VEC_free (tree, heap, inserted_exprs);
4139   VEC_free (tree, heap, need_creation);
4140   bitmap_obstack_release (&grand_bitmap_obstack);
4141   free_alloc_pool (bitmap_set_pool);
4142   free_alloc_pool (pre_expr_pool);
4143   htab_delete (phi_translate_table);
4144   htab_delete (expression_to_id);
4145   remove_fake_exit_edges ();
4146
4147   FOR_ALL_BB (bb)
4148     {
4149       free (bb->aux);
4150       bb->aux = NULL;
4151     }
4152
4153   free_dominance_info (CDI_POST_DOMINATORS);
4154
4155   if (!bitmap_empty_p (need_eh_cleanup))
4156     {
4157       tree_purge_all_dead_eh_edges (need_eh_cleanup);
4158       cleanup_tree_cfg ();
4159     }
4160
4161   BITMAP_FREE (need_eh_cleanup);
4162
4163   if (current_loops != NULL)
4164     loop_optimizer_finalize ();
4165 }
4166
4167 /* Main entry point to the SSA-PRE pass.  DO_FRE is true if the caller
4168    only wants to do full redundancy elimination.  */
4169
4170 static unsigned int
4171 execute_pre (bool do_fre)
4172 {
4173   unsigned int todo = 0;
4174
4175   do_partial_partial = optimize > 2;
4176
4177   /* This has to happen before SCCVN runs because
4178      loop_optimizer_init may create new phis, etc.  */
4179   if (!do_fre)
4180     loop_optimizer_init (LOOPS_NORMAL);
4181   if (0 && !do_fre)
4182     insert_fake_stores ();
4183
4184   if (!run_scc_vn (do_fre))
4185     {
4186       if (!do_fre)
4187         {
4188           remove_dead_inserted_code ();
4189           loop_optimizer_finalize ();
4190         }
4191       
4192       return 0;
4193     }
4194   init_pre (do_fre);
4195
4196
4197   /* Collect and value number expressions computed in each basic block.  */
4198   compute_avail ();
4199
4200   if (dump_file && (dump_flags & TDF_DETAILS))
4201     {
4202       basic_block bb;
4203
4204       FOR_ALL_BB (bb)
4205         {
4206           print_bitmap_set (dump_file, EXP_GEN (bb), "exp_gen", bb->index);
4207           print_bitmap_set (dump_file, TMP_GEN (bb), "tmp_gen",
4208                                   bb->index);
4209           print_bitmap_set (dump_file, AVAIL_OUT (bb), "avail_out",
4210                                   bb->index);
4211         }
4212     }
4213
4214   /* Insert can get quite slow on an incredibly large number of basic
4215      blocks due to some quadratic behavior.  Until this behavior is
4216      fixed, don't run it when he have an incredibly large number of
4217      bb's.  If we aren't going to run insert, there is no point in
4218      computing ANTIC, either, even though it's plenty fast.  */
4219   if (!do_fre && n_basic_blocks < 4000)
4220     {
4221       compute_antic ();
4222       insert ();
4223     }
4224
4225   /* Remove all the redundant expressions.  */
4226   todo |= eliminate ();
4227
4228   statistics_counter_event (cfun, "Insertions", pre_stats.insertions);
4229   statistics_counter_event (cfun, "PA inserted", pre_stats.pa_insert);
4230   statistics_counter_event (cfun, "New PHIs", pre_stats.phis);
4231   statistics_counter_event (cfun, "Eliminated", pre_stats.eliminations);
4232   statistics_counter_event (cfun, "Constified", pre_stats.constified);
4233   bsi_commit_edge_inserts ();
4234
4235   clear_expression_ids ();
4236   free_scc_vn ();
4237   if (!do_fre)
4238     {
4239       remove_dead_inserted_code ();
4240       if (0)
4241         realify_fake_stores ();
4242     }
4243
4244   fini_pre ();
4245
4246   return todo;
4247 }
4248
4249 /* Gate and execute functions for PRE.  */
4250
4251 static unsigned int
4252 do_pre (void)
4253 {
4254   return TODO_rebuild_alias | execute_pre (false);
4255 }
4256
4257 static bool
4258 gate_pre (void)
4259 {
4260   return flag_tree_pre != 0;
4261 }
4262
4263 struct gimple_opt_pass pass_pre =
4264 {
4265  {
4266   GIMPLE_PASS,
4267   "pre",                                /* name */
4268   gate_pre,                             /* gate */
4269   do_pre,                               /* execute */
4270   NULL,                                 /* sub */
4271   NULL,                                 /* next */
4272   0,                                    /* static_pass_number */
4273   TV_TREE_PRE,                          /* tv_id */
4274   PROP_no_crit_edges | PROP_cfg
4275     | PROP_ssa | PROP_alias,            /* properties_required */
4276   0,                                    /* properties_provided */
4277   0,                                    /* properties_destroyed */
4278   0,                                    /* todo_flags_start */
4279   TODO_update_ssa_only_virtuals | TODO_dump_func | TODO_ggc_collect
4280   | TODO_verify_ssa /* todo_flags_finish */
4281  }
4282 };
4283
4284
4285 /* Gate and execute functions for FRE.  */
4286
4287 static unsigned int
4288 execute_fre (void)
4289 {
4290   return execute_pre (true);
4291 }
4292
4293 static bool
4294 gate_fre (void)
4295 {
4296   return flag_tree_fre != 0;
4297 }
4298
4299 struct gimple_opt_pass pass_fre =
4300 {
4301  {
4302   GIMPLE_PASS,
4303   "fre",                                /* name */
4304   gate_fre,                             /* gate */
4305   execute_fre,                          /* execute */
4306   NULL,                                 /* sub */
4307   NULL,                                 /* next */
4308   0,                                    /* static_pass_number */
4309   TV_TREE_FRE,                          /* tv_id */
4310   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
4311   0,                                    /* properties_provided */
4312   0,                                    /* properties_destroyed */
4313   0,                                    /* todo_flags_start */
4314   TODO_dump_func | TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
4315  }
4316 };