OSDN Git Service

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