OSDN Git Service

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