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