OSDN Git Service

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