Import from savannah.gnu.org:
[official-gcc.git] / gcc / tree-ssa-pre.c
blobbd13476d31d9a276814e85e9218769d6062c1095
1 /* SSA-PRE for trees.
2 Copyright (C) 2001-2013 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <dan@dberlin.org> and Steven Bosscher
4 <stevenb@suse.de>
6 This file is part of GCC.
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 3, or (at your option)
11 any later version.
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.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "basic-block.h"
28 #include "gimple-pretty-print.h"
29 #include "tree-inline.h"
30 #include "tree-ssa.h"
31 #include "gimple.h"
32 #include "hash-table.h"
33 #include "tree-iterator.h"
34 #include "alloc-pool.h"
35 #include "obstack.h"
36 #include "tree-pass.h"
37 #include "flags.h"
38 #include "bitmap.h"
39 #include "langhooks.h"
40 #include "cfgloop.h"
41 #include "tree-ssa-sccvn.h"
42 #include "tree-scalar-evolution.h"
43 #include "params.h"
44 #include "dbgcnt.h"
45 #include "domwalk.h"
46 #include "ipa-prop.h"
48 /* TODO:
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. Strength reduction can be performed by anticipating expressions
54 we can repair later on.
55 3. We can do back-substitution or smarter value numbering to catch
56 commutative expressions split up over multiple statements.
59 /* For ease of terminology, "expression node" in the below refers to
60 every expression node but GIMPLE_ASSIGN, because GIMPLE_ASSIGNs
61 represent the actual statement containing the expressions we care about,
62 and we cache the value number by putting it in the expression. */
64 /* Basic algorithm
66 First we walk the statements to generate the AVAIL sets, the
67 EXP_GEN sets, and the tmp_gen sets. EXP_GEN sets represent the
68 generation of values/expressions by a given block. We use them
69 when computing the ANTIC sets. The AVAIL sets consist of
70 SSA_NAME's that represent values, so we know what values are
71 available in what blocks. AVAIL is a forward dataflow problem. In
72 SSA, values are never killed, so we don't need a kill set, or a
73 fixpoint iteration, in order to calculate the AVAIL sets. In
74 traditional parlance, AVAIL sets tell us the downsafety of the
75 expressions/values.
77 Next, we generate the ANTIC sets. These sets represent the
78 anticipatable expressions. ANTIC is a backwards dataflow
79 problem. An expression is anticipatable in a given block if it could
80 be generated in that block. This means that if we had to perform
81 an insertion in that block, of the value of that expression, we
82 could. Calculating the ANTIC sets requires phi translation of
83 expressions, because the flow goes backwards through phis. We must
84 iterate to a fixpoint of the ANTIC sets, because we have a kill
85 set. Even in SSA form, values are not live over the entire
86 function, only from their definition point onwards. So we have to
87 remove values from the ANTIC set once we go past the definition
88 point of the leaders that make them up.
89 compute_antic/compute_antic_aux performs this computation.
91 Third, we perform insertions to make partially redundant
92 expressions fully redundant.
94 An expression is partially redundant (excluding partial
95 anticipation) if:
97 1. It is AVAIL in some, but not all, of the predecessors of a
98 given block.
99 2. It is ANTIC in all the predecessors.
101 In order to make it fully redundant, we insert the expression into
102 the predecessors where it is not available, but is ANTIC.
104 For the partial anticipation case, we only perform insertion if it
105 is partially anticipated in some block, and fully available in all
106 of the predecessors.
108 insert/insert_aux/do_regular_insertion/do_partial_partial_insertion
109 performs these steps.
111 Fourth, we eliminate fully redundant expressions.
112 This is a simple statement walk that replaces redundant
113 calculations with the now available values. */
115 /* Representations of value numbers:
117 Value numbers are represented by a representative SSA_NAME. We
118 will create fake SSA_NAME's in situations where we need a
119 representative but do not have one (because it is a complex
120 expression). In order to facilitate storing the value numbers in
121 bitmaps, and keep the number of wasted SSA_NAME's down, we also
122 associate a value_id with each value number, and create full blown
123 ssa_name's only where we actually need them (IE in operands of
124 existing expressions).
126 Theoretically you could replace all the value_id's with
127 SSA_NAME_VERSION, but this would allocate a large number of
128 SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
129 It would also require an additional indirection at each point we
130 use the value id. */
132 /* Representation of expressions on value numbers:
134 Expressions consisting of value numbers are represented the same
135 way as our VN internally represents them, with an additional
136 "pre_expr" wrapping around them in order to facilitate storing all
137 of the expressions in the same sets. */
139 /* Representation of sets:
141 The dataflow sets do not need to be sorted in any particular order
142 for the majority of their lifetime, are simply represented as two
143 bitmaps, one that keeps track of values present in the set, and one
144 that keeps track of expressions present in the set.
146 When we need them in topological order, we produce it on demand by
147 transforming the bitmap into an array and sorting it into topo
148 order. */
150 /* Type of expression, used to know which member of the PRE_EXPR union
151 is valid. */
153 enum pre_expr_kind
155 NAME,
156 NARY,
157 REFERENCE,
158 CONSTANT
161 typedef union pre_expr_union_d
163 tree name;
164 tree constant;
165 vn_nary_op_t nary;
166 vn_reference_t reference;
167 } pre_expr_union;
169 typedef struct pre_expr_d : typed_noop_remove <pre_expr_d>
171 enum pre_expr_kind kind;
172 unsigned int id;
173 pre_expr_union u;
175 /* hash_table support. */
176 typedef pre_expr_d value_type;
177 typedef pre_expr_d compare_type;
178 static inline hashval_t hash (const pre_expr_d *);
179 static inline int equal (const pre_expr_d *, const pre_expr_d *);
180 } *pre_expr;
182 #define PRE_EXPR_NAME(e) (e)->u.name
183 #define PRE_EXPR_NARY(e) (e)->u.nary
184 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
185 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
187 /* Compare E1 and E1 for equality. */
189 inline int
190 pre_expr_d::equal (const value_type *e1, const compare_type *e2)
192 if (e1->kind != e2->kind)
193 return false;
195 switch (e1->kind)
197 case CONSTANT:
198 return vn_constant_eq_with_type (PRE_EXPR_CONSTANT (e1),
199 PRE_EXPR_CONSTANT (e2));
200 case NAME:
201 return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
202 case NARY:
203 return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
204 case REFERENCE:
205 return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
206 PRE_EXPR_REFERENCE (e2));
207 default:
208 gcc_unreachable ();
212 /* Hash E. */
214 inline hashval_t
215 pre_expr_d::hash (const value_type *e)
217 switch (e->kind)
219 case CONSTANT:
220 return vn_hash_constant_with_type (PRE_EXPR_CONSTANT (e));
221 case NAME:
222 return SSA_NAME_VERSION (PRE_EXPR_NAME (e));
223 case NARY:
224 return PRE_EXPR_NARY (e)->hashcode;
225 case REFERENCE:
226 return PRE_EXPR_REFERENCE (e)->hashcode;
227 default:
228 gcc_unreachable ();
232 /* Next global expression id number. */
233 static unsigned int next_expression_id;
235 /* Mapping from expression to id number we can use in bitmap sets. */
236 static vec<pre_expr> expressions;
237 static hash_table <pre_expr_d> expression_to_id;
238 static vec<unsigned> name_to_id;
240 /* Allocate an expression id for EXPR. */
242 static inline unsigned int
243 alloc_expression_id (pre_expr expr)
245 struct pre_expr_d **slot;
246 /* Make sure we won't overflow. */
247 gcc_assert (next_expression_id + 1 > next_expression_id);
248 expr->id = next_expression_id++;
249 expressions.safe_push (expr);
250 if (expr->kind == NAME)
252 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
253 /* vec::safe_grow_cleared allocates no headroom. Avoid frequent
254 re-allocations by using vec::reserve upfront. There is no
255 vec::quick_grow_cleared unfortunately. */
256 unsigned old_len = name_to_id.length ();
257 name_to_id.reserve (num_ssa_names - old_len);
258 name_to_id.safe_grow_cleared (num_ssa_names);
259 gcc_assert (name_to_id[version] == 0);
260 name_to_id[version] = expr->id;
262 else
264 slot = expression_to_id.find_slot (expr, INSERT);
265 gcc_assert (!*slot);
266 *slot = expr;
268 return next_expression_id - 1;
271 /* Return the expression id for tree EXPR. */
273 static inline unsigned int
274 get_expression_id (const pre_expr expr)
276 return expr->id;
279 static inline unsigned int
280 lookup_expression_id (const pre_expr expr)
282 struct pre_expr_d **slot;
284 if (expr->kind == NAME)
286 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
287 if (name_to_id.length () <= version)
288 return 0;
289 return name_to_id[version];
291 else
293 slot = expression_to_id.find_slot (expr, NO_INSERT);
294 if (!slot)
295 return 0;
296 return ((pre_expr)*slot)->id;
300 /* Return the existing expression id for EXPR, or create one if one
301 does not exist yet. */
303 static inline unsigned int
304 get_or_alloc_expression_id (pre_expr expr)
306 unsigned int id = lookup_expression_id (expr);
307 if (id == 0)
308 return alloc_expression_id (expr);
309 return expr->id = id;
312 /* Return the expression that has expression id ID */
314 static inline pre_expr
315 expression_for_id (unsigned int id)
317 return expressions[id];
320 /* Free the expression id field in all of our expressions,
321 and then destroy the expressions array. */
323 static void
324 clear_expression_ids (void)
326 expressions.release ();
329 static alloc_pool pre_expr_pool;
331 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it. */
333 static pre_expr
334 get_or_alloc_expr_for_name (tree name)
336 struct pre_expr_d expr;
337 pre_expr result;
338 unsigned int result_id;
340 expr.kind = NAME;
341 expr.id = 0;
342 PRE_EXPR_NAME (&expr) = name;
343 result_id = lookup_expression_id (&expr);
344 if (result_id != 0)
345 return expression_for_id (result_id);
347 result = (pre_expr) pool_alloc (pre_expr_pool);
348 result->kind = NAME;
349 PRE_EXPR_NAME (result) = name;
350 alloc_expression_id (result);
351 return result;
354 /* An unordered bitmap set. One bitmap tracks values, the other,
355 expressions. */
356 typedef struct bitmap_set
358 bitmap_head expressions;
359 bitmap_head values;
360 } *bitmap_set_t;
362 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi) \
363 EXECUTE_IF_SET_IN_BITMAP (&(set)->expressions, 0, (id), (bi))
365 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi) \
366 EXECUTE_IF_SET_IN_BITMAP (&(set)->values, 0, (id), (bi))
368 /* Mapping from value id to expressions with that value_id. */
369 static vec<bitmap> value_expressions;
371 /* Sets that we need to keep track of. */
372 typedef struct bb_bitmap_sets
374 /* The EXP_GEN set, which represents expressions/values generated in
375 a basic block. */
376 bitmap_set_t exp_gen;
378 /* The PHI_GEN set, which represents PHI results generated in a
379 basic block. */
380 bitmap_set_t phi_gen;
382 /* The TMP_GEN set, which represents results/temporaries generated
383 in a basic block. IE the LHS of an expression. */
384 bitmap_set_t tmp_gen;
386 /* The AVAIL_OUT set, which represents which values are available in
387 a given basic block. */
388 bitmap_set_t avail_out;
390 /* The ANTIC_IN set, which represents which values are anticipatable
391 in a given basic block. */
392 bitmap_set_t antic_in;
394 /* The PA_IN set, which represents which values are
395 partially anticipatable in a given basic block. */
396 bitmap_set_t pa_in;
398 /* The NEW_SETS set, which is used during insertion to augment the
399 AVAIL_OUT set of blocks with the new insertions performed during
400 the current iteration. */
401 bitmap_set_t new_sets;
403 /* A cache for value_dies_in_block_x. */
404 bitmap expr_dies;
406 /* True if we have visited this block during ANTIC calculation. */
407 unsigned int visited : 1;
409 /* True we have deferred processing this block during ANTIC
410 calculation until its successor is processed. */
411 unsigned int deferred : 1;
413 /* True when the block contains a call that might not return. */
414 unsigned int contains_may_not_return_call : 1;
415 } *bb_value_sets_t;
417 #define EXP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->exp_gen
418 #define PHI_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->phi_gen
419 #define TMP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->tmp_gen
420 #define AVAIL_OUT(BB) ((bb_value_sets_t) ((BB)->aux))->avail_out
421 #define ANTIC_IN(BB) ((bb_value_sets_t) ((BB)->aux))->antic_in
422 #define PA_IN(BB) ((bb_value_sets_t) ((BB)->aux))->pa_in
423 #define NEW_SETS(BB) ((bb_value_sets_t) ((BB)->aux))->new_sets
424 #define EXPR_DIES(BB) ((bb_value_sets_t) ((BB)->aux))->expr_dies
425 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
426 #define BB_DEFERRED(BB) ((bb_value_sets_t) ((BB)->aux))->deferred
427 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
430 /* Basic block list in postorder. */
431 static int *postorder;
432 static int postorder_num;
434 /* This structure is used to keep track of statistics on what
435 optimization PRE was able to perform. */
436 static struct
438 /* The number of RHS computations eliminated by PRE. */
439 int eliminations;
441 /* The number of new expressions/temporaries generated by PRE. */
442 int insertions;
444 /* The number of inserts found due to partial anticipation */
445 int pa_insert;
447 /* The number of new PHI nodes added by PRE. */
448 int phis;
449 } pre_stats;
451 static bool do_partial_partial;
452 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
453 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
454 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
455 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
456 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
457 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
458 static void bitmap_insert_into_set_1 (bitmap_set_t, pre_expr,
459 unsigned int, bool);
460 static bitmap_set_t bitmap_set_new (void);
461 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
462 tree);
463 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
464 static unsigned int get_expr_value_id (pre_expr);
466 /* We can add and remove elements and entries to and from sets
467 and hash tables, so we use alloc pools for them. */
469 static alloc_pool bitmap_set_pool;
470 static bitmap_obstack grand_bitmap_obstack;
472 /* Set of blocks with statements that have had their EH properties changed. */
473 static bitmap need_eh_cleanup;
475 /* Set of blocks with statements that have had their AB properties changed. */
476 static bitmap need_ab_cleanup;
478 /* A three tuple {e, pred, v} used to cache phi translations in the
479 phi_translate_table. */
481 typedef struct expr_pred_trans_d : typed_free_remove<expr_pred_trans_d>
483 /* The expression. */
484 pre_expr e;
486 /* The predecessor block along which we translated the expression. */
487 basic_block pred;
489 /* The value that resulted from the translation. */
490 pre_expr v;
492 /* The hashcode for the expression, pred pair. This is cached for
493 speed reasons. */
494 hashval_t hashcode;
496 /* hash_table support. */
497 typedef expr_pred_trans_d value_type;
498 typedef expr_pred_trans_d compare_type;
499 static inline hashval_t hash (const value_type *);
500 static inline int equal (const value_type *, const compare_type *);
501 } *expr_pred_trans_t;
502 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
504 inline hashval_t
505 expr_pred_trans_d::hash (const expr_pred_trans_d *e)
507 return e->hashcode;
510 inline int
511 expr_pred_trans_d::equal (const value_type *ve1,
512 const compare_type *ve2)
514 basic_block b1 = ve1->pred;
515 basic_block b2 = ve2->pred;
517 /* If they are not translations for the same basic block, they can't
518 be equal. */
519 if (b1 != b2)
520 return false;
521 return pre_expr_d::equal (ve1->e, ve2->e);
524 /* The phi_translate_table caches phi translations for a given
525 expression and predecessor. */
526 static hash_table <expr_pred_trans_d> phi_translate_table;
528 /* Add the tuple mapping from {expression E, basic block PRED} to
529 the phi translation table and return whether it pre-existed. */
531 static inline bool
532 phi_trans_add (expr_pred_trans_t *entry, pre_expr e, basic_block pred)
534 expr_pred_trans_t *slot;
535 expr_pred_trans_d tem;
536 hashval_t hash = iterative_hash_hashval_t (pre_expr_d::hash (e),
537 pred->index);
538 tem.e = e;
539 tem.pred = pred;
540 tem.hashcode = hash;
541 slot = phi_translate_table.find_slot_with_hash (&tem, hash, INSERT);
542 if (*slot)
544 *entry = *slot;
545 return true;
548 *entry = *slot = XNEW (struct expr_pred_trans_d);
549 (*entry)->e = e;
550 (*entry)->pred = pred;
551 (*entry)->hashcode = hash;
552 return false;
556 /* Add expression E to the expression set of value id V. */
558 static void
559 add_to_value (unsigned int v, pre_expr e)
561 bitmap set;
563 gcc_checking_assert (get_expr_value_id (e) == v);
565 if (v >= value_expressions.length ())
567 value_expressions.safe_grow_cleared (v + 1);
570 set = value_expressions[v];
571 if (!set)
573 set = BITMAP_ALLOC (&grand_bitmap_obstack);
574 value_expressions[v] = set;
577 bitmap_set_bit (set, get_or_alloc_expression_id (e));
580 /* Create a new bitmap set and return it. */
582 static bitmap_set_t
583 bitmap_set_new (void)
585 bitmap_set_t ret = (bitmap_set_t) pool_alloc (bitmap_set_pool);
586 bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
587 bitmap_initialize (&ret->values, &grand_bitmap_obstack);
588 return ret;
591 /* Return the value id for a PRE expression EXPR. */
593 static unsigned int
594 get_expr_value_id (pre_expr expr)
596 unsigned int id;
597 switch (expr->kind)
599 case CONSTANT:
600 id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
601 break;
602 case NAME:
603 id = VN_INFO (PRE_EXPR_NAME (expr))->value_id;
604 break;
605 case NARY:
606 id = PRE_EXPR_NARY (expr)->value_id;
607 break;
608 case REFERENCE:
609 id = PRE_EXPR_REFERENCE (expr)->value_id;
610 break;
611 default:
612 gcc_unreachable ();
614 /* ??? We cannot assert that expr has a value-id (it can be 0), because
615 we assign value-ids only to expressions that have a result
616 in set_hashtable_value_ids. */
617 return id;
620 /* Return a SCCVN valnum (SSA name or constant) for the PRE value-id VAL. */
622 static tree
623 sccvn_valnum_from_value_id (unsigned int val)
625 bitmap_iterator bi;
626 unsigned int i;
627 bitmap exprset = value_expressions[val];
628 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
630 pre_expr vexpr = expression_for_id (i);
631 if (vexpr->kind == NAME)
632 return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
633 else if (vexpr->kind == CONSTANT)
634 return PRE_EXPR_CONSTANT (vexpr);
636 return NULL_TREE;
639 /* Remove an expression EXPR from a bitmapped set. */
641 static void
642 bitmap_remove_from_set (bitmap_set_t set, pre_expr expr)
644 unsigned int val = get_expr_value_id (expr);
645 if (!value_id_constant_p (val))
647 bitmap_clear_bit (&set->values, val);
648 bitmap_clear_bit (&set->expressions, get_expression_id (expr));
652 static void
653 bitmap_insert_into_set_1 (bitmap_set_t set, pre_expr expr,
654 unsigned int val, bool allow_constants)
656 if (allow_constants || !value_id_constant_p (val))
658 /* We specifically expect this and only this function to be able to
659 insert constants into a set. */
660 bitmap_set_bit (&set->values, val);
661 bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
665 /* Insert an expression EXPR into a bitmapped set. */
667 static void
668 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
670 bitmap_insert_into_set_1 (set, expr, get_expr_value_id (expr), false);
673 /* Copy a bitmapped set ORIG, into bitmapped set DEST. */
675 static void
676 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
678 bitmap_copy (&dest->expressions, &orig->expressions);
679 bitmap_copy (&dest->values, &orig->values);
683 /* Free memory used up by SET. */
684 static void
685 bitmap_set_free (bitmap_set_t set)
687 bitmap_clear (&set->expressions);
688 bitmap_clear (&set->values);
692 /* Generate an topological-ordered array of bitmap set SET. */
694 static vec<pre_expr>
695 sorted_array_from_bitmap_set (bitmap_set_t set)
697 unsigned int i, j;
698 bitmap_iterator bi, bj;
699 vec<pre_expr> result;
701 /* Pre-allocate roughly enough space for the array. */
702 result.create (bitmap_count_bits (&set->values));
704 FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
706 /* The number of expressions having a given value is usually
707 relatively small. Thus, rather than making a vector of all
708 the expressions and sorting it by value-id, we walk the values
709 and check in the reverse mapping that tells us what expressions
710 have a given value, to filter those in our set. As a result,
711 the expressions are inserted in value-id order, which means
712 topological order.
714 If this is somehow a significant lose for some cases, we can
715 choose which set to walk based on the set size. */
716 bitmap exprset = value_expressions[i];
717 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bj)
719 if (bitmap_bit_p (&set->expressions, j))
720 result.safe_push (expression_for_id (j));
724 return result;
727 /* Perform bitmapped set operation DEST &= ORIG. */
729 static void
730 bitmap_set_and (bitmap_set_t dest, bitmap_set_t orig)
732 bitmap_iterator bi;
733 unsigned int i;
735 if (dest != orig)
737 bitmap_head temp;
738 bitmap_initialize (&temp, &grand_bitmap_obstack);
740 bitmap_and_into (&dest->values, &orig->values);
741 bitmap_copy (&temp, &dest->expressions);
742 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
744 pre_expr expr = expression_for_id (i);
745 unsigned int value_id = get_expr_value_id (expr);
746 if (!bitmap_bit_p (&dest->values, value_id))
747 bitmap_clear_bit (&dest->expressions, i);
749 bitmap_clear (&temp);
753 /* Subtract all values and expressions contained in ORIG from DEST. */
755 static bitmap_set_t
756 bitmap_set_subtract (bitmap_set_t dest, bitmap_set_t orig)
758 bitmap_set_t result = bitmap_set_new ();
759 bitmap_iterator bi;
760 unsigned int i;
762 bitmap_and_compl (&result->expressions, &dest->expressions,
763 &orig->expressions);
765 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
767 pre_expr expr = expression_for_id (i);
768 unsigned int value_id = get_expr_value_id (expr);
769 bitmap_set_bit (&result->values, value_id);
772 return result;
775 /* Subtract all the values in bitmap set B from bitmap set A. */
777 static void
778 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
780 unsigned int i;
781 bitmap_iterator bi;
782 bitmap_head temp;
784 bitmap_initialize (&temp, &grand_bitmap_obstack);
786 bitmap_copy (&temp, &a->expressions);
787 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
789 pre_expr expr = expression_for_id (i);
790 if (bitmap_set_contains_value (b, get_expr_value_id (expr)))
791 bitmap_remove_from_set (a, expr);
793 bitmap_clear (&temp);
797 /* Return true if bitmapped set SET contains the value VALUE_ID. */
799 static bool
800 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
802 if (value_id_constant_p (value_id))
803 return true;
805 if (!set || bitmap_empty_p (&set->expressions))
806 return false;
808 return bitmap_bit_p (&set->values, value_id);
811 static inline bool
812 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
814 return bitmap_bit_p (&set->expressions, get_expression_id (expr));
817 /* Replace an instance of value LOOKFOR with expression EXPR in SET. */
819 static void
820 bitmap_set_replace_value (bitmap_set_t set, unsigned int lookfor,
821 const pre_expr expr)
823 bitmap exprset;
824 unsigned int i;
825 bitmap_iterator bi;
827 if (value_id_constant_p (lookfor))
828 return;
830 if (!bitmap_set_contains_value (set, lookfor))
831 return;
833 /* The number of expressions having a given value is usually
834 significantly less than the total number of expressions in SET.
835 Thus, rather than check, for each expression in SET, whether it
836 has the value LOOKFOR, we walk the reverse mapping that tells us
837 what expressions have a given value, and see if any of those
838 expressions are in our set. For large testcases, this is about
839 5-10x faster than walking the bitmap. If this is somehow a
840 significant lose for some cases, we can choose which set to walk
841 based on the set size. */
842 exprset = value_expressions[lookfor];
843 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
845 if (bitmap_clear_bit (&set->expressions, i))
847 bitmap_set_bit (&set->expressions, get_expression_id (expr));
848 return;
852 gcc_unreachable ();
855 /* Return true if two bitmap sets are equal. */
857 static bool
858 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
860 return bitmap_equal_p (&a->values, &b->values);
863 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
864 and add it otherwise. */
866 static void
867 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
869 unsigned int val = get_expr_value_id (expr);
871 if (bitmap_set_contains_value (set, val))
872 bitmap_set_replace_value (set, val, expr);
873 else
874 bitmap_insert_into_set (set, expr);
877 /* Insert EXPR into SET if EXPR's value is not already present in
878 SET. */
880 static void
881 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
883 unsigned int val = get_expr_value_id (expr);
885 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
887 /* Constant values are always considered to be part of the set. */
888 if (value_id_constant_p (val))
889 return;
891 /* If the value membership changed, add the expression. */
892 if (bitmap_set_bit (&set->values, val))
893 bitmap_set_bit (&set->expressions, expr->id);
896 /* Print out EXPR to outfile. */
898 static void
899 print_pre_expr (FILE *outfile, const pre_expr expr)
901 switch (expr->kind)
903 case CONSTANT:
904 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr), 0);
905 break;
906 case NAME:
907 print_generic_expr (outfile, PRE_EXPR_NAME (expr), 0);
908 break;
909 case NARY:
911 unsigned int i;
912 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
913 fprintf (outfile, "{%s,", tree_code_name [nary->opcode]);
914 for (i = 0; i < nary->length; i++)
916 print_generic_expr (outfile, nary->op[i], 0);
917 if (i != (unsigned) nary->length - 1)
918 fprintf (outfile, ",");
920 fprintf (outfile, "}");
922 break;
924 case REFERENCE:
926 vn_reference_op_t vro;
927 unsigned int i;
928 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
929 fprintf (outfile, "{");
930 for (i = 0;
931 ref->operands.iterate (i, &vro);
932 i++)
934 bool closebrace = false;
935 if (vro->opcode != SSA_NAME
936 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
938 fprintf (outfile, "%s", tree_code_name [vro->opcode]);
939 if (vro->op0)
941 fprintf (outfile, "<");
942 closebrace = true;
945 if (vro->op0)
947 print_generic_expr (outfile, vro->op0, 0);
948 if (vro->op1)
950 fprintf (outfile, ",");
951 print_generic_expr (outfile, vro->op1, 0);
953 if (vro->op2)
955 fprintf (outfile, ",");
956 print_generic_expr (outfile, vro->op2, 0);
959 if (closebrace)
960 fprintf (outfile, ">");
961 if (i != ref->operands.length () - 1)
962 fprintf (outfile, ",");
964 fprintf (outfile, "}");
965 if (ref->vuse)
967 fprintf (outfile, "@");
968 print_generic_expr (outfile, ref->vuse, 0);
971 break;
974 void debug_pre_expr (pre_expr);
976 /* Like print_pre_expr but always prints to stderr. */
977 DEBUG_FUNCTION void
978 debug_pre_expr (pre_expr e)
980 print_pre_expr (stderr, e);
981 fprintf (stderr, "\n");
984 /* Print out SET to OUTFILE. */
986 static void
987 print_bitmap_set (FILE *outfile, bitmap_set_t set,
988 const char *setname, int blockindex)
990 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
991 if (set)
993 bool first = true;
994 unsigned i;
995 bitmap_iterator bi;
997 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
999 const pre_expr expr = expression_for_id (i);
1001 if (!first)
1002 fprintf (outfile, ", ");
1003 first = false;
1004 print_pre_expr (outfile, expr);
1006 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1009 fprintf (outfile, " }\n");
1012 void debug_bitmap_set (bitmap_set_t);
1014 DEBUG_FUNCTION void
1015 debug_bitmap_set (bitmap_set_t set)
1017 print_bitmap_set (stderr, set, "debug", 0);
1020 void debug_bitmap_sets_for (basic_block);
1022 DEBUG_FUNCTION void
1023 debug_bitmap_sets_for (basic_block bb)
1025 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1026 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1027 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1028 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1029 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1030 if (do_partial_partial)
1031 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1032 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1035 /* Print out the expressions that have VAL to OUTFILE. */
1037 static void
1038 print_value_expressions (FILE *outfile, unsigned int val)
1040 bitmap set = value_expressions[val];
1041 if (set)
1043 bitmap_set x;
1044 char s[10];
1045 sprintf (s, "%04d", val);
1046 x.expressions = *set;
1047 print_bitmap_set (outfile, &x, s, 0);
1052 DEBUG_FUNCTION void
1053 debug_value_expressions (unsigned int val)
1055 print_value_expressions (stderr, val);
1058 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1059 represent it. */
1061 static pre_expr
1062 get_or_alloc_expr_for_constant (tree constant)
1064 unsigned int result_id;
1065 unsigned int value_id;
1066 struct pre_expr_d expr;
1067 pre_expr newexpr;
1069 expr.kind = CONSTANT;
1070 PRE_EXPR_CONSTANT (&expr) = constant;
1071 result_id = lookup_expression_id (&expr);
1072 if (result_id != 0)
1073 return expression_for_id (result_id);
1075 newexpr = (pre_expr) pool_alloc (pre_expr_pool);
1076 newexpr->kind = CONSTANT;
1077 PRE_EXPR_CONSTANT (newexpr) = constant;
1078 alloc_expression_id (newexpr);
1079 value_id = get_or_alloc_constant_value_id (constant);
1080 add_to_value (value_id, newexpr);
1081 return newexpr;
1084 /* Given a value id V, find the actual tree representing the constant
1085 value if there is one, and return it. Return NULL if we can't find
1086 a constant. */
1088 static tree
1089 get_constant_for_value_id (unsigned int v)
1091 if (value_id_constant_p (v))
1093 unsigned int i;
1094 bitmap_iterator bi;
1095 bitmap exprset = value_expressions[v];
1097 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1099 pre_expr expr = expression_for_id (i);
1100 if (expr->kind == CONSTANT)
1101 return PRE_EXPR_CONSTANT (expr);
1104 return NULL;
1107 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1108 Currently only supports constants and SSA_NAMES. */
1109 static pre_expr
1110 get_or_alloc_expr_for (tree t)
1112 if (TREE_CODE (t) == SSA_NAME)
1113 return get_or_alloc_expr_for_name (t);
1114 else if (is_gimple_min_invariant (t))
1115 return get_or_alloc_expr_for_constant (t);
1116 else
1118 /* More complex expressions can result from SCCVN expression
1119 simplification that inserts values for them. As they all
1120 do not have VOPs the get handled by the nary ops struct. */
1121 vn_nary_op_t result;
1122 unsigned int result_id;
1123 vn_nary_op_lookup (t, &result);
1124 if (result != NULL)
1126 pre_expr e = (pre_expr) pool_alloc (pre_expr_pool);
1127 e->kind = NARY;
1128 PRE_EXPR_NARY (e) = result;
1129 result_id = lookup_expression_id (e);
1130 if (result_id != 0)
1132 pool_free (pre_expr_pool, e);
1133 e = expression_for_id (result_id);
1134 return e;
1136 alloc_expression_id (e);
1137 return e;
1140 return NULL;
1143 /* Return the folded version of T if T, when folded, is a gimple
1144 min_invariant. Otherwise, return T. */
1146 static pre_expr
1147 fully_constant_expression (pre_expr e)
1149 switch (e->kind)
1151 case CONSTANT:
1152 return e;
1153 case NARY:
1155 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1156 switch (TREE_CODE_CLASS (nary->opcode))
1158 case tcc_binary:
1159 case tcc_comparison:
1161 /* We have to go from trees to pre exprs to value ids to
1162 constants. */
1163 tree naryop0 = nary->op[0];
1164 tree naryop1 = nary->op[1];
1165 tree result;
1166 if (!is_gimple_min_invariant (naryop0))
1168 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1169 unsigned int vrep0 = get_expr_value_id (rep0);
1170 tree const0 = get_constant_for_value_id (vrep0);
1171 if (const0)
1172 naryop0 = fold_convert (TREE_TYPE (naryop0), const0);
1174 if (!is_gimple_min_invariant (naryop1))
1176 pre_expr rep1 = get_or_alloc_expr_for (naryop1);
1177 unsigned int vrep1 = get_expr_value_id (rep1);
1178 tree const1 = get_constant_for_value_id (vrep1);
1179 if (const1)
1180 naryop1 = fold_convert (TREE_TYPE (naryop1), const1);
1182 result = fold_binary (nary->opcode, nary->type,
1183 naryop0, naryop1);
1184 if (result && is_gimple_min_invariant (result))
1185 return get_or_alloc_expr_for_constant (result);
1186 /* We might have simplified the expression to a
1187 SSA_NAME for example from x_1 * 1. But we cannot
1188 insert a PHI for x_1 unconditionally as x_1 might
1189 not be available readily. */
1190 return e;
1192 case tcc_reference:
1193 if (nary->opcode != REALPART_EXPR
1194 && nary->opcode != IMAGPART_EXPR
1195 && nary->opcode != VIEW_CONVERT_EXPR)
1196 return e;
1197 /* Fallthrough. */
1198 case tcc_unary:
1200 /* We have to go from trees to pre exprs to value ids to
1201 constants. */
1202 tree naryop0 = nary->op[0];
1203 tree const0, result;
1204 if (is_gimple_min_invariant (naryop0))
1205 const0 = naryop0;
1206 else
1208 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1209 unsigned int vrep0 = get_expr_value_id (rep0);
1210 const0 = get_constant_for_value_id (vrep0);
1212 result = NULL;
1213 if (const0)
1215 tree type1 = TREE_TYPE (nary->op[0]);
1216 const0 = fold_convert (type1, const0);
1217 result = fold_unary (nary->opcode, nary->type, const0);
1219 if (result && is_gimple_min_invariant (result))
1220 return get_or_alloc_expr_for_constant (result);
1221 return e;
1223 default:
1224 return e;
1227 case REFERENCE:
1229 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1230 tree folded;
1231 if ((folded = fully_constant_vn_reference_p (ref)))
1232 return get_or_alloc_expr_for_constant (folded);
1233 return e;
1235 default:
1236 return e;
1238 return e;
1241 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1242 it has the value it would have in BLOCK. Set *SAME_VALID to true
1243 in case the new vuse doesn't change the value id of the OPERANDS. */
1245 static tree
1246 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1247 alias_set_type set, tree type, tree vuse,
1248 basic_block phiblock,
1249 basic_block block, bool *same_valid)
1251 gimple phi = SSA_NAME_DEF_STMT (vuse);
1252 ao_ref ref;
1253 edge e = NULL;
1254 bool use_oracle;
1256 *same_valid = true;
1258 if (gimple_bb (phi) != phiblock)
1259 return vuse;
1261 use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1263 /* Use the alias-oracle to find either the PHI node in this block,
1264 the first VUSE used in this block that is equivalent to vuse or
1265 the first VUSE which definition in this block kills the value. */
1266 if (gimple_code (phi) == GIMPLE_PHI)
1267 e = find_edge (block, phiblock);
1268 else if (use_oracle)
1269 while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1271 vuse = gimple_vuse (phi);
1272 phi = SSA_NAME_DEF_STMT (vuse);
1273 if (gimple_bb (phi) != phiblock)
1274 return vuse;
1275 if (gimple_code (phi) == GIMPLE_PHI)
1277 e = find_edge (block, phiblock);
1278 break;
1281 else
1282 return NULL_TREE;
1284 if (e)
1286 if (use_oracle)
1288 bitmap visited = NULL;
1289 unsigned int cnt;
1290 /* Try to find a vuse that dominates this phi node by skipping
1291 non-clobbering statements. */
1292 vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false);
1293 if (visited)
1294 BITMAP_FREE (visited);
1296 else
1297 vuse = NULL_TREE;
1298 if (!vuse)
1300 /* If we didn't find any, the value ID can't stay the same,
1301 but return the translated vuse. */
1302 *same_valid = false;
1303 vuse = PHI_ARG_DEF (phi, e->dest_idx);
1305 /* ??? We would like to return vuse here as this is the canonical
1306 upmost vdef that this reference is associated with. But during
1307 insertion of the references into the hash tables we only ever
1308 directly insert with their direct gimple_vuse, hence returning
1309 something else would make us not find the other expression. */
1310 return PHI_ARG_DEF (phi, e->dest_idx);
1313 return NULL_TREE;
1316 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1317 SET2. This is used to avoid making a set consisting of the union
1318 of PA_IN and ANTIC_IN during insert. */
1320 static inline pre_expr
1321 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2)
1323 pre_expr result;
1325 result = bitmap_find_leader (set1, val);
1326 if (!result && set2)
1327 result = bitmap_find_leader (set2, val);
1328 return result;
1331 /* Get the tree type for our PRE expression e. */
1333 static tree
1334 get_expr_type (const pre_expr e)
1336 switch (e->kind)
1338 case NAME:
1339 return TREE_TYPE (PRE_EXPR_NAME (e));
1340 case CONSTANT:
1341 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1342 case REFERENCE:
1343 return PRE_EXPR_REFERENCE (e)->type;
1344 case NARY:
1345 return PRE_EXPR_NARY (e)->type;
1347 gcc_unreachable ();
1350 /* Get a representative SSA_NAME for a given expression.
1351 Since all of our sub-expressions are treated as values, we require
1352 them to be SSA_NAME's for simplicity.
1353 Prior versions of GVNPRE used to use "value handles" here, so that
1354 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1355 either case, the operands are really values (IE we do not expect
1356 them to be usable without finding leaders). */
1358 static tree
1359 get_representative_for (const pre_expr e)
1361 tree name;
1362 unsigned int value_id = get_expr_value_id (e);
1364 switch (e->kind)
1366 case NAME:
1367 return PRE_EXPR_NAME (e);
1368 case CONSTANT:
1369 return PRE_EXPR_CONSTANT (e);
1370 case NARY:
1371 case REFERENCE:
1373 /* Go through all of the expressions representing this value
1374 and pick out an SSA_NAME. */
1375 unsigned int i;
1376 bitmap_iterator bi;
1377 bitmap exprs = value_expressions[value_id];
1378 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1380 pre_expr rep = expression_for_id (i);
1381 if (rep->kind == NAME)
1382 return PRE_EXPR_NAME (rep);
1383 else if (rep->kind == CONSTANT)
1384 return PRE_EXPR_CONSTANT (rep);
1387 break;
1390 /* If we reached here we couldn't find an SSA_NAME. This can
1391 happen when we've discovered a value that has never appeared in
1392 the program as set to an SSA_NAME, as the result of phi translation.
1393 Create one here.
1394 ??? We should be able to re-use this when we insert the statement
1395 to compute it. */
1396 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1397 VN_INFO_GET (name)->value_id = value_id;
1398 VN_INFO (name)->valnum = name;
1399 /* ??? For now mark this SSA name for release by SCCVN. */
1400 VN_INFO (name)->needs_insertion = true;
1401 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1402 if (dump_file && (dump_flags & TDF_DETAILS))
1404 fprintf (dump_file, "Created SSA_NAME representative ");
1405 print_generic_expr (dump_file, name, 0);
1406 fprintf (dump_file, " for expression:");
1407 print_pre_expr (dump_file, e);
1408 fprintf (dump_file, " (%04d)\n", value_id);
1411 return name;
1416 static pre_expr
1417 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1418 basic_block pred, basic_block phiblock);
1420 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1421 the phis in PRED. Return NULL if we can't find a leader for each part
1422 of the translated expression. */
1424 static pre_expr
1425 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1426 basic_block pred, basic_block phiblock)
1428 switch (expr->kind)
1430 case NARY:
1432 unsigned int i;
1433 bool changed = false;
1434 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1435 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1436 sizeof_vn_nary_op (nary->length));
1437 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1439 for (i = 0; i < newnary->length; i++)
1441 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1442 continue;
1443 else
1445 pre_expr leader, result;
1446 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1447 leader = find_leader_in_sets (op_val_id, set1, set2);
1448 result = phi_translate (leader, set1, set2, pred, phiblock);
1449 if (result && result != leader)
1451 tree name = get_representative_for (result);
1452 if (!name)
1453 return NULL;
1454 newnary->op[i] = name;
1456 else if (!result)
1457 return NULL;
1459 changed |= newnary->op[i] != nary->op[i];
1462 if (changed)
1464 pre_expr constant;
1465 unsigned int new_val_id;
1467 tree result = vn_nary_op_lookup_pieces (newnary->length,
1468 newnary->opcode,
1469 newnary->type,
1470 &newnary->op[0],
1471 &nary);
1472 if (result && is_gimple_min_invariant (result))
1473 return get_or_alloc_expr_for_constant (result);
1475 expr = (pre_expr) pool_alloc (pre_expr_pool);
1476 expr->kind = NARY;
1477 expr->id = 0;
1478 if (nary)
1480 PRE_EXPR_NARY (expr) = nary;
1481 constant = fully_constant_expression (expr);
1482 if (constant != expr)
1483 return constant;
1485 new_val_id = nary->value_id;
1486 get_or_alloc_expression_id (expr);
1488 else
1490 new_val_id = get_next_value_id ();
1491 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
1492 nary = vn_nary_op_insert_pieces (newnary->length,
1493 newnary->opcode,
1494 newnary->type,
1495 &newnary->op[0],
1496 result, new_val_id);
1497 PRE_EXPR_NARY (expr) = nary;
1498 constant = fully_constant_expression (expr);
1499 if (constant != expr)
1500 return constant;
1501 get_or_alloc_expression_id (expr);
1503 add_to_value (new_val_id, expr);
1505 return expr;
1507 break;
1509 case REFERENCE:
1511 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1512 vec<vn_reference_op_s> operands = ref->operands;
1513 tree vuse = ref->vuse;
1514 tree newvuse = vuse;
1515 vec<vn_reference_op_s> newoperands = vNULL;
1516 bool changed = false, same_valid = true;
1517 unsigned int i, j, n;
1518 vn_reference_op_t operand;
1519 vn_reference_t newref;
1521 for (i = 0, j = 0;
1522 operands.iterate (i, &operand); i++, j++)
1524 pre_expr opresult;
1525 pre_expr leader;
1526 tree op[3];
1527 tree type = operand->type;
1528 vn_reference_op_s newop = *operand;
1529 op[0] = operand->op0;
1530 op[1] = operand->op1;
1531 op[2] = operand->op2;
1532 for (n = 0; n < 3; ++n)
1534 unsigned int op_val_id;
1535 if (!op[n])
1536 continue;
1537 if (TREE_CODE (op[n]) != SSA_NAME)
1539 /* We can't possibly insert these. */
1540 if (n != 0
1541 && !is_gimple_min_invariant (op[n]))
1542 break;
1543 continue;
1545 op_val_id = VN_INFO (op[n])->value_id;
1546 leader = find_leader_in_sets (op_val_id, set1, set2);
1547 if (!leader)
1548 break;
1549 opresult = phi_translate (leader, set1, set2, pred, phiblock);
1550 if (!opresult)
1551 break;
1552 if (opresult != leader)
1554 tree name = get_representative_for (opresult);
1555 if (!name)
1556 break;
1557 changed |= name != op[n];
1558 op[n] = name;
1561 if (n != 3)
1563 newoperands.release ();
1564 return NULL;
1566 if (!newoperands.exists ())
1567 newoperands = operands.copy ();
1568 /* We may have changed from an SSA_NAME to a constant */
1569 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1570 newop.opcode = TREE_CODE (op[0]);
1571 newop.type = type;
1572 newop.op0 = op[0];
1573 newop.op1 = op[1];
1574 newop.op2 = op[2];
1575 /* If it transforms a non-constant ARRAY_REF into a constant
1576 one, adjust the constant offset. */
1577 if (newop.opcode == ARRAY_REF
1578 && newop.off == -1
1579 && TREE_CODE (op[0]) == INTEGER_CST
1580 && TREE_CODE (op[1]) == INTEGER_CST
1581 && TREE_CODE (op[2]) == INTEGER_CST)
1583 double_int off = tree_to_double_int (op[0]);
1584 off += -tree_to_double_int (op[1]);
1585 off *= tree_to_double_int (op[2]);
1586 if (off.fits_shwi ())
1587 newop.off = off.low;
1589 newoperands[j] = newop;
1590 /* If it transforms from an SSA_NAME to an address, fold with
1591 a preceding indirect reference. */
1592 if (j > 0 && op[0] && TREE_CODE (op[0]) == ADDR_EXPR
1593 && newoperands[j - 1].opcode == MEM_REF)
1594 vn_reference_fold_indirect (&newoperands, &j);
1596 if (i != operands.length ())
1598 newoperands.release ();
1599 return NULL;
1602 if (vuse)
1604 newvuse = translate_vuse_through_block (newoperands,
1605 ref->set, ref->type,
1606 vuse, phiblock, pred,
1607 &same_valid);
1608 if (newvuse == NULL_TREE)
1610 newoperands.release ();
1611 return NULL;
1615 if (changed || newvuse != vuse)
1617 unsigned int new_val_id;
1618 pre_expr constant;
1620 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1621 ref->type,
1622 newoperands,
1623 &newref, VN_WALK);
1624 if (result)
1625 newoperands.release ();
1627 /* We can always insert constants, so if we have a partial
1628 redundant constant load of another type try to translate it
1629 to a constant of appropriate type. */
1630 if (result && is_gimple_min_invariant (result))
1632 tree tem = result;
1633 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1635 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1636 if (tem && !is_gimple_min_invariant (tem))
1637 tem = NULL_TREE;
1639 if (tem)
1640 return get_or_alloc_expr_for_constant (tem);
1643 /* If we'd have to convert things we would need to validate
1644 if we can insert the translated expression. So fail
1645 here for now - we cannot insert an alias with a different
1646 type in the VN tables either, as that would assert. */
1647 if (result
1648 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1649 return NULL;
1650 else if (!result && newref
1651 && !useless_type_conversion_p (ref->type, newref->type))
1653 newoperands.release ();
1654 return NULL;
1657 expr = (pre_expr) pool_alloc (pre_expr_pool);
1658 expr->kind = REFERENCE;
1659 expr->id = 0;
1661 if (newref)
1663 PRE_EXPR_REFERENCE (expr) = newref;
1664 constant = fully_constant_expression (expr);
1665 if (constant != expr)
1666 return constant;
1668 new_val_id = newref->value_id;
1669 get_or_alloc_expression_id (expr);
1671 else
1673 if (changed || !same_valid)
1675 new_val_id = get_next_value_id ();
1676 value_expressions.safe_grow_cleared
1677 (get_max_value_id () + 1);
1679 else
1680 new_val_id = ref->value_id;
1681 newref = vn_reference_insert_pieces (newvuse, ref->set,
1682 ref->type,
1683 newoperands,
1684 result, new_val_id);
1685 newoperands.create (0);
1686 PRE_EXPR_REFERENCE (expr) = newref;
1687 constant = fully_constant_expression (expr);
1688 if (constant != expr)
1689 return constant;
1690 get_or_alloc_expression_id (expr);
1692 add_to_value (new_val_id, expr);
1694 newoperands.release ();
1695 return expr;
1697 break;
1699 case NAME:
1701 tree name = PRE_EXPR_NAME (expr);
1702 gimple def_stmt = SSA_NAME_DEF_STMT (name);
1703 /* If the SSA name is defined by a PHI node in this block,
1704 translate it. */
1705 if (gimple_code (def_stmt) == GIMPLE_PHI
1706 && gimple_bb (def_stmt) == phiblock)
1708 edge e = find_edge (pred, gimple_bb (def_stmt));
1709 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1711 /* Handle constant. */
1712 if (is_gimple_min_invariant (def))
1713 return get_or_alloc_expr_for_constant (def);
1715 return get_or_alloc_expr_for_name (def);
1717 /* Otherwise return it unchanged - it will get cleaned if its
1718 value is not available in PREDs AVAIL_OUT set of expressions. */
1719 return expr;
1722 default:
1723 gcc_unreachable ();
1727 /* Wrapper around phi_translate_1 providing caching functionality. */
1729 static pre_expr
1730 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1731 basic_block pred, basic_block phiblock)
1733 expr_pred_trans_t slot = NULL;
1734 pre_expr phitrans;
1736 if (!expr)
1737 return NULL;
1739 /* Constants contain no values that need translation. */
1740 if (expr->kind == CONSTANT)
1741 return expr;
1743 if (value_id_constant_p (get_expr_value_id (expr)))
1744 return expr;
1746 /* Don't add translations of NAMEs as those are cheap to translate. */
1747 if (expr->kind != NAME)
1749 if (phi_trans_add (&slot, expr, pred))
1750 return slot->v;
1751 /* Store NULL for the value we want to return in the case of
1752 recursing. */
1753 slot->v = NULL;
1756 /* Translate. */
1757 phitrans = phi_translate_1 (expr, set1, set2, pred, phiblock);
1759 if (slot)
1760 slot->v = phitrans;
1762 return phitrans;
1766 /* For each expression in SET, translate the values through phi nodes
1767 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1768 expressions in DEST. */
1770 static void
1771 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1772 basic_block phiblock)
1774 vec<pre_expr> exprs;
1775 pre_expr expr;
1776 int i;
1778 if (gimple_seq_empty_p (phi_nodes (phiblock)))
1780 bitmap_set_copy (dest, set);
1781 return;
1784 exprs = sorted_array_from_bitmap_set (set);
1785 FOR_EACH_VEC_ELT (exprs, i, expr)
1787 pre_expr translated;
1788 translated = phi_translate (expr, set, NULL, pred, phiblock);
1789 if (!translated)
1790 continue;
1792 /* We might end up with multiple expressions from SET being
1793 translated to the same value. In this case we do not want
1794 to retain the NARY or REFERENCE expression but prefer a NAME
1795 which would be the leader. */
1796 if (translated->kind == NAME)
1797 bitmap_value_replace_in_set (dest, translated);
1798 else
1799 bitmap_value_insert_into_set (dest, translated);
1801 exprs.release ();
1804 /* Find the leader for a value (i.e., the name representing that
1805 value) in a given set, and return it. Return NULL if no leader
1806 is found. */
1808 static pre_expr
1809 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1811 if (value_id_constant_p (val))
1813 unsigned int i;
1814 bitmap_iterator bi;
1815 bitmap exprset = value_expressions[val];
1817 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1819 pre_expr expr = expression_for_id (i);
1820 if (expr->kind == CONSTANT)
1821 return expr;
1824 if (bitmap_set_contains_value (set, val))
1826 /* Rather than walk the entire bitmap of expressions, and see
1827 whether any of them has the value we are looking for, we look
1828 at the reverse mapping, which tells us the set of expressions
1829 that have a given value (IE value->expressions with that
1830 value) and see if any of those expressions are in our set.
1831 The number of expressions per value is usually significantly
1832 less than the number of expressions in the set. In fact, for
1833 large testcases, doing it this way is roughly 5-10x faster
1834 than walking the bitmap.
1835 If this is somehow a significant lose for some cases, we can
1836 choose which set to walk based on which set is smaller. */
1837 unsigned int i;
1838 bitmap_iterator bi;
1839 bitmap exprset = value_expressions[val];
1841 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1842 return expression_for_id (i);
1844 return NULL;
1847 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1848 BLOCK by seeing if it is not killed in the block. Note that we are
1849 only determining whether there is a store that kills it. Because
1850 of the order in which clean iterates over values, we are guaranteed
1851 that altered operands will have caused us to be eliminated from the
1852 ANTIC_IN set already. */
1854 static bool
1855 value_dies_in_block_x (pre_expr expr, basic_block block)
1857 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1858 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1859 gimple def;
1860 gimple_stmt_iterator gsi;
1861 unsigned id = get_expression_id (expr);
1862 bool res = false;
1863 ao_ref ref;
1865 if (!vuse)
1866 return false;
1868 /* Lookup a previously calculated result. */
1869 if (EXPR_DIES (block)
1870 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1871 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1873 /* A memory expression {e, VUSE} dies in the block if there is a
1874 statement that may clobber e. If, starting statement walk from the
1875 top of the basic block, a statement uses VUSE there can be no kill
1876 inbetween that use and the original statement that loaded {e, VUSE},
1877 so we can stop walking. */
1878 ref.base = NULL_TREE;
1879 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1881 tree def_vuse, def_vdef;
1882 def = gsi_stmt (gsi);
1883 def_vuse = gimple_vuse (def);
1884 def_vdef = gimple_vdef (def);
1886 /* Not a memory statement. */
1887 if (!def_vuse)
1888 continue;
1890 /* Not a may-def. */
1891 if (!def_vdef)
1893 /* A load with the same VUSE, we're done. */
1894 if (def_vuse == vuse)
1895 break;
1897 continue;
1900 /* Init ref only if we really need it. */
1901 if (ref.base == NULL_TREE
1902 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1903 refx->operands))
1905 res = true;
1906 break;
1908 /* If the statement may clobber expr, it dies. */
1909 if (stmt_may_clobber_ref_p_1 (def, &ref))
1911 res = true;
1912 break;
1916 /* Remember the result. */
1917 if (!EXPR_DIES (block))
1918 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1919 bitmap_set_bit (EXPR_DIES (block), id * 2);
1920 if (res)
1921 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1923 return res;
1927 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1928 contains its value-id. */
1930 static bool
1931 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1933 if (op && TREE_CODE (op) == SSA_NAME)
1935 unsigned int value_id = VN_INFO (op)->value_id;
1936 if (!(bitmap_set_contains_value (set1, value_id)
1937 || (set2 && bitmap_set_contains_value (set2, value_id))))
1938 return false;
1940 return true;
1943 /* Determine if the expression EXPR is valid in SET1 U SET2.
1944 ONLY SET2 CAN BE NULL.
1945 This means that we have a leader for each part of the expression
1946 (if it consists of values), or the expression is an SSA_NAME.
1947 For loads/calls, we also see if the vuse is killed in this block. */
1949 static bool
1950 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr,
1951 basic_block block)
1953 switch (expr->kind)
1955 case NAME:
1956 return bitmap_find_leader (AVAIL_OUT (block),
1957 get_expr_value_id (expr)) != NULL;
1958 case NARY:
1960 unsigned int i;
1961 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1962 for (i = 0; i < nary->length; i++)
1963 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1964 return false;
1965 return true;
1967 break;
1968 case REFERENCE:
1970 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1971 vn_reference_op_t vro;
1972 unsigned int i;
1974 FOR_EACH_VEC_ELT (ref->operands, i, vro)
1976 if (!op_valid_in_sets (set1, set2, vro->op0)
1977 || !op_valid_in_sets (set1, set2, vro->op1)
1978 || !op_valid_in_sets (set1, set2, vro->op2))
1979 return false;
1981 return true;
1983 default:
1984 gcc_unreachable ();
1988 /* Clean the set of expressions that are no longer valid in SET1 or
1989 SET2. This means expressions that are made up of values we have no
1990 leaders for in SET1 or SET2. This version is used for partial
1991 anticipation, which means it is not valid in either ANTIC_IN or
1992 PA_IN. */
1994 static void
1995 dependent_clean (bitmap_set_t set1, bitmap_set_t set2, basic_block block)
1997 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
1998 pre_expr expr;
1999 int i;
2001 FOR_EACH_VEC_ELT (exprs, i, expr)
2003 if (!valid_in_sets (set1, set2, expr, block))
2004 bitmap_remove_from_set (set1, expr);
2006 exprs.release ();
2009 /* Clean the set of expressions that are no longer valid in SET. This
2010 means expressions that are made up of values we have no leaders for
2011 in SET. */
2013 static void
2014 clean (bitmap_set_t set, basic_block block)
2016 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set);
2017 pre_expr expr;
2018 int i;
2020 FOR_EACH_VEC_ELT (exprs, i, expr)
2022 if (!valid_in_sets (set, NULL, expr, block))
2023 bitmap_remove_from_set (set, expr);
2025 exprs.release ();
2028 /* Clean the set of expressions that are no longer valid in SET because
2029 they are clobbered in BLOCK or because they trap and may not be executed. */
2031 static void
2032 prune_clobbered_mems (bitmap_set_t set, basic_block block)
2034 bitmap_iterator bi;
2035 unsigned i;
2037 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2039 pre_expr expr = expression_for_id (i);
2040 if (expr->kind == REFERENCE)
2042 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2043 if (ref->vuse)
2045 gimple def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
2046 if (!gimple_nop_p (def_stmt)
2047 && ((gimple_bb (def_stmt) != block
2048 && !dominated_by_p (CDI_DOMINATORS,
2049 block, gimple_bb (def_stmt)))
2050 || (gimple_bb (def_stmt) == block
2051 && value_dies_in_block_x (expr, block))))
2052 bitmap_remove_from_set (set, expr);
2055 else if (expr->kind == NARY)
2057 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2058 /* If the NARY may trap make sure the block does not contain
2059 a possible exit point.
2060 ??? This is overly conservative if we translate AVAIL_OUT
2061 as the available expression might be after the exit point. */
2062 if (BB_MAY_NOTRETURN (block)
2063 && vn_nary_may_trap (nary))
2064 bitmap_remove_from_set (set, expr);
2069 static sbitmap has_abnormal_preds;
2071 /* List of blocks that may have changed during ANTIC computation and
2072 thus need to be iterated over. */
2074 static sbitmap changed_blocks;
2076 /* Decide whether to defer a block for a later iteration, or PHI
2077 translate SOURCE to DEST using phis in PHIBLOCK. Return false if we
2078 should defer the block, and true if we processed it. */
2080 static bool
2081 defer_or_phi_translate_block (bitmap_set_t dest, bitmap_set_t source,
2082 basic_block block, basic_block phiblock)
2084 if (!BB_VISITED (phiblock))
2086 bitmap_set_bit (changed_blocks, block->index);
2087 BB_VISITED (block) = 0;
2088 BB_DEFERRED (block) = 1;
2089 return false;
2091 else
2092 phi_translate_set (dest, source, block, phiblock);
2093 return true;
2096 /* Compute the ANTIC set for BLOCK.
2098 If succs(BLOCK) > 1 then
2099 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2100 else if succs(BLOCK) == 1 then
2101 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2103 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2106 static bool
2107 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2109 bool changed = false;
2110 bitmap_set_t S, old, ANTIC_OUT;
2111 bitmap_iterator bi;
2112 unsigned int bii;
2113 edge e;
2114 edge_iterator ei;
2116 old = ANTIC_OUT = S = NULL;
2117 BB_VISITED (block) = 1;
2119 /* If any edges from predecessors are abnormal, antic_in is empty,
2120 so do nothing. */
2121 if (block_has_abnormal_pred_edge)
2122 goto maybe_dump_sets;
2124 old = ANTIC_IN (block);
2125 ANTIC_OUT = bitmap_set_new ();
2127 /* If the block has no successors, ANTIC_OUT is empty. */
2128 if (EDGE_COUNT (block->succs) == 0)
2130 /* If we have one successor, we could have some phi nodes to
2131 translate through. */
2132 else if (single_succ_p (block))
2134 basic_block succ_bb = single_succ (block);
2136 /* We trade iterations of the dataflow equations for having to
2137 phi translate the maximal set, which is incredibly slow
2138 (since the maximal set often has 300+ members, even when you
2139 have a small number of blocks).
2140 Basically, we defer the computation of ANTIC for this block
2141 until we have processed it's successor, which will inevitably
2142 have a *much* smaller set of values to phi translate once
2143 clean has been run on it.
2144 The cost of doing this is that we technically perform more
2145 iterations, however, they are lower cost iterations.
2147 Timings for PRE on tramp3d-v4:
2148 without maximal set fix: 11 seconds
2149 with maximal set fix/without deferring: 26 seconds
2150 with maximal set fix/with deferring: 11 seconds
2153 if (!defer_or_phi_translate_block (ANTIC_OUT, ANTIC_IN (succ_bb),
2154 block, succ_bb))
2156 changed = true;
2157 goto maybe_dump_sets;
2160 /* If we have multiple successors, we take the intersection of all of
2161 them. Note that in the case of loop exit phi nodes, we may have
2162 phis to translate through. */
2163 else
2165 vec<basic_block> worklist;
2166 size_t i;
2167 basic_block bprime, first = NULL;
2169 worklist.create (EDGE_COUNT (block->succs));
2170 FOR_EACH_EDGE (e, ei, block->succs)
2172 if (!first
2173 && BB_VISITED (e->dest))
2174 first = e->dest;
2175 else if (BB_VISITED (e->dest))
2176 worklist.quick_push (e->dest);
2179 /* Of multiple successors we have to have visited one already. */
2180 if (!first)
2182 bitmap_set_bit (changed_blocks, block->index);
2183 BB_VISITED (block) = 0;
2184 BB_DEFERRED (block) = 1;
2185 changed = true;
2186 worklist.release ();
2187 goto maybe_dump_sets;
2190 if (!gimple_seq_empty_p (phi_nodes (first)))
2191 phi_translate_set (ANTIC_OUT, ANTIC_IN (first), block, first);
2192 else
2193 bitmap_set_copy (ANTIC_OUT, ANTIC_IN (first));
2195 FOR_EACH_VEC_ELT (worklist, i, bprime)
2197 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2199 bitmap_set_t tmp = bitmap_set_new ();
2200 phi_translate_set (tmp, ANTIC_IN (bprime), block, bprime);
2201 bitmap_set_and (ANTIC_OUT, tmp);
2202 bitmap_set_free (tmp);
2204 else
2205 bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2207 worklist.release ();
2210 /* Prune expressions that are clobbered in block and thus become
2211 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2212 prune_clobbered_mems (ANTIC_OUT, block);
2214 /* Generate ANTIC_OUT - TMP_GEN. */
2215 S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2217 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2218 ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2219 TMP_GEN (block));
2221 /* Then union in the ANTIC_OUT - TMP_GEN values,
2222 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2223 FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2224 bitmap_value_insert_into_set (ANTIC_IN (block),
2225 expression_for_id (bii));
2227 clean (ANTIC_IN (block), block);
2229 if (!bitmap_set_equal (old, ANTIC_IN (block)))
2231 changed = true;
2232 bitmap_set_bit (changed_blocks, block->index);
2233 FOR_EACH_EDGE (e, ei, block->preds)
2234 bitmap_set_bit (changed_blocks, e->src->index);
2236 else
2237 bitmap_clear_bit (changed_blocks, block->index);
2239 maybe_dump_sets:
2240 if (dump_file && (dump_flags & TDF_DETAILS))
2242 if (!BB_DEFERRED (block) || BB_VISITED (block))
2244 if (ANTIC_OUT)
2245 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2247 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2248 block->index);
2250 if (S)
2251 print_bitmap_set (dump_file, S, "S", block->index);
2253 else
2255 fprintf (dump_file,
2256 "Block %d was deferred for a future iteration.\n",
2257 block->index);
2260 if (old)
2261 bitmap_set_free (old);
2262 if (S)
2263 bitmap_set_free (S);
2264 if (ANTIC_OUT)
2265 bitmap_set_free (ANTIC_OUT);
2266 return changed;
2269 /* Compute PARTIAL_ANTIC for BLOCK.
2271 If succs(BLOCK) > 1 then
2272 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2273 in ANTIC_OUT for all succ(BLOCK)
2274 else if succs(BLOCK) == 1 then
2275 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2277 PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2278 - ANTIC_IN[BLOCK])
2281 static bool
2282 compute_partial_antic_aux (basic_block block,
2283 bool block_has_abnormal_pred_edge)
2285 bool changed = false;
2286 bitmap_set_t old_PA_IN;
2287 bitmap_set_t PA_OUT;
2288 edge e;
2289 edge_iterator ei;
2290 unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2292 old_PA_IN = PA_OUT = NULL;
2294 /* If any edges from predecessors are abnormal, antic_in is empty,
2295 so do nothing. */
2296 if (block_has_abnormal_pred_edge)
2297 goto maybe_dump_sets;
2299 /* If there are too many partially anticipatable values in the
2300 block, phi_translate_set can take an exponential time: stop
2301 before the translation starts. */
2302 if (max_pa
2303 && single_succ_p (block)
2304 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2305 goto maybe_dump_sets;
2307 old_PA_IN = PA_IN (block);
2308 PA_OUT = bitmap_set_new ();
2310 /* If the block has no successors, ANTIC_OUT is empty. */
2311 if (EDGE_COUNT (block->succs) == 0)
2313 /* If we have one successor, we could have some phi nodes to
2314 translate through. Note that we can't phi translate across DFS
2315 back edges in partial antic, because it uses a union operation on
2316 the successors. For recurrences like IV's, we will end up
2317 generating a new value in the set on each go around (i + 3 (VH.1)
2318 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2319 else if (single_succ_p (block))
2321 basic_block succ = single_succ (block);
2322 if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2323 phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2325 /* If we have multiple successors, we take the union of all of
2326 them. */
2327 else
2329 vec<basic_block> worklist;
2330 size_t i;
2331 basic_block bprime;
2333 worklist.create (EDGE_COUNT (block->succs));
2334 FOR_EACH_EDGE (e, ei, block->succs)
2336 if (e->flags & EDGE_DFS_BACK)
2337 continue;
2338 worklist.quick_push (e->dest);
2340 if (worklist.length () > 0)
2342 FOR_EACH_VEC_ELT (worklist, i, bprime)
2344 unsigned int i;
2345 bitmap_iterator bi;
2347 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2348 bitmap_value_insert_into_set (PA_OUT,
2349 expression_for_id (i));
2350 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2352 bitmap_set_t pa_in = bitmap_set_new ();
2353 phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2354 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2355 bitmap_value_insert_into_set (PA_OUT,
2356 expression_for_id (i));
2357 bitmap_set_free (pa_in);
2359 else
2360 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2361 bitmap_value_insert_into_set (PA_OUT,
2362 expression_for_id (i));
2365 worklist.release ();
2368 /* Prune expressions that are clobbered in block and thus become
2369 invalid if translated from PA_OUT to PA_IN. */
2370 prune_clobbered_mems (PA_OUT, block);
2372 /* PA_IN starts with PA_OUT - TMP_GEN.
2373 Then we subtract things from ANTIC_IN. */
2374 PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2376 /* For partial antic, we want to put back in the phi results, since
2377 we will properly avoid making them partially antic over backedges. */
2378 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2379 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2381 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2382 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2384 dependent_clean (PA_IN (block), ANTIC_IN (block), block);
2386 if (!bitmap_set_equal (old_PA_IN, PA_IN (block)))
2388 changed = true;
2389 bitmap_set_bit (changed_blocks, block->index);
2390 FOR_EACH_EDGE (e, ei, block->preds)
2391 bitmap_set_bit (changed_blocks, e->src->index);
2393 else
2394 bitmap_clear_bit (changed_blocks, block->index);
2396 maybe_dump_sets:
2397 if (dump_file && (dump_flags & TDF_DETAILS))
2399 if (PA_OUT)
2400 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2402 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2404 if (old_PA_IN)
2405 bitmap_set_free (old_PA_IN);
2406 if (PA_OUT)
2407 bitmap_set_free (PA_OUT);
2408 return changed;
2411 /* Compute ANTIC and partial ANTIC sets. */
2413 static void
2414 compute_antic (void)
2416 bool changed = true;
2417 int num_iterations = 0;
2418 basic_block block;
2419 int i;
2421 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2422 We pre-build the map of blocks with incoming abnormal edges here. */
2423 has_abnormal_preds = sbitmap_alloc (last_basic_block);
2424 bitmap_clear (has_abnormal_preds);
2426 FOR_ALL_BB (block)
2428 edge_iterator ei;
2429 edge e;
2431 FOR_EACH_EDGE (e, ei, block->preds)
2433 e->flags &= ~EDGE_DFS_BACK;
2434 if (e->flags & EDGE_ABNORMAL)
2436 bitmap_set_bit (has_abnormal_preds, block->index);
2437 break;
2441 BB_VISITED (block) = 0;
2442 BB_DEFERRED (block) = 0;
2444 /* While we are here, give empty ANTIC_IN sets to each block. */
2445 ANTIC_IN (block) = bitmap_set_new ();
2446 PA_IN (block) = bitmap_set_new ();
2449 /* At the exit block we anticipate nothing. */
2450 BB_VISITED (EXIT_BLOCK_PTR) = 1;
2452 changed_blocks = sbitmap_alloc (last_basic_block + 1);
2453 bitmap_ones (changed_blocks);
2454 while (changed)
2456 if (dump_file && (dump_flags & TDF_DETAILS))
2457 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2458 /* ??? We need to clear our PHI translation cache here as the
2459 ANTIC sets shrink and we restrict valid translations to
2460 those having operands with leaders in ANTIC. Same below
2461 for PA ANTIC computation. */
2462 num_iterations++;
2463 changed = false;
2464 for (i = postorder_num - 1; i >= 0; i--)
2466 if (bitmap_bit_p (changed_blocks, postorder[i]))
2468 basic_block block = BASIC_BLOCK (postorder[i]);
2469 changed |= compute_antic_aux (block,
2470 bitmap_bit_p (has_abnormal_preds,
2471 block->index));
2474 /* Theoretically possible, but *highly* unlikely. */
2475 gcc_checking_assert (num_iterations < 500);
2478 statistics_histogram_event (cfun, "compute_antic iterations",
2479 num_iterations);
2481 if (do_partial_partial)
2483 bitmap_ones (changed_blocks);
2484 mark_dfs_back_edges ();
2485 num_iterations = 0;
2486 changed = true;
2487 while (changed)
2489 if (dump_file && (dump_flags & TDF_DETAILS))
2490 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2491 num_iterations++;
2492 changed = false;
2493 for (i = postorder_num - 1 ; i >= 0; i--)
2495 if (bitmap_bit_p (changed_blocks, postorder[i]))
2497 basic_block block = BASIC_BLOCK (postorder[i]);
2498 changed
2499 |= compute_partial_antic_aux (block,
2500 bitmap_bit_p (has_abnormal_preds,
2501 block->index));
2504 /* Theoretically possible, but *highly* unlikely. */
2505 gcc_checking_assert (num_iterations < 500);
2507 statistics_histogram_event (cfun, "compute_partial_antic iterations",
2508 num_iterations);
2510 sbitmap_free (has_abnormal_preds);
2511 sbitmap_free (changed_blocks);
2515 /* Inserted expressions are placed onto this worklist, which is used
2516 for performing quick dead code elimination of insertions we made
2517 that didn't turn out to be necessary. */
2518 static bitmap inserted_exprs;
2520 /* The actual worker for create_component_ref_by_pieces. */
2522 static tree
2523 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2524 unsigned int *operand, gimple_seq *stmts)
2526 vn_reference_op_t currop = &ref->operands[*operand];
2527 tree genop;
2528 ++*operand;
2529 switch (currop->opcode)
2531 case CALL_EXPR:
2533 tree folded, sc = NULL_TREE;
2534 unsigned int nargs = 0;
2535 tree fn, *args;
2536 if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2537 fn = currop->op0;
2538 else
2539 fn = find_or_generate_expression (block, currop->op0, stmts);
2540 if (!fn)
2541 return NULL_TREE;
2542 if (currop->op1)
2544 sc = find_or_generate_expression (block, currop->op1, stmts);
2545 if (!sc)
2546 return NULL_TREE;
2548 args = XNEWVEC (tree, ref->operands.length () - 1);
2549 while (*operand < ref->operands.length ())
2551 args[nargs] = create_component_ref_by_pieces_1 (block, ref,
2552 operand, stmts);
2553 if (!args[nargs])
2554 return NULL_TREE;
2555 nargs++;
2557 folded = build_call_array (currop->type,
2558 (TREE_CODE (fn) == FUNCTION_DECL
2559 ? build_fold_addr_expr (fn) : fn),
2560 nargs, args);
2561 free (args);
2562 if (sc)
2563 CALL_EXPR_STATIC_CHAIN (folded) = sc;
2564 return folded;
2567 case MEM_REF:
2569 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2570 stmts);
2571 if (!baseop)
2572 return NULL_TREE;
2573 tree offset = currop->op0;
2574 if (TREE_CODE (baseop) == ADDR_EXPR
2575 && handled_component_p (TREE_OPERAND (baseop, 0)))
2577 HOST_WIDE_INT off;
2578 tree base;
2579 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2580 &off);
2581 gcc_assert (base);
2582 offset = int_const_binop (PLUS_EXPR, offset,
2583 build_int_cst (TREE_TYPE (offset),
2584 off));
2585 baseop = build_fold_addr_expr (base);
2587 return fold_build2 (MEM_REF, currop->type, baseop, offset);
2590 case TARGET_MEM_REF:
2592 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2593 vn_reference_op_t nextop = &ref->operands[++*operand];
2594 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2595 stmts);
2596 if (!baseop)
2597 return NULL_TREE;
2598 if (currop->op0)
2600 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2601 if (!genop0)
2602 return NULL_TREE;
2604 if (nextop->op0)
2606 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2607 if (!genop1)
2608 return NULL_TREE;
2610 return build5 (TARGET_MEM_REF, currop->type,
2611 baseop, currop->op2, genop0, currop->op1, genop1);
2614 case ADDR_EXPR:
2615 if (currop->op0)
2617 gcc_assert (is_gimple_min_invariant (currop->op0));
2618 return currop->op0;
2620 /* Fallthrough. */
2621 case REALPART_EXPR:
2622 case IMAGPART_EXPR:
2623 case VIEW_CONVERT_EXPR:
2625 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2626 stmts);
2627 if (!genop0)
2628 return NULL_TREE;
2629 return fold_build1 (currop->opcode, currop->type, genop0);
2632 case WITH_SIZE_EXPR:
2634 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2635 stmts);
2636 if (!genop0)
2637 return NULL_TREE;
2638 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2639 if (!genop1)
2640 return NULL_TREE;
2641 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2644 case BIT_FIELD_REF:
2646 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2647 stmts);
2648 if (!genop0)
2649 return NULL_TREE;
2650 tree op1 = currop->op0;
2651 tree op2 = currop->op1;
2652 return fold_build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2655 /* For array ref vn_reference_op's, operand 1 of the array ref
2656 is op0 of the reference op and operand 3 of the array ref is
2657 op1. */
2658 case ARRAY_RANGE_REF:
2659 case ARRAY_REF:
2661 tree genop0;
2662 tree genop1 = currop->op0;
2663 tree genop2 = currop->op1;
2664 tree genop3 = currop->op2;
2665 genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2666 stmts);
2667 if (!genop0)
2668 return NULL_TREE;
2669 genop1 = find_or_generate_expression (block, genop1, stmts);
2670 if (!genop1)
2671 return NULL_TREE;
2672 if (genop2)
2674 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2675 /* Drop zero minimum index if redundant. */
2676 if (integer_zerop (genop2)
2677 && (!domain_type
2678 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2679 genop2 = NULL_TREE;
2680 else
2682 genop2 = find_or_generate_expression (block, genop2, stmts);
2683 if (!genop2)
2684 return NULL_TREE;
2687 if (genop3)
2689 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2690 /* We can't always put a size in units of the element alignment
2691 here as the element alignment may be not visible. See
2692 PR43783. Simply drop the element size for constant
2693 sizes. */
2694 if (tree_int_cst_equal (genop3, TYPE_SIZE_UNIT (elmt_type)))
2695 genop3 = NULL_TREE;
2696 else
2698 genop3 = size_binop (EXACT_DIV_EXPR, genop3,
2699 size_int (TYPE_ALIGN_UNIT (elmt_type)));
2700 genop3 = find_or_generate_expression (block, genop3, stmts);
2701 if (!genop3)
2702 return NULL_TREE;
2705 return build4 (currop->opcode, currop->type, genop0, genop1,
2706 genop2, genop3);
2708 case COMPONENT_REF:
2710 tree op0;
2711 tree op1;
2712 tree genop2 = currop->op1;
2713 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2714 if (!op0)
2715 return NULL_TREE;
2716 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2717 op1 = currop->op0;
2718 if (genop2)
2720 genop2 = find_or_generate_expression (block, genop2, stmts);
2721 if (!genop2)
2722 return NULL_TREE;
2724 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2727 case SSA_NAME:
2729 genop = find_or_generate_expression (block, currop->op0, stmts);
2730 return genop;
2732 case STRING_CST:
2733 case INTEGER_CST:
2734 case COMPLEX_CST:
2735 case VECTOR_CST:
2736 case REAL_CST:
2737 case CONSTRUCTOR:
2738 case VAR_DECL:
2739 case PARM_DECL:
2740 case CONST_DECL:
2741 case RESULT_DECL:
2742 case FUNCTION_DECL:
2743 return currop->op0;
2745 default:
2746 gcc_unreachable ();
2750 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2751 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2752 trying to rename aggregates into ssa form directly, which is a no no.
2754 Thus, this routine doesn't create temporaries, it just builds a
2755 single access expression for the array, calling
2756 find_or_generate_expression to build the innermost pieces.
2758 This function is a subroutine of create_expression_by_pieces, and
2759 should not be called on it's own unless you really know what you
2760 are doing. */
2762 static tree
2763 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2764 gimple_seq *stmts)
2766 unsigned int op = 0;
2767 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2770 /* Find a simple leader for an expression, or generate one using
2771 create_expression_by_pieces from a NARY expression for the value.
2772 BLOCK is the basic_block we are looking for leaders in.
2773 OP is the tree expression to find a leader for or generate.
2774 Returns the leader or NULL_TREE on failure. */
2776 static tree
2777 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2779 pre_expr expr = get_or_alloc_expr_for (op);
2780 unsigned int lookfor = get_expr_value_id (expr);
2781 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2782 if (leader)
2784 if (leader->kind == NAME)
2785 return PRE_EXPR_NAME (leader);
2786 else if (leader->kind == CONSTANT)
2787 return PRE_EXPR_CONSTANT (leader);
2789 /* Defer. */
2790 return NULL_TREE;
2793 /* It must be a complex expression, so generate it recursively. Note
2794 that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2795 where the insert algorithm fails to insert a required expression. */
2796 bitmap exprset = value_expressions[lookfor];
2797 bitmap_iterator bi;
2798 unsigned int i;
2799 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2801 pre_expr temp = expression_for_id (i);
2802 /* We cannot insert random REFERENCE expressions at arbitrary
2803 places. We can insert NARYs which eventually re-materializes
2804 its operand values. */
2805 if (temp->kind == NARY)
2806 return create_expression_by_pieces (block, temp, stmts,
2807 get_expr_type (expr));
2810 /* Defer. */
2811 return NULL_TREE;
2814 #define NECESSARY GF_PLF_1
2816 /* Create an expression in pieces, so that we can handle very complex
2817 expressions that may be ANTIC, but not necessary GIMPLE.
2818 BLOCK is the basic block the expression will be inserted into,
2819 EXPR is the expression to insert (in value form)
2820 STMTS is a statement list to append the necessary insertions into.
2822 This function will die if we hit some value that shouldn't be
2823 ANTIC but is (IE there is no leader for it, or its components).
2824 The function returns NULL_TREE in case a different antic expression
2825 has to be inserted first.
2826 This function may also generate expressions that are themselves
2827 partially or fully redundant. Those that are will be either made
2828 fully redundant during the next iteration of insert (for partially
2829 redundant ones), or eliminated by eliminate (for fully redundant
2830 ones). */
2832 static tree
2833 create_expression_by_pieces (basic_block block, pre_expr expr,
2834 gimple_seq *stmts, tree type)
2836 tree name;
2837 tree folded;
2838 gimple_seq forced_stmts = NULL;
2839 unsigned int value_id;
2840 gimple_stmt_iterator gsi;
2841 tree exprtype = type ? type : get_expr_type (expr);
2842 pre_expr nameexpr;
2843 gimple newstmt;
2845 switch (expr->kind)
2847 /* We may hit the NAME/CONSTANT case if we have to convert types
2848 that value numbering saw through. */
2849 case NAME:
2850 folded = PRE_EXPR_NAME (expr);
2851 break;
2852 case CONSTANT:
2853 folded = PRE_EXPR_CONSTANT (expr);
2854 break;
2855 case REFERENCE:
2857 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2858 folded = create_component_ref_by_pieces (block, ref, stmts);
2859 if (!folded)
2860 return NULL_TREE;
2862 break;
2863 case NARY:
2865 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2866 tree *genop = XALLOCAVEC (tree, nary->length);
2867 unsigned i;
2868 for (i = 0; i < nary->length; ++i)
2870 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2871 if (!genop[i])
2872 return NULL_TREE;
2873 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2874 may have conversions stripped. */
2875 if (nary->opcode == POINTER_PLUS_EXPR)
2877 if (i == 0)
2878 genop[i] = fold_convert (nary->type, genop[i]);
2879 else if (i == 1)
2880 genop[i] = convert_to_ptrofftype (genop[i]);
2882 else
2883 genop[i] = fold_convert (TREE_TYPE (nary->op[i]), genop[i]);
2885 if (nary->opcode == CONSTRUCTOR)
2887 vec<constructor_elt, va_gc> *elts = NULL;
2888 for (i = 0; i < nary->length; ++i)
2889 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2890 folded = build_constructor (nary->type, elts);
2892 else
2894 switch (nary->length)
2896 case 1:
2897 folded = fold_build1 (nary->opcode, nary->type,
2898 genop[0]);
2899 break;
2900 case 2:
2901 folded = fold_build2 (nary->opcode, nary->type,
2902 genop[0], genop[1]);
2903 break;
2904 case 3:
2905 folded = fold_build3 (nary->opcode, nary->type,
2906 genop[0], genop[1], genop[2]);
2907 break;
2908 default:
2909 gcc_unreachable ();
2913 break;
2914 default:
2915 gcc_unreachable ();
2918 if (!useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2919 folded = fold_convert (exprtype, folded);
2921 /* Force the generated expression to be a sequence of GIMPLE
2922 statements.
2923 We have to call unshare_expr because force_gimple_operand may
2924 modify the tree we pass to it. */
2925 folded = force_gimple_operand (unshare_expr (folded), &forced_stmts,
2926 false, NULL);
2928 /* If we have any intermediate expressions to the value sets, add them
2929 to the value sets and chain them in the instruction stream. */
2930 if (forced_stmts)
2932 gsi = gsi_start (forced_stmts);
2933 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2935 gimple stmt = gsi_stmt (gsi);
2936 tree forcedname = gimple_get_lhs (stmt);
2937 pre_expr nameexpr;
2939 if (TREE_CODE (forcedname) == SSA_NAME)
2941 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2942 VN_INFO_GET (forcedname)->valnum = forcedname;
2943 VN_INFO (forcedname)->value_id = get_next_value_id ();
2944 nameexpr = get_or_alloc_expr_for_name (forcedname);
2945 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2946 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2947 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2950 gimple_seq_add_seq (stmts, forced_stmts);
2953 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2954 newstmt = gimple_build_assign (name, folded);
2955 gimple_set_plf (newstmt, NECESSARY, false);
2957 gimple_seq_add_stmt (stmts, newstmt);
2958 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
2960 /* Fold the last statement. */
2961 gsi = gsi_last (*stmts);
2962 if (fold_stmt_inplace (&gsi))
2963 update_stmt (gsi_stmt (gsi));
2965 /* Add a value number to the temporary.
2966 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2967 we are creating the expression by pieces, and this particular piece of
2968 the expression may have been represented. There is no harm in replacing
2969 here. */
2970 value_id = get_expr_value_id (expr);
2971 VN_INFO_GET (name)->value_id = value_id;
2972 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2973 if (VN_INFO (name)->valnum == NULL_TREE)
2974 VN_INFO (name)->valnum = name;
2975 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2976 nameexpr = get_or_alloc_expr_for_name (name);
2977 add_to_value (value_id, nameexpr);
2978 if (NEW_SETS (block))
2979 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2980 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2982 pre_stats.insertions++;
2983 if (dump_file && (dump_flags & TDF_DETAILS))
2985 fprintf (dump_file, "Inserted ");
2986 print_gimple_stmt (dump_file, newstmt, 0, 0);
2987 fprintf (dump_file, " in predecessor %d (%04d)\n",
2988 block->index, value_id);
2991 return name;
2995 /* Returns true if we want to inhibit the insertions of PHI nodes
2996 for the given EXPR for basic block BB (a member of a loop).
2997 We want to do this, when we fear that the induction variable we
2998 create might inhibit vectorization. */
3000 static bool
3001 inhibit_phi_insertion (basic_block bb, pre_expr expr)
3003 vn_reference_t vr = PRE_EXPR_REFERENCE (expr);
3004 vec<vn_reference_op_s> ops = vr->operands;
3005 vn_reference_op_t op;
3006 unsigned i;
3008 /* If we aren't going to vectorize we don't inhibit anything. */
3009 if (!flag_tree_loop_vectorize)
3010 return false;
3012 /* Otherwise we inhibit the insertion when the address of the
3013 memory reference is a simple induction variable. In other
3014 cases the vectorizer won't do anything anyway (either it's
3015 loop invariant or a complicated expression). */
3016 FOR_EACH_VEC_ELT (ops, i, op)
3018 switch (op->opcode)
3020 case CALL_EXPR:
3021 /* Calls are not a problem. */
3022 return false;
3024 case ARRAY_REF:
3025 case ARRAY_RANGE_REF:
3026 if (TREE_CODE (op->op0) != SSA_NAME)
3027 break;
3028 /* Fallthru. */
3029 case SSA_NAME:
3031 basic_block defbb = gimple_bb (SSA_NAME_DEF_STMT (op->op0));
3032 affine_iv iv;
3033 /* Default defs are loop invariant. */
3034 if (!defbb)
3035 break;
3036 /* Defined outside this loop, also loop invariant. */
3037 if (!flow_bb_inside_loop_p (bb->loop_father, defbb))
3038 break;
3039 /* If it's a simple induction variable inhibit insertion,
3040 the vectorizer might be interested in this one. */
3041 if (simple_iv (bb->loop_father, bb->loop_father,
3042 op->op0, &iv, true))
3043 return true;
3044 /* No simple IV, vectorizer can't do anything, hence no
3045 reason to inhibit the transformation for this operand. */
3046 break;
3048 default:
3049 break;
3052 return false;
3055 /* Insert the to-be-made-available values of expression EXPRNUM for each
3056 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
3057 merge the result with a phi node, given the same value number as
3058 NODE. Return true if we have inserted new stuff. */
3060 static bool
3061 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
3062 vec<pre_expr> avail)
3064 pre_expr expr = expression_for_id (exprnum);
3065 pre_expr newphi;
3066 unsigned int val = get_expr_value_id (expr);
3067 edge pred;
3068 bool insertions = false;
3069 bool nophi = false;
3070 basic_block bprime;
3071 pre_expr eprime;
3072 edge_iterator ei;
3073 tree type = get_expr_type (expr);
3074 tree temp;
3075 gimple phi;
3077 /* Make sure we aren't creating an induction variable. */
3078 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
3080 bool firstinsideloop = false;
3081 bool secondinsideloop = false;
3082 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
3083 EDGE_PRED (block, 0)->src);
3084 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
3085 EDGE_PRED (block, 1)->src);
3086 /* Induction variables only have one edge inside the loop. */
3087 if ((firstinsideloop ^ secondinsideloop)
3088 && (expr->kind != REFERENCE
3089 || inhibit_phi_insertion (block, expr)))
3091 if (dump_file && (dump_flags & TDF_DETAILS))
3092 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
3093 nophi = true;
3097 /* Make the necessary insertions. */
3098 FOR_EACH_EDGE (pred, ei, block->preds)
3100 gimple_seq stmts = NULL;
3101 tree builtexpr;
3102 bprime = pred->src;
3103 eprime = avail[pred->dest_idx];
3105 if (eprime->kind != NAME && eprime->kind != CONSTANT)
3107 builtexpr = create_expression_by_pieces (bprime, eprime,
3108 &stmts, type);
3109 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
3110 gsi_insert_seq_on_edge (pred, stmts);
3111 if (!builtexpr)
3113 /* We cannot insert a PHI node if we failed to insert
3114 on one edge. */
3115 nophi = true;
3116 continue;
3118 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
3119 insertions = true;
3121 else if (eprime->kind == CONSTANT)
3123 /* Constants may not have the right type, fold_convert
3124 should give us back a constant with the right type. */
3125 tree constant = PRE_EXPR_CONSTANT (eprime);
3126 if (!useless_type_conversion_p (type, TREE_TYPE (constant)))
3128 tree builtexpr = fold_convert (type, constant);
3129 if (!is_gimple_min_invariant (builtexpr))
3131 tree forcedexpr = force_gimple_operand (builtexpr,
3132 &stmts, true,
3133 NULL);
3134 if (!is_gimple_min_invariant (forcedexpr))
3136 if (forcedexpr != builtexpr)
3138 VN_INFO_GET (forcedexpr)->valnum = PRE_EXPR_CONSTANT (eprime);
3139 VN_INFO (forcedexpr)->value_id = get_expr_value_id (eprime);
3141 if (stmts)
3143 gimple_stmt_iterator gsi;
3144 gsi = gsi_start (stmts);
3145 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3147 gimple stmt = gsi_stmt (gsi);
3148 tree lhs = gimple_get_lhs (stmt);
3149 if (TREE_CODE (lhs) == SSA_NAME)
3150 bitmap_set_bit (inserted_exprs,
3151 SSA_NAME_VERSION (lhs));
3152 gimple_set_plf (stmt, NECESSARY, false);
3154 gsi_insert_seq_on_edge (pred, stmts);
3156 avail[pred->dest_idx]
3157 = get_or_alloc_expr_for_name (forcedexpr);
3160 else
3161 avail[pred->dest_idx]
3162 = get_or_alloc_expr_for_constant (builtexpr);
3165 else if (eprime->kind == NAME)
3167 /* We may have to do a conversion because our value
3168 numbering can look through types in certain cases, but
3169 our IL requires all operands of a phi node have the same
3170 type. */
3171 tree name = PRE_EXPR_NAME (eprime);
3172 if (!useless_type_conversion_p (type, TREE_TYPE (name)))
3174 tree builtexpr;
3175 tree forcedexpr;
3176 builtexpr = fold_convert (type, name);
3177 forcedexpr = force_gimple_operand (builtexpr,
3178 &stmts, true,
3179 NULL);
3181 if (forcedexpr != name)
3183 VN_INFO_GET (forcedexpr)->valnum = VN_INFO (name)->valnum;
3184 VN_INFO (forcedexpr)->value_id = VN_INFO (name)->value_id;
3187 if (stmts)
3189 gimple_stmt_iterator gsi;
3190 gsi = gsi_start (stmts);
3191 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3193 gimple stmt = gsi_stmt (gsi);
3194 tree lhs = gimple_get_lhs (stmt);
3195 if (TREE_CODE (lhs) == SSA_NAME)
3196 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
3197 gimple_set_plf (stmt, NECESSARY, false);
3199 gsi_insert_seq_on_edge (pred, stmts);
3201 avail[pred->dest_idx] = get_or_alloc_expr_for_name (forcedexpr);
3205 /* If we didn't want a phi node, and we made insertions, we still have
3206 inserted new stuff, and thus return true. If we didn't want a phi node,
3207 and didn't make insertions, we haven't added anything new, so return
3208 false. */
3209 if (nophi && insertions)
3210 return true;
3211 else if (nophi && !insertions)
3212 return false;
3214 /* Now build a phi for the new variable. */
3215 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3216 phi = create_phi_node (temp, block);
3218 gimple_set_plf (phi, NECESSARY, false);
3219 VN_INFO_GET (temp)->value_id = val;
3220 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3221 if (VN_INFO (temp)->valnum == NULL_TREE)
3222 VN_INFO (temp)->valnum = temp;
3223 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3224 FOR_EACH_EDGE (pred, ei, block->preds)
3226 pre_expr ae = avail[pred->dest_idx];
3227 gcc_assert (get_expr_type (ae) == type
3228 || useless_type_conversion_p (type, get_expr_type (ae)));
3229 if (ae->kind == CONSTANT)
3230 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3231 pred, UNKNOWN_LOCATION);
3232 else
3233 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3236 newphi = get_or_alloc_expr_for_name (temp);
3237 add_to_value (val, newphi);
3239 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3240 this insertion, since we test for the existence of this value in PHI_GEN
3241 before proceeding with the partial redundancy checks in insert_aux.
3243 The value may exist in AVAIL_OUT, in particular, it could be represented
3244 by the expression we are trying to eliminate, in which case we want the
3245 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3246 inserted there.
3248 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3249 this block, because if it did, it would have existed in our dominator's
3250 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3253 bitmap_insert_into_set (PHI_GEN (block), newphi);
3254 bitmap_value_replace_in_set (AVAIL_OUT (block),
3255 newphi);
3256 bitmap_insert_into_set (NEW_SETS (block),
3257 newphi);
3259 if (dump_file && (dump_flags & TDF_DETAILS))
3261 fprintf (dump_file, "Created phi ");
3262 print_gimple_stmt (dump_file, phi, 0, 0);
3263 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3265 pre_stats.phis++;
3266 return true;
3271 /* Perform insertion of partially redundant values.
3272 For BLOCK, do the following:
3273 1. Propagate the NEW_SETS of the dominator into the current block.
3274 If the block has multiple predecessors,
3275 2a. Iterate over the ANTIC expressions for the block to see if
3276 any of them are partially redundant.
3277 2b. If so, insert them into the necessary predecessors to make
3278 the expression fully redundant.
3279 2c. Insert a new PHI merging the values of the predecessors.
3280 2d. Insert the new PHI, and the new expressions, into the
3281 NEW_SETS set.
3282 3. Recursively call ourselves on the dominator children of BLOCK.
3284 Steps 1, 2a, and 3 are done by insert_aux. 2b, 2c and 2d are done by
3285 do_regular_insertion and do_partial_insertion.
3289 static bool
3290 do_regular_insertion (basic_block block, basic_block dom)
3292 bool new_stuff = false;
3293 vec<pre_expr> exprs;
3294 pre_expr expr;
3295 vec<pre_expr> avail = vNULL;
3296 int i;
3298 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3299 avail.safe_grow (EDGE_COUNT (block->preds));
3301 FOR_EACH_VEC_ELT (exprs, i, expr)
3303 if (expr->kind == NARY
3304 || expr->kind == REFERENCE)
3306 unsigned int val;
3307 bool by_some = false;
3308 bool cant_insert = false;
3309 bool all_same = true;
3310 pre_expr first_s = NULL;
3311 edge pred;
3312 basic_block bprime;
3313 pre_expr eprime = NULL;
3314 edge_iterator ei;
3315 pre_expr edoubleprime = NULL;
3316 bool do_insertion = false;
3318 val = get_expr_value_id (expr);
3319 if (bitmap_set_contains_value (PHI_GEN (block), val))
3320 continue;
3321 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3323 if (dump_file && (dump_flags & TDF_DETAILS))
3325 fprintf (dump_file, "Found fully redundant value: ");
3326 print_pre_expr (dump_file, expr);
3327 fprintf (dump_file, "\n");
3329 continue;
3332 FOR_EACH_EDGE (pred, ei, block->preds)
3334 unsigned int vprime;
3336 /* We should never run insertion for the exit block
3337 and so not come across fake pred edges. */
3338 gcc_assert (!(pred->flags & EDGE_FAKE));
3339 bprime = pred->src;
3340 eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3341 bprime, block);
3343 /* eprime will generally only be NULL if the
3344 value of the expression, translated
3345 through the PHI for this predecessor, is
3346 undefined. If that is the case, we can't
3347 make the expression fully redundant,
3348 because its value is undefined along a
3349 predecessor path. We can thus break out
3350 early because it doesn't matter what the
3351 rest of the results are. */
3352 if (eprime == NULL)
3354 avail[pred->dest_idx] = NULL;
3355 cant_insert = true;
3356 break;
3359 eprime = fully_constant_expression (eprime);
3360 vprime = get_expr_value_id (eprime);
3361 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3362 vprime);
3363 if (edoubleprime == NULL)
3365 avail[pred->dest_idx] = eprime;
3366 all_same = false;
3368 else
3370 avail[pred->dest_idx] = edoubleprime;
3371 by_some = true;
3372 /* We want to perform insertions to remove a redundancy on
3373 a path in the CFG we want to optimize for speed. */
3374 if (optimize_edge_for_speed_p (pred))
3375 do_insertion = true;
3376 if (first_s == NULL)
3377 first_s = edoubleprime;
3378 else if (!pre_expr_d::equal (first_s, edoubleprime))
3379 all_same = false;
3382 /* If we can insert it, it's not the same value
3383 already existing along every predecessor, and
3384 it's defined by some predecessor, it is
3385 partially redundant. */
3386 if (!cant_insert && !all_same && by_some)
3388 if (!do_insertion)
3390 if (dump_file && (dump_flags & TDF_DETAILS))
3392 fprintf (dump_file, "Skipping partial redundancy for "
3393 "expression ");
3394 print_pre_expr (dump_file, expr);
3395 fprintf (dump_file, " (%04d), no redundancy on to be "
3396 "optimized for speed edge\n", val);
3399 else if (dbg_cnt (treepre_insert))
3401 if (dump_file && (dump_flags & TDF_DETAILS))
3403 fprintf (dump_file, "Found partial redundancy for "
3404 "expression ");
3405 print_pre_expr (dump_file, expr);
3406 fprintf (dump_file, " (%04d)\n",
3407 get_expr_value_id (expr));
3409 if (insert_into_preds_of_block (block,
3410 get_expression_id (expr),
3411 avail))
3412 new_stuff = true;
3415 /* If all edges produce the same value and that value is
3416 an invariant, then the PHI has the same value on all
3417 edges. Note this. */
3418 else if (!cant_insert && all_same)
3420 gcc_assert (edoubleprime->kind == CONSTANT
3421 || edoubleprime->kind == NAME);
3423 tree temp = make_temp_ssa_name (get_expr_type (expr),
3424 NULL, "pretmp");
3425 gimple assign = gimple_build_assign (temp,
3426 edoubleprime->kind == CONSTANT ? PRE_EXPR_CONSTANT (edoubleprime) : PRE_EXPR_NAME (edoubleprime));
3427 gimple_stmt_iterator gsi = gsi_after_labels (block);
3428 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3430 gimple_set_plf (assign, NECESSARY, false);
3431 VN_INFO_GET (temp)->value_id = val;
3432 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3433 if (VN_INFO (temp)->valnum == NULL_TREE)
3434 VN_INFO (temp)->valnum = temp;
3435 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3436 pre_expr newe = get_or_alloc_expr_for_name (temp);
3437 add_to_value (val, newe);
3438 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3439 bitmap_insert_into_set (NEW_SETS (block), newe);
3444 exprs.release ();
3445 avail.release ();
3446 return new_stuff;
3450 /* Perform insertion for partially anticipatable expressions. There
3451 is only one case we will perform insertion for these. This case is
3452 if the expression is partially anticipatable, and fully available.
3453 In this case, we know that putting it earlier will enable us to
3454 remove the later computation. */
3457 static bool
3458 do_partial_partial_insertion (basic_block block, basic_block dom)
3460 bool new_stuff = false;
3461 vec<pre_expr> exprs;
3462 pre_expr expr;
3463 vec<pre_expr> avail = vNULL;
3464 int i;
3466 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3467 avail.safe_grow (EDGE_COUNT (block->preds));
3469 FOR_EACH_VEC_ELT (exprs, i, expr)
3471 if (expr->kind == NARY
3472 || expr->kind == REFERENCE)
3474 unsigned int val;
3475 bool by_all = true;
3476 bool cant_insert = false;
3477 edge pred;
3478 basic_block bprime;
3479 pre_expr eprime = NULL;
3480 edge_iterator ei;
3482 val = get_expr_value_id (expr);
3483 if (bitmap_set_contains_value (PHI_GEN (block), val))
3484 continue;
3485 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3486 continue;
3488 FOR_EACH_EDGE (pred, ei, block->preds)
3490 unsigned int vprime;
3491 pre_expr edoubleprime;
3493 /* We should never run insertion for the exit block
3494 and so not come across fake pred edges. */
3495 gcc_assert (!(pred->flags & EDGE_FAKE));
3496 bprime = pred->src;
3497 eprime = phi_translate (expr, ANTIC_IN (block),
3498 PA_IN (block),
3499 bprime, block);
3501 /* eprime will generally only be NULL if the
3502 value of the expression, translated
3503 through the PHI for this predecessor, is
3504 undefined. If that is the case, we can't
3505 make the expression fully redundant,
3506 because its value is undefined along a
3507 predecessor path. We can thus break out
3508 early because it doesn't matter what the
3509 rest of the results are. */
3510 if (eprime == NULL)
3512 avail[pred->dest_idx] = NULL;
3513 cant_insert = true;
3514 break;
3517 eprime = fully_constant_expression (eprime);
3518 vprime = get_expr_value_id (eprime);
3519 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3520 avail[pred->dest_idx] = edoubleprime;
3521 if (edoubleprime == NULL)
3523 by_all = false;
3524 break;
3528 /* If we can insert it, it's not the same value
3529 already existing along every predecessor, and
3530 it's defined by some predecessor, it is
3531 partially redundant. */
3532 if (!cant_insert && by_all)
3534 edge succ;
3535 bool do_insertion = false;
3537 /* Insert only if we can remove a later expression on a path
3538 that we want to optimize for speed.
3539 The phi node that we will be inserting in BLOCK is not free,
3540 and inserting it for the sake of !optimize_for_speed successor
3541 may cause regressions on the speed path. */
3542 FOR_EACH_EDGE (succ, ei, block->succs)
3544 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3545 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3547 if (optimize_edge_for_speed_p (succ))
3548 do_insertion = true;
3552 if (!do_insertion)
3554 if (dump_file && (dump_flags & TDF_DETAILS))
3556 fprintf (dump_file, "Skipping partial partial redundancy "
3557 "for expression ");
3558 print_pre_expr (dump_file, expr);
3559 fprintf (dump_file, " (%04d), not (partially) anticipated "
3560 "on any to be optimized for speed edges\n", val);
3563 else if (dbg_cnt (treepre_insert))
3565 pre_stats.pa_insert++;
3566 if (dump_file && (dump_flags & TDF_DETAILS))
3568 fprintf (dump_file, "Found partial partial redundancy "
3569 "for expression ");
3570 print_pre_expr (dump_file, expr);
3571 fprintf (dump_file, " (%04d)\n",
3572 get_expr_value_id (expr));
3574 if (insert_into_preds_of_block (block,
3575 get_expression_id (expr),
3576 avail))
3577 new_stuff = true;
3583 exprs.release ();
3584 avail.release ();
3585 return new_stuff;
3588 static bool
3589 insert_aux (basic_block block)
3591 basic_block son;
3592 bool new_stuff = false;
3594 if (block)
3596 basic_block dom;
3597 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3598 if (dom)
3600 unsigned i;
3601 bitmap_iterator bi;
3602 bitmap_set_t newset = NEW_SETS (dom);
3603 if (newset)
3605 /* Note that we need to value_replace both NEW_SETS, and
3606 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3607 represented by some non-simple expression here that we want
3608 to replace it with. */
3609 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3611 pre_expr expr = expression_for_id (i);
3612 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3613 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3616 if (!single_pred_p (block))
3618 new_stuff |= do_regular_insertion (block, dom);
3619 if (do_partial_partial)
3620 new_stuff |= do_partial_partial_insertion (block, dom);
3624 for (son = first_dom_son (CDI_DOMINATORS, block);
3625 son;
3626 son = next_dom_son (CDI_DOMINATORS, son))
3628 new_stuff |= insert_aux (son);
3631 return new_stuff;
3634 /* Perform insertion of partially redundant values. */
3636 static void
3637 insert (void)
3639 bool new_stuff = true;
3640 basic_block bb;
3641 int num_iterations = 0;
3643 FOR_ALL_BB (bb)
3644 NEW_SETS (bb) = bitmap_set_new ();
3646 while (new_stuff)
3648 num_iterations++;
3649 if (dump_file && dump_flags & TDF_DETAILS)
3650 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3651 new_stuff = insert_aux (ENTRY_BLOCK_PTR);
3653 /* Clear the NEW sets before the next iteration. We have already
3654 fully propagated its contents. */
3655 if (new_stuff)
3656 FOR_ALL_BB (bb)
3657 bitmap_set_free (NEW_SETS (bb));
3659 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3663 /* Compute the AVAIL set for all basic blocks.
3665 This function performs value numbering of the statements in each basic
3666 block. The AVAIL sets are built from information we glean while doing
3667 this value numbering, since the AVAIL sets contain only one entry per
3668 value.
3670 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3671 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3673 static void
3674 compute_avail (void)
3677 basic_block block, son;
3678 basic_block *worklist;
3679 size_t sp = 0;
3680 unsigned i;
3682 /* We pretend that default definitions are defined in the entry block.
3683 This includes function arguments and the static chain decl. */
3684 for (i = 1; i < num_ssa_names; ++i)
3686 tree name = ssa_name (i);
3687 pre_expr e;
3688 if (!name
3689 || !SSA_NAME_IS_DEFAULT_DEF (name)
3690 || has_zero_uses (name)
3691 || virtual_operand_p (name))
3692 continue;
3694 e = get_or_alloc_expr_for_name (name);
3695 add_to_value (get_expr_value_id (e), e);
3696 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR), e);
3697 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR), e);
3700 if (dump_file && (dump_flags & TDF_DETAILS))
3702 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR),
3703 "tmp_gen", ENTRY_BLOCK);
3704 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR),
3705 "avail_out", ENTRY_BLOCK);
3708 /* Allocate the worklist. */
3709 worklist = XNEWVEC (basic_block, n_basic_blocks);
3711 /* Seed the algorithm by putting the dominator children of the entry
3712 block on the worklist. */
3713 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR);
3714 son;
3715 son = next_dom_son (CDI_DOMINATORS, son))
3716 worklist[sp++] = son;
3718 /* Loop until the worklist is empty. */
3719 while (sp)
3721 gimple_stmt_iterator gsi;
3722 gimple stmt;
3723 basic_block dom;
3725 /* Pick a block from the worklist. */
3726 block = worklist[--sp];
3728 /* Initially, the set of available values in BLOCK is that of
3729 its immediate dominator. */
3730 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3731 if (dom)
3732 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3734 /* Generate values for PHI nodes. */
3735 for (gsi = gsi_start_phis (block); !gsi_end_p (gsi); gsi_next (&gsi))
3737 tree result = gimple_phi_result (gsi_stmt (gsi));
3739 /* We have no need for virtual phis, as they don't represent
3740 actual computations. */
3741 if (virtual_operand_p (result))
3742 continue;
3744 pre_expr e = get_or_alloc_expr_for_name (result);
3745 add_to_value (get_expr_value_id (e), e);
3746 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3747 bitmap_insert_into_set (PHI_GEN (block), e);
3750 BB_MAY_NOTRETURN (block) = 0;
3752 /* Now compute value numbers and populate value sets with all
3753 the expressions computed in BLOCK. */
3754 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
3756 ssa_op_iter iter;
3757 tree op;
3759 stmt = gsi_stmt (gsi);
3761 /* Cache whether the basic-block has any non-visible side-effect
3762 or control flow.
3763 If this isn't a call or it is the last stmt in the
3764 basic-block then the CFG represents things correctly. */
3765 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3767 /* Non-looping const functions always return normally.
3768 Otherwise the call might not return or have side-effects
3769 that forbids hoisting possibly trapping expressions
3770 before it. */
3771 int flags = gimple_call_flags (stmt);
3772 if (!(flags & ECF_CONST)
3773 || (flags & ECF_LOOPING_CONST_OR_PURE))
3774 BB_MAY_NOTRETURN (block) = 1;
3777 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3779 pre_expr e = get_or_alloc_expr_for_name (op);
3781 add_to_value (get_expr_value_id (e), e);
3782 bitmap_insert_into_set (TMP_GEN (block), e);
3783 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3786 if (gimple_has_side_effects (stmt)
3787 || stmt_could_throw_p (stmt)
3788 || is_gimple_debug (stmt))
3789 continue;
3791 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3793 if (ssa_undefined_value_p (op))
3794 continue;
3795 pre_expr e = get_or_alloc_expr_for_name (op);
3796 bitmap_value_insert_into_set (EXP_GEN (block), e);
3799 switch (gimple_code (stmt))
3801 case GIMPLE_RETURN:
3802 continue;
3804 case GIMPLE_CALL:
3806 vn_reference_t ref;
3807 pre_expr result = NULL;
3808 vec<vn_reference_op_s> ops = vNULL;
3810 /* We can value number only calls to real functions. */
3811 if (gimple_call_internal_p (stmt))
3812 continue;
3814 copy_reference_ops_from_call (stmt, &ops);
3815 vn_reference_lookup_pieces (gimple_vuse (stmt), 0,
3816 gimple_expr_type (stmt),
3817 ops, &ref, VN_NOWALK);
3818 ops.release ();
3819 if (!ref)
3820 continue;
3822 /* If the value of the call is not invalidated in
3823 this block until it is computed, add the expression
3824 to EXP_GEN. */
3825 if (!gimple_vuse (stmt)
3826 || gimple_code
3827 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3828 || gimple_bb (SSA_NAME_DEF_STMT
3829 (gimple_vuse (stmt))) != block)
3831 result = (pre_expr) pool_alloc (pre_expr_pool);
3832 result->kind = REFERENCE;
3833 result->id = 0;
3834 PRE_EXPR_REFERENCE (result) = ref;
3836 get_or_alloc_expression_id (result);
3837 add_to_value (get_expr_value_id (result), result);
3838 bitmap_value_insert_into_set (EXP_GEN (block), result);
3840 continue;
3843 case GIMPLE_ASSIGN:
3845 pre_expr result = NULL;
3846 switch (vn_get_stmt_kind (stmt))
3848 case VN_NARY:
3850 enum tree_code code = gimple_assign_rhs_code (stmt);
3851 vn_nary_op_t nary;
3853 /* COND_EXPR and VEC_COND_EXPR are awkward in
3854 that they contain an embedded complex expression.
3855 Don't even try to shove those through PRE. */
3856 if (code == COND_EXPR
3857 || code == VEC_COND_EXPR)
3858 continue;
3860 vn_nary_op_lookup_stmt (stmt, &nary);
3861 if (!nary)
3862 continue;
3864 /* If the NARY traps and there was a preceding
3865 point in the block that might not return avoid
3866 adding the nary to EXP_GEN. */
3867 if (BB_MAY_NOTRETURN (block)
3868 && vn_nary_may_trap (nary))
3869 continue;
3871 result = (pre_expr) pool_alloc (pre_expr_pool);
3872 result->kind = NARY;
3873 result->id = 0;
3874 PRE_EXPR_NARY (result) = nary;
3875 break;
3878 case VN_REFERENCE:
3880 vn_reference_t ref;
3881 vn_reference_lookup (gimple_assign_rhs1 (stmt),
3882 gimple_vuse (stmt),
3883 VN_WALK, &ref);
3884 if (!ref)
3885 continue;
3887 /* If the value of the reference is not invalidated in
3888 this block until it is computed, add the expression
3889 to EXP_GEN. */
3890 if (gimple_vuse (stmt))
3892 gimple def_stmt;
3893 bool ok = true;
3894 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3895 while (!gimple_nop_p (def_stmt)
3896 && gimple_code (def_stmt) != GIMPLE_PHI
3897 && gimple_bb (def_stmt) == block)
3899 if (stmt_may_clobber_ref_p
3900 (def_stmt, gimple_assign_rhs1 (stmt)))
3902 ok = false;
3903 break;
3905 def_stmt
3906 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3908 if (!ok)
3909 continue;
3912 result = (pre_expr) pool_alloc (pre_expr_pool);
3913 result->kind = REFERENCE;
3914 result->id = 0;
3915 PRE_EXPR_REFERENCE (result) = ref;
3916 break;
3919 default:
3920 continue;
3923 get_or_alloc_expression_id (result);
3924 add_to_value (get_expr_value_id (result), result);
3925 bitmap_value_insert_into_set (EXP_GEN (block), result);
3926 continue;
3928 default:
3929 break;
3933 if (dump_file && (dump_flags & TDF_DETAILS))
3935 print_bitmap_set (dump_file, EXP_GEN (block),
3936 "exp_gen", block->index);
3937 print_bitmap_set (dump_file, PHI_GEN (block),
3938 "phi_gen", block->index);
3939 print_bitmap_set (dump_file, TMP_GEN (block),
3940 "tmp_gen", block->index);
3941 print_bitmap_set (dump_file, AVAIL_OUT (block),
3942 "avail_out", block->index);
3945 /* Put the dominator children of BLOCK on the worklist of blocks
3946 to compute available sets for. */
3947 for (son = first_dom_son (CDI_DOMINATORS, block);
3948 son;
3949 son = next_dom_son (CDI_DOMINATORS, son))
3950 worklist[sp++] = son;
3953 free (worklist);
3957 /* Local state for the eliminate domwalk. */
3958 static vec<gimple> el_to_remove;
3959 static vec<gimple> el_to_update;
3960 static unsigned int el_todo;
3961 static vec<tree> el_avail;
3962 static vec<tree> el_avail_stack;
3964 /* Return a leader for OP that is available at the current point of the
3965 eliminate domwalk. */
3967 static tree
3968 eliminate_avail (tree op)
3970 tree valnum = VN_INFO (op)->valnum;
3971 if (TREE_CODE (valnum) == SSA_NAME)
3973 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
3974 return valnum;
3975 if (el_avail.length () > SSA_NAME_VERSION (valnum))
3976 return el_avail[SSA_NAME_VERSION (valnum)];
3978 else if (is_gimple_min_invariant (valnum))
3979 return valnum;
3980 return NULL_TREE;
3983 /* At the current point of the eliminate domwalk make OP available. */
3985 static void
3986 eliminate_push_avail (tree op)
3988 tree valnum = VN_INFO (op)->valnum;
3989 if (TREE_CODE (valnum) == SSA_NAME)
3991 if (el_avail.length () <= SSA_NAME_VERSION (valnum))
3992 el_avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1);
3993 el_avail[SSA_NAME_VERSION (valnum)] = op;
3994 el_avail_stack.safe_push (op);
3998 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
3999 the leader for the expression if insertion was successful. */
4001 static tree
4002 eliminate_insert (gimple_stmt_iterator *gsi, tree val)
4004 tree expr = vn_get_expr_for (val);
4005 if (!CONVERT_EXPR_P (expr)
4006 && TREE_CODE (expr) != VIEW_CONVERT_EXPR)
4007 return NULL_TREE;
4009 tree op = TREE_OPERAND (expr, 0);
4010 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (op) : op;
4011 if (!leader)
4012 return NULL_TREE;
4014 tree res = make_temp_ssa_name (TREE_TYPE (val), NULL, "pretmp");
4015 gimple tem = gimple_build_assign (res,
4016 fold_build1 (TREE_CODE (expr),
4017 TREE_TYPE (expr), leader));
4018 gsi_insert_before (gsi, tem, GSI_SAME_STMT);
4019 VN_INFO_GET (res)->valnum = val;
4021 if (TREE_CODE (leader) == SSA_NAME)
4022 gimple_set_plf (SSA_NAME_DEF_STMT (leader), NECESSARY, true);
4024 pre_stats.insertions++;
4025 if (dump_file && (dump_flags & TDF_DETAILS))
4027 fprintf (dump_file, "Inserted ");
4028 print_gimple_stmt (dump_file, tem, 0, 0);
4031 return res;
4034 class eliminate_dom_walker : public dom_walker
4036 public:
4037 eliminate_dom_walker (cdi_direction direction) : dom_walker (direction) {}
4039 virtual void before_dom_children (basic_block);
4040 virtual void after_dom_children (basic_block);
4043 /* Perform elimination for the basic-block B during the domwalk. */
4045 void
4046 eliminate_dom_walker::before_dom_children (basic_block b)
4048 gimple_stmt_iterator gsi;
4049 gimple stmt;
4051 /* Mark new bb. */
4052 el_avail_stack.safe_push (NULL_TREE);
4054 for (gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
4056 gimple stmt, phi = gsi_stmt (gsi);
4057 tree sprime = NULL_TREE, res = PHI_RESULT (phi);
4058 gimple_stmt_iterator gsi2;
4060 /* We want to perform redundant PHI elimination. Do so by
4061 replacing the PHI with a single copy if possible.
4062 Do not touch inserted, single-argument or virtual PHIs. */
4063 if (gimple_phi_num_args (phi) == 1
4064 || virtual_operand_p (res))
4066 gsi_next (&gsi);
4067 continue;
4070 sprime = eliminate_avail (res);
4071 if (!sprime
4072 || sprime == res)
4074 eliminate_push_avail (res);
4075 gsi_next (&gsi);
4076 continue;
4078 else if (is_gimple_min_invariant (sprime))
4080 if (!useless_type_conversion_p (TREE_TYPE (res),
4081 TREE_TYPE (sprime)))
4082 sprime = fold_convert (TREE_TYPE (res), sprime);
4085 if (dump_file && (dump_flags & TDF_DETAILS))
4087 fprintf (dump_file, "Replaced redundant PHI node defining ");
4088 print_generic_expr (dump_file, res, 0);
4089 fprintf (dump_file, " with ");
4090 print_generic_expr (dump_file, sprime, 0);
4091 fprintf (dump_file, "\n");
4094 remove_phi_node (&gsi, false);
4096 if (inserted_exprs
4097 && !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res))
4098 && TREE_CODE (sprime) == SSA_NAME)
4099 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4101 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
4102 sprime = fold_convert (TREE_TYPE (res), sprime);
4103 stmt = gimple_build_assign (res, sprime);
4104 SSA_NAME_DEF_STMT (res) = stmt;
4105 gimple_set_plf (stmt, NECESSARY, gimple_plf (phi, NECESSARY));
4107 gsi2 = gsi_after_labels (b);
4108 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
4109 /* Queue the copy for eventual removal. */
4110 el_to_remove.safe_push (stmt);
4111 /* If we inserted this PHI node ourself, it's not an elimination. */
4112 if (inserted_exprs
4113 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
4114 pre_stats.phis--;
4115 else
4116 pre_stats.eliminations++;
4119 for (gsi = gsi_start_bb (b); !gsi_end_p (gsi); gsi_next (&gsi))
4121 tree lhs = NULL_TREE;
4122 tree rhs = NULL_TREE;
4124 stmt = gsi_stmt (gsi);
4126 if (gimple_has_lhs (stmt))
4127 lhs = gimple_get_lhs (stmt);
4129 if (gimple_assign_single_p (stmt))
4130 rhs = gimple_assign_rhs1 (stmt);
4132 /* Lookup the RHS of the expression, see if we have an
4133 available computation for it. If so, replace the RHS with
4134 the available computation. */
4135 if (gimple_has_lhs (stmt)
4136 && TREE_CODE (lhs) == SSA_NAME
4137 && !gimple_has_volatile_ops (stmt))
4139 tree sprime;
4140 gimple orig_stmt = stmt;
4142 sprime = eliminate_avail (lhs);
4143 /* If there is no usable leader mark lhs as leader for its value. */
4144 if (!sprime)
4145 eliminate_push_avail (lhs);
4147 /* See PR43491. Do not replace a global register variable when
4148 it is a the RHS of an assignment. Do replace local register
4149 variables since gcc does not guarantee a local variable will
4150 be allocated in register.
4151 Do not perform copy propagation or undo constant propagation. */
4152 if (gimple_assign_single_p (stmt)
4153 && (TREE_CODE (rhs) == SSA_NAME
4154 || is_gimple_min_invariant (rhs)
4155 || (TREE_CODE (rhs) == VAR_DECL
4156 && is_global_var (rhs)
4157 && DECL_HARD_REGISTER (rhs))))
4158 continue;
4160 if (!sprime)
4162 /* If there is no existing usable leader but SCCVN thinks
4163 it has an expression it wants to use as replacement,
4164 insert that. */
4165 tree val = VN_INFO (lhs)->valnum;
4166 if (val != VN_TOP
4167 && TREE_CODE (val) == SSA_NAME
4168 && VN_INFO (val)->needs_insertion
4169 && VN_INFO (val)->expr != NULL_TREE
4170 && (sprime = eliminate_insert (&gsi, val)) != NULL_TREE)
4171 eliminate_push_avail (sprime);
4173 else if (is_gimple_min_invariant (sprime))
4175 /* If there is no existing leader but SCCVN knows this
4176 value is constant, use that constant. */
4177 if (!useless_type_conversion_p (TREE_TYPE (lhs),
4178 TREE_TYPE (sprime)))
4179 sprime = fold_convert (TREE_TYPE (lhs), sprime);
4181 if (dump_file && (dump_flags & TDF_DETAILS))
4183 fprintf (dump_file, "Replaced ");
4184 print_gimple_expr (dump_file, stmt, 0, 0);
4185 fprintf (dump_file, " with ");
4186 print_generic_expr (dump_file, sprime, 0);
4187 fprintf (dump_file, " in ");
4188 print_gimple_stmt (dump_file, stmt, 0, 0);
4190 pre_stats.eliminations++;
4191 propagate_tree_value_into_stmt (&gsi, sprime);
4192 stmt = gsi_stmt (gsi);
4193 update_stmt (stmt);
4195 /* If we removed EH side-effects from the statement, clean
4196 its EH information. */
4197 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4199 bitmap_set_bit (need_eh_cleanup,
4200 gimple_bb (stmt)->index);
4201 if (dump_file && (dump_flags & TDF_DETAILS))
4202 fprintf (dump_file, " Removed EH side-effects.\n");
4204 continue;
4207 if (sprime
4208 && sprime != lhs
4209 && (rhs == NULL_TREE
4210 || TREE_CODE (rhs) != SSA_NAME
4211 || may_propagate_copy (rhs, sprime)))
4213 bool can_make_abnormal_goto
4214 = is_gimple_call (stmt)
4215 && stmt_can_make_abnormal_goto (stmt);
4217 gcc_assert (sprime != rhs);
4219 if (dump_file && (dump_flags & TDF_DETAILS))
4221 fprintf (dump_file, "Replaced ");
4222 print_gimple_expr (dump_file, stmt, 0, 0);
4223 fprintf (dump_file, " with ");
4224 print_generic_expr (dump_file, sprime, 0);
4225 fprintf (dump_file, " in ");
4226 print_gimple_stmt (dump_file, stmt, 0, 0);
4229 if (TREE_CODE (sprime) == SSA_NAME)
4230 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4231 NECESSARY, true);
4232 /* We need to make sure the new and old types actually match,
4233 which may require adding a simple cast, which fold_convert
4234 will do for us. */
4235 if ((!rhs || TREE_CODE (rhs) != SSA_NAME)
4236 && !useless_type_conversion_p (gimple_expr_type (stmt),
4237 TREE_TYPE (sprime)))
4238 sprime = fold_convert (gimple_expr_type (stmt), sprime);
4240 pre_stats.eliminations++;
4241 propagate_tree_value_into_stmt (&gsi, sprime);
4242 stmt = gsi_stmt (gsi);
4243 update_stmt (stmt);
4245 /* If we removed EH side-effects from the statement, clean
4246 its EH information. */
4247 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4249 bitmap_set_bit (need_eh_cleanup,
4250 gimple_bb (stmt)->index);
4251 if (dump_file && (dump_flags & TDF_DETAILS))
4252 fprintf (dump_file, " Removed EH side-effects.\n");
4255 /* Likewise for AB side-effects. */
4256 if (can_make_abnormal_goto
4257 && !stmt_can_make_abnormal_goto (stmt))
4259 bitmap_set_bit (need_ab_cleanup,
4260 gimple_bb (stmt)->index);
4261 if (dump_file && (dump_flags & TDF_DETAILS))
4262 fprintf (dump_file, " Removed AB side-effects.\n");
4266 /* If the statement is a scalar store, see if the expression
4267 has the same value number as its rhs. If so, the store is
4268 dead. */
4269 else if (gimple_assign_single_p (stmt)
4270 && !gimple_has_volatile_ops (stmt)
4271 && !is_gimple_reg (gimple_assign_lhs (stmt))
4272 && (TREE_CODE (rhs) == SSA_NAME
4273 || is_gimple_min_invariant (rhs)))
4275 tree val;
4276 val = vn_reference_lookup (gimple_assign_lhs (stmt),
4277 gimple_vuse (stmt), VN_WALK, NULL);
4278 if (TREE_CODE (rhs) == SSA_NAME)
4279 rhs = VN_INFO (rhs)->valnum;
4280 if (val
4281 && operand_equal_p (val, rhs, 0))
4283 if (dump_file && (dump_flags & TDF_DETAILS))
4285 fprintf (dump_file, "Deleted redundant store ");
4286 print_gimple_stmt (dump_file, stmt, 0, 0);
4289 /* Queue stmt for removal. */
4290 el_to_remove.safe_push (stmt);
4293 /* Visit COND_EXPRs and fold the comparison with the
4294 available value-numbers. */
4295 else if (gimple_code (stmt) == GIMPLE_COND)
4297 tree op0 = gimple_cond_lhs (stmt);
4298 tree op1 = gimple_cond_rhs (stmt);
4299 tree result;
4301 if (TREE_CODE (op0) == SSA_NAME)
4302 op0 = VN_INFO (op0)->valnum;
4303 if (TREE_CODE (op1) == SSA_NAME)
4304 op1 = VN_INFO (op1)->valnum;
4305 result = fold_binary (gimple_cond_code (stmt), boolean_type_node,
4306 op0, op1);
4307 if (result && TREE_CODE (result) == INTEGER_CST)
4309 if (integer_zerop (result))
4310 gimple_cond_make_false (stmt);
4311 else
4312 gimple_cond_make_true (stmt);
4313 update_stmt (stmt);
4314 el_todo = TODO_cleanup_cfg;
4317 /* Visit indirect calls and turn them into direct calls if
4318 possible. */
4319 if (is_gimple_call (stmt))
4321 tree orig_fn = gimple_call_fn (stmt);
4322 tree fn;
4323 if (!orig_fn)
4324 continue;
4325 if (TREE_CODE (orig_fn) == SSA_NAME)
4326 fn = VN_INFO (orig_fn)->valnum;
4327 else if (TREE_CODE (orig_fn) == OBJ_TYPE_REF
4328 && TREE_CODE (OBJ_TYPE_REF_EXPR (orig_fn)) == SSA_NAME)
4330 fn = VN_INFO (OBJ_TYPE_REF_EXPR (orig_fn))->valnum;
4331 if (!gimple_call_addr_fndecl (fn))
4333 fn = ipa_intraprocedural_devirtualization (stmt);
4334 if (fn)
4335 fn = build_fold_addr_expr (fn);
4338 else
4339 continue;
4340 if (gimple_call_addr_fndecl (fn) != NULL_TREE
4341 && useless_type_conversion_p (TREE_TYPE (orig_fn),
4342 TREE_TYPE (fn)))
4344 bool can_make_abnormal_goto
4345 = stmt_can_make_abnormal_goto (stmt);
4346 bool was_noreturn = gimple_call_noreturn_p (stmt);
4348 if (dump_file && (dump_flags & TDF_DETAILS))
4350 fprintf (dump_file, "Replacing call target with ");
4351 print_generic_expr (dump_file, fn, 0);
4352 fprintf (dump_file, " in ");
4353 print_gimple_stmt (dump_file, stmt, 0, 0);
4356 gimple_call_set_fn (stmt, fn);
4357 el_to_update.safe_push (stmt);
4359 /* When changing a call into a noreturn call, cfg cleanup
4360 is needed to fix up the noreturn call. */
4361 if (!was_noreturn && gimple_call_noreturn_p (stmt))
4362 el_todo |= TODO_cleanup_cfg;
4364 /* If we removed EH side-effects from the statement, clean
4365 its EH information. */
4366 if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
4368 bitmap_set_bit (need_eh_cleanup,
4369 gimple_bb (stmt)->index);
4370 if (dump_file && (dump_flags & TDF_DETAILS))
4371 fprintf (dump_file, " Removed EH side-effects.\n");
4374 /* Likewise for AB side-effects. */
4375 if (can_make_abnormal_goto
4376 && !stmt_can_make_abnormal_goto (stmt))
4378 bitmap_set_bit (need_ab_cleanup,
4379 gimple_bb (stmt)->index);
4380 if (dump_file && (dump_flags & TDF_DETAILS))
4381 fprintf (dump_file, " Removed AB side-effects.\n");
4384 /* Changing an indirect call to a direct call may
4385 have exposed different semantics. This may
4386 require an SSA update. */
4387 el_todo |= TODO_update_ssa_only_virtuals;
4393 /* Make no longer available leaders no longer available. */
4395 void
4396 eliminate_dom_walker::after_dom_children (basic_block)
4398 tree entry;
4399 while ((entry = el_avail_stack.pop ()) != NULL_TREE)
4400 el_avail[SSA_NAME_VERSION (VN_INFO (entry)->valnum)] = NULL_TREE;
4403 /* Eliminate fully redundant computations. */
4405 static unsigned int
4406 eliminate (void)
4408 gimple_stmt_iterator gsi;
4409 gimple stmt;
4410 unsigned i;
4412 need_eh_cleanup = BITMAP_ALLOC (NULL);
4413 need_ab_cleanup = BITMAP_ALLOC (NULL);
4415 el_to_remove.create (0);
4416 el_to_update.create (0);
4417 el_todo = 0;
4418 el_avail.create (0);
4419 el_avail_stack.create (0);
4421 eliminate_dom_walker (CDI_DOMINATORS).walk (cfun->cfg->x_entry_block_ptr);
4423 el_avail.release ();
4424 el_avail_stack.release ();
4426 /* We cannot remove stmts during BB walk, especially not release SSA
4427 names there as this confuses the VN machinery. The stmts ending
4428 up in el_to_remove are either stores or simple copies. */
4429 FOR_EACH_VEC_ELT (el_to_remove, i, stmt)
4431 tree lhs = gimple_assign_lhs (stmt);
4432 tree rhs = gimple_assign_rhs1 (stmt);
4433 use_operand_p use_p;
4434 gimple use_stmt;
4436 /* If there is a single use only, propagate the equivalency
4437 instead of keeping the copy. */
4438 if (TREE_CODE (lhs) == SSA_NAME
4439 && TREE_CODE (rhs) == SSA_NAME
4440 && single_imm_use (lhs, &use_p, &use_stmt)
4441 && may_propagate_copy (USE_FROM_PTR (use_p), rhs))
4443 SET_USE (use_p, rhs);
4444 update_stmt (use_stmt);
4445 if (inserted_exprs
4446 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (lhs))
4447 && TREE_CODE (rhs) == SSA_NAME)
4448 gimple_set_plf (SSA_NAME_DEF_STMT (rhs), NECESSARY, true);
4451 /* If this is a store or a now unused copy, remove it. */
4452 if (TREE_CODE (lhs) != SSA_NAME
4453 || has_zero_uses (lhs))
4455 basic_block bb = gimple_bb (stmt);
4456 gsi = gsi_for_stmt (stmt);
4457 unlink_stmt_vdef (stmt);
4458 if (gsi_remove (&gsi, true))
4459 bitmap_set_bit (need_eh_cleanup, bb->index);
4460 if (inserted_exprs
4461 && TREE_CODE (lhs) == SSA_NAME)
4462 bitmap_clear_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
4463 release_defs (stmt);
4466 el_to_remove.release ();
4468 /* We cannot update call statements with virtual operands during
4469 SSA walk. This might remove them which in turn makes our
4470 VN lattice invalid. */
4471 FOR_EACH_VEC_ELT (el_to_update, i, stmt)
4472 update_stmt (stmt);
4473 el_to_update.release ();
4475 return el_todo;
4478 /* Perform CFG cleanups made necessary by elimination. */
4480 static unsigned
4481 fini_eliminate (void)
4483 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
4484 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
4486 if (do_eh_cleanup)
4487 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
4489 if (do_ab_cleanup)
4490 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
4492 BITMAP_FREE (need_eh_cleanup);
4493 BITMAP_FREE (need_ab_cleanup);
4495 if (do_eh_cleanup || do_ab_cleanup)
4496 return TODO_cleanup_cfg;
4497 return 0;
4500 /* Borrow a bit of tree-ssa-dce.c for the moment.
4501 XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
4502 this may be a bit faster, and we may want critical edges kept split. */
4504 /* If OP's defining statement has not already been determined to be necessary,
4505 mark that statement necessary. Return the stmt, if it is newly
4506 necessary. */
4508 static inline gimple
4509 mark_operand_necessary (tree op)
4511 gimple stmt;
4513 gcc_assert (op);
4515 if (TREE_CODE (op) != SSA_NAME)
4516 return NULL;
4518 stmt = SSA_NAME_DEF_STMT (op);
4519 gcc_assert (stmt);
4521 if (gimple_plf (stmt, NECESSARY)
4522 || gimple_nop_p (stmt))
4523 return NULL;
4525 gimple_set_plf (stmt, NECESSARY, true);
4526 return stmt;
4529 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4530 to insert PHI nodes sometimes, and because value numbering of casts isn't
4531 perfect, we sometimes end up inserting dead code. This simple DCE-like
4532 pass removes any insertions we made that weren't actually used. */
4534 static void
4535 remove_dead_inserted_code (void)
4537 bitmap worklist;
4538 unsigned i;
4539 bitmap_iterator bi;
4540 gimple t;
4542 worklist = BITMAP_ALLOC (NULL);
4543 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4545 t = SSA_NAME_DEF_STMT (ssa_name (i));
4546 if (gimple_plf (t, NECESSARY))
4547 bitmap_set_bit (worklist, i);
4549 while (!bitmap_empty_p (worklist))
4551 i = bitmap_first_set_bit (worklist);
4552 bitmap_clear_bit (worklist, i);
4553 t = SSA_NAME_DEF_STMT (ssa_name (i));
4555 /* PHI nodes are somewhat special in that each PHI alternative has
4556 data and control dependencies. All the statements feeding the
4557 PHI node's arguments are always necessary. */
4558 if (gimple_code (t) == GIMPLE_PHI)
4560 unsigned k;
4562 for (k = 0; k < gimple_phi_num_args (t); k++)
4564 tree arg = PHI_ARG_DEF (t, k);
4565 if (TREE_CODE (arg) == SSA_NAME)
4567 gimple n = mark_operand_necessary (arg);
4568 if (n)
4569 bitmap_set_bit (worklist, SSA_NAME_VERSION (arg));
4573 else
4575 /* Propagate through the operands. Examine all the USE, VUSE and
4576 VDEF operands in this statement. Mark all the statements
4577 which feed this statement's uses as necessary. */
4578 ssa_op_iter iter;
4579 tree use;
4581 /* The operands of VDEF expressions are also needed as they
4582 represent potential definitions that may reach this
4583 statement (VDEF operands allow us to follow def-def
4584 links). */
4586 FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
4588 gimple n = mark_operand_necessary (use);
4589 if (n)
4590 bitmap_set_bit (worklist, SSA_NAME_VERSION (use));
4595 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4597 t = SSA_NAME_DEF_STMT (ssa_name (i));
4598 if (!gimple_plf (t, NECESSARY))
4600 gimple_stmt_iterator gsi;
4602 if (dump_file && (dump_flags & TDF_DETAILS))
4604 fprintf (dump_file, "Removing unnecessary insertion:");
4605 print_gimple_stmt (dump_file, t, 0, 0);
4608 gsi = gsi_for_stmt (t);
4609 if (gimple_code (t) == GIMPLE_PHI)
4610 remove_phi_node (&gsi, true);
4611 else
4613 gsi_remove (&gsi, true);
4614 release_defs (t);
4618 BITMAP_FREE (worklist);
4622 /* Initialize data structures used by PRE. */
4624 static void
4625 init_pre (void)
4627 basic_block bb;
4629 next_expression_id = 1;
4630 expressions.create (0);
4631 expressions.safe_push (NULL);
4632 value_expressions.create (get_max_value_id () + 1);
4633 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
4634 name_to_id.create (0);
4636 inserted_exprs = BITMAP_ALLOC (NULL);
4638 connect_infinite_loops_to_exit ();
4639 memset (&pre_stats, 0, sizeof (pre_stats));
4641 postorder = XNEWVEC (int, n_basic_blocks);
4642 postorder_num = inverted_post_order_compute (postorder);
4644 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4646 calculate_dominance_info (CDI_POST_DOMINATORS);
4647 calculate_dominance_info (CDI_DOMINATORS);
4649 bitmap_obstack_initialize (&grand_bitmap_obstack);
4650 phi_translate_table.create (5110);
4651 expression_to_id.create (num_ssa_names * 3);
4652 bitmap_set_pool = create_alloc_pool ("Bitmap sets",
4653 sizeof (struct bitmap_set), 30);
4654 pre_expr_pool = create_alloc_pool ("pre_expr nodes",
4655 sizeof (struct pre_expr_d), 30);
4656 FOR_ALL_BB (bb)
4658 EXP_GEN (bb) = bitmap_set_new ();
4659 PHI_GEN (bb) = bitmap_set_new ();
4660 TMP_GEN (bb) = bitmap_set_new ();
4661 AVAIL_OUT (bb) = bitmap_set_new ();
4666 /* Deallocate data structures used by PRE. */
4668 static void
4669 fini_pre ()
4671 free (postorder);
4672 value_expressions.release ();
4673 BITMAP_FREE (inserted_exprs);
4674 bitmap_obstack_release (&grand_bitmap_obstack);
4675 free_alloc_pool (bitmap_set_pool);
4676 free_alloc_pool (pre_expr_pool);
4677 phi_translate_table.dispose ();
4678 expression_to_id.dispose ();
4679 name_to_id.release ();
4681 free_aux_for_blocks ();
4683 free_dominance_info (CDI_POST_DOMINATORS);
4686 /* Gate and execute functions for PRE. */
4688 static unsigned int
4689 do_pre (void)
4691 unsigned int todo = 0;
4693 do_partial_partial =
4694 flag_tree_partial_pre && optimize_function_for_speed_p (cfun);
4696 /* This has to happen before SCCVN runs because
4697 loop_optimizer_init may create new phis, etc. */
4698 loop_optimizer_init (LOOPS_NORMAL);
4700 if (!run_scc_vn (VN_WALK))
4702 loop_optimizer_finalize ();
4703 return 0;
4706 init_pre ();
4707 scev_initialize ();
4709 /* Collect and value number expressions computed in each basic block. */
4710 compute_avail ();
4712 /* Insert can get quite slow on an incredibly large number of basic
4713 blocks due to some quadratic behavior. Until this behavior is
4714 fixed, don't run it when he have an incredibly large number of
4715 bb's. If we aren't going to run insert, there is no point in
4716 computing ANTIC, either, even though it's plenty fast. */
4717 if (n_basic_blocks < 4000)
4719 compute_antic ();
4720 insert ();
4723 /* Make sure to remove fake edges before committing our inserts.
4724 This makes sure we don't end up with extra critical edges that
4725 we would need to split. */
4726 remove_fake_exit_edges ();
4727 gsi_commit_edge_inserts ();
4729 /* Remove all the redundant expressions. */
4730 todo |= eliminate ();
4732 statistics_counter_event (cfun, "Insertions", pre_stats.insertions);
4733 statistics_counter_event (cfun, "PA inserted", pre_stats.pa_insert);
4734 statistics_counter_event (cfun, "New PHIs", pre_stats.phis);
4735 statistics_counter_event (cfun, "Eliminated", pre_stats.eliminations);
4737 clear_expression_ids ();
4738 remove_dead_inserted_code ();
4739 todo |= TODO_verify_flow;
4741 scev_finalize ();
4742 fini_pre ();
4743 todo |= fini_eliminate ();
4744 loop_optimizer_finalize ();
4746 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
4747 case we can merge the block with the remaining predecessor of the block.
4748 It should either:
4749 - call merge_blocks after each tail merge iteration
4750 - call merge_blocks after all tail merge iterations
4751 - mark TODO_cleanup_cfg when necessary
4752 - share the cfg cleanup with fini_pre. */
4753 todo |= tail_merge_optimize (todo);
4755 free_scc_vn ();
4757 /* Tail merging invalidates the virtual SSA web, together with
4758 cfg-cleanup opportunities exposed by PRE this will wreck the
4759 SSA updating machinery. So make sure to run update-ssa
4760 manually, before eventually scheduling cfg-cleanup as part of
4761 the todo. */
4762 update_ssa (TODO_update_ssa_only_virtuals);
4764 return todo;
4767 static bool
4768 gate_pre (void)
4770 return flag_tree_pre != 0;
4773 namespace {
4775 const pass_data pass_data_pre =
4777 GIMPLE_PASS, /* type */
4778 "pre", /* name */
4779 OPTGROUP_NONE, /* optinfo_flags */
4780 true, /* has_gate */
4781 true, /* has_execute */
4782 TV_TREE_PRE, /* tv_id */
4783 ( PROP_no_crit_edges | PROP_cfg | PROP_ssa ), /* properties_required */
4784 0, /* properties_provided */
4785 0, /* properties_destroyed */
4786 TODO_rebuild_alias, /* todo_flags_start */
4787 TODO_verify_ssa, /* todo_flags_finish */
4790 class pass_pre : public gimple_opt_pass
4792 public:
4793 pass_pre (gcc::context *ctxt)
4794 : gimple_opt_pass (pass_data_pre, ctxt)
4797 /* opt_pass methods: */
4798 bool gate () { return gate_pre (); }
4799 unsigned int execute () { return do_pre (); }
4801 }; // class pass_pre
4803 } // anon namespace
4805 gimple_opt_pass *
4806 make_pass_pre (gcc::context *ctxt)
4808 return new pass_pre (ctxt);
4812 /* Gate and execute functions for FRE. */
4814 static unsigned int
4815 execute_fre (void)
4817 unsigned int todo = 0;
4819 if (!run_scc_vn (VN_WALKREWRITE))
4820 return 0;
4822 memset (&pre_stats, 0, sizeof (pre_stats));
4824 /* Remove all the redundant expressions. */
4825 todo |= eliminate ();
4827 todo |= fini_eliminate ();
4829 free_scc_vn ();
4831 statistics_counter_event (cfun, "Insertions", pre_stats.insertions);
4832 statistics_counter_event (cfun, "Eliminated", pre_stats.eliminations);
4834 return todo;
4837 static bool
4838 gate_fre (void)
4840 return flag_tree_fre != 0;
4843 namespace {
4845 const pass_data pass_data_fre =
4847 GIMPLE_PASS, /* type */
4848 "fre", /* name */
4849 OPTGROUP_NONE, /* optinfo_flags */
4850 true, /* has_gate */
4851 true, /* has_execute */
4852 TV_TREE_FRE, /* tv_id */
4853 ( PROP_cfg | PROP_ssa ), /* properties_required */
4854 0, /* properties_provided */
4855 0, /* properties_destroyed */
4856 0, /* todo_flags_start */
4857 TODO_verify_ssa, /* todo_flags_finish */
4860 class pass_fre : public gimple_opt_pass
4862 public:
4863 pass_fre (gcc::context *ctxt)
4864 : gimple_opt_pass (pass_data_fre, ctxt)
4867 /* opt_pass methods: */
4868 opt_pass * clone () { return new pass_fre (m_ctxt); }
4869 bool gate () { return gate_fre (); }
4870 unsigned int execute () { return execute_fre (); }
4872 }; // class pass_fre
4874 } // anon namespace
4876 gimple_opt_pass *
4877 make_pass_fre (gcc::context *ctxt)
4879 return new pass_fre (ctxt);