* ipa-devirt.c (type_pair, default_hashset_traits): New types.
[official-gcc.git] / gcc / tree-ssa-pre.c
blob5f32b59096928c9e059d351325bc96f4da54e551
1 /* SSA-PRE for trees.
2 Copyright (C) 2001-2014 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 "inchash.h"
31 #include "hash-table.h"
32 #include "tree-ssa-alias.h"
33 #include "internal-fn.h"
34 #include "gimple-fold.h"
35 #include "tree-eh.h"
36 #include "gimple-expr.h"
37 #include "is-a.h"
38 #include "gimple.h"
39 #include "gimplify.h"
40 #include "gimple-iterator.h"
41 #include "gimplify-me.h"
42 #include "gimple-ssa.h"
43 #include "tree-cfg.h"
44 #include "tree-phinodes.h"
45 #include "ssa-iterators.h"
46 #include "stringpool.h"
47 #include "tree-ssanames.h"
48 #include "tree-ssa-loop.h"
49 #include "tree-into-ssa.h"
50 #include "expr.h"
51 #include "tree-dfa.h"
52 #include "tree-ssa.h"
53 #include "tree-iterator.h"
54 #include "alloc-pool.h"
55 #include "obstack.h"
56 #include "tree-pass.h"
57 #include "flags.h"
58 #include "langhooks.h"
59 #include "cfgloop.h"
60 #include "tree-ssa-sccvn.h"
61 #include "tree-scalar-evolution.h"
62 #include "params.h"
63 #include "dbgcnt.h"
64 #include "domwalk.h"
65 #include "ipa-prop.h"
66 #include "tree-ssa-propagate.h"
67 #include "ipa-utils.h"
69 /* TODO:
71 1. Avail sets can be shared by making an avail_find_leader that
72 walks up the dominator tree and looks in those avail sets.
73 This might affect code optimality, it's unclear right now.
74 2. Strength reduction can be performed by anticipating expressions
75 we can repair later on.
76 3. We can do back-substitution or smarter value numbering to catch
77 commutative expressions split up over multiple statements.
80 /* For ease of terminology, "expression node" in the below refers to
81 every expression node but GIMPLE_ASSIGN, because GIMPLE_ASSIGNs
82 represent the actual statement containing the expressions we care about,
83 and we cache the value number by putting it in the expression. */
85 /* Basic algorithm
87 First we walk the statements to generate the AVAIL sets, the
88 EXP_GEN sets, and the tmp_gen sets. EXP_GEN sets represent the
89 generation of values/expressions by a given block. We use them
90 when computing the ANTIC sets. The AVAIL sets consist of
91 SSA_NAME's that represent values, so we know what values are
92 available in what blocks. AVAIL is a forward dataflow problem. In
93 SSA, values are never killed, so we don't need a kill set, or a
94 fixpoint iteration, in order to calculate the AVAIL sets. In
95 traditional parlance, AVAIL sets tell us the downsafety of the
96 expressions/values.
98 Next, we generate the ANTIC sets. These sets represent the
99 anticipatable expressions. ANTIC is a backwards dataflow
100 problem. An expression is anticipatable in a given block if it could
101 be generated in that block. This means that if we had to perform
102 an insertion in that block, of the value of that expression, we
103 could. Calculating the ANTIC sets requires phi translation of
104 expressions, because the flow goes backwards through phis. We must
105 iterate to a fixpoint of the ANTIC sets, because we have a kill
106 set. Even in SSA form, values are not live over the entire
107 function, only from their definition point onwards. So we have to
108 remove values from the ANTIC set once we go past the definition
109 point of the leaders that make them up.
110 compute_antic/compute_antic_aux performs this computation.
112 Third, we perform insertions to make partially redundant
113 expressions fully redundant.
115 An expression is partially redundant (excluding partial
116 anticipation) if:
118 1. It is AVAIL in some, but not all, of the predecessors of a
119 given block.
120 2. It is ANTIC in all the predecessors.
122 In order to make it fully redundant, we insert the expression into
123 the predecessors where it is not available, but is ANTIC.
125 For the partial anticipation case, we only perform insertion if it
126 is partially anticipated in some block, and fully available in all
127 of the predecessors.
129 insert/insert_aux/do_regular_insertion/do_partial_partial_insertion
130 performs these steps.
132 Fourth, we eliminate fully redundant expressions.
133 This is a simple statement walk that replaces redundant
134 calculations with the now available values. */
136 /* Representations of value numbers:
138 Value numbers are represented by a representative SSA_NAME. We
139 will create fake SSA_NAME's in situations where we need a
140 representative but do not have one (because it is a complex
141 expression). In order to facilitate storing the value numbers in
142 bitmaps, and keep the number of wasted SSA_NAME's down, we also
143 associate a value_id with each value number, and create full blown
144 ssa_name's only where we actually need them (IE in operands of
145 existing expressions).
147 Theoretically you could replace all the value_id's with
148 SSA_NAME_VERSION, but this would allocate a large number of
149 SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
150 It would also require an additional indirection at each point we
151 use the value id. */
153 /* Representation of expressions on value numbers:
155 Expressions consisting of value numbers are represented the same
156 way as our VN internally represents them, with an additional
157 "pre_expr" wrapping around them in order to facilitate storing all
158 of the expressions in the same sets. */
160 /* Representation of sets:
162 The dataflow sets do not need to be sorted in any particular order
163 for the majority of their lifetime, are simply represented as two
164 bitmaps, one that keeps track of values present in the set, and one
165 that keeps track of expressions present in the set.
167 When we need them in topological order, we produce it on demand by
168 transforming the bitmap into an array and sorting it into topo
169 order. */
171 /* Type of expression, used to know which member of the PRE_EXPR union
172 is valid. */
174 enum pre_expr_kind
176 NAME,
177 NARY,
178 REFERENCE,
179 CONSTANT
182 typedef union pre_expr_union_d
184 tree name;
185 tree constant;
186 vn_nary_op_t nary;
187 vn_reference_t reference;
188 } pre_expr_union;
190 typedef struct pre_expr_d : typed_noop_remove <pre_expr_d>
192 enum pre_expr_kind kind;
193 unsigned int id;
194 pre_expr_union u;
196 /* hash_table support. */
197 typedef pre_expr_d value_type;
198 typedef pre_expr_d compare_type;
199 static inline hashval_t hash (const pre_expr_d *);
200 static inline int equal (const pre_expr_d *, const pre_expr_d *);
201 } *pre_expr;
203 #define PRE_EXPR_NAME(e) (e)->u.name
204 #define PRE_EXPR_NARY(e) (e)->u.nary
205 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
206 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
208 /* Compare E1 and E1 for equality. */
210 inline int
211 pre_expr_d::equal (const value_type *e1, const compare_type *e2)
213 if (e1->kind != e2->kind)
214 return false;
216 switch (e1->kind)
218 case CONSTANT:
219 return vn_constant_eq_with_type (PRE_EXPR_CONSTANT (e1),
220 PRE_EXPR_CONSTANT (e2));
221 case NAME:
222 return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
223 case NARY:
224 return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
225 case REFERENCE:
226 return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
227 PRE_EXPR_REFERENCE (e2));
228 default:
229 gcc_unreachable ();
233 /* Hash E. */
235 inline hashval_t
236 pre_expr_d::hash (const value_type *e)
238 switch (e->kind)
240 case CONSTANT:
241 return vn_hash_constant_with_type (PRE_EXPR_CONSTANT (e));
242 case NAME:
243 return SSA_NAME_VERSION (PRE_EXPR_NAME (e));
244 case NARY:
245 return PRE_EXPR_NARY (e)->hashcode;
246 case REFERENCE:
247 return PRE_EXPR_REFERENCE (e)->hashcode;
248 default:
249 gcc_unreachable ();
253 /* Next global expression id number. */
254 static unsigned int next_expression_id;
256 /* Mapping from expression to id number we can use in bitmap sets. */
257 static vec<pre_expr> expressions;
258 static hash_table<pre_expr_d> *expression_to_id;
259 static vec<unsigned> name_to_id;
261 /* Allocate an expression id for EXPR. */
263 static inline unsigned int
264 alloc_expression_id (pre_expr expr)
266 struct pre_expr_d **slot;
267 /* Make sure we won't overflow. */
268 gcc_assert (next_expression_id + 1 > next_expression_id);
269 expr->id = next_expression_id++;
270 expressions.safe_push (expr);
271 if (expr->kind == NAME)
273 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
274 /* vec::safe_grow_cleared allocates no headroom. Avoid frequent
275 re-allocations by using vec::reserve upfront. */
276 unsigned old_len = name_to_id.length ();
277 name_to_id.reserve (num_ssa_names - old_len);
278 name_to_id.quick_grow_cleared (num_ssa_names);
279 gcc_assert (name_to_id[version] == 0);
280 name_to_id[version] = expr->id;
282 else
284 slot = expression_to_id->find_slot (expr, INSERT);
285 gcc_assert (!*slot);
286 *slot = expr;
288 return next_expression_id - 1;
291 /* Return the expression id for tree EXPR. */
293 static inline unsigned int
294 get_expression_id (const pre_expr expr)
296 return expr->id;
299 static inline unsigned int
300 lookup_expression_id (const pre_expr expr)
302 struct pre_expr_d **slot;
304 if (expr->kind == NAME)
306 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
307 if (name_to_id.length () <= version)
308 return 0;
309 return name_to_id[version];
311 else
313 slot = expression_to_id->find_slot (expr, NO_INSERT);
314 if (!slot)
315 return 0;
316 return ((pre_expr)*slot)->id;
320 /* Return the existing expression id for EXPR, or create one if one
321 does not exist yet. */
323 static inline unsigned int
324 get_or_alloc_expression_id (pre_expr expr)
326 unsigned int id = lookup_expression_id (expr);
327 if (id == 0)
328 return alloc_expression_id (expr);
329 return expr->id = id;
332 /* Return the expression that has expression id ID */
334 static inline pre_expr
335 expression_for_id (unsigned int id)
337 return expressions[id];
340 /* Free the expression id field in all of our expressions,
341 and then destroy the expressions array. */
343 static void
344 clear_expression_ids (void)
346 expressions.release ();
349 static alloc_pool pre_expr_pool;
351 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it. */
353 static pre_expr
354 get_or_alloc_expr_for_name (tree name)
356 struct pre_expr_d expr;
357 pre_expr result;
358 unsigned int result_id;
360 expr.kind = NAME;
361 expr.id = 0;
362 PRE_EXPR_NAME (&expr) = name;
363 result_id = lookup_expression_id (&expr);
364 if (result_id != 0)
365 return expression_for_id (result_id);
367 result = (pre_expr) pool_alloc (pre_expr_pool);
368 result->kind = NAME;
369 PRE_EXPR_NAME (result) = name;
370 alloc_expression_id (result);
371 return result;
374 /* An unordered bitmap set. One bitmap tracks values, the other,
375 expressions. */
376 typedef struct bitmap_set
378 bitmap_head expressions;
379 bitmap_head values;
380 } *bitmap_set_t;
382 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi) \
383 EXECUTE_IF_SET_IN_BITMAP (&(set)->expressions, 0, (id), (bi))
385 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi) \
386 EXECUTE_IF_SET_IN_BITMAP (&(set)->values, 0, (id), (bi))
388 /* Mapping from value id to expressions with that value_id. */
389 static vec<bitmap> value_expressions;
391 /* Sets that we need to keep track of. */
392 typedef struct bb_bitmap_sets
394 /* The EXP_GEN set, which represents expressions/values generated in
395 a basic block. */
396 bitmap_set_t exp_gen;
398 /* The PHI_GEN set, which represents PHI results generated in a
399 basic block. */
400 bitmap_set_t phi_gen;
402 /* The TMP_GEN set, which represents results/temporaries generated
403 in a basic block. IE the LHS of an expression. */
404 bitmap_set_t tmp_gen;
406 /* The AVAIL_OUT set, which represents which values are available in
407 a given basic block. */
408 bitmap_set_t avail_out;
410 /* The ANTIC_IN set, which represents which values are anticipatable
411 in a given basic block. */
412 bitmap_set_t antic_in;
414 /* The PA_IN set, which represents which values are
415 partially anticipatable in a given basic block. */
416 bitmap_set_t pa_in;
418 /* The NEW_SETS set, which is used during insertion to augment the
419 AVAIL_OUT set of blocks with the new insertions performed during
420 the current iteration. */
421 bitmap_set_t new_sets;
423 /* A cache for value_dies_in_block_x. */
424 bitmap expr_dies;
426 /* True if we have visited this block during ANTIC calculation. */
427 unsigned int visited : 1;
429 /* True when the block contains a call that might not return. */
430 unsigned int contains_may_not_return_call : 1;
431 } *bb_value_sets_t;
433 #define EXP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->exp_gen
434 #define PHI_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->phi_gen
435 #define TMP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->tmp_gen
436 #define AVAIL_OUT(BB) ((bb_value_sets_t) ((BB)->aux))->avail_out
437 #define ANTIC_IN(BB) ((bb_value_sets_t) ((BB)->aux))->antic_in
438 #define PA_IN(BB) ((bb_value_sets_t) ((BB)->aux))->pa_in
439 #define NEW_SETS(BB) ((bb_value_sets_t) ((BB)->aux))->new_sets
440 #define EXPR_DIES(BB) ((bb_value_sets_t) ((BB)->aux))->expr_dies
441 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
442 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
445 /* Basic block list in postorder. */
446 static int *postorder;
447 static int postorder_num;
449 /* This structure is used to keep track of statistics on what
450 optimization PRE was able to perform. */
451 static struct
453 /* The number of RHS computations eliminated by PRE. */
454 int eliminations;
456 /* The number of new expressions/temporaries generated by PRE. */
457 int insertions;
459 /* The number of inserts found due to partial anticipation */
460 int pa_insert;
462 /* The number of new PHI nodes added by PRE. */
463 int phis;
464 } pre_stats;
466 static bool do_partial_partial;
467 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
468 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
469 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
470 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
471 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
472 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
473 static void bitmap_insert_into_set_1 (bitmap_set_t, pre_expr,
474 unsigned int, bool);
475 static bitmap_set_t bitmap_set_new (void);
476 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
477 tree);
478 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
479 static unsigned int get_expr_value_id (pre_expr);
481 /* We can add and remove elements and entries to and from sets
482 and hash tables, so we use alloc pools for them. */
484 static alloc_pool bitmap_set_pool;
485 static bitmap_obstack grand_bitmap_obstack;
487 /* Set of blocks with statements that have had their EH properties changed. */
488 static bitmap need_eh_cleanup;
490 /* Set of blocks with statements that have had their AB properties changed. */
491 static bitmap need_ab_cleanup;
493 /* A three tuple {e, pred, v} used to cache phi translations in the
494 phi_translate_table. */
496 typedef struct expr_pred_trans_d : typed_free_remove<expr_pred_trans_d>
498 /* The expression. */
499 pre_expr e;
501 /* The predecessor block along which we translated the expression. */
502 basic_block pred;
504 /* The value that resulted from the translation. */
505 pre_expr v;
507 /* The hashcode for the expression, pred pair. This is cached for
508 speed reasons. */
509 hashval_t hashcode;
511 /* hash_table support. */
512 typedef expr_pred_trans_d value_type;
513 typedef expr_pred_trans_d compare_type;
514 static inline hashval_t hash (const value_type *);
515 static inline int equal (const value_type *, const compare_type *);
516 } *expr_pred_trans_t;
517 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
519 inline hashval_t
520 expr_pred_trans_d::hash (const expr_pred_trans_d *e)
522 return e->hashcode;
525 inline int
526 expr_pred_trans_d::equal (const value_type *ve1,
527 const compare_type *ve2)
529 basic_block b1 = ve1->pred;
530 basic_block b2 = ve2->pred;
532 /* If they are not translations for the same basic block, they can't
533 be equal. */
534 if (b1 != b2)
535 return false;
536 return pre_expr_d::equal (ve1->e, ve2->e);
539 /* The phi_translate_table caches phi translations for a given
540 expression and predecessor. */
541 static hash_table<expr_pred_trans_d> *phi_translate_table;
543 /* Add the tuple mapping from {expression E, basic block PRED} to
544 the phi translation table and return whether it pre-existed. */
546 static inline bool
547 phi_trans_add (expr_pred_trans_t *entry, pre_expr e, basic_block pred)
549 expr_pred_trans_t *slot;
550 expr_pred_trans_d tem;
551 hashval_t hash = iterative_hash_hashval_t (pre_expr_d::hash (e),
552 pred->index);
553 tem.e = e;
554 tem.pred = pred;
555 tem.hashcode = hash;
556 slot = phi_translate_table->find_slot_with_hash (&tem, hash, INSERT);
557 if (*slot)
559 *entry = *slot;
560 return true;
563 *entry = *slot = XNEW (struct expr_pred_trans_d);
564 (*entry)->e = e;
565 (*entry)->pred = pred;
566 (*entry)->hashcode = hash;
567 return false;
571 /* Add expression E to the expression set of value id V. */
573 static void
574 add_to_value (unsigned int v, pre_expr e)
576 bitmap set;
578 gcc_checking_assert (get_expr_value_id (e) == v);
580 if (v >= value_expressions.length ())
582 value_expressions.safe_grow_cleared (v + 1);
585 set = value_expressions[v];
586 if (!set)
588 set = BITMAP_ALLOC (&grand_bitmap_obstack);
589 value_expressions[v] = set;
592 bitmap_set_bit (set, get_or_alloc_expression_id (e));
595 /* Create a new bitmap set and return it. */
597 static bitmap_set_t
598 bitmap_set_new (void)
600 bitmap_set_t ret = (bitmap_set_t) pool_alloc (bitmap_set_pool);
601 bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
602 bitmap_initialize (&ret->values, &grand_bitmap_obstack);
603 return ret;
606 /* Return the value id for a PRE expression EXPR. */
608 static unsigned int
609 get_expr_value_id (pre_expr expr)
611 unsigned int id;
612 switch (expr->kind)
614 case CONSTANT:
615 id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
616 break;
617 case NAME:
618 id = VN_INFO (PRE_EXPR_NAME (expr))->value_id;
619 break;
620 case NARY:
621 id = PRE_EXPR_NARY (expr)->value_id;
622 break;
623 case REFERENCE:
624 id = PRE_EXPR_REFERENCE (expr)->value_id;
625 break;
626 default:
627 gcc_unreachable ();
629 /* ??? We cannot assert that expr has a value-id (it can be 0), because
630 we assign value-ids only to expressions that have a result
631 in set_hashtable_value_ids. */
632 return id;
635 /* Return a SCCVN valnum (SSA name or constant) for the PRE value-id VAL. */
637 static tree
638 sccvn_valnum_from_value_id (unsigned int val)
640 bitmap_iterator bi;
641 unsigned int i;
642 bitmap exprset = value_expressions[val];
643 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
645 pre_expr vexpr = expression_for_id (i);
646 if (vexpr->kind == NAME)
647 return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
648 else if (vexpr->kind == CONSTANT)
649 return PRE_EXPR_CONSTANT (vexpr);
651 return NULL_TREE;
654 /* Remove an expression EXPR from a bitmapped set. */
656 static void
657 bitmap_remove_from_set (bitmap_set_t set, pre_expr expr)
659 unsigned int val = get_expr_value_id (expr);
660 if (!value_id_constant_p (val))
662 bitmap_clear_bit (&set->values, val);
663 bitmap_clear_bit (&set->expressions, get_expression_id (expr));
667 static void
668 bitmap_insert_into_set_1 (bitmap_set_t set, pre_expr expr,
669 unsigned int val, bool allow_constants)
671 if (allow_constants || !value_id_constant_p (val))
673 /* We specifically expect this and only this function to be able to
674 insert constants into a set. */
675 bitmap_set_bit (&set->values, val);
676 bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
680 /* Insert an expression EXPR into a bitmapped set. */
682 static void
683 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
685 bitmap_insert_into_set_1 (set, expr, get_expr_value_id (expr), false);
688 /* Copy a bitmapped set ORIG, into bitmapped set DEST. */
690 static void
691 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
693 bitmap_copy (&dest->expressions, &orig->expressions);
694 bitmap_copy (&dest->values, &orig->values);
698 /* Free memory used up by SET. */
699 static void
700 bitmap_set_free (bitmap_set_t set)
702 bitmap_clear (&set->expressions);
703 bitmap_clear (&set->values);
707 /* Generate an topological-ordered array of bitmap set SET. */
709 static vec<pre_expr>
710 sorted_array_from_bitmap_set (bitmap_set_t set)
712 unsigned int i, j;
713 bitmap_iterator bi, bj;
714 vec<pre_expr> result;
716 /* Pre-allocate enough space for the array. */
717 result.create (bitmap_count_bits (&set->expressions));
719 FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
721 /* The number of expressions having a given value is usually
722 relatively small. Thus, rather than making a vector of all
723 the expressions and sorting it by value-id, we walk the values
724 and check in the reverse mapping that tells us what expressions
725 have a given value, to filter those in our set. As a result,
726 the expressions are inserted in value-id order, which means
727 topological order.
729 If this is somehow a significant lose for some cases, we can
730 choose which set to walk based on the set size. */
731 bitmap exprset = value_expressions[i];
732 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bj)
734 if (bitmap_bit_p (&set->expressions, j))
735 result.quick_push (expression_for_id (j));
739 return result;
742 /* Perform bitmapped set operation DEST &= ORIG. */
744 static void
745 bitmap_set_and (bitmap_set_t dest, bitmap_set_t orig)
747 bitmap_iterator bi;
748 unsigned int i;
750 if (dest != orig)
752 bitmap_head temp;
753 bitmap_initialize (&temp, &grand_bitmap_obstack);
755 bitmap_and_into (&dest->values, &orig->values);
756 bitmap_copy (&temp, &dest->expressions);
757 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
759 pre_expr expr = expression_for_id (i);
760 unsigned int value_id = get_expr_value_id (expr);
761 if (!bitmap_bit_p (&dest->values, value_id))
762 bitmap_clear_bit (&dest->expressions, i);
764 bitmap_clear (&temp);
768 /* Subtract all values and expressions contained in ORIG from DEST. */
770 static bitmap_set_t
771 bitmap_set_subtract (bitmap_set_t dest, bitmap_set_t orig)
773 bitmap_set_t result = bitmap_set_new ();
774 bitmap_iterator bi;
775 unsigned int i;
777 bitmap_and_compl (&result->expressions, &dest->expressions,
778 &orig->expressions);
780 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
782 pre_expr expr = expression_for_id (i);
783 unsigned int value_id = get_expr_value_id (expr);
784 bitmap_set_bit (&result->values, value_id);
787 return result;
790 /* Subtract all the values in bitmap set B from bitmap set A. */
792 static void
793 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
795 unsigned int i;
796 bitmap_iterator bi;
797 bitmap_head temp;
799 bitmap_initialize (&temp, &grand_bitmap_obstack);
801 bitmap_copy (&temp, &a->expressions);
802 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
804 pre_expr expr = expression_for_id (i);
805 if (bitmap_set_contains_value (b, get_expr_value_id (expr)))
806 bitmap_remove_from_set (a, expr);
808 bitmap_clear (&temp);
812 /* Return true if bitmapped set SET contains the value VALUE_ID. */
814 static bool
815 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
817 if (value_id_constant_p (value_id))
818 return true;
820 if (!set || bitmap_empty_p (&set->expressions))
821 return false;
823 return bitmap_bit_p (&set->values, value_id);
826 static inline bool
827 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
829 return bitmap_bit_p (&set->expressions, get_expression_id (expr));
832 /* Replace an instance of value LOOKFOR with expression EXPR in SET. */
834 static void
835 bitmap_set_replace_value (bitmap_set_t set, unsigned int lookfor,
836 const pre_expr expr)
838 bitmap exprset;
839 unsigned int i;
840 bitmap_iterator bi;
842 if (value_id_constant_p (lookfor))
843 return;
845 if (!bitmap_set_contains_value (set, lookfor))
846 return;
848 /* The number of expressions having a given value is usually
849 significantly less than the total number of expressions in SET.
850 Thus, rather than check, for each expression in SET, whether it
851 has the value LOOKFOR, we walk the reverse mapping that tells us
852 what expressions have a given value, and see if any of those
853 expressions are in our set. For large testcases, this is about
854 5-10x faster than walking the bitmap. If this is somehow a
855 significant lose for some cases, we can choose which set to walk
856 based on the set size. */
857 exprset = value_expressions[lookfor];
858 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
860 if (bitmap_clear_bit (&set->expressions, i))
862 bitmap_set_bit (&set->expressions, get_expression_id (expr));
863 return;
867 gcc_unreachable ();
870 /* Return true if two bitmap sets are equal. */
872 static bool
873 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
875 return bitmap_equal_p (&a->values, &b->values);
878 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
879 and add it otherwise. */
881 static void
882 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
884 unsigned int val = get_expr_value_id (expr);
886 if (bitmap_set_contains_value (set, val))
887 bitmap_set_replace_value (set, val, expr);
888 else
889 bitmap_insert_into_set (set, expr);
892 /* Insert EXPR into SET if EXPR's value is not already present in
893 SET. */
895 static void
896 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
898 unsigned int val = get_expr_value_id (expr);
900 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
902 /* Constant values are always considered to be part of the set. */
903 if (value_id_constant_p (val))
904 return;
906 /* If the value membership changed, add the expression. */
907 if (bitmap_set_bit (&set->values, val))
908 bitmap_set_bit (&set->expressions, expr->id);
911 /* Print out EXPR to outfile. */
913 static void
914 print_pre_expr (FILE *outfile, const pre_expr expr)
916 switch (expr->kind)
918 case CONSTANT:
919 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr), 0);
920 break;
921 case NAME:
922 print_generic_expr (outfile, PRE_EXPR_NAME (expr), 0);
923 break;
924 case NARY:
926 unsigned int i;
927 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
928 fprintf (outfile, "{%s,", get_tree_code_name (nary->opcode));
929 for (i = 0; i < nary->length; i++)
931 print_generic_expr (outfile, nary->op[i], 0);
932 if (i != (unsigned) nary->length - 1)
933 fprintf (outfile, ",");
935 fprintf (outfile, "}");
937 break;
939 case REFERENCE:
941 vn_reference_op_t vro;
942 unsigned int i;
943 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
944 fprintf (outfile, "{");
945 for (i = 0;
946 ref->operands.iterate (i, &vro);
947 i++)
949 bool closebrace = false;
950 if (vro->opcode != SSA_NAME
951 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
953 fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
954 if (vro->op0)
956 fprintf (outfile, "<");
957 closebrace = true;
960 if (vro->op0)
962 print_generic_expr (outfile, vro->op0, 0);
963 if (vro->op1)
965 fprintf (outfile, ",");
966 print_generic_expr (outfile, vro->op1, 0);
968 if (vro->op2)
970 fprintf (outfile, ",");
971 print_generic_expr (outfile, vro->op2, 0);
974 if (closebrace)
975 fprintf (outfile, ">");
976 if (i != ref->operands.length () - 1)
977 fprintf (outfile, ",");
979 fprintf (outfile, "}");
980 if (ref->vuse)
982 fprintf (outfile, "@");
983 print_generic_expr (outfile, ref->vuse, 0);
986 break;
989 void debug_pre_expr (pre_expr);
991 /* Like print_pre_expr but always prints to stderr. */
992 DEBUG_FUNCTION void
993 debug_pre_expr (pre_expr e)
995 print_pre_expr (stderr, e);
996 fprintf (stderr, "\n");
999 /* Print out SET to OUTFILE. */
1001 static void
1002 print_bitmap_set (FILE *outfile, bitmap_set_t set,
1003 const char *setname, int blockindex)
1005 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
1006 if (set)
1008 bool first = true;
1009 unsigned i;
1010 bitmap_iterator bi;
1012 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1014 const pre_expr expr = expression_for_id (i);
1016 if (!first)
1017 fprintf (outfile, ", ");
1018 first = false;
1019 print_pre_expr (outfile, expr);
1021 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1024 fprintf (outfile, " }\n");
1027 void debug_bitmap_set (bitmap_set_t);
1029 DEBUG_FUNCTION void
1030 debug_bitmap_set (bitmap_set_t set)
1032 print_bitmap_set (stderr, set, "debug", 0);
1035 void debug_bitmap_sets_for (basic_block);
1037 DEBUG_FUNCTION void
1038 debug_bitmap_sets_for (basic_block bb)
1040 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1041 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1042 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1043 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1044 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1045 if (do_partial_partial)
1046 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1047 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1050 /* Print out the expressions that have VAL to OUTFILE. */
1052 static void
1053 print_value_expressions (FILE *outfile, unsigned int val)
1055 bitmap set = value_expressions[val];
1056 if (set)
1058 bitmap_set x;
1059 char s[10];
1060 sprintf (s, "%04d", val);
1061 x.expressions = *set;
1062 print_bitmap_set (outfile, &x, s, 0);
1067 DEBUG_FUNCTION void
1068 debug_value_expressions (unsigned int val)
1070 print_value_expressions (stderr, val);
1073 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1074 represent it. */
1076 static pre_expr
1077 get_or_alloc_expr_for_constant (tree constant)
1079 unsigned int result_id;
1080 unsigned int value_id;
1081 struct pre_expr_d expr;
1082 pre_expr newexpr;
1084 expr.kind = CONSTANT;
1085 PRE_EXPR_CONSTANT (&expr) = constant;
1086 result_id = lookup_expression_id (&expr);
1087 if (result_id != 0)
1088 return expression_for_id (result_id);
1090 newexpr = (pre_expr) pool_alloc (pre_expr_pool);
1091 newexpr->kind = CONSTANT;
1092 PRE_EXPR_CONSTANT (newexpr) = constant;
1093 alloc_expression_id (newexpr);
1094 value_id = get_or_alloc_constant_value_id (constant);
1095 add_to_value (value_id, newexpr);
1096 return newexpr;
1099 /* Given a value id V, find the actual tree representing the constant
1100 value if there is one, and return it. Return NULL if we can't find
1101 a constant. */
1103 static tree
1104 get_constant_for_value_id (unsigned int v)
1106 if (value_id_constant_p (v))
1108 unsigned int i;
1109 bitmap_iterator bi;
1110 bitmap exprset = value_expressions[v];
1112 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1114 pre_expr expr = expression_for_id (i);
1115 if (expr->kind == CONSTANT)
1116 return PRE_EXPR_CONSTANT (expr);
1119 return NULL;
1122 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1123 Currently only supports constants and SSA_NAMES. */
1124 static pre_expr
1125 get_or_alloc_expr_for (tree t)
1127 if (TREE_CODE (t) == SSA_NAME)
1128 return get_or_alloc_expr_for_name (t);
1129 else if (is_gimple_min_invariant (t))
1130 return get_or_alloc_expr_for_constant (t);
1131 else
1133 /* More complex expressions can result from SCCVN expression
1134 simplification that inserts values for them. As they all
1135 do not have VOPs the get handled by the nary ops struct. */
1136 vn_nary_op_t result;
1137 unsigned int result_id;
1138 vn_nary_op_lookup (t, &result);
1139 if (result != NULL)
1141 pre_expr e = (pre_expr) pool_alloc (pre_expr_pool);
1142 e->kind = NARY;
1143 PRE_EXPR_NARY (e) = result;
1144 result_id = lookup_expression_id (e);
1145 if (result_id != 0)
1147 pool_free (pre_expr_pool, e);
1148 e = expression_for_id (result_id);
1149 return e;
1151 alloc_expression_id (e);
1152 return e;
1155 return NULL;
1158 /* Return the folded version of T if T, when folded, is a gimple
1159 min_invariant. Otherwise, return T. */
1161 static pre_expr
1162 fully_constant_expression (pre_expr e)
1164 switch (e->kind)
1166 case CONSTANT:
1167 return e;
1168 case NARY:
1170 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1171 switch (TREE_CODE_CLASS (nary->opcode))
1173 case tcc_binary:
1174 case tcc_comparison:
1176 /* We have to go from trees to pre exprs to value ids to
1177 constants. */
1178 tree naryop0 = nary->op[0];
1179 tree naryop1 = nary->op[1];
1180 tree result;
1181 if (!is_gimple_min_invariant (naryop0))
1183 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1184 unsigned int vrep0 = get_expr_value_id (rep0);
1185 tree const0 = get_constant_for_value_id (vrep0);
1186 if (const0)
1187 naryop0 = fold_convert (TREE_TYPE (naryop0), const0);
1189 if (!is_gimple_min_invariant (naryop1))
1191 pre_expr rep1 = get_or_alloc_expr_for (naryop1);
1192 unsigned int vrep1 = get_expr_value_id (rep1);
1193 tree const1 = get_constant_for_value_id (vrep1);
1194 if (const1)
1195 naryop1 = fold_convert (TREE_TYPE (naryop1), const1);
1197 result = fold_binary (nary->opcode, nary->type,
1198 naryop0, naryop1);
1199 if (result && is_gimple_min_invariant (result))
1200 return get_or_alloc_expr_for_constant (result);
1201 /* We might have simplified the expression to a
1202 SSA_NAME for example from x_1 * 1. But we cannot
1203 insert a PHI for x_1 unconditionally as x_1 might
1204 not be available readily. */
1205 return e;
1207 case tcc_reference:
1208 if (nary->opcode != REALPART_EXPR
1209 && nary->opcode != IMAGPART_EXPR
1210 && nary->opcode != VIEW_CONVERT_EXPR)
1211 return e;
1212 /* Fallthrough. */
1213 case tcc_unary:
1215 /* We have to go from trees to pre exprs to value ids to
1216 constants. */
1217 tree naryop0 = nary->op[0];
1218 tree const0, result;
1219 if (is_gimple_min_invariant (naryop0))
1220 const0 = naryop0;
1221 else
1223 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1224 unsigned int vrep0 = get_expr_value_id (rep0);
1225 const0 = get_constant_for_value_id (vrep0);
1227 result = NULL;
1228 if (const0)
1230 tree type1 = TREE_TYPE (nary->op[0]);
1231 const0 = fold_convert (type1, const0);
1232 result = fold_unary (nary->opcode, nary->type, const0);
1234 if (result && is_gimple_min_invariant (result))
1235 return get_or_alloc_expr_for_constant (result);
1236 return e;
1238 default:
1239 return e;
1242 case REFERENCE:
1244 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1245 tree folded;
1246 if ((folded = fully_constant_vn_reference_p (ref)))
1247 return get_or_alloc_expr_for_constant (folded);
1248 return e;
1250 default:
1251 return e;
1253 return e;
1256 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1257 it has the value it would have in BLOCK. Set *SAME_VALID to true
1258 in case the new vuse doesn't change the value id of the OPERANDS. */
1260 static tree
1261 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1262 alias_set_type set, tree type, tree vuse,
1263 basic_block phiblock,
1264 basic_block block, bool *same_valid)
1266 gimple phi = SSA_NAME_DEF_STMT (vuse);
1267 ao_ref ref;
1268 edge e = NULL;
1269 bool use_oracle;
1271 *same_valid = true;
1273 if (gimple_bb (phi) != phiblock)
1274 return vuse;
1276 use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1278 /* Use the alias-oracle to find either the PHI node in this block,
1279 the first VUSE used in this block that is equivalent to vuse or
1280 the first VUSE which definition in this block kills the value. */
1281 if (gimple_code (phi) == GIMPLE_PHI)
1282 e = find_edge (block, phiblock);
1283 else if (use_oracle)
1284 while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1286 vuse = gimple_vuse (phi);
1287 phi = SSA_NAME_DEF_STMT (vuse);
1288 if (gimple_bb (phi) != phiblock)
1289 return vuse;
1290 if (gimple_code (phi) == GIMPLE_PHI)
1292 e = find_edge (block, phiblock);
1293 break;
1296 else
1297 return NULL_TREE;
1299 if (e)
1301 if (use_oracle)
1303 bitmap visited = NULL;
1304 unsigned int cnt;
1305 /* Try to find a vuse that dominates this phi node by skipping
1306 non-clobbering statements. */
1307 vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false,
1308 NULL, NULL);
1309 if (visited)
1310 BITMAP_FREE (visited);
1312 else
1313 vuse = NULL_TREE;
1314 if (!vuse)
1316 /* If we didn't find any, the value ID can't stay the same,
1317 but return the translated vuse. */
1318 *same_valid = false;
1319 vuse = PHI_ARG_DEF (phi, e->dest_idx);
1321 /* ??? We would like to return vuse here as this is the canonical
1322 upmost vdef that this reference is associated with. But during
1323 insertion of the references into the hash tables we only ever
1324 directly insert with their direct gimple_vuse, hence returning
1325 something else would make us not find the other expression. */
1326 return PHI_ARG_DEF (phi, e->dest_idx);
1329 return NULL_TREE;
1332 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1333 SET2. This is used to avoid making a set consisting of the union
1334 of PA_IN and ANTIC_IN during insert. */
1336 static inline pre_expr
1337 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2)
1339 pre_expr result;
1341 result = bitmap_find_leader (set1, val);
1342 if (!result && set2)
1343 result = bitmap_find_leader (set2, val);
1344 return result;
1347 /* Get the tree type for our PRE expression e. */
1349 static tree
1350 get_expr_type (const pre_expr e)
1352 switch (e->kind)
1354 case NAME:
1355 return TREE_TYPE (PRE_EXPR_NAME (e));
1356 case CONSTANT:
1357 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1358 case REFERENCE:
1359 return PRE_EXPR_REFERENCE (e)->type;
1360 case NARY:
1361 return PRE_EXPR_NARY (e)->type;
1363 gcc_unreachable ();
1366 /* Get a representative SSA_NAME for a given expression.
1367 Since all of our sub-expressions are treated as values, we require
1368 them to be SSA_NAME's for simplicity.
1369 Prior versions of GVNPRE used to use "value handles" here, so that
1370 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1371 either case, the operands are really values (IE we do not expect
1372 them to be usable without finding leaders). */
1374 static tree
1375 get_representative_for (const pre_expr e)
1377 tree name;
1378 unsigned int value_id = get_expr_value_id (e);
1380 switch (e->kind)
1382 case NAME:
1383 return PRE_EXPR_NAME (e);
1384 case CONSTANT:
1385 return PRE_EXPR_CONSTANT (e);
1386 case NARY:
1387 case REFERENCE:
1389 /* Go through all of the expressions representing this value
1390 and pick out an SSA_NAME. */
1391 unsigned int i;
1392 bitmap_iterator bi;
1393 bitmap exprs = value_expressions[value_id];
1394 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1396 pre_expr rep = expression_for_id (i);
1397 if (rep->kind == NAME)
1398 return PRE_EXPR_NAME (rep);
1399 else if (rep->kind == CONSTANT)
1400 return PRE_EXPR_CONSTANT (rep);
1403 break;
1406 /* If we reached here we couldn't find an SSA_NAME. This can
1407 happen when we've discovered a value that has never appeared in
1408 the program as set to an SSA_NAME, as the result of phi translation.
1409 Create one here.
1410 ??? We should be able to re-use this when we insert the statement
1411 to compute it. */
1412 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1413 VN_INFO_GET (name)->value_id = value_id;
1414 VN_INFO (name)->valnum = name;
1415 /* ??? For now mark this SSA name for release by SCCVN. */
1416 VN_INFO (name)->needs_insertion = true;
1417 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1418 if (dump_file && (dump_flags & TDF_DETAILS))
1420 fprintf (dump_file, "Created SSA_NAME representative ");
1421 print_generic_expr (dump_file, name, 0);
1422 fprintf (dump_file, " for expression:");
1423 print_pre_expr (dump_file, e);
1424 fprintf (dump_file, " (%04d)\n", value_id);
1427 return name;
1432 static pre_expr
1433 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1434 basic_block pred, basic_block phiblock);
1436 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1437 the phis in PRED. Return NULL if we can't find a leader for each part
1438 of the translated expression. */
1440 static pre_expr
1441 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1442 basic_block pred, basic_block phiblock)
1444 switch (expr->kind)
1446 case NARY:
1448 unsigned int i;
1449 bool changed = false;
1450 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1451 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1452 sizeof_vn_nary_op (nary->length));
1453 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1455 for (i = 0; i < newnary->length; i++)
1457 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1458 continue;
1459 else
1461 pre_expr leader, result;
1462 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1463 leader = find_leader_in_sets (op_val_id, set1, set2);
1464 result = phi_translate (leader, set1, set2, pred, phiblock);
1465 if (result && result != leader)
1467 tree name = get_representative_for (result);
1468 if (!name)
1469 return NULL;
1470 newnary->op[i] = name;
1472 else if (!result)
1473 return NULL;
1475 changed |= newnary->op[i] != nary->op[i];
1478 if (changed)
1480 pre_expr constant;
1481 unsigned int new_val_id;
1483 tree result = vn_nary_op_lookup_pieces (newnary->length,
1484 newnary->opcode,
1485 newnary->type,
1486 &newnary->op[0],
1487 &nary);
1488 if (result && is_gimple_min_invariant (result))
1489 return get_or_alloc_expr_for_constant (result);
1491 expr = (pre_expr) pool_alloc (pre_expr_pool);
1492 expr->kind = NARY;
1493 expr->id = 0;
1494 if (nary)
1496 PRE_EXPR_NARY (expr) = nary;
1497 constant = fully_constant_expression (expr);
1498 if (constant != expr)
1499 return constant;
1501 new_val_id = nary->value_id;
1502 get_or_alloc_expression_id (expr);
1504 else
1506 new_val_id = get_next_value_id ();
1507 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
1508 nary = vn_nary_op_insert_pieces (newnary->length,
1509 newnary->opcode,
1510 newnary->type,
1511 &newnary->op[0],
1512 result, new_val_id);
1513 PRE_EXPR_NARY (expr) = nary;
1514 constant = fully_constant_expression (expr);
1515 if (constant != expr)
1516 return constant;
1517 get_or_alloc_expression_id (expr);
1519 add_to_value (new_val_id, expr);
1521 return expr;
1523 break;
1525 case REFERENCE:
1527 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1528 vec<vn_reference_op_s> operands = ref->operands;
1529 tree vuse = ref->vuse;
1530 tree newvuse = vuse;
1531 vec<vn_reference_op_s> newoperands = vNULL;
1532 bool changed = false, same_valid = true;
1533 unsigned int i, n;
1534 vn_reference_op_t operand;
1535 vn_reference_t newref;
1537 for (i = 0; operands.iterate (i, &operand); i++)
1539 pre_expr opresult;
1540 pre_expr leader;
1541 tree op[3];
1542 tree type = operand->type;
1543 vn_reference_op_s newop = *operand;
1544 op[0] = operand->op0;
1545 op[1] = operand->op1;
1546 op[2] = operand->op2;
1547 for (n = 0; n < 3; ++n)
1549 unsigned int op_val_id;
1550 if (!op[n])
1551 continue;
1552 if (TREE_CODE (op[n]) != SSA_NAME)
1554 /* We can't possibly insert these. */
1555 if (n != 0
1556 && !is_gimple_min_invariant (op[n]))
1557 break;
1558 continue;
1560 op_val_id = VN_INFO (op[n])->value_id;
1561 leader = find_leader_in_sets (op_val_id, set1, set2);
1562 if (!leader)
1563 break;
1564 opresult = phi_translate (leader, set1, set2, pred, phiblock);
1565 if (!opresult)
1566 break;
1567 if (opresult != leader)
1569 tree name = get_representative_for (opresult);
1570 if (!name)
1571 break;
1572 changed |= name != op[n];
1573 op[n] = name;
1576 if (n != 3)
1578 newoperands.release ();
1579 return NULL;
1581 if (!changed)
1582 continue;
1583 if (!newoperands.exists ())
1584 newoperands = operands.copy ();
1585 /* We may have changed from an SSA_NAME to a constant */
1586 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1587 newop.opcode = TREE_CODE (op[0]);
1588 newop.type = type;
1589 newop.op0 = op[0];
1590 newop.op1 = op[1];
1591 newop.op2 = op[2];
1592 newoperands[i] = newop;
1594 gcc_checking_assert (i == operands.length ());
1596 if (vuse)
1598 newvuse = translate_vuse_through_block (newoperands.exists ()
1599 ? newoperands : operands,
1600 ref->set, ref->type,
1601 vuse, phiblock, pred,
1602 &same_valid);
1603 if (newvuse == NULL_TREE)
1605 newoperands.release ();
1606 return NULL;
1610 if (changed || newvuse != vuse)
1612 unsigned int new_val_id;
1613 pre_expr constant;
1615 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1616 ref->type,
1617 newoperands.exists ()
1618 ? newoperands : operands,
1619 &newref, VN_WALK);
1620 if (result)
1621 newoperands.release ();
1623 /* We can always insert constants, so if we have a partial
1624 redundant constant load of another type try to translate it
1625 to a constant of appropriate type. */
1626 if (result && is_gimple_min_invariant (result))
1628 tree tem = result;
1629 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1631 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1632 if (tem && !is_gimple_min_invariant (tem))
1633 tem = NULL_TREE;
1635 if (tem)
1636 return get_or_alloc_expr_for_constant (tem);
1639 /* If we'd have to convert things we would need to validate
1640 if we can insert the translated expression. So fail
1641 here for now - we cannot insert an alias with a different
1642 type in the VN tables either, as that would assert. */
1643 if (result
1644 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1645 return NULL;
1646 else if (!result && newref
1647 && !useless_type_conversion_p (ref->type, newref->type))
1649 newoperands.release ();
1650 return NULL;
1653 expr = (pre_expr) pool_alloc (pre_expr_pool);
1654 expr->kind = REFERENCE;
1655 expr->id = 0;
1657 if (newref)
1659 PRE_EXPR_REFERENCE (expr) = newref;
1660 constant = fully_constant_expression (expr);
1661 if (constant != expr)
1662 return constant;
1664 new_val_id = newref->value_id;
1665 get_or_alloc_expression_id (expr);
1667 else
1669 if (changed || !same_valid)
1671 new_val_id = get_next_value_id ();
1672 value_expressions.safe_grow_cleared
1673 (get_max_value_id () + 1);
1675 else
1676 new_val_id = ref->value_id;
1677 if (!newoperands.exists ())
1678 newoperands = operands.copy ();
1679 newref = vn_reference_insert_pieces (newvuse, ref->set,
1680 ref->type,
1681 newoperands,
1682 result, new_val_id);
1683 newoperands = vNULL;
1684 PRE_EXPR_REFERENCE (expr) = newref;
1685 constant = fully_constant_expression (expr);
1686 if (constant != expr)
1687 return constant;
1688 get_or_alloc_expression_id (expr);
1690 add_to_value (new_val_id, expr);
1692 newoperands.release ();
1693 return expr;
1695 break;
1697 case NAME:
1699 tree name = PRE_EXPR_NAME (expr);
1700 gimple def_stmt = SSA_NAME_DEF_STMT (name);
1701 /* If the SSA name is defined by a PHI node in this block,
1702 translate it. */
1703 if (gimple_code (def_stmt) == GIMPLE_PHI
1704 && gimple_bb (def_stmt) == phiblock)
1706 edge e = find_edge (pred, gimple_bb (def_stmt));
1707 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1709 /* Handle constant. */
1710 if (is_gimple_min_invariant (def))
1711 return get_or_alloc_expr_for_constant (def);
1713 return get_or_alloc_expr_for_name (def);
1715 /* Otherwise return it unchanged - it will get removed if its
1716 value is not available in PREDs AVAIL_OUT set of expressions
1717 by the subtraction of TMP_GEN. */
1718 return expr;
1721 default:
1722 gcc_unreachable ();
1726 /* Wrapper around phi_translate_1 providing caching functionality. */
1728 static pre_expr
1729 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1730 basic_block pred, basic_block phiblock)
1732 expr_pred_trans_t slot = NULL;
1733 pre_expr phitrans;
1735 if (!expr)
1736 return NULL;
1738 /* Constants contain no values that need translation. */
1739 if (expr->kind == CONSTANT)
1740 return expr;
1742 if (value_id_constant_p (get_expr_value_id (expr)))
1743 return expr;
1745 /* Don't add translations of NAMEs as those are cheap to translate. */
1746 if (expr->kind != NAME)
1748 if (phi_trans_add (&slot, expr, pred))
1749 return slot->v;
1750 /* Store NULL for the value we want to return in the case of
1751 recursing. */
1752 slot->v = NULL;
1755 /* Translate. */
1756 phitrans = phi_translate_1 (expr, set1, set2, pred, phiblock);
1758 if (slot)
1760 if (phitrans)
1761 slot->v = phitrans;
1762 else
1763 /* Remove failed translations again, they cause insert
1764 iteration to not pick up new opportunities reliably. */
1765 phi_translate_table->remove_elt_with_hash (slot, slot->hashcode);
1768 return phitrans;
1772 /* For each expression in SET, translate the values through phi nodes
1773 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1774 expressions in DEST. */
1776 static void
1777 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1778 basic_block phiblock)
1780 vec<pre_expr> exprs;
1781 pre_expr expr;
1782 int i;
1784 if (gimple_seq_empty_p (phi_nodes (phiblock)))
1786 bitmap_set_copy (dest, set);
1787 return;
1790 exprs = sorted_array_from_bitmap_set (set);
1791 FOR_EACH_VEC_ELT (exprs, i, expr)
1793 pre_expr translated;
1794 translated = phi_translate (expr, set, NULL, pred, phiblock);
1795 if (!translated)
1796 continue;
1798 /* We might end up with multiple expressions from SET being
1799 translated to the same value. In this case we do not want
1800 to retain the NARY or REFERENCE expression but prefer a NAME
1801 which would be the leader. */
1802 if (translated->kind == NAME)
1803 bitmap_value_replace_in_set (dest, translated);
1804 else
1805 bitmap_value_insert_into_set (dest, translated);
1807 exprs.release ();
1810 /* Find the leader for a value (i.e., the name representing that
1811 value) in a given set, and return it. Return NULL if no leader
1812 is found. */
1814 static pre_expr
1815 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1817 if (value_id_constant_p (val))
1819 unsigned int i;
1820 bitmap_iterator bi;
1821 bitmap exprset = value_expressions[val];
1823 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1825 pre_expr expr = expression_for_id (i);
1826 if (expr->kind == CONSTANT)
1827 return expr;
1830 if (bitmap_set_contains_value (set, val))
1832 /* Rather than walk the entire bitmap of expressions, and see
1833 whether any of them has the value we are looking for, we look
1834 at the reverse mapping, which tells us the set of expressions
1835 that have a given value (IE value->expressions with that
1836 value) and see if any of those expressions are in our set.
1837 The number of expressions per value is usually significantly
1838 less than the number of expressions in the set. In fact, for
1839 large testcases, doing it this way is roughly 5-10x faster
1840 than walking the bitmap.
1841 If this is somehow a significant lose for some cases, we can
1842 choose which set to walk based on which set is smaller. */
1843 unsigned int i;
1844 bitmap_iterator bi;
1845 bitmap exprset = value_expressions[val];
1847 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1848 return expression_for_id (i);
1850 return NULL;
1853 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1854 BLOCK by seeing if it is not killed in the block. Note that we are
1855 only determining whether there is a store that kills it. Because
1856 of the order in which clean iterates over values, we are guaranteed
1857 that altered operands will have caused us to be eliminated from the
1858 ANTIC_IN set already. */
1860 static bool
1861 value_dies_in_block_x (pre_expr expr, basic_block block)
1863 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1864 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1865 gimple def;
1866 gimple_stmt_iterator gsi;
1867 unsigned id = get_expression_id (expr);
1868 bool res = false;
1869 ao_ref ref;
1871 if (!vuse)
1872 return false;
1874 /* Lookup a previously calculated result. */
1875 if (EXPR_DIES (block)
1876 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1877 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1879 /* A memory expression {e, VUSE} dies in the block if there is a
1880 statement that may clobber e. If, starting statement walk from the
1881 top of the basic block, a statement uses VUSE there can be no kill
1882 inbetween that use and the original statement that loaded {e, VUSE},
1883 so we can stop walking. */
1884 ref.base = NULL_TREE;
1885 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1887 tree def_vuse, def_vdef;
1888 def = gsi_stmt (gsi);
1889 def_vuse = gimple_vuse (def);
1890 def_vdef = gimple_vdef (def);
1892 /* Not a memory statement. */
1893 if (!def_vuse)
1894 continue;
1896 /* Not a may-def. */
1897 if (!def_vdef)
1899 /* A load with the same VUSE, we're done. */
1900 if (def_vuse == vuse)
1901 break;
1903 continue;
1906 /* Init ref only if we really need it. */
1907 if (ref.base == NULL_TREE
1908 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1909 refx->operands))
1911 res = true;
1912 break;
1914 /* If the statement may clobber expr, it dies. */
1915 if (stmt_may_clobber_ref_p_1 (def, &ref))
1917 res = true;
1918 break;
1922 /* Remember the result. */
1923 if (!EXPR_DIES (block))
1924 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1925 bitmap_set_bit (EXPR_DIES (block), id * 2);
1926 if (res)
1927 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1929 return res;
1933 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1934 contains its value-id. */
1936 static bool
1937 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1939 if (op && TREE_CODE (op) == SSA_NAME)
1941 unsigned int value_id = VN_INFO (op)->value_id;
1942 if (!(bitmap_set_contains_value (set1, value_id)
1943 || (set2 && bitmap_set_contains_value (set2, value_id))))
1944 return false;
1946 return true;
1949 /* Determine if the expression EXPR is valid in SET1 U SET2.
1950 ONLY SET2 CAN BE NULL.
1951 This means that we have a leader for each part of the expression
1952 (if it consists of values), or the expression is an SSA_NAME.
1953 For loads/calls, we also see if the vuse is killed in this block. */
1955 static bool
1956 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr)
1958 switch (expr->kind)
1960 case NAME:
1961 /* By construction all NAMEs are available. Non-available
1962 NAMEs are removed by subtracting TMP_GEN from the sets. */
1963 return true;
1964 case NARY:
1966 unsigned int i;
1967 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1968 for (i = 0; i < nary->length; i++)
1969 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1970 return false;
1971 return true;
1973 break;
1974 case REFERENCE:
1976 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1977 vn_reference_op_t vro;
1978 unsigned int i;
1980 FOR_EACH_VEC_ELT (ref->operands, i, vro)
1982 if (!op_valid_in_sets (set1, set2, vro->op0)
1983 || !op_valid_in_sets (set1, set2, vro->op1)
1984 || !op_valid_in_sets (set1, set2, vro->op2))
1985 return false;
1987 return true;
1989 default:
1990 gcc_unreachable ();
1994 /* Clean the set of expressions that are no longer valid in SET1 or
1995 SET2. This means expressions that are made up of values we have no
1996 leaders for in SET1 or SET2. This version is used for partial
1997 anticipation, which means it is not valid in either ANTIC_IN or
1998 PA_IN. */
2000 static void
2001 dependent_clean (bitmap_set_t set1, bitmap_set_t set2)
2003 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
2004 pre_expr expr;
2005 int i;
2007 FOR_EACH_VEC_ELT (exprs, i, expr)
2009 if (!valid_in_sets (set1, set2, expr))
2010 bitmap_remove_from_set (set1, expr);
2012 exprs.release ();
2015 /* Clean the set of expressions that are no longer valid in SET. This
2016 means expressions that are made up of values we have no leaders for
2017 in SET. */
2019 static void
2020 clean (bitmap_set_t set)
2022 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set);
2023 pre_expr expr;
2024 int i;
2026 FOR_EACH_VEC_ELT (exprs, i, expr)
2028 if (!valid_in_sets (set, NULL, expr))
2029 bitmap_remove_from_set (set, expr);
2031 exprs.release ();
2034 /* Clean the set of expressions that are no longer valid in SET because
2035 they are clobbered in BLOCK or because they trap and may not be executed. */
2037 static void
2038 prune_clobbered_mems (bitmap_set_t set, basic_block block)
2040 bitmap_iterator bi;
2041 unsigned i;
2043 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2045 pre_expr expr = expression_for_id (i);
2046 if (expr->kind == REFERENCE)
2048 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2049 if (ref->vuse)
2051 gimple def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
2052 if (!gimple_nop_p (def_stmt)
2053 && ((gimple_bb (def_stmt) != block
2054 && !dominated_by_p (CDI_DOMINATORS,
2055 block, gimple_bb (def_stmt)))
2056 || (gimple_bb (def_stmt) == block
2057 && value_dies_in_block_x (expr, block))))
2058 bitmap_remove_from_set (set, expr);
2061 else if (expr->kind == NARY)
2063 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2064 /* If the NARY may trap make sure the block does not contain
2065 a possible exit point.
2066 ??? This is overly conservative if we translate AVAIL_OUT
2067 as the available expression might be after the exit point. */
2068 if (BB_MAY_NOTRETURN (block)
2069 && vn_nary_may_trap (nary))
2070 bitmap_remove_from_set (set, expr);
2075 static sbitmap has_abnormal_preds;
2077 /* List of blocks that may have changed during ANTIC computation and
2078 thus need to be iterated over. */
2080 static sbitmap changed_blocks;
2082 /* Compute the ANTIC set for BLOCK.
2084 If succs(BLOCK) > 1 then
2085 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2086 else if succs(BLOCK) == 1 then
2087 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2089 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2092 static bool
2093 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2095 bool changed = false;
2096 bitmap_set_t S, old, ANTIC_OUT;
2097 bitmap_iterator bi;
2098 unsigned int bii;
2099 edge e;
2100 edge_iterator ei;
2102 old = ANTIC_OUT = S = NULL;
2103 BB_VISITED (block) = 1;
2105 /* If any edges from predecessors are abnormal, antic_in is empty,
2106 so do nothing. */
2107 if (block_has_abnormal_pred_edge)
2108 goto maybe_dump_sets;
2110 old = ANTIC_IN (block);
2111 ANTIC_OUT = bitmap_set_new ();
2113 /* If the block has no successors, ANTIC_OUT is empty. */
2114 if (EDGE_COUNT (block->succs) == 0)
2116 /* If we have one successor, we could have some phi nodes to
2117 translate through. */
2118 else if (single_succ_p (block))
2120 basic_block succ_bb = single_succ (block);
2121 gcc_assert (BB_VISITED (succ_bb));
2122 phi_translate_set (ANTIC_OUT, ANTIC_IN (succ_bb), block, succ_bb);
2124 /* If we have multiple successors, we take the intersection of all of
2125 them. Note that in the case of loop exit phi nodes, we may have
2126 phis to translate through. */
2127 else
2129 size_t i;
2130 basic_block bprime, first = NULL;
2132 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2133 FOR_EACH_EDGE (e, ei, block->succs)
2135 if (!first
2136 && BB_VISITED (e->dest))
2137 first = e->dest;
2138 else if (BB_VISITED (e->dest))
2139 worklist.quick_push (e->dest);
2142 /* Of multiple successors we have to have visited one already
2143 which is guaranteed by iteration order. */
2144 gcc_assert (first != NULL);
2146 phi_translate_set (ANTIC_OUT, ANTIC_IN (first), block, first);
2148 FOR_EACH_VEC_ELT (worklist, i, bprime)
2150 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2152 bitmap_set_t tmp = bitmap_set_new ();
2153 phi_translate_set (tmp, ANTIC_IN (bprime), block, bprime);
2154 bitmap_set_and (ANTIC_OUT, tmp);
2155 bitmap_set_free (tmp);
2157 else
2158 bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2162 /* Prune expressions that are clobbered in block and thus become
2163 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2164 prune_clobbered_mems (ANTIC_OUT, block);
2166 /* Generate ANTIC_OUT - TMP_GEN. */
2167 S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2169 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2170 ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2171 TMP_GEN (block));
2173 /* Then union in the ANTIC_OUT - TMP_GEN values,
2174 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2175 FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2176 bitmap_value_insert_into_set (ANTIC_IN (block),
2177 expression_for_id (bii));
2179 clean (ANTIC_IN (block));
2181 if (!bitmap_set_equal (old, ANTIC_IN (block)))
2183 changed = true;
2184 bitmap_set_bit (changed_blocks, block->index);
2185 FOR_EACH_EDGE (e, ei, block->preds)
2186 bitmap_set_bit (changed_blocks, e->src->index);
2188 else
2189 bitmap_clear_bit (changed_blocks, block->index);
2191 maybe_dump_sets:
2192 if (dump_file && (dump_flags & TDF_DETAILS))
2194 if (ANTIC_OUT)
2195 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2197 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2198 block->index);
2200 if (S)
2201 print_bitmap_set (dump_file, S, "S", block->index);
2203 if (old)
2204 bitmap_set_free (old);
2205 if (S)
2206 bitmap_set_free (S);
2207 if (ANTIC_OUT)
2208 bitmap_set_free (ANTIC_OUT);
2209 return changed;
2212 /* Compute PARTIAL_ANTIC for BLOCK.
2214 If succs(BLOCK) > 1 then
2215 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2216 in ANTIC_OUT for all succ(BLOCK)
2217 else if succs(BLOCK) == 1 then
2218 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2220 PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2221 - ANTIC_IN[BLOCK])
2224 static bool
2225 compute_partial_antic_aux (basic_block block,
2226 bool block_has_abnormal_pred_edge)
2228 bool changed = false;
2229 bitmap_set_t old_PA_IN;
2230 bitmap_set_t PA_OUT;
2231 edge e;
2232 edge_iterator ei;
2233 unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2235 old_PA_IN = PA_OUT = NULL;
2237 /* If any edges from predecessors are abnormal, antic_in is empty,
2238 so do nothing. */
2239 if (block_has_abnormal_pred_edge)
2240 goto maybe_dump_sets;
2242 /* If there are too many partially anticipatable values in the
2243 block, phi_translate_set can take an exponential time: stop
2244 before the translation starts. */
2245 if (max_pa
2246 && single_succ_p (block)
2247 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2248 goto maybe_dump_sets;
2250 old_PA_IN = PA_IN (block);
2251 PA_OUT = bitmap_set_new ();
2253 /* If the block has no successors, ANTIC_OUT is empty. */
2254 if (EDGE_COUNT (block->succs) == 0)
2256 /* If we have one successor, we could have some phi nodes to
2257 translate through. Note that we can't phi translate across DFS
2258 back edges in partial antic, because it uses a union operation on
2259 the successors. For recurrences like IV's, we will end up
2260 generating a new value in the set on each go around (i + 3 (VH.1)
2261 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2262 else if (single_succ_p (block))
2264 basic_block succ = single_succ (block);
2265 if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2266 phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2268 /* If we have multiple successors, we take the union of all of
2269 them. */
2270 else
2272 size_t i;
2273 basic_block bprime;
2275 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2276 FOR_EACH_EDGE (e, ei, block->succs)
2278 if (e->flags & EDGE_DFS_BACK)
2279 continue;
2280 worklist.quick_push (e->dest);
2282 if (worklist.length () > 0)
2284 FOR_EACH_VEC_ELT (worklist, i, bprime)
2286 unsigned int i;
2287 bitmap_iterator bi;
2289 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2290 bitmap_value_insert_into_set (PA_OUT,
2291 expression_for_id (i));
2292 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2294 bitmap_set_t pa_in = bitmap_set_new ();
2295 phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2296 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2297 bitmap_value_insert_into_set (PA_OUT,
2298 expression_for_id (i));
2299 bitmap_set_free (pa_in);
2301 else
2302 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2303 bitmap_value_insert_into_set (PA_OUT,
2304 expression_for_id (i));
2309 /* Prune expressions that are clobbered in block and thus become
2310 invalid if translated from PA_OUT to PA_IN. */
2311 prune_clobbered_mems (PA_OUT, block);
2313 /* PA_IN starts with PA_OUT - TMP_GEN.
2314 Then we subtract things from ANTIC_IN. */
2315 PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2317 /* For partial antic, we want to put back in the phi results, since
2318 we will properly avoid making them partially antic over backedges. */
2319 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2320 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2322 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2323 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2325 dependent_clean (PA_IN (block), ANTIC_IN (block));
2327 if (!bitmap_set_equal (old_PA_IN, PA_IN (block)))
2329 changed = true;
2330 bitmap_set_bit (changed_blocks, block->index);
2331 FOR_EACH_EDGE (e, ei, block->preds)
2332 bitmap_set_bit (changed_blocks, e->src->index);
2334 else
2335 bitmap_clear_bit (changed_blocks, block->index);
2337 maybe_dump_sets:
2338 if (dump_file && (dump_flags & TDF_DETAILS))
2340 if (PA_OUT)
2341 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2343 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2345 if (old_PA_IN)
2346 bitmap_set_free (old_PA_IN);
2347 if (PA_OUT)
2348 bitmap_set_free (PA_OUT);
2349 return changed;
2352 /* Compute ANTIC and partial ANTIC sets. */
2354 static void
2355 compute_antic (void)
2357 bool changed = true;
2358 int num_iterations = 0;
2359 basic_block block;
2360 int i;
2362 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2363 We pre-build the map of blocks with incoming abnormal edges here. */
2364 has_abnormal_preds = sbitmap_alloc (last_basic_block_for_fn (cfun));
2365 bitmap_clear (has_abnormal_preds);
2367 FOR_ALL_BB_FN (block, cfun)
2369 edge_iterator ei;
2370 edge e;
2372 FOR_EACH_EDGE (e, ei, block->preds)
2374 e->flags &= ~EDGE_DFS_BACK;
2375 if (e->flags & EDGE_ABNORMAL)
2377 bitmap_set_bit (has_abnormal_preds, block->index);
2378 break;
2382 BB_VISITED (block) = 0;
2384 /* While we are here, give empty ANTIC_IN sets to each block. */
2385 ANTIC_IN (block) = bitmap_set_new ();
2386 PA_IN (block) = bitmap_set_new ();
2389 /* At the exit block we anticipate nothing. */
2390 BB_VISITED (EXIT_BLOCK_PTR_FOR_FN (cfun)) = 1;
2392 changed_blocks = sbitmap_alloc (last_basic_block_for_fn (cfun) + 1);
2393 bitmap_ones (changed_blocks);
2394 while (changed)
2396 if (dump_file && (dump_flags & TDF_DETAILS))
2397 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2398 /* ??? We need to clear our PHI translation cache here as the
2399 ANTIC sets shrink and we restrict valid translations to
2400 those having operands with leaders in ANTIC. Same below
2401 for PA ANTIC computation. */
2402 num_iterations++;
2403 changed = false;
2404 for (i = postorder_num - 1; i >= 0; i--)
2406 if (bitmap_bit_p (changed_blocks, postorder[i]))
2408 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2409 changed |= compute_antic_aux (block,
2410 bitmap_bit_p (has_abnormal_preds,
2411 block->index));
2414 /* Theoretically possible, but *highly* unlikely. */
2415 gcc_checking_assert (num_iterations < 500);
2418 statistics_histogram_event (cfun, "compute_antic iterations",
2419 num_iterations);
2421 if (do_partial_partial)
2423 bitmap_ones (changed_blocks);
2424 mark_dfs_back_edges ();
2425 num_iterations = 0;
2426 changed = true;
2427 while (changed)
2429 if (dump_file && (dump_flags & TDF_DETAILS))
2430 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2431 num_iterations++;
2432 changed = false;
2433 for (i = postorder_num - 1 ; i >= 0; i--)
2435 if (bitmap_bit_p (changed_blocks, postorder[i]))
2437 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2438 changed
2439 |= compute_partial_antic_aux (block,
2440 bitmap_bit_p (has_abnormal_preds,
2441 block->index));
2444 /* Theoretically possible, but *highly* unlikely. */
2445 gcc_checking_assert (num_iterations < 500);
2447 statistics_histogram_event (cfun, "compute_partial_antic iterations",
2448 num_iterations);
2450 sbitmap_free (has_abnormal_preds);
2451 sbitmap_free (changed_blocks);
2455 /* Inserted expressions are placed onto this worklist, which is used
2456 for performing quick dead code elimination of insertions we made
2457 that didn't turn out to be necessary. */
2458 static bitmap inserted_exprs;
2460 /* The actual worker for create_component_ref_by_pieces. */
2462 static tree
2463 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2464 unsigned int *operand, gimple_seq *stmts)
2466 vn_reference_op_t currop = &ref->operands[*operand];
2467 tree genop;
2468 ++*operand;
2469 switch (currop->opcode)
2471 case CALL_EXPR:
2473 tree folded, sc = NULL_TREE;
2474 unsigned int nargs = 0;
2475 tree fn, *args;
2476 if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2477 fn = currop->op0;
2478 else
2479 fn = find_or_generate_expression (block, currop->op0, stmts);
2480 if (!fn)
2481 return NULL_TREE;
2482 if (currop->op1)
2484 sc = find_or_generate_expression (block, currop->op1, stmts);
2485 if (!sc)
2486 return NULL_TREE;
2488 args = XNEWVEC (tree, ref->operands.length () - 1);
2489 while (*operand < ref->operands.length ())
2491 args[nargs] = create_component_ref_by_pieces_1 (block, ref,
2492 operand, stmts);
2493 if (!args[nargs])
2494 return NULL_TREE;
2495 nargs++;
2497 folded = build_call_array (currop->type,
2498 (TREE_CODE (fn) == FUNCTION_DECL
2499 ? build_fold_addr_expr (fn) : fn),
2500 nargs, args);
2501 free (args);
2502 if (sc)
2503 CALL_EXPR_STATIC_CHAIN (folded) = sc;
2504 return folded;
2507 case MEM_REF:
2509 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2510 stmts);
2511 if (!baseop)
2512 return NULL_TREE;
2513 tree offset = currop->op0;
2514 if (TREE_CODE (baseop) == ADDR_EXPR
2515 && handled_component_p (TREE_OPERAND (baseop, 0)))
2517 HOST_WIDE_INT off;
2518 tree base;
2519 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2520 &off);
2521 gcc_assert (base);
2522 offset = int_const_binop (PLUS_EXPR, offset,
2523 build_int_cst (TREE_TYPE (offset),
2524 off));
2525 baseop = build_fold_addr_expr (base);
2527 return fold_build2 (MEM_REF, currop->type, baseop, offset);
2530 case TARGET_MEM_REF:
2532 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2533 vn_reference_op_t nextop = &ref->operands[++*operand];
2534 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2535 stmts);
2536 if (!baseop)
2537 return NULL_TREE;
2538 if (currop->op0)
2540 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2541 if (!genop0)
2542 return NULL_TREE;
2544 if (nextop->op0)
2546 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2547 if (!genop1)
2548 return NULL_TREE;
2550 return build5 (TARGET_MEM_REF, currop->type,
2551 baseop, currop->op2, genop0, currop->op1, genop1);
2554 case ADDR_EXPR:
2555 if (currop->op0)
2557 gcc_assert (is_gimple_min_invariant (currop->op0));
2558 return currop->op0;
2560 /* Fallthrough. */
2561 case REALPART_EXPR:
2562 case IMAGPART_EXPR:
2563 case VIEW_CONVERT_EXPR:
2565 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2566 stmts);
2567 if (!genop0)
2568 return NULL_TREE;
2569 return fold_build1 (currop->opcode, currop->type, genop0);
2572 case WITH_SIZE_EXPR:
2574 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2575 stmts);
2576 if (!genop0)
2577 return NULL_TREE;
2578 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2579 if (!genop1)
2580 return NULL_TREE;
2581 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2584 case BIT_FIELD_REF:
2586 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2587 stmts);
2588 if (!genop0)
2589 return NULL_TREE;
2590 tree op1 = currop->op0;
2591 tree op2 = currop->op1;
2592 return fold_build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2595 /* For array ref vn_reference_op's, operand 1 of the array ref
2596 is op0 of the reference op and operand 3 of the array ref is
2597 op1. */
2598 case ARRAY_RANGE_REF:
2599 case ARRAY_REF:
2601 tree genop0;
2602 tree genop1 = currop->op0;
2603 tree genop2 = currop->op1;
2604 tree genop3 = currop->op2;
2605 genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2606 stmts);
2607 if (!genop0)
2608 return NULL_TREE;
2609 genop1 = find_or_generate_expression (block, genop1, stmts);
2610 if (!genop1)
2611 return NULL_TREE;
2612 if (genop2)
2614 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2615 /* Drop zero minimum index if redundant. */
2616 if (integer_zerop (genop2)
2617 && (!domain_type
2618 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2619 genop2 = NULL_TREE;
2620 else
2622 genop2 = find_or_generate_expression (block, genop2, stmts);
2623 if (!genop2)
2624 return NULL_TREE;
2627 if (genop3)
2629 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2630 /* We can't always put a size in units of the element alignment
2631 here as the element alignment may be not visible. See
2632 PR43783. Simply drop the element size for constant
2633 sizes. */
2634 if (tree_int_cst_equal (genop3, TYPE_SIZE_UNIT (elmt_type)))
2635 genop3 = NULL_TREE;
2636 else
2638 genop3 = size_binop (EXACT_DIV_EXPR, genop3,
2639 size_int (TYPE_ALIGN_UNIT (elmt_type)));
2640 genop3 = find_or_generate_expression (block, genop3, stmts);
2641 if (!genop3)
2642 return NULL_TREE;
2645 return build4 (currop->opcode, currop->type, genop0, genop1,
2646 genop2, genop3);
2648 case COMPONENT_REF:
2650 tree op0;
2651 tree op1;
2652 tree genop2 = currop->op1;
2653 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2654 if (!op0)
2655 return NULL_TREE;
2656 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2657 op1 = currop->op0;
2658 if (genop2)
2660 genop2 = find_or_generate_expression (block, genop2, stmts);
2661 if (!genop2)
2662 return NULL_TREE;
2664 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2667 case SSA_NAME:
2669 genop = find_or_generate_expression (block, currop->op0, stmts);
2670 return genop;
2672 case STRING_CST:
2673 case INTEGER_CST:
2674 case COMPLEX_CST:
2675 case VECTOR_CST:
2676 case REAL_CST:
2677 case CONSTRUCTOR:
2678 case VAR_DECL:
2679 case PARM_DECL:
2680 case CONST_DECL:
2681 case RESULT_DECL:
2682 case FUNCTION_DECL:
2683 return currop->op0;
2685 default:
2686 gcc_unreachable ();
2690 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2691 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2692 trying to rename aggregates into ssa form directly, which is a no no.
2694 Thus, this routine doesn't create temporaries, it just builds a
2695 single access expression for the array, calling
2696 find_or_generate_expression to build the innermost pieces.
2698 This function is a subroutine of create_expression_by_pieces, and
2699 should not be called on it's own unless you really know what you
2700 are doing. */
2702 static tree
2703 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2704 gimple_seq *stmts)
2706 unsigned int op = 0;
2707 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2710 /* Find a simple leader for an expression, or generate one using
2711 create_expression_by_pieces from a NARY expression for the value.
2712 BLOCK is the basic_block we are looking for leaders in.
2713 OP is the tree expression to find a leader for or generate.
2714 Returns the leader or NULL_TREE on failure. */
2716 static tree
2717 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2719 pre_expr expr = get_or_alloc_expr_for (op);
2720 unsigned int lookfor = get_expr_value_id (expr);
2721 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2722 if (leader)
2724 if (leader->kind == NAME)
2725 return PRE_EXPR_NAME (leader);
2726 else if (leader->kind == CONSTANT)
2727 return PRE_EXPR_CONSTANT (leader);
2729 /* Defer. */
2730 return NULL_TREE;
2733 /* It must be a complex expression, so generate it recursively. Note
2734 that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2735 where the insert algorithm fails to insert a required expression. */
2736 bitmap exprset = value_expressions[lookfor];
2737 bitmap_iterator bi;
2738 unsigned int i;
2739 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2741 pre_expr temp = expression_for_id (i);
2742 /* We cannot insert random REFERENCE expressions at arbitrary
2743 places. We can insert NARYs which eventually re-materializes
2744 its operand values. */
2745 if (temp->kind == NARY)
2746 return create_expression_by_pieces (block, temp, stmts,
2747 get_expr_type (expr));
2750 /* Defer. */
2751 return NULL_TREE;
2754 #define NECESSARY GF_PLF_1
2756 /* Create an expression in pieces, so that we can handle very complex
2757 expressions that may be ANTIC, but not necessary GIMPLE.
2758 BLOCK is the basic block the expression will be inserted into,
2759 EXPR is the expression to insert (in value form)
2760 STMTS is a statement list to append the necessary insertions into.
2762 This function will die if we hit some value that shouldn't be
2763 ANTIC but is (IE there is no leader for it, or its components).
2764 The function returns NULL_TREE in case a different antic expression
2765 has to be inserted first.
2766 This function may also generate expressions that are themselves
2767 partially or fully redundant. Those that are will be either made
2768 fully redundant during the next iteration of insert (for partially
2769 redundant ones), or eliminated by eliminate (for fully redundant
2770 ones). */
2772 static tree
2773 create_expression_by_pieces (basic_block block, pre_expr expr,
2774 gimple_seq *stmts, tree type)
2776 tree name;
2777 tree folded;
2778 gimple_seq forced_stmts = NULL;
2779 unsigned int value_id;
2780 gimple_stmt_iterator gsi;
2781 tree exprtype = type ? type : get_expr_type (expr);
2782 pre_expr nameexpr;
2783 gimple newstmt;
2785 switch (expr->kind)
2787 /* We may hit the NAME/CONSTANT case if we have to convert types
2788 that value numbering saw through. */
2789 case NAME:
2790 folded = PRE_EXPR_NAME (expr);
2791 break;
2792 case CONSTANT:
2793 folded = PRE_EXPR_CONSTANT (expr);
2794 break;
2795 case REFERENCE:
2797 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2798 folded = create_component_ref_by_pieces (block, ref, stmts);
2799 if (!folded)
2800 return NULL_TREE;
2802 break;
2803 case NARY:
2805 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2806 tree *genop = XALLOCAVEC (tree, nary->length);
2807 unsigned i;
2808 for (i = 0; i < nary->length; ++i)
2810 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2811 if (!genop[i])
2812 return NULL_TREE;
2813 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2814 may have conversions stripped. */
2815 if (nary->opcode == POINTER_PLUS_EXPR)
2817 if (i == 0)
2818 genop[i] = fold_convert (nary->type, genop[i]);
2819 else if (i == 1)
2820 genop[i] = convert_to_ptrofftype (genop[i]);
2822 else
2823 genop[i] = fold_convert (TREE_TYPE (nary->op[i]), genop[i]);
2825 if (nary->opcode == CONSTRUCTOR)
2827 vec<constructor_elt, va_gc> *elts = NULL;
2828 for (i = 0; i < nary->length; ++i)
2829 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2830 folded = build_constructor (nary->type, elts);
2832 else
2834 switch (nary->length)
2836 case 1:
2837 folded = fold_build1 (nary->opcode, nary->type,
2838 genop[0]);
2839 break;
2840 case 2:
2841 folded = fold_build2 (nary->opcode, nary->type,
2842 genop[0], genop[1]);
2843 break;
2844 case 3:
2845 folded = fold_build3 (nary->opcode, nary->type,
2846 genop[0], genop[1], genop[2]);
2847 break;
2848 default:
2849 gcc_unreachable ();
2853 break;
2854 default:
2855 gcc_unreachable ();
2858 if (!useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2859 folded = fold_convert (exprtype, folded);
2861 /* Force the generated expression to be a sequence of GIMPLE
2862 statements.
2863 We have to call unshare_expr because force_gimple_operand may
2864 modify the tree we pass to it. */
2865 folded = force_gimple_operand (unshare_expr (folded), &forced_stmts,
2866 false, NULL);
2868 /* If we have any intermediate expressions to the value sets, add them
2869 to the value sets and chain them in the instruction stream. */
2870 if (forced_stmts)
2872 gsi = gsi_start (forced_stmts);
2873 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2875 gimple stmt = gsi_stmt (gsi);
2876 tree forcedname = gimple_get_lhs (stmt);
2877 pre_expr nameexpr;
2879 if (TREE_CODE (forcedname) == SSA_NAME)
2881 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2882 VN_INFO_GET (forcedname)->valnum = forcedname;
2883 VN_INFO (forcedname)->value_id = get_next_value_id ();
2884 nameexpr = get_or_alloc_expr_for_name (forcedname);
2885 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2886 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2887 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2890 gimple_seq_add_seq (stmts, forced_stmts);
2893 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2894 newstmt = gimple_build_assign (name, folded);
2895 gimple_set_plf (newstmt, NECESSARY, false);
2897 gimple_seq_add_stmt (stmts, newstmt);
2898 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
2900 /* Fold the last statement. */
2901 gsi = gsi_last (*stmts);
2902 if (fold_stmt_inplace (&gsi))
2903 update_stmt (gsi_stmt (gsi));
2905 /* Add a value number to the temporary.
2906 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2907 we are creating the expression by pieces, and this particular piece of
2908 the expression may have been represented. There is no harm in replacing
2909 here. */
2910 value_id = get_expr_value_id (expr);
2911 VN_INFO_GET (name)->value_id = value_id;
2912 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2913 if (VN_INFO (name)->valnum == NULL_TREE)
2914 VN_INFO (name)->valnum = name;
2915 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2916 nameexpr = get_or_alloc_expr_for_name (name);
2917 add_to_value (value_id, nameexpr);
2918 if (NEW_SETS (block))
2919 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2920 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2922 pre_stats.insertions++;
2923 if (dump_file && (dump_flags & TDF_DETAILS))
2925 fprintf (dump_file, "Inserted ");
2926 print_gimple_stmt (dump_file, newstmt, 0, 0);
2927 fprintf (dump_file, " in predecessor %d (%04d)\n",
2928 block->index, value_id);
2931 return name;
2935 /* Insert the to-be-made-available values of expression EXPRNUM for each
2936 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
2937 merge the result with a phi node, given the same value number as
2938 NODE. Return true if we have inserted new stuff. */
2940 static bool
2941 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
2942 vec<pre_expr> avail)
2944 pre_expr expr = expression_for_id (exprnum);
2945 pre_expr newphi;
2946 unsigned int val = get_expr_value_id (expr);
2947 edge pred;
2948 bool insertions = false;
2949 bool nophi = false;
2950 basic_block bprime;
2951 pre_expr eprime;
2952 edge_iterator ei;
2953 tree type = get_expr_type (expr);
2954 tree temp;
2955 gimple phi;
2957 /* Make sure we aren't creating an induction variable. */
2958 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
2960 bool firstinsideloop = false;
2961 bool secondinsideloop = false;
2962 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
2963 EDGE_PRED (block, 0)->src);
2964 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
2965 EDGE_PRED (block, 1)->src);
2966 /* Induction variables only have one edge inside the loop. */
2967 if ((firstinsideloop ^ secondinsideloop)
2968 && expr->kind != REFERENCE)
2970 if (dump_file && (dump_flags & TDF_DETAILS))
2971 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
2972 nophi = true;
2976 /* Make the necessary insertions. */
2977 FOR_EACH_EDGE (pred, ei, block->preds)
2979 gimple_seq stmts = NULL;
2980 tree builtexpr;
2981 bprime = pred->src;
2982 eprime = avail[pred->dest_idx];
2984 if (eprime->kind != NAME && eprime->kind != CONSTANT)
2986 builtexpr = create_expression_by_pieces (bprime, eprime,
2987 &stmts, type);
2988 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
2989 gsi_insert_seq_on_edge (pred, stmts);
2990 if (!builtexpr)
2992 /* We cannot insert a PHI node if we failed to insert
2993 on one edge. */
2994 nophi = true;
2995 continue;
2997 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
2998 insertions = true;
3000 else if (eprime->kind == CONSTANT)
3002 /* Constants may not have the right type, fold_convert
3003 should give us back a constant with the right type. */
3004 tree constant = PRE_EXPR_CONSTANT (eprime);
3005 if (!useless_type_conversion_p (type, TREE_TYPE (constant)))
3007 tree builtexpr = fold_convert (type, constant);
3008 if (!is_gimple_min_invariant (builtexpr))
3010 tree forcedexpr = force_gimple_operand (builtexpr,
3011 &stmts, true,
3012 NULL);
3013 if (!is_gimple_min_invariant (forcedexpr))
3015 if (forcedexpr != builtexpr)
3017 VN_INFO_GET (forcedexpr)->valnum = PRE_EXPR_CONSTANT (eprime);
3018 VN_INFO (forcedexpr)->value_id = get_expr_value_id (eprime);
3020 if (stmts)
3022 gimple_stmt_iterator gsi;
3023 gsi = gsi_start (stmts);
3024 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3026 gimple stmt = gsi_stmt (gsi);
3027 tree lhs = gimple_get_lhs (stmt);
3028 if (TREE_CODE (lhs) == SSA_NAME)
3029 bitmap_set_bit (inserted_exprs,
3030 SSA_NAME_VERSION (lhs));
3031 gimple_set_plf (stmt, NECESSARY, false);
3033 gsi_insert_seq_on_edge (pred, stmts);
3035 avail[pred->dest_idx]
3036 = get_or_alloc_expr_for_name (forcedexpr);
3039 else
3040 avail[pred->dest_idx]
3041 = get_or_alloc_expr_for_constant (builtexpr);
3044 else if (eprime->kind == NAME)
3046 /* We may have to do a conversion because our value
3047 numbering can look through types in certain cases, but
3048 our IL requires all operands of a phi node have the same
3049 type. */
3050 tree name = PRE_EXPR_NAME (eprime);
3051 if (!useless_type_conversion_p (type, TREE_TYPE (name)))
3053 tree builtexpr;
3054 tree forcedexpr;
3055 builtexpr = fold_convert (type, name);
3056 forcedexpr = force_gimple_operand (builtexpr,
3057 &stmts, true,
3058 NULL);
3060 if (forcedexpr != name)
3062 VN_INFO_GET (forcedexpr)->valnum = VN_INFO (name)->valnum;
3063 VN_INFO (forcedexpr)->value_id = VN_INFO (name)->value_id;
3066 if (stmts)
3068 gimple_stmt_iterator gsi;
3069 gsi = gsi_start (stmts);
3070 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3072 gimple stmt = gsi_stmt (gsi);
3073 tree lhs = gimple_get_lhs (stmt);
3074 if (TREE_CODE (lhs) == SSA_NAME)
3075 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
3076 gimple_set_plf (stmt, NECESSARY, false);
3078 gsi_insert_seq_on_edge (pred, stmts);
3080 avail[pred->dest_idx] = get_or_alloc_expr_for_name (forcedexpr);
3084 /* If we didn't want a phi node, and we made insertions, we still have
3085 inserted new stuff, and thus return true. If we didn't want a phi node,
3086 and didn't make insertions, we haven't added anything new, so return
3087 false. */
3088 if (nophi && insertions)
3089 return true;
3090 else if (nophi && !insertions)
3091 return false;
3093 /* Now build a phi for the new variable. */
3094 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3095 phi = create_phi_node (temp, block);
3097 gimple_set_plf (phi, NECESSARY, false);
3098 VN_INFO_GET (temp)->value_id = val;
3099 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3100 if (VN_INFO (temp)->valnum == NULL_TREE)
3101 VN_INFO (temp)->valnum = temp;
3102 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3103 FOR_EACH_EDGE (pred, ei, block->preds)
3105 pre_expr ae = avail[pred->dest_idx];
3106 gcc_assert (get_expr_type (ae) == type
3107 || useless_type_conversion_p (type, get_expr_type (ae)));
3108 if (ae->kind == CONSTANT)
3109 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3110 pred, UNKNOWN_LOCATION);
3111 else
3112 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3115 newphi = get_or_alloc_expr_for_name (temp);
3116 add_to_value (val, newphi);
3118 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3119 this insertion, since we test for the existence of this value in PHI_GEN
3120 before proceeding with the partial redundancy checks in insert_aux.
3122 The value may exist in AVAIL_OUT, in particular, it could be represented
3123 by the expression we are trying to eliminate, in which case we want the
3124 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3125 inserted there.
3127 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3128 this block, because if it did, it would have existed in our dominator's
3129 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3132 bitmap_insert_into_set (PHI_GEN (block), newphi);
3133 bitmap_value_replace_in_set (AVAIL_OUT (block),
3134 newphi);
3135 bitmap_insert_into_set (NEW_SETS (block),
3136 newphi);
3138 if (dump_file && (dump_flags & TDF_DETAILS))
3140 fprintf (dump_file, "Created phi ");
3141 print_gimple_stmt (dump_file, phi, 0, 0);
3142 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3144 pre_stats.phis++;
3145 return true;
3150 /* Perform insertion of partially redundant values.
3151 For BLOCK, do the following:
3152 1. Propagate the NEW_SETS of the dominator into the current block.
3153 If the block has multiple predecessors,
3154 2a. Iterate over the ANTIC expressions for the block to see if
3155 any of them are partially redundant.
3156 2b. If so, insert them into the necessary predecessors to make
3157 the expression fully redundant.
3158 2c. Insert a new PHI merging the values of the predecessors.
3159 2d. Insert the new PHI, and the new expressions, into the
3160 NEW_SETS set.
3161 3. Recursively call ourselves on the dominator children of BLOCK.
3163 Steps 1, 2a, and 3 are done by insert_aux. 2b, 2c and 2d are done by
3164 do_regular_insertion and do_partial_insertion.
3168 static bool
3169 do_regular_insertion (basic_block block, basic_block dom)
3171 bool new_stuff = false;
3172 vec<pre_expr> exprs;
3173 pre_expr expr;
3174 vec<pre_expr> avail = vNULL;
3175 int i;
3177 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3178 avail.safe_grow (EDGE_COUNT (block->preds));
3180 FOR_EACH_VEC_ELT (exprs, i, expr)
3182 if (expr->kind == NARY
3183 || expr->kind == REFERENCE)
3185 unsigned int val;
3186 bool by_some = false;
3187 bool cant_insert = false;
3188 bool all_same = true;
3189 pre_expr first_s = NULL;
3190 edge pred;
3191 basic_block bprime;
3192 pre_expr eprime = NULL;
3193 edge_iterator ei;
3194 pre_expr edoubleprime = NULL;
3195 bool do_insertion = false;
3197 val = get_expr_value_id (expr);
3198 if (bitmap_set_contains_value (PHI_GEN (block), val))
3199 continue;
3200 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3202 if (dump_file && (dump_flags & TDF_DETAILS))
3204 fprintf (dump_file, "Found fully redundant value: ");
3205 print_pre_expr (dump_file, expr);
3206 fprintf (dump_file, "\n");
3208 continue;
3211 FOR_EACH_EDGE (pred, ei, block->preds)
3213 unsigned int vprime;
3215 /* We should never run insertion for the exit block
3216 and so not come across fake pred edges. */
3217 gcc_assert (!(pred->flags & EDGE_FAKE));
3218 bprime = pred->src;
3219 eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3220 bprime, block);
3222 /* eprime will generally only be NULL if the
3223 value of the expression, translated
3224 through the PHI for this predecessor, is
3225 undefined. If that is the case, we can't
3226 make the expression fully redundant,
3227 because its value is undefined along a
3228 predecessor path. We can thus break out
3229 early because it doesn't matter what the
3230 rest of the results are. */
3231 if (eprime == NULL)
3233 avail[pred->dest_idx] = NULL;
3234 cant_insert = true;
3235 break;
3238 eprime = fully_constant_expression (eprime);
3239 vprime = get_expr_value_id (eprime);
3240 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3241 vprime);
3242 if (edoubleprime == NULL)
3244 avail[pred->dest_idx] = eprime;
3245 all_same = false;
3247 else
3249 avail[pred->dest_idx] = edoubleprime;
3250 by_some = true;
3251 /* We want to perform insertions to remove a redundancy on
3252 a path in the CFG we want to optimize for speed. */
3253 if (optimize_edge_for_speed_p (pred))
3254 do_insertion = true;
3255 if (first_s == NULL)
3256 first_s = edoubleprime;
3257 else if (!pre_expr_d::equal (first_s, edoubleprime))
3258 all_same = false;
3261 /* If we can insert it, it's not the same value
3262 already existing along every predecessor, and
3263 it's defined by some predecessor, it is
3264 partially redundant. */
3265 if (!cant_insert && !all_same && by_some)
3267 if (!do_insertion)
3269 if (dump_file && (dump_flags & TDF_DETAILS))
3271 fprintf (dump_file, "Skipping partial redundancy for "
3272 "expression ");
3273 print_pre_expr (dump_file, expr);
3274 fprintf (dump_file, " (%04d), no redundancy on to be "
3275 "optimized for speed edge\n", val);
3278 else if (dbg_cnt (treepre_insert))
3280 if (dump_file && (dump_flags & TDF_DETAILS))
3282 fprintf (dump_file, "Found partial redundancy for "
3283 "expression ");
3284 print_pre_expr (dump_file, expr);
3285 fprintf (dump_file, " (%04d)\n",
3286 get_expr_value_id (expr));
3288 if (insert_into_preds_of_block (block,
3289 get_expression_id (expr),
3290 avail))
3291 new_stuff = true;
3294 /* If all edges produce the same value and that value is
3295 an invariant, then the PHI has the same value on all
3296 edges. Note this. */
3297 else if (!cant_insert && all_same)
3299 gcc_assert (edoubleprime->kind == CONSTANT
3300 || edoubleprime->kind == NAME);
3302 tree temp = make_temp_ssa_name (get_expr_type (expr),
3303 NULL, "pretmp");
3304 gimple assign = gimple_build_assign (temp,
3305 edoubleprime->kind == CONSTANT ? PRE_EXPR_CONSTANT (edoubleprime) : PRE_EXPR_NAME (edoubleprime));
3306 gimple_stmt_iterator gsi = gsi_after_labels (block);
3307 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3309 gimple_set_plf (assign, NECESSARY, false);
3310 VN_INFO_GET (temp)->value_id = val;
3311 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3312 if (VN_INFO (temp)->valnum == NULL_TREE)
3313 VN_INFO (temp)->valnum = temp;
3314 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3315 pre_expr newe = get_or_alloc_expr_for_name (temp);
3316 add_to_value (val, newe);
3317 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3318 bitmap_insert_into_set (NEW_SETS (block), newe);
3323 exprs.release ();
3324 return new_stuff;
3328 /* Perform insertion for partially anticipatable expressions. There
3329 is only one case we will perform insertion for these. This case is
3330 if the expression is partially anticipatable, and fully available.
3331 In this case, we know that putting it earlier will enable us to
3332 remove the later computation. */
3335 static bool
3336 do_partial_partial_insertion (basic_block block, basic_block dom)
3338 bool new_stuff = false;
3339 vec<pre_expr> exprs;
3340 pre_expr expr;
3341 auto_vec<pre_expr> avail;
3342 int i;
3344 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3345 avail.safe_grow (EDGE_COUNT (block->preds));
3347 FOR_EACH_VEC_ELT (exprs, i, expr)
3349 if (expr->kind == NARY
3350 || expr->kind == REFERENCE)
3352 unsigned int val;
3353 bool by_all = true;
3354 bool cant_insert = false;
3355 edge pred;
3356 basic_block bprime;
3357 pre_expr eprime = NULL;
3358 edge_iterator ei;
3360 val = get_expr_value_id (expr);
3361 if (bitmap_set_contains_value (PHI_GEN (block), val))
3362 continue;
3363 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3364 continue;
3366 FOR_EACH_EDGE (pred, ei, block->preds)
3368 unsigned int vprime;
3369 pre_expr edoubleprime;
3371 /* We should never run insertion for the exit block
3372 and so not come across fake pred edges. */
3373 gcc_assert (!(pred->flags & EDGE_FAKE));
3374 bprime = pred->src;
3375 eprime = phi_translate (expr, ANTIC_IN (block),
3376 PA_IN (block),
3377 bprime, block);
3379 /* eprime will generally only be NULL if the
3380 value of the expression, translated
3381 through the PHI for this predecessor, is
3382 undefined. If that is the case, we can't
3383 make the expression fully redundant,
3384 because its value is undefined along a
3385 predecessor path. We can thus break out
3386 early because it doesn't matter what the
3387 rest of the results are. */
3388 if (eprime == NULL)
3390 avail[pred->dest_idx] = NULL;
3391 cant_insert = true;
3392 break;
3395 eprime = fully_constant_expression (eprime);
3396 vprime = get_expr_value_id (eprime);
3397 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3398 avail[pred->dest_idx] = edoubleprime;
3399 if (edoubleprime == NULL)
3401 by_all = false;
3402 break;
3406 /* If we can insert it, it's not the same value
3407 already existing along every predecessor, and
3408 it's defined by some predecessor, it is
3409 partially redundant. */
3410 if (!cant_insert && by_all)
3412 edge succ;
3413 bool do_insertion = false;
3415 /* Insert only if we can remove a later expression on a path
3416 that we want to optimize for speed.
3417 The phi node that we will be inserting in BLOCK is not free,
3418 and inserting it for the sake of !optimize_for_speed successor
3419 may cause regressions on the speed path. */
3420 FOR_EACH_EDGE (succ, ei, block->succs)
3422 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3423 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3425 if (optimize_edge_for_speed_p (succ))
3426 do_insertion = true;
3430 if (!do_insertion)
3432 if (dump_file && (dump_flags & TDF_DETAILS))
3434 fprintf (dump_file, "Skipping partial partial redundancy "
3435 "for expression ");
3436 print_pre_expr (dump_file, expr);
3437 fprintf (dump_file, " (%04d), not (partially) anticipated "
3438 "on any to be optimized for speed edges\n", val);
3441 else if (dbg_cnt (treepre_insert))
3443 pre_stats.pa_insert++;
3444 if (dump_file && (dump_flags & TDF_DETAILS))
3446 fprintf (dump_file, "Found partial partial redundancy "
3447 "for expression ");
3448 print_pre_expr (dump_file, expr);
3449 fprintf (dump_file, " (%04d)\n",
3450 get_expr_value_id (expr));
3452 if (insert_into_preds_of_block (block,
3453 get_expression_id (expr),
3454 avail))
3455 new_stuff = true;
3461 exprs.release ();
3462 return new_stuff;
3465 static bool
3466 insert_aux (basic_block block)
3468 basic_block son;
3469 bool new_stuff = false;
3471 if (block)
3473 basic_block dom;
3474 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3475 if (dom)
3477 unsigned i;
3478 bitmap_iterator bi;
3479 bitmap_set_t newset = NEW_SETS (dom);
3480 if (newset)
3482 /* Note that we need to value_replace both NEW_SETS, and
3483 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3484 represented by some non-simple expression here that we want
3485 to replace it with. */
3486 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3488 pre_expr expr = expression_for_id (i);
3489 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3490 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3493 if (!single_pred_p (block))
3495 new_stuff |= do_regular_insertion (block, dom);
3496 if (do_partial_partial)
3497 new_stuff |= do_partial_partial_insertion (block, dom);
3501 for (son = first_dom_son (CDI_DOMINATORS, block);
3502 son;
3503 son = next_dom_son (CDI_DOMINATORS, son))
3505 new_stuff |= insert_aux (son);
3508 return new_stuff;
3511 /* Perform insertion of partially redundant values. */
3513 static void
3514 insert (void)
3516 bool new_stuff = true;
3517 basic_block bb;
3518 int num_iterations = 0;
3520 FOR_ALL_BB_FN (bb, cfun)
3521 NEW_SETS (bb) = bitmap_set_new ();
3523 while (new_stuff)
3525 num_iterations++;
3526 if (dump_file && dump_flags & TDF_DETAILS)
3527 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3528 new_stuff = insert_aux (ENTRY_BLOCK_PTR_FOR_FN (cfun));
3530 /* Clear the NEW sets before the next iteration. We have already
3531 fully propagated its contents. */
3532 if (new_stuff)
3533 FOR_ALL_BB_FN (bb, cfun)
3534 bitmap_set_free (NEW_SETS (bb));
3536 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3540 /* Compute the AVAIL set for all basic blocks.
3542 This function performs value numbering of the statements in each basic
3543 block. The AVAIL sets are built from information we glean while doing
3544 this value numbering, since the AVAIL sets contain only one entry per
3545 value.
3547 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3548 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3550 static void
3551 compute_avail (void)
3554 basic_block block, son;
3555 basic_block *worklist;
3556 size_t sp = 0;
3557 unsigned i;
3559 /* We pretend that default definitions are defined in the entry block.
3560 This includes function arguments and the static chain decl. */
3561 for (i = 1; i < num_ssa_names; ++i)
3563 tree name = ssa_name (i);
3564 pre_expr e;
3565 if (!name
3566 || !SSA_NAME_IS_DEFAULT_DEF (name)
3567 || has_zero_uses (name)
3568 || virtual_operand_p (name))
3569 continue;
3571 e = get_or_alloc_expr_for_name (name);
3572 add_to_value (get_expr_value_id (e), e);
3573 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)), e);
3574 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3578 if (dump_file && (dump_flags & TDF_DETAILS))
3580 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3581 "tmp_gen", ENTRY_BLOCK);
3582 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3583 "avail_out", ENTRY_BLOCK);
3586 /* Allocate the worklist. */
3587 worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
3589 /* Seed the algorithm by putting the dominator children of the entry
3590 block on the worklist. */
3591 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
3592 son;
3593 son = next_dom_son (CDI_DOMINATORS, son))
3594 worklist[sp++] = son;
3596 /* Loop until the worklist is empty. */
3597 while (sp)
3599 gimple_stmt_iterator gsi;
3600 gimple stmt;
3601 basic_block dom;
3603 /* Pick a block from the worklist. */
3604 block = worklist[--sp];
3606 /* Initially, the set of available values in BLOCK is that of
3607 its immediate dominator. */
3608 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3609 if (dom)
3610 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3612 /* Generate values for PHI nodes. */
3613 for (gsi = gsi_start_phis (block); !gsi_end_p (gsi); gsi_next (&gsi))
3615 tree result = gimple_phi_result (gsi_stmt (gsi));
3617 /* We have no need for virtual phis, as they don't represent
3618 actual computations. */
3619 if (virtual_operand_p (result))
3620 continue;
3622 pre_expr e = get_or_alloc_expr_for_name (result);
3623 add_to_value (get_expr_value_id (e), e);
3624 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3625 bitmap_insert_into_set (PHI_GEN (block), e);
3628 BB_MAY_NOTRETURN (block) = 0;
3630 /* Now compute value numbers and populate value sets with all
3631 the expressions computed in BLOCK. */
3632 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
3634 ssa_op_iter iter;
3635 tree op;
3637 stmt = gsi_stmt (gsi);
3639 /* Cache whether the basic-block has any non-visible side-effect
3640 or control flow.
3641 If this isn't a call or it is the last stmt in the
3642 basic-block then the CFG represents things correctly. */
3643 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3645 /* Non-looping const functions always return normally.
3646 Otherwise the call might not return or have side-effects
3647 that forbids hoisting possibly trapping expressions
3648 before it. */
3649 int flags = gimple_call_flags (stmt);
3650 if (!(flags & ECF_CONST)
3651 || (flags & ECF_LOOPING_CONST_OR_PURE))
3652 BB_MAY_NOTRETURN (block) = 1;
3655 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3657 pre_expr e = get_or_alloc_expr_for_name (op);
3659 add_to_value (get_expr_value_id (e), e);
3660 bitmap_insert_into_set (TMP_GEN (block), e);
3661 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3664 if (gimple_has_side_effects (stmt)
3665 || stmt_could_throw_p (stmt)
3666 || is_gimple_debug (stmt))
3667 continue;
3669 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3671 if (ssa_undefined_value_p (op))
3672 continue;
3673 pre_expr e = get_or_alloc_expr_for_name (op);
3674 bitmap_value_insert_into_set (EXP_GEN (block), e);
3677 switch (gimple_code (stmt))
3679 case GIMPLE_RETURN:
3680 continue;
3682 case GIMPLE_CALL:
3684 vn_reference_t ref;
3685 vn_reference_s ref1;
3686 pre_expr result = NULL;
3688 /* We can value number only calls to real functions. */
3689 if (gimple_call_internal_p (stmt))
3690 continue;
3692 vn_reference_lookup_call (stmt, &ref, &ref1);
3693 if (!ref)
3694 continue;
3696 /* If the value of the call is not invalidated in
3697 this block until it is computed, add the expression
3698 to EXP_GEN. */
3699 if (!gimple_vuse (stmt)
3700 || gimple_code
3701 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3702 || gimple_bb (SSA_NAME_DEF_STMT
3703 (gimple_vuse (stmt))) != block)
3705 result = (pre_expr) pool_alloc (pre_expr_pool);
3706 result->kind = REFERENCE;
3707 result->id = 0;
3708 PRE_EXPR_REFERENCE (result) = ref;
3710 get_or_alloc_expression_id (result);
3711 add_to_value (get_expr_value_id (result), result);
3712 bitmap_value_insert_into_set (EXP_GEN (block), result);
3714 continue;
3717 case GIMPLE_ASSIGN:
3719 pre_expr result = NULL;
3720 switch (vn_get_stmt_kind (stmt))
3722 case VN_NARY:
3724 enum tree_code code = gimple_assign_rhs_code (stmt);
3725 vn_nary_op_t nary;
3727 /* COND_EXPR and VEC_COND_EXPR are awkward in
3728 that they contain an embedded complex expression.
3729 Don't even try to shove those through PRE. */
3730 if (code == COND_EXPR
3731 || code == VEC_COND_EXPR)
3732 continue;
3734 vn_nary_op_lookup_stmt (stmt, &nary);
3735 if (!nary)
3736 continue;
3738 /* If the NARY traps and there was a preceding
3739 point in the block that might not return avoid
3740 adding the nary to EXP_GEN. */
3741 if (BB_MAY_NOTRETURN (block)
3742 && vn_nary_may_trap (nary))
3743 continue;
3745 result = (pre_expr) pool_alloc (pre_expr_pool);
3746 result->kind = NARY;
3747 result->id = 0;
3748 PRE_EXPR_NARY (result) = nary;
3749 break;
3752 case VN_REFERENCE:
3754 vn_reference_t ref;
3755 vn_reference_lookup (gimple_assign_rhs1 (stmt),
3756 gimple_vuse (stmt),
3757 VN_WALK, &ref);
3758 if (!ref)
3759 continue;
3761 /* If the value of the reference is not invalidated in
3762 this block until it is computed, add the expression
3763 to EXP_GEN. */
3764 if (gimple_vuse (stmt))
3766 gimple def_stmt;
3767 bool ok = true;
3768 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3769 while (!gimple_nop_p (def_stmt)
3770 && gimple_code (def_stmt) != GIMPLE_PHI
3771 && gimple_bb (def_stmt) == block)
3773 if (stmt_may_clobber_ref_p
3774 (def_stmt, gimple_assign_rhs1 (stmt)))
3776 ok = false;
3777 break;
3779 def_stmt
3780 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3782 if (!ok)
3783 continue;
3786 result = (pre_expr) pool_alloc (pre_expr_pool);
3787 result->kind = REFERENCE;
3788 result->id = 0;
3789 PRE_EXPR_REFERENCE (result) = ref;
3790 break;
3793 default:
3794 continue;
3797 get_or_alloc_expression_id (result);
3798 add_to_value (get_expr_value_id (result), result);
3799 bitmap_value_insert_into_set (EXP_GEN (block), result);
3800 continue;
3802 default:
3803 break;
3807 if (dump_file && (dump_flags & TDF_DETAILS))
3809 print_bitmap_set (dump_file, EXP_GEN (block),
3810 "exp_gen", block->index);
3811 print_bitmap_set (dump_file, PHI_GEN (block),
3812 "phi_gen", block->index);
3813 print_bitmap_set (dump_file, TMP_GEN (block),
3814 "tmp_gen", block->index);
3815 print_bitmap_set (dump_file, AVAIL_OUT (block),
3816 "avail_out", block->index);
3819 /* Put the dominator children of BLOCK on the worklist of blocks
3820 to compute available sets for. */
3821 for (son = first_dom_son (CDI_DOMINATORS, block);
3822 son;
3823 son = next_dom_son (CDI_DOMINATORS, son))
3824 worklist[sp++] = son;
3827 free (worklist);
3831 /* Local state for the eliminate domwalk. */
3832 static vec<gimple> el_to_remove;
3833 static unsigned int el_todo;
3834 static vec<tree> el_avail;
3835 static vec<tree> el_avail_stack;
3837 /* Return a leader for OP that is available at the current point of the
3838 eliminate domwalk. */
3840 static tree
3841 eliminate_avail (tree op)
3843 tree valnum = VN_INFO (op)->valnum;
3844 if (TREE_CODE (valnum) == SSA_NAME)
3846 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
3847 return valnum;
3848 if (el_avail.length () > SSA_NAME_VERSION (valnum))
3849 return el_avail[SSA_NAME_VERSION (valnum)];
3851 else if (is_gimple_min_invariant (valnum))
3852 return valnum;
3853 return NULL_TREE;
3856 /* At the current point of the eliminate domwalk make OP available. */
3858 static void
3859 eliminate_push_avail (tree op)
3861 tree valnum = VN_INFO (op)->valnum;
3862 if (TREE_CODE (valnum) == SSA_NAME)
3864 if (el_avail.length () <= SSA_NAME_VERSION (valnum))
3865 el_avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1);
3866 el_avail[SSA_NAME_VERSION (valnum)] = op;
3867 el_avail_stack.safe_push (op);
3871 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
3872 the leader for the expression if insertion was successful. */
3874 static tree
3875 eliminate_insert (gimple_stmt_iterator *gsi, tree val)
3877 tree expr = vn_get_expr_for (val);
3878 if (!CONVERT_EXPR_P (expr)
3879 && TREE_CODE (expr) != VIEW_CONVERT_EXPR)
3880 return NULL_TREE;
3882 tree op = TREE_OPERAND (expr, 0);
3883 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (op) : op;
3884 if (!leader)
3885 return NULL_TREE;
3887 tree res = make_temp_ssa_name (TREE_TYPE (val), NULL, "pretmp");
3888 gimple tem = gimple_build_assign (res,
3889 fold_build1 (TREE_CODE (expr),
3890 TREE_TYPE (expr), leader));
3891 gsi_insert_before (gsi, tem, GSI_SAME_STMT);
3892 VN_INFO_GET (res)->valnum = val;
3894 if (TREE_CODE (leader) == SSA_NAME)
3895 gimple_set_plf (SSA_NAME_DEF_STMT (leader), NECESSARY, true);
3897 pre_stats.insertions++;
3898 if (dump_file && (dump_flags & TDF_DETAILS))
3900 fprintf (dump_file, "Inserted ");
3901 print_gimple_stmt (dump_file, tem, 0, 0);
3904 return res;
3907 class eliminate_dom_walker : public dom_walker
3909 public:
3910 eliminate_dom_walker (cdi_direction direction, bool do_pre_)
3911 : dom_walker (direction), do_pre (do_pre_) {}
3913 virtual void before_dom_children (basic_block);
3914 virtual void after_dom_children (basic_block);
3916 bool do_pre;
3919 /* Perform elimination for the basic-block B during the domwalk. */
3921 void
3922 eliminate_dom_walker::before_dom_children (basic_block b)
3924 gimple_stmt_iterator gsi;
3925 gimple stmt;
3927 /* Mark new bb. */
3928 el_avail_stack.safe_push (NULL_TREE);
3930 /* ??? If we do nothing for unreachable blocks then this will confuse
3931 tailmerging. Eventually we can reduce its reliance on SCCVN now
3932 that we fully copy/constant-propagate (most) things. */
3934 for (gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
3936 gimple phi = gsi_stmt (gsi);
3937 tree res = PHI_RESULT (phi);
3939 if (virtual_operand_p (res))
3941 gsi_next (&gsi);
3942 continue;
3945 tree sprime = eliminate_avail (res);
3946 if (sprime
3947 && sprime != res)
3949 if (dump_file && (dump_flags & TDF_DETAILS))
3951 fprintf (dump_file, "Replaced redundant PHI node defining ");
3952 print_generic_expr (dump_file, res, 0);
3953 fprintf (dump_file, " with ");
3954 print_generic_expr (dump_file, sprime, 0);
3955 fprintf (dump_file, "\n");
3958 /* If we inserted this PHI node ourself, it's not an elimination. */
3959 if (inserted_exprs
3960 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
3961 pre_stats.phis--;
3962 else
3963 pre_stats.eliminations++;
3965 /* If we will propagate into all uses don't bother to do
3966 anything. */
3967 if (may_propagate_copy (res, sprime))
3969 /* Mark the PHI for removal. */
3970 el_to_remove.safe_push (phi);
3971 gsi_next (&gsi);
3972 continue;
3975 remove_phi_node (&gsi, false);
3977 if (inserted_exprs
3978 && !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res))
3979 && TREE_CODE (sprime) == SSA_NAME)
3980 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
3982 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
3983 sprime = fold_convert (TREE_TYPE (res), sprime);
3984 gimple stmt = gimple_build_assign (res, sprime);
3985 /* ??? It cannot yet be necessary (DOM walk). */
3986 gimple_set_plf (stmt, NECESSARY, gimple_plf (phi, NECESSARY));
3988 gimple_stmt_iterator gsi2 = gsi_after_labels (b);
3989 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
3990 continue;
3993 eliminate_push_avail (res);
3994 gsi_next (&gsi);
3997 for (gsi = gsi_start_bb (b); !gsi_end_p (gsi); gsi_next (&gsi))
3999 tree sprime = NULL_TREE;
4000 stmt = gsi_stmt (gsi);
4001 tree lhs = gimple_get_lhs (stmt);
4002 if (lhs && TREE_CODE (lhs) == SSA_NAME
4003 && !gimple_has_volatile_ops (stmt)
4004 /* See PR43491. Do not replace a global register variable when
4005 it is a the RHS of an assignment. Do replace local register
4006 variables since gcc does not guarantee a local variable will
4007 be allocated in register.
4008 ??? The fix isn't effective here. This should instead
4009 be ensured by not value-numbering them the same but treating
4010 them like volatiles? */
4011 && !(gimple_assign_single_p (stmt)
4012 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == VAR_DECL
4013 && DECL_HARD_REGISTER (gimple_assign_rhs1 (stmt))
4014 && is_global_var (gimple_assign_rhs1 (stmt)))))
4016 sprime = eliminate_avail (lhs);
4017 if (!sprime)
4019 /* If there is no existing usable leader but SCCVN thinks
4020 it has an expression it wants to use as replacement,
4021 insert that. */
4022 tree val = VN_INFO (lhs)->valnum;
4023 if (val != VN_TOP
4024 && TREE_CODE (val) == SSA_NAME
4025 && VN_INFO (val)->needs_insertion
4026 && VN_INFO (val)->expr != NULL_TREE
4027 && (sprime = eliminate_insert (&gsi, val)) != NULL_TREE)
4028 eliminate_push_avail (sprime);
4031 /* If this now constitutes a copy duplicate points-to
4032 and range info appropriately. This is especially
4033 important for inserted code. See tree-ssa-copy.c
4034 for similar code. */
4035 if (sprime
4036 && TREE_CODE (sprime) == SSA_NAME)
4038 basic_block sprime_b = gimple_bb (SSA_NAME_DEF_STMT (sprime));
4039 if (POINTER_TYPE_P (TREE_TYPE (lhs))
4040 && SSA_NAME_PTR_INFO (lhs)
4041 && !SSA_NAME_PTR_INFO (sprime))
4043 duplicate_ssa_name_ptr_info (sprime,
4044 SSA_NAME_PTR_INFO (lhs));
4045 if (b != sprime_b)
4046 mark_ptr_info_alignment_unknown
4047 (SSA_NAME_PTR_INFO (sprime));
4049 else if (!POINTER_TYPE_P (TREE_TYPE (lhs))
4050 && SSA_NAME_RANGE_INFO (lhs)
4051 && !SSA_NAME_RANGE_INFO (sprime)
4052 && b == sprime_b)
4053 duplicate_ssa_name_range_info (sprime,
4054 SSA_NAME_RANGE_TYPE (lhs),
4055 SSA_NAME_RANGE_INFO (lhs));
4058 /* Inhibit the use of an inserted PHI on a loop header when
4059 the address of the memory reference is a simple induction
4060 variable. In other cases the vectorizer won't do anything
4061 anyway (either it's loop invariant or a complicated
4062 expression). */
4063 if (sprime
4064 && TREE_CODE (sprime) == SSA_NAME
4065 && do_pre
4066 && flag_tree_loop_vectorize
4067 && loop_outer (b->loop_father)
4068 && has_zero_uses (sprime)
4069 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))
4070 && gimple_assign_load_p (stmt))
4072 gimple def_stmt = SSA_NAME_DEF_STMT (sprime);
4073 basic_block def_bb = gimple_bb (def_stmt);
4074 if (gimple_code (def_stmt) == GIMPLE_PHI
4075 && b->loop_father->header == def_bb)
4077 ssa_op_iter iter;
4078 tree op;
4079 bool found = false;
4080 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
4082 affine_iv iv;
4083 def_bb = gimple_bb (SSA_NAME_DEF_STMT (op));
4084 if (def_bb
4085 && flow_bb_inside_loop_p (b->loop_father, def_bb)
4086 && simple_iv (b->loop_father,
4087 b->loop_father, op, &iv, true))
4089 found = true;
4090 break;
4093 if (found)
4095 if (dump_file && (dump_flags & TDF_DETAILS))
4097 fprintf (dump_file, "Not replacing ");
4098 print_gimple_expr (dump_file, stmt, 0, 0);
4099 fprintf (dump_file, " with ");
4100 print_generic_expr (dump_file, sprime, 0);
4101 fprintf (dump_file, " which would add a loop"
4102 " carried dependence to loop %d\n",
4103 b->loop_father->num);
4105 /* Don't keep sprime available. */
4106 sprime = NULL_TREE;
4111 if (sprime)
4113 /* If we can propagate the value computed for LHS into
4114 all uses don't bother doing anything with this stmt. */
4115 if (may_propagate_copy (lhs, sprime))
4117 /* Mark it for removal. */
4118 el_to_remove.safe_push (stmt);
4120 /* ??? Don't count copy/constant propagations. */
4121 if (gimple_assign_single_p (stmt)
4122 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4123 || gimple_assign_rhs1 (stmt) == sprime))
4124 continue;
4126 if (dump_file && (dump_flags & TDF_DETAILS))
4128 fprintf (dump_file, "Replaced ");
4129 print_gimple_expr (dump_file, stmt, 0, 0);
4130 fprintf (dump_file, " with ");
4131 print_generic_expr (dump_file, sprime, 0);
4132 fprintf (dump_file, " in all uses of ");
4133 print_gimple_stmt (dump_file, stmt, 0, 0);
4136 pre_stats.eliminations++;
4137 continue;
4140 /* If this is an assignment from our leader (which
4141 happens in the case the value-number is a constant)
4142 then there is nothing to do. */
4143 if (gimple_assign_single_p (stmt)
4144 && sprime == gimple_assign_rhs1 (stmt))
4145 continue;
4147 /* Else replace its RHS. */
4148 bool can_make_abnormal_goto
4149 = is_gimple_call (stmt)
4150 && stmt_can_make_abnormal_goto (stmt);
4152 if (dump_file && (dump_flags & TDF_DETAILS))
4154 fprintf (dump_file, "Replaced ");
4155 print_gimple_expr (dump_file, stmt, 0, 0);
4156 fprintf (dump_file, " with ");
4157 print_generic_expr (dump_file, sprime, 0);
4158 fprintf (dump_file, " in ");
4159 print_gimple_stmt (dump_file, stmt, 0, 0);
4162 if (TREE_CODE (sprime) == SSA_NAME)
4163 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4164 NECESSARY, true);
4166 pre_stats.eliminations++;
4167 gimple orig_stmt = stmt;
4168 if (!useless_type_conversion_p (TREE_TYPE (lhs),
4169 TREE_TYPE (sprime)))
4170 sprime = fold_convert (TREE_TYPE (lhs), sprime);
4171 tree vdef = gimple_vdef (stmt);
4172 tree vuse = gimple_vuse (stmt);
4173 propagate_tree_value_into_stmt (&gsi, sprime);
4174 stmt = gsi_stmt (gsi);
4175 update_stmt (stmt);
4176 if (vdef != gimple_vdef (stmt))
4177 VN_INFO (vdef)->valnum = vuse;
4179 /* If we removed EH side-effects from the statement, clean
4180 its EH information. */
4181 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4183 bitmap_set_bit (need_eh_cleanup,
4184 gimple_bb (stmt)->index);
4185 if (dump_file && (dump_flags & TDF_DETAILS))
4186 fprintf (dump_file, " Removed EH side-effects.\n");
4189 /* Likewise for AB side-effects. */
4190 if (can_make_abnormal_goto
4191 && !stmt_can_make_abnormal_goto (stmt))
4193 bitmap_set_bit (need_ab_cleanup,
4194 gimple_bb (stmt)->index);
4195 if (dump_file && (dump_flags & TDF_DETAILS))
4196 fprintf (dump_file, " Removed AB side-effects.\n");
4199 continue;
4203 /* If the statement is a scalar store, see if the expression
4204 has the same value number as its rhs. If so, the store is
4205 dead. */
4206 if (gimple_assign_single_p (stmt)
4207 && !gimple_has_volatile_ops (stmt)
4208 && !is_gimple_reg (gimple_assign_lhs (stmt))
4209 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4210 || is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
4212 tree val;
4213 tree rhs = gimple_assign_rhs1 (stmt);
4214 val = vn_reference_lookup (gimple_assign_lhs (stmt),
4215 gimple_vuse (stmt), VN_WALK, NULL);
4216 if (TREE_CODE (rhs) == SSA_NAME)
4217 rhs = VN_INFO (rhs)->valnum;
4218 if (val
4219 && operand_equal_p (val, rhs, 0))
4221 if (dump_file && (dump_flags & TDF_DETAILS))
4223 fprintf (dump_file, "Deleted redundant store ");
4224 print_gimple_stmt (dump_file, stmt, 0, 0);
4227 /* Queue stmt for removal. */
4228 el_to_remove.safe_push (stmt);
4229 continue;
4233 bool can_make_abnormal_goto = stmt_can_make_abnormal_goto (stmt);
4234 bool was_noreturn = (is_gimple_call (stmt)
4235 && gimple_call_noreturn_p (stmt));
4236 tree vdef = gimple_vdef (stmt);
4237 tree vuse = gimple_vuse (stmt);
4239 /* If we didn't replace the whole stmt (or propagate the result
4240 into all uses), replace all uses on this stmt with their
4241 leaders. */
4242 use_operand_p use_p;
4243 ssa_op_iter iter;
4244 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
4246 tree use = USE_FROM_PTR (use_p);
4247 /* ??? The call code above leaves stmt operands un-updated. */
4248 if (TREE_CODE (use) != SSA_NAME)
4249 continue;
4250 tree sprime = eliminate_avail (use);
4251 if (sprime && sprime != use
4252 && may_propagate_copy (use, sprime)
4253 /* We substitute into debug stmts to avoid excessive
4254 debug temporaries created by removed stmts, but we need
4255 to avoid doing so for inserted sprimes as we never want
4256 to create debug temporaries for them. */
4257 && (!inserted_exprs
4258 || TREE_CODE (sprime) != SSA_NAME
4259 || !is_gimple_debug (stmt)
4260 || !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))))
4262 propagate_value (use_p, sprime);
4263 gimple_set_modified (stmt, true);
4264 if (TREE_CODE (sprime) == SSA_NAME
4265 && !is_gimple_debug (stmt))
4266 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4267 NECESSARY, true);
4271 /* Visit indirect calls and turn them into direct calls if
4272 possible using the devirtualization machinery. */
4273 if (is_gimple_call (stmt))
4275 tree fn = gimple_call_fn (stmt);
4276 if (fn
4277 && flag_devirtualize
4278 && virtual_method_call_p (fn))
4280 tree otr_type;
4281 HOST_WIDE_INT otr_token;
4282 ipa_polymorphic_call_context context;
4283 tree instance;
4284 bool final;
4286 instance = get_polymorphic_call_info (current_function_decl,
4288 &otr_type, &otr_token, &context, stmt);
4290 context.get_dynamic_type (instance, OBJ_TYPE_REF_OBJECT (fn), otr_type, stmt);
4292 vec <cgraph_node *>targets
4293 = possible_polymorphic_call_targets (obj_type_ref_class (fn),
4294 tree_to_uhwi
4295 (OBJ_TYPE_REF_TOKEN (fn)),
4296 context,
4297 &final);
4298 if (dump_enabled_p ())
4299 dump_possible_polymorphic_call_targets (dump_file,
4300 obj_type_ref_class (fn),
4301 tree_to_uhwi
4302 (OBJ_TYPE_REF_TOKEN (fn)),
4303 context);
4304 if (final && targets.length () <= 1 && dbg_cnt (devirt))
4306 tree fn;
4307 if (targets.length () == 1)
4308 fn = targets[0]->decl;
4309 else
4310 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
4311 if (dump_enabled_p ())
4313 location_t loc = gimple_location_safe (stmt);
4314 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
4315 "converting indirect call to "
4316 "function %s\n",
4317 cgraph_node::get (fn)->name ());
4319 gimple_call_set_fndecl (stmt, fn);
4320 gimple_set_modified (stmt, true);
4322 else
4323 gcc_assert (!ipa_intraprocedural_devirtualization (stmt));
4327 if (gimple_modified_p (stmt))
4329 /* If a formerly non-invariant ADDR_EXPR is turned into an
4330 invariant one it was on a separate stmt. */
4331 if (gimple_assign_single_p (stmt)
4332 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
4333 recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
4334 gimple old_stmt = stmt;
4335 if (is_gimple_call (stmt))
4337 /* ??? Only fold calls inplace for now, this may create new
4338 SSA names which in turn will confuse free_scc_vn SSA name
4339 release code. */
4340 fold_stmt_inplace (&gsi);
4341 /* When changing a call into a noreturn call, cfg cleanup
4342 is needed to fix up the noreturn call. */
4343 if (!was_noreturn && gimple_call_noreturn_p (stmt))
4344 el_todo |= TODO_cleanup_cfg;
4346 else
4348 fold_stmt (&gsi);
4349 stmt = gsi_stmt (gsi);
4350 if ((gimple_code (stmt) == GIMPLE_COND
4351 && (gimple_cond_true_p (stmt)
4352 || gimple_cond_false_p (stmt)))
4353 || (gimple_code (stmt) == GIMPLE_SWITCH
4354 && TREE_CODE (gimple_switch_index (stmt)) == INTEGER_CST))
4355 el_todo |= TODO_cleanup_cfg;
4357 /* If we removed EH side-effects from the statement, clean
4358 its EH information. */
4359 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
4361 bitmap_set_bit (need_eh_cleanup,
4362 gimple_bb (stmt)->index);
4363 if (dump_file && (dump_flags & TDF_DETAILS))
4364 fprintf (dump_file, " Removed EH side-effects.\n");
4366 /* Likewise for AB side-effects. */
4367 if (can_make_abnormal_goto
4368 && !stmt_can_make_abnormal_goto (stmt))
4370 bitmap_set_bit (need_ab_cleanup,
4371 gimple_bb (stmt)->index);
4372 if (dump_file && (dump_flags & TDF_DETAILS))
4373 fprintf (dump_file, " Removed AB side-effects.\n");
4375 update_stmt (stmt);
4376 if (vdef != gimple_vdef (stmt))
4377 VN_INFO (vdef)->valnum = vuse;
4380 /* Make new values available - for fully redundant LHS we
4381 continue with the next stmt above and skip this. */
4382 def_operand_p defp;
4383 FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_DEF)
4384 eliminate_push_avail (DEF_FROM_PTR (defp));
4387 /* Replace destination PHI arguments. */
4388 edge_iterator ei;
4389 edge e;
4390 FOR_EACH_EDGE (e, ei, b->succs)
4392 for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4394 gimple phi = gsi_stmt (gsi);
4395 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
4396 tree arg = USE_FROM_PTR (use_p);
4397 if (TREE_CODE (arg) != SSA_NAME
4398 || virtual_operand_p (arg))
4399 continue;
4400 tree sprime = eliminate_avail (arg);
4401 if (sprime && may_propagate_copy (arg, sprime))
4403 propagate_value (use_p, sprime);
4404 if (TREE_CODE (sprime) == SSA_NAME)
4405 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4411 /* Make no longer available leaders no longer available. */
4413 void
4414 eliminate_dom_walker::after_dom_children (basic_block)
4416 tree entry;
4417 while ((entry = el_avail_stack.pop ()) != NULL_TREE)
4418 el_avail[SSA_NAME_VERSION (VN_INFO (entry)->valnum)] = NULL_TREE;
4421 /* Eliminate fully redundant computations. */
4423 static unsigned int
4424 eliminate (bool do_pre)
4426 gimple_stmt_iterator gsi;
4427 gimple stmt;
4429 need_eh_cleanup = BITMAP_ALLOC (NULL);
4430 need_ab_cleanup = BITMAP_ALLOC (NULL);
4432 el_to_remove.create (0);
4433 el_todo = 0;
4434 el_avail.create (num_ssa_names);
4435 el_avail_stack.create (0);
4437 eliminate_dom_walker (CDI_DOMINATORS,
4438 do_pre).walk (cfun->cfg->x_entry_block_ptr);
4440 el_avail.release ();
4441 el_avail_stack.release ();
4443 /* We cannot remove stmts during BB walk, especially not release SSA
4444 names there as this confuses the VN machinery. The stmts ending
4445 up in el_to_remove are either stores or simple copies.
4446 Remove stmts in reverse order to make debug stmt creation possible. */
4447 while (!el_to_remove.is_empty ())
4449 stmt = el_to_remove.pop ();
4451 if (dump_file && (dump_flags & TDF_DETAILS))
4453 fprintf (dump_file, "Removing dead stmt ");
4454 print_gimple_stmt (dump_file, stmt, 0, 0);
4457 tree lhs;
4458 if (gimple_code (stmt) == GIMPLE_PHI)
4459 lhs = gimple_phi_result (stmt);
4460 else
4461 lhs = gimple_get_lhs (stmt);
4463 if (inserted_exprs
4464 && TREE_CODE (lhs) == SSA_NAME)
4465 bitmap_clear_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
4467 gsi = gsi_for_stmt (stmt);
4468 if (gimple_code (stmt) == GIMPLE_PHI)
4469 remove_phi_node (&gsi, true);
4470 else
4472 basic_block bb = gimple_bb (stmt);
4473 unlink_stmt_vdef (stmt);
4474 if (gsi_remove (&gsi, true))
4475 bitmap_set_bit (need_eh_cleanup, bb->index);
4476 release_defs (stmt);
4479 /* Removing a stmt may expose a forwarder block. */
4480 el_todo |= TODO_cleanup_cfg;
4482 el_to_remove.release ();
4484 return el_todo;
4487 /* Perform CFG cleanups made necessary by elimination. */
4489 static unsigned
4490 fini_eliminate (void)
4492 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
4493 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
4495 if (do_eh_cleanup)
4496 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
4498 if (do_ab_cleanup)
4499 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
4501 BITMAP_FREE (need_eh_cleanup);
4502 BITMAP_FREE (need_ab_cleanup);
4504 if (do_eh_cleanup || do_ab_cleanup)
4505 return TODO_cleanup_cfg;
4506 return 0;
4509 /* Borrow a bit of tree-ssa-dce.c for the moment.
4510 XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
4511 this may be a bit faster, and we may want critical edges kept split. */
4513 /* If OP's defining statement has not already been determined to be necessary,
4514 mark that statement necessary. Return the stmt, if it is newly
4515 necessary. */
4517 static inline gimple
4518 mark_operand_necessary (tree op)
4520 gimple stmt;
4522 gcc_assert (op);
4524 if (TREE_CODE (op) != SSA_NAME)
4525 return NULL;
4527 stmt = SSA_NAME_DEF_STMT (op);
4528 gcc_assert (stmt);
4530 if (gimple_plf (stmt, NECESSARY)
4531 || gimple_nop_p (stmt))
4532 return NULL;
4534 gimple_set_plf (stmt, NECESSARY, true);
4535 return stmt;
4538 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4539 to insert PHI nodes sometimes, and because value numbering of casts isn't
4540 perfect, we sometimes end up inserting dead code. This simple DCE-like
4541 pass removes any insertions we made that weren't actually used. */
4543 static void
4544 remove_dead_inserted_code (void)
4546 bitmap worklist;
4547 unsigned i;
4548 bitmap_iterator bi;
4549 gimple t;
4551 worklist = BITMAP_ALLOC (NULL);
4552 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4554 t = SSA_NAME_DEF_STMT (ssa_name (i));
4555 if (gimple_plf (t, NECESSARY))
4556 bitmap_set_bit (worklist, i);
4558 while (!bitmap_empty_p (worklist))
4560 i = bitmap_first_set_bit (worklist);
4561 bitmap_clear_bit (worklist, i);
4562 t = SSA_NAME_DEF_STMT (ssa_name (i));
4564 /* PHI nodes are somewhat special in that each PHI alternative has
4565 data and control dependencies. All the statements feeding the
4566 PHI node's arguments are always necessary. */
4567 if (gimple_code (t) == GIMPLE_PHI)
4569 unsigned k;
4571 for (k = 0; k < gimple_phi_num_args (t); k++)
4573 tree arg = PHI_ARG_DEF (t, k);
4574 if (TREE_CODE (arg) == SSA_NAME)
4576 gimple n = mark_operand_necessary (arg);
4577 if (n)
4578 bitmap_set_bit (worklist, SSA_NAME_VERSION (arg));
4582 else
4584 /* Propagate through the operands. Examine all the USE, VUSE and
4585 VDEF operands in this statement. Mark all the statements
4586 which feed this statement's uses as necessary. */
4587 ssa_op_iter iter;
4588 tree use;
4590 /* The operands of VDEF expressions are also needed as they
4591 represent potential definitions that may reach this
4592 statement (VDEF operands allow us to follow def-def
4593 links). */
4595 FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
4597 gimple n = mark_operand_necessary (use);
4598 if (n)
4599 bitmap_set_bit (worklist, SSA_NAME_VERSION (use));
4604 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4606 t = SSA_NAME_DEF_STMT (ssa_name (i));
4607 if (!gimple_plf (t, NECESSARY))
4609 gimple_stmt_iterator gsi;
4611 if (dump_file && (dump_flags & TDF_DETAILS))
4613 fprintf (dump_file, "Removing unnecessary insertion:");
4614 print_gimple_stmt (dump_file, t, 0, 0);
4617 gsi = gsi_for_stmt (t);
4618 if (gimple_code (t) == GIMPLE_PHI)
4619 remove_phi_node (&gsi, true);
4620 else
4622 gsi_remove (&gsi, true);
4623 release_defs (t);
4627 BITMAP_FREE (worklist);
4631 /* Initialize data structures used by PRE. */
4633 static void
4634 init_pre (void)
4636 basic_block bb;
4638 next_expression_id = 1;
4639 expressions.create (0);
4640 expressions.safe_push (NULL);
4641 value_expressions.create (get_max_value_id () + 1);
4642 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
4643 name_to_id.create (0);
4645 inserted_exprs = BITMAP_ALLOC (NULL);
4647 connect_infinite_loops_to_exit ();
4648 memset (&pre_stats, 0, sizeof (pre_stats));
4650 postorder = XNEWVEC (int, n_basic_blocks_for_fn (cfun));
4651 postorder_num = inverted_post_order_compute (postorder);
4653 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4655 calculate_dominance_info (CDI_POST_DOMINATORS);
4656 calculate_dominance_info (CDI_DOMINATORS);
4658 bitmap_obstack_initialize (&grand_bitmap_obstack);
4659 phi_translate_table = new hash_table<expr_pred_trans_d> (5110);
4660 expression_to_id = new hash_table<pre_expr_d> (num_ssa_names * 3);
4661 bitmap_set_pool = create_alloc_pool ("Bitmap sets",
4662 sizeof (struct bitmap_set), 30);
4663 pre_expr_pool = create_alloc_pool ("pre_expr nodes",
4664 sizeof (struct pre_expr_d), 30);
4665 FOR_ALL_BB_FN (bb, cfun)
4667 EXP_GEN (bb) = bitmap_set_new ();
4668 PHI_GEN (bb) = bitmap_set_new ();
4669 TMP_GEN (bb) = bitmap_set_new ();
4670 AVAIL_OUT (bb) = bitmap_set_new ();
4675 /* Deallocate data structures used by PRE. */
4677 static void
4678 fini_pre ()
4680 free (postorder);
4681 value_expressions.release ();
4682 BITMAP_FREE (inserted_exprs);
4683 bitmap_obstack_release (&grand_bitmap_obstack);
4684 free_alloc_pool (bitmap_set_pool);
4685 free_alloc_pool (pre_expr_pool);
4686 delete phi_translate_table;
4687 phi_translate_table = NULL;
4688 delete expression_to_id;
4689 expression_to_id = NULL;
4690 name_to_id.release ();
4692 free_aux_for_blocks ();
4694 free_dominance_info (CDI_POST_DOMINATORS);
4697 namespace {
4699 const pass_data pass_data_pre =
4701 GIMPLE_PASS, /* type */
4702 "pre", /* name */
4703 OPTGROUP_NONE, /* optinfo_flags */
4704 TV_TREE_PRE, /* tv_id */
4705 /* PROP_no_crit_edges is ensured by placing pass_split_crit_edges before
4706 pass_pre. */
4707 ( PROP_no_crit_edges | PROP_cfg | PROP_ssa ), /* properties_required */
4708 0, /* properties_provided */
4709 PROP_no_crit_edges, /* properties_destroyed */
4710 TODO_rebuild_alias, /* todo_flags_start */
4711 0, /* todo_flags_finish */
4714 class pass_pre : public gimple_opt_pass
4716 public:
4717 pass_pre (gcc::context *ctxt)
4718 : gimple_opt_pass (pass_data_pre, ctxt)
4721 /* opt_pass methods: */
4722 virtual bool gate (function *) { return flag_tree_pre != 0; }
4723 virtual unsigned int execute (function *);
4725 }; // class pass_pre
4727 unsigned int
4728 pass_pre::execute (function *fun)
4730 unsigned int todo = 0;
4732 do_partial_partial =
4733 flag_tree_partial_pre && optimize_function_for_speed_p (fun);
4735 /* This has to happen before SCCVN runs because
4736 loop_optimizer_init may create new phis, etc. */
4737 loop_optimizer_init (LOOPS_NORMAL);
4739 if (!run_scc_vn (VN_WALK))
4741 loop_optimizer_finalize ();
4742 return 0;
4745 init_pre ();
4746 scev_initialize ();
4748 /* Collect and value number expressions computed in each basic block. */
4749 compute_avail ();
4751 /* Insert can get quite slow on an incredibly large number of basic
4752 blocks due to some quadratic behavior. Until this behavior is
4753 fixed, don't run it when he have an incredibly large number of
4754 bb's. If we aren't going to run insert, there is no point in
4755 computing ANTIC, either, even though it's plenty fast. */
4756 if (n_basic_blocks_for_fn (fun) < 4000)
4758 compute_antic ();
4759 insert ();
4762 /* Make sure to remove fake edges before committing our inserts.
4763 This makes sure we don't end up with extra critical edges that
4764 we would need to split. */
4765 remove_fake_exit_edges ();
4766 gsi_commit_edge_inserts ();
4768 /* Remove all the redundant expressions. */
4769 todo |= eliminate (true);
4771 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
4772 statistics_counter_event (fun, "PA inserted", pre_stats.pa_insert);
4773 statistics_counter_event (fun, "New PHIs", pre_stats.phis);
4774 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
4776 clear_expression_ids ();
4777 remove_dead_inserted_code ();
4779 scev_finalize ();
4780 fini_pre ();
4781 todo |= fini_eliminate ();
4782 loop_optimizer_finalize ();
4784 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
4785 case we can merge the block with the remaining predecessor of the block.
4786 It should either:
4787 - call merge_blocks after each tail merge iteration
4788 - call merge_blocks after all tail merge iterations
4789 - mark TODO_cleanup_cfg when necessary
4790 - share the cfg cleanup with fini_pre. */
4791 todo |= tail_merge_optimize (todo);
4793 free_scc_vn ();
4795 /* Tail merging invalidates the virtual SSA web, together with
4796 cfg-cleanup opportunities exposed by PRE this will wreck the
4797 SSA updating machinery. So make sure to run update-ssa
4798 manually, before eventually scheduling cfg-cleanup as part of
4799 the todo. */
4800 update_ssa (TODO_update_ssa_only_virtuals);
4802 return todo;
4805 } // anon namespace
4807 gimple_opt_pass *
4808 make_pass_pre (gcc::context *ctxt)
4810 return new pass_pre (ctxt);
4813 namespace {
4815 const pass_data pass_data_fre =
4817 GIMPLE_PASS, /* type */
4818 "fre", /* name */
4819 OPTGROUP_NONE, /* optinfo_flags */
4820 TV_TREE_FRE, /* tv_id */
4821 ( PROP_cfg | PROP_ssa ), /* properties_required */
4822 0, /* properties_provided */
4823 0, /* properties_destroyed */
4824 0, /* todo_flags_start */
4825 0, /* todo_flags_finish */
4828 class pass_fre : public gimple_opt_pass
4830 public:
4831 pass_fre (gcc::context *ctxt)
4832 : gimple_opt_pass (pass_data_fre, ctxt)
4835 /* opt_pass methods: */
4836 opt_pass * clone () { return new pass_fre (m_ctxt); }
4837 virtual bool gate (function *) { return flag_tree_fre != 0; }
4838 virtual unsigned int execute (function *);
4840 }; // class pass_fre
4842 unsigned int
4843 pass_fre::execute (function *fun)
4845 unsigned int todo = 0;
4847 if (!run_scc_vn (VN_WALKREWRITE))
4848 return 0;
4850 memset (&pre_stats, 0, sizeof (pre_stats));
4852 /* Remove all the redundant expressions. */
4853 todo |= eliminate (false);
4855 todo |= fini_eliminate ();
4857 free_scc_vn ();
4859 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
4860 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
4862 return todo;
4865 } // anon namespace
4867 gimple_opt_pass *
4868 make_pass_fre (gcc::context *ctxt)
4870 return new pass_fre (ctxt);