OSDN Git Service

2009-01-29 Robert Millan <rmh@aybabtu.com>
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-pre.c
1 /* SSA-PRE for trees.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007
3    Free Software Foundation, Inc.
4    Contributed by Daniel Berlin <dan@dberlin.org> and Steven Bosscher
5    <stevenb@suse.de>
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "ggc.h"
28 #include "tree.h"
29 #include "basic-block.h"
30 #include "diagnostic.h"
31 #include "tree-inline.h"
32 #include "tree-flow.h"
33 #include "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_expr (PRE_EXPR_NAME (e), 0);
220     case NARY:
221       return vn_nary_op_compute_hash (PRE_EXPR_NARY (e));
222     case REFERENCE:
223       return vn_reference_compute_hash (PRE_EXPR_REFERENCE (e));
224     default:
225       abort ();
226     }
227 }
228
229
230 /* Next global expression id number.  */
231 static unsigned int next_expression_id;
232
233 /* Mapping from expression to id number we can use in bitmap sets.  */
234 DEF_VEC_P (pre_expr);
235 DEF_VEC_ALLOC_P (pre_expr, heap);
236 static VEC(pre_expr, heap) *expressions;
237 static htab_t expression_to_id;
238
239 /* Allocate an expression id for EXPR.  */
240
241 static inline unsigned int
242 alloc_expression_id (pre_expr expr)
243 {
244   void **slot;
245   /* Make sure we won't overflow. */
246   gcc_assert (next_expression_id + 1 > next_expression_id);
247   expr->id = next_expression_id++;
248   VEC_safe_push (pre_expr, heap, expressions, expr);
249   slot = htab_find_slot (expression_to_id, expr, INSERT);
250   gcc_assert (!*slot);
251   *slot = expr;
252   return next_expression_id - 1;
253 }
254
255 /* Return the expression id for tree EXPR.  */
256
257 static inline unsigned int
258 get_expression_id (const pre_expr expr)
259 {
260   return expr->id;
261 }
262
263 static inline unsigned int
264 lookup_expression_id (const pre_expr expr)
265 {
266   void **slot;
267
268   slot = htab_find_slot (expression_to_id, expr, NO_INSERT);
269   if (!slot)
270     return 0;
271   return ((pre_expr)*slot)->id;
272 }
273
274 /* Return the existing expression id for EXPR, or create one if one
275    does not exist yet.  */
276
277 static inline unsigned int
278 get_or_alloc_expression_id (pre_expr expr)
279 {
280   unsigned int id = lookup_expression_id (expr);
281   if (id == 0)
282     return alloc_expression_id (expr);
283   return expr->id = id;
284 }
285
286 /* Return the expression that has expression id ID */
287
288 static inline pre_expr
289 expression_for_id (unsigned int id)
290 {
291   return VEC_index (pre_expr, expressions, id);
292 }
293
294 /* Free the expression id field in all of our expressions,
295    and then destroy the expressions array.  */
296
297 static void
298 clear_expression_ids (void)
299 {
300   VEC_free (pre_expr, heap, expressions);
301 }
302
303 static alloc_pool pre_expr_pool;
304
305 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it.  */
306
307 static pre_expr
308 get_or_alloc_expr_for_name (tree name)
309 {
310   pre_expr result = (pre_expr) pool_alloc (pre_expr_pool);
311   unsigned int result_id;
312
313   result->kind = NAME;
314   result->id = 0;
315   PRE_EXPR_NAME (result) = name;
316   result_id = lookup_expression_id (result);
317   if (result_id != 0)
318     {
319       pool_free (pre_expr_pool, result);
320       result = expression_for_id (result_id);
321       return result;
322     }
323   get_or_alloc_expression_id (result);
324   return result;
325 }
326
327 static bool in_fre = false;
328
329 /* An unordered bitmap set.  One bitmap tracks values, the other,
330    expressions.  */
331 typedef struct bitmap_set
332 {
333   bitmap expressions;
334   bitmap values;
335 } *bitmap_set_t;
336
337 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi)            \
338   EXECUTE_IF_SET_IN_BITMAP((set)->expressions, 0, (id), (bi))
339
340 /* Mapping from value id to expressions with that value_id.  */
341 DEF_VEC_P (bitmap_set_t);
342 DEF_VEC_ALLOC_P (bitmap_set_t, heap);
343 static VEC(bitmap_set_t, heap) *value_expressions;
344
345 /* Sets that we need to keep track of.  */
346 typedef struct bb_bitmap_sets
347 {
348   /* The EXP_GEN set, which represents expressions/values generated in
349      a basic block.  */
350   bitmap_set_t exp_gen;
351
352   /* The PHI_GEN set, which represents PHI results generated in a
353      basic block.  */
354   bitmap_set_t phi_gen;
355
356   /* The TMP_GEN set, which represents results/temporaries generated
357      in a basic block. IE the LHS of an expression.  */
358   bitmap_set_t tmp_gen;
359
360   /* The AVAIL_OUT set, which represents which values are available in
361      a given basic block.  */
362   bitmap_set_t avail_out;
363
364   /* The ANTIC_IN set, which represents which values are anticipatable
365      in a given basic block.  */
366   bitmap_set_t antic_in;
367
368   /* The PA_IN set, which represents which values are
369      partially anticipatable in a given basic block.  */
370   bitmap_set_t pa_in;
371
372   /* The NEW_SETS set, which is used during insertion to augment the
373      AVAIL_OUT set of blocks with the new insertions performed during
374      the current iteration.  */
375   bitmap_set_t new_sets;
376
377   /* True if we have visited this block during ANTIC calculation.  */
378   unsigned int visited:1;
379
380   /* True we have deferred processing this block during ANTIC
381      calculation until its successor is processed.  */
382   unsigned int deferred : 1;
383 } *bb_value_sets_t;
384
385 #define EXP_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->exp_gen
386 #define PHI_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->phi_gen
387 #define TMP_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->tmp_gen
388 #define AVAIL_OUT(BB)   ((bb_value_sets_t) ((BB)->aux))->avail_out
389 #define ANTIC_IN(BB)    ((bb_value_sets_t) ((BB)->aux))->antic_in
390 #define PA_IN(BB)       ((bb_value_sets_t) ((BB)->aux))->pa_in
391 #define NEW_SETS(BB)    ((bb_value_sets_t) ((BB)->aux))->new_sets
392 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
393 #define BB_DEFERRED(BB) ((bb_value_sets_t) ((BB)->aux))->deferred
394
395
396 /* Maximal set of values, used to initialize the ANTIC problem, which
397    is an intersection problem.  */
398 static bitmap_set_t maximal_set;
399
400 /* Basic block list in postorder.  */
401 static int *postorder;
402
403 /* This structure is used to keep track of statistics on what
404    optimization PRE was able to perform.  */
405 static struct
406 {
407   /* The number of RHS computations eliminated by PRE.  */
408   int eliminations;
409
410   /* The number of new expressions/temporaries generated by PRE.  */
411   int insertions;
412
413   /* The number of inserts found due to partial anticipation  */
414   int pa_insert;
415
416   /* The number of new PHI nodes added by PRE.  */
417   int phis;
418
419   /* The number of values found constant.  */
420   int constified;
421
422 } pre_stats;
423
424 static bool do_partial_partial;
425 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int, gimple);
426 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
427 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
428 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
429 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
430 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
431 static void bitmap_insert_into_set_1 (bitmap_set_t, pre_expr, bool);
432 static bitmap_set_t bitmap_set_new (void);
433 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
434                                          gimple, tree);
435 static tree find_or_generate_expression (basic_block, pre_expr, gimple_seq *,
436                                          gimple);
437 static unsigned int get_expr_value_id (pre_expr);
438
439 /* We can add and remove elements and entries to and from sets
440    and hash tables, so we use alloc pools for them.  */
441
442 static alloc_pool bitmap_set_pool;
443 static bitmap_obstack grand_bitmap_obstack;
444
445 /* To avoid adding 300 temporary variables when we only need one, we
446    only create one temporary variable, on demand, and build ssa names
447    off that.  We do have to change the variable if the types don't
448    match the current variable's type.  */
449 static tree pretemp;
450 static tree storetemp;
451 static tree prephitemp;
452
453 /* Set of blocks with statements that have had its EH information
454    cleaned up.  */
455 static bitmap need_eh_cleanup;
456
457 /* Which expressions have been seen during a given phi translation.  */
458 static bitmap seen_during_translate;
459
460 /* The phi_translate_table caches phi translations for a given
461    expression and predecessor.  */
462
463 static htab_t phi_translate_table;
464
465 /* A three tuple {e, pred, v} used to cache phi translations in the
466    phi_translate_table.  */
467
468 typedef struct expr_pred_trans_d
469 {
470   /* The expression.  */
471   pre_expr e;
472
473   /* The predecessor block along which we translated the expression.  */
474   basic_block pred;
475
476   /* The value that resulted from the translation.  */
477   pre_expr v;
478
479   /* The hashcode for the expression, pred pair. This is cached for
480      speed reasons.  */
481   hashval_t hashcode;
482 } *expr_pred_trans_t;
483 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
484
485 /* Return the hash value for a phi translation table entry.  */
486
487 static hashval_t
488 expr_pred_trans_hash (const void *p)
489 {
490   const_expr_pred_trans_t const ve = (const_expr_pred_trans_t) p;
491   return ve->hashcode;
492 }
493
494 /* Return true if two phi translation table entries are the same.
495    P1 and P2 should point to the expr_pred_trans_t's to be compared.*/
496
497 static int
498 expr_pred_trans_eq (const void *p1, const void *p2)
499 {
500   const_expr_pred_trans_t const ve1 = (const_expr_pred_trans_t) p1;
501   const_expr_pred_trans_t const ve2 = (const_expr_pred_trans_t) p2;
502   basic_block b1 = ve1->pred;
503   basic_block b2 = ve2->pred;
504
505   /* If they are not translations for the same basic block, they can't
506      be equal.  */
507   if (b1 != b2)
508     return false;
509   return pre_expr_eq (ve1->e, ve2->e);
510 }
511
512 /* Search in the phi translation table for the translation of
513    expression E in basic block PRED.
514    Return the translated value, if found, NULL otherwise.  */
515
516 static inline pre_expr
517 phi_trans_lookup (pre_expr e, basic_block pred)
518 {
519   void **slot;
520   struct expr_pred_trans_d ept;
521
522   ept.e = e;
523   ept.pred = pred;
524   ept.hashcode = iterative_hash_hashval_t (pre_expr_hash (e), pred->index);
525   slot = htab_find_slot_with_hash (phi_translate_table, &ept, ept.hashcode,
526                                    NO_INSERT);
527   if (!slot)
528     return NULL;
529   else
530     return ((expr_pred_trans_t) *slot)->v;
531 }
532
533
534 /* Add the tuple mapping from {expression E, basic block PRED} to
535    value V, to the phi translation table.  */
536
537 static inline void
538 phi_trans_add (pre_expr e, pre_expr v, basic_block pred)
539 {
540   void **slot;
541   expr_pred_trans_t new_pair = XNEW (struct expr_pred_trans_d);
542   new_pair->e = e;
543   new_pair->pred = pred;
544   new_pair->v = v;
545   new_pair->hashcode = iterative_hash_hashval_t (pre_expr_hash (e),
546                                                  pred->index);
547
548   slot = htab_find_slot_with_hash (phi_translate_table, new_pair,
549                                    new_pair->hashcode, INSERT);
550   if (*slot)
551     free (*slot);
552   *slot = (void *) new_pair;
553 }
554
555
556 /* Add expression E to the expression set of value id V.  */
557
558 void
559 add_to_value (unsigned int v, pre_expr e)
560 {
561   bitmap_set_t set;
562
563   gcc_assert (get_expr_value_id (e) == v);
564
565   if (v >= VEC_length (bitmap_set_t, value_expressions))
566     {
567       VEC_safe_grow_cleared (bitmap_set_t, heap, value_expressions,
568                              v + 1);
569     }
570
571   set = VEC_index (bitmap_set_t, value_expressions, v);
572   if (!set)
573     {
574       set = bitmap_set_new ();
575       VEC_replace (bitmap_set_t, value_expressions, v, set);
576     }
577
578   bitmap_insert_into_set_1 (set, e, true);
579 }
580
581 /* Create a new bitmap set and return it.  */
582
583 static bitmap_set_t
584 bitmap_set_new (void)
585 {
586   bitmap_set_t ret = (bitmap_set_t) pool_alloc (bitmap_set_pool);
587   ret->expressions = BITMAP_ALLOC (&grand_bitmap_obstack);
588   ret->values = BITMAP_ALLOC (&grand_bitmap_obstack);
589   return ret;
590 }
591
592 /* Return the value id for a PRE expression EXPR.  */
593
594 static unsigned int
595 get_expr_value_id (pre_expr expr)
596 {
597   switch (expr->kind)
598     {
599     case CONSTANT:
600       {
601         unsigned int id;
602         id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
603         if (id == 0)
604           {
605             id = get_or_alloc_constant_value_id (PRE_EXPR_CONSTANT (expr));
606             add_to_value (id, expr);
607           }
608         return id;
609       }
610     case NAME:
611       return VN_INFO (PRE_EXPR_NAME (expr))->value_id;
612     case NARY:
613       return PRE_EXPR_NARY (expr)->value_id;
614     case REFERENCE:
615       return PRE_EXPR_REFERENCE (expr)->value_id;
616     default:
617       gcc_unreachable ();
618     }
619 }
620
621 /* Remove an expression EXPR from a bitmapped set.  */
622
623 static void
624 bitmap_remove_from_set (bitmap_set_t set, pre_expr expr)
625 {
626   unsigned int val  = get_expr_value_id (expr);
627   if (!value_id_constant_p (val))
628     {
629       bitmap_clear_bit (set->values, val);
630       bitmap_clear_bit (set->expressions, get_expression_id (expr));
631     }
632 }
633
634 static void
635 bitmap_insert_into_set_1 (bitmap_set_t set, pre_expr expr,
636                           bool allow_constants)
637 {
638   unsigned int val  = get_expr_value_id (expr);
639   if (allow_constants || !value_id_constant_p (val))
640     {
641       /* We specifically expect this and only this function to be able to
642          insert constants into a set.  */
643       bitmap_set_bit (set->values, val);
644       bitmap_set_bit (set->expressions, get_or_alloc_expression_id (expr));
645     }
646 }
647
648 /* Insert an expression EXPR into a bitmapped set.  */
649
650 static void
651 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
652 {
653   bitmap_insert_into_set_1 (set, expr, false);
654 }
655
656 /* Copy a bitmapped set ORIG, into bitmapped set DEST.  */
657
658 static void
659 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
660 {
661   bitmap_copy (dest->expressions, orig->expressions);
662   bitmap_copy (dest->values, orig->values);
663 }
664
665
666 /* Free memory used up by SET.  */
667 static void
668 bitmap_set_free (bitmap_set_t set)
669 {
670   BITMAP_FREE (set->expressions);
671   BITMAP_FREE (set->values);
672 }
673
674
675 /* A comparison function for use in qsort to top sort a bitmap set.  Simply
676    subtracts value ids, since they are created with leaves before
677    their parent users (IE topological order).  */
678
679 static int
680 value_id_compare (const void *pa, const void *pb)
681 {
682   const unsigned int vha = get_expr_value_id (*((const pre_expr *)pa));
683   const unsigned int vhb = get_expr_value_id (*((const pre_expr *)pb));
684
685   return vha - vhb;
686 }
687
688 /* Generate an topological-ordered array of bitmap set SET.  */
689
690 static VEC(pre_expr, heap) *
691 sorted_array_from_bitmap_set (bitmap_set_t set)
692 {
693   unsigned int i;
694   bitmap_iterator bi;
695   VEC(pre_expr, heap) *result = NULL;
696
697   FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
698     VEC_safe_push (pre_expr, heap, result, expression_for_id (i));
699
700   qsort (VEC_address (pre_expr, result), VEC_length (pre_expr, result),
701          sizeof (pre_expr), value_id_compare);
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             /* Handle constant. */
1707             if (is_gimple_min_invariant (def))
1708               return get_or_alloc_expr_for_constant (def);
1709
1710             if (TREE_CODE (def) == SSA_NAME && ssa_undefined_value_p (def))
1711               return NULL;
1712
1713             newexpr = get_or_alloc_expr_for_name (def);
1714             return newexpr;
1715           }
1716       }
1717       return expr;
1718
1719     default:
1720       gcc_unreachable ();
1721     }
1722 }
1723
1724 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1725    the phis in PRED.
1726    Return NULL if we can't find a leader for each part of the
1727    translated expression.  */
1728
1729 static pre_expr
1730 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1731                basic_block pred, basic_block phiblock)
1732 {
1733   bitmap_clear (seen_during_translate);
1734   return phi_translate_1 (expr, set1, set2, pred, phiblock,
1735                           seen_during_translate);
1736 }
1737
1738 /* For each expression in SET, translate the values through phi nodes
1739    in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1740    expressions in DEST.  */
1741
1742 static void
1743 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1744                    basic_block phiblock)
1745 {
1746   VEC (pre_expr, heap) *exprs;
1747   pre_expr expr;
1748   int i;
1749
1750   if (!phi_nodes (phiblock))
1751     {
1752       bitmap_set_copy (dest, set);
1753       return;
1754     }
1755
1756   exprs = sorted_array_from_bitmap_set (set);
1757   for (i = 0; VEC_iterate (pre_expr, exprs, i, expr); i++)
1758     {
1759       pre_expr translated;
1760       translated = phi_translate (expr, set, NULL, pred, phiblock);
1761
1762       /* Don't add empty translations to the cache  */
1763       if (translated)
1764         phi_trans_add (expr, translated, pred);
1765
1766       if (translated != NULL)
1767         bitmap_value_insert_into_set (dest, translated);
1768     }
1769   VEC_free (pre_expr, heap, exprs);
1770 }
1771
1772 /* Find the leader for a value (i.e., the name representing that
1773    value) in a given set, and return it.  If STMT is non-NULL it
1774    makes sure the defining statement for the leader dominates it.
1775    Return NULL if no leader is found.  */
1776
1777 static pre_expr
1778 bitmap_find_leader (bitmap_set_t set, unsigned int val, gimple stmt)
1779 {
1780   if (value_id_constant_p (val))
1781     {
1782       unsigned int i;
1783       bitmap_iterator bi;
1784       bitmap_set_t exprset = VEC_index (bitmap_set_t, value_expressions, val);
1785
1786       FOR_EACH_EXPR_ID_IN_SET (exprset, i, bi)
1787         {
1788           pre_expr expr = expression_for_id (i);
1789           if (expr->kind == CONSTANT)
1790             return expr;
1791         }
1792     }
1793   if (bitmap_set_contains_value (set, val))
1794     {
1795       /* Rather than walk the entire bitmap of expressions, and see
1796          whether any of them has the value we are looking for, we look
1797          at the reverse mapping, which tells us the set of expressions
1798          that have a given value (IE value->expressions with that
1799          value) and see if any of those expressions are in our set.
1800          The number of expressions per value is usually significantly
1801          less than the number of expressions in the set.  In fact, for
1802          large testcases, doing it this way is roughly 5-10x faster
1803          than walking the bitmap.
1804          If this is somehow a significant lose for some cases, we can
1805          choose which set to walk based on which set is smaller.  */
1806       unsigned int i;
1807       bitmap_iterator bi;
1808       bitmap_set_t exprset = VEC_index (bitmap_set_t, value_expressions, val);
1809
1810       EXECUTE_IF_AND_IN_BITMAP (exprset->expressions,
1811                                 set->expressions, 0, i, bi)
1812         {
1813           pre_expr val = expression_for_id (i);
1814           /* At the point where stmt is not null, there should always
1815              be an SSA_NAME first in the list of expressions.  */
1816           if (stmt)
1817             {
1818               gimple def_stmt = SSA_NAME_DEF_STMT (PRE_EXPR_NAME (val));
1819               if (gimple_code (def_stmt) != GIMPLE_PHI
1820                   && gimple_bb (def_stmt) == gimple_bb (stmt)
1821                   && gimple_uid (def_stmt) >= gimple_uid (stmt))
1822                 continue;
1823             }
1824           return val;
1825         }
1826     }
1827   return NULL;
1828 }
1829
1830 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1831    BLOCK by seeing if it is not killed in the block.  Note that we are
1832    only determining whether there is a store that kills it.  Because
1833    of the order in which clean iterates over values, we are guaranteed
1834    that altered operands will have caused us to be eliminated from the
1835    ANTIC_IN set already.  */
1836
1837 static bool
1838 value_dies_in_block_x (pre_expr expr, basic_block block)
1839 {
1840   int i;
1841   tree vuse;
1842   VEC (tree, gc) *vuses = PRE_EXPR_REFERENCE (expr)->vuses;
1843
1844   /* Conservatively, a value dies if it's vuses are defined in this
1845      block, unless they come from phi nodes (which are merge operations,
1846      rather than stores.  */
1847   for (i = 0; VEC_iterate (tree, vuses, i, vuse); i++)
1848     {
1849       gimple def = SSA_NAME_DEF_STMT (vuse);
1850
1851       if (gimple_bb (def) != block)
1852         continue;
1853       if (gimple_code (def) == GIMPLE_PHI)
1854         continue;
1855       return true;
1856     }
1857   return false;
1858 }
1859
1860
1861 #define union_contains_value(SET1, SET2, VAL)                   \
1862   (bitmap_set_contains_value ((SET1), (VAL))                    \
1863    || ((SET2) && bitmap_set_contains_value ((SET2), (VAL))))
1864
1865 /* Determine if vn_reference_op_t VRO is legal in SET1 U SET2.
1866  */
1867 static bool
1868 vro_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2,
1869                    vn_reference_op_t vro)
1870 {
1871   if (vro->op0 && TREE_CODE (vro->op0) == SSA_NAME)
1872     {
1873       struct pre_expr_d temp;
1874       temp.kind = NAME;
1875       temp.id = 0;
1876       PRE_EXPR_NAME (&temp) = vro->op0;
1877       temp.id = lookup_expression_id (&temp);
1878       if (temp.id == 0)
1879         return false;
1880       if (!union_contains_value (set1, set2,
1881                                  get_expr_value_id (&temp)))
1882         return false;
1883     }
1884   if (vro->op1 && TREE_CODE (vro->op1) == SSA_NAME)
1885     {
1886       struct pre_expr_d temp;
1887       temp.kind = NAME;
1888       temp.id = 0;
1889       PRE_EXPR_NAME (&temp) = vro->op1;
1890       temp.id = lookup_expression_id (&temp);
1891       if (temp.id == 0)
1892         return false;
1893       if (!union_contains_value (set1, set2,
1894                                  get_expr_value_id (&temp)))
1895         return false;
1896     }
1897
1898   if (vro->op2 && TREE_CODE (vro->op2) == SSA_NAME)
1899     {
1900       struct pre_expr_d temp;
1901       temp.kind = NAME;
1902       temp.id = 0;
1903       PRE_EXPR_NAME (&temp) = vro->op2;
1904       temp.id = lookup_expression_id (&temp);
1905       if (temp.id == 0)
1906         return false;
1907       if (!union_contains_value (set1, set2,
1908                                  get_expr_value_id (&temp)))
1909         return false;
1910     }
1911
1912   return true;
1913 }
1914
1915 /* Determine if the expression EXPR is valid in SET1 U SET2.
1916    ONLY SET2 CAN BE NULL.
1917    This means that we have a leader for each part of the expression
1918    (if it consists of values), or the expression is an SSA_NAME.
1919    For loads/calls, we also see if the vuses are killed in this block.
1920 */
1921
1922 static bool
1923 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr,
1924                basic_block block)
1925 {
1926   switch (expr->kind)
1927     {
1928     case NAME:
1929       return bitmap_set_contains_expr (AVAIL_OUT (block), expr);
1930     case NARY:
1931       {
1932         unsigned int i;
1933         vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1934         for (i = 0; i < nary->length; i++)
1935           {
1936             if (TREE_CODE (nary->op[i]) == SSA_NAME)
1937               {
1938                 struct pre_expr_d temp;
1939                 temp.kind = NAME;
1940                 temp.id = 0;
1941                 PRE_EXPR_NAME (&temp) = nary->op[i];
1942                 temp.id = lookup_expression_id (&temp);
1943                 if (temp.id == 0)
1944                   return false;
1945                 if (!union_contains_value (set1, set2,
1946                                            get_expr_value_id (&temp)))
1947                   return false;
1948               }
1949           }
1950         return true;
1951       }
1952       break;
1953     case REFERENCE:
1954       {
1955         vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1956         vn_reference_op_t vro;
1957         unsigned int i;
1958
1959         for (i = 0; VEC_iterate (vn_reference_op_s, ref->operands, i, vro); i++)
1960           {
1961             if (!vro_valid_in_sets (set1, set2, vro))
1962               return false;
1963           }
1964         return !value_dies_in_block_x (expr, block);
1965       }
1966     default:
1967       gcc_unreachable ();
1968     }
1969 }
1970
1971 /* Clean the set of expressions that are no longer valid in SET1 or
1972    SET2.  This means expressions that are made up of values we have no
1973    leaders for in SET1 or SET2.  This version is used for partial
1974    anticipation, which means it is not valid in either ANTIC_IN or
1975    PA_IN.  */
1976
1977 static void
1978 dependent_clean (bitmap_set_t set1, bitmap_set_t set2, basic_block block)
1979 {
1980   VEC (pre_expr, heap) *exprs = sorted_array_from_bitmap_set (set1);
1981   pre_expr expr;
1982   int i;
1983
1984   for (i = 0; VEC_iterate (pre_expr, exprs, i, expr); i++)
1985     {
1986       if (!valid_in_sets (set1, set2, expr, block))
1987         bitmap_remove_from_set (set1, expr);
1988     }
1989   VEC_free (pre_expr, heap, exprs);
1990 }
1991
1992 /* Clean the set of expressions that are no longer valid in SET.  This
1993    means expressions that are made up of values we have no leaders for
1994    in SET.  */
1995
1996 static void
1997 clean (bitmap_set_t set, basic_block block)
1998 {
1999   VEC (pre_expr, heap) *exprs = sorted_array_from_bitmap_set (set);
2000   pre_expr expr;
2001   int i;
2002
2003   for (i = 0; VEC_iterate (pre_expr, exprs, i, expr); i++)
2004     {
2005       if (!valid_in_sets (set, NULL, expr, block))
2006         bitmap_remove_from_set (set, expr);
2007     }
2008   VEC_free (pre_expr, heap, exprs);
2009 }
2010
2011 static sbitmap has_abnormal_preds;
2012
2013 /* List of blocks that may have changed during ANTIC computation and
2014    thus need to be iterated over.  */
2015
2016 static sbitmap changed_blocks;
2017
2018 /* Decide whether to defer a block for a later iteration, or PHI
2019    translate SOURCE to DEST using phis in PHIBLOCK.  Return false if we
2020    should defer the block, and true if we processed it.  */
2021
2022 static bool
2023 defer_or_phi_translate_block (bitmap_set_t dest, bitmap_set_t source,
2024                               basic_block block, basic_block phiblock)
2025 {
2026   if (!BB_VISITED (phiblock))
2027     {
2028       SET_BIT (changed_blocks, block->index);
2029       BB_VISITED (block) = 0;
2030       BB_DEFERRED (block) = 1;
2031       return false;
2032     }
2033   else
2034     phi_translate_set (dest, source, block, phiblock);
2035   return true;
2036 }
2037
2038 /* Compute the ANTIC set for BLOCK.
2039
2040    If succs(BLOCK) > 1 then
2041      ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2042    else if succs(BLOCK) == 1 then
2043      ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2044
2045    ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2046 */
2047
2048 static bool
2049 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2050 {
2051   bool changed = false;
2052   bitmap_set_t S, old, ANTIC_OUT;
2053   bitmap_iterator bi;
2054   unsigned int bii;
2055   edge e;
2056   edge_iterator ei;
2057
2058   old = ANTIC_OUT = S = NULL;
2059   BB_VISITED (block) = 1;
2060
2061   /* If any edges from predecessors are abnormal, antic_in is empty,
2062      so do nothing.  */
2063   if (block_has_abnormal_pred_edge)
2064     goto maybe_dump_sets;
2065
2066   old = ANTIC_IN (block);
2067   ANTIC_OUT = bitmap_set_new ();
2068
2069   /* If the block has no successors, ANTIC_OUT is empty.  */
2070   if (EDGE_COUNT (block->succs) == 0)
2071     ;
2072   /* If we have one successor, we could have some phi nodes to
2073      translate through.  */
2074   else if (single_succ_p (block))
2075     {
2076       basic_block succ_bb = single_succ (block);
2077
2078       /* We trade iterations of the dataflow equations for having to
2079          phi translate the maximal set, which is incredibly slow
2080          (since the maximal set often has 300+ members, even when you
2081          have a small number of blocks).
2082          Basically, we defer the computation of ANTIC for this block
2083          until we have processed it's successor, which will inevitably
2084          have a *much* smaller set of values to phi translate once
2085          clean has been run on it.
2086          The cost of doing this is that we technically perform more
2087          iterations, however, they are lower cost iterations.
2088
2089          Timings for PRE on tramp3d-v4:
2090          without maximal set fix: 11 seconds
2091          with maximal set fix/without deferring: 26 seconds
2092          with maximal set fix/with deferring: 11 seconds
2093      */
2094
2095       if (!defer_or_phi_translate_block (ANTIC_OUT, ANTIC_IN (succ_bb),
2096                                         block, succ_bb))
2097         {
2098           changed = true;
2099           goto maybe_dump_sets;
2100         }
2101     }
2102   /* If we have multiple successors, we take the intersection of all of
2103      them.  Note that in the case of loop exit phi nodes, we may have
2104      phis to translate through.  */
2105   else
2106     {
2107       VEC(basic_block, heap) * worklist;
2108       size_t i;
2109       basic_block bprime, first;
2110
2111       worklist = VEC_alloc (basic_block, heap, EDGE_COUNT (block->succs));
2112       FOR_EACH_EDGE (e, ei, block->succs)
2113         VEC_quick_push (basic_block, worklist, e->dest);
2114       first = VEC_index (basic_block, worklist, 0);
2115
2116       if (phi_nodes (first))
2117         {
2118           bitmap_set_t from = ANTIC_IN (first);
2119
2120           if (!BB_VISITED (first))
2121             from = maximal_set;
2122           phi_translate_set (ANTIC_OUT, from, block, first);
2123         }
2124       else
2125         {
2126           if (!BB_VISITED (first))
2127             bitmap_set_copy (ANTIC_OUT, maximal_set);
2128           else
2129             bitmap_set_copy (ANTIC_OUT, ANTIC_IN (first));
2130         }
2131
2132       for (i = 1; VEC_iterate (basic_block, worklist, i, bprime); i++)
2133         {
2134           if (phi_nodes (bprime))
2135             {
2136               bitmap_set_t tmp = bitmap_set_new ();
2137               bitmap_set_t from = ANTIC_IN (bprime);
2138
2139               if (!BB_VISITED (bprime))
2140                 from = maximal_set;
2141               phi_translate_set (tmp, from, block, bprime);
2142               bitmap_set_and (ANTIC_OUT, tmp);
2143               bitmap_set_free (tmp);
2144             }
2145           else
2146             {
2147               if (!BB_VISITED (bprime))
2148                 bitmap_set_and (ANTIC_OUT, maximal_set);
2149               else
2150                 bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2151             }
2152         }
2153       VEC_free (basic_block, heap, worklist);
2154     }
2155
2156   /* Generate ANTIC_OUT - TMP_GEN.  */
2157   S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2158
2159   /* Start ANTIC_IN with EXP_GEN - TMP_GEN.  */
2160   ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2161                                           TMP_GEN (block));
2162
2163   /* Then union in the ANTIC_OUT - TMP_GEN values,
2164      to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2165   FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2166     bitmap_value_insert_into_set (ANTIC_IN (block),
2167                                   expression_for_id (bii));
2168
2169   clean (ANTIC_IN (block), block);
2170
2171   /* !old->expressions can happen when we deferred a block.  */
2172   if (!old->expressions || !bitmap_set_equal (old, ANTIC_IN (block)))
2173     {
2174       changed = true;
2175       SET_BIT (changed_blocks, block->index);
2176       FOR_EACH_EDGE (e, ei, block->preds)
2177         SET_BIT (changed_blocks, e->src->index);
2178     }
2179   else
2180     RESET_BIT (changed_blocks, block->index);
2181
2182  maybe_dump_sets:
2183   if (dump_file && (dump_flags & TDF_DETAILS))
2184     {
2185       if (!BB_DEFERRED (block) || BB_VISITED (block))
2186         {
2187           if (ANTIC_OUT)
2188             print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2189
2190           print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2191                             block->index);
2192
2193           if (S)
2194             print_bitmap_set (dump_file, S, "S", block->index);
2195         }
2196       else
2197         {
2198           fprintf (dump_file,
2199                    "Block %d was deferred for a future iteration.\n",
2200                    block->index);
2201         }
2202     }
2203   if (old)
2204     bitmap_set_free (old);
2205   if (S)
2206     bitmap_set_free (S);
2207   if (ANTIC_OUT)
2208     bitmap_set_free (ANTIC_OUT);
2209   return changed;
2210 }
2211
2212 /* Compute PARTIAL_ANTIC for BLOCK.
2213
2214    If succs(BLOCK) > 1 then
2215      PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2216      in ANTIC_OUT for all succ(BLOCK)
2217    else if succs(BLOCK) == 1 then
2218      PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2219
2220    PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2221                                   - ANTIC_IN[BLOCK])
2222
2223 */
2224 static bool
2225 compute_partial_antic_aux (basic_block block,
2226                            bool block_has_abnormal_pred_edge)
2227 {
2228   bool changed = false;
2229   bitmap_set_t old_PA_IN;
2230   bitmap_set_t PA_OUT;
2231   edge e;
2232   edge_iterator ei;
2233   unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2234
2235   old_PA_IN = PA_OUT = NULL;
2236
2237   /* If any edges from predecessors are abnormal, antic_in is empty,
2238      so do nothing.  */
2239   if (block_has_abnormal_pred_edge)
2240     goto maybe_dump_sets;
2241
2242   /* If there are too many partially anticipatable values in the
2243      block, phi_translate_set can take an exponential time: stop
2244      before the translation starts.  */
2245   if (max_pa
2246       && single_succ_p (block)
2247       && bitmap_count_bits (PA_IN (single_succ (block))->values) > max_pa)
2248     goto maybe_dump_sets;
2249
2250   old_PA_IN = PA_IN (block);
2251   PA_OUT = bitmap_set_new ();
2252
2253   /* If the block has no successors, ANTIC_OUT is empty.  */
2254   if (EDGE_COUNT (block->succs) == 0)
2255     ;
2256   /* If we have one successor, we could have some phi nodes to
2257      translate through.  Note that we can't phi translate across DFS
2258      back edges in partial antic, because it uses a union operation on
2259      the successors.  For recurrences like IV's, we will end up
2260      generating a new value in the set on each go around (i + 3 (VH.1)
2261      VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever.  */
2262   else if (single_succ_p (block))
2263     {
2264       basic_block succ = single_succ (block);
2265       if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2266         phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2267     }
2268   /* If we have multiple successors, we take the union of all of
2269      them.  */
2270   else
2271     {
2272       VEC(basic_block, heap) * worklist;
2273       size_t i;
2274       basic_block bprime;
2275
2276       worklist = VEC_alloc (basic_block, heap, EDGE_COUNT (block->succs));
2277       FOR_EACH_EDGE (e, ei, block->succs)
2278         {
2279           if (e->flags & EDGE_DFS_BACK)
2280             continue;
2281           VEC_quick_push (basic_block, worklist, e->dest);
2282         }
2283       if (VEC_length (basic_block, worklist) > 0)
2284         {
2285           for (i = 0; VEC_iterate (basic_block, worklist, i, bprime); i++)
2286             {
2287               unsigned int i;
2288               bitmap_iterator bi;
2289
2290               FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2291                 bitmap_value_insert_into_set (PA_OUT,
2292                                               expression_for_id (i));
2293               if (phi_nodes (bprime))
2294                 {
2295                   bitmap_set_t pa_in = bitmap_set_new ();
2296                   phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2297                   FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2298                     bitmap_value_insert_into_set (PA_OUT,
2299                                                   expression_for_id (i));
2300                   bitmap_set_free (pa_in);
2301                 }
2302               else
2303                 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2304                   bitmap_value_insert_into_set (PA_OUT,
2305                                                 expression_for_id (i));
2306             }
2307         }
2308       VEC_free (basic_block, heap, worklist);
2309     }
2310
2311   /* PA_IN starts with PA_OUT - TMP_GEN.
2312      Then we subtract things from ANTIC_IN.  */
2313   PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2314
2315   /* For partial antic, we want to put back in the phi results, since
2316      we will properly avoid making them partially antic over backedges.  */
2317   bitmap_ior_into (PA_IN (block)->values, PHI_GEN (block)->values);
2318   bitmap_ior_into (PA_IN (block)->expressions, PHI_GEN (block)->expressions);
2319
2320   /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2321   bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2322
2323   dependent_clean (PA_IN (block), ANTIC_IN (block), block);
2324
2325   if (!bitmap_set_equal (old_PA_IN, PA_IN (block)))
2326     {
2327       changed = true;
2328       SET_BIT (changed_blocks, block->index);
2329       FOR_EACH_EDGE (e, ei, block->preds)
2330         SET_BIT (changed_blocks, e->src->index);
2331     }
2332   else
2333     RESET_BIT (changed_blocks, block->index);
2334
2335  maybe_dump_sets:
2336   if (dump_file && (dump_flags & TDF_DETAILS))
2337     {
2338       if (PA_OUT)
2339         print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2340
2341       print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2342     }
2343   if (old_PA_IN)
2344     bitmap_set_free (old_PA_IN);
2345   if (PA_OUT)
2346     bitmap_set_free (PA_OUT);
2347   return changed;
2348 }
2349
2350 /* Compute ANTIC and partial ANTIC sets.  */
2351
2352 static void
2353 compute_antic (void)
2354 {
2355   bool changed = true;
2356   int num_iterations = 0;
2357   basic_block block;
2358   int i;
2359
2360   /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2361      We pre-build the map of blocks with incoming abnormal edges here.  */
2362   has_abnormal_preds = sbitmap_alloc (last_basic_block);
2363   sbitmap_zero (has_abnormal_preds);
2364
2365   FOR_EACH_BB (block)
2366     {
2367       edge_iterator ei;
2368       edge e;
2369
2370       FOR_EACH_EDGE (e, ei, block->preds)
2371         {
2372           e->flags &= ~EDGE_DFS_BACK;
2373           if (e->flags & EDGE_ABNORMAL)
2374             {
2375               SET_BIT (has_abnormal_preds, block->index);
2376               break;
2377             }
2378         }
2379
2380       BB_VISITED (block) = 0;
2381       BB_DEFERRED (block) = 0;
2382       /* While we are here, give empty ANTIC_IN sets to each block.  */
2383       ANTIC_IN (block) = bitmap_set_new ();
2384       PA_IN (block) = bitmap_set_new ();
2385     }
2386
2387   /* At the exit block we anticipate nothing.  */
2388   ANTIC_IN (EXIT_BLOCK_PTR) = bitmap_set_new ();
2389   BB_VISITED (EXIT_BLOCK_PTR) = 1;
2390   PA_IN (EXIT_BLOCK_PTR) = bitmap_set_new ();
2391
2392   changed_blocks = sbitmap_alloc (last_basic_block + 1);
2393   sbitmap_ones (changed_blocks);
2394   while (changed)
2395     {
2396       if (dump_file && (dump_flags & TDF_DETAILS))
2397         fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2398       num_iterations++;
2399       changed = false;
2400       for (i = 0; i < n_basic_blocks - NUM_FIXED_BLOCKS; i++)
2401         {
2402           if (TEST_BIT (changed_blocks, postorder[i]))
2403             {
2404               basic_block block = BASIC_BLOCK (postorder[i]);
2405               changed |= compute_antic_aux (block,
2406                                             TEST_BIT (has_abnormal_preds,
2407                                                       block->index));
2408             }
2409         }
2410 #ifdef ENABLE_CHECKING
2411       /* Theoretically possible, but *highly* unlikely.  */
2412       gcc_assert (num_iterations < 500);
2413 #endif
2414     }
2415
2416   statistics_histogram_event (cfun, "compute_antic iterations",
2417                               num_iterations);
2418
2419   if (do_partial_partial)
2420     {
2421       sbitmap_ones (changed_blocks);
2422       mark_dfs_back_edges ();
2423       num_iterations = 0;
2424       changed = true;
2425       while (changed)
2426         {
2427           if (dump_file && (dump_flags & TDF_DETAILS))
2428             fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2429           num_iterations++;
2430           changed = false;
2431           for (i = 0; i < n_basic_blocks - NUM_FIXED_BLOCKS; i++)
2432             {
2433               if (TEST_BIT (changed_blocks, postorder[i]))
2434                 {
2435                   basic_block block = BASIC_BLOCK (postorder[i]);
2436                   changed
2437                     |= compute_partial_antic_aux (block,
2438                                                   TEST_BIT (has_abnormal_preds,
2439                                                             block->index));
2440                 }
2441             }
2442 #ifdef ENABLE_CHECKING
2443           /* Theoretically possible, but *highly* unlikely.  */
2444           gcc_assert (num_iterations < 500);
2445 #endif
2446         }
2447       statistics_histogram_event (cfun, "compute_partial_antic iterations",
2448                                   num_iterations);
2449     }
2450   sbitmap_free (has_abnormal_preds);
2451   sbitmap_free (changed_blocks);
2452 }
2453
2454 /* Return true if we can value number the call in STMT.  This is true
2455    if we have a pure or constant call.  */
2456
2457 static bool
2458 can_value_number_call (gimple stmt)
2459 {
2460   if (gimple_call_flags (stmt) & (ECF_PURE | ECF_CONST))
2461     return true;
2462   return false;
2463 }
2464
2465 /* Return true if OP is an exception handler related operation, such as
2466    FILTER_EXPR or EXC_PTR_EXPR.  */
2467
2468 static bool
2469 is_exception_related (gimple stmt)
2470 {
2471   return (is_gimple_assign (stmt)
2472           && (gimple_assign_rhs_code (stmt) == FILTER_EXPR
2473               || gimple_assign_rhs_code (stmt) == EXC_PTR_EXPR));
2474 }
2475
2476 /* Return true if OP is a tree which we can perform PRE on
2477    on.  This may not match the operations we can value number, but in
2478    a perfect world would.  */
2479
2480 static bool
2481 can_PRE_operation (tree op)
2482 {
2483   return UNARY_CLASS_P (op)
2484     || BINARY_CLASS_P (op)
2485     || COMPARISON_CLASS_P (op)
2486     || TREE_CODE (op) == INDIRECT_REF
2487     || TREE_CODE (op) == COMPONENT_REF
2488     || TREE_CODE (op) == VIEW_CONVERT_EXPR
2489     || TREE_CODE (op) == CALL_EXPR
2490     || TREE_CODE (op) == ARRAY_REF;
2491 }
2492
2493
2494 /* Inserted expressions are placed onto this worklist, which is used
2495    for performing quick dead code elimination of insertions we made
2496    that didn't turn out to be necessary.   */
2497 static VEC(gimple,heap) *inserted_exprs;
2498
2499 /* Pool allocated fake store expressions are placed onto this
2500    worklist, which, after performing dead code elimination, is walked
2501    to see which expressions need to be put into GC'able memory  */
2502 static VEC(gimple, heap) *need_creation;
2503
2504 /* The actual worker for create_component_ref_by_pieces.  */
2505
2506 static tree
2507 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2508                                   unsigned int *operand, gimple_seq *stmts,
2509                                   gimple domstmt)
2510 {
2511   vn_reference_op_t currop = VEC_index (vn_reference_op_s, ref->operands,
2512                                         *operand);
2513   tree genop;
2514   ++*operand;
2515   switch (currop->opcode)
2516     {
2517     case CALL_EXPR:
2518       {
2519         tree folded, sc = currop->op1;
2520         unsigned int nargs = 0;
2521         tree *args = XNEWVEC (tree, VEC_length (vn_reference_op_s,
2522                                                 ref->operands) - 1);
2523         while (*operand < VEC_length (vn_reference_op_s, ref->operands))
2524           {
2525             args[nargs] = create_component_ref_by_pieces_1 (block, ref,
2526                                                             operand, stmts,
2527                                                             domstmt);
2528             nargs++;
2529           }
2530         folded = build_call_array (currop->type,
2531                                    TREE_CODE (currop->op0) == FUNCTION_DECL
2532                                    ? build_fold_addr_expr (currop->op0)
2533                                    : currop->op0,
2534                                    nargs, args);
2535         free (args);
2536         if (sc)
2537           {
2538             pre_expr scexpr = get_or_alloc_expr_for (sc);
2539             sc = find_or_generate_expression (block, scexpr, stmts, domstmt);
2540             if (!sc)
2541               return NULL_TREE;
2542             CALL_EXPR_STATIC_CHAIN (folded) = sc;
2543           }
2544         return folded;
2545       }
2546       break;
2547     case ADDR_EXPR:
2548       if (currop->op0)
2549         {
2550           gcc_assert (is_gimple_min_invariant (currop->op0));
2551           return currop->op0;
2552         }
2553       /* Fallthrough.  */
2554     case REALPART_EXPR:
2555     case IMAGPART_EXPR:
2556     case VIEW_CONVERT_EXPR:
2557       {
2558         tree folded;
2559         tree genop0 = create_component_ref_by_pieces_1 (block, ref,
2560                                                         operand,
2561                                                         stmts, domstmt);
2562         if (!genop0)
2563           return NULL_TREE;
2564         folded = fold_build1 (currop->opcode, currop->type,
2565                               genop0);
2566         return folded;
2567       }
2568       break;
2569     case ALIGN_INDIRECT_REF:
2570     case MISALIGNED_INDIRECT_REF:
2571     case INDIRECT_REF:
2572       {
2573         tree folded;
2574         tree genop1 = create_component_ref_by_pieces_1 (block, ref,
2575                                                         operand,
2576                                                         stmts, domstmt);
2577         if (!genop1)
2578           return NULL_TREE;
2579         genop1 = fold_convert (build_pointer_type (currop->type),
2580                                genop1);
2581
2582         if (currop->opcode == MISALIGNED_INDIRECT_REF)
2583           folded = fold_build2 (currop->opcode, currop->type,
2584                                 genop1, currop->op1);
2585         else
2586           folded = fold_build1 (currop->opcode, currop->type,
2587                                 genop1);
2588         return folded;
2589       }
2590       break;
2591     case BIT_FIELD_REF:
2592       {
2593         tree folded;
2594         tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2595                                                         stmts, domstmt);
2596         pre_expr op1expr = get_or_alloc_expr_for (currop->op0);
2597         pre_expr op2expr = get_or_alloc_expr_for (currop->op1);
2598         tree genop1;
2599         tree genop2;
2600
2601         if (!genop0)
2602           return NULL_TREE;
2603         genop1 = find_or_generate_expression (block, op1expr, stmts, domstmt);
2604         if (!genop1)
2605           return NULL_TREE;
2606         genop2 = find_or_generate_expression (block, op2expr, stmts, domstmt);
2607         if (!genop2)
2608           return NULL_TREE;
2609         folded = fold_build3 (BIT_FIELD_REF, currop->type, genop0, genop1,
2610                               genop2);
2611         return folded;
2612       }
2613
2614       /* For array ref vn_reference_op's, operand 1 of the array ref
2615          is op0 of the reference op and operand 3 of the array ref is
2616          op1.  */
2617     case ARRAY_RANGE_REF:
2618     case ARRAY_REF:
2619       {
2620         tree genop0;
2621         tree genop1 = currop->op0;
2622         pre_expr op1expr;
2623         tree genop2 = currop->op1;
2624         pre_expr op2expr;
2625         tree genop3;
2626         genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2627                                                    stmts, domstmt);
2628         if (!genop0)
2629           return NULL_TREE;
2630         op1expr = get_or_alloc_expr_for (genop1);
2631         genop1 = find_or_generate_expression (block, op1expr, stmts, domstmt);
2632         if (!genop1)
2633           return NULL_TREE;
2634         if (genop2)
2635           {
2636             op2expr = get_or_alloc_expr_for (genop2);
2637             genop2 = find_or_generate_expression (block, op2expr, stmts,
2638                                                   domstmt);
2639             if (!genop2)
2640               return NULL_TREE;
2641           }
2642
2643         genop3 = currop->op2;
2644         return build4 (currop->opcode, currop->type, genop0, genop1,
2645                        genop2, genop3);
2646       }
2647     case COMPONENT_REF:
2648       {
2649         tree op0;
2650         tree op1;
2651         tree genop2 = currop->op1;
2652         pre_expr op2expr;
2653         op0 = create_component_ref_by_pieces_1 (block, ref, operand,
2654                                                 stmts, domstmt);
2655         if (!op0)
2656           return NULL_TREE;
2657         /* op1 should be a FIELD_DECL, which are represented by
2658            themselves.  */
2659         op1 = currop->op0;
2660         if (genop2)
2661           {
2662             op2expr = get_or_alloc_expr_for (genop2);
2663             genop2 = find_or_generate_expression (block, op2expr, stmts,
2664                                                   domstmt);
2665             if (!genop2)
2666               return NULL_TREE;
2667           }
2668
2669         return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1,
2670                             genop2);
2671       }
2672       break;
2673     case SSA_NAME:
2674       {
2675         pre_expr op0expr = get_or_alloc_expr_for (currop->op0);
2676         genop = find_or_generate_expression (block, op0expr, stmts, domstmt);
2677         return genop;
2678       }
2679     case STRING_CST:
2680     case INTEGER_CST:
2681     case COMPLEX_CST:
2682     case VECTOR_CST:
2683     case REAL_CST:
2684     case CONSTRUCTOR:
2685     case VAR_DECL:
2686     case PARM_DECL:
2687     case CONST_DECL:
2688     case RESULT_DECL:
2689     case FUNCTION_DECL:
2690       return currop->op0;
2691
2692     default:
2693       gcc_unreachable ();
2694     }
2695 }
2696
2697 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2698    COMPONENT_REF or INDIRECT_REF or ARRAY_REF portion, because we'd end up with
2699    trying to rename aggregates into ssa form directly, which is a no no.
2700
2701    Thus, this routine doesn't create temporaries, it just builds a
2702    single access expression for the array, calling
2703    find_or_generate_expression to build the innermost pieces.
2704
2705    This function is a subroutine of create_expression_by_pieces, and
2706    should not be called on it's own unless you really know what you
2707    are doing.  */
2708
2709 static tree
2710 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2711                                 gimple_seq *stmts, gimple domstmt)
2712 {
2713   unsigned int op = 0;
2714   return create_component_ref_by_pieces_1 (block, ref, &op, stmts, domstmt);
2715 }
2716
2717 /* Find a leader for an expression, or generate one using
2718    create_expression_by_pieces if it's ANTIC but
2719    complex.
2720    BLOCK is the basic_block we are looking for leaders in.
2721    EXPR is the expression to find a leader or generate for.
2722    STMTS is the statement list to put the inserted expressions on.
2723    Returns the SSA_NAME of the LHS of the generated expression or the
2724    leader.
2725    DOMSTMT if non-NULL is a statement that should be dominated by
2726    all uses in the generated expression.  If DOMSTMT is non-NULL this
2727    routine can fail and return NULL_TREE.  Otherwise it will assert
2728    on failure.  */
2729
2730 static tree
2731 find_or_generate_expression (basic_block block, pre_expr expr,
2732                              gimple_seq *stmts, gimple domstmt)
2733 {
2734   pre_expr leader = bitmap_find_leader (AVAIL_OUT (block),
2735                                         get_expr_value_id (expr), domstmt);
2736   tree genop = NULL;
2737   if (leader)
2738     {
2739       if (leader->kind == NAME)
2740         genop = PRE_EXPR_NAME (leader);
2741       else if (leader->kind == CONSTANT)
2742         genop = PRE_EXPR_CONSTANT (leader);
2743     }
2744
2745   /* If it's still NULL, it must be a complex expression, so generate
2746      it recursively.  Not so for FRE though.  */
2747   if (genop == NULL
2748       && !in_fre)
2749     {
2750       bitmap_set_t exprset;
2751       unsigned int lookfor = get_expr_value_id (expr);
2752       bool handled = false;
2753       bitmap_iterator bi;
2754       unsigned int i;
2755
2756       exprset = VEC_index (bitmap_set_t, value_expressions, lookfor);
2757       FOR_EACH_EXPR_ID_IN_SET (exprset, i, bi)
2758         {
2759           pre_expr temp = expression_for_id (i);
2760           if (temp->kind != NAME)
2761             {
2762               handled = true;
2763               genop = create_expression_by_pieces (block, temp, stmts,
2764                                                    domstmt,
2765                                                    get_expr_type (expr));
2766               break;
2767             }
2768         }
2769       if (!handled && domstmt)
2770         return NULL_TREE;
2771
2772       gcc_assert (handled);
2773     }
2774   return genop;
2775 }
2776
2777 #define NECESSARY GF_PLF_1
2778
2779 /* Create an expression in pieces, so that we can handle very complex
2780    expressions that may be ANTIC, but not necessary GIMPLE.
2781    BLOCK is the basic block the expression will be inserted into,
2782    EXPR is the expression to insert (in value form)
2783    STMTS is a statement list to append the necessary insertions into.
2784
2785    This function will die if we hit some value that shouldn't be
2786    ANTIC but is (IE there is no leader for it, or its components).
2787    This function may also generate expressions that are themselves
2788    partially or fully redundant.  Those that are will be either made
2789    fully redundant during the next iteration of insert (for partially
2790    redundant ones), or eliminated by eliminate (for fully redundant
2791    ones).
2792
2793    If DOMSTMT is non-NULL then we make sure that all uses in the
2794    expressions dominate that statement.  In this case the function
2795    can return NULL_TREE to signal failure.  */
2796
2797 static tree
2798 create_expression_by_pieces (basic_block block, pre_expr expr,
2799                              gimple_seq *stmts, gimple domstmt, tree type)
2800 {
2801   tree temp, name;
2802   tree folded, newexpr;
2803   gimple_seq forced_stmts;
2804   unsigned int value_id;
2805   gimple_stmt_iterator gsi;
2806   tree exprtype = type ? type : get_expr_type (expr);
2807   pre_expr nameexpr;
2808   gimple newstmt;
2809
2810   switch (expr->kind)
2811     {
2812       /* We may hit the NAME/CONSTANT case if we have to convert types
2813          that value numbering saw through.  */
2814     case NAME:
2815       folded = PRE_EXPR_NAME (expr);
2816       break;
2817     case CONSTANT:
2818       folded = PRE_EXPR_CONSTANT (expr);
2819       break;
2820     case REFERENCE:
2821       {
2822         vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2823         folded = create_component_ref_by_pieces (block, ref, stmts, domstmt);
2824       }
2825       break;
2826     case NARY:
2827       {
2828         vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2829         switch (nary->length)
2830           {
2831           case 2:
2832             {
2833               pre_expr op1 = get_or_alloc_expr_for (nary->op[0]);
2834               pre_expr op2 = get_or_alloc_expr_for (nary->op[1]);
2835               tree genop1 = find_or_generate_expression (block, op1,
2836                                                          stmts, domstmt);
2837               tree genop2 = find_or_generate_expression (block, op2,
2838                                                          stmts, domstmt);
2839               if (!genop1 || !genop2)
2840                 return NULL_TREE;
2841               genop1 = fold_convert (TREE_TYPE (nary->op[0]),
2842                                      genop1);
2843               /* Ensure op2 is a sizetype for POINTER_PLUS_EXPR.  It
2844                  may be a constant with the wrong type.  */
2845               if (nary->opcode == POINTER_PLUS_EXPR)
2846                 genop2 = fold_convert (sizetype, genop2);
2847               else
2848                 genop2 = fold_convert (TREE_TYPE (nary->op[1]), genop2);
2849               
2850               folded = fold_build2 (nary->opcode, nary->type,
2851                                     genop1, genop2);
2852             }
2853             break;
2854           case 1:
2855             {
2856               pre_expr op1 = get_or_alloc_expr_for (nary->op[0]);
2857               tree genop1 = find_or_generate_expression (block, op1,
2858                                                          stmts, domstmt);
2859               if (!genop1)
2860                 return NULL_TREE;
2861               genop1 = fold_convert (TREE_TYPE (nary->op[0]), genop1);
2862
2863               folded = fold_build1 (nary->opcode, nary->type,
2864                                     genop1);
2865             }
2866             break;
2867           default:
2868             return NULL_TREE;
2869           }
2870       }
2871       break;
2872     default:
2873       return NULL_TREE;
2874     }
2875   folded = fold_convert (exprtype, folded);
2876   /* Force the generated expression to be a sequence of GIMPLE
2877      statements.
2878      We have to call unshare_expr because force_gimple_operand may
2879      modify the tree we pass to it.  */
2880   newexpr = force_gimple_operand (unshare_expr (folded), &forced_stmts,
2881                                   false, NULL);
2882
2883   /* If we have any intermediate expressions to the value sets, add them
2884      to the value sets and chain them in the instruction stream.  */
2885   if (forced_stmts)
2886     {
2887       gsi = gsi_start (forced_stmts);
2888       for (; !gsi_end_p (gsi); gsi_next (&gsi))
2889         {
2890           gimple stmt = gsi_stmt (gsi);
2891           tree forcedname = gimple_get_lhs (stmt);
2892           pre_expr nameexpr;
2893
2894           VEC_safe_push (gimple, heap, inserted_exprs, stmt);
2895           if (TREE_CODE (forcedname) == SSA_NAME)
2896             {
2897               VN_INFO_GET (forcedname)->valnum = forcedname;
2898               VN_INFO (forcedname)->value_id = get_next_value_id ();
2899               nameexpr = get_or_alloc_expr_for_name (forcedname);
2900               add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2901               if (!in_fre)
2902                 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2903               bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2904             }
2905           mark_symbols_for_renaming (stmt);
2906         }
2907       gimple_seq_add_seq (stmts, forced_stmts);
2908     }
2909
2910   /* Build and insert the assignment of the end result to the temporary
2911      that we will return.  */
2912   if (!pretemp || exprtype != TREE_TYPE (pretemp))
2913     {
2914       pretemp = create_tmp_var (exprtype, "pretmp");
2915       get_var_ann (pretemp);
2916     }
2917
2918   temp = pretemp;
2919   add_referenced_var (temp);
2920
2921   if (TREE_CODE (exprtype) == COMPLEX_TYPE
2922       || TREE_CODE (exprtype) == VECTOR_TYPE)
2923     DECL_GIMPLE_REG_P (temp) = 1;
2924
2925   newstmt = gimple_build_assign (temp, newexpr);
2926   name = make_ssa_name (temp, newstmt);
2927   gimple_assign_set_lhs (newstmt, name);
2928   gimple_set_plf (newstmt, NECESSARY, false);
2929
2930   gimple_seq_add_stmt (stmts, newstmt);
2931   VEC_safe_push (gimple, heap, inserted_exprs, newstmt);
2932
2933   /* All the symbols in NEWEXPR should be put into SSA form.  */
2934   mark_symbols_for_renaming (newstmt);
2935
2936   /* Add a value number to the temporary.
2937      The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2938      we are creating the expression by pieces, and this particular piece of
2939      the expression may have been represented.  There is no harm in replacing
2940      here.  */
2941   VN_INFO_GET (name)->valnum = name;
2942   value_id = get_expr_value_id (expr);
2943   VN_INFO (name)->value_id = value_id;
2944   nameexpr = get_or_alloc_expr_for_name (name);
2945   add_to_value (value_id, nameexpr);
2946   if (!in_fre)
2947     bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2948   bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2949
2950   pre_stats.insertions++;
2951   if (dump_file && (dump_flags & TDF_DETAILS))
2952     {
2953       fprintf (dump_file, "Inserted ");
2954       print_gimple_stmt (dump_file, newstmt, 0, 0);
2955       fprintf (dump_file, " in predecessor %d\n", block->index);
2956     }
2957
2958   return name;
2959 }
2960
2961
2962 /* Insert the to-be-made-available values of expression EXPRNUM for each
2963    predecessor, stored in AVAIL, into the predecessors of BLOCK, and
2964    merge the result with a phi node, given the same value number as
2965    NODE.  Return true if we have inserted new stuff.  */
2966
2967 static bool
2968 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
2969                             pre_expr *avail)
2970 {
2971   pre_expr expr = expression_for_id (exprnum);
2972   pre_expr newphi;
2973   unsigned int val = get_expr_value_id (expr);
2974   edge pred;
2975   bool insertions = false;
2976   bool nophi = false;
2977   basic_block bprime;
2978   pre_expr eprime;
2979   edge_iterator ei;
2980   tree type = get_expr_type (expr);
2981   tree temp;
2982   gimple phi;
2983
2984   if (dump_file && (dump_flags & TDF_DETAILS))
2985     {
2986       fprintf (dump_file, "Found partial redundancy for expression ");
2987       print_pre_expr (dump_file, expr);
2988       fprintf (dump_file, " (%04d)\n", val);
2989     }
2990
2991   /* Make sure we aren't creating an induction variable.  */
2992   if (block->loop_depth > 0 && EDGE_COUNT (block->preds) == 2
2993       && expr->kind != REFERENCE)
2994     {
2995       bool firstinsideloop = false;
2996       bool secondinsideloop = false;
2997       firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
2998                                                EDGE_PRED (block, 0)->src);
2999       secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
3000                                                 EDGE_PRED (block, 1)->src);
3001       /* Induction variables only have one edge inside the loop.  */
3002       if (firstinsideloop ^ secondinsideloop)
3003         {
3004           if (dump_file && (dump_flags & TDF_DETAILS))
3005             fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
3006           nophi = true;
3007         }
3008     }
3009
3010   /* Make sure we are not inserting trapping expressions.  */
3011   FOR_EACH_EDGE (pred, ei, block->preds)
3012     {
3013       bprime = pred->src;
3014       eprime = avail[bprime->index];
3015       if (eprime->kind == NARY
3016           && vn_nary_may_trap (PRE_EXPR_NARY (eprime)))
3017         return false;
3018     }
3019
3020   /* Make the necessary insertions.  */
3021   FOR_EACH_EDGE (pred, ei, block->preds)
3022     {
3023       gimple_seq stmts = NULL;
3024       tree builtexpr;
3025       bprime = pred->src;
3026       eprime = avail[bprime->index];
3027
3028       if (eprime->kind != NAME && eprime->kind != CONSTANT)
3029         {
3030           builtexpr = create_expression_by_pieces (bprime,
3031                                                    eprime,
3032                                                    &stmts, NULL,
3033                                                    type);
3034           gcc_assert (!(pred->flags & EDGE_ABNORMAL));
3035           gsi_insert_seq_on_edge (pred, stmts);
3036           avail[bprime->index] = get_or_alloc_expr_for_name (builtexpr);
3037           insertions = true;
3038         }
3039       else if (eprime->kind == CONSTANT)
3040         {
3041           /* Constants may not have the right type, fold_convert
3042              should give us back a constant with the right type.
3043           */
3044           tree constant = PRE_EXPR_CONSTANT (eprime);
3045           if (!useless_type_conversion_p (type, TREE_TYPE (constant)))
3046             {
3047               tree builtexpr = fold_convert (type, constant);
3048               if (!is_gimple_min_invariant (builtexpr)) 
3049                 {
3050                   tree forcedexpr = force_gimple_operand (builtexpr,
3051                                                           &stmts, true,
3052                                                           NULL);
3053                   if (!is_gimple_min_invariant (forcedexpr))
3054                     {
3055                       if (forcedexpr != builtexpr)
3056                         {
3057                           VN_INFO_GET (forcedexpr)->valnum = PRE_EXPR_CONSTANT (eprime);
3058                           VN_INFO (forcedexpr)->value_id = get_expr_value_id (eprime);
3059                         }
3060                       if (stmts)
3061                         {
3062                           gimple_stmt_iterator gsi;
3063                           gsi = gsi_start (stmts);
3064                           for (; !gsi_end_p (gsi); gsi_next (&gsi))
3065                             {
3066                               gimple stmt = gsi_stmt (gsi);
3067                               VEC_safe_push (gimple, heap, inserted_exprs, stmt);
3068                               gimple_set_plf (stmt, NECESSARY, false);
3069                             }
3070                           gsi_insert_seq_on_edge (pred, stmts);
3071                         }
3072                       avail[bprime->index] = get_or_alloc_expr_for_name (forcedexpr);
3073                     }
3074                 }
3075             }
3076         }
3077       else if (eprime->kind == NAME)
3078         {
3079           /* We may have to do a conversion because our value
3080              numbering can look through types in certain cases, but
3081              our IL requires all operands of a phi node have the same
3082              type.  */
3083           tree name = PRE_EXPR_NAME (eprime);
3084           if (!useless_type_conversion_p (type, TREE_TYPE (name)))
3085             {
3086               tree builtexpr;
3087               tree forcedexpr;
3088               builtexpr = fold_convert (type, name);
3089               forcedexpr = force_gimple_operand (builtexpr,
3090                                                  &stmts, true,
3091                                                  NULL);
3092
3093               if (forcedexpr != name)
3094                 {
3095                   VN_INFO_GET (forcedexpr)->valnum = VN_INFO (name)->valnum;
3096                   VN_INFO (forcedexpr)->value_id = VN_INFO (name)->value_id;
3097                 }
3098
3099               if (stmts)
3100                 {
3101                   gimple_stmt_iterator gsi;
3102                   gsi = gsi_start (stmts);
3103                   for (; !gsi_end_p (gsi); gsi_next (&gsi))
3104                     {
3105                       gimple stmt = gsi_stmt (gsi);
3106                       VEC_safe_push (gimple, heap, inserted_exprs, stmt);
3107                       gimple_set_plf (stmt, NECESSARY, false);
3108                     }
3109                   gsi_insert_seq_on_edge (pred, stmts);
3110                 }
3111               avail[bprime->index] = get_or_alloc_expr_for_name (forcedexpr);
3112             }
3113         }
3114     }
3115   /* If we didn't want a phi node, and we made insertions, we still have
3116      inserted new stuff, and thus return true.  If we didn't want a phi node,
3117      and didn't make insertions, we haven't added anything new, so return
3118      false.  */
3119   if (nophi && insertions)
3120     return true;
3121   else if (nophi && !insertions)
3122     return false;
3123
3124   /* Now build a phi for the new variable.  */
3125   if (!prephitemp || TREE_TYPE (prephitemp) != type)
3126     {
3127       prephitemp = create_tmp_var (type, "prephitmp");
3128       get_var_ann (prephitemp);
3129     }
3130
3131   temp = prephitemp;
3132   add_referenced_var (temp);
3133
3134   if (TREE_CODE (type) == COMPLEX_TYPE
3135       || TREE_CODE (type) == VECTOR_TYPE)
3136     DECL_GIMPLE_REG_P (temp) = 1;
3137   phi = create_phi_node (temp, block);
3138
3139   gimple_set_plf (phi, NECESSARY, false);
3140   VN_INFO_GET (gimple_phi_result (phi))->valnum = gimple_phi_result (phi);
3141   VN_INFO (gimple_phi_result (phi))->value_id = val;
3142   VEC_safe_push (gimple, heap, inserted_exprs, phi);
3143   FOR_EACH_EDGE (pred, ei, block->preds)
3144     {
3145       pre_expr ae = avail[pred->src->index];
3146       gcc_assert (get_expr_type (ae) == type
3147                   || useless_type_conversion_p (type, get_expr_type (ae)));
3148       if (ae->kind == CONSTANT)
3149         add_phi_arg (phi, PRE_EXPR_CONSTANT (ae), pred);
3150       else
3151         add_phi_arg (phi, PRE_EXPR_NAME (avail[pred->src->index]), pred);
3152     }
3153
3154   newphi = get_or_alloc_expr_for_name (gimple_phi_result (phi));
3155   add_to_value (val, newphi);
3156
3157   /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3158      this insertion, since we test for the existence of this value in PHI_GEN
3159      before proceeding with the partial redundancy checks in insert_aux.
3160
3161      The value may exist in AVAIL_OUT, in particular, it could be represented
3162      by the expression we are trying to eliminate, in which case we want the
3163      replacement to occur.  If it's not existing in AVAIL_OUT, we want it
3164      inserted there.
3165
3166      Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3167      this block, because if it did, it would have existed in our dominator's
3168      AVAIL_OUT, and would have been skipped due to the full redundancy check.
3169   */
3170
3171   bitmap_insert_into_set (PHI_GEN (block), newphi);
3172   bitmap_value_replace_in_set (AVAIL_OUT (block),
3173                                newphi);
3174   bitmap_insert_into_set (NEW_SETS (block),
3175                           newphi);
3176
3177   if (dump_file && (dump_flags & TDF_DETAILS))
3178     {
3179       fprintf (dump_file, "Created phi ");
3180       print_gimple_stmt (dump_file, phi, 0, 0);
3181       fprintf (dump_file, " in block %d\n", block->index);
3182     }
3183   pre_stats.phis++;
3184   return true;
3185 }
3186
3187
3188
3189 /* Perform insertion of partially redundant values.
3190    For BLOCK, do the following:
3191    1.  Propagate the NEW_SETS of the dominator into the current block.
3192    If the block has multiple predecessors,
3193        2a. Iterate over the ANTIC expressions for the block to see if
3194            any of them are partially redundant.
3195        2b. If so, insert them into the necessary predecessors to make
3196            the expression fully redundant.
3197        2c. Insert a new PHI merging the values of the predecessors.
3198        2d. Insert the new PHI, and the new expressions, into the
3199            NEW_SETS set.
3200    3. Recursively call ourselves on the dominator children of BLOCK.
3201
3202    Steps 1, 2a, and 3 are done by insert_aux. 2b, 2c and 2d are done by
3203    do_regular_insertion and do_partial_insertion.
3204
3205 */
3206
3207 static bool
3208 do_regular_insertion (basic_block block, basic_block dom)
3209 {
3210   bool new_stuff = false;
3211   VEC (pre_expr, heap) *exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3212   pre_expr expr;
3213   int i;
3214
3215   for (i = 0; VEC_iterate (pre_expr, exprs, i, expr); i++)
3216     {
3217       if (expr->kind != NAME)
3218         {
3219           pre_expr *avail;
3220           unsigned int val;
3221           bool by_some = false;
3222           bool cant_insert = false;
3223           bool all_same = true;
3224           pre_expr first_s = NULL;
3225           edge pred;
3226           basic_block bprime;
3227           pre_expr eprime = NULL;
3228           edge_iterator ei;
3229           pre_expr edoubleprime = NULL;
3230
3231           val = get_expr_value_id (expr);
3232           if (bitmap_set_contains_value (PHI_GEN (block), val))
3233             continue;
3234           if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3235             {
3236               if (dump_file && (dump_flags & TDF_DETAILS))
3237                 fprintf (dump_file, "Found fully redundant value\n");
3238               continue;
3239             }
3240
3241           avail = XCNEWVEC (pre_expr, last_basic_block);
3242           FOR_EACH_EDGE (pred, ei, block->preds)
3243             {
3244               unsigned int vprime;
3245
3246               /* We should never run insertion for the exit block
3247                  and so not come across fake pred edges.  */
3248               gcc_assert (!(pred->flags & EDGE_FAKE));
3249               bprime = pred->src;
3250               eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3251                                       bprime, block);
3252
3253               /* eprime will generally only be NULL if the
3254                  value of the expression, translated
3255                  through the PHI for this predecessor, is
3256                  undefined.  If that is the case, we can't
3257                  make the expression fully redundant,
3258                  because its value is undefined along a
3259                  predecessor path.  We can thus break out
3260                  early because it doesn't matter what the
3261                  rest of the results are.  */
3262               if (eprime == NULL)
3263                 {
3264                   cant_insert = true;
3265                   break;
3266                 }
3267
3268               eprime = fully_constant_expression (eprime);
3269               vprime = get_expr_value_id (eprime);
3270               edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3271                                                  vprime, NULL);
3272               if (edoubleprime == NULL)
3273                 {
3274                   avail[bprime->index] = eprime;
3275                   all_same = false;
3276                 }
3277               else
3278                 {
3279                   avail[bprime->index] = edoubleprime;
3280                   by_some = true;
3281                   if (first_s == NULL)
3282                     first_s = edoubleprime;
3283                   else if (!pre_expr_eq (first_s, edoubleprime))
3284                     all_same = false;
3285                 }
3286             }
3287           /* If we can insert it, it's not the same value
3288              already existing along every predecessor, and
3289              it's defined by some predecessor, it is
3290              partially redundant.  */
3291           if (!cant_insert && !all_same && by_some && dbg_cnt (treepre_insert))
3292             {
3293               if (insert_into_preds_of_block (block, get_expression_id (expr),
3294                                               avail))
3295                 new_stuff = true;
3296             }
3297           /* If all edges produce the same value and that value is
3298              an invariant, then the PHI has the same value on all
3299              edges.  Note this.  */
3300           else if (!cant_insert && all_same && eprime
3301                    && (edoubleprime->kind == CONSTANT
3302                        || edoubleprime->kind == NAME)
3303                    && !value_id_constant_p (val))
3304             {
3305               unsigned int j;
3306               bitmap_iterator bi;
3307               bitmap_set_t exprset = VEC_index (bitmap_set_t,
3308                                                 value_expressions, val);
3309
3310               unsigned int new_val = get_expr_value_id (edoubleprime);
3311               FOR_EACH_EXPR_ID_IN_SET (exprset, j, bi)
3312                 {
3313                   pre_expr expr = expression_for_id (j);
3314
3315                   if (expr->kind == NAME)
3316                     {
3317                       vn_ssa_aux_t info = VN_INFO (PRE_EXPR_NAME (expr));
3318                       /* Just reset the value id and valnum so it is
3319                          the same as the constant we have discovered.  */
3320                       if (edoubleprime->kind == CONSTANT)
3321                         {
3322                           info->valnum = PRE_EXPR_CONSTANT (edoubleprime);
3323                           pre_stats.constified++;
3324                         }
3325                       else
3326                         info->valnum = VN_INFO (PRE_EXPR_NAME (edoubleprime))->valnum;
3327                       info->value_id = new_val;
3328                     }
3329                 }
3330             }
3331           free (avail);
3332         }
3333     }
3334
3335   VEC_free (pre_expr, heap, exprs);
3336   return new_stuff;
3337 }
3338
3339
3340 /* Perform insertion for partially anticipatable expressions.  There
3341    is only one case we will perform insertion for these.  This case is
3342    if the expression is partially anticipatable, and fully available.
3343    In this case, we know that putting it earlier will enable us to
3344    remove the later computation.  */
3345
3346
3347 static bool
3348 do_partial_partial_insertion (basic_block block, basic_block dom)
3349 {
3350   bool new_stuff = false;
3351   VEC (pre_expr, heap) *exprs = sorted_array_from_bitmap_set (PA_IN (block));
3352   pre_expr expr;
3353   int i;
3354
3355   for (i = 0; VEC_iterate (pre_expr, exprs, i, expr); i++)
3356     {
3357       if (expr->kind != NAME)
3358         {
3359           pre_expr *avail;
3360           unsigned int val;
3361           bool by_all = true;
3362           bool cant_insert = false;
3363           edge pred;
3364           basic_block bprime;
3365           pre_expr eprime = NULL;
3366           edge_iterator ei;
3367
3368           val = get_expr_value_id (expr);
3369           if (bitmap_set_contains_value (PHI_GEN (block), val))
3370             continue;
3371           if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3372             continue;
3373
3374           avail = XCNEWVEC (pre_expr, last_basic_block);
3375           FOR_EACH_EDGE (pred, ei, block->preds)
3376             {
3377               unsigned int vprime;
3378               pre_expr edoubleprime;
3379
3380               /* We should never run insertion for the exit block
3381                  and so not come across fake pred edges.  */
3382               gcc_assert (!(pred->flags & EDGE_FAKE));
3383               bprime = pred->src;
3384               eprime = phi_translate (expr, ANTIC_IN (block),
3385                                       PA_IN (block),
3386                                       bprime, block);
3387
3388               /* eprime will generally only be NULL if the
3389                  value of the expression, translated
3390                  through the PHI for this predecessor, is
3391                  undefined.  If that is the case, we can't
3392                  make the expression fully redundant,
3393                  because its value is undefined along a
3394                  predecessor path.  We can thus break out
3395                  early because it doesn't matter what the
3396                  rest of the results are.  */
3397               if (eprime == NULL)
3398                 {
3399                   cant_insert = true;
3400                   break;
3401                 }
3402
3403               eprime = fully_constant_expression (eprime);
3404               vprime = get_expr_value_id (eprime);
3405               edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3406                                                  vprime, NULL);
3407               if (edoubleprime == NULL)
3408                 {
3409                   by_all = false;
3410                   break;
3411                 }
3412               else
3413                 avail[bprime->index] = edoubleprime;
3414
3415             }
3416
3417           /* If we can insert it, it's not the same value
3418              already existing along every predecessor, and
3419              it's defined by some predecessor, it is
3420              partially redundant.  */
3421           if (!cant_insert && by_all && dbg_cnt (treepre_insert))
3422             {
3423               pre_stats.pa_insert++;
3424               if (insert_into_preds_of_block (block, get_expression_id (expr),
3425                                               avail))
3426                 new_stuff = true;
3427             }
3428           free (avail);
3429         }
3430     }
3431
3432   VEC_free (pre_expr, heap, exprs);
3433   return new_stuff;
3434 }
3435
3436 static bool
3437 insert_aux (basic_block block)
3438 {
3439   basic_block son;
3440   bool new_stuff = false;
3441
3442   if (block)
3443     {
3444       basic_block dom;
3445       dom = get_immediate_dominator (CDI_DOMINATORS, block);
3446       if (dom)
3447         {
3448           unsigned i;
3449           bitmap_iterator bi;
3450           bitmap_set_t newset = NEW_SETS (dom);
3451           if (newset)
3452             {
3453               /* Note that we need to value_replace both NEW_SETS, and
3454                  AVAIL_OUT. For both the case of NEW_SETS, the value may be
3455                  represented by some non-simple expression here that we want
3456                  to replace it with.  */
3457               FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3458                 {
3459                   pre_expr expr = expression_for_id (i);
3460                   bitmap_value_replace_in_set (NEW_SETS (block), expr);
3461                   bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3462                 }
3463             }
3464           if (!single_pred_p (block))
3465             {
3466               new_stuff |= do_regular_insertion (block, dom);
3467               if (do_partial_partial)
3468                 new_stuff |= do_partial_partial_insertion (block, dom);
3469             }
3470         }
3471     }
3472   for (son = first_dom_son (CDI_DOMINATORS, block);
3473        son;
3474        son = next_dom_son (CDI_DOMINATORS, son))
3475     {
3476       new_stuff |= insert_aux (son);
3477     }
3478
3479   return new_stuff;
3480 }
3481
3482 /* Perform insertion of partially redundant values.  */
3483
3484 static void
3485 insert (void)
3486 {
3487   bool new_stuff = true;
3488   basic_block bb;
3489   int num_iterations = 0;
3490
3491   FOR_ALL_BB (bb)
3492     NEW_SETS (bb) = bitmap_set_new ();
3493
3494   while (new_stuff)
3495     {
3496       num_iterations++;
3497       new_stuff = insert_aux (ENTRY_BLOCK_PTR);
3498     }
3499   statistics_histogram_event (cfun, "insert iterations", num_iterations);
3500 }
3501
3502
3503 /* Add OP to EXP_GEN (block), and possibly to the maximal set if it is
3504    not defined by a phi node.
3505    PHI nodes can't go in the maximal sets because they are not in
3506    TMP_GEN, so it is possible to get into non-monotonic situations
3507    during ANTIC calculation, because it will *add* bits.  */
3508
3509 static void
3510 add_to_exp_gen (basic_block block, tree op)
3511 {
3512   if (!in_fre)
3513     {
3514       pre_expr result;
3515       if (TREE_CODE (op) == SSA_NAME && ssa_undefined_value_p (op))
3516         return;
3517       result = get_or_alloc_expr_for_name (op);
3518       bitmap_value_insert_into_set (EXP_GEN (block), result);
3519       if (TREE_CODE (op) != SSA_NAME
3520           || gimple_code (SSA_NAME_DEF_STMT (op)) != GIMPLE_PHI)
3521         bitmap_value_insert_into_set (maximal_set, result);
3522     }
3523 }
3524
3525 /* Create value ids for PHI in BLOCK.  */
3526
3527 static void
3528 make_values_for_phi (gimple phi, basic_block block)
3529 {
3530   tree result = gimple_phi_result (phi);
3531
3532   /* We have no need for virtual phis, as they don't represent
3533      actual computations.  */
3534   if (is_gimple_reg (result))
3535     {
3536       pre_expr e = get_or_alloc_expr_for_name (result);
3537       add_to_value (get_expr_value_id (e), e);
3538       bitmap_insert_into_set (PHI_GEN (block), e);
3539       bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3540     }
3541 }
3542
3543 /* Compute the AVAIL set for all basic blocks.
3544
3545    This function performs value numbering of the statements in each basic
3546    block.  The AVAIL sets are built from information we glean while doing
3547    this value numbering, since the AVAIL sets contain only one entry per
3548    value.
3549
3550    AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3551    AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK].  */
3552
3553 static void
3554 compute_avail (void)
3555 {
3556
3557   basic_block block, son;
3558   basic_block *worklist;
3559   size_t sp = 0;
3560   tree param;
3561
3562   /* For arguments with default definitions, we pretend they are
3563      defined in the entry block.  */
3564   for (param = DECL_ARGUMENTS (current_function_decl);
3565        param;
3566        param = TREE_CHAIN (param))
3567     {
3568       if (gimple_default_def (cfun, param) != NULL)
3569         {
3570           tree def = gimple_default_def (cfun, param);
3571           pre_expr e = get_or_alloc_expr_for_name (def);
3572
3573           add_to_value (get_expr_value_id (e), e);
3574           if (!in_fre)
3575             {
3576               bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR), e);
3577               bitmap_value_insert_into_set (maximal_set, e);
3578             }
3579           bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR), e);
3580         }
3581     }
3582
3583   /* Likewise for the static chain decl. */
3584   if (cfun->static_chain_decl)
3585     {
3586       param = cfun->static_chain_decl;
3587       if (gimple_default_def (cfun, param) != NULL)
3588         {
3589           tree def = gimple_default_def (cfun, param);
3590           pre_expr e = get_or_alloc_expr_for_name (def);
3591
3592           add_to_value (get_expr_value_id (e), e);
3593           if (!in_fre)
3594             {
3595               bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR), e);
3596               bitmap_value_insert_into_set (maximal_set, e);
3597             }
3598           bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR), e);
3599         }
3600     }
3601
3602   /* Allocate the worklist.  */
3603   worklist = XNEWVEC (basic_block, n_basic_blocks);
3604
3605   /* Seed the algorithm by putting the dominator children of the entry
3606      block on the worklist.  */
3607   for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR);
3608        son;
3609        son = next_dom_son (CDI_DOMINATORS, son))
3610     worklist[sp++] = son;
3611
3612   /* Loop until the worklist is empty.  */
3613   while (sp)
3614     {
3615       gimple_stmt_iterator gsi;
3616       gimple stmt;
3617       basic_block dom;
3618       unsigned int stmt_uid = 1;
3619
3620       /* Pick a block from the worklist.  */
3621       block = worklist[--sp];
3622
3623       /* Initially, the set of available values in BLOCK is that of
3624          its immediate dominator.  */
3625       dom = get_immediate_dominator (CDI_DOMINATORS, block);
3626       if (dom)
3627         bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3628
3629       /* Generate values for PHI nodes.  */
3630       for (gsi = gsi_start_phis (block); !gsi_end_p (gsi); gsi_next (&gsi))
3631         make_values_for_phi (gsi_stmt (gsi), block);
3632
3633       /* Now compute value numbers and populate value sets with all
3634          the expressions computed in BLOCK.  */
3635       for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
3636         {
3637           ssa_op_iter iter;
3638           tree op;
3639
3640           stmt = gsi_stmt (gsi);
3641           gimple_set_uid (stmt, stmt_uid++);
3642
3643           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3644             {
3645               pre_expr e = get_or_alloc_expr_for_name (op);
3646
3647               add_to_value (get_expr_value_id (e), e);
3648               if (!in_fre)
3649                 bitmap_insert_into_set (TMP_GEN (block), e);
3650               bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3651             }
3652
3653           if (gimple_has_volatile_ops (stmt)
3654               || stmt_could_throw_p (stmt))
3655             continue;
3656
3657           switch (gimple_code (stmt))
3658             {
3659             case GIMPLE_RETURN:
3660               FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3661                 add_to_exp_gen (block, op);
3662               continue;
3663
3664             case GIMPLE_CALL:
3665               {
3666                 vn_reference_t ref;
3667                 unsigned int i;
3668                 vn_reference_op_t vro;
3669                 pre_expr result = NULL;
3670                 VEC(vn_reference_op_s, heap) *ops = NULL;
3671
3672                 if (!can_value_number_call (stmt))
3673                   continue;
3674
3675                 copy_reference_ops_from_call (stmt, &ops);
3676                 vn_reference_lookup_pieces (shared_vuses_from_stmt (stmt),
3677                                             ops, &ref, false);
3678                 VEC_free (vn_reference_op_s, heap, ops);
3679                 if (!ref)
3680                   continue;
3681
3682                 for (i = 0; VEC_iterate (vn_reference_op_s,
3683                                          ref->operands, i,
3684                                          vro); i++)
3685                   {
3686                     if (vro->op0 && TREE_CODE (vro->op0) == SSA_NAME)
3687                       add_to_exp_gen (block, vro->op0);
3688                     if (vro->op1 && TREE_CODE (vro->op1) == SSA_NAME)
3689                       add_to_exp_gen (block, vro->op1);
3690                     if (vro->op2 && TREE_CODE (vro->op2) == SSA_NAME)
3691                       add_to_exp_gen (block, vro->op2);
3692                   }
3693                 result = (pre_expr) pool_alloc (pre_expr_pool);
3694                 result->kind = REFERENCE;
3695                 result->id = 0;
3696                 PRE_EXPR_REFERENCE (result) = ref;
3697
3698                 get_or_alloc_expression_id (result);
3699                 add_to_value (get_expr_value_id (result), result);
3700                 if (!in_fre)
3701                   {
3702                     bitmap_value_insert_into_set (EXP_GEN (block),
3703                                                   result);
3704                     bitmap_value_insert_into_set (maximal_set, result);
3705                   }
3706                 continue;
3707               }
3708
3709             case GIMPLE_ASSIGN:
3710               {
3711                 pre_expr result = NULL;
3712                 switch (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)))
3713                   {
3714                   case tcc_unary:
3715                     if (is_exception_related (stmt))
3716                       continue;
3717                   case tcc_binary:
3718                   case tcc_comparison:
3719                     {
3720                       vn_nary_op_t nary;
3721                       unsigned int i;
3722
3723                       vn_nary_op_lookup_pieces (gimple_num_ops (stmt) - 1,
3724                                                 gimple_assign_rhs_code (stmt),
3725                                                 gimple_expr_type (stmt),
3726                                                 gimple_assign_rhs1 (stmt),
3727                                                 gimple_assign_rhs2 (stmt),
3728                                                 NULL_TREE, NULL_TREE, &nary);
3729
3730                       if (!nary)
3731                         continue;
3732
3733                       for (i = 0; i < nary->length; i++)
3734                         if (TREE_CODE (nary->op[i]) == SSA_NAME)
3735                           add_to_exp_gen (block, nary->op[i]);
3736
3737                       result = (pre_expr) pool_alloc (pre_expr_pool);
3738                       result->kind = NARY;
3739                       result->id = 0;
3740                       PRE_EXPR_NARY (result) = nary;
3741                       break;
3742                     }
3743
3744                   case tcc_declaration:
3745                   case tcc_reference:
3746                     {
3747                       vn_reference_t ref;
3748                       unsigned int i;
3749                       vn_reference_op_t vro;
3750
3751                       vn_reference_lookup (gimple_assign_rhs1 (stmt),
3752                                            shared_vuses_from_stmt (stmt),
3753                                            false, &ref);
3754                       if (!ref)
3755                         continue;
3756
3757                       for (i = 0; VEC_iterate (vn_reference_op_s,
3758                                                ref->operands, i,
3759                                                vro); i++)
3760                         {
3761                           if (vro->op0 && TREE_CODE (vro->op0) == SSA_NAME)
3762                             add_to_exp_gen (block, vro->op0);
3763                           if (vro->op1 && TREE_CODE (vro->op1) == SSA_NAME)
3764                             add_to_exp_gen (block, vro->op1);
3765                           if (vro->op2 && TREE_CODE (vro->op2) == SSA_NAME)
3766                             add_to_exp_gen (block, vro->op2);
3767                         }
3768                       result = (pre_expr) pool_alloc (pre_expr_pool);
3769                       result->kind = REFERENCE;
3770                       result->id = 0;
3771                       PRE_EXPR_REFERENCE (result) = ref;
3772                       break;
3773                     }
3774
3775                   default:
3776                     /* For any other statement that we don't
3777                        recognize, simply add all referenced
3778                        SSA_NAMEs to EXP_GEN.  */
3779                     FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3780                       add_to_exp_gen (block, op);
3781                     continue;
3782                   }
3783
3784                 get_or_alloc_expression_id (result);
3785                 add_to_value (get_expr_value_id (result), result);
3786                 if (!in_fre)
3787                   {
3788                     bitmap_value_insert_into_set (EXP_GEN (block), result);
3789                     bitmap_value_insert_into_set (maximal_set, result);
3790                   }
3791
3792                 continue;
3793               }
3794             default:
3795               break;
3796             }
3797         }
3798
3799       /* Put the dominator children of BLOCK on the worklist of blocks
3800          to compute available sets for.  */
3801       for (son = first_dom_son (CDI_DOMINATORS, block);
3802            son;
3803            son = next_dom_son (CDI_DOMINATORS, son))
3804         worklist[sp++] = son;
3805     }
3806
3807   free (worklist);
3808 }
3809
3810 /* Insert the expression for SSA_VN that SCCVN thought would be simpler
3811    than the available expressions for it.  The insertion point is
3812    right before the first use in STMT.  Returns the SSA_NAME that should
3813    be used for replacement.  */
3814
3815 static tree
3816 do_SCCVN_insertion (gimple stmt, tree ssa_vn)
3817 {
3818   basic_block bb = gimple_bb (stmt);
3819   gimple_stmt_iterator gsi;
3820   gimple_seq stmts = NULL;
3821   tree expr;
3822   pre_expr e;
3823
3824   /* First create a value expression from the expression we want
3825      to insert and associate it with the value handle for SSA_VN.  */
3826   e = get_or_alloc_expr_for (vn_get_expr_for (ssa_vn));
3827   if (e == NULL)
3828     return NULL_TREE;
3829
3830   /* Then use create_expression_by_pieces to generate a valid
3831      expression to insert at this point of the IL stream.  */
3832   expr = create_expression_by_pieces (bb, e, &stmts, stmt, NULL);
3833   if (expr == NULL_TREE)
3834     return NULL_TREE;
3835   gsi = gsi_for_stmt (stmt);
3836   gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
3837
3838   return expr;
3839 }
3840
3841 /* Eliminate fully redundant computations.  */
3842
3843 static unsigned int
3844 eliminate (void)
3845 {
3846   basic_block b;
3847   unsigned int todo = 0;
3848
3849   FOR_EACH_BB (b)
3850     {
3851       gimple_stmt_iterator i;
3852
3853       for (i = gsi_start_bb (b); !gsi_end_p (i); gsi_next (&i))
3854         {
3855           gimple stmt = gsi_stmt (i);
3856
3857           /* Lookup the RHS of the expression, see if we have an
3858              available computation for it.  If so, replace the RHS with
3859              the available computation.  */
3860           if (gimple_has_lhs (stmt)
3861               && TREE_CODE (gimple_get_lhs (stmt)) == SSA_NAME
3862               && !gimple_assign_ssa_name_copy_p (stmt)
3863               && (!gimple_assign_single_p (stmt)
3864                   || !is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
3865               && !gimple_has_volatile_ops  (stmt)
3866               && !has_zero_uses (gimple_get_lhs (stmt)))
3867             {
3868               tree lhs = gimple_get_lhs (stmt);
3869               tree rhs = NULL_TREE;
3870               tree sprime = NULL;
3871               pre_expr lhsexpr = get_or_alloc_expr_for_name (lhs);
3872               pre_expr sprimeexpr;
3873
3874               if (gimple_assign_single_p (stmt))
3875                 rhs = gimple_assign_rhs1 (stmt);
3876
3877               sprimeexpr = bitmap_find_leader (AVAIL_OUT (b),
3878                                                get_expr_value_id (lhsexpr),
3879                                                NULL);
3880
3881               if (sprimeexpr)
3882                 {
3883                   if (sprimeexpr->kind == CONSTANT)
3884                     sprime = PRE_EXPR_CONSTANT (sprimeexpr);
3885                   else if (sprimeexpr->kind == NAME)
3886                     sprime = PRE_EXPR_NAME (sprimeexpr);
3887                   else
3888                     gcc_unreachable ();
3889                 }
3890
3891               /* If there is no existing leader but SCCVN knows this
3892                  value is constant, use that constant.  */
3893               if (!sprime && is_gimple_min_invariant (VN_INFO (lhs)->valnum))
3894                 {
3895                   sprime = fold_convert (TREE_TYPE (lhs),
3896                                          VN_INFO (lhs)->valnum);
3897
3898                   if (dump_file && (dump_flags & TDF_DETAILS))
3899                     {
3900                       fprintf (dump_file, "Replaced ");
3901                       print_gimple_expr (dump_file, stmt, 0, 0);
3902                       fprintf (dump_file, " with ");
3903                       print_generic_expr (dump_file, sprime, 0);
3904                       fprintf (dump_file, " in ");
3905                       print_gimple_stmt (dump_file, stmt, 0, 0);
3906                     }
3907                   pre_stats.eliminations++;
3908                   propagate_tree_value_into_stmt (&i, sprime);
3909                   stmt = gsi_stmt (i);
3910                   update_stmt (stmt);
3911                   continue;
3912                 }
3913
3914               /* If there is no existing usable leader but SCCVN thinks
3915                  it has an expression it wants to use as replacement,
3916                  insert that.  */
3917               if (!sprime || sprime == lhs)
3918                 {
3919                   tree val = VN_INFO (lhs)->valnum;
3920                   if (val != VN_TOP
3921                       && TREE_CODE (val) == SSA_NAME
3922                       && VN_INFO (val)->needs_insertion
3923                       && can_PRE_operation (vn_get_expr_for (val)))
3924                     sprime = do_SCCVN_insertion (stmt, val);
3925                 }
3926               if (sprime
3927                   && sprime != lhs
3928                   && (rhs == NULL_TREE
3929                       || TREE_CODE (rhs) != SSA_NAME
3930                       || may_propagate_copy (rhs, sprime)))
3931                 {
3932                   gcc_assert (sprime != rhs);
3933
3934                   if (dump_file && (dump_flags & TDF_DETAILS))
3935                     {
3936                       fprintf (dump_file, "Replaced ");
3937                       print_gimple_expr (dump_file, stmt, 0, 0);
3938                       fprintf (dump_file, " with ");
3939                       print_generic_expr (dump_file, sprime, 0);
3940                       fprintf (dump_file, " in ");
3941                       print_gimple_stmt (dump_file, stmt, 0, 0);
3942                     }
3943
3944                   if (TREE_CODE (sprime) == SSA_NAME)
3945                     gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
3946                                     NECESSARY, true);
3947                   /* We need to make sure the new and old types actually match,
3948                      which may require adding a simple cast, which fold_convert
3949                      will do for us.  */
3950                   if ((!rhs || TREE_CODE (rhs) != SSA_NAME)
3951                       && !useless_type_conversion_p (gimple_expr_type (stmt),
3952                                                      TREE_TYPE (sprime)))
3953                     sprime = fold_convert (gimple_expr_type (stmt), sprime);
3954
3955                   pre_stats.eliminations++;
3956                   propagate_tree_value_into_stmt (&i, sprime);
3957                   stmt = gsi_stmt (i);
3958                   update_stmt (stmt);
3959
3960                   /* If we removed EH side effects from the statement, clean
3961                      its EH information.  */
3962                   if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
3963                     {
3964                       bitmap_set_bit (need_eh_cleanup,
3965                                       gimple_bb (stmt)->index);
3966                       if (dump_file && (dump_flags & TDF_DETAILS))
3967                         fprintf (dump_file, "  Removed EH side effects.\n");
3968                     }
3969                 }
3970             }
3971           /* Visit COND_EXPRs and fold the comparison with the
3972              available value-numbers.  */
3973           else if (gimple_code (stmt) == GIMPLE_COND)
3974             {
3975               tree op0 = gimple_cond_lhs (stmt);
3976               tree op1 = gimple_cond_rhs (stmt);
3977               tree result;
3978
3979               if (TREE_CODE (op0) == SSA_NAME)
3980                 op0 = VN_INFO (op0)->valnum;
3981               if (TREE_CODE (op1) == SSA_NAME)
3982                 op1 = VN_INFO (op1)->valnum;
3983               result = fold_binary (gimple_cond_code (stmt), boolean_type_node,
3984                                     op0, op1);
3985               if (result && TREE_CODE (result) == INTEGER_CST)
3986                 {
3987                   if (integer_zerop (result))
3988                     gimple_cond_make_false (stmt);
3989                   else
3990                     gimple_cond_make_true (stmt);
3991                   update_stmt (stmt);
3992                   todo = TODO_cleanup_cfg;
3993                 }
3994             }
3995         }
3996     }
3997
3998   return todo;
3999 }
4000
4001 /* Borrow a bit of tree-ssa-dce.c for the moment.
4002    XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
4003    this may be a bit faster, and we may want critical edges kept split.  */
4004
4005 /* If OP's defining statement has not already been determined to be necessary,
4006    mark that statement necessary. Return the stmt, if it is newly
4007    necessary.  */
4008
4009 static inline gimple
4010 mark_operand_necessary (tree op)
4011 {
4012   gimple stmt;
4013
4014   gcc_assert (op);
4015
4016   if (TREE_CODE (op) != SSA_NAME)
4017     return NULL;
4018
4019   stmt = SSA_NAME_DEF_STMT (op);
4020   gcc_assert (stmt);
4021
4022   if (gimple_plf (stmt, NECESSARY)
4023       || gimple_nop_p (stmt))
4024     return NULL;
4025
4026   gimple_set_plf (stmt, NECESSARY, true);
4027   return stmt;
4028 }
4029
4030 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4031    to insert PHI nodes sometimes, and because value numbering of casts isn't
4032    perfect, we sometimes end up inserting dead code.   This simple DCE-like
4033    pass removes any insertions we made that weren't actually used.  */
4034
4035 static void
4036 remove_dead_inserted_code (void)
4037 {
4038   VEC(gimple,heap) *worklist = NULL;
4039   int i;
4040   gimple t;
4041
4042   worklist = VEC_alloc (gimple, heap, VEC_length (gimple, inserted_exprs));
4043   for (i = 0; VEC_iterate (gimple, inserted_exprs, i, t); i++)
4044     {
4045       if (gimple_plf (t, NECESSARY))
4046         VEC_quick_push (gimple, worklist, t);
4047     }
4048   while (VEC_length (gimple, worklist) > 0)
4049     {
4050       t = VEC_pop (gimple, worklist);
4051
4052       /* PHI nodes are somewhat special in that each PHI alternative has
4053          data and control dependencies.  All the statements feeding the
4054          PHI node's arguments are always necessary. */
4055       if (gimple_code (t) == GIMPLE_PHI)
4056         {
4057           unsigned k;
4058
4059           VEC_reserve (gimple, heap, worklist, gimple_phi_num_args (t));
4060           for (k = 0; k < gimple_phi_num_args (t); k++)
4061             {
4062               tree arg = PHI_ARG_DEF (t, k);
4063               if (TREE_CODE (arg) == SSA_NAME)
4064                 {
4065                   gimple n = mark_operand_necessary (arg);
4066                   if (n)
4067                     VEC_quick_push (gimple, worklist, n);
4068                 }
4069             }
4070         }
4071       else
4072         {
4073           /* Propagate through the operands.  Examine all the USE, VUSE and
4074              VDEF operands in this statement.  Mark all the statements
4075              which feed this statement's uses as necessary.  */
4076           ssa_op_iter iter;
4077           tree use;
4078
4079           /* The operands of VDEF expressions are also needed as they
4080              represent potential definitions that may reach this
4081              statement (VDEF operands allow us to follow def-def
4082              links).  */
4083
4084           FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
4085             {
4086               gimple n = mark_operand_necessary (use);
4087               if (n)
4088                 VEC_safe_push (gimple, heap, worklist, n);
4089             }
4090         }
4091     }
4092
4093   for (i = 0; VEC_iterate (gimple, inserted_exprs, i, t); i++)
4094     {
4095       if (!gimple_plf (t, NECESSARY))
4096         {
4097           gimple_stmt_iterator gsi;
4098
4099           if (dump_file && (dump_flags & TDF_DETAILS))
4100             {
4101               fprintf (dump_file, "Removing unnecessary insertion:");
4102               print_gimple_stmt (dump_file, t, 0, 0);
4103             }
4104
4105           gsi = gsi_for_stmt (t);
4106           if (gimple_code (t) == GIMPLE_PHI)
4107             remove_phi_node (&gsi, true);
4108           else
4109             gsi_remove (&gsi, true);
4110           release_defs (t);
4111         }
4112     }
4113   VEC_free (gimple, heap, worklist);
4114 }
4115
4116 /* Initialize data structures used by PRE.  */
4117
4118 static void
4119 init_pre (bool do_fre)
4120 {
4121   basic_block bb;
4122
4123   next_expression_id = 1;
4124   expressions = NULL;
4125   VEC_safe_push (pre_expr, heap, expressions, NULL);
4126   value_expressions = VEC_alloc (bitmap_set_t, heap, get_max_value_id () + 1);
4127   VEC_safe_grow_cleared (bitmap_set_t, heap, value_expressions,
4128                          get_max_value_id() + 1);
4129
4130   in_fre = do_fre;
4131
4132   inserted_exprs = NULL;
4133   need_creation = NULL;
4134   pretemp = NULL_TREE;
4135   storetemp = NULL_TREE;
4136   prephitemp = NULL_TREE;
4137
4138   connect_infinite_loops_to_exit ();
4139   memset (&pre_stats, 0, sizeof (pre_stats));
4140
4141
4142   postorder = XNEWVEC (int, n_basic_blocks - NUM_FIXED_BLOCKS);
4143   post_order_compute (postorder, false, false);
4144
4145   FOR_ALL_BB (bb)
4146     bb->aux = XCNEWVEC (struct bb_bitmap_sets, 1);
4147
4148   calculate_dominance_info (CDI_POST_DOMINATORS);
4149   calculate_dominance_info (CDI_DOMINATORS);
4150
4151   bitmap_obstack_initialize (&grand_bitmap_obstack);
4152   phi_translate_table = htab_create (5110, expr_pred_trans_hash,
4153                                      expr_pred_trans_eq, free);
4154   expression_to_id = htab_create (num_ssa_names * 3,
4155                                   pre_expr_hash,
4156                                   pre_expr_eq, NULL);
4157   seen_during_translate = BITMAP_ALLOC (&grand_bitmap_obstack);
4158   bitmap_set_pool = create_alloc_pool ("Bitmap sets",
4159                                        sizeof (struct bitmap_set), 30);
4160   pre_expr_pool = create_alloc_pool ("pre_expr nodes",
4161                                      sizeof (struct pre_expr_d), 30);
4162   FOR_ALL_BB (bb)
4163     {
4164       EXP_GEN (bb) = bitmap_set_new ();
4165       PHI_GEN (bb) = bitmap_set_new ();
4166       TMP_GEN (bb) = bitmap_set_new ();
4167       AVAIL_OUT (bb) = bitmap_set_new ();
4168     }
4169   maximal_set = in_fre ? NULL : bitmap_set_new ();
4170
4171   need_eh_cleanup = BITMAP_ALLOC (NULL);
4172 }
4173
4174
4175 /* Deallocate data structures used by PRE.  */
4176
4177 static void
4178 fini_pre (bool do_fre)
4179 {
4180   basic_block bb;
4181
4182   free (postorder);
4183   VEC_free (bitmap_set_t, heap, value_expressions);
4184   VEC_free (gimple, heap, inserted_exprs);
4185   VEC_free (gimple, heap, need_creation);
4186   bitmap_obstack_release (&grand_bitmap_obstack);
4187   free_alloc_pool (bitmap_set_pool);
4188   free_alloc_pool (pre_expr_pool);
4189   htab_delete (phi_translate_table);
4190   htab_delete (expression_to_id);
4191
4192   FOR_ALL_BB (bb)
4193     {
4194       free (bb->aux);
4195       bb->aux = NULL;
4196     }
4197
4198   free_dominance_info (CDI_POST_DOMINATORS);
4199
4200   if (!bitmap_empty_p (need_eh_cleanup))
4201     {
4202       gimple_purge_all_dead_eh_edges (need_eh_cleanup);
4203       cleanup_tree_cfg ();
4204     }
4205
4206   BITMAP_FREE (need_eh_cleanup);
4207
4208   if (!do_fre)
4209     loop_optimizer_finalize ();
4210 }
4211
4212 /* Main entry point to the SSA-PRE pass.  DO_FRE is true if the caller
4213    only wants to do full redundancy elimination.  */
4214
4215 static unsigned int
4216 execute_pre (bool do_fre ATTRIBUTE_UNUSED)
4217 {
4218   unsigned int todo = 0;
4219
4220   do_partial_partial = optimize > 2;
4221
4222   /* This has to happen before SCCVN runs because
4223      loop_optimizer_init may create new phis, etc.  */
4224   if (!do_fre)
4225     loop_optimizer_init (LOOPS_NORMAL);
4226
4227   if (!run_scc_vn (do_fre))
4228     {
4229       if (!do_fre)
4230         {
4231           remove_dead_inserted_code ();
4232           loop_optimizer_finalize ();
4233         }
4234       
4235       return 0;
4236     }
4237   init_pre (do_fre);
4238
4239
4240   /* Collect and value number expressions computed in each basic block.  */
4241   compute_avail ();
4242
4243   if (dump_file && (dump_flags & TDF_DETAILS))
4244     {
4245       basic_block bb;
4246
4247       FOR_ALL_BB (bb)
4248         {
4249           print_bitmap_set (dump_file, EXP_GEN (bb), "exp_gen", bb->index);
4250           print_bitmap_set (dump_file, TMP_GEN (bb), "tmp_gen",
4251                                   bb->index);
4252           print_bitmap_set (dump_file, AVAIL_OUT (bb), "avail_out",
4253                                   bb->index);
4254         }
4255     }
4256
4257   /* Insert can get quite slow on an incredibly large number of basic
4258      blocks due to some quadratic behavior.  Until this behavior is
4259      fixed, don't run it when he have an incredibly large number of
4260      bb's.  If we aren't going to run insert, there is no point in
4261      computing ANTIC, either, even though it's plenty fast.  */
4262   if (!do_fre && n_basic_blocks < 4000)
4263     {
4264       compute_antic ();
4265       insert ();
4266     }
4267
4268   /* Remove all the redundant expressions.  */
4269   todo |= eliminate ();
4270
4271   statistics_counter_event (cfun, "Insertions", pre_stats.insertions);
4272   statistics_counter_event (cfun, "PA inserted", pre_stats.pa_insert);
4273   statistics_counter_event (cfun, "New PHIs", pre_stats.phis);
4274   statistics_counter_event (cfun, "Eliminated", pre_stats.eliminations);
4275   statistics_counter_event (cfun, "Constified", pre_stats.constified);
4276
4277   /* Make sure to remove fake edges before committing our inserts.
4278      This makes sure we don't end up with extra critical edges that
4279      we would need to split.  */
4280   remove_fake_exit_edges ();
4281   gsi_commit_edge_inserts ();
4282
4283   clear_expression_ids ();
4284   free_scc_vn ();
4285   if (!do_fre)
4286     remove_dead_inserted_code ();
4287
4288   fini_pre (do_fre);
4289
4290   return todo;
4291 }
4292
4293 /* Gate and execute functions for PRE.  */
4294
4295 static unsigned int
4296 do_pre (void)
4297 {
4298   return TODO_rebuild_alias | execute_pre (false);
4299 }
4300
4301 static bool
4302 gate_pre (void)
4303 {
4304   /* PRE tends to generate bigger code.  */
4305   return flag_tree_pre != 0 && optimize_function_for_speed_p (cfun);
4306 }
4307
4308 struct gimple_opt_pass pass_pre =
4309 {
4310  {
4311   GIMPLE_PASS,
4312   "pre",                                /* name */
4313   gate_pre,                             /* gate */
4314   do_pre,                               /* execute */
4315   NULL,                                 /* sub */
4316   NULL,                                 /* next */
4317   0,                                    /* static_pass_number */
4318   TV_TREE_PRE,                          /* tv_id */
4319   PROP_no_crit_edges | PROP_cfg
4320     | PROP_ssa | PROP_alias,            /* properties_required */
4321   0,                                    /* properties_provided */
4322   0,                                    /* properties_destroyed */
4323   0,                                    /* todo_flags_start */
4324   TODO_update_ssa_only_virtuals | TODO_dump_func | TODO_ggc_collect
4325   | TODO_verify_ssa /* todo_flags_finish */
4326  }
4327 };
4328
4329
4330 /* Gate and execute functions for FRE.  */
4331
4332 static unsigned int
4333 execute_fre (void)
4334 {
4335   return execute_pre (true);
4336 }
4337
4338 static bool
4339 gate_fre (void)
4340 {
4341   return flag_tree_fre != 0;
4342 }
4343
4344 struct gimple_opt_pass pass_fre =
4345 {
4346  {
4347   GIMPLE_PASS,
4348   "fre",                                /* name */
4349   gate_fre,                             /* gate */
4350   execute_fre,                          /* execute */
4351   NULL,                                 /* sub */
4352   NULL,                                 /* next */
4353   0,                                    /* static_pass_number */
4354   TV_TREE_FRE,                          /* tv_id */
4355   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
4356   0,                                    /* properties_provided */
4357   0,                                    /* properties_destroyed */
4358   0,                                    /* todo_flags_start */
4359   TODO_dump_func | TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
4360  }
4361 };