OSDN Git Service

* Makefile.in (distclean): Don't try to remove empty directories.
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-pre.c
1 /* SSA-PRE for trees.
2    Copyright (C) 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
3    Contributed by Daniel Berlin <dan@dberlin.org> and Steven Bosscher
4    <stevenb@suse.de> 
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to
20 the Free Software Foundation, 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.  */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "errors.h"
27 #include "ggc.h"
28 #include "tree.h"
29
30 /* These RTL headers are needed for basic-block.h.  */
31 #include "rtl.h"
32 #include "tm_p.h"
33 #include "hard-reg-set.h"
34 #include "basic-block.h"
35 #include "diagnostic.h"
36 #include "tree-inline.h"
37 #include "tree-flow.h"
38 #include "tree-gimple.h"
39 #include "tree-dump.h"
40 #include "timevar.h"
41 #include "fibheap.h"
42 #include "hashtab.h"
43 #include "tree-iterator.h"
44 #include "real.h"
45 #include "alloc-pool.h"
46 #include "tree-pass.h"
47 #include "flags.h"
48 #include "splay-tree.h"
49 #include "bitmap.h"
50 #include "langhooks.h"
51 /* TODO:
52    
53    1. Implement load value numbering.
54    2. Speed up insert_aux so that we can use it all the time.  It
55       spends most of it's time in quadratic value replacement.
56    3. Avail sets can be shared by making an avail_find_leader that
57       walks up the dominator tree and looks in those avail sets.
58       This might affect code optimality, it's unclear right now.
59    4. Load motion can be performed by value numbering the loads the
60       same as we do other expressions.  This requires iterative
61       hashing the vuses into the values.  Right now we simply assign
62       a new value every time we see a statement with a vuse.
63    5. Strength reduction can be performed by anticipating expressions
64       we can repair later on.
65    6. Our canonicalization of expressions during lookups don't take
66       constants into account very well.  In particular, we don't fold
67       anywhere, so we can get situations where we stupidly think
68       something is a new value (a + 1 + 1 vs a + 2).  This is somewhat
69       expensive to fix, but it does expose a lot more eliminations.
70       It may or not be worth it, depending on how critical you
71       consider PRE vs just plain GRE.
72 */   
73
74 /* For ease of terminology, "expression node" in the below refers to
75    every expression node but MODIFY_EXPR, because MODIFY_EXPR's represent
76    the actual statement containing the expressions we care about, and
77    we cache the value number by putting it in the expression.  */
78
79 /* Basic algorithm
80    
81    First we walk the statements to generate the AVAIL sets, the
82    EXP_GEN sets, and the tmp_gen sets.  EXP_GEN sets represent the
83    generation of values/expressions by a given block.  We use them
84    when computing the ANTIC sets.  The AVAIL sets consist of
85    SSA_NAME's that represent values, so we know what values are
86    available in what blocks.  AVAIL is a forward dataflow problem.  In
87    SSA, values are never killed, so we don't need a kill set, or a
88    fixpoint iteration, in order to calculate the AVAIL sets.  In
89    traditional parlance, AVAIL sets tell us the downsafety of the
90    expressions/values.
91    
92    Next, we generate the ANTIC sets.  These sets represent the
93    anticipatable expressions.  ANTIC is a backwards dataflow
94    problem.An expression is anticipatable in a given block if it could
95    be generated in that block.  This means that if we had to perform
96    an insertion in that block, of the value of that expression, we
97    could.  Calculating the ANTIC sets requires phi translation of
98    expressions, because the flow goes backwards through phis.  We must
99    iterate to a fixpoint of the ANTIC sets, because we have a kill
100    set.  Even in SSA form, values are not live over the entire
101    function, only from their definition point onwards.  So we have to
102    remove values from the ANTIC set once we go past the definition
103    point of the leaders that make them up.
104    compute_antic/compute_antic_aux performs this computation.
105
106    Third, we perform insertions to make partially redundant
107    expressions fully redundant.
108
109    An expression is partially redundant (excluding partial
110    anticipation) if:
111
112    1. It is AVAIL in some, but not all, of the predecessors of a
113       given block.
114    2. It is ANTIC in all the predecessors.
115
116    In order to make it fully redundant, we insert the expression into
117    the predecessors where it is not available, but is ANTIC.
118    insert/insert_aux performs this insertion.
119
120    Fourth, we eliminate fully redundant expressions.
121    This is a simple statement walk that replaces redundant
122    calculations  with the now available values.  */
123
124 /* Representations of value numbers:
125
126    Value numbers are represented using the "value handle" approach.
127    This means that each SSA_NAME (and for other reasons to be
128    disclosed in a moment, expression nodes) has a value handle that
129    can be retrieved through get_value_handle.  This value handle, *is*
130    the value number of the SSA_NAME.  You can pointer compare the
131    value handles for equivalence purposes.
132
133    For debugging reasons, the value handle is internally more than
134    just a number, it is a VAR_DECL named "value.x", where x is a
135    unique number for each value number in use.  This allows
136    expressions with SSA_NAMES replaced by value handles to still be
137    pretty printed in a sane way.  They simply print as "value.3 *
138    value.5", etc.  
139
140    Expression nodes have value handles associated with them as a
141    cache.  Otherwise, we'd have to look them up again in the hash
142    table This makes significant difference (factor of two or more) on
143    some test cases.  They can be thrown away after the pass is
144    finished.  */
145
146 /* Representation of expressions on value numbers: 
147
148    In some portions of this code, you will notice we allocate "fake"
149    analogues to the expression we are value numbering, and replace the
150    operands with the values of the expression.  Since we work on
151    values, and not just names, we canonicalize expressions to value
152    expressions for use in the ANTIC sets, the EXP_GEN set, etc.  
153
154    This is theoretically unnecessary, it just saves a bunch of
155    repeated get_value_handle and find_leader calls in the remainder of
156    the code, trading off temporary memory usage for speed.  The tree
157    nodes aren't actually creating more garbage, since they are
158    allocated in a special pools which are thrown away at the end of
159    this pass.  
160
161    All of this also means that if you print the EXP_GEN or ANTIC sets,
162    you will see "value.5 + value.7" in the set, instead of "a_55 +
163    b_66" or something.  The only thing that actually cares about
164    seeing the value leaders is phi translation, and it needs to be
165    able to find the leader for a value in an arbitrary block, so this
166    "value expression" form is perfect for it (otherwise you'd do
167    get_value_handle->find_leader->translate->get_value_handle->find_leader).*/
168
169
170 /* Representation of sets:
171
172    Sets are represented as doubly linked lists kept in topological
173    order, with an optional supporting bitmap of values present in the
174    set.  The sets represent values, and the elements can be values or
175    expressions.  The elements can appear in different sets, but each
176    element can only appear once in each set.
177
178    Since each node in the set represents a value, we also want to be
179    able to map expression, set pairs to something that tells us
180    whether the value is present is a set.  We use a per-set bitmap for
181    that.  The value handles also point to a linked list of the
182    expressions they represent via a tree annotation.  This is mainly
183    useful only for debugging, since we don't do identity lookups.  */
184
185
186 /* A value set element.  Basically a single linked list of
187    expressions/values.  */
188 typedef struct value_set_node
189 {
190   /* An expression.  */
191   tree expr;
192
193   /* A pointer to the next element of the value set.  */
194   struct value_set_node *next;
195 } *value_set_node_t;
196
197
198 /* A value set.  This is a singly linked list of value_set_node
199    elements with a possible bitmap that tells us what values exist in
200    the set.  This set must be kept in topologically sorted order.  */
201 typedef struct value_set
202 {
203   /* The head of the list.  Used for iterating over the list in
204      order.  */
205   value_set_node_t head;
206
207   /* The tail of the list.  Used for tail insertions, which are
208      necessary to keep the set in topologically sorted order because
209      of how the set is built.  */
210   value_set_node_t tail;
211   
212   /* The length of the list.  */
213   size_t length;
214   
215   /* True if the set is indexed, which means it contains a backing
216      bitmap for quick determination of whether certain values exist in the
217      set.  */
218   bool indexed;
219   
220   /* The bitmap of values that exist in the set.  May be NULL in an
221      empty or non-indexed set.  */
222   bitmap values;
223   
224 } *value_set_t;
225
226 /* All of the following sets, except for TMP_GEN, are indexed.
227    TMP_GEN is only ever iterated over, we never check what values
228    exist in it.  */
229
230 typedef struct bb_value_sets
231 {
232   /* The EXP_GEN set, which represents expressions/values generated in
233      a basic block.  */
234   value_set_t exp_gen;
235
236   /* The PHI_GEN set, which represents PHI results generated in a
237      basic block.  */
238   value_set_t phi_gen;
239
240   /* The TMP_GEN set, which represents results/temporaries genererated
241      in a basic block. IE the LHS of an expression.  */
242   value_set_t tmp_gen;
243
244   /* The AVAIL_OUT set, which represents which values are available in
245      a given basic block.  */
246   value_set_t avail_out;
247
248   /* The ANTIC_IN set, which represents which values are anticiptable
249      in a given basic block.  */
250   value_set_t antic_in;
251
252   /* The NEW_SETS set, which is used during insertion to augment the
253      AVAIL_OUT set of blocks with the new insertions performed during
254      the current iteration.  */
255   value_set_t new_sets;
256 } *bb_value_sets_t;
257
258 #define EXP_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->exp_gen
259 #define PHI_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->phi_gen
260 #define TMP_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->tmp_gen
261 #define AVAIL_OUT(BB)   ((bb_value_sets_t) ((BB)->aux))->avail_out
262 #define ANTIC_IN(BB)    ((bb_value_sets_t) ((BB)->aux))->antic_in
263 #define NEW_SETS(BB)    ((bb_value_sets_t) ((BB)->aux))->new_sets
264
265 /* This structure is used to keep track of statistics on what
266    optimization PRE was able to perform.  */
267 static struct
268 {
269   /* The number of RHS computations eliminated by PRE.  */
270   int eliminations;
271
272   /* The number of new expressions/temporaries generated by PRE.  */
273   int insertions;
274
275   /* The number of new PHI nodes added by PRE.  */
276   int phis;
277 } pre_stats;
278
279 static tree find_leader (value_set_t, tree);
280 static void value_insert_into_set (value_set_t, tree);
281 static void insert_into_set (value_set_t, tree);
282 static void add_to_value (tree, tree);
283 static value_set_t set_new  (bool);
284 static bool is_undefined_value (tree);
285 static bool expressions_equal_p (tree, tree);
286 static tree create_expression_by_pieces (basic_block, tree, tree);
287
288 /* We can add and remove elements and entries to and from sets
289    and hash tables, so we use alloc pools for them.  */
290
291 static alloc_pool value_set_pool;
292 static alloc_pool value_set_node_pool;
293 static alloc_pool binary_node_pool;
294 static alloc_pool unary_node_pool;
295
296 /* The value table that maps expressions to values.  */
297
298 static htab_t value_table;
299
300 /* The phi_translate_table caches phi translations for a given
301    expression and predecessor.  */
302
303 static htab_t phi_translate_table;
304
305 /* Compare two expressions E1 and E2 and return true if they are
306    equal.  */
307
308 static bool
309 expressions_equal_p (tree e1, tree e2)
310 {
311   tree te1, te2;
312   
313   if (e1 == e2)
314     return true;
315   
316   te1 = TREE_TYPE (e1);
317   te2 = TREE_TYPE (e2);
318
319   if (TREE_CODE (e1) == TREE_CODE (e2) 
320       && (te1 == te2 || lang_hooks.types_compatible_p (te1, te2))
321       && operand_equal_p (e1, e2, 0))
322     return true;
323   return false;
324 }
325
326 /* Map expressions to values.  These are simple pairs of expressions
327    and the values they represent.  To find the value represented by
328    an expression, we use a hash table where the elements are {e,v}
329    pairs, and the expression is the key.  */
330
331 typedef struct val_expr_pair_d
332 {
333   tree v, e;
334   hashval_t hashcode;
335 } *val_expr_pair_t;
336
337
338 /* Hash a {v,e} pair that is pointed to by P.
339    The hashcode is cached in the val_expr_pair, so we just return
340    that.  */
341
342 static hashval_t
343 val_expr_pair_hash (const void *p)
344 {
345   const val_expr_pair_t ve = (val_expr_pair_t) p;
346   return ve->hashcode;
347 }
348
349
350 /* Given two val_expr_pair_t's, return true if they represent the same
351    expression, false otherwise.
352    P1 and P2 should point to the val_expr_pair_t's to be compared.  */
353
354 static int
355 val_expr_pair_expr_eq (const void *p1, const void *p2)
356 {
357   const val_expr_pair_t ve1 = (val_expr_pair_t) p1;
358   const val_expr_pair_t ve2 = (val_expr_pair_t) p2;
359
360   if (expressions_equal_p (ve1->e, ve2->e))
361     return true;
362   
363   return false;
364 }
365
366
367 /* Get the value handle of EXPR.  This is the only correct way to get
368    the value handle for a "thing". 
369    Returns NULL if the value handle does not exist.  */
370
371 tree
372 get_value_handle (tree expr)
373 {
374   /* We should never see these.  */
375   if (DECL_P (expr))
376     abort ();
377   else if (TREE_CODE (expr) == SSA_NAME)
378     {
379       return SSA_NAME_VALUE (expr);
380     }
381   else if (TREE_CODE_CLASS (TREE_CODE (expr)) == 'c')
382     return expr;
383   else if (EXPR_P (expr))
384     {
385       tree_ann_t ann = tree_ann (expr);  
386       if (ann)
387         return ann->common.value_handle;
388       return NULL;
389     }
390   abort ();
391 }
392
393
394 /* Set the value handle for expression E to value V */
395    
396 void
397 set_value_handle (tree e, tree v)
398 {
399   if (DECL_P (e))
400     abort ();
401   else if (TREE_CODE (e) == SSA_NAME)
402     SSA_NAME_VALUE (e) = v;
403   else if (EXPR_P (e))
404     get_tree_ann (e)->common.value_handle = v;
405 }
406
407 /* A three tuple {e, pred, v} used to cache phi translations in the
408    phi_translate_table.  */
409
410 typedef struct expr_pred_trans_d
411 {
412   /* The expression. */
413   tree e;
414
415   /* The predecessor block along which we translated the expression.  */
416   basic_block pred;
417
418   /* The value that resulted from the translation.  */
419   tree v;
420
421   /* The hashcode for the expression, pred pair. This is cached for
422      speed reasons.  */
423   hashval_t hashcode;
424 } *expr_pred_trans_t;
425
426 /* Return the hash value for a phi translation table entry.  */
427
428 static hashval_t
429 expr_pred_trans_hash (const void *p)
430 {
431   const expr_pred_trans_t ve = (expr_pred_trans_t) p;
432   return ve->hashcode;
433 }
434
435 /* Return true if two phi translation table entries are the same.
436    P1 and P2 should point to the expr_pred_trans_t's to be compared.*/
437
438 static int
439 expr_pred_trans_eq (const void *p1, const void *p2)
440 {
441   const expr_pred_trans_t ve1 = (expr_pred_trans_t) p1;
442   const expr_pred_trans_t ve2 = (expr_pred_trans_t) p2;
443   basic_block b1 = ve1->pred;
444   basic_block b2 = ve2->pred;
445
446   
447   /* If they are not translations for the same basic block, they can't
448      be equal.  */
449   if (b1 != b2)
450     return false;
451
452   /* If they are for the same basic block, determine if the
453      expressions are equal.   */  
454   if (expressions_equal_p (ve1->e, ve2->e))
455     return true;
456   
457   return false;
458 }
459
460 /* Search in the phi translation table for the translation of
461    expression E in basic block PRED. Return the translated value, if
462    found, NULL otherwise. */ 
463
464 static inline tree
465 phi_trans_lookup (tree e, basic_block pred)
466 {
467   void **slot;
468   struct expr_pred_trans_d ept;
469   ept.e = e;
470   ept.pred = pred;
471   ept.hashcode = iterative_hash_expr (e, (unsigned long) pred);
472   slot = htab_find_slot_with_hash (phi_translate_table, &ept, ept.hashcode,
473                                    NO_INSERT);
474   if (!slot)
475     return NULL;
476   else
477     return ((expr_pred_trans_t) *slot)->v;
478 }
479
480
481 /* Add the tuple mapping from {expression E, basic block PRED} to
482    value V, to the phi translation table.  */
483
484 static inline void
485 phi_trans_add (tree e, tree v, basic_block pred)
486 {
487   void **slot;
488   expr_pred_trans_t new_pair = xmalloc (sizeof (*new_pair));
489   new_pair->e = e;
490   new_pair->pred = pred;
491   new_pair->v = v;
492   new_pair->hashcode = iterative_hash_expr (e, (unsigned long) pred);
493   slot = htab_find_slot_with_hash (phi_translate_table, new_pair,
494                                    new_pair->hashcode, INSERT);
495   if (*slot)
496     free (*slot);
497   *slot = (void *) new_pair;
498 }
499
500 /* Search in TABLE for an existing instance of expression E,
501    and return its value, or NULL if none has been set.  */
502
503 static inline tree
504 lookup (htab_t table, tree e)
505 {
506   void **slot;
507   struct val_expr_pair_d vep = {NULL, NULL, 0};
508   if (TREE_CODE_CLASS (TREE_CODE (e)) == 'c')
509     return e;
510   vep.e = e;
511   vep.hashcode = iterative_hash_expr (e,0); 
512   slot = htab_find_slot_with_hash (table, &vep, vep.hashcode, NO_INSERT);
513   if (!slot)
514     return NULL_TREE;
515   else
516     return ((val_expr_pair_t) *slot)->v;
517 }
518
519 /* Add expression E to the expression set of value V.  */
520
521 static inline void
522 add_to_value (tree v, tree e)
523 {
524   var_ann_t va;
525   /* For values representing non-CST nodes, but still function
526      invariant things we mark TREE_CONSTANT as true and set the tree
527      chain to the actual constant.  This is because unlike values
528      involving expressions, which are only available to use where the
529      expressions are live, a function invariant can be remade
530      anywhere, and thus, is available everywhere, just like a constant.  */
531   if (TREE_CODE_CLASS (TREE_CODE (v)) == 'c')
532     return;
533   else if (is_gimple_min_invariant (v))
534     {
535       TREE_CONSTANT (v) = true;
536       TREE_CHAIN (v) = e;
537       return;
538     }
539   va = var_ann (v);
540   if (va->expr_set == NULL)
541     va->expr_set = set_new (false);
542   insert_into_set (va->expr_set, e);
543 }
544
545 /* Insert E into TABLE with value V, and add expression E to the value
546    set for value V.  */
547
548 static inline void
549 add (htab_t table, tree e, tree v)
550 {
551
552   void **slot;
553   val_expr_pair_t new_pair = xmalloc (sizeof (struct val_expr_pair_d));
554   new_pair->e = e;
555   new_pair->v = v;
556   new_pair->hashcode = iterative_hash_expr (e, 0);
557   slot = htab_find_slot_with_hash (table, new_pair, new_pair->hashcode,
558                                    INSERT);
559   if (*slot)
560     free (*slot);
561   *slot = (void *) new_pair;
562   set_value_handle (e, v);
563
564   add_to_value (v, e);
565  
566 }
567
568 /* A unique counter that is incremented every time we create a new
569    value.  */
570 static int pre_uid;
571
572 /* Create a new value handle for expression EXPR.  */
573
574 static tree
575 create_new_value (tree expr)
576 {
577   tree a = create_tmp_var_raw (TREE_TYPE (expr), "value");
578   create_var_ann (a);
579   var_ann (a)->uid = pre_uid++;
580
581   if (dump_file && (dump_flags & TDF_DETAILS))
582     {     
583       fprintf (dump_file, "Created value ");
584       print_generic_expr (dump_file, a, dump_flags);
585       fprintf (dump_file, " for ");
586       print_generic_expr (dump_file, expr, dump_flags);
587       fprintf (dump_file, "\n");
588     }
589   return a;
590 }
591
592 /* Like lookup, but creates a new value for expression E if E doesn't
593    already have a value.
594    Return the existing/created value for E.  */
595
596 static inline tree
597 lookup_or_add (htab_t table, tree e)
598 {
599   tree x = lookup (table, e);
600   if (x == NULL_TREE)
601     {
602       tree v;
603       v = create_new_value (e);
604       add (table, e, v);
605       x = v;
606     }
607   set_value_handle (e, x);
608   return x;
609 }
610
611   
612 /* Return true if value V exists in the bitmap for SET.  */
613
614 static inline bool
615 value_exists_in_set_bitmap (value_set_t set, tree v)
616 {
617   if (TREE_CODE (v) != VAR_DECL)
618     abort ();
619
620   if (!set->values)
621     return false;
622   return bitmap_bit_p (set->values, get_var_ann (v)->uid);
623 }
624
625 /* Remove value V from the bitmap for SET.  */
626
627 static void
628 value_remove_from_set_bitmap (value_set_t set, tree v)
629 {
630   if (TREE_CODE (v) != VAR_DECL)
631     abort ();
632 #ifdef ENABLE_CHECKING
633   if (!set->indexed)
634     abort ();
635 #endif
636   if (!set->values)
637     return;
638   bitmap_clear_bit (set->values, get_var_ann (v)->uid);
639 }
640
641
642 /* Insert the value number V into the bitmap of values existing in
643    SET.  */
644
645 static inline void
646 value_insert_into_set_bitmap (value_set_t set, tree v)
647 {
648   if (TREE_CODE (v) != VAR_DECL)
649     abort ();  
650 #ifdef ENABLE_CHECKING
651   if (!set->indexed)
652     abort ();
653 #endif
654   if (set->values == NULL)
655     {
656       set->values = BITMAP_GGC_ALLOC ();
657       bitmap_clear (set->values);
658     }
659   bitmap_set_bit (set->values, get_var_ann (v)->uid);
660 }
661
662 /* Create a new set.  */
663
664 static value_set_t
665 set_new  (bool indexed)
666 {
667   value_set_t ret;
668   ret = pool_alloc (value_set_pool);
669   ret->head = ret->tail = NULL;
670   ret->length = 0;
671   ret->indexed = indexed;
672   ret->values = NULL;
673   return ret;
674 }
675
676
677 /* Insert EXPR into SET.  */
678
679 static void
680 insert_into_set (value_set_t set, tree expr)
681 {
682   value_set_node_t newnode = pool_alloc (value_set_node_pool);
683   tree val = get_value_handle (expr);
684   if (DECL_P (expr))
685     abort ();
686   
687   if (val == NULL)
688     abort ();
689
690   /* For indexed sets, insert the value into the set value bitmap.
691      For all sets, add it to the linked list and increment the list
692      length.  */
693   if (set->indexed)
694     value_insert_into_set_bitmap (set, val);
695
696   newnode->next = NULL;
697   newnode->expr = expr;
698   set->length ++;
699   if (set->head == NULL)
700     {
701       set->head = set->tail = newnode;
702     }
703   else
704     {
705       set->tail->next = newnode;
706       set->tail = newnode;
707     }
708 }
709
710 /* Copy the set ORIG to the set DEST.  */
711
712 static void
713 set_copy (value_set_t dest, value_set_t orig)
714 {
715   value_set_node_t node;
716  
717   if (!orig || !orig->head)
718     return;
719
720   for (node = orig->head;
721        node;
722        node = node->next)
723     {
724       insert_into_set (dest, node->expr);
725     }
726 }
727
728 /* Remove EXPR from SET.  */
729
730 static void
731 set_remove (value_set_t set, tree expr)
732 {
733   value_set_node_t node, prev;
734
735   /* Remove the value of EXPR from the bitmap, decrement the set
736      length, and remove it from the actual double linked list.  */ 
737   value_remove_from_set_bitmap (set, get_value_handle (expr));
738   set->length--;
739   prev = NULL;
740   for (node = set->head; 
741        node != NULL; 
742        prev = node, node = node->next)
743     {
744       if (node->expr == expr)
745         {
746           if (prev == NULL)
747             set->head = node->next;
748           else
749             prev->next= node->next;
750  
751           if (node == set->tail)
752             set->tail = prev;
753           pool_free (value_set_node_pool, node);
754           return;
755         }
756     }
757 }
758
759 /* Return true if SET contains the value VAL.  */
760
761 static bool
762 set_contains_value (value_set_t set, tree val)
763 {
764   /* All true constants are in every set.  */
765   if (TREE_CODE_CLASS (TREE_CODE (val)) == 'c')
766     return true;
767   /* This is only referring to the flag above that we set on
768      values referring to invariants, because we know that we
769      are dealing with one of the value handles we created.  */
770
771   if (TREE_CONSTANT (val))
772     return true;
773   
774   if (set->length == 0)
775     return false;
776   
777   return value_exists_in_set_bitmap (set, val);
778 }
779
780 /* Replace the leader for the value LOOKFOR in SET with EXPR.  */
781
782 static void
783 set_replace_value (value_set_t set, tree lookfor, tree expr)
784 {
785   value_set_node_t node = set->head;
786
787   /* The lookup is probably more expensive than walking the linked
788      list when we have only a small number of nodes.  */
789   if (!set_contains_value (set, lookfor))
790     return;
791
792   for (node = set->head;
793        node;
794        node = node->next)
795     {
796       if (get_value_handle (node->expr) == lookfor)
797         {
798           node->expr = expr;
799           return;
800         }
801     }
802 }
803
804 /* Return true if the set contains expression (not value) EXPR.  */
805
806 static bool
807 set_contains (value_set_t set, tree expr)
808 {
809   value_set_node_t node;
810   
811   for (node = set->head;
812        node;
813        node = node->next)
814     {
815       if (operand_equal_p (node->expr, expr, 0))
816         return true;
817     }
818   return false;
819 }
820
821 /* Subtract set B from set A, and return the new set.  */
822
823 static value_set_t
824 set_subtract (value_set_t a, value_set_t b, bool indexed)
825 {
826   value_set_t ret = set_new (indexed);
827   value_set_node_t node;
828   for (node = a->head;
829        node;
830        node = node->next)
831     {
832       if (!set_contains (b, node->expr))
833         insert_into_set (ret, node->expr);
834     }
835   return ret;
836 }
837
838 /* Return true if two sets are equal. */
839
840 static bool
841 set_equal (value_set_t a, value_set_t b)
842 {
843   value_set_node_t node;
844
845   if (a->length != b->length)
846     return false;
847   for (node = a->head;
848        node;
849        node = node->next)
850     {
851       if (!set_contains_value (b, get_value_handle (node->expr)))
852         return false;
853     }
854   return true;
855 }
856
857 /* Replace the value for EXPR in SET with EXPR.  */
858 static void
859 value_replace_in_set (value_set_t set, tree expr)
860 {
861   tree val = get_value_handle (expr);
862
863   if (set->length == 0)
864     return;
865   
866   set_replace_value (set, val, expr);
867 }
868
869 /* Insert the value for EXPR into SET, if it doesn't exist already.  */
870
871 static void
872 value_insert_into_set (value_set_t set, tree expr)
873 {
874   tree val = get_value_handle (expr);
875
876
877   /* Constant and invariant values exist everywhere, and thus,
878      actually keeping them in the sets is pointless.  */
879   if (TREE_CONSTANT (val))
880     return;
881
882   if (!set_contains_value (set, val))
883     insert_into_set (set, expr);
884 }
885
886
887 /* Print out the value_set SET to OUTFILE.  */
888
889 static void
890 print_value_set (FILE *outfile, value_set_t set,
891                  const char *setname, int blockindex)
892 {
893   value_set_node_t node;
894   fprintf (outfile, "%s[%d] := { ", setname, blockindex);
895   if (set)
896     {
897       for (node = set->head;
898            node;
899            node = node->next)
900         {
901           print_generic_expr (outfile, node->expr, 0);
902           
903           fprintf (outfile, " (");
904           print_generic_expr (outfile, get_value_handle (node->expr), 0);
905           fprintf (outfile, ") ");
906                      
907           if (node->next)
908             fprintf (outfile, ", ");
909         }
910     }
911
912   fprintf (outfile, " }\n");
913 }
914
915 /* Print out the expressions that have VAL to OUTFILE.  */
916 void
917 print_value_expressions (FILE *outfile, tree val)
918 {
919   var_ann_t va = var_ann (val);
920   if (va && va->expr_set)
921     print_value_set (outfile, va->expr_set, 
922                      IDENTIFIER_POINTER (DECL_NAME (val)), 0);
923 }
924
925
926 void
927 debug_value_expressions (tree val)
928 {
929   print_value_expressions (stderr, val);
930 }
931
932   
933 void debug_value_set (value_set_t, const char *, int);
934
935 void
936 debug_value_set (value_set_t set, const char *setname, int blockindex)
937 {
938   print_value_set (stderr, set, setname, blockindex);
939 }
940
941 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
942    the phis in PRED.  Return NULL if we can't find a leader for each
943    part of the translated expression.  */
944
945 static tree
946 phi_translate (tree expr, value_set_t set,  basic_block pred,
947                basic_block phiblock)
948 {
949   tree phitrans = NULL;
950   tree oldexpr = expr;
951   
952   if (expr == NULL)
953     return NULL;
954
955   /* Phi translations of a given expression don't change,  */
956   phitrans = phi_trans_lookup (expr, pred);
957   if (phitrans)
958     return phitrans;
959   
960   
961   switch (TREE_CODE_CLASS (TREE_CODE (expr)))
962     {
963     case '2':
964       {
965         tree oldop1 = TREE_OPERAND (expr, 0);
966         tree oldop2 = TREE_OPERAND (expr, 1);
967         tree newop1;
968         tree newop2;
969         tree newexpr;
970         
971         newop1 = phi_translate (find_leader (set, oldop1),
972                                 set, pred, phiblock);
973         if (newop1 == NULL)
974           return NULL;
975         newop2 = phi_translate (find_leader (set, oldop2),
976                                 set, pred, phiblock);
977         if (newop2 == NULL)
978           return NULL;
979         if (newop1 != oldop1 || newop2 != oldop2)
980           {
981             newexpr = pool_alloc (binary_node_pool);
982             memcpy (newexpr, expr, tree_size (expr));
983             create_tree_ann (newexpr);
984             TREE_OPERAND (newexpr, 0) = newop1 == oldop1 ? oldop1 : get_value_handle (newop1);
985             TREE_OPERAND (newexpr, 1) = newop2 == oldop2 ? oldop2 : get_value_handle (newop2);
986             lookup_or_add (value_table, newexpr);
987             expr = newexpr;
988             phi_trans_add (oldexpr, newexpr, pred);         
989           }
990       }
991       break;
992       /* XXX: Until we have PRE of loads working, none will be ANTIC.
993        */
994     case 'r':
995       return NULL;
996       break;
997     case '1':
998       {
999         tree oldop1 = TREE_OPERAND (expr, 0);
1000         tree newop1;
1001         tree newexpr;
1002
1003         newop1 = phi_translate (find_leader (set, oldop1),
1004                                 set, pred, phiblock);
1005         if (newop1 == NULL)
1006           return NULL;
1007         if (newop1 != oldop1)
1008           {
1009             newexpr = pool_alloc (unary_node_pool);
1010             memcpy (newexpr, expr, tree_size (expr));
1011             create_tree_ann (newexpr);   
1012             TREE_OPERAND (newexpr, 0) = get_value_handle (newop1);
1013             lookup_or_add (value_table, newexpr);
1014             expr = newexpr;
1015             phi_trans_add (oldexpr, newexpr, pred);
1016           }
1017       }
1018       break;
1019     case 'd':
1020       abort ();
1021     case 'x':
1022       {
1023         tree phi = NULL;
1024         int i;
1025         if (TREE_CODE (expr) != SSA_NAME)
1026           abort ();
1027         if (TREE_CODE (SSA_NAME_DEF_STMT (expr)) == PHI_NODE)
1028           phi = SSA_NAME_DEF_STMT (expr);
1029         else
1030           return expr;
1031         
1032         for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1033           if (PHI_ARG_EDGE (phi, i)->src == pred)
1034             {
1035               tree val;
1036               if (is_undefined_value (PHI_ARG_DEF (phi, i)))
1037                 return NULL;
1038               val = lookup_or_add (value_table, PHI_ARG_DEF (phi, i));
1039               return PHI_ARG_DEF (phi, i);
1040             }
1041       }
1042       break;
1043     }
1044   return expr;
1045 }
1046
1047 static void
1048 phi_translate_set (value_set_t dest, value_set_t set, basic_block pred,
1049                    basic_block phiblock)
1050 {
1051   value_set_node_t node;
1052   for (node = set->head;
1053        node;
1054        node = node->next)
1055     {
1056       tree translated;
1057       translated = phi_translate (node->expr, set, pred, phiblock);
1058       phi_trans_add (node->expr, translated, pred);
1059       
1060       if (translated != NULL)
1061         value_insert_into_set (dest, translated);
1062     } 
1063 }
1064
1065 /* Find the leader for a value (IE the name representing that
1066    value) in a given set, and return it.  Return NULL if no leader is
1067    found.  */
1068
1069 static tree
1070 find_leader (value_set_t set, tree val)
1071 {
1072   value_set_node_t node;
1073
1074   if (val == NULL)
1075     return NULL;
1076   /* True constants represent themselves.  */
1077   if (TREE_CODE_CLASS (TREE_CODE (val)) == 'c')
1078     return val;
1079   /* Invariants are still represented by values, since they may be
1080      more than a single _CST node.  */  
1081   if (TREE_CONSTANT (val))
1082     return TREE_CHAIN (val);
1083
1084   if (set->length == 0)
1085     return NULL;
1086   
1087   if (value_exists_in_set_bitmap (set, val))
1088     {
1089       for (node = set->head;
1090            node;
1091            node = node->next)
1092         {
1093           if (get_value_handle (node->expr) == val)
1094             return node->expr;
1095         }
1096     }
1097   return NULL;
1098 }
1099
1100 /* Determine if the expression EXPR is valid in SET.  This means that
1101    we have a leader for each part of the expression (if it consists of
1102    values), or the expression is an SSA_NAME.  
1103
1104    NB:  We never should run into a case where we have SSA_NAME +
1105    SSA_NAME or SSA_NAME + value.  The sets valid_in_set is called on,
1106    the ANTIC sets, will only ever have SSA_NAME's or binary value
1107    expression (IE VALUE1 + VALUE2)  */
1108
1109 static bool
1110 valid_in_set (value_set_t set, tree expr)
1111 {
1112   switch (TREE_CODE_CLASS (TREE_CODE (expr)))
1113     {
1114     case '2':
1115       {
1116         tree op1 = TREE_OPERAND (expr, 0);
1117         tree op2 = TREE_OPERAND (expr, 1);
1118         return set_contains_value (set, op1) && set_contains_value (set, op2);
1119       }
1120       break;
1121     case '1':
1122       {
1123         tree op1 = TREE_OPERAND (expr, 0);
1124         return set_contains_value (set, op1);
1125       }
1126       break;
1127       /* XXX: Until PRE of loads works, no reference nodes are ANTIC.
1128        */
1129     case 'r':
1130       {
1131         return false;
1132       }
1133     case 'x':
1134       {
1135         if (TREE_CODE (expr) == SSA_NAME)
1136           return true;
1137         abort ();
1138       }
1139     case 'c':
1140       abort ();
1141     }
1142   return false;
1143 }
1144
1145 /* Clean the set of expressions that are no longer valid in SET.  This
1146    means expressions that are made up of values we have no leaders for
1147    in SET.  */
1148
1149 static void
1150 clean (value_set_t set)
1151 {
1152   value_set_node_t node;
1153   value_set_node_t next;
1154   node = set->head;
1155   while (node)
1156     {
1157       next = node->next;
1158       if (!valid_in_set (set, node->expr))      
1159         set_remove (set, node->expr);
1160       node = next;
1161     }
1162 }
1163
1164 /* Compute the ANTIC set for BLOCK.
1165
1166 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK), if
1167 succs(BLOCK) > 1
1168 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)]) if
1169 succs(BLOCK) == 1
1170
1171 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] -
1172 TMP_GEN[BLOCK])
1173
1174 Iterate until fixpointed.
1175
1176 XXX: It would be nice to either write a set_clear, and use it for
1177 antic_out, or to mark the antic_out set as deleted at the end
1178 of this routine, so that the pool can hand the same memory back out
1179 again for the next antic_out.  */
1180
1181
1182 static bool
1183 compute_antic_aux (basic_block block)
1184 {
1185   basic_block son;
1186   edge e;
1187   bool changed = false;
1188   value_set_t S, old, ANTIC_OUT;
1189   value_set_node_t node;
1190   
1191   ANTIC_OUT = S = NULL;
1192   /* If any edges from predecessors are abnormal, antic_in is empty, so
1193      punt.  Remember that the block has an incoming abnormal edge by
1194      setting the BB_VISITED flag.  */
1195   if (! (block->flags & BB_VISITED))
1196     {
1197       for (e = block->pred; e; e = e->pred_next)
1198         if (e->flags & EDGE_ABNORMAL)
1199           {
1200             block->flags |= BB_VISITED;
1201             break;
1202           }
1203     }
1204   if (block->flags & BB_VISITED)
1205     {
1206       S = NULL;
1207       goto visit_sons;
1208     }
1209   
1210
1211   old = set_new (false);
1212   set_copy (old, ANTIC_IN (block));
1213   ANTIC_OUT = set_new (true);
1214
1215   /* If the block has no successors, ANTIC_OUT is empty, because it is
1216      the exit block.  */
1217   if (block->succ == NULL);
1218
1219   /* If we have one successor, we could have some phi nodes to
1220      translate through.  */
1221   else if (block->succ->succ_next == NULL)
1222     {
1223       phi_translate_set (ANTIC_OUT, ANTIC_IN(block->succ->dest),
1224                          block, block->succ->dest);
1225     }
1226   /* If we have multiple successors, we take the intersection of all of
1227      them.  */
1228   else
1229     {
1230       varray_type worklist;
1231       edge e;
1232       size_t i;
1233       basic_block bprime, first;
1234
1235       VARRAY_BB_INIT (worklist, 1, "succ");
1236       e = block->succ;
1237       while (e)
1238         {
1239           VARRAY_PUSH_BB (worklist, e->dest);
1240           e = e->succ_next;
1241         }
1242       first = VARRAY_BB (worklist, 0);
1243       set_copy (ANTIC_OUT, ANTIC_IN (first));
1244
1245       for (i = 1; i < VARRAY_ACTIVE_SIZE (worklist); i++)
1246         {
1247           bprime = VARRAY_BB (worklist, i);
1248           node = ANTIC_OUT->head;
1249           while (node)
1250             {
1251               tree val;
1252               value_set_node_t next = node->next;
1253               val = get_value_handle (node->expr);
1254               if (!set_contains_value (ANTIC_IN (bprime), val))
1255                 set_remove (ANTIC_OUT, node->expr);
1256               node = next;
1257             }
1258         }
1259       VARRAY_CLEAR (worklist);
1260     }
1261
1262   /* Generate ANTIC_OUT - TMP_GEN */
1263   S = set_subtract (ANTIC_OUT, TMP_GEN (block), false);
1264
1265   /* Start ANTIC_IN with EXP_GEN - TMP_GEN */
1266   ANTIC_IN (block) = set_subtract (EXP_GEN (block),TMP_GEN (block), true);
1267   
1268   /* Then union in the ANTIC_OUT - TMP_GEN values, to get ANTIC_OUT U
1269      EXP_GEN - TMP_GEN */
1270   for (node = S->head;
1271        node;
1272        node = node->next)
1273     {
1274       value_insert_into_set (ANTIC_IN (block), node->expr);
1275     }
1276   clean (ANTIC_IN (block));
1277   
1278
1279   if (!set_equal (old, ANTIC_IN (block)))
1280     changed = true;
1281
1282  visit_sons:
1283   if (dump_file && (dump_flags & TDF_DETAILS))
1284     {
1285       if (ANTIC_OUT)
1286         print_value_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
1287       print_value_set (dump_file, ANTIC_IN (block), "ANTIC_IN", block->index);
1288       if (S)
1289         print_value_set (dump_file, S, "S", block->index);
1290
1291     }
1292
1293   for (son = first_dom_son (CDI_POST_DOMINATORS, block);
1294        son;
1295        son = next_dom_son (CDI_POST_DOMINATORS, son))
1296     {
1297       changed |= compute_antic_aux (son);
1298     }
1299   return changed;
1300 }
1301
1302 /* Compute ANTIC sets.  */
1303
1304 static void
1305 compute_antic (void)
1306 {
1307   bool changed = true;
1308   basic_block bb;
1309   int num_iterations = 0;
1310   FOR_ALL_BB (bb)
1311     {
1312       ANTIC_IN (bb) = set_new (true);
1313       if (bb->flags & BB_VISITED)
1314         abort ();
1315     }
1316
1317   while (changed)
1318     {
1319       num_iterations++;
1320       changed = false;
1321       changed = compute_antic_aux (EXIT_BLOCK_PTR);
1322     }
1323   FOR_ALL_BB (bb)
1324     {
1325       bb->flags &= ~BB_VISITED;
1326     }
1327   if (num_iterations > 2 && dump_file && (dump_flags & TDF_STATS))
1328     fprintf (dump_file, "compute_antic required %d iterations\n", num_iterations);
1329 }
1330
1331 /* Get the expressions represented by value VAL.  */
1332
1333 static value_set_t
1334 get_expr_set (tree val)
1335 {
1336   var_ann_t va = var_ann (val);
1337   return va->expr_set;
1338 }
1339
1340
1341 /* Find a leader for an expression, or generate one using
1342    create_expression_by_pieces if it's ANTIC but
1343    complex.  
1344    BLOCK is the basic_block we are looking for leaders in.
1345    EXPR is the expression to find a leader or generate for. 
1346    STMTS is the statement list to put the inserted expressions on.
1347    Returns the SSA_NAME of the LHS of the generated expression or the
1348    leader.  */
1349
1350 static tree
1351 find_or_generate_expression (basic_block block, tree expr, tree stmts)
1352 {
1353   tree genop;
1354   genop = find_leader (AVAIL_OUT (block), expr);
1355   /* Depending on the order we process DOM branches in, the value
1356      may not have propagated to all the dom children yet during
1357      this iteration.  In this case, the value will always be in
1358      the NEW_SETS for us already, having been propogated from our
1359      dominator.  */
1360   if (genop == NULL)
1361     genop = find_leader (NEW_SETS (block), expr);
1362   /* If it's still NULL, see if it is a complex expression, and if
1363      so, generate it recursively, otherwise, abort, because it's
1364      not really .  */
1365   if (genop == NULL)
1366     {
1367       genop = get_expr_set (expr)->head->expr;
1368       if (TREE_CODE_CLASS (TREE_CODE (genop)) != '1'
1369           && TREE_CODE_CLASS (TREE_CODE (genop)) != '2')
1370         abort ();
1371       genop = create_expression_by_pieces (block, genop, stmts);
1372     }
1373   return genop;
1374 }
1375
1376   
1377 /* Create an expression in pieces, so that we can handle very complex
1378    expressions that may be ANTIC, but not necessary GIMPLE.  
1379    BLOCK is the basic block the expression will be inserted into,
1380    EXPR is the expression to insert (in value form)
1381    STMTS is a statement list to append the necessary insertions into.
1382
1383    This function will abort if we hit some value that shouldn't be
1384    ANTIC but is (IE there is no leader for it, or its components).
1385    This function may also generate expressions that are themselves
1386    partially or fully redundant.  Those that are will be either made
1387    fully redundant during the next iteration of insert (for partially
1388    redundant ones), or eliminated by eliminate (for fully redundant
1389    ones).  */
1390
1391 static tree
1392 create_expression_by_pieces (basic_block block, tree expr, tree stmts)
1393 {
1394   tree name = NULL_TREE;
1395   tree newexpr = NULL_TREE;
1396   tree v;
1397   
1398   switch (TREE_CODE_CLASS (TREE_CODE (expr)))
1399     {
1400     case '2':
1401       {
1402         tree_stmt_iterator tsi;
1403         tree genop1, genop2;
1404         tree temp;
1405         tree op1 = TREE_OPERAND (expr, 0);
1406         tree op2 = TREE_OPERAND (expr, 1);
1407         genop1 = find_or_generate_expression (block, op1, stmts);
1408         genop2 = find_or_generate_expression (block, op2, stmts);
1409         temp = create_tmp_var (TREE_TYPE (expr), "pretmp");
1410         add_referenced_tmp_var (temp);
1411         newexpr = build (TREE_CODE (expr), TREE_TYPE (expr), 
1412                          genop1, genop2);
1413         newexpr = build (MODIFY_EXPR, TREE_TYPE (expr),
1414                          temp, newexpr);
1415         name = make_ssa_name (temp, newexpr);
1416         TREE_OPERAND (newexpr, 0) = name;
1417         tsi = tsi_last (stmts);
1418         tsi_link_after (&tsi, newexpr, TSI_CONTINUE_LINKING);
1419         pre_stats.insertions++;
1420         break;
1421       }
1422     case '1':
1423       {
1424         tree_stmt_iterator tsi;
1425         tree genop1;
1426         tree temp;
1427         tree op1 = TREE_OPERAND (expr, 0);
1428         genop1 = find_or_generate_expression (block, op1, stmts);
1429         temp = create_tmp_var (TREE_TYPE (expr), "pretmp");
1430         add_referenced_tmp_var (temp);
1431         newexpr = build (TREE_CODE (expr), TREE_TYPE (expr), 
1432                          genop1);
1433         newexpr = build (MODIFY_EXPR, TREE_TYPE (expr),
1434                          temp, newexpr);
1435         name = make_ssa_name (temp, newexpr);
1436         TREE_OPERAND (newexpr, 0) = name;
1437         tsi = tsi_last (stmts);
1438         tsi_link_after (&tsi, newexpr, TSI_CONTINUE_LINKING);
1439         pre_stats.insertions++;
1440
1441         break;
1442       }
1443     default:
1444       abort ();
1445       
1446     }
1447   v = get_value_handle (expr);
1448   add (value_table, name, v);
1449   insert_into_set (NEW_SETS (block), name);
1450   value_insert_into_set (AVAIL_OUT (block), name);
1451   if (dump_file && (dump_flags & TDF_DETAILS))
1452     {                               
1453       fprintf (dump_file, "Inserted ");
1454       print_generic_expr (dump_file, newexpr, 0);
1455       fprintf (dump_file, " in predecessor %d\n", block->index);
1456     }
1457   return name;
1458 }
1459       
1460 /* Perform insertion of partially redundant values.
1461    For BLOCK, do the following:
1462    1.  Propagate the NEW_SETS of the dominator into the current block.
1463    If the block has multiple predecessors, 
1464        2a. Iterate over the ANTIC expressions for the block to see if
1465            any of them are partially redundant.
1466        2b. If so, insert them into the necessary predecessors to make
1467            the expression fully redundant.
1468        2c. Insert a new PHI merging the values of the predecessors.
1469        2d. Insert the new PHI, and the new expressions, into the
1470            NEW_SETS set.  
1471    3. Recursively call ourselves on the dominator children of BLOCK.
1472
1473 */
1474 static bool
1475 insert_aux (basic_block block)
1476 {
1477   basic_block son;
1478   bool new_stuff = false;
1479
1480   if (block)
1481     {
1482       value_set_node_t e;
1483       basic_block dom;
1484       dom = get_immediate_dominator (CDI_DOMINATORS, block);
1485       if (dom)
1486         {
1487           e = NEW_SETS (dom)->head;
1488           while (e)
1489             {
1490               insert_into_set (NEW_SETS (block), e->expr);
1491               value_replace_in_set (AVAIL_OUT (block), e->expr);
1492               e = e->next;
1493             }
1494           if (block->pred->pred_next)
1495             {
1496               value_set_node_t node;
1497               for (node = ANTIC_IN (block)->head;
1498                    node;
1499                    node = node->next)
1500                 {
1501                   if (TREE_CODE_CLASS (TREE_CODE (node->expr)) == '2'
1502                       || TREE_CODE_CLASS (TREE_CODE (node->expr)) == '1')
1503                     {
1504                       tree *avail;
1505                       tree val;
1506                       bool by_some = false;
1507                       bool cant_insert = false;
1508                       bool all_same = true;
1509                       tree first_s = NULL;
1510                       edge pred;
1511                       basic_block bprime;
1512                       tree eprime;
1513
1514                       val = get_value_handle (node->expr);
1515                       if (set_contains_value (PHI_GEN (block), val))
1516                         continue; 
1517                       if (set_contains_value (AVAIL_OUT (dom), val))
1518                         {
1519                           if (dump_file && (dump_flags & TDF_DETAILS))
1520                             fprintf (dump_file, "Found fully redundant value\n");
1521                           continue;
1522                         }
1523                                     
1524                       avail = xcalloc (last_basic_block, sizeof (tree));
1525                       for (pred = block->pred;
1526                            pred;
1527                            pred = pred->pred_next)
1528                         {
1529                           tree vprime;
1530                           tree edoubleprime;
1531                           bprime = pred->src;
1532                           eprime = phi_translate (node->expr,
1533                                                   ANTIC_IN (block),
1534                                                   bprime, block);
1535
1536                           /* eprime will generally only be NULL if the
1537                              value of the expression, translated
1538                              through the PHI for this predecessor, is
1539                              undefined.  If that is the case, we can't
1540                              make the expression fully redundant,
1541                              because its value is undefined along a
1542                              predecessor path.  We can thus break out
1543                              early because it doesn't matter what the
1544                              rest of the results are.  */
1545                           if (eprime == NULL)
1546                             {
1547                               cant_insert = true;
1548                               break;
1549                             }
1550
1551                           vprime = get_value_handle (eprime);
1552                           if (!vprime)
1553                             abort ();                     
1554                           edoubleprime = find_leader (AVAIL_OUT (bprime),
1555                                                       vprime);
1556                           if (edoubleprime == NULL)
1557                             {
1558                               avail[bprime->index] = eprime;
1559                               all_same = false;
1560                             }
1561                           else
1562                             {
1563                               avail[bprime->index] = edoubleprime;
1564                               by_some = true; 
1565                               if (first_s == NULL)
1566                                 first_s = edoubleprime;
1567                               else if (first_s != edoubleprime)
1568                                 all_same = false;
1569                               if (first_s != edoubleprime 
1570                                   && operand_equal_p (first_s, edoubleprime, 0))
1571                                 abort ();
1572                             }
1573                         }
1574                       /* If we can insert it, it's not the same value
1575                          already existing along every predecessor, and
1576                          it's defined by some predecessor, it is
1577                          partially redundant.  */
1578                       if (!cant_insert && !all_same && by_some)
1579                         {
1580                           tree type = TREE_TYPE (avail[block->pred->src->index]);
1581                           tree temp;
1582                           if (dump_file && (dump_flags & TDF_DETAILS))
1583                             {
1584                               fprintf (dump_file, "Found partial redundancy for expression ");
1585                               print_generic_expr (dump_file, node->expr, 0);
1586                               fprintf (dump_file, "\n");
1587                             }
1588
1589                           /* Make the necessary insertions. */
1590                           for (pred = block->pred;
1591                                pred;
1592                                pred = pred->pred_next)
1593                             {
1594                               tree stmts = alloc_stmt_list ();
1595                               tree builtexpr;
1596                               bprime = pred->src;
1597                               eprime = avail[bprime->index];
1598                               if (TREE_CODE_CLASS (TREE_CODE (eprime)) == '2'
1599                                   || TREE_CODE_CLASS (TREE_CODE (eprime)) == '1')
1600                                 {
1601                                   builtexpr = create_expression_by_pieces (bprime,
1602                                                                            eprime,
1603                                                                            stmts);
1604                                   bsi_insert_on_edge (pred, stmts);
1605                                   bsi_commit_edge_inserts (NULL);
1606                                   avail[bprime->index] = builtexpr;
1607                                 }                             
1608                             } 
1609                           /* Now build a phi for the new variable.  */
1610                           temp = create_tmp_var (type, "prephitmp");
1611                           add_referenced_tmp_var (temp);
1612                           temp = create_phi_node (temp, block);
1613                           add (value_table, PHI_RESULT (temp), val);
1614
1615 #if 0
1616                           if (!set_contains_value (AVAIL_OUT (block), val))
1617                             insert_into_set (AVAIL_OUT (block), 
1618                                              PHI_RESULT (temp));
1619                           else
1620 #endif
1621                             value_replace_in_set (AVAIL_OUT (block), 
1622                                                  PHI_RESULT (temp));
1623                           for (pred = block->pred;
1624                                pred;
1625                                pred = pred->pred_next)
1626                             {
1627                               add_phi_arg (&temp, avail[pred->src->index],
1628                                            pred);
1629                             }
1630                           if (dump_file && (dump_flags & TDF_DETAILS))
1631                             {
1632                               fprintf (dump_file, "Created phi ");
1633                               print_generic_expr (dump_file, temp, 0);
1634                               fprintf (dump_file, " in block %d\n", block->index);
1635                             }
1636                           pre_stats.phis++;
1637                           new_stuff = true;
1638                           insert_into_set (NEW_SETS (block),
1639                                            PHI_RESULT (temp));
1640                           insert_into_set (PHI_GEN (block),
1641                                            PHI_RESULT (temp));
1642                         }
1643
1644                       free (avail);
1645                     }
1646                 }
1647             }
1648         }
1649     }
1650   for (son = first_dom_son (CDI_DOMINATORS, block);
1651        son;
1652        son = next_dom_son (CDI_DOMINATORS, son))
1653     {
1654       new_stuff |= insert_aux (son);
1655     }
1656
1657   return new_stuff;
1658 }
1659
1660 /* Perform insertion of partially redundant values.  */
1661
1662 static void
1663 insert (void)
1664 {
1665   bool new_stuff = true;
1666   basic_block bb;
1667   int num_iterations = 0;
1668
1669   FOR_ALL_BB (bb)
1670     NEW_SETS (bb) = set_new (true);
1671   
1672   while (new_stuff)
1673     {
1674       num_iterations++;
1675       new_stuff = false;
1676       new_stuff = insert_aux (ENTRY_BLOCK_PTR);
1677     }
1678   if (num_iterations > 2 && dump_file && (dump_flags & TDF_STATS))
1679     fprintf (dump_file, "insert required %d iterations\n", num_iterations);
1680 }
1681
1682 /* Return true if EXPR has no defining statement in this procedure,
1683    *AND* isn't a live-on-entry parameter.  */
1684 static bool
1685 is_undefined_value (tree expr)
1686 {  
1687   
1688 #ifdef ENABLE_CHECKING
1689   /* We should never be handed DECL's  */
1690   if (DECL_P (expr))
1691     abort ();
1692 #endif
1693   if (TREE_CODE (expr) == SSA_NAME)
1694     {
1695       /* XXX: Is this the correct test?  */
1696       if (TREE_CODE (SSA_NAME_VAR (expr)) == PARM_DECL)
1697         return false;
1698       if (IS_EMPTY_STMT (SSA_NAME_DEF_STMT (expr)))
1699         return true;
1700     }
1701   return false;
1702 }
1703
1704 /* Compute the AVAIL set for BLOCK.
1705    This function performs value numbering of the statements in BLOCK. 
1706    The AVAIL sets are built from information we glean while doing this
1707    value numbering, since the AVAIL sets contain only entry per
1708    value.
1709
1710    
1711    AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
1712    AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U
1713    TMP_GEN[BLOCK].
1714 */
1715
1716 static void
1717 compute_avail (basic_block block)
1718 {
1719   basic_block son;
1720   
1721   /* For arguments with default definitions, we pretend they are
1722      defined in the entry block.  */
1723   if (block == ENTRY_BLOCK_PTR)
1724     {
1725       tree param;
1726       for (param = DECL_ARGUMENTS (current_function_decl);
1727            param;
1728            param = TREE_CHAIN (param))
1729         {
1730           if (default_def (param) != NULL)
1731             {
1732               tree val;
1733               tree def = default_def (param);
1734               val = lookup_or_add (value_table, def);
1735               insert_into_set (TMP_GEN (block), def);
1736               value_insert_into_set (AVAIL_OUT (block), def);
1737             }
1738         }
1739     }
1740   else if (block)
1741     {
1742       block_stmt_iterator bsi;
1743       tree stmt, phi;
1744       basic_block dom;
1745
1746       dom = get_immediate_dominator (CDI_DOMINATORS, block);
1747       if (dom)
1748         set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
1749       for (phi = phi_nodes (block); phi; phi = PHI_CHAIN (phi))
1750         {
1751           /* Ignore virtual PHIs until we can do PRE on expressions
1752              with virtual operands.  */
1753           if (!is_gimple_reg (SSA_NAME_VAR (PHI_RESULT (phi))))
1754             continue;
1755
1756           lookup_or_add (value_table, PHI_RESULT (phi));
1757           value_insert_into_set (AVAIL_OUT (block), PHI_RESULT (phi));
1758           insert_into_set (PHI_GEN (block), PHI_RESULT (phi));
1759         }
1760
1761       for (bsi = bsi_start (block); !bsi_end_p (bsi); bsi_next (&bsi))
1762         {
1763           tree op0, op1;
1764           stmt = bsi_stmt (bsi);
1765           get_stmt_operands (stmt);
1766           
1767           if (NUM_VUSES (STMT_VUSE_OPS (stmt))
1768               || NUM_V_MUST_DEFS (STMT_V_MUST_DEF_OPS (stmt))
1769               || NUM_V_MAY_DEFS (STMT_V_MAY_DEF_OPS (stmt))
1770               || stmt_ann (stmt)->has_volatile_ops)
1771             {
1772               size_t j;
1773               for (j = 0; j < NUM_DEFS (STMT_DEF_OPS (stmt)); j++)
1774                 {
1775                   tree def = DEF_OP (STMT_DEF_OPS (stmt), j);
1776                   lookup_or_add (value_table, def);
1777                   insert_into_set (TMP_GEN (block), def);
1778                   value_insert_into_set (AVAIL_OUT (block), def);
1779                 }
1780               for (j = 0; j < NUM_USES (STMT_USE_OPS (stmt)); j++)
1781                 {
1782                   tree use = USE_OP (STMT_USE_OPS (stmt), j);
1783                   if (TREE_CODE (use) == SSA_NAME)
1784                     {
1785                       lookup_or_add (value_table, use);
1786                       insert_into_set (TMP_GEN (block), use);
1787                       value_insert_into_set (AVAIL_OUT (block), use);
1788                     }
1789                 }
1790               continue;
1791             }
1792
1793           if (TREE_CODE (stmt) == MODIFY_EXPR)
1794             {
1795               op0 = TREE_OPERAND (stmt, 0);
1796               if (TREE_CODE (op0) != SSA_NAME)
1797                 continue;
1798               if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op0))
1799                 continue;
1800               op1 = TREE_OPERAND (stmt, 1);
1801               STRIP_USELESS_TYPE_CONVERSION (op1);
1802               if (is_gimple_min_invariant (op1))
1803                 {
1804                   add (value_table, op0, lookup_or_add (value_table, op1));
1805                   insert_into_set (TMP_GEN (block), op0);
1806                   value_insert_into_set (AVAIL_OUT (block), op0);
1807                 }
1808               else if (TREE_CODE_CLASS (TREE_CODE (op1)) == '2')
1809                 {
1810                   tree bop1, bop2;
1811                   tree val, val1, val2;
1812                   tree newt;
1813                   bop1 = TREE_OPERAND (op1, 0);
1814                   bop2 = TREE_OPERAND (op1, 1);
1815                   val1 = lookup_or_add (value_table, bop1);
1816                   val2 = lookup_or_add (value_table, bop2);
1817  
1818                   newt = pool_alloc (binary_node_pool);
1819                   memcpy (newt, op1, tree_size (op1));
1820                   TREE_OPERAND (newt, 0) = val1;
1821                   TREE_OPERAND (newt, 1) = val2;
1822                   val = lookup_or_add (value_table, newt);
1823                   add (value_table, op0, val);
1824                   if (!is_undefined_value (bop1))
1825                     value_insert_into_set (EXP_GEN (block), bop1);
1826                   if (!is_undefined_value (bop2))
1827                     value_insert_into_set (EXP_GEN (block), bop2);
1828                   value_insert_into_set (EXP_GEN (block), newt);
1829                   insert_into_set (TMP_GEN (block), op0);
1830                   value_insert_into_set (AVAIL_OUT (block), op0);  
1831                 }
1832               else if (TREE_CODE_CLASS (TREE_CODE (op1)) == '1'
1833                        && !is_gimple_cast (op1))
1834                 {
1835                   tree uop;
1836                   tree val, val1;
1837                   tree newt;
1838                   uop = TREE_OPERAND (op1, 0);
1839                   val1 = lookup_or_add (value_table, uop);
1840                   newt = pool_alloc (unary_node_pool);
1841                   memcpy (newt, op1, tree_size (op1));
1842                   TREE_OPERAND (newt, 0) = val1;
1843                   val = lookup_or_add (value_table, newt);
1844                   add (value_table, op0, val);
1845                   if (!is_undefined_value (uop))
1846                     value_insert_into_set (EXP_GEN (block), uop);
1847                   value_insert_into_set (EXP_GEN (block), newt);
1848                   insert_into_set (TMP_GEN (block), op0);
1849                   value_insert_into_set (AVAIL_OUT (block), op0);
1850                 }
1851               else if (TREE_CODE (op1) == SSA_NAME)
1852                 {
1853                   tree val = lookup_or_add (value_table, op1);
1854                   add (value_table, op0, val);
1855                   if (!is_undefined_value (op1))
1856                     value_insert_into_set (EXP_GEN (block), op1);
1857                   insert_into_set (TMP_GEN (block), op0);
1858                   value_insert_into_set (AVAIL_OUT (block), op0);
1859                 }
1860               else
1861                 {
1862                   size_t j;
1863                   for (j = 0; j < NUM_DEFS (STMT_DEF_OPS (stmt)); j++)
1864                     {
1865                       tree def = DEF_OP (STMT_DEF_OPS (stmt), j);
1866                       lookup_or_add (value_table, def);
1867                       insert_into_set (TMP_GEN (block), def);
1868                       value_insert_into_set (AVAIL_OUT (block), def);
1869                       if (def != op0)
1870                         abort ();
1871                     }
1872                   for (j = 0; j < NUM_USES (STMT_USE_OPS (stmt)); j++)
1873                     {
1874                       tree use = USE_OP (STMT_USE_OPS (stmt), j);
1875                       if (TREE_CODE (use) == SSA_NAME)
1876                         {
1877                           lookup_or_add (value_table, use);
1878                           insert_into_set (TMP_GEN (block), use);
1879                           value_insert_into_set (AVAIL_OUT (block), use);
1880                         }
1881                     }
1882                 }
1883             }
1884           else
1885             {
1886               size_t j;
1887               for (j = 0; j < NUM_DEFS (STMT_DEF_OPS (stmt)); j++)
1888                 {
1889                   tree def = DEF_OP (STMT_DEF_OPS (stmt), j);
1890                   lookup_or_add (value_table, def);
1891                   insert_into_set (TMP_GEN (block), def);
1892                   value_insert_into_set (AVAIL_OUT (block), def);
1893                 }
1894               for (j = 0; j < NUM_USES (STMT_USE_OPS (stmt)); j++)
1895                 {
1896                   tree use = USE_OP (STMT_USE_OPS (stmt), j);
1897                   if (TREE_CODE (use) == SSA_NAME)
1898                     {
1899                       lookup_or_add (value_table, use);
1900                       insert_into_set (TMP_GEN (block), use);
1901                       value_insert_into_set (AVAIL_OUT (block), use);
1902                     }
1903                 }
1904             }
1905         }
1906     }
1907   for (son = first_dom_son (CDI_DOMINATORS, block);
1908        son;
1909        son = next_dom_son (CDI_DOMINATORS, son))
1910     compute_avail (son);
1911
1912 }
1913
1914 /* Eliminate fully redundant computations.  */
1915
1916 static void
1917 eliminate (void)
1918 {
1919   basic_block b;
1920
1921   FOR_EACH_BB (b)
1922     {
1923       block_stmt_iterator i;
1924       
1925       for (i = bsi_start (b); !bsi_end_p (i); bsi_next (&i))
1926         {
1927           tree stmt = bsi_stmt (i);
1928
1929           if (NUM_VUSES (STMT_VUSE_OPS (stmt))
1930               || NUM_V_MUST_DEFS (STMT_V_MUST_DEF_OPS (stmt))
1931               || NUM_V_MAY_DEFS (STMT_V_MAY_DEF_OPS (stmt))
1932               || stmt_ann (stmt)->has_volatile_ops)
1933             continue;
1934           /* Lookup the RHS of the expression, see if we have an
1935              available computation for it. If so, replace the RHS with
1936              the available computation.  */
1937           if (TREE_CODE (stmt) == MODIFY_EXPR)
1938             {
1939               tree t = TREE_OPERAND (stmt, 0);
1940               tree expr = TREE_OPERAND (stmt, 1);
1941               tree sprime;
1942               /* There is no point in eliminating NOP_EXPR, it isn't
1943                  supposed to generate any code.  */
1944               if (TREE_CODE (expr) == NOP_EXPR
1945                   || (TREE_CODE_CLASS (TREE_CODE (expr)) != '2' 
1946                    && TREE_CODE_CLASS (TREE_CODE (expr)) != '1'))
1947                 continue;
1948               sprime = find_leader (AVAIL_OUT (b),
1949                                     lookup (value_table, t));
1950               if (sprime 
1951                   && sprime != t 
1952                   && may_propagate_copy (sprime, TREE_OPERAND (stmt, 1)))
1953                 {
1954                   if (dump_file && (dump_flags & TDF_DETAILS))
1955                     {
1956                       fprintf (dump_file, "Replaced ");
1957                       print_generic_expr (dump_file, expr, 0);
1958                       fprintf (dump_file, " with ");
1959                       print_generic_expr (dump_file, sprime, 0);
1960                       fprintf (dump_file, " in ");
1961                       print_generic_stmt (dump_file, stmt, 0);
1962                     }
1963                   pre_stats.eliminations++;
1964                   propagate_tree_value (&TREE_OPERAND (stmt, 1), sprime);
1965                   modify_stmt (stmt);
1966                 }
1967             }
1968
1969         }
1970     }
1971 }
1972
1973 /* Main entry point to the SSA-PRE pass.
1974
1975    PHASE indicates which dump file from the DUMP_FILES array to use when
1976    dumping debugging information.  */
1977
1978 static void
1979 execute_pre (void)
1980 {
1981   size_t tsize;
1982   basic_block bb;
1983   pre_uid = num_referenced_vars;
1984   memset (&pre_stats, 0, sizeof (pre_stats));
1985   FOR_ALL_BB (bb)
1986     {
1987       bb->aux = xcalloc (1, sizeof (struct bb_value_sets));
1988     }
1989   phi_translate_table = htab_create (511, expr_pred_trans_hash,
1990                                      expr_pred_trans_eq,
1991                                      free);
1992   value_table = htab_create (511, val_expr_pair_hash,
1993                              val_expr_pair_expr_eq, free);
1994   value_set_pool = create_alloc_pool ("Value sets",
1995                                       sizeof (struct value_set), 30);
1996   value_set_node_pool = create_alloc_pool ("Value set nodes",
1997                                        sizeof (struct value_set_node), 30);
1998   calculate_dominance_info (CDI_POST_DOMINATORS);
1999   calculate_dominance_info (CDI_DOMINATORS);
2000   tsize = tree_size (build (PLUS_EXPR, void_type_node, NULL_TREE,
2001                             NULL_TREE));
2002   binary_node_pool = create_alloc_pool ("Binary tree nodes", tsize, 30);
2003   tsize = tree_size (build1 (NEGATE_EXPR, void_type_node, NULL_TREE));
2004   unary_node_pool = create_alloc_pool ("Unary tree nodes", tsize, 30);
2005
2006   FOR_ALL_BB (bb)
2007     {
2008       EXP_GEN (bb) = set_new (true);
2009       PHI_GEN (bb) = set_new (true);
2010       TMP_GEN (bb) = set_new (false);
2011       AVAIL_OUT (bb) = set_new (true);
2012     }
2013
2014   compute_avail (ENTRY_BLOCK_PTR);
2015
2016   if (dump_file && (dump_flags & TDF_DETAILS))
2017     {
2018       FOR_ALL_BB (bb)
2019         {
2020           print_value_set (dump_file, EXP_GEN (bb), "exp_gen", bb->index);
2021           print_value_set (dump_file, TMP_GEN (bb), "tmp_gen", bb->index);
2022           print_value_set (dump_file, AVAIL_OUT (bb), "avail_out", bb->index);
2023         }
2024     }
2025
2026   /* Insert can get quite slow on an incredibly large number of basic
2027      blocks due to some quadratic behavior.  Until this behavior is
2028      fixed, don't run it when he have an incredibly large number of
2029      bb's.  If we aren't going to run insert, there is no point in
2030      computing ANTIC, either, even though it's plenty fast.  */
2031  
2032   if (n_basic_blocks < 4000)
2033     {
2034       compute_antic ();
2035       
2036       insert ();
2037     }
2038   eliminate ();
2039   
2040   if (dump_file && (dump_flags & TDF_STATS))
2041     {
2042       fprintf (dump_file, "Insertions:%d\n", pre_stats.insertions);
2043       fprintf (dump_file, "New PHIs:%d\n", pre_stats.phis);
2044       fprintf (dump_file, "Eliminated:%d\n", pre_stats.eliminations);
2045     }
2046
2047   free_alloc_pool (value_set_pool);
2048   free_alloc_pool (value_set_node_pool);
2049   free_alloc_pool (binary_node_pool);
2050   free_alloc_pool (unary_node_pool);
2051   htab_delete (value_table);
2052   htab_delete (phi_translate_table);
2053   
2054   FOR_ALL_BB (bb)
2055     {
2056       free (bb->aux);
2057       bb->aux = NULL;
2058     }
2059   free_dominance_info (CDI_POST_DOMINATORS);
2060 }
2061
2062 static bool
2063 gate_pre (void)
2064 {
2065   return flag_tree_pre != 0;
2066 }
2067
2068 struct tree_opt_pass pass_pre =
2069 {
2070   "pre",                                /* name */
2071   gate_pre,                             /* gate */
2072   execute_pre,                          /* execute */
2073   NULL,                                 /* sub */
2074   NULL,                                 /* next */
2075   0,                                    /* static_pass_number */
2076   TV_TREE_PRE,                          /* tv_id */
2077   PROP_no_crit_edges | PROP_cfg | PROP_ssa,/* properties_required */
2078   0,                                    /* properties_provided */
2079   0,                                    /* properties_destroyed */
2080   0,                                    /* todo_flags_start */
2081   TODO_dump_func | TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2082 };