2018-03-08 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / tree-ssa-pre.c
blobf165a1eb9759a69074c46711abd9aefb40696215
1 /* Full and partial redundancy elimination and code hoisting on SSA GIMPLE.
2 Copyright (C) 2001-2018 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 "backend.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "predict.h"
30 #include "alloc-pool.h"
31 #include "tree-pass.h"
32 #include "ssa.h"
33 #include "cgraph.h"
34 #include "gimple-pretty-print.h"
35 #include "fold-const.h"
36 #include "cfganal.h"
37 #include "gimple-fold.h"
38 #include "tree-eh.h"
39 #include "gimplify.h"
40 #include "gimple-iterator.h"
41 #include "tree-cfg.h"
42 #include "tree-into-ssa.h"
43 #include "tree-dfa.h"
44 #include "tree-ssa.h"
45 #include "cfgloop.h"
46 #include "tree-ssa-sccvn.h"
47 #include "tree-scalar-evolution.h"
48 #include "params.h"
49 #include "dbgcnt.h"
50 #include "domwalk.h"
51 #include "tree-ssa-propagate.h"
52 #include "tree-ssa-dce.h"
53 #include "tree-cfgcleanup.h"
54 #include "alias.h"
56 /* Even though this file is called tree-ssa-pre.c, we actually
57 implement a bit more than just PRE here. All of them piggy-back
58 on GVN which is implemented in tree-ssa-sccvn.c.
60 1. Full Redundancy Elimination (FRE)
61 This is the elimination phase of GVN.
63 2. Partial Redundancy Elimination (PRE)
64 This is adds computation of AVAIL_OUT and ANTIC_IN and
65 doing expression insertion to form GVN-PRE.
67 3. Code hoisting
68 This optimization uses the ANTIC_IN sets computed for PRE
69 to move expressions further up than PRE would do, to make
70 multiple computations of the same value fully redundant.
71 This pass is explained below (after the explanation of the
72 basic algorithm for PRE).
75 /* TODO:
77 1. Avail sets can be shared by making an avail_find_leader that
78 walks up the dominator tree and looks in those avail sets.
79 This might affect code optimality, it's unclear right now.
80 Currently the AVAIL_OUT sets are the remaining quadraticness in
81 memory of GVN-PRE.
82 2. Strength reduction can be performed by anticipating expressions
83 we can repair later on.
84 3. We can do back-substitution or smarter value numbering to catch
85 commutative expressions split up over multiple statements.
88 /* For ease of terminology, "expression node" in the below refers to
89 every expression node but GIMPLE_ASSIGN, because GIMPLE_ASSIGNs
90 represent the actual statement containing the expressions we care about,
91 and we cache the value number by putting it in the expression. */
93 /* Basic algorithm for Partial Redundancy Elimination:
95 First we walk the statements to generate the AVAIL sets, the
96 EXP_GEN sets, and the tmp_gen sets. EXP_GEN sets represent the
97 generation of values/expressions by a given block. We use them
98 when computing the ANTIC sets. The AVAIL sets consist of
99 SSA_NAME's that represent values, so we know what values are
100 available in what blocks. AVAIL is a forward dataflow problem. In
101 SSA, values are never killed, so we don't need a kill set, or a
102 fixpoint iteration, in order to calculate the AVAIL sets. In
103 traditional parlance, AVAIL sets tell us the downsafety of the
104 expressions/values.
106 Next, we generate the ANTIC sets. These sets represent the
107 anticipatable expressions. ANTIC is a backwards dataflow
108 problem. An expression is anticipatable in a given block if it could
109 be generated in that block. This means that if we had to perform
110 an insertion in that block, of the value of that expression, we
111 could. Calculating the ANTIC sets requires phi translation of
112 expressions, because the flow goes backwards through phis. We must
113 iterate to a fixpoint of the ANTIC sets, because we have a kill
114 set. Even in SSA form, values are not live over the entire
115 function, only from their definition point onwards. So we have to
116 remove values from the ANTIC set once we go past the definition
117 point of the leaders that make them up.
118 compute_antic/compute_antic_aux performs this computation.
120 Third, we perform insertions to make partially redundant
121 expressions fully redundant.
123 An expression is partially redundant (excluding partial
124 anticipation) if:
126 1. It is AVAIL in some, but not all, of the predecessors of a
127 given block.
128 2. It is ANTIC in all the predecessors.
130 In order to make it fully redundant, we insert the expression into
131 the predecessors where it is not available, but is ANTIC.
133 When optimizing for size, we only eliminate the partial redundancy
134 if we need to insert in only one predecessor. This avoids almost
135 completely the code size increase that PRE usually causes.
137 For the partial anticipation case, we only perform insertion if it
138 is partially anticipated in some block, and fully available in all
139 of the predecessors.
141 do_pre_regular_insertion/do_pre_partial_partial_insertion
142 performs these steps, driven by insert/insert_aux.
144 Fourth, we eliminate fully redundant expressions.
145 This is a simple statement walk that replaces redundant
146 calculations with the now available values. */
148 /* Basic algorithm for Code Hoisting:
150 Code hoisting is: Moving value computations up in the control flow
151 graph to make multiple copies redundant. Typically this is a size
152 optimization, but there are cases where it also is helpful for speed.
154 A simple code hoisting algorithm is implemented that piggy-backs on
155 the PRE infrastructure. For code hoisting, we have to know ANTIC_OUT
156 which is effectively ANTIC_IN - AVAIL_OUT. The latter two have to be
157 computed for PRE, and we can use them to perform a limited version of
158 code hoisting, too.
160 For the purpose of this implementation, a value is hoistable to a basic
161 block B if the following properties are met:
163 1. The value is in ANTIC_IN(B) -- the value will be computed on all
164 paths from B to function exit and it can be computed in B);
166 2. The value is not in AVAIL_OUT(B) -- there would be no need to
167 compute the value again and make it available twice;
169 3. All successors of B are dominated by B -- makes sure that inserting
170 a computation of the value in B will make the remaining
171 computations fully redundant;
173 4. At least one successor has the value in AVAIL_OUT -- to avoid
174 hoisting values up too far;
176 5. There are at least two successors of B -- hoisting in straight
177 line code is pointless.
179 The third condition is not strictly necessary, but it would complicate
180 the hoisting pass a lot. In fact, I don't know of any code hoisting
181 algorithm that does not have this requirement. Fortunately, experiments
182 have show that most candidate hoistable values are in regions that meet
183 this condition (e.g. diamond-shape regions).
185 The forth condition is necessary to avoid hoisting things up too far
186 away from the uses of the value. Nothing else limits the algorithm
187 from hoisting everything up as far as ANTIC_IN allows. Experiments
188 with SPEC and CSiBE have shown that hoisting up too far results in more
189 spilling, less benefits for code size, and worse benchmark scores.
190 Fortunately, in practice most of the interesting hoisting opportunities
191 are caught despite this limitation.
193 For hoistable values that meet all conditions, expressions are inserted
194 to make the calculation of the hoistable value fully redundant. We
195 perform code hoisting insertions after each round of PRE insertions,
196 because code hoisting never exposes new PRE opportunities, but PRE can
197 create new code hoisting opportunities.
199 The code hoisting algorithm is implemented in do_hoist_insert, driven
200 by insert/insert_aux. */
202 /* Representations of value numbers:
204 Value numbers are represented by a representative SSA_NAME. We
205 will create fake SSA_NAME's in situations where we need a
206 representative but do not have one (because it is a complex
207 expression). In order to facilitate storing the value numbers in
208 bitmaps, and keep the number of wasted SSA_NAME's down, we also
209 associate a value_id with each value number, and create full blown
210 ssa_name's only where we actually need them (IE in operands of
211 existing expressions).
213 Theoretically you could replace all the value_id's with
214 SSA_NAME_VERSION, but this would allocate a large number of
215 SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
216 It would also require an additional indirection at each point we
217 use the value id. */
219 /* Representation of expressions on value numbers:
221 Expressions consisting of value numbers are represented the same
222 way as our VN internally represents them, with an additional
223 "pre_expr" wrapping around them in order to facilitate storing all
224 of the expressions in the same sets. */
226 /* Representation of sets:
228 The dataflow sets do not need to be sorted in any particular order
229 for the majority of their lifetime, are simply represented as two
230 bitmaps, one that keeps track of values present in the set, and one
231 that keeps track of expressions present in the set.
233 When we need them in topological order, we produce it on demand by
234 transforming the bitmap into an array and sorting it into topo
235 order. */
237 /* Type of expression, used to know which member of the PRE_EXPR union
238 is valid. */
240 enum pre_expr_kind
242 NAME,
243 NARY,
244 REFERENCE,
245 CONSTANT
248 union pre_expr_union
250 tree name;
251 tree constant;
252 vn_nary_op_t nary;
253 vn_reference_t reference;
256 typedef struct pre_expr_d : nofree_ptr_hash <pre_expr_d>
258 enum pre_expr_kind kind;
259 unsigned int id;
260 pre_expr_union u;
262 /* hash_table support. */
263 static inline hashval_t hash (const pre_expr_d *);
264 static inline int equal (const pre_expr_d *, const pre_expr_d *);
265 } *pre_expr;
267 #define PRE_EXPR_NAME(e) (e)->u.name
268 #define PRE_EXPR_NARY(e) (e)->u.nary
269 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
270 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
272 /* Compare E1 and E1 for equality. */
274 inline int
275 pre_expr_d::equal (const pre_expr_d *e1, const pre_expr_d *e2)
277 if (e1->kind != e2->kind)
278 return false;
280 switch (e1->kind)
282 case CONSTANT:
283 return vn_constant_eq_with_type (PRE_EXPR_CONSTANT (e1),
284 PRE_EXPR_CONSTANT (e2));
285 case NAME:
286 return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
287 case NARY:
288 return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
289 case REFERENCE:
290 return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
291 PRE_EXPR_REFERENCE (e2));
292 default:
293 gcc_unreachable ();
297 /* Hash E. */
299 inline hashval_t
300 pre_expr_d::hash (const pre_expr_d *e)
302 switch (e->kind)
304 case CONSTANT:
305 return vn_hash_constant_with_type (PRE_EXPR_CONSTANT (e));
306 case NAME:
307 return SSA_NAME_VERSION (PRE_EXPR_NAME (e));
308 case NARY:
309 return PRE_EXPR_NARY (e)->hashcode;
310 case REFERENCE:
311 return PRE_EXPR_REFERENCE (e)->hashcode;
312 default:
313 gcc_unreachable ();
317 /* Next global expression id number. */
318 static unsigned int next_expression_id;
320 /* Mapping from expression to id number we can use in bitmap sets. */
321 static vec<pre_expr> expressions;
322 static hash_table<pre_expr_d> *expression_to_id;
323 static vec<unsigned> name_to_id;
325 /* Allocate an expression id for EXPR. */
327 static inline unsigned int
328 alloc_expression_id (pre_expr expr)
330 struct pre_expr_d **slot;
331 /* Make sure we won't overflow. */
332 gcc_assert (next_expression_id + 1 > next_expression_id);
333 expr->id = next_expression_id++;
334 expressions.safe_push (expr);
335 if (expr->kind == NAME)
337 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
338 /* vec::safe_grow_cleared allocates no headroom. Avoid frequent
339 re-allocations by using vec::reserve upfront. */
340 unsigned old_len = name_to_id.length ();
341 name_to_id.reserve (num_ssa_names - old_len);
342 name_to_id.quick_grow_cleared (num_ssa_names);
343 gcc_assert (name_to_id[version] == 0);
344 name_to_id[version] = expr->id;
346 else
348 slot = expression_to_id->find_slot (expr, INSERT);
349 gcc_assert (!*slot);
350 *slot = expr;
352 return next_expression_id - 1;
355 /* Return the expression id for tree EXPR. */
357 static inline unsigned int
358 get_expression_id (const pre_expr expr)
360 return expr->id;
363 static inline unsigned int
364 lookup_expression_id (const pre_expr expr)
366 struct pre_expr_d **slot;
368 if (expr->kind == NAME)
370 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
371 if (name_to_id.length () <= version)
372 return 0;
373 return name_to_id[version];
375 else
377 slot = expression_to_id->find_slot (expr, NO_INSERT);
378 if (!slot)
379 return 0;
380 return ((pre_expr)*slot)->id;
384 /* Return the existing expression id for EXPR, or create one if one
385 does not exist yet. */
387 static inline unsigned int
388 get_or_alloc_expression_id (pre_expr expr)
390 unsigned int id = lookup_expression_id (expr);
391 if (id == 0)
392 return alloc_expression_id (expr);
393 return expr->id = id;
396 /* Return the expression that has expression id ID */
398 static inline pre_expr
399 expression_for_id (unsigned int id)
401 return expressions[id];
404 static object_allocator<pre_expr_d> pre_expr_pool ("pre_expr nodes");
406 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it. */
408 static pre_expr
409 get_or_alloc_expr_for_name (tree name)
411 struct pre_expr_d expr;
412 pre_expr result;
413 unsigned int result_id;
415 expr.kind = NAME;
416 expr.id = 0;
417 PRE_EXPR_NAME (&expr) = name;
418 result_id = lookup_expression_id (&expr);
419 if (result_id != 0)
420 return expression_for_id (result_id);
422 result = pre_expr_pool.allocate ();
423 result->kind = NAME;
424 PRE_EXPR_NAME (result) = name;
425 alloc_expression_id (result);
426 return result;
429 /* An unordered bitmap set. One bitmap tracks values, the other,
430 expressions. */
431 typedef struct bitmap_set
433 bitmap_head expressions;
434 bitmap_head values;
435 } *bitmap_set_t;
437 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi) \
438 EXECUTE_IF_SET_IN_BITMAP (&(set)->expressions, 0, (id), (bi))
440 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi) \
441 EXECUTE_IF_SET_IN_BITMAP (&(set)->values, 0, (id), (bi))
443 /* Mapping from value id to expressions with that value_id. */
444 static vec<bitmap> value_expressions;
446 /* Sets that we need to keep track of. */
447 typedef struct bb_bitmap_sets
449 /* The EXP_GEN set, which represents expressions/values generated in
450 a basic block. */
451 bitmap_set_t exp_gen;
453 /* The PHI_GEN set, which represents PHI results generated in a
454 basic block. */
455 bitmap_set_t phi_gen;
457 /* The TMP_GEN set, which represents results/temporaries generated
458 in a basic block. IE the LHS of an expression. */
459 bitmap_set_t tmp_gen;
461 /* The AVAIL_OUT set, which represents which values are available in
462 a given basic block. */
463 bitmap_set_t avail_out;
465 /* The ANTIC_IN set, which represents which values are anticipatable
466 in a given basic block. */
467 bitmap_set_t antic_in;
469 /* The PA_IN set, which represents which values are
470 partially anticipatable in a given basic block. */
471 bitmap_set_t pa_in;
473 /* The NEW_SETS set, which is used during insertion to augment the
474 AVAIL_OUT set of blocks with the new insertions performed during
475 the current iteration. */
476 bitmap_set_t new_sets;
478 /* A cache for value_dies_in_block_x. */
479 bitmap expr_dies;
481 /* The live virtual operand on successor edges. */
482 tree vop_on_exit;
484 /* True if we have visited this block during ANTIC calculation. */
485 unsigned int visited : 1;
487 /* True if we have visited this block after all successors have been
488 visited this way. */
489 unsigned int visited_with_visited_succs : 1;
491 /* True when the block contains a call that might not return. */
492 unsigned int contains_may_not_return_call : 1;
493 } *bb_value_sets_t;
495 #define EXP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->exp_gen
496 #define PHI_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->phi_gen
497 #define TMP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->tmp_gen
498 #define AVAIL_OUT(BB) ((bb_value_sets_t) ((BB)->aux))->avail_out
499 #define ANTIC_IN(BB) ((bb_value_sets_t) ((BB)->aux))->antic_in
500 #define PA_IN(BB) ((bb_value_sets_t) ((BB)->aux))->pa_in
501 #define NEW_SETS(BB) ((bb_value_sets_t) ((BB)->aux))->new_sets
502 #define EXPR_DIES(BB) ((bb_value_sets_t) ((BB)->aux))->expr_dies
503 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
504 #define BB_VISITED_WITH_VISITED_SUCCS(BB) \
505 ((bb_value_sets_t) ((BB)->aux))->visited_with_visited_succs
506 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
507 #define BB_LIVE_VOP_ON_EXIT(BB) ((bb_value_sets_t) ((BB)->aux))->vop_on_exit
510 /* This structure is used to keep track of statistics on what
511 optimization PRE was able to perform. */
512 static struct
514 /* The number of new expressions/temporaries generated by PRE. */
515 int insertions;
517 /* The number of inserts found due to partial anticipation */
518 int pa_insert;
520 /* The number of inserts made for code hoisting. */
521 int hoist_insert;
523 /* The number of new PHI nodes added by PRE. */
524 int phis;
525 } pre_stats;
527 static bool do_partial_partial;
528 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
529 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
530 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
531 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
532 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
533 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
534 static bitmap_set_t bitmap_set_new (void);
535 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
536 tree);
537 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
538 static unsigned int get_expr_value_id (pre_expr);
540 /* We can add and remove elements and entries to and from sets
541 and hash tables, so we use alloc pools for them. */
543 static object_allocator<bitmap_set> bitmap_set_pool ("Bitmap sets");
544 static bitmap_obstack grand_bitmap_obstack;
546 /* A three tuple {e, pred, v} used to cache phi translations in the
547 phi_translate_table. */
549 typedef struct expr_pred_trans_d : free_ptr_hash<expr_pred_trans_d>
551 /* The expression. */
552 pre_expr e;
554 /* The predecessor block along which we translated the expression. */
555 basic_block pred;
557 /* The value that resulted from the translation. */
558 pre_expr v;
560 /* The hashcode for the expression, pred pair. This is cached for
561 speed reasons. */
562 hashval_t hashcode;
564 /* hash_table support. */
565 static inline hashval_t hash (const expr_pred_trans_d *);
566 static inline int equal (const expr_pred_trans_d *, const expr_pred_trans_d *);
567 } *expr_pred_trans_t;
568 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
570 inline hashval_t
571 expr_pred_trans_d::hash (const expr_pred_trans_d *e)
573 return e->hashcode;
576 inline int
577 expr_pred_trans_d::equal (const expr_pred_trans_d *ve1,
578 const expr_pred_trans_d *ve2)
580 basic_block b1 = ve1->pred;
581 basic_block b2 = ve2->pred;
583 /* If they are not translations for the same basic block, they can't
584 be equal. */
585 if (b1 != b2)
586 return false;
587 return pre_expr_d::equal (ve1->e, ve2->e);
590 /* The phi_translate_table caches phi translations for a given
591 expression and predecessor. */
592 static hash_table<expr_pred_trans_d> *phi_translate_table;
594 /* Add the tuple mapping from {expression E, basic block PRED} to
595 the phi translation table and return whether it pre-existed. */
597 static inline bool
598 phi_trans_add (expr_pred_trans_t *entry, pre_expr e, basic_block pred)
600 expr_pred_trans_t *slot;
601 expr_pred_trans_d tem;
602 hashval_t hash = iterative_hash_hashval_t (pre_expr_d::hash (e),
603 pred->index);
604 tem.e = e;
605 tem.pred = pred;
606 tem.hashcode = hash;
607 slot = phi_translate_table->find_slot_with_hash (&tem, hash, INSERT);
608 if (*slot)
610 *entry = *slot;
611 return true;
614 *entry = *slot = XNEW (struct expr_pred_trans_d);
615 (*entry)->e = e;
616 (*entry)->pred = pred;
617 (*entry)->hashcode = hash;
618 return false;
622 /* Add expression E to the expression set of value id V. */
624 static void
625 add_to_value (unsigned int v, pre_expr e)
627 bitmap set;
629 gcc_checking_assert (get_expr_value_id (e) == v);
631 if (v >= value_expressions.length ())
633 value_expressions.safe_grow_cleared (v + 1);
636 set = value_expressions[v];
637 if (!set)
639 set = BITMAP_ALLOC (&grand_bitmap_obstack);
640 value_expressions[v] = set;
643 bitmap_set_bit (set, get_or_alloc_expression_id (e));
646 /* Create a new bitmap set and return it. */
648 static bitmap_set_t
649 bitmap_set_new (void)
651 bitmap_set_t ret = bitmap_set_pool.allocate ();
652 bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
653 bitmap_initialize (&ret->values, &grand_bitmap_obstack);
654 return ret;
657 /* Return the value id for a PRE expression EXPR. */
659 static unsigned int
660 get_expr_value_id (pre_expr expr)
662 unsigned int id;
663 switch (expr->kind)
665 case CONSTANT:
666 id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
667 break;
668 case NAME:
669 id = VN_INFO (PRE_EXPR_NAME (expr))->value_id;
670 break;
671 case NARY:
672 id = PRE_EXPR_NARY (expr)->value_id;
673 break;
674 case REFERENCE:
675 id = PRE_EXPR_REFERENCE (expr)->value_id;
676 break;
677 default:
678 gcc_unreachable ();
680 /* ??? We cannot assert that expr has a value-id (it can be 0), because
681 we assign value-ids only to expressions that have a result
682 in set_hashtable_value_ids. */
683 return id;
686 /* Return a SCCVN valnum (SSA name or constant) for the PRE value-id VAL. */
688 static tree
689 sccvn_valnum_from_value_id (unsigned int val)
691 bitmap_iterator bi;
692 unsigned int i;
693 bitmap exprset = value_expressions[val];
694 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
696 pre_expr vexpr = expression_for_id (i);
697 if (vexpr->kind == NAME)
698 return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
699 else if (vexpr->kind == CONSTANT)
700 return PRE_EXPR_CONSTANT (vexpr);
702 return NULL_TREE;
705 /* Insert an expression EXPR into a bitmapped set. */
707 static void
708 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
710 unsigned int val = get_expr_value_id (expr);
711 if (! value_id_constant_p (val))
713 /* Note this is the only function causing multiple expressions
714 for the same value to appear in a set. This is needed for
715 TMP_GEN, PHI_GEN and NEW_SETs. */
716 bitmap_set_bit (&set->values, val);
717 bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
721 /* Copy a bitmapped set ORIG, into bitmapped set DEST. */
723 static void
724 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
726 bitmap_copy (&dest->expressions, &orig->expressions);
727 bitmap_copy (&dest->values, &orig->values);
731 /* Free memory used up by SET. */
732 static void
733 bitmap_set_free (bitmap_set_t set)
735 bitmap_clear (&set->expressions);
736 bitmap_clear (&set->values);
740 /* Generate an topological-ordered array of bitmap set SET. */
742 static vec<pre_expr>
743 sorted_array_from_bitmap_set (bitmap_set_t set)
745 unsigned int i, j;
746 bitmap_iterator bi, bj;
747 vec<pre_expr> result;
749 /* Pre-allocate enough space for the array. */
750 result.create (bitmap_count_bits (&set->expressions));
752 FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
754 /* The number of expressions having a given value is usually
755 relatively small. Thus, rather than making a vector of all
756 the expressions and sorting it by value-id, we walk the values
757 and check in the reverse mapping that tells us what expressions
758 have a given value, to filter those in our set. As a result,
759 the expressions are inserted in value-id order, which means
760 topological order.
762 If this is somehow a significant lose for some cases, we can
763 choose which set to walk based on the set size. */
764 bitmap exprset = value_expressions[i];
765 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bj)
767 if (bitmap_bit_p (&set->expressions, j))
768 result.quick_push (expression_for_id (j));
772 return result;
775 /* Subtract all expressions contained in ORIG from DEST. */
777 static bitmap_set_t
778 bitmap_set_subtract_expressions (bitmap_set_t dest, bitmap_set_t orig)
780 bitmap_set_t result = bitmap_set_new ();
781 bitmap_iterator bi;
782 unsigned int i;
784 bitmap_and_compl (&result->expressions, &dest->expressions,
785 &orig->expressions);
787 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
789 pre_expr expr = expression_for_id (i);
790 unsigned int value_id = get_expr_value_id (expr);
791 bitmap_set_bit (&result->values, value_id);
794 return result;
797 /* Subtract all values in bitmap set B from bitmap set A. */
799 static void
800 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
802 unsigned int i;
803 bitmap_iterator bi;
804 unsigned to_remove = -1U;
805 bitmap_and_compl_into (&a->values, &b->values);
806 FOR_EACH_EXPR_ID_IN_SET (a, i, bi)
808 if (to_remove != -1U)
810 bitmap_clear_bit (&a->expressions, to_remove);
811 to_remove = -1U;
813 pre_expr expr = expression_for_id (i);
814 if (! bitmap_bit_p (&a->values, get_expr_value_id (expr)))
815 to_remove = i;
817 if (to_remove != -1U)
818 bitmap_clear_bit (&a->expressions, to_remove);
822 /* Return true if bitmapped set SET contains the value VALUE_ID. */
824 static bool
825 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
827 if (value_id_constant_p (value_id))
828 return true;
830 return bitmap_bit_p (&set->values, value_id);
833 static inline bool
834 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
836 return bitmap_bit_p (&set->expressions, get_expression_id (expr));
839 /* Return true if two bitmap sets are equal. */
841 static bool
842 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
844 return bitmap_equal_p (&a->values, &b->values);
847 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
848 and add it otherwise. */
850 static void
851 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
853 unsigned int val = get_expr_value_id (expr);
854 if (value_id_constant_p (val))
855 return;
857 if (bitmap_set_contains_value (set, val))
859 /* The number of expressions having a given value is usually
860 significantly less than the total number of expressions in SET.
861 Thus, rather than check, for each expression in SET, whether it
862 has the value LOOKFOR, we walk the reverse mapping that tells us
863 what expressions have a given value, and see if any of those
864 expressions are in our set. For large testcases, this is about
865 5-10x faster than walking the bitmap. If this is somehow a
866 significant lose for some cases, we can choose which set to walk
867 based on the set size. */
868 unsigned int i;
869 bitmap_iterator bi;
870 bitmap exprset = value_expressions[val];
871 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
873 if (bitmap_clear_bit (&set->expressions, i))
875 bitmap_set_bit (&set->expressions, get_expression_id (expr));
876 return;
879 gcc_unreachable ();
881 else
882 bitmap_insert_into_set (set, expr);
885 /* Insert EXPR into SET if EXPR's value is not already present in
886 SET. */
888 static void
889 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
891 unsigned int val = get_expr_value_id (expr);
893 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
895 /* Constant values are always considered to be part of the set. */
896 if (value_id_constant_p (val))
897 return;
899 /* If the value membership changed, add the expression. */
900 if (bitmap_set_bit (&set->values, val))
901 bitmap_set_bit (&set->expressions, expr->id);
904 /* Print out EXPR to outfile. */
906 static void
907 print_pre_expr (FILE *outfile, const pre_expr expr)
909 if (! expr)
911 fprintf (outfile, "NULL");
912 return;
914 switch (expr->kind)
916 case CONSTANT:
917 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr));
918 break;
919 case NAME:
920 print_generic_expr (outfile, PRE_EXPR_NAME (expr));
921 break;
922 case NARY:
924 unsigned int i;
925 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
926 fprintf (outfile, "{%s,", get_tree_code_name (nary->opcode));
927 for (i = 0; i < nary->length; i++)
929 print_generic_expr (outfile, nary->op[i]);
930 if (i != (unsigned) nary->length - 1)
931 fprintf (outfile, ",");
933 fprintf (outfile, "}");
935 break;
937 case REFERENCE:
939 vn_reference_op_t vro;
940 unsigned int i;
941 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
942 fprintf (outfile, "{");
943 for (i = 0;
944 ref->operands.iterate (i, &vro);
945 i++)
947 bool closebrace = false;
948 if (vro->opcode != SSA_NAME
949 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
951 fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
952 if (vro->op0)
954 fprintf (outfile, "<");
955 closebrace = true;
958 if (vro->op0)
960 print_generic_expr (outfile, vro->op0);
961 if (vro->op1)
963 fprintf (outfile, ",");
964 print_generic_expr (outfile, vro->op1);
966 if (vro->op2)
968 fprintf (outfile, ",");
969 print_generic_expr (outfile, vro->op2);
972 if (closebrace)
973 fprintf (outfile, ">");
974 if (i != ref->operands.length () - 1)
975 fprintf (outfile, ",");
977 fprintf (outfile, "}");
978 if (ref->vuse)
980 fprintf (outfile, "@");
981 print_generic_expr (outfile, ref->vuse);
984 break;
987 void debug_pre_expr (pre_expr);
989 /* Like print_pre_expr but always prints to stderr. */
990 DEBUG_FUNCTION void
991 debug_pre_expr (pre_expr e)
993 print_pre_expr (stderr, e);
994 fprintf (stderr, "\n");
997 /* Print out SET to OUTFILE. */
999 static void
1000 print_bitmap_set (FILE *outfile, bitmap_set_t set,
1001 const char *setname, int blockindex)
1003 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
1004 if (set)
1006 bool first = true;
1007 unsigned i;
1008 bitmap_iterator bi;
1010 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1012 const pre_expr expr = expression_for_id (i);
1014 if (!first)
1015 fprintf (outfile, ", ");
1016 first = false;
1017 print_pre_expr (outfile, expr);
1019 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1022 fprintf (outfile, " }\n");
1025 void debug_bitmap_set (bitmap_set_t);
1027 DEBUG_FUNCTION void
1028 debug_bitmap_set (bitmap_set_t set)
1030 print_bitmap_set (stderr, set, "debug", 0);
1033 void debug_bitmap_sets_for (basic_block);
1035 DEBUG_FUNCTION void
1036 debug_bitmap_sets_for (basic_block bb)
1038 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1039 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1040 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1041 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1042 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1043 if (do_partial_partial)
1044 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1045 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1048 /* Print out the expressions that have VAL to OUTFILE. */
1050 static void
1051 print_value_expressions (FILE *outfile, unsigned int val)
1053 bitmap set = value_expressions[val];
1054 if (set)
1056 bitmap_set x;
1057 char s[10];
1058 sprintf (s, "%04d", val);
1059 x.expressions = *set;
1060 print_bitmap_set (outfile, &x, s, 0);
1065 DEBUG_FUNCTION void
1066 debug_value_expressions (unsigned int val)
1068 print_value_expressions (stderr, val);
1071 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1072 represent it. */
1074 static pre_expr
1075 get_or_alloc_expr_for_constant (tree constant)
1077 unsigned int result_id;
1078 unsigned int value_id;
1079 struct pre_expr_d expr;
1080 pre_expr newexpr;
1082 expr.kind = CONSTANT;
1083 PRE_EXPR_CONSTANT (&expr) = constant;
1084 result_id = lookup_expression_id (&expr);
1085 if (result_id != 0)
1086 return expression_for_id (result_id);
1088 newexpr = pre_expr_pool.allocate ();
1089 newexpr->kind = CONSTANT;
1090 PRE_EXPR_CONSTANT (newexpr) = constant;
1091 alloc_expression_id (newexpr);
1092 value_id = get_or_alloc_constant_value_id (constant);
1093 add_to_value (value_id, newexpr);
1094 return newexpr;
1097 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1098 Currently only supports constants and SSA_NAMES. */
1099 static pre_expr
1100 get_or_alloc_expr_for (tree t)
1102 if (TREE_CODE (t) == SSA_NAME)
1103 return get_or_alloc_expr_for_name (t);
1104 else if (is_gimple_min_invariant (t))
1105 return get_or_alloc_expr_for_constant (t);
1106 gcc_unreachable ();
1109 /* Return the folded version of T if T, when folded, is a gimple
1110 min_invariant or an SSA name. Otherwise, return T. */
1112 static pre_expr
1113 fully_constant_expression (pre_expr e)
1115 switch (e->kind)
1117 case CONSTANT:
1118 return e;
1119 case NARY:
1121 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1122 tree res = vn_nary_simplify (nary);
1123 if (!res)
1124 return e;
1125 if (is_gimple_min_invariant (res))
1126 return get_or_alloc_expr_for_constant (res);
1127 if (TREE_CODE (res) == SSA_NAME)
1128 return get_or_alloc_expr_for_name (res);
1129 return e;
1131 case REFERENCE:
1133 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1134 tree folded;
1135 if ((folded = fully_constant_vn_reference_p (ref)))
1136 return get_or_alloc_expr_for_constant (folded);
1137 return e;
1139 default:
1140 return e;
1142 return e;
1145 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1146 it has the value it would have in BLOCK. Set *SAME_VALID to true
1147 in case the new vuse doesn't change the value id of the OPERANDS. */
1149 static tree
1150 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1151 alias_set_type set, tree type, tree vuse,
1152 basic_block phiblock,
1153 basic_block block, bool *same_valid)
1155 gimple *phi = SSA_NAME_DEF_STMT (vuse);
1156 ao_ref ref;
1157 edge e = NULL;
1158 bool use_oracle;
1160 *same_valid = true;
1162 if (gimple_bb (phi) != phiblock)
1163 return vuse;
1165 use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1167 /* Use the alias-oracle to find either the PHI node in this block,
1168 the first VUSE used in this block that is equivalent to vuse or
1169 the first VUSE which definition in this block kills the value. */
1170 if (gimple_code (phi) == GIMPLE_PHI)
1171 e = find_edge (block, phiblock);
1172 else if (use_oracle)
1173 while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1175 vuse = gimple_vuse (phi);
1176 phi = SSA_NAME_DEF_STMT (vuse);
1177 if (gimple_bb (phi) != phiblock)
1178 return vuse;
1179 if (gimple_code (phi) == GIMPLE_PHI)
1181 e = find_edge (block, phiblock);
1182 break;
1185 else
1186 return NULL_TREE;
1188 if (e)
1190 if (use_oracle)
1192 bitmap visited = NULL;
1193 unsigned int cnt;
1194 /* Try to find a vuse that dominates this phi node by skipping
1195 non-clobbering statements. */
1196 vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false,
1197 NULL, NULL);
1198 if (visited)
1199 BITMAP_FREE (visited);
1201 else
1202 vuse = NULL_TREE;
1203 if (!vuse)
1205 /* If we didn't find any, the value ID can't stay the same,
1206 but return the translated vuse. */
1207 *same_valid = false;
1208 vuse = PHI_ARG_DEF (phi, e->dest_idx);
1210 /* ??? We would like to return vuse here as this is the canonical
1211 upmost vdef that this reference is associated with. But during
1212 insertion of the references into the hash tables we only ever
1213 directly insert with their direct gimple_vuse, hence returning
1214 something else would make us not find the other expression. */
1215 return PHI_ARG_DEF (phi, e->dest_idx);
1218 return NULL_TREE;
1221 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1222 SET2 *or* SET3. This is used to avoid making a set consisting of the union
1223 of PA_IN and ANTIC_IN during insert and phi-translation. */
1225 static inline pre_expr
1226 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2,
1227 bitmap_set_t set3 = NULL)
1229 pre_expr result = NULL;
1231 if (set1)
1232 result = bitmap_find_leader (set1, val);
1233 if (!result && set2)
1234 result = bitmap_find_leader (set2, val);
1235 if (!result && set3)
1236 result = bitmap_find_leader (set3, val);
1237 return result;
1240 /* Get the tree type for our PRE expression e. */
1242 static tree
1243 get_expr_type (const pre_expr e)
1245 switch (e->kind)
1247 case NAME:
1248 return TREE_TYPE (PRE_EXPR_NAME (e));
1249 case CONSTANT:
1250 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1251 case REFERENCE:
1252 return PRE_EXPR_REFERENCE (e)->type;
1253 case NARY:
1254 return PRE_EXPR_NARY (e)->type;
1256 gcc_unreachable ();
1259 /* Get a representative SSA_NAME for a given expression that is available in B.
1260 Since all of our sub-expressions are treated as values, we require
1261 them to be SSA_NAME's for simplicity.
1262 Prior versions of GVNPRE used to use "value handles" here, so that
1263 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1264 either case, the operands are really values (IE we do not expect
1265 them to be usable without finding leaders). */
1267 static tree
1268 get_representative_for (const pre_expr e, basic_block b = NULL)
1270 tree name, valnum = NULL_TREE;
1271 unsigned int value_id = get_expr_value_id (e);
1273 switch (e->kind)
1275 case NAME:
1276 return VN_INFO (PRE_EXPR_NAME (e))->valnum;
1277 case CONSTANT:
1278 return PRE_EXPR_CONSTANT (e);
1279 case NARY:
1280 case REFERENCE:
1282 /* Go through all of the expressions representing this value
1283 and pick out an SSA_NAME. */
1284 unsigned int i;
1285 bitmap_iterator bi;
1286 bitmap exprs = value_expressions[value_id];
1287 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1289 pre_expr rep = expression_for_id (i);
1290 if (rep->kind == NAME)
1292 tree name = PRE_EXPR_NAME (rep);
1293 valnum = VN_INFO (name)->valnum;
1294 gimple *def = SSA_NAME_DEF_STMT (name);
1295 /* We have to return either a new representative or one
1296 that can be used for expression simplification and thus
1297 is available in B. */
1298 if (! b
1299 || gimple_nop_p (def)
1300 || dominated_by_p (CDI_DOMINATORS, b, gimple_bb (def)))
1301 return name;
1303 else if (rep->kind == CONSTANT)
1304 return PRE_EXPR_CONSTANT (rep);
1307 break;
1310 /* If we reached here we couldn't find an SSA_NAME. This can
1311 happen when we've discovered a value that has never appeared in
1312 the program as set to an SSA_NAME, as the result of phi translation.
1313 Create one here.
1314 ??? We should be able to re-use this when we insert the statement
1315 to compute it. */
1316 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1317 VN_INFO_GET (name)->value_id = value_id;
1318 VN_INFO (name)->valnum = valnum ? valnum : name;
1319 /* ??? For now mark this SSA name for release by SCCVN. */
1320 VN_INFO (name)->needs_insertion = true;
1321 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1322 if (dump_file && (dump_flags & TDF_DETAILS))
1324 fprintf (dump_file, "Created SSA_NAME representative ");
1325 print_generic_expr (dump_file, name);
1326 fprintf (dump_file, " for expression:");
1327 print_pre_expr (dump_file, e);
1328 fprintf (dump_file, " (%04d)\n", value_id);
1331 return name;
1335 static pre_expr
1336 phi_translate (bitmap_set_t, pre_expr, bitmap_set_t, bitmap_set_t, edge);
1338 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1339 the phis in PRED. Return NULL if we can't find a leader for each part
1340 of the translated expression. */
1342 static pre_expr
1343 phi_translate_1 (bitmap_set_t dest,
1344 pre_expr expr, bitmap_set_t set1, bitmap_set_t set2, edge e)
1346 basic_block pred = e->src;
1347 basic_block phiblock = e->dest;
1348 switch (expr->kind)
1350 case NARY:
1352 unsigned int i;
1353 bool changed = false;
1354 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1355 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1356 sizeof_vn_nary_op (nary->length));
1357 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1359 for (i = 0; i < newnary->length; i++)
1361 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1362 continue;
1363 else
1365 pre_expr leader, result;
1366 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1367 leader = find_leader_in_sets (op_val_id, set1, set2);
1368 result = phi_translate (dest, leader, set1, set2, e);
1369 if (result && result != leader)
1370 /* If op has a leader in the sets we translate make
1371 sure to use the value of the translated expression.
1372 We might need a new representative for that. */
1373 newnary->op[i] = get_representative_for (result, pred);
1374 else if (!result)
1375 return NULL;
1377 changed |= newnary->op[i] != nary->op[i];
1380 if (changed)
1382 pre_expr constant;
1383 unsigned int new_val_id;
1385 PRE_EXPR_NARY (expr) = newnary;
1386 constant = fully_constant_expression (expr);
1387 PRE_EXPR_NARY (expr) = nary;
1388 if (constant != expr)
1390 /* For non-CONSTANTs we have to make sure we can eventually
1391 insert the expression. Which means we need to have a
1392 leader for it. */
1393 if (constant->kind != CONSTANT)
1395 /* Do not allow simplifications to non-constants over
1396 backedges as this will likely result in a loop PHI node
1397 to be inserted and increased register pressure.
1398 See PR77498 - this avoids doing predcoms work in
1399 a less efficient way. */
1400 if (e->flags & EDGE_DFS_BACK)
1402 else
1404 unsigned value_id = get_expr_value_id (constant);
1405 /* We want a leader in ANTIC_OUT or AVAIL_OUT here.
1406 dest has what we computed into ANTIC_OUT sofar
1407 so pick from that - since topological sorting
1408 by sorted_array_from_bitmap_set isn't perfect
1409 we may lose some cases here. */
1410 constant = find_leader_in_sets (value_id, dest,
1411 AVAIL_OUT (pred));
1412 if (constant)
1413 return constant;
1416 else
1417 return constant;
1420 /* vn_nary_* do not valueize operands. */
1421 for (i = 0; i < newnary->length; ++i)
1422 if (TREE_CODE (newnary->op[i]) == SSA_NAME)
1423 newnary->op[i] = VN_INFO (newnary->op[i])->valnum;
1424 tree result = vn_nary_op_lookup_pieces (newnary->length,
1425 newnary->opcode,
1426 newnary->type,
1427 &newnary->op[0],
1428 &nary);
1429 if (result && is_gimple_min_invariant (result))
1430 return get_or_alloc_expr_for_constant (result);
1432 expr = pre_expr_pool.allocate ();
1433 expr->kind = NARY;
1434 expr->id = 0;
1435 if (nary)
1437 PRE_EXPR_NARY (expr) = nary;
1438 new_val_id = nary->value_id;
1439 get_or_alloc_expression_id (expr);
1441 else
1443 new_val_id = get_next_value_id ();
1444 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
1445 nary = vn_nary_op_insert_pieces (newnary->length,
1446 newnary->opcode,
1447 newnary->type,
1448 &newnary->op[0],
1449 result, new_val_id);
1450 PRE_EXPR_NARY (expr) = nary;
1451 get_or_alloc_expression_id (expr);
1453 add_to_value (new_val_id, expr);
1455 return expr;
1457 break;
1459 case REFERENCE:
1461 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1462 vec<vn_reference_op_s> operands = ref->operands;
1463 tree vuse = ref->vuse;
1464 tree newvuse = vuse;
1465 vec<vn_reference_op_s> newoperands = vNULL;
1466 bool changed = false, same_valid = true;
1467 unsigned int i, n;
1468 vn_reference_op_t operand;
1469 vn_reference_t newref;
1471 for (i = 0; operands.iterate (i, &operand); i++)
1473 pre_expr opresult;
1474 pre_expr leader;
1475 tree op[3];
1476 tree type = operand->type;
1477 vn_reference_op_s newop = *operand;
1478 op[0] = operand->op0;
1479 op[1] = operand->op1;
1480 op[2] = operand->op2;
1481 for (n = 0; n < 3; ++n)
1483 unsigned int op_val_id;
1484 if (!op[n])
1485 continue;
1486 if (TREE_CODE (op[n]) != SSA_NAME)
1488 /* We can't possibly insert these. */
1489 if (n != 0
1490 && !is_gimple_min_invariant (op[n]))
1491 break;
1492 continue;
1494 op_val_id = VN_INFO (op[n])->value_id;
1495 leader = find_leader_in_sets (op_val_id, set1, set2);
1496 opresult = phi_translate (dest, leader, set1, set2, e);
1497 if (opresult && opresult != leader)
1499 tree name = get_representative_for (opresult);
1500 changed |= name != op[n];
1501 op[n] = name;
1503 else if (!opresult)
1504 break;
1506 if (n != 3)
1508 newoperands.release ();
1509 return NULL;
1511 if (!changed)
1512 continue;
1513 if (!newoperands.exists ())
1514 newoperands = operands.copy ();
1515 /* We may have changed from an SSA_NAME to a constant */
1516 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1517 newop.opcode = TREE_CODE (op[0]);
1518 newop.type = type;
1519 newop.op0 = op[0];
1520 newop.op1 = op[1];
1521 newop.op2 = op[2];
1522 newoperands[i] = newop;
1524 gcc_checking_assert (i == operands.length ());
1526 if (vuse)
1528 newvuse = translate_vuse_through_block (newoperands.exists ()
1529 ? newoperands : operands,
1530 ref->set, ref->type,
1531 vuse, phiblock, pred,
1532 &same_valid);
1533 if (newvuse == NULL_TREE)
1535 newoperands.release ();
1536 return NULL;
1540 if (changed || newvuse != vuse)
1542 unsigned int new_val_id;
1544 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1545 ref->type,
1546 newoperands.exists ()
1547 ? newoperands : operands,
1548 &newref, VN_WALK);
1549 if (result)
1550 newoperands.release ();
1552 /* We can always insert constants, so if we have a partial
1553 redundant constant load of another type try to translate it
1554 to a constant of appropriate type. */
1555 if (result && is_gimple_min_invariant (result))
1557 tree tem = result;
1558 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1560 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1561 if (tem && !is_gimple_min_invariant (tem))
1562 tem = NULL_TREE;
1564 if (tem)
1565 return get_or_alloc_expr_for_constant (tem);
1568 /* If we'd have to convert things we would need to validate
1569 if we can insert the translated expression. So fail
1570 here for now - we cannot insert an alias with a different
1571 type in the VN tables either, as that would assert. */
1572 if (result
1573 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1574 return NULL;
1575 else if (!result && newref
1576 && !useless_type_conversion_p (ref->type, newref->type))
1578 newoperands.release ();
1579 return NULL;
1582 expr = pre_expr_pool.allocate ();
1583 expr->kind = REFERENCE;
1584 expr->id = 0;
1586 if (newref)
1587 new_val_id = newref->value_id;
1588 else
1590 if (changed || !same_valid)
1592 new_val_id = get_next_value_id ();
1593 value_expressions.safe_grow_cleared
1594 (get_max_value_id () + 1);
1596 else
1597 new_val_id = ref->value_id;
1598 if (!newoperands.exists ())
1599 newoperands = operands.copy ();
1600 newref = vn_reference_insert_pieces (newvuse, ref->set,
1601 ref->type,
1602 newoperands,
1603 result, new_val_id);
1604 newoperands = vNULL;
1606 PRE_EXPR_REFERENCE (expr) = newref;
1607 get_or_alloc_expression_id (expr);
1608 add_to_value (new_val_id, expr);
1610 newoperands.release ();
1611 return expr;
1613 break;
1615 case NAME:
1617 tree name = PRE_EXPR_NAME (expr);
1618 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1619 /* If the SSA name is defined by a PHI node in this block,
1620 translate it. */
1621 if (gimple_code (def_stmt) == GIMPLE_PHI
1622 && gimple_bb (def_stmt) == phiblock)
1624 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1626 /* Handle constant. */
1627 if (is_gimple_min_invariant (def))
1628 return get_or_alloc_expr_for_constant (def);
1630 return get_or_alloc_expr_for_name (def);
1632 /* Otherwise return it unchanged - it will get removed if its
1633 value is not available in PREDs AVAIL_OUT set of expressions
1634 by the subtraction of TMP_GEN. */
1635 return expr;
1638 default:
1639 gcc_unreachable ();
1643 /* Wrapper around phi_translate_1 providing caching functionality. */
1645 static pre_expr
1646 phi_translate (bitmap_set_t dest, pre_expr expr,
1647 bitmap_set_t set1, bitmap_set_t set2, edge e)
1649 expr_pred_trans_t slot = NULL;
1650 pre_expr phitrans;
1652 if (!expr)
1653 return NULL;
1655 /* Constants contain no values that need translation. */
1656 if (expr->kind == CONSTANT)
1657 return expr;
1659 if (value_id_constant_p (get_expr_value_id (expr)))
1660 return expr;
1662 /* Don't add translations of NAMEs as those are cheap to translate. */
1663 if (expr->kind != NAME)
1665 if (phi_trans_add (&slot, expr, e->src))
1666 return slot->v;
1667 /* Store NULL for the value we want to return in the case of
1668 recursing. */
1669 slot->v = NULL;
1672 /* Translate. */
1673 phitrans = phi_translate_1 (dest, expr, set1, set2, e);
1675 if (slot)
1677 if (phitrans)
1678 slot->v = phitrans;
1679 else
1680 /* Remove failed translations again, they cause insert
1681 iteration to not pick up new opportunities reliably. */
1682 phi_translate_table->remove_elt_with_hash (slot, slot->hashcode);
1685 return phitrans;
1689 /* For each expression in SET, translate the values through phi nodes
1690 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1691 expressions in DEST. */
1693 static void
1694 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, edge e)
1696 vec<pre_expr> exprs;
1697 pre_expr expr;
1698 int i;
1700 if (gimple_seq_empty_p (phi_nodes (e->dest)))
1702 bitmap_set_copy (dest, set);
1703 return;
1706 exprs = sorted_array_from_bitmap_set (set);
1707 FOR_EACH_VEC_ELT (exprs, i, expr)
1709 pre_expr translated;
1710 translated = phi_translate (dest, expr, set, NULL, e);
1711 if (!translated)
1712 continue;
1714 bitmap_insert_into_set (dest, translated);
1716 exprs.release ();
1719 /* Find the leader for a value (i.e., the name representing that
1720 value) in a given set, and return it. Return NULL if no leader
1721 is found. */
1723 static pre_expr
1724 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1726 if (value_id_constant_p (val))
1728 unsigned int i;
1729 bitmap_iterator bi;
1730 bitmap exprset = value_expressions[val];
1732 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1734 pre_expr expr = expression_for_id (i);
1735 if (expr->kind == CONSTANT)
1736 return expr;
1739 if (bitmap_set_contains_value (set, val))
1741 /* Rather than walk the entire bitmap of expressions, and see
1742 whether any of them has the value we are looking for, we look
1743 at the reverse mapping, which tells us the set of expressions
1744 that have a given value (IE value->expressions with that
1745 value) and see if any of those expressions are in our set.
1746 The number of expressions per value is usually significantly
1747 less than the number of expressions in the set. In fact, for
1748 large testcases, doing it this way is roughly 5-10x faster
1749 than walking the bitmap.
1750 If this is somehow a significant lose for some cases, we can
1751 choose which set to walk based on which set is smaller. */
1752 unsigned int i;
1753 bitmap_iterator bi;
1754 bitmap exprset = value_expressions[val];
1756 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1757 return expression_for_id (i);
1759 return NULL;
1762 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1763 BLOCK by seeing if it is not killed in the block. Note that we are
1764 only determining whether there is a store that kills it. Because
1765 of the order in which clean iterates over values, we are guaranteed
1766 that altered operands will have caused us to be eliminated from the
1767 ANTIC_IN set already. */
1769 static bool
1770 value_dies_in_block_x (pre_expr expr, basic_block block)
1772 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1773 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1774 gimple *def;
1775 gimple_stmt_iterator gsi;
1776 unsigned id = get_expression_id (expr);
1777 bool res = false;
1778 ao_ref ref;
1780 if (!vuse)
1781 return false;
1783 /* Lookup a previously calculated result. */
1784 if (EXPR_DIES (block)
1785 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1786 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1788 /* A memory expression {e, VUSE} dies in the block if there is a
1789 statement that may clobber e. If, starting statement walk from the
1790 top of the basic block, a statement uses VUSE there can be no kill
1791 inbetween that use and the original statement that loaded {e, VUSE},
1792 so we can stop walking. */
1793 ref.base = NULL_TREE;
1794 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1796 tree def_vuse, def_vdef;
1797 def = gsi_stmt (gsi);
1798 def_vuse = gimple_vuse (def);
1799 def_vdef = gimple_vdef (def);
1801 /* Not a memory statement. */
1802 if (!def_vuse)
1803 continue;
1805 /* Not a may-def. */
1806 if (!def_vdef)
1808 /* A load with the same VUSE, we're done. */
1809 if (def_vuse == vuse)
1810 break;
1812 continue;
1815 /* Init ref only if we really need it. */
1816 if (ref.base == NULL_TREE
1817 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1818 refx->operands))
1820 res = true;
1821 break;
1823 /* If the statement may clobber expr, it dies. */
1824 if (stmt_may_clobber_ref_p_1 (def, &ref))
1826 res = true;
1827 break;
1831 /* Remember the result. */
1832 if (!EXPR_DIES (block))
1833 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1834 bitmap_set_bit (EXPR_DIES (block), id * 2);
1835 if (res)
1836 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1838 return res;
1842 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1843 contains its value-id. */
1845 static bool
1846 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1848 if (op && TREE_CODE (op) == SSA_NAME)
1850 unsigned int value_id = VN_INFO (op)->value_id;
1851 if (!(bitmap_set_contains_value (set1, value_id)
1852 || (set2 && bitmap_set_contains_value (set2, value_id))))
1853 return false;
1855 return true;
1858 /* Determine if the expression EXPR is valid in SET1 U SET2.
1859 ONLY SET2 CAN BE NULL.
1860 This means that we have a leader for each part of the expression
1861 (if it consists of values), or the expression is an SSA_NAME.
1862 For loads/calls, we also see if the vuse is killed in this block. */
1864 static bool
1865 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr)
1867 switch (expr->kind)
1869 case NAME:
1870 /* By construction all NAMEs are available. Non-available
1871 NAMEs are removed by subtracting TMP_GEN from the sets. */
1872 return true;
1873 case NARY:
1875 unsigned int i;
1876 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1877 for (i = 0; i < nary->length; i++)
1878 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1879 return false;
1880 return true;
1882 break;
1883 case REFERENCE:
1885 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1886 vn_reference_op_t vro;
1887 unsigned int i;
1889 FOR_EACH_VEC_ELT (ref->operands, i, vro)
1891 if (!op_valid_in_sets (set1, set2, vro->op0)
1892 || !op_valid_in_sets (set1, set2, vro->op1)
1893 || !op_valid_in_sets (set1, set2, vro->op2))
1894 return false;
1896 return true;
1898 default:
1899 gcc_unreachable ();
1903 /* Clean the set of expressions SET1 that are no longer valid in SET1 or SET2.
1904 This means expressions that are made up of values we have no leaders for
1905 in SET1 or SET2. */
1907 static void
1908 clean (bitmap_set_t set1, bitmap_set_t set2 = NULL)
1910 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
1911 pre_expr expr;
1912 int i;
1914 FOR_EACH_VEC_ELT (exprs, i, expr)
1916 if (!valid_in_sets (set1, set2, expr))
1918 unsigned int val = get_expr_value_id (expr);
1919 bitmap_clear_bit (&set1->expressions, get_expression_id (expr));
1920 /* We are entered with possibly multiple expressions for a value
1921 so before removing a value from the set see if there's an
1922 expression for it left. */
1923 if (! bitmap_find_leader (set1, val))
1924 bitmap_clear_bit (&set1->values, val);
1927 exprs.release ();
1930 /* Clean the set of expressions that are no longer valid in SET because
1931 they are clobbered in BLOCK or because they trap and may not be executed. */
1933 static void
1934 prune_clobbered_mems (bitmap_set_t set, basic_block block)
1936 bitmap_iterator bi;
1937 unsigned i;
1938 unsigned to_remove = -1U;
1939 bool any_removed = false;
1941 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1943 /* Remove queued expr. */
1944 if (to_remove != -1U)
1946 bitmap_clear_bit (&set->expressions, to_remove);
1947 any_removed = true;
1948 to_remove = -1U;
1951 pre_expr expr = expression_for_id (i);
1952 if (expr->kind == REFERENCE)
1954 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1955 if (ref->vuse)
1957 gimple *def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
1958 if (!gimple_nop_p (def_stmt)
1959 && ((gimple_bb (def_stmt) != block
1960 && !dominated_by_p (CDI_DOMINATORS,
1961 block, gimple_bb (def_stmt)))
1962 || (gimple_bb (def_stmt) == block
1963 && value_dies_in_block_x (expr, block))))
1964 to_remove = i;
1967 else if (expr->kind == NARY)
1969 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1970 /* If the NARY may trap make sure the block does not contain
1971 a possible exit point.
1972 ??? This is overly conservative if we translate AVAIL_OUT
1973 as the available expression might be after the exit point. */
1974 if (BB_MAY_NOTRETURN (block)
1975 && vn_nary_may_trap (nary))
1976 to_remove = i;
1980 /* Remove queued expr. */
1981 if (to_remove != -1U)
1983 bitmap_clear_bit (&set->expressions, to_remove);
1984 any_removed = true;
1987 /* Above we only removed expressions, now clean the set of values
1988 which no longer have any corresponding expression. We cannot
1989 clear the value at the time we remove an expression since there
1990 may be multiple expressions per value.
1991 If we'd queue possibly to be removed values we could use
1992 the bitmap_find_leader way to see if there's still an expression
1993 for it. For some ratio of to be removed values and number of
1994 values/expressions in the set this might be faster than rebuilding
1995 the value-set. */
1996 if (any_removed)
1998 bitmap_clear (&set->values);
1999 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2001 pre_expr expr = expression_for_id (i);
2002 unsigned int value_id = get_expr_value_id (expr);
2003 bitmap_set_bit (&set->values, value_id);
2008 static sbitmap has_abnormal_preds;
2010 /* Compute the ANTIC set for BLOCK.
2012 If succs(BLOCK) > 1 then
2013 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2014 else if succs(BLOCK) == 1 then
2015 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2017 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2019 Note that clean() is deferred until after the iteration. */
2021 static bool
2022 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2024 bitmap_set_t S, old, ANTIC_OUT;
2025 edge e;
2026 edge_iterator ei;
2028 bool was_visited = BB_VISITED (block);
2029 bool changed = ! BB_VISITED (block);
2030 BB_VISITED (block) = 1;
2031 old = ANTIC_OUT = S = NULL;
2033 /* If any edges from predecessors are abnormal, antic_in is empty,
2034 so do nothing. */
2035 if (block_has_abnormal_pred_edge)
2036 goto maybe_dump_sets;
2038 old = ANTIC_IN (block);
2039 ANTIC_OUT = bitmap_set_new ();
2041 /* If the block has no successors, ANTIC_OUT is empty. */
2042 if (EDGE_COUNT (block->succs) == 0)
2044 /* If we have one successor, we could have some phi nodes to
2045 translate through. */
2046 else if (single_succ_p (block))
2048 e = single_succ_edge (block);
2049 gcc_assert (BB_VISITED (e->dest));
2050 BB_VISITED_WITH_VISITED_SUCCS (block)
2051 = BB_VISITED_WITH_VISITED_SUCCS (e->dest);
2052 phi_translate_set (ANTIC_OUT, ANTIC_IN (e->dest), e);
2054 /* If we have multiple successors, we take the intersection of all of
2055 them. Note that in the case of loop exit phi nodes, we may have
2056 phis to translate through. */
2057 else
2059 size_t i;
2060 edge first = NULL;
2062 BB_VISITED_WITH_VISITED_SUCCS (block) = true;
2063 auto_vec<edge> worklist (EDGE_COUNT (block->succs));
2064 FOR_EACH_EDGE (e, ei, block->succs)
2066 if (!first
2067 && BB_VISITED (e->dest))
2068 first = e;
2069 else if (BB_VISITED (e->dest))
2070 worklist.quick_push (e);
2071 else
2073 /* Unvisited successors get their ANTIC_IN replaced by the
2074 maximal set to arrive at a maximum ANTIC_IN solution.
2075 We can ignore them in the intersection operation and thus
2076 need not explicitely represent that maximum solution. */
2077 if (dump_file && (dump_flags & TDF_DETAILS))
2078 fprintf (dump_file, "ANTIC_IN is MAX on %d->%d\n",
2079 e->src->index, e->dest->index);
2081 BB_VISITED_WITH_VISITED_SUCCS (block)
2082 &= BB_VISITED_WITH_VISITED_SUCCS (e->dest);
2085 /* Of multiple successors we have to have visited one already
2086 which is guaranteed by iteration order. */
2087 gcc_assert (first != NULL);
2089 phi_translate_set (ANTIC_OUT, ANTIC_IN (first->dest), first);
2091 /* If we have multiple successors we need to intersect the ANTIC_OUT
2092 sets. For values that's a simple intersection but for
2093 expressions it is a union. Given we want to have a single
2094 expression per value in our sets we have to canonicalize.
2095 Avoid randomness and running into cycles like for PR82129 and
2096 canonicalize the expression we choose to the one with the
2097 lowest id. This requires we actually compute the union first. */
2098 FOR_EACH_VEC_ELT (worklist, i, e)
2100 if (!gimple_seq_empty_p (phi_nodes (e->dest)))
2102 bitmap_set_t tmp = bitmap_set_new ();
2103 phi_translate_set (tmp, ANTIC_IN (e->dest), e);
2104 bitmap_and_into (&ANTIC_OUT->values, &tmp->values);
2105 bitmap_ior_into (&ANTIC_OUT->expressions, &tmp->expressions);
2106 bitmap_set_free (tmp);
2108 else
2110 bitmap_and_into (&ANTIC_OUT->values, &ANTIC_IN (e->dest)->values);
2111 bitmap_ior_into (&ANTIC_OUT->expressions,
2112 &ANTIC_IN (e->dest)->expressions);
2115 if (! worklist.is_empty ())
2117 /* Prune expressions not in the value set. */
2118 bitmap_iterator bi;
2119 unsigned int i;
2120 unsigned int to_clear = -1U;
2121 FOR_EACH_EXPR_ID_IN_SET (ANTIC_OUT, i, bi)
2123 if (to_clear != -1U)
2125 bitmap_clear_bit (&ANTIC_OUT->expressions, to_clear);
2126 to_clear = -1U;
2128 pre_expr expr = expression_for_id (i);
2129 unsigned int value_id = get_expr_value_id (expr);
2130 if (!bitmap_bit_p (&ANTIC_OUT->values, value_id))
2131 to_clear = i;
2133 if (to_clear != -1U)
2134 bitmap_clear_bit (&ANTIC_OUT->expressions, to_clear);
2138 /* Prune expressions that are clobbered in block and thus become
2139 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2140 prune_clobbered_mems (ANTIC_OUT, block);
2142 /* Generate ANTIC_OUT - TMP_GEN. */
2143 S = bitmap_set_subtract_expressions (ANTIC_OUT, TMP_GEN (block));
2145 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2146 ANTIC_IN (block) = bitmap_set_subtract_expressions (EXP_GEN (block),
2147 TMP_GEN (block));
2149 /* Then union in the ANTIC_OUT - TMP_GEN values,
2150 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2151 bitmap_ior_into (&ANTIC_IN (block)->values, &S->values);
2152 bitmap_ior_into (&ANTIC_IN (block)->expressions, &S->expressions);
2154 /* clean (ANTIC_IN (block)) is defered to after the iteration converged
2155 because it can cause non-convergence, see for example PR81181. */
2157 if (!bitmap_set_equal (old, ANTIC_IN (block)))
2159 changed = true;
2160 /* After the initial value set computation the value set may
2161 only shrink during the iteration. */
2162 if (was_visited && BB_VISITED_WITH_VISITED_SUCCS (block) && flag_checking)
2164 bitmap_iterator bi;
2165 unsigned int i;
2166 EXECUTE_IF_AND_COMPL_IN_BITMAP (&ANTIC_IN (block)->values,
2167 &old->values, 0, i, bi)
2168 gcc_unreachable ();
2172 maybe_dump_sets:
2173 if (dump_file && (dump_flags & TDF_DETAILS))
2175 if (ANTIC_OUT)
2176 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2178 if (changed)
2179 fprintf (dump_file, "[changed] ");
2180 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2181 block->index);
2183 if (S)
2184 print_bitmap_set (dump_file, S, "S", block->index);
2186 if (old)
2187 bitmap_set_free (old);
2188 if (S)
2189 bitmap_set_free (S);
2190 if (ANTIC_OUT)
2191 bitmap_set_free (ANTIC_OUT);
2192 return changed;
2195 /* Compute PARTIAL_ANTIC for BLOCK.
2197 If succs(BLOCK) > 1 then
2198 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2199 in ANTIC_OUT for all succ(BLOCK)
2200 else if succs(BLOCK) == 1 then
2201 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2203 PA_IN[BLOCK] = clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK] - ANTIC_IN[BLOCK])
2206 static void
2207 compute_partial_antic_aux (basic_block block,
2208 bool block_has_abnormal_pred_edge)
2210 bitmap_set_t old_PA_IN;
2211 bitmap_set_t PA_OUT;
2212 edge e;
2213 edge_iterator ei;
2214 unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2216 old_PA_IN = PA_OUT = NULL;
2218 /* If any edges from predecessors are abnormal, antic_in is empty,
2219 so do nothing. */
2220 if (block_has_abnormal_pred_edge)
2221 goto maybe_dump_sets;
2223 /* If there are too many partially anticipatable values in the
2224 block, phi_translate_set can take an exponential time: stop
2225 before the translation starts. */
2226 if (max_pa
2227 && single_succ_p (block)
2228 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2229 goto maybe_dump_sets;
2231 old_PA_IN = PA_IN (block);
2232 PA_OUT = bitmap_set_new ();
2234 /* If the block has no successors, ANTIC_OUT is empty. */
2235 if (EDGE_COUNT (block->succs) == 0)
2237 /* If we have one successor, we could have some phi nodes to
2238 translate through. Note that we can't phi translate across DFS
2239 back edges in partial antic, because it uses a union operation on
2240 the successors. For recurrences like IV's, we will end up
2241 generating a new value in the set on each go around (i + 3 (VH.1)
2242 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2243 else if (single_succ_p (block))
2245 e = single_succ_edge (block);
2246 if (!(e->flags & EDGE_DFS_BACK))
2247 phi_translate_set (PA_OUT, PA_IN (e->dest), e);
2249 /* If we have multiple successors, we take the union of all of
2250 them. */
2251 else
2253 size_t i;
2255 auto_vec<edge> worklist (EDGE_COUNT (block->succs));
2256 FOR_EACH_EDGE (e, ei, block->succs)
2258 if (e->flags & EDGE_DFS_BACK)
2259 continue;
2260 worklist.quick_push (e);
2262 if (worklist.length () > 0)
2264 FOR_EACH_VEC_ELT (worklist, i, e)
2266 unsigned int i;
2267 bitmap_iterator bi;
2269 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (e->dest), i, bi)
2270 bitmap_value_insert_into_set (PA_OUT,
2271 expression_for_id (i));
2272 if (!gimple_seq_empty_p (phi_nodes (e->dest)))
2274 bitmap_set_t pa_in = bitmap_set_new ();
2275 phi_translate_set (pa_in, PA_IN (e->dest), e);
2276 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2277 bitmap_value_insert_into_set (PA_OUT,
2278 expression_for_id (i));
2279 bitmap_set_free (pa_in);
2281 else
2282 FOR_EACH_EXPR_ID_IN_SET (PA_IN (e->dest), i, bi)
2283 bitmap_value_insert_into_set (PA_OUT,
2284 expression_for_id (i));
2289 /* Prune expressions that are clobbered in block and thus become
2290 invalid if translated from PA_OUT to PA_IN. */
2291 prune_clobbered_mems (PA_OUT, block);
2293 /* PA_IN starts with PA_OUT - TMP_GEN.
2294 Then we subtract things from ANTIC_IN. */
2295 PA_IN (block) = bitmap_set_subtract_expressions (PA_OUT, TMP_GEN (block));
2297 /* For partial antic, we want to put back in the phi results, since
2298 we will properly avoid making them partially antic over backedges. */
2299 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2300 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2302 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2303 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2305 clean (PA_IN (block), ANTIC_IN (block));
2307 maybe_dump_sets:
2308 if (dump_file && (dump_flags & TDF_DETAILS))
2310 if (PA_OUT)
2311 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2313 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2315 if (old_PA_IN)
2316 bitmap_set_free (old_PA_IN);
2317 if (PA_OUT)
2318 bitmap_set_free (PA_OUT);
2321 /* Compute ANTIC and partial ANTIC sets. */
2323 static void
2324 compute_antic (void)
2326 bool changed = true;
2327 int num_iterations = 0;
2328 basic_block block;
2329 int i;
2330 edge_iterator ei;
2331 edge e;
2333 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2334 We pre-build the map of blocks with incoming abnormal edges here. */
2335 has_abnormal_preds = sbitmap_alloc (last_basic_block_for_fn (cfun));
2336 bitmap_clear (has_abnormal_preds);
2338 FOR_ALL_BB_FN (block, cfun)
2340 BB_VISITED (block) = 0;
2341 BB_VISITED_WITH_VISITED_SUCCS (block) = 0;
2343 FOR_EACH_EDGE (e, ei, block->preds)
2344 if (e->flags & EDGE_ABNORMAL)
2346 bitmap_set_bit (has_abnormal_preds, block->index);
2347 break;
2350 /* While we are here, give empty ANTIC_IN sets to each block. */
2351 ANTIC_IN (block) = bitmap_set_new ();
2352 if (do_partial_partial)
2353 PA_IN (block) = bitmap_set_new ();
2356 /* At the exit block we anticipate nothing. */
2357 BB_VISITED (EXIT_BLOCK_PTR_FOR_FN (cfun)) = 1;
2358 BB_VISITED_WITH_VISITED_SUCCS (EXIT_BLOCK_PTR_FOR_FN (cfun)) = 1;
2360 /* For ANTIC computation we need a postorder that also guarantees that
2361 a block with a single successor is visited after its successor.
2362 RPO on the inverted CFG has this property. */
2363 auto_vec<int, 20> postorder;
2364 inverted_post_order_compute (&postorder);
2366 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
2367 bitmap_clear (worklist);
2368 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
2369 bitmap_set_bit (worklist, e->src->index);
2370 while (changed)
2372 if (dump_file && (dump_flags & TDF_DETAILS))
2373 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2374 /* ??? We need to clear our PHI translation cache here as the
2375 ANTIC sets shrink and we restrict valid translations to
2376 those having operands with leaders in ANTIC. Same below
2377 for PA ANTIC computation. */
2378 num_iterations++;
2379 changed = false;
2380 for (i = postorder.length () - 1; i >= 0; i--)
2382 if (bitmap_bit_p (worklist, postorder[i]))
2384 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2385 bitmap_clear_bit (worklist, block->index);
2386 if (compute_antic_aux (block,
2387 bitmap_bit_p (has_abnormal_preds,
2388 block->index)))
2390 FOR_EACH_EDGE (e, ei, block->preds)
2391 bitmap_set_bit (worklist, e->src->index);
2392 changed = true;
2396 /* Theoretically possible, but *highly* unlikely. */
2397 gcc_checking_assert (num_iterations < 500);
2400 /* We have to clean after the dataflow problem converged as cleaning
2401 can cause non-convergence because it is based on expressions
2402 rather than values. */
2403 FOR_EACH_BB_FN (block, cfun)
2404 clean (ANTIC_IN (block));
2406 statistics_histogram_event (cfun, "compute_antic iterations",
2407 num_iterations);
2409 if (do_partial_partial)
2411 /* For partial antic we ignore backedges and thus we do not need
2412 to perform any iteration when we process blocks in postorder. */
2413 int postorder_num
2414 = pre_and_rev_post_order_compute (NULL, postorder.address (), false);
2415 for (i = postorder_num - 1 ; i >= 0; i--)
2417 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2418 compute_partial_antic_aux (block,
2419 bitmap_bit_p (has_abnormal_preds,
2420 block->index));
2424 sbitmap_free (has_abnormal_preds);
2428 /* Inserted expressions are placed onto this worklist, which is used
2429 for performing quick dead code elimination of insertions we made
2430 that didn't turn out to be necessary. */
2431 static bitmap inserted_exprs;
2433 /* The actual worker for create_component_ref_by_pieces. */
2435 static tree
2436 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2437 unsigned int *operand, gimple_seq *stmts)
2439 vn_reference_op_t currop = &ref->operands[*operand];
2440 tree genop;
2441 ++*operand;
2442 switch (currop->opcode)
2444 case CALL_EXPR:
2445 gcc_unreachable ();
2447 case MEM_REF:
2449 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2450 stmts);
2451 if (!baseop)
2452 return NULL_TREE;
2453 tree offset = currop->op0;
2454 if (TREE_CODE (baseop) == ADDR_EXPR
2455 && handled_component_p (TREE_OPERAND (baseop, 0)))
2457 poly_int64 off;
2458 tree base;
2459 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2460 &off);
2461 gcc_assert (base);
2462 offset = int_const_binop (PLUS_EXPR, offset,
2463 build_int_cst (TREE_TYPE (offset),
2464 off));
2465 baseop = build_fold_addr_expr (base);
2467 genop = build2 (MEM_REF, currop->type, baseop, offset);
2468 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2469 MR_DEPENDENCE_BASE (genop) = currop->base;
2470 REF_REVERSE_STORAGE_ORDER (genop) = currop->reverse;
2471 return genop;
2474 case TARGET_MEM_REF:
2476 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2477 vn_reference_op_t nextop = &ref->operands[++*operand];
2478 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2479 stmts);
2480 if (!baseop)
2481 return NULL_TREE;
2482 if (currop->op0)
2484 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2485 if (!genop0)
2486 return NULL_TREE;
2488 if (nextop->op0)
2490 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2491 if (!genop1)
2492 return NULL_TREE;
2494 genop = build5 (TARGET_MEM_REF, currop->type,
2495 baseop, currop->op2, genop0, currop->op1, genop1);
2497 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2498 MR_DEPENDENCE_BASE (genop) = currop->base;
2499 return genop;
2502 case ADDR_EXPR:
2503 if (currop->op0)
2505 gcc_assert (is_gimple_min_invariant (currop->op0));
2506 return currop->op0;
2508 /* Fallthrough. */
2509 case REALPART_EXPR:
2510 case IMAGPART_EXPR:
2511 case VIEW_CONVERT_EXPR:
2513 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2514 stmts);
2515 if (!genop0)
2516 return NULL_TREE;
2517 return fold_build1 (currop->opcode, currop->type, genop0);
2520 case WITH_SIZE_EXPR:
2522 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2523 stmts);
2524 if (!genop0)
2525 return NULL_TREE;
2526 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2527 if (!genop1)
2528 return NULL_TREE;
2529 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2532 case BIT_FIELD_REF:
2534 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2535 stmts);
2536 if (!genop0)
2537 return NULL_TREE;
2538 tree op1 = currop->op0;
2539 tree op2 = currop->op1;
2540 tree t = build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2541 REF_REVERSE_STORAGE_ORDER (t) = currop->reverse;
2542 return fold (t);
2545 /* For array ref vn_reference_op's, operand 1 of the array ref
2546 is op0 of the reference op and operand 3 of the array ref is
2547 op1. */
2548 case ARRAY_RANGE_REF:
2549 case ARRAY_REF:
2551 tree genop0;
2552 tree genop1 = currop->op0;
2553 tree genop2 = currop->op1;
2554 tree genop3 = currop->op2;
2555 genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2556 stmts);
2557 if (!genop0)
2558 return NULL_TREE;
2559 genop1 = find_or_generate_expression (block, genop1, stmts);
2560 if (!genop1)
2561 return NULL_TREE;
2562 if (genop2)
2564 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2565 /* Drop zero minimum index if redundant. */
2566 if (integer_zerop (genop2)
2567 && (!domain_type
2568 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2569 genop2 = NULL_TREE;
2570 else
2572 genop2 = find_or_generate_expression (block, genop2, stmts);
2573 if (!genop2)
2574 return NULL_TREE;
2577 if (genop3)
2579 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2580 /* We can't always put a size in units of the element alignment
2581 here as the element alignment may be not visible. See
2582 PR43783. Simply drop the element size for constant
2583 sizes. */
2584 if (TREE_CODE (genop3) == INTEGER_CST
2585 && TREE_CODE (TYPE_SIZE_UNIT (elmt_type)) == INTEGER_CST
2586 && wi::eq_p (wi::to_offset (TYPE_SIZE_UNIT (elmt_type)),
2587 (wi::to_offset (genop3)
2588 * vn_ref_op_align_unit (currop))))
2589 genop3 = NULL_TREE;
2590 else
2592 genop3 = find_or_generate_expression (block, genop3, stmts);
2593 if (!genop3)
2594 return NULL_TREE;
2597 return build4 (currop->opcode, currop->type, genop0, genop1,
2598 genop2, genop3);
2600 case COMPONENT_REF:
2602 tree op0;
2603 tree op1;
2604 tree genop2 = currop->op1;
2605 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2606 if (!op0)
2607 return NULL_TREE;
2608 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2609 op1 = currop->op0;
2610 if (genop2)
2612 genop2 = find_or_generate_expression (block, genop2, stmts);
2613 if (!genop2)
2614 return NULL_TREE;
2616 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2619 case SSA_NAME:
2621 genop = find_or_generate_expression (block, currop->op0, stmts);
2622 return genop;
2624 case STRING_CST:
2625 case INTEGER_CST:
2626 case COMPLEX_CST:
2627 case VECTOR_CST:
2628 case REAL_CST:
2629 case CONSTRUCTOR:
2630 case VAR_DECL:
2631 case PARM_DECL:
2632 case CONST_DECL:
2633 case RESULT_DECL:
2634 case FUNCTION_DECL:
2635 return currop->op0;
2637 default:
2638 gcc_unreachable ();
2642 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2643 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2644 trying to rename aggregates into ssa form directly, which is a no no.
2646 Thus, this routine doesn't create temporaries, it just builds a
2647 single access expression for the array, calling
2648 find_or_generate_expression to build the innermost pieces.
2650 This function is a subroutine of create_expression_by_pieces, and
2651 should not be called on it's own unless you really know what you
2652 are doing. */
2654 static tree
2655 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2656 gimple_seq *stmts)
2658 unsigned int op = 0;
2659 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2662 /* Find a simple leader for an expression, or generate one using
2663 create_expression_by_pieces from a NARY expression for the value.
2664 BLOCK is the basic_block we are looking for leaders in.
2665 OP is the tree expression to find a leader for or generate.
2666 Returns the leader or NULL_TREE on failure. */
2668 static tree
2669 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2671 pre_expr expr = get_or_alloc_expr_for (op);
2672 unsigned int lookfor = get_expr_value_id (expr);
2673 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2674 if (leader)
2676 if (leader->kind == NAME)
2677 return PRE_EXPR_NAME (leader);
2678 else if (leader->kind == CONSTANT)
2679 return PRE_EXPR_CONSTANT (leader);
2681 /* Defer. */
2682 return NULL_TREE;
2685 /* It must be a complex expression, so generate it recursively. Note
2686 that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2687 where the insert algorithm fails to insert a required expression. */
2688 bitmap exprset = value_expressions[lookfor];
2689 bitmap_iterator bi;
2690 unsigned int i;
2691 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2693 pre_expr temp = expression_for_id (i);
2694 /* We cannot insert random REFERENCE expressions at arbitrary
2695 places. We can insert NARYs which eventually re-materializes
2696 its operand values. */
2697 if (temp->kind == NARY)
2698 return create_expression_by_pieces (block, temp, stmts,
2699 get_expr_type (expr));
2702 /* Defer. */
2703 return NULL_TREE;
2706 /* Create an expression in pieces, so that we can handle very complex
2707 expressions that may be ANTIC, but not necessary GIMPLE.
2708 BLOCK is the basic block the expression will be inserted into,
2709 EXPR is the expression to insert (in value form)
2710 STMTS is a statement list to append the necessary insertions into.
2712 This function will die if we hit some value that shouldn't be
2713 ANTIC but is (IE there is no leader for it, or its components).
2714 The function returns NULL_TREE in case a different antic expression
2715 has to be inserted first.
2716 This function may also generate expressions that are themselves
2717 partially or fully redundant. Those that are will be either made
2718 fully redundant during the next iteration of insert (for partially
2719 redundant ones), or eliminated by eliminate (for fully redundant
2720 ones). */
2722 static tree
2723 create_expression_by_pieces (basic_block block, pre_expr expr,
2724 gimple_seq *stmts, tree type)
2726 tree name;
2727 tree folded;
2728 gimple_seq forced_stmts = NULL;
2729 unsigned int value_id;
2730 gimple_stmt_iterator gsi;
2731 tree exprtype = type ? type : get_expr_type (expr);
2732 pre_expr nameexpr;
2733 gassign *newstmt;
2735 switch (expr->kind)
2737 /* We may hit the NAME/CONSTANT case if we have to convert types
2738 that value numbering saw through. */
2739 case NAME:
2740 folded = PRE_EXPR_NAME (expr);
2741 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (folded))
2742 return NULL_TREE;
2743 if (useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2744 return folded;
2745 break;
2746 case CONSTANT:
2748 folded = PRE_EXPR_CONSTANT (expr);
2749 tree tem = fold_convert (exprtype, folded);
2750 if (is_gimple_min_invariant (tem))
2751 return tem;
2752 break;
2754 case REFERENCE:
2755 if (PRE_EXPR_REFERENCE (expr)->operands[0].opcode == CALL_EXPR)
2757 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2758 unsigned int operand = 1;
2759 vn_reference_op_t currop = &ref->operands[0];
2760 tree sc = NULL_TREE;
2761 tree fn = find_or_generate_expression (block, currop->op0, stmts);
2762 if (!fn)
2763 return NULL_TREE;
2764 if (currop->op1)
2766 sc = find_or_generate_expression (block, currop->op1, stmts);
2767 if (!sc)
2768 return NULL_TREE;
2770 auto_vec<tree> args (ref->operands.length () - 1);
2771 while (operand < ref->operands.length ())
2773 tree arg = create_component_ref_by_pieces_1 (block, ref,
2774 &operand, stmts);
2775 if (!arg)
2776 return NULL_TREE;
2777 args.quick_push (arg);
2779 gcall *call = gimple_build_call_vec (fn, args);
2780 gimple_call_set_with_bounds (call, currop->with_bounds);
2781 if (sc)
2782 gimple_call_set_chain (call, sc);
2783 tree forcedname = make_ssa_name (currop->type);
2784 gimple_call_set_lhs (call, forcedname);
2785 /* There's no CCP pass after PRE which would re-compute alignment
2786 information so make sure we re-materialize this here. */
2787 if (gimple_call_builtin_p (call, BUILT_IN_ASSUME_ALIGNED)
2788 && args.length () - 2 <= 1
2789 && tree_fits_uhwi_p (args[1])
2790 && (args.length () != 3 || tree_fits_uhwi_p (args[2])))
2792 unsigned HOST_WIDE_INT halign = tree_to_uhwi (args[1]);
2793 unsigned HOST_WIDE_INT hmisalign
2794 = args.length () == 3 ? tree_to_uhwi (args[2]) : 0;
2795 if ((halign & (halign - 1)) == 0
2796 && (hmisalign & ~(halign - 1)) == 0)
2797 set_ptr_info_alignment (get_ptr_info (forcedname),
2798 halign, hmisalign);
2800 gimple_set_vuse (call, BB_LIVE_VOP_ON_EXIT (block));
2801 gimple_seq_add_stmt_without_update (&forced_stmts, call);
2802 folded = forcedname;
2804 else
2806 folded = create_component_ref_by_pieces (block,
2807 PRE_EXPR_REFERENCE (expr),
2808 stmts);
2809 if (!folded)
2810 return NULL_TREE;
2811 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2812 newstmt = gimple_build_assign (name, folded);
2813 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2814 gimple_set_vuse (newstmt, BB_LIVE_VOP_ON_EXIT (block));
2815 folded = name;
2817 break;
2818 case NARY:
2820 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2821 tree *genop = XALLOCAVEC (tree, nary->length);
2822 unsigned i;
2823 for (i = 0; i < nary->length; ++i)
2825 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2826 if (!genop[i])
2827 return NULL_TREE;
2828 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2829 may have conversions stripped. */
2830 if (nary->opcode == POINTER_PLUS_EXPR)
2832 if (i == 0)
2833 genop[i] = gimple_convert (&forced_stmts,
2834 nary->type, genop[i]);
2835 else if (i == 1)
2836 genop[i] = gimple_convert (&forced_stmts,
2837 sizetype, genop[i]);
2839 else
2840 genop[i] = gimple_convert (&forced_stmts,
2841 TREE_TYPE (nary->op[i]), genop[i]);
2843 if (nary->opcode == CONSTRUCTOR)
2845 vec<constructor_elt, va_gc> *elts = NULL;
2846 for (i = 0; i < nary->length; ++i)
2847 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2848 folded = build_constructor (nary->type, elts);
2849 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2850 newstmt = gimple_build_assign (name, folded);
2851 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2852 folded = name;
2854 else
2856 switch (nary->length)
2858 case 1:
2859 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2860 genop[0]);
2861 break;
2862 case 2:
2863 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2864 genop[0], genop[1]);
2865 break;
2866 case 3:
2867 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2868 genop[0], genop[1], genop[2]);
2869 break;
2870 default:
2871 gcc_unreachable ();
2875 break;
2876 default:
2877 gcc_unreachable ();
2880 folded = gimple_convert (&forced_stmts, exprtype, folded);
2882 /* If there is nothing to insert, return the simplified result. */
2883 if (gimple_seq_empty_p (forced_stmts))
2884 return folded;
2885 /* If we simplified to a constant return it and discard eventually
2886 built stmts. */
2887 if (is_gimple_min_invariant (folded))
2889 gimple_seq_discard (forced_stmts);
2890 return folded;
2892 /* Likewise if we simplified to sth not queued for insertion. */
2893 bool found = false;
2894 gsi = gsi_last (forced_stmts);
2895 for (; !gsi_end_p (gsi); gsi_prev (&gsi))
2897 gimple *stmt = gsi_stmt (gsi);
2898 tree forcedname = gimple_get_lhs (stmt);
2899 if (forcedname == folded)
2901 found = true;
2902 break;
2905 if (! found)
2907 gimple_seq_discard (forced_stmts);
2908 return folded;
2910 gcc_assert (TREE_CODE (folded) == SSA_NAME);
2912 /* If we have any intermediate expressions to the value sets, add them
2913 to the value sets and chain them in the instruction stream. */
2914 if (forced_stmts)
2916 gsi = gsi_start (forced_stmts);
2917 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2919 gimple *stmt = gsi_stmt (gsi);
2920 tree forcedname = gimple_get_lhs (stmt);
2921 pre_expr nameexpr;
2923 if (forcedname != folded)
2925 VN_INFO_GET (forcedname)->valnum = forcedname;
2926 VN_INFO (forcedname)->value_id = get_next_value_id ();
2927 nameexpr = get_or_alloc_expr_for_name (forcedname);
2928 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2929 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2930 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2933 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2935 gimple_seq_add_seq (stmts, forced_stmts);
2938 name = folded;
2940 /* Fold the last statement. */
2941 gsi = gsi_last (*stmts);
2942 if (fold_stmt_inplace (&gsi))
2943 update_stmt (gsi_stmt (gsi));
2945 /* Add a value number to the temporary.
2946 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2947 we are creating the expression by pieces, and this particular piece of
2948 the expression may have been represented. There is no harm in replacing
2949 here. */
2950 value_id = get_expr_value_id (expr);
2951 VN_INFO_GET (name)->value_id = value_id;
2952 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2953 if (VN_INFO (name)->valnum == NULL_TREE)
2954 VN_INFO (name)->valnum = name;
2955 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2956 nameexpr = get_or_alloc_expr_for_name (name);
2957 add_to_value (value_id, nameexpr);
2958 if (NEW_SETS (block))
2959 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2960 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2962 pre_stats.insertions++;
2963 if (dump_file && (dump_flags & TDF_DETAILS))
2965 fprintf (dump_file, "Inserted ");
2966 print_gimple_stmt (dump_file, gsi_stmt (gsi_last (*stmts)), 0);
2967 fprintf (dump_file, " in predecessor %d (%04d)\n",
2968 block->index, value_id);
2971 return name;
2975 /* Insert the to-be-made-available values of expression EXPRNUM for each
2976 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
2977 merge the result with a phi node, given the same value number as
2978 NODE. Return true if we have inserted new stuff. */
2980 static bool
2981 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
2982 vec<pre_expr> avail)
2984 pre_expr expr = expression_for_id (exprnum);
2985 pre_expr newphi;
2986 unsigned int val = get_expr_value_id (expr);
2987 edge pred;
2988 bool insertions = false;
2989 bool nophi = false;
2990 basic_block bprime;
2991 pre_expr eprime;
2992 edge_iterator ei;
2993 tree type = get_expr_type (expr);
2994 tree temp;
2995 gphi *phi;
2997 /* Make sure we aren't creating an induction variable. */
2998 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
3000 bool firstinsideloop = false;
3001 bool secondinsideloop = false;
3002 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
3003 EDGE_PRED (block, 0)->src);
3004 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
3005 EDGE_PRED (block, 1)->src);
3006 /* Induction variables only have one edge inside the loop. */
3007 if ((firstinsideloop ^ secondinsideloop)
3008 && expr->kind != REFERENCE)
3010 if (dump_file && (dump_flags & TDF_DETAILS))
3011 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
3012 nophi = true;
3016 /* Make the necessary insertions. */
3017 FOR_EACH_EDGE (pred, ei, block->preds)
3019 gimple_seq stmts = NULL;
3020 tree builtexpr;
3021 bprime = pred->src;
3022 eprime = avail[pred->dest_idx];
3023 builtexpr = create_expression_by_pieces (bprime, eprime,
3024 &stmts, type);
3025 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
3026 if (!gimple_seq_empty_p (stmts))
3028 basic_block new_bb = gsi_insert_seq_on_edge_immediate (pred, stmts);
3029 gcc_assert (! new_bb);
3030 insertions = true;
3032 if (!builtexpr)
3034 /* We cannot insert a PHI node if we failed to insert
3035 on one edge. */
3036 nophi = true;
3037 continue;
3039 if (is_gimple_min_invariant (builtexpr))
3040 avail[pred->dest_idx] = get_or_alloc_expr_for_constant (builtexpr);
3041 else
3042 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
3044 /* If we didn't want a phi node, and we made insertions, we still have
3045 inserted new stuff, and thus return true. If we didn't want a phi node,
3046 and didn't make insertions, we haven't added anything new, so return
3047 false. */
3048 if (nophi && insertions)
3049 return true;
3050 else if (nophi && !insertions)
3051 return false;
3053 /* Now build a phi for the new variable. */
3054 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3055 phi = create_phi_node (temp, block);
3057 VN_INFO_GET (temp)->value_id = val;
3058 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3059 if (VN_INFO (temp)->valnum == NULL_TREE)
3060 VN_INFO (temp)->valnum = temp;
3061 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3062 FOR_EACH_EDGE (pred, ei, block->preds)
3064 pre_expr ae = avail[pred->dest_idx];
3065 gcc_assert (get_expr_type (ae) == type
3066 || useless_type_conversion_p (type, get_expr_type (ae)));
3067 if (ae->kind == CONSTANT)
3068 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3069 pred, UNKNOWN_LOCATION);
3070 else
3071 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3074 newphi = get_or_alloc_expr_for_name (temp);
3075 add_to_value (val, newphi);
3077 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3078 this insertion, since we test for the existence of this value in PHI_GEN
3079 before proceeding with the partial redundancy checks in insert_aux.
3081 The value may exist in AVAIL_OUT, in particular, it could be represented
3082 by the expression we are trying to eliminate, in which case we want the
3083 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3084 inserted there.
3086 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3087 this block, because if it did, it would have existed in our dominator's
3088 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3091 bitmap_insert_into_set (PHI_GEN (block), newphi);
3092 bitmap_value_replace_in_set (AVAIL_OUT (block),
3093 newphi);
3094 bitmap_insert_into_set (NEW_SETS (block),
3095 newphi);
3097 /* If we insert a PHI node for a conversion of another PHI node
3098 in the same basic-block try to preserve range information.
3099 This is important so that followup loop passes receive optimal
3100 number of iteration analysis results. See PR61743. */
3101 if (expr->kind == NARY
3102 && CONVERT_EXPR_CODE_P (expr->u.nary->opcode)
3103 && TREE_CODE (expr->u.nary->op[0]) == SSA_NAME
3104 && gimple_bb (SSA_NAME_DEF_STMT (expr->u.nary->op[0])) == block
3105 && INTEGRAL_TYPE_P (type)
3106 && INTEGRAL_TYPE_P (TREE_TYPE (expr->u.nary->op[0]))
3107 && (TYPE_PRECISION (type)
3108 >= TYPE_PRECISION (TREE_TYPE (expr->u.nary->op[0])))
3109 && SSA_NAME_RANGE_INFO (expr->u.nary->op[0]))
3111 wide_int min, max;
3112 if (get_range_info (expr->u.nary->op[0], &min, &max) == VR_RANGE
3113 && !wi::neg_p (min, SIGNED)
3114 && !wi::neg_p (max, SIGNED))
3115 /* Just handle extension and sign-changes of all-positive ranges. */
3116 set_range_info (temp,
3117 SSA_NAME_RANGE_TYPE (expr->u.nary->op[0]),
3118 wide_int_storage::from (min, TYPE_PRECISION (type),
3119 TYPE_SIGN (type)),
3120 wide_int_storage::from (max, TYPE_PRECISION (type),
3121 TYPE_SIGN (type)));
3124 if (dump_file && (dump_flags & TDF_DETAILS))
3126 fprintf (dump_file, "Created phi ");
3127 print_gimple_stmt (dump_file, phi, 0);
3128 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3130 pre_stats.phis++;
3131 return true;
3136 /* Perform insertion of partially redundant or hoistable values.
3137 For BLOCK, do the following:
3138 1. Propagate the NEW_SETS of the dominator into the current block.
3139 If the block has multiple predecessors,
3140 2a. Iterate over the ANTIC expressions for the block to see if
3141 any of them are partially redundant.
3142 2b. If so, insert them into the necessary predecessors to make
3143 the expression fully redundant.
3144 2c. Insert a new PHI merging the values of the predecessors.
3145 2d. Insert the new PHI, and the new expressions, into the
3146 NEW_SETS set.
3147 If the block has multiple successors,
3148 3a. Iterate over the ANTIC values for the block to see if
3149 any of them are good candidates for hoisting.
3150 3b. If so, insert expressions computing the values in BLOCK,
3151 and add the new expressions into the NEW_SETS set.
3152 4. Recursively call ourselves on the dominator children of BLOCK.
3154 Steps 1, 2a, and 4 are done by insert_aux. 2b, 2c and 2d are done by
3155 do_pre_regular_insertion and do_partial_insertion. 3a and 3b are
3156 done in do_hoist_insertion.
3159 static bool
3160 do_pre_regular_insertion (basic_block block, basic_block dom)
3162 bool new_stuff = false;
3163 vec<pre_expr> exprs;
3164 pre_expr expr;
3165 auto_vec<pre_expr> avail;
3166 int i;
3168 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3169 avail.safe_grow (EDGE_COUNT (block->preds));
3171 FOR_EACH_VEC_ELT (exprs, i, expr)
3173 if (expr->kind == NARY
3174 || expr->kind == REFERENCE)
3176 unsigned int val;
3177 bool by_some = false;
3178 bool cant_insert = false;
3179 bool all_same = true;
3180 pre_expr first_s = NULL;
3181 edge pred;
3182 basic_block bprime;
3183 pre_expr eprime = NULL;
3184 edge_iterator ei;
3185 pre_expr edoubleprime = NULL;
3186 bool do_insertion = false;
3188 val = get_expr_value_id (expr);
3189 if (bitmap_set_contains_value (PHI_GEN (block), val))
3190 continue;
3191 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3193 if (dump_file && (dump_flags & TDF_DETAILS))
3195 fprintf (dump_file, "Found fully redundant value: ");
3196 print_pre_expr (dump_file, expr);
3197 fprintf (dump_file, "\n");
3199 continue;
3202 FOR_EACH_EDGE (pred, ei, block->preds)
3204 unsigned int vprime;
3206 /* We should never run insertion for the exit block
3207 and so not come across fake pred edges. */
3208 gcc_assert (!(pred->flags & EDGE_FAKE));
3209 bprime = pred->src;
3210 /* We are looking at ANTIC_OUT of bprime. */
3211 eprime = phi_translate (NULL, expr, ANTIC_IN (block), NULL, pred);
3213 /* eprime will generally only be NULL if the
3214 value of the expression, translated
3215 through the PHI for this predecessor, is
3216 undefined. If that is the case, we can't
3217 make the expression fully redundant,
3218 because its value is undefined along a
3219 predecessor path. We can thus break out
3220 early because it doesn't matter what the
3221 rest of the results are. */
3222 if (eprime == NULL)
3224 avail[pred->dest_idx] = NULL;
3225 cant_insert = true;
3226 break;
3229 vprime = get_expr_value_id (eprime);
3230 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3231 vprime);
3232 if (edoubleprime == NULL)
3234 avail[pred->dest_idx] = eprime;
3235 all_same = false;
3237 else
3239 avail[pred->dest_idx] = edoubleprime;
3240 by_some = true;
3241 /* We want to perform insertions to remove a redundancy on
3242 a path in the CFG we want to optimize for speed. */
3243 if (optimize_edge_for_speed_p (pred))
3244 do_insertion = true;
3245 if (first_s == NULL)
3246 first_s = edoubleprime;
3247 else if (!pre_expr_d::equal (first_s, edoubleprime))
3248 all_same = false;
3251 /* If we can insert it, it's not the same value
3252 already existing along every predecessor, and
3253 it's defined by some predecessor, it is
3254 partially redundant. */
3255 if (!cant_insert && !all_same && by_some)
3257 if (!do_insertion)
3259 if (dump_file && (dump_flags & TDF_DETAILS))
3261 fprintf (dump_file, "Skipping partial redundancy for "
3262 "expression ");
3263 print_pre_expr (dump_file, expr);
3264 fprintf (dump_file, " (%04d), no redundancy on to be "
3265 "optimized for speed edge\n", val);
3268 else if (dbg_cnt (treepre_insert))
3270 if (dump_file && (dump_flags & TDF_DETAILS))
3272 fprintf (dump_file, "Found partial redundancy for "
3273 "expression ");
3274 print_pre_expr (dump_file, expr);
3275 fprintf (dump_file, " (%04d)\n",
3276 get_expr_value_id (expr));
3278 if (insert_into_preds_of_block (block,
3279 get_expression_id (expr),
3280 avail))
3281 new_stuff = true;
3284 /* If all edges produce the same value and that value is
3285 an invariant, then the PHI has the same value on all
3286 edges. Note this. */
3287 else if (!cant_insert && all_same)
3289 gcc_assert (edoubleprime->kind == CONSTANT
3290 || edoubleprime->kind == NAME);
3292 tree temp = make_temp_ssa_name (get_expr_type (expr),
3293 NULL, "pretmp");
3294 gassign *assign
3295 = gimple_build_assign (temp,
3296 edoubleprime->kind == CONSTANT ?
3297 PRE_EXPR_CONSTANT (edoubleprime) :
3298 PRE_EXPR_NAME (edoubleprime));
3299 gimple_stmt_iterator gsi = gsi_after_labels (block);
3300 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3302 VN_INFO_GET (temp)->value_id = val;
3303 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3304 if (VN_INFO (temp)->valnum == NULL_TREE)
3305 VN_INFO (temp)->valnum = temp;
3306 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3307 pre_expr newe = get_or_alloc_expr_for_name (temp);
3308 add_to_value (val, newe);
3309 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3310 bitmap_insert_into_set (NEW_SETS (block), newe);
3315 exprs.release ();
3316 return new_stuff;
3320 /* Perform insertion for partially anticipatable expressions. There
3321 is only one case we will perform insertion for these. This case is
3322 if the expression is partially anticipatable, and fully available.
3323 In this case, we know that putting it earlier will enable us to
3324 remove the later computation. */
3326 static bool
3327 do_pre_partial_partial_insertion (basic_block block, basic_block dom)
3329 bool new_stuff = false;
3330 vec<pre_expr> exprs;
3331 pre_expr expr;
3332 auto_vec<pre_expr> avail;
3333 int i;
3335 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3336 avail.safe_grow (EDGE_COUNT (block->preds));
3338 FOR_EACH_VEC_ELT (exprs, i, expr)
3340 if (expr->kind == NARY
3341 || expr->kind == REFERENCE)
3343 unsigned int val;
3344 bool by_all = true;
3345 bool cant_insert = false;
3346 edge pred;
3347 basic_block bprime;
3348 pre_expr eprime = NULL;
3349 edge_iterator ei;
3351 val = get_expr_value_id (expr);
3352 if (bitmap_set_contains_value (PHI_GEN (block), val))
3353 continue;
3354 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3355 continue;
3357 FOR_EACH_EDGE (pred, ei, block->preds)
3359 unsigned int vprime;
3360 pre_expr edoubleprime;
3362 /* We should never run insertion for the exit block
3363 and so not come across fake pred edges. */
3364 gcc_assert (!(pred->flags & EDGE_FAKE));
3365 bprime = pred->src;
3366 eprime = phi_translate (NULL, expr, ANTIC_IN (block),
3367 PA_IN (block), pred);
3369 /* eprime will generally only be NULL if the
3370 value of the expression, translated
3371 through the PHI for this predecessor, is
3372 undefined. If that is the case, we can't
3373 make the expression fully redundant,
3374 because its value is undefined along a
3375 predecessor path. We can thus break out
3376 early because it doesn't matter what the
3377 rest of the results are. */
3378 if (eprime == NULL)
3380 avail[pred->dest_idx] = NULL;
3381 cant_insert = true;
3382 break;
3385 vprime = get_expr_value_id (eprime);
3386 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3387 avail[pred->dest_idx] = edoubleprime;
3388 if (edoubleprime == NULL)
3390 by_all = false;
3391 break;
3395 /* If we can insert it, it's not the same value
3396 already existing along every predecessor, and
3397 it's defined by some predecessor, it is
3398 partially redundant. */
3399 if (!cant_insert && by_all)
3401 edge succ;
3402 bool do_insertion = false;
3404 /* Insert only if we can remove a later expression on a path
3405 that we want to optimize for speed.
3406 The phi node that we will be inserting in BLOCK is not free,
3407 and inserting it for the sake of !optimize_for_speed successor
3408 may cause regressions on the speed path. */
3409 FOR_EACH_EDGE (succ, ei, block->succs)
3411 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3412 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3414 if (optimize_edge_for_speed_p (succ))
3415 do_insertion = true;
3419 if (!do_insertion)
3421 if (dump_file && (dump_flags & TDF_DETAILS))
3423 fprintf (dump_file, "Skipping partial partial redundancy "
3424 "for expression ");
3425 print_pre_expr (dump_file, expr);
3426 fprintf (dump_file, " (%04d), not (partially) anticipated "
3427 "on any to be optimized for speed edges\n", val);
3430 else if (dbg_cnt (treepre_insert))
3432 pre_stats.pa_insert++;
3433 if (dump_file && (dump_flags & TDF_DETAILS))
3435 fprintf (dump_file, "Found partial partial redundancy "
3436 "for expression ");
3437 print_pre_expr (dump_file, expr);
3438 fprintf (dump_file, " (%04d)\n",
3439 get_expr_value_id (expr));
3441 if (insert_into_preds_of_block (block,
3442 get_expression_id (expr),
3443 avail))
3444 new_stuff = true;
3450 exprs.release ();
3451 return new_stuff;
3454 /* Insert expressions in BLOCK to compute hoistable values up.
3455 Return TRUE if something was inserted, otherwise return FALSE.
3456 The caller has to make sure that BLOCK has at least two successors. */
3458 static bool
3459 do_hoist_insertion (basic_block block)
3461 edge e;
3462 edge_iterator ei;
3463 bool new_stuff = false;
3464 unsigned i;
3465 gimple_stmt_iterator last;
3467 /* At least two successors, or else... */
3468 gcc_assert (EDGE_COUNT (block->succs) >= 2);
3470 /* Check that all successors of BLOCK are dominated by block.
3471 We could use dominated_by_p() for this, but actually there is a much
3472 quicker check: any successor that is dominated by BLOCK can't have
3473 more than one predecessor edge. */
3474 FOR_EACH_EDGE (e, ei, block->succs)
3475 if (! single_pred_p (e->dest))
3476 return false;
3478 /* Determine the insertion point. If we cannot safely insert before
3479 the last stmt if we'd have to, bail out. */
3480 last = gsi_last_bb (block);
3481 if (!gsi_end_p (last)
3482 && !is_ctrl_stmt (gsi_stmt (last))
3483 && stmt_ends_bb_p (gsi_stmt (last)))
3484 return false;
3486 /* Compute the set of hoistable expressions from ANTIC_IN. First compute
3487 hoistable values. */
3488 bitmap_set hoistable_set;
3490 /* A hoistable value must be in ANTIC_IN(block)
3491 but not in AVAIL_OUT(BLOCK). */
3492 bitmap_initialize (&hoistable_set.values, &grand_bitmap_obstack);
3493 bitmap_and_compl (&hoistable_set.values,
3494 &ANTIC_IN (block)->values, &AVAIL_OUT (block)->values);
3496 /* Short-cut for a common case: hoistable_set is empty. */
3497 if (bitmap_empty_p (&hoistable_set.values))
3498 return false;
3500 /* Compute which of the hoistable values is in AVAIL_OUT of
3501 at least one of the successors of BLOCK. */
3502 bitmap_head availout_in_some;
3503 bitmap_initialize (&availout_in_some, &grand_bitmap_obstack);
3504 FOR_EACH_EDGE (e, ei, block->succs)
3505 /* Do not consider expressions solely because their availability
3506 on loop exits. They'd be ANTIC-IN throughout the whole loop
3507 and thus effectively hoisted across loops by combination of
3508 PRE and hoisting. */
3509 if (! loop_exit_edge_p (block->loop_father, e))
3510 bitmap_ior_and_into (&availout_in_some, &hoistable_set.values,
3511 &AVAIL_OUT (e->dest)->values);
3512 bitmap_clear (&hoistable_set.values);
3514 /* Short-cut for a common case: availout_in_some is empty. */
3515 if (bitmap_empty_p (&availout_in_some))
3516 return false;
3518 /* Hack hoitable_set in-place so we can use sorted_array_from_bitmap_set. */
3519 hoistable_set.values = availout_in_some;
3520 hoistable_set.expressions = ANTIC_IN (block)->expressions;
3522 /* Now finally construct the topological-ordered expression set. */
3523 vec<pre_expr> exprs = sorted_array_from_bitmap_set (&hoistable_set);
3525 bitmap_clear (&hoistable_set.values);
3527 /* If there are candidate values for hoisting, insert expressions
3528 strategically to make the hoistable expressions fully redundant. */
3529 pre_expr expr;
3530 FOR_EACH_VEC_ELT (exprs, i, expr)
3532 /* While we try to sort expressions topologically above the
3533 sorting doesn't work out perfectly. Catch expressions we
3534 already inserted. */
3535 unsigned int value_id = get_expr_value_id (expr);
3536 if (bitmap_set_contains_value (AVAIL_OUT (block), value_id))
3538 if (dump_file && (dump_flags & TDF_DETAILS))
3540 fprintf (dump_file,
3541 "Already inserted expression for ");
3542 print_pre_expr (dump_file, expr);
3543 fprintf (dump_file, " (%04d)\n", value_id);
3545 continue;
3548 /* OK, we should hoist this value. Perform the transformation. */
3549 pre_stats.hoist_insert++;
3550 if (dump_file && (dump_flags & TDF_DETAILS))
3552 fprintf (dump_file,
3553 "Inserting expression in block %d for code hoisting: ",
3554 block->index);
3555 print_pre_expr (dump_file, expr);
3556 fprintf (dump_file, " (%04d)\n", value_id);
3559 gimple_seq stmts = NULL;
3560 tree res = create_expression_by_pieces (block, expr, &stmts,
3561 get_expr_type (expr));
3563 /* Do not return true if expression creation ultimately
3564 did not insert any statements. */
3565 if (gimple_seq_empty_p (stmts))
3566 res = NULL_TREE;
3567 else
3569 if (gsi_end_p (last) || is_ctrl_stmt (gsi_stmt (last)))
3570 gsi_insert_seq_before (&last, stmts, GSI_SAME_STMT);
3571 else
3572 gsi_insert_seq_after (&last, stmts, GSI_NEW_STMT);
3575 /* Make sure to not return true if expression creation ultimately
3576 failed but also make sure to insert any stmts produced as they
3577 are tracked in inserted_exprs. */
3578 if (! res)
3579 continue;
3581 new_stuff = true;
3584 exprs.release ();
3586 return new_stuff;
3589 /* Do a dominator walk on the control flow graph, and insert computations
3590 of values as necessary for PRE and hoisting. */
3592 static bool
3593 insert_aux (basic_block block, bool do_pre, bool do_hoist)
3595 basic_block son;
3596 bool new_stuff = false;
3598 if (block)
3600 basic_block dom;
3601 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3602 if (dom)
3604 unsigned i;
3605 bitmap_iterator bi;
3606 bitmap_set_t newset;
3608 /* First, update the AVAIL_OUT set with anything we may have
3609 inserted higher up in the dominator tree. */
3610 newset = NEW_SETS (dom);
3611 if (newset)
3613 /* Note that we need to value_replace both NEW_SETS, and
3614 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3615 represented by some non-simple expression here that we want
3616 to replace it with. */
3617 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3619 pre_expr expr = expression_for_id (i);
3620 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3621 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3625 /* Insert expressions for partial redundancies. */
3626 if (do_pre && !single_pred_p (block))
3628 new_stuff |= do_pre_regular_insertion (block, dom);
3629 if (do_partial_partial)
3630 new_stuff |= do_pre_partial_partial_insertion (block, dom);
3633 /* Insert expressions for hoisting. */
3634 if (do_hoist && EDGE_COUNT (block->succs) >= 2)
3635 new_stuff |= do_hoist_insertion (block);
3638 for (son = first_dom_son (CDI_DOMINATORS, block);
3639 son;
3640 son = next_dom_son (CDI_DOMINATORS, son))
3642 new_stuff |= insert_aux (son, do_pre, do_hoist);
3645 return new_stuff;
3648 /* Perform insertion of partially redundant and hoistable values. */
3650 static void
3651 insert (void)
3653 bool new_stuff = true;
3654 basic_block bb;
3655 int num_iterations = 0;
3657 FOR_ALL_BB_FN (bb, cfun)
3658 NEW_SETS (bb) = bitmap_set_new ();
3660 while (new_stuff)
3662 num_iterations++;
3663 if (dump_file && dump_flags & TDF_DETAILS)
3664 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3665 new_stuff = insert_aux (ENTRY_BLOCK_PTR_FOR_FN (cfun), flag_tree_pre,
3666 flag_code_hoisting);
3668 /* Clear the NEW sets before the next iteration. We have already
3669 fully propagated its contents. */
3670 if (new_stuff)
3671 FOR_ALL_BB_FN (bb, cfun)
3672 bitmap_set_free (NEW_SETS (bb));
3674 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3678 /* Compute the AVAIL set for all basic blocks.
3680 This function performs value numbering of the statements in each basic
3681 block. The AVAIL sets are built from information we glean while doing
3682 this value numbering, since the AVAIL sets contain only one entry per
3683 value.
3685 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3686 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3688 static void
3689 compute_avail (void)
3692 basic_block block, son;
3693 basic_block *worklist;
3694 size_t sp = 0;
3695 unsigned i;
3696 tree name;
3698 /* We pretend that default definitions are defined in the entry block.
3699 This includes function arguments and the static chain decl. */
3700 FOR_EACH_SSA_NAME (i, name, cfun)
3702 pre_expr e;
3703 if (!SSA_NAME_IS_DEFAULT_DEF (name)
3704 || has_zero_uses (name)
3705 || virtual_operand_p (name))
3706 continue;
3708 e = get_or_alloc_expr_for_name (name);
3709 add_to_value (get_expr_value_id (e), e);
3710 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)), e);
3711 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3715 if (dump_file && (dump_flags & TDF_DETAILS))
3717 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3718 "tmp_gen", ENTRY_BLOCK);
3719 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3720 "avail_out", ENTRY_BLOCK);
3723 /* Allocate the worklist. */
3724 worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
3726 /* Seed the algorithm by putting the dominator children of the entry
3727 block on the worklist. */
3728 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
3729 son;
3730 son = next_dom_son (CDI_DOMINATORS, son))
3731 worklist[sp++] = son;
3733 BB_LIVE_VOP_ON_EXIT (ENTRY_BLOCK_PTR_FOR_FN (cfun))
3734 = ssa_default_def (cfun, gimple_vop (cfun));
3736 /* Loop until the worklist is empty. */
3737 while (sp)
3739 gimple *stmt;
3740 basic_block dom;
3742 /* Pick a block from the worklist. */
3743 block = worklist[--sp];
3745 /* Initially, the set of available values in BLOCK is that of
3746 its immediate dominator. */
3747 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3748 if (dom)
3750 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3751 BB_LIVE_VOP_ON_EXIT (block) = BB_LIVE_VOP_ON_EXIT (dom);
3754 /* Generate values for PHI nodes. */
3755 for (gphi_iterator gsi = gsi_start_phis (block); !gsi_end_p (gsi);
3756 gsi_next (&gsi))
3758 tree result = gimple_phi_result (gsi.phi ());
3760 /* We have no need for virtual phis, as they don't represent
3761 actual computations. */
3762 if (virtual_operand_p (result))
3764 BB_LIVE_VOP_ON_EXIT (block) = result;
3765 continue;
3768 pre_expr e = get_or_alloc_expr_for_name (result);
3769 add_to_value (get_expr_value_id (e), e);
3770 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3771 bitmap_insert_into_set (PHI_GEN (block), e);
3774 BB_MAY_NOTRETURN (block) = 0;
3776 /* Now compute value numbers and populate value sets with all
3777 the expressions computed in BLOCK. */
3778 for (gimple_stmt_iterator gsi = gsi_start_bb (block); !gsi_end_p (gsi);
3779 gsi_next (&gsi))
3781 ssa_op_iter iter;
3782 tree op;
3784 stmt = gsi_stmt (gsi);
3786 /* Cache whether the basic-block has any non-visible side-effect
3787 or control flow.
3788 If this isn't a call or it is the last stmt in the
3789 basic-block then the CFG represents things correctly. */
3790 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3792 /* Non-looping const functions always return normally.
3793 Otherwise the call might not return or have side-effects
3794 that forbids hoisting possibly trapping expressions
3795 before it. */
3796 int flags = gimple_call_flags (stmt);
3797 if (!(flags & ECF_CONST)
3798 || (flags & ECF_LOOPING_CONST_OR_PURE))
3799 BB_MAY_NOTRETURN (block) = 1;
3802 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3804 pre_expr e = get_or_alloc_expr_for_name (op);
3806 add_to_value (get_expr_value_id (e), e);
3807 bitmap_insert_into_set (TMP_GEN (block), e);
3808 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3811 if (gimple_vdef (stmt))
3812 BB_LIVE_VOP_ON_EXIT (block) = gimple_vdef (stmt);
3814 if (gimple_has_side_effects (stmt)
3815 || stmt_could_throw_p (stmt)
3816 || is_gimple_debug (stmt))
3817 continue;
3819 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3821 if (ssa_undefined_value_p (op))
3822 continue;
3823 pre_expr e = get_or_alloc_expr_for_name (op);
3824 bitmap_value_insert_into_set (EXP_GEN (block), e);
3827 switch (gimple_code (stmt))
3829 case GIMPLE_RETURN:
3830 continue;
3832 case GIMPLE_CALL:
3834 vn_reference_t ref;
3835 vn_reference_s ref1;
3836 pre_expr result = NULL;
3838 /* We can value number only calls to real functions. */
3839 if (gimple_call_internal_p (stmt))
3840 continue;
3842 vn_reference_lookup_call (as_a <gcall *> (stmt), &ref, &ref1);
3843 if (!ref)
3844 continue;
3846 /* If the value of the call is not invalidated in
3847 this block until it is computed, add the expression
3848 to EXP_GEN. */
3849 if (!gimple_vuse (stmt)
3850 || gimple_code
3851 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3852 || gimple_bb (SSA_NAME_DEF_STMT
3853 (gimple_vuse (stmt))) != block)
3855 result = pre_expr_pool.allocate ();
3856 result->kind = REFERENCE;
3857 result->id = 0;
3858 PRE_EXPR_REFERENCE (result) = ref;
3860 get_or_alloc_expression_id (result);
3861 add_to_value (get_expr_value_id (result), result);
3862 bitmap_value_insert_into_set (EXP_GEN (block), result);
3864 continue;
3867 case GIMPLE_ASSIGN:
3869 pre_expr result = NULL;
3870 switch (vn_get_stmt_kind (stmt))
3872 case VN_NARY:
3874 enum tree_code code = gimple_assign_rhs_code (stmt);
3875 vn_nary_op_t nary;
3877 /* COND_EXPR and VEC_COND_EXPR are awkward in
3878 that they contain an embedded complex expression.
3879 Don't even try to shove those through PRE. */
3880 if (code == COND_EXPR
3881 || code == VEC_COND_EXPR)
3882 continue;
3884 vn_nary_op_lookup_stmt (stmt, &nary);
3885 if (!nary)
3886 continue;
3888 /* If the NARY traps and there was a preceding
3889 point in the block that might not return avoid
3890 adding the nary to EXP_GEN. */
3891 if (BB_MAY_NOTRETURN (block)
3892 && vn_nary_may_trap (nary))
3893 continue;
3895 result = pre_expr_pool.allocate ();
3896 result->kind = NARY;
3897 result->id = 0;
3898 PRE_EXPR_NARY (result) = nary;
3899 break;
3902 case VN_REFERENCE:
3904 tree rhs1 = gimple_assign_rhs1 (stmt);
3905 alias_set_type set = get_alias_set (rhs1);
3906 vec<vn_reference_op_s> operands
3907 = vn_reference_operands_for_lookup (rhs1);
3908 vn_reference_t ref;
3909 vn_reference_lookup_pieces (gimple_vuse (stmt), set,
3910 TREE_TYPE (rhs1),
3911 operands, &ref, VN_WALK);
3912 if (!ref)
3914 operands.release ();
3915 continue;
3918 /* If the value of the reference is not invalidated in
3919 this block until it is computed, add the expression
3920 to EXP_GEN. */
3921 if (gimple_vuse (stmt))
3923 gimple *def_stmt;
3924 bool ok = true;
3925 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3926 while (!gimple_nop_p (def_stmt)
3927 && gimple_code (def_stmt) != GIMPLE_PHI
3928 && gimple_bb (def_stmt) == block)
3930 if (stmt_may_clobber_ref_p
3931 (def_stmt, gimple_assign_rhs1 (stmt)))
3933 ok = false;
3934 break;
3936 def_stmt
3937 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3939 if (!ok)
3941 operands.release ();
3942 continue;
3946 /* If the load was value-numbered to another
3947 load make sure we do not use its expression
3948 for insertion if it wouldn't be a valid
3949 replacement. */
3950 /* At the momemt we have a testcase
3951 for hoist insertion of aligned vs. misaligned
3952 variants in gcc.dg/torture/pr65270-1.c thus
3953 with just alignment to be considered we can
3954 simply replace the expression in the hashtable
3955 with the most conservative one. */
3956 vn_reference_op_t ref1 = &ref->operands.last ();
3957 while (ref1->opcode != TARGET_MEM_REF
3958 && ref1->opcode != MEM_REF
3959 && ref1 != &ref->operands[0])
3960 --ref1;
3961 vn_reference_op_t ref2 = &operands.last ();
3962 while (ref2->opcode != TARGET_MEM_REF
3963 && ref2->opcode != MEM_REF
3964 && ref2 != &operands[0])
3965 --ref2;
3966 if ((ref1->opcode == TARGET_MEM_REF
3967 || ref1->opcode == MEM_REF)
3968 && (TYPE_ALIGN (ref1->type)
3969 > TYPE_ALIGN (ref2->type)))
3970 ref1->type
3971 = build_aligned_type (ref1->type,
3972 TYPE_ALIGN (ref2->type));
3973 /* TBAA behavior is an obvious part so make sure
3974 that the hashtable one covers this as well
3975 by adjusting the ref alias set and its base. */
3976 if (ref->set == set
3977 || alias_set_subset_of (set, ref->set))
3979 else if (alias_set_subset_of (ref->set, set))
3981 ref->set = set;
3982 if (ref1->opcode == MEM_REF)
3983 ref1->op0
3984 = wide_int_to_tree (TREE_TYPE (ref2->op0),
3985 wi::to_wide (ref1->op0));
3986 else
3987 ref1->op2
3988 = wide_int_to_tree (TREE_TYPE (ref2->op2),
3989 wi::to_wide (ref1->op2));
3991 else
3993 ref->set = 0;
3994 if (ref1->opcode == MEM_REF)
3995 ref1->op0
3996 = wide_int_to_tree (ptr_type_node,
3997 wi::to_wide (ref1->op0));
3998 else
3999 ref1->op2
4000 = wide_int_to_tree (ptr_type_node,
4001 wi::to_wide (ref1->op2));
4003 operands.release ();
4005 result = pre_expr_pool.allocate ();
4006 result->kind = REFERENCE;
4007 result->id = 0;
4008 PRE_EXPR_REFERENCE (result) = ref;
4009 break;
4012 default:
4013 continue;
4016 get_or_alloc_expression_id (result);
4017 add_to_value (get_expr_value_id (result), result);
4018 bitmap_value_insert_into_set (EXP_GEN (block), result);
4019 continue;
4021 default:
4022 break;
4026 if (dump_file && (dump_flags & TDF_DETAILS))
4028 print_bitmap_set (dump_file, EXP_GEN (block),
4029 "exp_gen", block->index);
4030 print_bitmap_set (dump_file, PHI_GEN (block),
4031 "phi_gen", block->index);
4032 print_bitmap_set (dump_file, TMP_GEN (block),
4033 "tmp_gen", block->index);
4034 print_bitmap_set (dump_file, AVAIL_OUT (block),
4035 "avail_out", block->index);
4038 /* Put the dominator children of BLOCK on the worklist of blocks
4039 to compute available sets for. */
4040 for (son = first_dom_son (CDI_DOMINATORS, block);
4041 son;
4042 son = next_dom_son (CDI_DOMINATORS, son))
4043 worklist[sp++] = son;
4046 free (worklist);
4050 /* Initialize data structures used by PRE. */
4052 static void
4053 init_pre (void)
4055 basic_block bb;
4057 next_expression_id = 1;
4058 expressions.create (0);
4059 expressions.safe_push (NULL);
4060 value_expressions.create (get_max_value_id () + 1);
4061 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
4062 name_to_id.create (0);
4064 inserted_exprs = BITMAP_ALLOC (NULL);
4066 connect_infinite_loops_to_exit ();
4067 memset (&pre_stats, 0, sizeof (pre_stats));
4069 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4071 calculate_dominance_info (CDI_DOMINATORS);
4073 bitmap_obstack_initialize (&grand_bitmap_obstack);
4074 phi_translate_table = new hash_table<expr_pred_trans_d> (5110);
4075 expression_to_id = new hash_table<pre_expr_d> (num_ssa_names * 3);
4076 FOR_ALL_BB_FN (bb, cfun)
4078 EXP_GEN (bb) = bitmap_set_new ();
4079 PHI_GEN (bb) = bitmap_set_new ();
4080 TMP_GEN (bb) = bitmap_set_new ();
4081 AVAIL_OUT (bb) = bitmap_set_new ();
4086 /* Deallocate data structures used by PRE. */
4088 static void
4089 fini_pre ()
4091 value_expressions.release ();
4092 expressions.release ();
4093 BITMAP_FREE (inserted_exprs);
4094 bitmap_obstack_release (&grand_bitmap_obstack);
4095 bitmap_set_pool.release ();
4096 pre_expr_pool.release ();
4097 delete phi_translate_table;
4098 phi_translate_table = NULL;
4099 delete expression_to_id;
4100 expression_to_id = NULL;
4101 name_to_id.release ();
4103 free_aux_for_blocks ();
4106 namespace {
4108 const pass_data pass_data_pre =
4110 GIMPLE_PASS, /* type */
4111 "pre", /* name */
4112 OPTGROUP_NONE, /* optinfo_flags */
4113 TV_TREE_PRE, /* tv_id */
4114 ( PROP_cfg | PROP_ssa ), /* properties_required */
4115 0, /* properties_provided */
4116 0, /* properties_destroyed */
4117 TODO_rebuild_alias, /* todo_flags_start */
4118 0, /* todo_flags_finish */
4121 class pass_pre : public gimple_opt_pass
4123 public:
4124 pass_pre (gcc::context *ctxt)
4125 : gimple_opt_pass (pass_data_pre, ctxt)
4128 /* opt_pass methods: */
4129 virtual bool gate (function *)
4130 { return flag_tree_pre != 0 || flag_code_hoisting != 0; }
4131 virtual unsigned int execute (function *);
4133 }; // class pass_pre
4135 unsigned int
4136 pass_pre::execute (function *fun)
4138 unsigned int todo = 0;
4140 do_partial_partial =
4141 flag_tree_partial_pre && optimize_function_for_speed_p (fun);
4143 /* This has to happen before SCCVN runs because
4144 loop_optimizer_init may create new phis, etc. */
4145 loop_optimizer_init (LOOPS_NORMAL);
4146 split_critical_edges ();
4147 scev_initialize ();
4149 run_scc_vn (VN_WALK);
4151 init_pre ();
4153 /* Insert can get quite slow on an incredibly large number of basic
4154 blocks due to some quadratic behavior. Until this behavior is
4155 fixed, don't run it when he have an incredibly large number of
4156 bb's. If we aren't going to run insert, there is no point in
4157 computing ANTIC, either, even though it's plenty fast nor do
4158 we require AVAIL. */
4159 if (n_basic_blocks_for_fn (fun) < 4000)
4161 compute_avail ();
4162 compute_antic ();
4163 insert ();
4166 /* Make sure to remove fake edges before committing our inserts.
4167 This makes sure we don't end up with extra critical edges that
4168 we would need to split. */
4169 remove_fake_exit_edges ();
4170 gsi_commit_edge_inserts ();
4172 /* Eliminate folds statements which might (should not...) end up
4173 not keeping virtual operands up-to-date. */
4174 gcc_assert (!need_ssa_update_p (fun));
4176 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
4177 statistics_counter_event (fun, "PA inserted", pre_stats.pa_insert);
4178 statistics_counter_event (fun, "HOIST inserted", pre_stats.hoist_insert);
4179 statistics_counter_event (fun, "New PHIs", pre_stats.phis);
4181 /* Remove all the redundant expressions. */
4182 todo |= vn_eliminate (inserted_exprs);
4184 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4185 to insert PHI nodes sometimes, and because value numbering of casts isn't
4186 perfect, we sometimes end up inserting dead code. This simple DCE-like
4187 pass removes any insertions we made that weren't actually used. */
4188 simple_dce_from_worklist (inserted_exprs);
4190 fini_pre ();
4192 scev_finalize ();
4193 loop_optimizer_finalize ();
4195 /* Restore SSA info before tail-merging as that resets it as well. */
4196 scc_vn_restore_ssa_info ();
4198 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
4199 case we can merge the block with the remaining predecessor of the block.
4200 It should either:
4201 - call merge_blocks after each tail merge iteration
4202 - call merge_blocks after all tail merge iterations
4203 - mark TODO_cleanup_cfg when necessary
4204 - share the cfg cleanup with fini_pre. */
4205 todo |= tail_merge_optimize (todo);
4207 free_scc_vn ();
4209 /* Tail merging invalidates the virtual SSA web, together with
4210 cfg-cleanup opportunities exposed by PRE this will wreck the
4211 SSA updating machinery. So make sure to run update-ssa
4212 manually, before eventually scheduling cfg-cleanup as part of
4213 the todo. */
4214 update_ssa (TODO_update_ssa_only_virtuals);
4216 return todo;
4219 } // anon namespace
4221 gimple_opt_pass *
4222 make_pass_pre (gcc::context *ctxt)
4224 return new pass_pre (ctxt);