2017-07-18 François Dumont <fdumont@gcc.gnu.org>
[official-gcc.git] / gcc / tree-ssa-pre.c
blob0ec3d3c7f7e0b80c3bd706134f2e09df2fe73844
1 /* Full and partial redundancy elimination and code hoisting on SSA GIMPLE.
2 Copyright (C) 2001-2017 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-ssa-loop.h"
43 #include "tree-into-ssa.h"
44 #include "tree-dfa.h"
45 #include "tree-ssa.h"
46 #include "cfgloop.h"
47 #include "tree-ssa-sccvn.h"
48 #include "tree-scalar-evolution.h"
49 #include "params.h"
50 #include "dbgcnt.h"
51 #include "domwalk.h"
52 #include "tree-ssa-propagate.h"
53 #include "ipa-utils.h"
54 #include "tree-cfgcleanup.h"
55 #include "langhooks.h"
56 #include "alias.h"
58 /* Even though this file is called tree-ssa-pre.c, we actually
59 implement a bit more than just PRE here. All of them piggy-back
60 on GVN which is implemented in tree-ssa-sccvn.c.
62 1. Full Redundancy Elimination (FRE)
63 This is the elimination phase of GVN.
65 2. Partial Redundancy Elimination (PRE)
66 This is adds computation of AVAIL_OUT and ANTIC_IN and
67 doing expression insertion to form GVN-PRE.
69 3. Code hoisting
70 This optimization uses the ANTIC_IN sets computed for PRE
71 to move expressions further up than PRE would do, to make
72 multiple computations of the same value fully redundant.
73 This pass is explained below (after the explanation of the
74 basic algorithm for PRE).
77 /* TODO:
79 1. Avail sets can be shared by making an avail_find_leader that
80 walks up the dominator tree and looks in those avail sets.
81 This might affect code optimality, it's unclear right now.
82 Currently the AVAIL_OUT sets are the remaining quadraticness in
83 memory of GVN-PRE.
84 2. Strength reduction can be performed by anticipating expressions
85 we can repair later on.
86 3. We can do back-substitution or smarter value numbering to catch
87 commutative expressions split up over multiple statements.
90 /* For ease of terminology, "expression node" in the below refers to
91 every expression node but GIMPLE_ASSIGN, because GIMPLE_ASSIGNs
92 represent the actual statement containing the expressions we care about,
93 and we cache the value number by putting it in the expression. */
95 /* Basic algorithm for Partial Redundancy Elimination:
97 First we walk the statements to generate the AVAIL sets, the
98 EXP_GEN sets, and the tmp_gen sets. EXP_GEN sets represent the
99 generation of values/expressions by a given block. We use them
100 when computing the ANTIC sets. The AVAIL sets consist of
101 SSA_NAME's that represent values, so we know what values are
102 available in what blocks. AVAIL is a forward dataflow problem. In
103 SSA, values are never killed, so we don't need a kill set, or a
104 fixpoint iteration, in order to calculate the AVAIL sets. In
105 traditional parlance, AVAIL sets tell us the downsafety of the
106 expressions/values.
108 Next, we generate the ANTIC sets. These sets represent the
109 anticipatable expressions. ANTIC is a backwards dataflow
110 problem. An expression is anticipatable in a given block if it could
111 be generated in that block. This means that if we had to perform
112 an insertion in that block, of the value of that expression, we
113 could. Calculating the ANTIC sets requires phi translation of
114 expressions, because the flow goes backwards through phis. We must
115 iterate to a fixpoint of the ANTIC sets, because we have a kill
116 set. Even in SSA form, values are not live over the entire
117 function, only from their definition point onwards. So we have to
118 remove values from the ANTIC set once we go past the definition
119 point of the leaders that make them up.
120 compute_antic/compute_antic_aux performs this computation.
122 Third, we perform insertions to make partially redundant
123 expressions fully redundant.
125 An expression is partially redundant (excluding partial
126 anticipation) if:
128 1. It is AVAIL in some, but not all, of the predecessors of a
129 given block.
130 2. It is ANTIC in all the predecessors.
132 In order to make it fully redundant, we insert the expression into
133 the predecessors where it is not available, but is ANTIC.
135 When optimizing for size, we only eliminate the partial redundancy
136 if we need to insert in only one predecessor. This avoids almost
137 completely the code size increase that PRE usually causes.
139 For the partial anticipation case, we only perform insertion if it
140 is partially anticipated in some block, and fully available in all
141 of the predecessors.
143 do_pre_regular_insertion/do_pre_partial_partial_insertion
144 performs these steps, driven by insert/insert_aux.
146 Fourth, we eliminate fully redundant expressions.
147 This is a simple statement walk that replaces redundant
148 calculations with the now available values. */
150 /* Basic algorithm for Code Hoisting:
152 Code hoisting is: Moving value computations up in the control flow
153 graph to make multiple copies redundant. Typically this is a size
154 optimization, but there are cases where it also is helpful for speed.
156 A simple code hoisting algorithm is implemented that piggy-backs on
157 the PRE infrastructure. For code hoisting, we have to know ANTIC_OUT
158 which is effectively ANTIC_IN - AVAIL_OUT. The latter two have to be
159 computed for PRE, and we can use them to perform a limited version of
160 code hoisting, too.
162 For the purpose of this implementation, a value is hoistable to a basic
163 block B if the following properties are met:
165 1. The value is in ANTIC_IN(B) -- the value will be computed on all
166 paths from B to function exit and it can be computed in B);
168 2. The value is not in AVAIL_OUT(B) -- there would be no need to
169 compute the value again and make it available twice;
171 3. All successors of B are dominated by B -- makes sure that inserting
172 a computation of the value in B will make the remaining
173 computations fully redundant;
175 4. At least one successor has the value in AVAIL_OUT -- to avoid
176 hoisting values up too far;
178 5. There are at least two successors of B -- hoisting in straight
179 line code is pointless.
181 The third condition is not strictly necessary, but it would complicate
182 the hoisting pass a lot. In fact, I don't know of any code hoisting
183 algorithm that does not have this requirement. Fortunately, experiments
184 have show that most candidate hoistable values are in regions that meet
185 this condition (e.g. diamond-shape regions).
187 The forth condition is necessary to avoid hoisting things up too far
188 away from the uses of the value. Nothing else limits the algorithm
189 from hoisting everything up as far as ANTIC_IN allows. Experiments
190 with SPEC and CSiBE have shown that hoisting up too far results in more
191 spilling, less benefits for code size, and worse benchmark scores.
192 Fortunately, in practice most of the interesting hoisting opportunities
193 are caught despite this limitation.
195 For hoistable values that meet all conditions, expressions are inserted
196 to make the calculation of the hoistable value fully redundant. We
197 perform code hoisting insertions after each round of PRE insertions,
198 because code hoisting never exposes new PRE opportunities, but PRE can
199 create new code hoisting opportunities.
201 The code hoisting algorithm is implemented in do_hoist_insert, driven
202 by insert/insert_aux. */
204 /* Representations of value numbers:
206 Value numbers are represented by a representative SSA_NAME. We
207 will create fake SSA_NAME's in situations where we need a
208 representative but do not have one (because it is a complex
209 expression). In order to facilitate storing the value numbers in
210 bitmaps, and keep the number of wasted SSA_NAME's down, we also
211 associate a value_id with each value number, and create full blown
212 ssa_name's only where we actually need them (IE in operands of
213 existing expressions).
215 Theoretically you could replace all the value_id's with
216 SSA_NAME_VERSION, but this would allocate a large number of
217 SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
218 It would also require an additional indirection at each point we
219 use the value id. */
221 /* Representation of expressions on value numbers:
223 Expressions consisting of value numbers are represented the same
224 way as our VN internally represents them, with an additional
225 "pre_expr" wrapping around them in order to facilitate storing all
226 of the expressions in the same sets. */
228 /* Representation of sets:
230 The dataflow sets do not need to be sorted in any particular order
231 for the majority of their lifetime, are simply represented as two
232 bitmaps, one that keeps track of values present in the set, and one
233 that keeps track of expressions present in the set.
235 When we need them in topological order, we produce it on demand by
236 transforming the bitmap into an array and sorting it into topo
237 order. */
239 /* Type of expression, used to know which member of the PRE_EXPR union
240 is valid. */
242 enum pre_expr_kind
244 NAME,
245 NARY,
246 REFERENCE,
247 CONSTANT
250 union pre_expr_union
252 tree name;
253 tree constant;
254 vn_nary_op_t nary;
255 vn_reference_t reference;
258 typedef struct pre_expr_d : nofree_ptr_hash <pre_expr_d>
260 enum pre_expr_kind kind;
261 unsigned int id;
262 pre_expr_union u;
264 /* hash_table support. */
265 static inline hashval_t hash (const pre_expr_d *);
266 static inline int equal (const pre_expr_d *, const pre_expr_d *);
267 } *pre_expr;
269 #define PRE_EXPR_NAME(e) (e)->u.name
270 #define PRE_EXPR_NARY(e) (e)->u.nary
271 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
272 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
274 /* Compare E1 and E1 for equality. */
276 inline int
277 pre_expr_d::equal (const pre_expr_d *e1, const pre_expr_d *e2)
279 if (e1->kind != e2->kind)
280 return false;
282 switch (e1->kind)
284 case CONSTANT:
285 return vn_constant_eq_with_type (PRE_EXPR_CONSTANT (e1),
286 PRE_EXPR_CONSTANT (e2));
287 case NAME:
288 return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
289 case NARY:
290 return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
291 case REFERENCE:
292 return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
293 PRE_EXPR_REFERENCE (e2));
294 default:
295 gcc_unreachable ();
299 /* Hash E. */
301 inline hashval_t
302 pre_expr_d::hash (const pre_expr_d *e)
304 switch (e->kind)
306 case CONSTANT:
307 return vn_hash_constant_with_type (PRE_EXPR_CONSTANT (e));
308 case NAME:
309 return SSA_NAME_VERSION (PRE_EXPR_NAME (e));
310 case NARY:
311 return PRE_EXPR_NARY (e)->hashcode;
312 case REFERENCE:
313 return PRE_EXPR_REFERENCE (e)->hashcode;
314 default:
315 gcc_unreachable ();
319 /* Next global expression id number. */
320 static unsigned int next_expression_id;
322 /* Mapping from expression to id number we can use in bitmap sets. */
323 static vec<pre_expr> expressions;
324 static hash_table<pre_expr_d> *expression_to_id;
325 static vec<unsigned> name_to_id;
327 /* Allocate an expression id for EXPR. */
329 static inline unsigned int
330 alloc_expression_id (pre_expr expr)
332 struct pre_expr_d **slot;
333 /* Make sure we won't overflow. */
334 gcc_assert (next_expression_id + 1 > next_expression_id);
335 expr->id = next_expression_id++;
336 expressions.safe_push (expr);
337 if (expr->kind == NAME)
339 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
340 /* vec::safe_grow_cleared allocates no headroom. Avoid frequent
341 re-allocations by using vec::reserve upfront. */
342 unsigned old_len = name_to_id.length ();
343 name_to_id.reserve (num_ssa_names - old_len);
344 name_to_id.quick_grow_cleared (num_ssa_names);
345 gcc_assert (name_to_id[version] == 0);
346 name_to_id[version] = expr->id;
348 else
350 slot = expression_to_id->find_slot (expr, INSERT);
351 gcc_assert (!*slot);
352 *slot = expr;
354 return next_expression_id - 1;
357 /* Return the expression id for tree EXPR. */
359 static inline unsigned int
360 get_expression_id (const pre_expr expr)
362 return expr->id;
365 static inline unsigned int
366 lookup_expression_id (const pre_expr expr)
368 struct pre_expr_d **slot;
370 if (expr->kind == NAME)
372 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
373 if (name_to_id.length () <= version)
374 return 0;
375 return name_to_id[version];
377 else
379 slot = expression_to_id->find_slot (expr, NO_INSERT);
380 if (!slot)
381 return 0;
382 return ((pre_expr)*slot)->id;
386 /* Return the existing expression id for EXPR, or create one if one
387 does not exist yet. */
389 static inline unsigned int
390 get_or_alloc_expression_id (pre_expr expr)
392 unsigned int id = lookup_expression_id (expr);
393 if (id == 0)
394 return alloc_expression_id (expr);
395 return expr->id = id;
398 /* Return the expression that has expression id ID */
400 static inline pre_expr
401 expression_for_id (unsigned int id)
403 return expressions[id];
406 /* Free the expression id field in all of our expressions,
407 and then destroy the expressions array. */
409 static void
410 clear_expression_ids (void)
412 expressions.release ();
415 static object_allocator<pre_expr_d> pre_expr_pool ("pre_expr nodes");
417 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it. */
419 static pre_expr
420 get_or_alloc_expr_for_name (tree name)
422 struct pre_expr_d expr;
423 pre_expr result;
424 unsigned int result_id;
426 expr.kind = NAME;
427 expr.id = 0;
428 PRE_EXPR_NAME (&expr) = name;
429 result_id = lookup_expression_id (&expr);
430 if (result_id != 0)
431 return expression_for_id (result_id);
433 result = pre_expr_pool.allocate ();
434 result->kind = NAME;
435 PRE_EXPR_NAME (result) = name;
436 alloc_expression_id (result);
437 return result;
440 /* An unordered bitmap set. One bitmap tracks values, the other,
441 expressions. */
442 typedef struct bitmap_set
444 bitmap_head expressions;
445 bitmap_head values;
446 } *bitmap_set_t;
448 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi) \
449 EXECUTE_IF_SET_IN_BITMAP (&(set)->expressions, 0, (id), (bi))
451 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi) \
452 EXECUTE_IF_SET_IN_BITMAP (&(set)->values, 0, (id), (bi))
454 /* Mapping from value id to expressions with that value_id. */
455 static vec<bitmap> value_expressions;
457 /* Sets that we need to keep track of. */
458 typedef struct bb_bitmap_sets
460 /* The EXP_GEN set, which represents expressions/values generated in
461 a basic block. */
462 bitmap_set_t exp_gen;
464 /* The PHI_GEN set, which represents PHI results generated in a
465 basic block. */
466 bitmap_set_t phi_gen;
468 /* The TMP_GEN set, which represents results/temporaries generated
469 in a basic block. IE the LHS of an expression. */
470 bitmap_set_t tmp_gen;
472 /* The AVAIL_OUT set, which represents which values are available in
473 a given basic block. */
474 bitmap_set_t avail_out;
476 /* The ANTIC_IN set, which represents which values are anticipatable
477 in a given basic block. */
478 bitmap_set_t antic_in;
480 /* The PA_IN set, which represents which values are
481 partially anticipatable in a given basic block. */
482 bitmap_set_t pa_in;
484 /* The NEW_SETS set, which is used during insertion to augment the
485 AVAIL_OUT set of blocks with the new insertions performed during
486 the current iteration. */
487 bitmap_set_t new_sets;
489 /* A cache for value_dies_in_block_x. */
490 bitmap expr_dies;
492 /* The live virtual operand on successor edges. */
493 tree vop_on_exit;
495 /* True if we have visited this block during ANTIC calculation. */
496 unsigned int visited : 1;
498 /* True when the block contains a call that might not return. */
499 unsigned int contains_may_not_return_call : 1;
500 } *bb_value_sets_t;
502 #define EXP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->exp_gen
503 #define PHI_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->phi_gen
504 #define TMP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->tmp_gen
505 #define AVAIL_OUT(BB) ((bb_value_sets_t) ((BB)->aux))->avail_out
506 #define ANTIC_IN(BB) ((bb_value_sets_t) ((BB)->aux))->antic_in
507 #define PA_IN(BB) ((bb_value_sets_t) ((BB)->aux))->pa_in
508 #define NEW_SETS(BB) ((bb_value_sets_t) ((BB)->aux))->new_sets
509 #define EXPR_DIES(BB) ((bb_value_sets_t) ((BB)->aux))->expr_dies
510 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
511 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
512 #define BB_LIVE_VOP_ON_EXIT(BB) ((bb_value_sets_t) ((BB)->aux))->vop_on_exit
515 /* This structure is used to keep track of statistics on what
516 optimization PRE was able to perform. */
517 static struct
519 /* The number of RHS computations eliminated by PRE. */
520 int eliminations;
522 /* The number of new expressions/temporaries generated by PRE. */
523 int insertions;
525 /* The number of inserts found due to partial anticipation */
526 int pa_insert;
528 /* The number of inserts made for code hoisting. */
529 int hoist_insert;
531 /* The number of new PHI nodes added by PRE. */
532 int phis;
533 } pre_stats;
535 static bool do_partial_partial;
536 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
537 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
538 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
539 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
540 static void bitmap_set_and (bitmap_set_t, bitmap_set_t);
541 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
542 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
543 static void bitmap_insert_into_set_1 (bitmap_set_t, pre_expr,
544 unsigned int, bool);
545 static bitmap_set_t bitmap_set_new (void);
546 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
547 tree);
548 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
549 static unsigned int get_expr_value_id (pre_expr);
551 /* We can add and remove elements and entries to and from sets
552 and hash tables, so we use alloc pools for them. */
554 static object_allocator<bitmap_set> bitmap_set_pool ("Bitmap sets");
555 static bitmap_obstack grand_bitmap_obstack;
557 /* Set of blocks with statements that have had their EH properties changed. */
558 static bitmap need_eh_cleanup;
560 /* Set of blocks with statements that have had their AB properties changed. */
561 static bitmap need_ab_cleanup;
563 /* A three tuple {e, pred, v} used to cache phi translations in the
564 phi_translate_table. */
566 typedef struct expr_pred_trans_d : free_ptr_hash<expr_pred_trans_d>
568 /* The expression. */
569 pre_expr e;
571 /* The predecessor block along which we translated the expression. */
572 basic_block pred;
574 /* The value that resulted from the translation. */
575 pre_expr v;
577 /* The hashcode for the expression, pred pair. This is cached for
578 speed reasons. */
579 hashval_t hashcode;
581 /* hash_table support. */
582 static inline hashval_t hash (const expr_pred_trans_d *);
583 static inline int equal (const expr_pred_trans_d *, const expr_pred_trans_d *);
584 } *expr_pred_trans_t;
585 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
587 inline hashval_t
588 expr_pred_trans_d::hash (const expr_pred_trans_d *e)
590 return e->hashcode;
593 inline int
594 expr_pred_trans_d::equal (const expr_pred_trans_d *ve1,
595 const expr_pred_trans_d *ve2)
597 basic_block b1 = ve1->pred;
598 basic_block b2 = ve2->pred;
600 /* If they are not translations for the same basic block, they can't
601 be equal. */
602 if (b1 != b2)
603 return false;
604 return pre_expr_d::equal (ve1->e, ve2->e);
607 /* The phi_translate_table caches phi translations for a given
608 expression and predecessor. */
609 static hash_table<expr_pred_trans_d> *phi_translate_table;
611 /* Add the tuple mapping from {expression E, basic block PRED} to
612 the phi translation table and return whether it pre-existed. */
614 static inline bool
615 phi_trans_add (expr_pred_trans_t *entry, pre_expr e, basic_block pred)
617 expr_pred_trans_t *slot;
618 expr_pred_trans_d tem;
619 hashval_t hash = iterative_hash_hashval_t (pre_expr_d::hash (e),
620 pred->index);
621 tem.e = e;
622 tem.pred = pred;
623 tem.hashcode = hash;
624 slot = phi_translate_table->find_slot_with_hash (&tem, hash, INSERT);
625 if (*slot)
627 *entry = *slot;
628 return true;
631 *entry = *slot = XNEW (struct expr_pred_trans_d);
632 (*entry)->e = e;
633 (*entry)->pred = pred;
634 (*entry)->hashcode = hash;
635 return false;
639 /* Add expression E to the expression set of value id V. */
641 static void
642 add_to_value (unsigned int v, pre_expr e)
644 bitmap set;
646 gcc_checking_assert (get_expr_value_id (e) == v);
648 if (v >= value_expressions.length ())
650 value_expressions.safe_grow_cleared (v + 1);
653 set = value_expressions[v];
654 if (!set)
656 set = BITMAP_ALLOC (&grand_bitmap_obstack);
657 value_expressions[v] = set;
660 bitmap_set_bit (set, get_or_alloc_expression_id (e));
663 /* Create a new bitmap set and return it. */
665 static bitmap_set_t
666 bitmap_set_new (void)
668 bitmap_set_t ret = bitmap_set_pool.allocate ();
669 bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
670 bitmap_initialize (&ret->values, &grand_bitmap_obstack);
671 return ret;
674 /* Return the value id for a PRE expression EXPR. */
676 static unsigned int
677 get_expr_value_id (pre_expr expr)
679 unsigned int id;
680 switch (expr->kind)
682 case CONSTANT:
683 id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
684 break;
685 case NAME:
686 id = VN_INFO (PRE_EXPR_NAME (expr))->value_id;
687 break;
688 case NARY:
689 id = PRE_EXPR_NARY (expr)->value_id;
690 break;
691 case REFERENCE:
692 id = PRE_EXPR_REFERENCE (expr)->value_id;
693 break;
694 default:
695 gcc_unreachable ();
697 /* ??? We cannot assert that expr has a value-id (it can be 0), because
698 we assign value-ids only to expressions that have a result
699 in set_hashtable_value_ids. */
700 return id;
703 /* Return a SCCVN valnum (SSA name or constant) for the PRE value-id VAL. */
705 static tree
706 sccvn_valnum_from_value_id (unsigned int val)
708 bitmap_iterator bi;
709 unsigned int i;
710 bitmap exprset = value_expressions[val];
711 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
713 pre_expr vexpr = expression_for_id (i);
714 if (vexpr->kind == NAME)
715 return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
716 else if (vexpr->kind == CONSTANT)
717 return PRE_EXPR_CONSTANT (vexpr);
719 return NULL_TREE;
722 /* Remove an expression EXPR from a bitmapped set. */
724 static void
725 bitmap_remove_from_set (bitmap_set_t set, pre_expr expr)
727 unsigned int val = get_expr_value_id (expr);
728 if (!value_id_constant_p (val))
730 bitmap_clear_bit (&set->values, val);
731 bitmap_clear_bit (&set->expressions, get_expression_id (expr));
735 static void
736 bitmap_insert_into_set_1 (bitmap_set_t set, pre_expr expr,
737 unsigned int val, bool allow_constants)
739 if (allow_constants || !value_id_constant_p (val))
741 /* We specifically expect this and only this function to be able to
742 insert constants into a set. */
743 bitmap_set_bit (&set->values, val);
744 bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
748 /* Insert an expression EXPR into a bitmapped set. */
750 static void
751 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
753 bitmap_insert_into_set_1 (set, expr, get_expr_value_id (expr), false);
756 /* Copy a bitmapped set ORIG, into bitmapped set DEST. */
758 static void
759 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
761 bitmap_copy (&dest->expressions, &orig->expressions);
762 bitmap_copy (&dest->values, &orig->values);
766 /* Free memory used up by SET. */
767 static void
768 bitmap_set_free (bitmap_set_t set)
770 bitmap_clear (&set->expressions);
771 bitmap_clear (&set->values);
775 /* Generate an topological-ordered array of bitmap set SET. */
777 static vec<pre_expr>
778 sorted_array_from_bitmap_set (bitmap_set_t set)
780 unsigned int i, j;
781 bitmap_iterator bi, bj;
782 vec<pre_expr> result;
784 /* Pre-allocate enough space for the array. */
785 result.create (bitmap_count_bits (&set->expressions));
787 FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
789 /* The number of expressions having a given value is usually
790 relatively small. Thus, rather than making a vector of all
791 the expressions and sorting it by value-id, we walk the values
792 and check in the reverse mapping that tells us what expressions
793 have a given value, to filter those in our set. As a result,
794 the expressions are inserted in value-id order, which means
795 topological order.
797 If this is somehow a significant lose for some cases, we can
798 choose which set to walk based on the set size. */
799 bitmap exprset = value_expressions[i];
800 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bj)
802 if (bitmap_bit_p (&set->expressions, j))
803 result.quick_push (expression_for_id (j));
807 return result;
810 /* Perform bitmapped set operation DEST &= ORIG. */
812 static void
813 bitmap_set_and (bitmap_set_t dest, bitmap_set_t orig)
815 bitmap_iterator bi;
816 unsigned int i;
818 if (dest != orig)
820 bitmap_and_into (&dest->values, &orig->values);
822 unsigned int to_clear = -1U;
823 FOR_EACH_EXPR_ID_IN_SET (dest, i, bi)
825 if (to_clear != -1U)
827 bitmap_clear_bit (&dest->expressions, to_clear);
828 to_clear = -1U;
830 pre_expr expr = expression_for_id (i);
831 unsigned int value_id = get_expr_value_id (expr);
832 if (!bitmap_bit_p (&dest->values, value_id))
833 to_clear = i;
835 if (to_clear != -1U)
836 bitmap_clear_bit (&dest->expressions, to_clear);
840 /* Subtract all values and expressions contained in ORIG from DEST. */
842 static bitmap_set_t
843 bitmap_set_subtract (bitmap_set_t dest, bitmap_set_t orig)
845 bitmap_set_t result = bitmap_set_new ();
846 bitmap_iterator bi;
847 unsigned int i;
849 bitmap_and_compl (&result->expressions, &dest->expressions,
850 &orig->expressions);
852 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
854 pre_expr expr = expression_for_id (i);
855 unsigned int value_id = get_expr_value_id (expr);
856 bitmap_set_bit (&result->values, value_id);
859 return result;
862 /* Subtract all the values in bitmap set B from bitmap set A. */
864 static void
865 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
867 unsigned int i;
868 bitmap_iterator bi;
869 pre_expr to_remove = NULL;
870 FOR_EACH_EXPR_ID_IN_SET (a, i, bi)
872 if (to_remove)
874 bitmap_remove_from_set (a, to_remove);
875 to_remove = NULL;
877 pre_expr expr = expression_for_id (i);
878 if (bitmap_set_contains_value (b, get_expr_value_id (expr)))
879 to_remove = expr;
881 if (to_remove)
882 bitmap_remove_from_set (a, to_remove);
886 /* Return true if bitmapped set SET contains the value VALUE_ID. */
888 static bool
889 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
891 if (value_id_constant_p (value_id))
892 return true;
894 if (!set || bitmap_empty_p (&set->expressions))
895 return false;
897 return bitmap_bit_p (&set->values, value_id);
900 static inline bool
901 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
903 return bitmap_bit_p (&set->expressions, get_expression_id (expr));
906 /* Replace an instance of value LOOKFOR with expression EXPR in SET. */
908 static void
909 bitmap_set_replace_value (bitmap_set_t set, unsigned int lookfor,
910 const pre_expr expr)
912 bitmap exprset;
913 unsigned int i;
914 bitmap_iterator bi;
916 if (value_id_constant_p (lookfor))
917 return;
919 if (!bitmap_set_contains_value (set, lookfor))
920 return;
922 /* The number of expressions having a given value is usually
923 significantly less than the total number of expressions in SET.
924 Thus, rather than check, for each expression in SET, whether it
925 has the value LOOKFOR, we walk the reverse mapping that tells us
926 what expressions have a given value, and see if any of those
927 expressions are in our set. For large testcases, this is about
928 5-10x faster than walking the bitmap. If this is somehow a
929 significant lose for some cases, we can choose which set to walk
930 based on the set size. */
931 exprset = value_expressions[lookfor];
932 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
934 if (bitmap_clear_bit (&set->expressions, i))
936 bitmap_set_bit (&set->expressions, get_expression_id (expr));
937 return;
941 gcc_unreachable ();
944 /* Return true if two bitmap sets are equal. */
946 static bool
947 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
949 return bitmap_equal_p (&a->values, &b->values);
952 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
953 and add it otherwise. */
955 static void
956 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
958 unsigned int val = get_expr_value_id (expr);
960 if (bitmap_set_contains_value (set, val))
961 bitmap_set_replace_value (set, val, expr);
962 else
963 bitmap_insert_into_set (set, expr);
966 /* Insert EXPR into SET if EXPR's value is not already present in
967 SET. */
969 static void
970 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
972 unsigned int val = get_expr_value_id (expr);
974 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
976 /* Constant values are always considered to be part of the set. */
977 if (value_id_constant_p (val))
978 return;
980 /* If the value membership changed, add the expression. */
981 if (bitmap_set_bit (&set->values, val))
982 bitmap_set_bit (&set->expressions, expr->id);
985 /* Print out EXPR to outfile. */
987 static void
988 print_pre_expr (FILE *outfile, const pre_expr expr)
990 switch (expr->kind)
992 case CONSTANT:
993 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr));
994 break;
995 case NAME:
996 print_generic_expr (outfile, PRE_EXPR_NAME (expr));
997 break;
998 case NARY:
1000 unsigned int i;
1001 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1002 fprintf (outfile, "{%s,", get_tree_code_name (nary->opcode));
1003 for (i = 0; i < nary->length; i++)
1005 print_generic_expr (outfile, nary->op[i]);
1006 if (i != (unsigned) nary->length - 1)
1007 fprintf (outfile, ",");
1009 fprintf (outfile, "}");
1011 break;
1013 case REFERENCE:
1015 vn_reference_op_t vro;
1016 unsigned int i;
1017 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1018 fprintf (outfile, "{");
1019 for (i = 0;
1020 ref->operands.iterate (i, &vro);
1021 i++)
1023 bool closebrace = false;
1024 if (vro->opcode != SSA_NAME
1025 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
1027 fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
1028 if (vro->op0)
1030 fprintf (outfile, "<");
1031 closebrace = true;
1034 if (vro->op0)
1036 print_generic_expr (outfile, vro->op0);
1037 if (vro->op1)
1039 fprintf (outfile, ",");
1040 print_generic_expr (outfile, vro->op1);
1042 if (vro->op2)
1044 fprintf (outfile, ",");
1045 print_generic_expr (outfile, vro->op2);
1048 if (closebrace)
1049 fprintf (outfile, ">");
1050 if (i != ref->operands.length () - 1)
1051 fprintf (outfile, ",");
1053 fprintf (outfile, "}");
1054 if (ref->vuse)
1056 fprintf (outfile, "@");
1057 print_generic_expr (outfile, ref->vuse);
1060 break;
1063 void debug_pre_expr (pre_expr);
1065 /* Like print_pre_expr but always prints to stderr. */
1066 DEBUG_FUNCTION void
1067 debug_pre_expr (pre_expr e)
1069 print_pre_expr (stderr, e);
1070 fprintf (stderr, "\n");
1073 /* Print out SET to OUTFILE. */
1075 static void
1076 print_bitmap_set (FILE *outfile, bitmap_set_t set,
1077 const char *setname, int blockindex)
1079 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
1080 if (set)
1082 bool first = true;
1083 unsigned i;
1084 bitmap_iterator bi;
1086 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1088 const pre_expr expr = expression_for_id (i);
1090 if (!first)
1091 fprintf (outfile, ", ");
1092 first = false;
1093 print_pre_expr (outfile, expr);
1095 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1098 fprintf (outfile, " }\n");
1101 void debug_bitmap_set (bitmap_set_t);
1103 DEBUG_FUNCTION void
1104 debug_bitmap_set (bitmap_set_t set)
1106 print_bitmap_set (stderr, set, "debug", 0);
1109 void debug_bitmap_sets_for (basic_block);
1111 DEBUG_FUNCTION void
1112 debug_bitmap_sets_for (basic_block bb)
1114 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1115 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1116 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1117 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1118 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1119 if (do_partial_partial)
1120 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1121 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1124 /* Print out the expressions that have VAL to OUTFILE. */
1126 static void
1127 print_value_expressions (FILE *outfile, unsigned int val)
1129 bitmap set = value_expressions[val];
1130 if (set)
1132 bitmap_set x;
1133 char s[10];
1134 sprintf (s, "%04d", val);
1135 x.expressions = *set;
1136 print_bitmap_set (outfile, &x, s, 0);
1141 DEBUG_FUNCTION void
1142 debug_value_expressions (unsigned int val)
1144 print_value_expressions (stderr, val);
1147 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1148 represent it. */
1150 static pre_expr
1151 get_or_alloc_expr_for_constant (tree constant)
1153 unsigned int result_id;
1154 unsigned int value_id;
1155 struct pre_expr_d expr;
1156 pre_expr newexpr;
1158 expr.kind = CONSTANT;
1159 PRE_EXPR_CONSTANT (&expr) = constant;
1160 result_id = lookup_expression_id (&expr);
1161 if (result_id != 0)
1162 return expression_for_id (result_id);
1164 newexpr = pre_expr_pool.allocate ();
1165 newexpr->kind = CONSTANT;
1166 PRE_EXPR_CONSTANT (newexpr) = constant;
1167 alloc_expression_id (newexpr);
1168 value_id = get_or_alloc_constant_value_id (constant);
1169 add_to_value (value_id, newexpr);
1170 return newexpr;
1173 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1174 Currently only supports constants and SSA_NAMES. */
1175 static pre_expr
1176 get_or_alloc_expr_for (tree t)
1178 if (TREE_CODE (t) == SSA_NAME)
1179 return get_or_alloc_expr_for_name (t);
1180 else if (is_gimple_min_invariant (t))
1181 return get_or_alloc_expr_for_constant (t);
1182 gcc_unreachable ();
1185 /* Return the folded version of T if T, when folded, is a gimple
1186 min_invariant or an SSA name. Otherwise, return T. */
1188 static pre_expr
1189 fully_constant_expression (pre_expr e)
1191 switch (e->kind)
1193 case CONSTANT:
1194 return e;
1195 case NARY:
1197 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1198 tree res = vn_nary_simplify (nary);
1199 if (!res)
1200 return e;
1201 if (is_gimple_min_invariant (res))
1202 return get_or_alloc_expr_for_constant (res);
1203 if (TREE_CODE (res) == SSA_NAME)
1204 return get_or_alloc_expr_for_name (res);
1205 return e;
1207 case REFERENCE:
1209 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1210 tree folded;
1211 if ((folded = fully_constant_vn_reference_p (ref)))
1212 return get_or_alloc_expr_for_constant (folded);
1213 return e;
1215 default:
1216 return e;
1218 return e;
1221 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1222 it has the value it would have in BLOCK. Set *SAME_VALID to true
1223 in case the new vuse doesn't change the value id of the OPERANDS. */
1225 static tree
1226 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1227 alias_set_type set, tree type, tree vuse,
1228 basic_block phiblock,
1229 basic_block block, bool *same_valid)
1231 gimple *phi = SSA_NAME_DEF_STMT (vuse);
1232 ao_ref ref;
1233 edge e = NULL;
1234 bool use_oracle;
1236 *same_valid = true;
1238 if (gimple_bb (phi) != phiblock)
1239 return vuse;
1241 use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1243 /* Use the alias-oracle to find either the PHI node in this block,
1244 the first VUSE used in this block that is equivalent to vuse or
1245 the first VUSE which definition in this block kills the value. */
1246 if (gimple_code (phi) == GIMPLE_PHI)
1247 e = find_edge (block, phiblock);
1248 else if (use_oracle)
1249 while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1251 vuse = gimple_vuse (phi);
1252 phi = SSA_NAME_DEF_STMT (vuse);
1253 if (gimple_bb (phi) != phiblock)
1254 return vuse;
1255 if (gimple_code (phi) == GIMPLE_PHI)
1257 e = find_edge (block, phiblock);
1258 break;
1261 else
1262 return NULL_TREE;
1264 if (e)
1266 if (use_oracle)
1268 bitmap visited = NULL;
1269 unsigned int cnt;
1270 /* Try to find a vuse that dominates this phi node by skipping
1271 non-clobbering statements. */
1272 vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false,
1273 NULL, NULL);
1274 if (visited)
1275 BITMAP_FREE (visited);
1277 else
1278 vuse = NULL_TREE;
1279 if (!vuse)
1281 /* If we didn't find any, the value ID can't stay the same,
1282 but return the translated vuse. */
1283 *same_valid = false;
1284 vuse = PHI_ARG_DEF (phi, e->dest_idx);
1286 /* ??? We would like to return vuse here as this is the canonical
1287 upmost vdef that this reference is associated with. But during
1288 insertion of the references into the hash tables we only ever
1289 directly insert with their direct gimple_vuse, hence returning
1290 something else would make us not find the other expression. */
1291 return PHI_ARG_DEF (phi, e->dest_idx);
1294 return NULL_TREE;
1297 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1298 SET2 *or* SET3. This is used to avoid making a set consisting of the union
1299 of PA_IN and ANTIC_IN during insert and phi-translation. */
1301 static inline pre_expr
1302 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2,
1303 bitmap_set_t set3 = NULL)
1305 pre_expr result;
1307 result = bitmap_find_leader (set1, val);
1308 if (!result && set2)
1309 result = bitmap_find_leader (set2, val);
1310 if (!result && set3)
1311 result = bitmap_find_leader (set3, val);
1312 return result;
1315 /* Get the tree type for our PRE expression e. */
1317 static tree
1318 get_expr_type (const pre_expr e)
1320 switch (e->kind)
1322 case NAME:
1323 return TREE_TYPE (PRE_EXPR_NAME (e));
1324 case CONSTANT:
1325 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1326 case REFERENCE:
1327 return PRE_EXPR_REFERENCE (e)->type;
1328 case NARY:
1329 return PRE_EXPR_NARY (e)->type;
1331 gcc_unreachable ();
1334 /* Get a representative SSA_NAME for a given expression.
1335 Since all of our sub-expressions are treated as values, we require
1336 them to be SSA_NAME's for simplicity.
1337 Prior versions of GVNPRE used to use "value handles" here, so that
1338 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1339 either case, the operands are really values (IE we do not expect
1340 them to be usable without finding leaders). */
1342 static tree
1343 get_representative_for (const pre_expr e)
1345 tree name;
1346 unsigned int value_id = get_expr_value_id (e);
1348 switch (e->kind)
1350 case NAME:
1351 return VN_INFO (PRE_EXPR_NAME (e))->valnum;
1352 case CONSTANT:
1353 return PRE_EXPR_CONSTANT (e);
1354 case NARY:
1355 case REFERENCE:
1357 /* Go through all of the expressions representing this value
1358 and pick out an SSA_NAME. */
1359 unsigned int i;
1360 bitmap_iterator bi;
1361 bitmap exprs = value_expressions[value_id];
1362 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1364 pre_expr rep = expression_for_id (i);
1365 if (rep->kind == NAME)
1366 return VN_INFO (PRE_EXPR_NAME (rep))->valnum;
1367 else if (rep->kind == CONSTANT)
1368 return PRE_EXPR_CONSTANT (rep);
1371 break;
1374 /* If we reached here we couldn't find an SSA_NAME. This can
1375 happen when we've discovered a value that has never appeared in
1376 the program as set to an SSA_NAME, as the result of phi translation.
1377 Create one here.
1378 ??? We should be able to re-use this when we insert the statement
1379 to compute it. */
1380 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1381 VN_INFO_GET (name)->value_id = value_id;
1382 VN_INFO (name)->valnum = name;
1383 /* ??? For now mark this SSA name for release by SCCVN. */
1384 VN_INFO (name)->needs_insertion = true;
1385 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1386 if (dump_file && (dump_flags & TDF_DETAILS))
1388 fprintf (dump_file, "Created SSA_NAME representative ");
1389 print_generic_expr (dump_file, name);
1390 fprintf (dump_file, " for expression:");
1391 print_pre_expr (dump_file, e);
1392 fprintf (dump_file, " (%04d)\n", value_id);
1395 return name;
1400 static pre_expr
1401 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1402 basic_block pred, basic_block phiblock);
1404 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1405 the phis in PRED. Return NULL if we can't find a leader for each part
1406 of the translated expression. */
1408 static pre_expr
1409 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1410 basic_block pred, basic_block phiblock)
1412 switch (expr->kind)
1414 case NARY:
1416 unsigned int i;
1417 bool changed = false;
1418 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1419 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1420 sizeof_vn_nary_op (nary->length));
1421 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1423 for (i = 0; i < newnary->length; i++)
1425 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1426 continue;
1427 else
1429 pre_expr leader, result;
1430 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1431 leader = find_leader_in_sets (op_val_id, set1, set2);
1432 result = phi_translate (leader, set1, set2, pred, phiblock);
1433 if (result && result != leader)
1434 newnary->op[i] = get_representative_for (result);
1435 else if (!result)
1436 return NULL;
1438 changed |= newnary->op[i] != nary->op[i];
1441 if (changed)
1443 pre_expr constant;
1444 unsigned int new_val_id;
1446 PRE_EXPR_NARY (expr) = newnary;
1447 constant = fully_constant_expression (expr);
1448 PRE_EXPR_NARY (expr) = nary;
1449 if (constant != expr)
1451 /* For non-CONSTANTs we have to make sure we can eventually
1452 insert the expression. Which means we need to have a
1453 leader for it. */
1454 if (constant->kind != CONSTANT)
1456 /* Do not allow simplifications to non-constants over
1457 backedges as this will likely result in a loop PHI node
1458 to be inserted and increased register pressure.
1459 See PR77498 - this avoids doing predcoms work in
1460 a less efficient way. */
1461 if (find_edge (pred, phiblock)->flags & EDGE_DFS_BACK)
1463 else
1465 unsigned value_id = get_expr_value_id (constant);
1466 constant = find_leader_in_sets (value_id, set1, set2,
1467 AVAIL_OUT (pred));
1468 if (constant)
1469 return constant;
1472 else
1473 return constant;
1476 tree result = vn_nary_op_lookup_pieces (newnary->length,
1477 newnary->opcode,
1478 newnary->type,
1479 &newnary->op[0],
1480 &nary);
1481 if (result && is_gimple_min_invariant (result))
1482 return get_or_alloc_expr_for_constant (result);
1484 expr = pre_expr_pool.allocate ();
1485 expr->kind = NARY;
1486 expr->id = 0;
1487 if (nary)
1489 PRE_EXPR_NARY (expr) = nary;
1490 new_val_id = nary->value_id;
1491 get_or_alloc_expression_id (expr);
1492 /* When we end up re-using a value number make sure that
1493 doesn't have unrelated (which we can't check here)
1494 range or points-to info on it. */
1495 if (result
1496 && INTEGRAL_TYPE_P (TREE_TYPE (result))
1497 && SSA_NAME_RANGE_INFO (result)
1498 && ! SSA_NAME_IS_DEFAULT_DEF (result))
1500 if (! VN_INFO (result)->info.range_info)
1502 VN_INFO (result)->info.range_info
1503 = SSA_NAME_RANGE_INFO (result);
1504 VN_INFO (result)->range_info_anti_range_p
1505 = SSA_NAME_ANTI_RANGE_P (result);
1507 if (dump_file && (dump_flags & TDF_DETAILS))
1509 fprintf (dump_file, "clearing range info of ");
1510 print_generic_expr (dump_file, result);
1511 fprintf (dump_file, "\n");
1513 SSA_NAME_RANGE_INFO (result) = NULL;
1515 else if (result
1516 && POINTER_TYPE_P (TREE_TYPE (result))
1517 && SSA_NAME_PTR_INFO (result)
1518 && ! SSA_NAME_IS_DEFAULT_DEF (result))
1520 if (! VN_INFO (result)->info.ptr_info)
1521 VN_INFO (result)->info.ptr_info
1522 = SSA_NAME_PTR_INFO (result);
1523 if (dump_file && (dump_flags & TDF_DETAILS))
1525 fprintf (dump_file, "clearing points-to info of ");
1526 print_generic_expr (dump_file, result);
1527 fprintf (dump_file, "\n");
1529 SSA_NAME_PTR_INFO (result) = NULL;
1532 else
1534 new_val_id = get_next_value_id ();
1535 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
1536 nary = vn_nary_op_insert_pieces (newnary->length,
1537 newnary->opcode,
1538 newnary->type,
1539 &newnary->op[0],
1540 result, new_val_id);
1541 PRE_EXPR_NARY (expr) = nary;
1542 get_or_alloc_expression_id (expr);
1544 add_to_value (new_val_id, expr);
1546 return expr;
1548 break;
1550 case REFERENCE:
1552 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1553 vec<vn_reference_op_s> operands = ref->operands;
1554 tree vuse = ref->vuse;
1555 tree newvuse = vuse;
1556 vec<vn_reference_op_s> newoperands = vNULL;
1557 bool changed = false, same_valid = true;
1558 unsigned int i, n;
1559 vn_reference_op_t operand;
1560 vn_reference_t newref;
1562 for (i = 0; operands.iterate (i, &operand); i++)
1564 pre_expr opresult;
1565 pre_expr leader;
1566 tree op[3];
1567 tree type = operand->type;
1568 vn_reference_op_s newop = *operand;
1569 op[0] = operand->op0;
1570 op[1] = operand->op1;
1571 op[2] = operand->op2;
1572 for (n = 0; n < 3; ++n)
1574 unsigned int op_val_id;
1575 if (!op[n])
1576 continue;
1577 if (TREE_CODE (op[n]) != SSA_NAME)
1579 /* We can't possibly insert these. */
1580 if (n != 0
1581 && !is_gimple_min_invariant (op[n]))
1582 break;
1583 continue;
1585 op_val_id = VN_INFO (op[n])->value_id;
1586 leader = find_leader_in_sets (op_val_id, set1, set2);
1587 opresult = phi_translate (leader, set1, set2, pred, phiblock);
1588 if (opresult && opresult != leader)
1590 tree name = get_representative_for (opresult);
1591 changed |= name != op[n];
1592 op[n] = name;
1594 else if (!opresult)
1595 break;
1597 if (n != 3)
1599 newoperands.release ();
1600 return NULL;
1602 if (!changed)
1603 continue;
1604 if (!newoperands.exists ())
1605 newoperands = operands.copy ();
1606 /* We may have changed from an SSA_NAME to a constant */
1607 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1608 newop.opcode = TREE_CODE (op[0]);
1609 newop.type = type;
1610 newop.op0 = op[0];
1611 newop.op1 = op[1];
1612 newop.op2 = op[2];
1613 newoperands[i] = newop;
1615 gcc_checking_assert (i == operands.length ());
1617 if (vuse)
1619 newvuse = translate_vuse_through_block (newoperands.exists ()
1620 ? newoperands : operands,
1621 ref->set, ref->type,
1622 vuse, phiblock, pred,
1623 &same_valid);
1624 if (newvuse == NULL_TREE)
1626 newoperands.release ();
1627 return NULL;
1631 if (changed || newvuse != vuse)
1633 unsigned int new_val_id;
1634 pre_expr constant;
1636 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1637 ref->type,
1638 newoperands.exists ()
1639 ? newoperands : operands,
1640 &newref, VN_WALK);
1641 if (result)
1642 newoperands.release ();
1644 /* We can always insert constants, so if we have a partial
1645 redundant constant load of another type try to translate it
1646 to a constant of appropriate type. */
1647 if (result && is_gimple_min_invariant (result))
1649 tree tem = result;
1650 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1652 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1653 if (tem && !is_gimple_min_invariant (tem))
1654 tem = NULL_TREE;
1656 if (tem)
1657 return get_or_alloc_expr_for_constant (tem);
1660 /* If we'd have to convert things we would need to validate
1661 if we can insert the translated expression. So fail
1662 here for now - we cannot insert an alias with a different
1663 type in the VN tables either, as that would assert. */
1664 if (result
1665 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1666 return NULL;
1667 else if (!result && newref
1668 && !useless_type_conversion_p (ref->type, newref->type))
1670 newoperands.release ();
1671 return NULL;
1674 expr = pre_expr_pool.allocate ();
1675 expr->kind = REFERENCE;
1676 expr->id = 0;
1678 if (newref)
1680 PRE_EXPR_REFERENCE (expr) = newref;
1681 constant = fully_constant_expression (expr);
1682 if (constant != expr)
1683 return constant;
1685 new_val_id = newref->value_id;
1686 get_or_alloc_expression_id (expr);
1688 else
1690 if (changed || !same_valid)
1692 new_val_id = get_next_value_id ();
1693 value_expressions.safe_grow_cleared
1694 (get_max_value_id () + 1);
1696 else
1697 new_val_id = ref->value_id;
1698 if (!newoperands.exists ())
1699 newoperands = operands.copy ();
1700 newref = vn_reference_insert_pieces (newvuse, ref->set,
1701 ref->type,
1702 newoperands,
1703 result, new_val_id);
1704 newoperands = vNULL;
1705 PRE_EXPR_REFERENCE (expr) = newref;
1706 constant = fully_constant_expression (expr);
1707 if (constant != expr)
1708 return constant;
1709 get_or_alloc_expression_id (expr);
1711 add_to_value (new_val_id, expr);
1713 newoperands.release ();
1714 return expr;
1716 break;
1718 case NAME:
1720 tree name = PRE_EXPR_NAME (expr);
1721 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1722 /* If the SSA name is defined by a PHI node in this block,
1723 translate it. */
1724 if (gimple_code (def_stmt) == GIMPLE_PHI
1725 && gimple_bb (def_stmt) == phiblock)
1727 edge e = find_edge (pred, gimple_bb (def_stmt));
1728 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1730 /* Handle constant. */
1731 if (is_gimple_min_invariant (def))
1732 return get_or_alloc_expr_for_constant (def);
1734 return get_or_alloc_expr_for_name (def);
1736 /* Otherwise return it unchanged - it will get removed if its
1737 value is not available in PREDs AVAIL_OUT set of expressions
1738 by the subtraction of TMP_GEN. */
1739 return expr;
1742 default:
1743 gcc_unreachable ();
1747 /* Wrapper around phi_translate_1 providing caching functionality. */
1749 static pre_expr
1750 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1751 basic_block pred, basic_block phiblock)
1753 expr_pred_trans_t slot = NULL;
1754 pre_expr phitrans;
1756 if (!expr)
1757 return NULL;
1759 /* Constants contain no values that need translation. */
1760 if (expr->kind == CONSTANT)
1761 return expr;
1763 if (value_id_constant_p (get_expr_value_id (expr)))
1764 return expr;
1766 /* Don't add translations of NAMEs as those are cheap to translate. */
1767 if (expr->kind != NAME)
1769 if (phi_trans_add (&slot, expr, pred))
1770 return slot->v;
1771 /* Store NULL for the value we want to return in the case of
1772 recursing. */
1773 slot->v = NULL;
1776 /* Translate. */
1777 phitrans = phi_translate_1 (expr, set1, set2, pred, phiblock);
1779 if (slot)
1781 if (phitrans)
1782 slot->v = phitrans;
1783 else
1784 /* Remove failed translations again, they cause insert
1785 iteration to not pick up new opportunities reliably. */
1786 phi_translate_table->remove_elt_with_hash (slot, slot->hashcode);
1789 return phitrans;
1793 /* For each expression in SET, translate the values through phi nodes
1794 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1795 expressions in DEST. */
1797 static void
1798 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1799 basic_block phiblock)
1801 vec<pre_expr> exprs;
1802 pre_expr expr;
1803 int i;
1805 if (gimple_seq_empty_p (phi_nodes (phiblock)))
1807 bitmap_set_copy (dest, set);
1808 return;
1811 exprs = sorted_array_from_bitmap_set (set);
1812 FOR_EACH_VEC_ELT (exprs, i, expr)
1814 pre_expr translated;
1815 translated = phi_translate (expr, set, NULL, pred, phiblock);
1816 if (!translated)
1817 continue;
1819 /* We might end up with multiple expressions from SET being
1820 translated to the same value. In this case we do not want
1821 to retain the NARY or REFERENCE expression but prefer a NAME
1822 which would be the leader. */
1823 if (translated->kind == NAME)
1824 bitmap_value_replace_in_set (dest, translated);
1825 else
1826 bitmap_value_insert_into_set (dest, translated);
1828 exprs.release ();
1831 /* Find the leader for a value (i.e., the name representing that
1832 value) in a given set, and return it. Return NULL if no leader
1833 is found. */
1835 static pre_expr
1836 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1838 if (value_id_constant_p (val))
1840 unsigned int i;
1841 bitmap_iterator bi;
1842 bitmap exprset = value_expressions[val];
1844 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1846 pre_expr expr = expression_for_id (i);
1847 if (expr->kind == CONSTANT)
1848 return expr;
1851 if (bitmap_set_contains_value (set, val))
1853 /* Rather than walk the entire bitmap of expressions, and see
1854 whether any of them has the value we are looking for, we look
1855 at the reverse mapping, which tells us the set of expressions
1856 that have a given value (IE value->expressions with that
1857 value) and see if any of those expressions are in our set.
1858 The number of expressions per value is usually significantly
1859 less than the number of expressions in the set. In fact, for
1860 large testcases, doing it this way is roughly 5-10x faster
1861 than walking the bitmap.
1862 If this is somehow a significant lose for some cases, we can
1863 choose which set to walk based on which set is smaller. */
1864 unsigned int i;
1865 bitmap_iterator bi;
1866 bitmap exprset = value_expressions[val];
1868 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1869 return expression_for_id (i);
1871 return NULL;
1874 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1875 BLOCK by seeing if it is not killed in the block. Note that we are
1876 only determining whether there is a store that kills it. Because
1877 of the order in which clean iterates over values, we are guaranteed
1878 that altered operands will have caused us to be eliminated from the
1879 ANTIC_IN set already. */
1881 static bool
1882 value_dies_in_block_x (pre_expr expr, basic_block block)
1884 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1885 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1886 gimple *def;
1887 gimple_stmt_iterator gsi;
1888 unsigned id = get_expression_id (expr);
1889 bool res = false;
1890 ao_ref ref;
1892 if (!vuse)
1893 return false;
1895 /* Lookup a previously calculated result. */
1896 if (EXPR_DIES (block)
1897 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1898 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1900 /* A memory expression {e, VUSE} dies in the block if there is a
1901 statement that may clobber e. If, starting statement walk from the
1902 top of the basic block, a statement uses VUSE there can be no kill
1903 inbetween that use and the original statement that loaded {e, VUSE},
1904 so we can stop walking. */
1905 ref.base = NULL_TREE;
1906 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1908 tree def_vuse, def_vdef;
1909 def = gsi_stmt (gsi);
1910 def_vuse = gimple_vuse (def);
1911 def_vdef = gimple_vdef (def);
1913 /* Not a memory statement. */
1914 if (!def_vuse)
1915 continue;
1917 /* Not a may-def. */
1918 if (!def_vdef)
1920 /* A load with the same VUSE, we're done. */
1921 if (def_vuse == vuse)
1922 break;
1924 continue;
1927 /* Init ref only if we really need it. */
1928 if (ref.base == NULL_TREE
1929 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1930 refx->operands))
1932 res = true;
1933 break;
1935 /* If the statement may clobber expr, it dies. */
1936 if (stmt_may_clobber_ref_p_1 (def, &ref))
1938 res = true;
1939 break;
1943 /* Remember the result. */
1944 if (!EXPR_DIES (block))
1945 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1946 bitmap_set_bit (EXPR_DIES (block), id * 2);
1947 if (res)
1948 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1950 return res;
1954 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1955 contains its value-id. */
1957 static bool
1958 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1960 if (op && TREE_CODE (op) == SSA_NAME)
1962 unsigned int value_id = VN_INFO (op)->value_id;
1963 if (!(bitmap_set_contains_value (set1, value_id)
1964 || (set2 && bitmap_set_contains_value (set2, value_id))))
1965 return false;
1967 return true;
1970 /* Determine if the expression EXPR is valid in SET1 U SET2.
1971 ONLY SET2 CAN BE NULL.
1972 This means that we have a leader for each part of the expression
1973 (if it consists of values), or the expression is an SSA_NAME.
1974 For loads/calls, we also see if the vuse is killed in this block. */
1976 static bool
1977 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr)
1979 switch (expr->kind)
1981 case NAME:
1982 /* By construction all NAMEs are available. Non-available
1983 NAMEs are removed by subtracting TMP_GEN from the sets. */
1984 return true;
1985 case NARY:
1987 unsigned int i;
1988 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1989 for (i = 0; i < nary->length; i++)
1990 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1991 return false;
1992 return true;
1994 break;
1995 case REFERENCE:
1997 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1998 vn_reference_op_t vro;
1999 unsigned int i;
2001 FOR_EACH_VEC_ELT (ref->operands, i, vro)
2003 if (!op_valid_in_sets (set1, set2, vro->op0)
2004 || !op_valid_in_sets (set1, set2, vro->op1)
2005 || !op_valid_in_sets (set1, set2, vro->op2))
2006 return false;
2008 return true;
2010 default:
2011 gcc_unreachable ();
2015 /* Clean the set of expressions that are no longer valid in SET1 or
2016 SET2. This means expressions that are made up of values we have no
2017 leaders for in SET1 or SET2. This version is used for partial
2018 anticipation, which means it is not valid in either ANTIC_IN or
2019 PA_IN. */
2021 static void
2022 dependent_clean (bitmap_set_t set1, bitmap_set_t set2)
2024 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
2025 pre_expr expr;
2026 int i;
2028 FOR_EACH_VEC_ELT (exprs, i, expr)
2030 if (!valid_in_sets (set1, set2, expr))
2031 bitmap_remove_from_set (set1, expr);
2033 exprs.release ();
2036 /* Clean the set of expressions that are no longer valid in SET. This
2037 means expressions that are made up of values we have no leaders for
2038 in SET. */
2040 static void
2041 clean (bitmap_set_t set)
2043 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set);
2044 pre_expr expr;
2045 int i;
2047 FOR_EACH_VEC_ELT (exprs, i, expr)
2049 if (!valid_in_sets (set, NULL, expr))
2050 bitmap_remove_from_set (set, expr);
2052 exprs.release ();
2055 /* Clean the set of expressions that are no longer valid in SET because
2056 they are clobbered in BLOCK or because they trap and may not be executed. */
2058 static void
2059 prune_clobbered_mems (bitmap_set_t set, basic_block block)
2061 bitmap_iterator bi;
2062 unsigned i;
2063 pre_expr to_remove = NULL;
2065 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2067 /* Remove queued expr. */
2068 if (to_remove)
2070 bitmap_remove_from_set (set, to_remove);
2071 to_remove = NULL;
2074 pre_expr expr = expression_for_id (i);
2075 if (expr->kind == REFERENCE)
2077 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2078 if (ref->vuse)
2080 gimple *def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
2081 if (!gimple_nop_p (def_stmt)
2082 && ((gimple_bb (def_stmt) != block
2083 && !dominated_by_p (CDI_DOMINATORS,
2084 block, gimple_bb (def_stmt)))
2085 || (gimple_bb (def_stmt) == block
2086 && value_dies_in_block_x (expr, block))))
2087 to_remove = expr;
2090 else if (expr->kind == NARY)
2092 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2093 /* If the NARY may trap make sure the block does not contain
2094 a possible exit point.
2095 ??? This is overly conservative if we translate AVAIL_OUT
2096 as the available expression might be after the exit point. */
2097 if (BB_MAY_NOTRETURN (block)
2098 && vn_nary_may_trap (nary))
2099 to_remove = expr;
2103 /* Remove queued expr. */
2104 if (to_remove)
2105 bitmap_remove_from_set (set, to_remove);
2108 static sbitmap has_abnormal_preds;
2110 /* Compute the ANTIC set for BLOCK.
2112 If succs(BLOCK) > 1 then
2113 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2114 else if succs(BLOCK) == 1 then
2115 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2117 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2120 static bool
2121 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2123 bool changed = false;
2124 bitmap_set_t S, old, ANTIC_OUT;
2125 bitmap_iterator bi;
2126 unsigned int bii;
2127 edge e;
2128 edge_iterator ei;
2129 bool was_visited = BB_VISITED (block);
2131 old = ANTIC_OUT = S = NULL;
2132 BB_VISITED (block) = 1;
2134 /* If any edges from predecessors are abnormal, antic_in is empty,
2135 so do nothing. */
2136 if (block_has_abnormal_pred_edge)
2137 goto maybe_dump_sets;
2139 old = ANTIC_IN (block);
2140 ANTIC_OUT = bitmap_set_new ();
2142 /* If the block has no successors, ANTIC_OUT is empty. */
2143 if (EDGE_COUNT (block->succs) == 0)
2145 /* If we have one successor, we could have some phi nodes to
2146 translate through. */
2147 else if (single_succ_p (block))
2149 basic_block succ_bb = single_succ (block);
2150 gcc_assert (BB_VISITED (succ_bb));
2151 phi_translate_set (ANTIC_OUT, ANTIC_IN (succ_bb), block, succ_bb);
2153 /* If we have multiple successors, we take the intersection of all of
2154 them. Note that in the case of loop exit phi nodes, we may have
2155 phis to translate through. */
2156 else
2158 size_t i;
2159 basic_block bprime, first = NULL;
2161 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2162 FOR_EACH_EDGE (e, ei, block->succs)
2164 if (!first
2165 && BB_VISITED (e->dest))
2166 first = e->dest;
2167 else if (BB_VISITED (e->dest))
2168 worklist.quick_push (e->dest);
2169 else
2171 /* Unvisited successors get their ANTIC_IN replaced by the
2172 maximal set to arrive at a maximum ANTIC_IN solution.
2173 We can ignore them in the intersection operation and thus
2174 need not explicitely represent that maximum solution. */
2175 if (dump_file && (dump_flags & TDF_DETAILS))
2176 fprintf (dump_file, "ANTIC_IN is MAX on %d->%d\n",
2177 e->src->index, e->dest->index);
2181 /* Of multiple successors we have to have visited one already
2182 which is guaranteed by iteration order. */
2183 gcc_assert (first != NULL);
2185 phi_translate_set (ANTIC_OUT, ANTIC_IN (first), block, first);
2187 FOR_EACH_VEC_ELT (worklist, i, bprime)
2189 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2191 bitmap_set_t tmp = bitmap_set_new ();
2192 phi_translate_set (tmp, ANTIC_IN (bprime), block, bprime);
2193 bitmap_set_and (ANTIC_OUT, tmp);
2194 bitmap_set_free (tmp);
2196 else
2197 bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2201 /* Prune expressions that are clobbered in block and thus become
2202 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2203 prune_clobbered_mems (ANTIC_OUT, block);
2205 /* Generate ANTIC_OUT - TMP_GEN. */
2206 S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2208 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2209 ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2210 TMP_GEN (block));
2212 /* Then union in the ANTIC_OUT - TMP_GEN values,
2213 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2214 FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2215 bitmap_value_insert_into_set (ANTIC_IN (block),
2216 expression_for_id (bii));
2218 clean (ANTIC_IN (block));
2220 if (!was_visited || !bitmap_set_equal (old, ANTIC_IN (block)))
2221 changed = true;
2223 maybe_dump_sets:
2224 if (dump_file && (dump_flags & TDF_DETAILS))
2226 if (ANTIC_OUT)
2227 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2229 if (changed)
2230 fprintf (dump_file, "[changed] ");
2231 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2232 block->index);
2234 if (S)
2235 print_bitmap_set (dump_file, S, "S", block->index);
2237 if (old)
2238 bitmap_set_free (old);
2239 if (S)
2240 bitmap_set_free (S);
2241 if (ANTIC_OUT)
2242 bitmap_set_free (ANTIC_OUT);
2243 return changed;
2246 /* Compute PARTIAL_ANTIC for BLOCK.
2248 If succs(BLOCK) > 1 then
2249 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2250 in ANTIC_OUT for all succ(BLOCK)
2251 else if succs(BLOCK) == 1 then
2252 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2254 PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2255 - ANTIC_IN[BLOCK])
2258 static void
2259 compute_partial_antic_aux (basic_block block,
2260 bool block_has_abnormal_pred_edge)
2262 bitmap_set_t old_PA_IN;
2263 bitmap_set_t PA_OUT;
2264 edge e;
2265 edge_iterator ei;
2266 unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2268 old_PA_IN = PA_OUT = NULL;
2270 /* If any edges from predecessors are abnormal, antic_in is empty,
2271 so do nothing. */
2272 if (block_has_abnormal_pred_edge)
2273 goto maybe_dump_sets;
2275 /* If there are too many partially anticipatable values in the
2276 block, phi_translate_set can take an exponential time: stop
2277 before the translation starts. */
2278 if (max_pa
2279 && single_succ_p (block)
2280 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2281 goto maybe_dump_sets;
2283 old_PA_IN = PA_IN (block);
2284 PA_OUT = bitmap_set_new ();
2286 /* If the block has no successors, ANTIC_OUT is empty. */
2287 if (EDGE_COUNT (block->succs) == 0)
2289 /* If we have one successor, we could have some phi nodes to
2290 translate through. Note that we can't phi translate across DFS
2291 back edges in partial antic, because it uses a union operation on
2292 the successors. For recurrences like IV's, we will end up
2293 generating a new value in the set on each go around (i + 3 (VH.1)
2294 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2295 else if (single_succ_p (block))
2297 basic_block succ = single_succ (block);
2298 if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2299 phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2301 /* If we have multiple successors, we take the union of all of
2302 them. */
2303 else
2305 size_t i;
2306 basic_block bprime;
2308 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2309 FOR_EACH_EDGE (e, ei, block->succs)
2311 if (e->flags & EDGE_DFS_BACK)
2312 continue;
2313 worklist.quick_push (e->dest);
2315 if (worklist.length () > 0)
2317 FOR_EACH_VEC_ELT (worklist, i, bprime)
2319 unsigned int i;
2320 bitmap_iterator bi;
2322 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2323 bitmap_value_insert_into_set (PA_OUT,
2324 expression_for_id (i));
2325 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2327 bitmap_set_t pa_in = bitmap_set_new ();
2328 phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2329 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2330 bitmap_value_insert_into_set (PA_OUT,
2331 expression_for_id (i));
2332 bitmap_set_free (pa_in);
2334 else
2335 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2336 bitmap_value_insert_into_set (PA_OUT,
2337 expression_for_id (i));
2342 /* Prune expressions that are clobbered in block and thus become
2343 invalid if translated from PA_OUT to PA_IN. */
2344 prune_clobbered_mems (PA_OUT, block);
2346 /* PA_IN starts with PA_OUT - TMP_GEN.
2347 Then we subtract things from ANTIC_IN. */
2348 PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2350 /* For partial antic, we want to put back in the phi results, since
2351 we will properly avoid making them partially antic over backedges. */
2352 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2353 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2355 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2356 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2358 dependent_clean (PA_IN (block), ANTIC_IN (block));
2360 maybe_dump_sets:
2361 if (dump_file && (dump_flags & TDF_DETAILS))
2363 if (PA_OUT)
2364 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2366 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2368 if (old_PA_IN)
2369 bitmap_set_free (old_PA_IN);
2370 if (PA_OUT)
2371 bitmap_set_free (PA_OUT);
2374 /* Compute ANTIC and partial ANTIC sets. */
2376 static void
2377 compute_antic (void)
2379 bool changed = true;
2380 int num_iterations = 0;
2381 basic_block block;
2382 int i;
2383 edge_iterator ei;
2384 edge e;
2386 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2387 We pre-build the map of blocks with incoming abnormal edges here. */
2388 has_abnormal_preds = sbitmap_alloc (last_basic_block_for_fn (cfun));
2389 bitmap_clear (has_abnormal_preds);
2391 FOR_ALL_BB_FN (block, cfun)
2393 BB_VISITED (block) = 0;
2395 FOR_EACH_EDGE (e, ei, block->preds)
2396 if (e->flags & EDGE_ABNORMAL)
2398 bitmap_set_bit (has_abnormal_preds, block->index);
2400 /* We also anticipate nothing. */
2401 BB_VISITED (block) = 1;
2402 break;
2405 /* While we are here, give empty ANTIC_IN sets to each block. */
2406 ANTIC_IN (block) = bitmap_set_new ();
2407 if (do_partial_partial)
2408 PA_IN (block) = bitmap_set_new ();
2411 /* At the exit block we anticipate nothing. */
2412 BB_VISITED (EXIT_BLOCK_PTR_FOR_FN (cfun)) = 1;
2414 /* For ANTIC computation we need a postorder that also guarantees that
2415 a block with a single successor is visited after its successor.
2416 RPO on the inverted CFG has this property. */
2417 auto_vec<int, 20> postorder;
2418 inverted_post_order_compute (&postorder);
2420 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
2421 bitmap_ones (worklist);
2422 while (changed)
2424 if (dump_file && (dump_flags & TDF_DETAILS))
2425 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2426 /* ??? We need to clear our PHI translation cache here as the
2427 ANTIC sets shrink and we restrict valid translations to
2428 those having operands with leaders in ANTIC. Same below
2429 for PA ANTIC computation. */
2430 num_iterations++;
2431 changed = false;
2432 for (i = postorder.length () - 1; i >= 0; i--)
2434 if (bitmap_bit_p (worklist, postorder[i]))
2436 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2437 bitmap_clear_bit (worklist, block->index);
2438 if (compute_antic_aux (block,
2439 bitmap_bit_p (has_abnormal_preds,
2440 block->index)))
2442 FOR_EACH_EDGE (e, ei, block->preds)
2443 bitmap_set_bit (worklist, e->src->index);
2444 changed = true;
2448 /* Theoretically possible, but *highly* unlikely. */
2449 gcc_checking_assert (num_iterations < 500);
2452 statistics_histogram_event (cfun, "compute_antic iterations",
2453 num_iterations);
2455 if (do_partial_partial)
2457 /* For partial antic we ignore backedges and thus we do not need
2458 to perform any iteration when we process blocks in postorder. */
2459 int postorder_num = pre_and_rev_post_order_compute (NULL, postorder.address (), false);
2460 for (i = postorder_num - 1 ; i >= 0; i--)
2462 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2463 compute_partial_antic_aux (block,
2464 bitmap_bit_p (has_abnormal_preds,
2465 block->index));
2469 sbitmap_free (has_abnormal_preds);
2473 /* Inserted expressions are placed onto this worklist, which is used
2474 for performing quick dead code elimination of insertions we made
2475 that didn't turn out to be necessary. */
2476 static bitmap inserted_exprs;
2478 /* The actual worker for create_component_ref_by_pieces. */
2480 static tree
2481 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2482 unsigned int *operand, gimple_seq *stmts)
2484 vn_reference_op_t currop = &ref->operands[*operand];
2485 tree genop;
2486 ++*operand;
2487 switch (currop->opcode)
2489 case CALL_EXPR:
2490 gcc_unreachable ();
2492 case MEM_REF:
2494 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2495 stmts);
2496 if (!baseop)
2497 return NULL_TREE;
2498 tree offset = currop->op0;
2499 if (TREE_CODE (baseop) == ADDR_EXPR
2500 && handled_component_p (TREE_OPERAND (baseop, 0)))
2502 HOST_WIDE_INT off;
2503 tree base;
2504 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2505 &off);
2506 gcc_assert (base);
2507 offset = int_const_binop (PLUS_EXPR, offset,
2508 build_int_cst (TREE_TYPE (offset),
2509 off));
2510 baseop = build_fold_addr_expr (base);
2512 genop = build2 (MEM_REF, currop->type, baseop, offset);
2513 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2514 MR_DEPENDENCE_BASE (genop) = currop->base;
2515 REF_REVERSE_STORAGE_ORDER (genop) = currop->reverse;
2516 return genop;
2519 case TARGET_MEM_REF:
2521 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2522 vn_reference_op_t nextop = &ref->operands[++*operand];
2523 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2524 stmts);
2525 if (!baseop)
2526 return NULL_TREE;
2527 if (currop->op0)
2529 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2530 if (!genop0)
2531 return NULL_TREE;
2533 if (nextop->op0)
2535 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2536 if (!genop1)
2537 return NULL_TREE;
2539 genop = build5 (TARGET_MEM_REF, currop->type,
2540 baseop, currop->op2, genop0, currop->op1, genop1);
2542 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2543 MR_DEPENDENCE_BASE (genop) = currop->base;
2544 return genop;
2547 case ADDR_EXPR:
2548 if (currop->op0)
2550 gcc_assert (is_gimple_min_invariant (currop->op0));
2551 return currop->op0;
2553 /* Fallthrough. */
2554 case REALPART_EXPR:
2555 case IMAGPART_EXPR:
2556 case VIEW_CONVERT_EXPR:
2558 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2559 stmts);
2560 if (!genop0)
2561 return NULL_TREE;
2562 return fold_build1 (currop->opcode, currop->type, genop0);
2565 case WITH_SIZE_EXPR:
2567 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2568 stmts);
2569 if (!genop0)
2570 return NULL_TREE;
2571 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2572 if (!genop1)
2573 return NULL_TREE;
2574 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2577 case BIT_FIELD_REF:
2579 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2580 stmts);
2581 if (!genop0)
2582 return NULL_TREE;
2583 tree op1 = currop->op0;
2584 tree op2 = currop->op1;
2585 tree t = build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2586 REF_REVERSE_STORAGE_ORDER (t) = currop->reverse;
2587 return fold (t);
2590 /* For array ref vn_reference_op's, operand 1 of the array ref
2591 is op0 of the reference op and operand 3 of the array ref is
2592 op1. */
2593 case ARRAY_RANGE_REF:
2594 case ARRAY_REF:
2596 tree genop0;
2597 tree genop1 = currop->op0;
2598 tree genop2 = currop->op1;
2599 tree genop3 = currop->op2;
2600 genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2601 stmts);
2602 if (!genop0)
2603 return NULL_TREE;
2604 genop1 = find_or_generate_expression (block, genop1, stmts);
2605 if (!genop1)
2606 return NULL_TREE;
2607 if (genop2)
2609 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2610 /* Drop zero minimum index if redundant. */
2611 if (integer_zerop (genop2)
2612 && (!domain_type
2613 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2614 genop2 = NULL_TREE;
2615 else
2617 genop2 = find_or_generate_expression (block, genop2, stmts);
2618 if (!genop2)
2619 return NULL_TREE;
2622 if (genop3)
2624 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2625 /* We can't always put a size in units of the element alignment
2626 here as the element alignment may be not visible. See
2627 PR43783. Simply drop the element size for constant
2628 sizes. */
2629 if (TREE_CODE (genop3) == INTEGER_CST
2630 && TREE_CODE (TYPE_SIZE_UNIT (elmt_type)) == INTEGER_CST
2631 && wi::eq_p (wi::to_offset (TYPE_SIZE_UNIT (elmt_type)),
2632 (wi::to_offset (genop3)
2633 * vn_ref_op_align_unit (currop))))
2634 genop3 = NULL_TREE;
2635 else
2637 genop3 = find_or_generate_expression (block, genop3, stmts);
2638 if (!genop3)
2639 return NULL_TREE;
2642 return build4 (currop->opcode, currop->type, genop0, genop1,
2643 genop2, genop3);
2645 case COMPONENT_REF:
2647 tree op0;
2648 tree op1;
2649 tree genop2 = currop->op1;
2650 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2651 if (!op0)
2652 return NULL_TREE;
2653 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2654 op1 = currop->op0;
2655 if (genop2)
2657 genop2 = find_or_generate_expression (block, genop2, stmts);
2658 if (!genop2)
2659 return NULL_TREE;
2661 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2664 case SSA_NAME:
2666 genop = find_or_generate_expression (block, currop->op0, stmts);
2667 return genop;
2669 case STRING_CST:
2670 case INTEGER_CST:
2671 case COMPLEX_CST:
2672 case VECTOR_CST:
2673 case REAL_CST:
2674 case CONSTRUCTOR:
2675 case VAR_DECL:
2676 case PARM_DECL:
2677 case CONST_DECL:
2678 case RESULT_DECL:
2679 case FUNCTION_DECL:
2680 return currop->op0;
2682 default:
2683 gcc_unreachable ();
2687 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2688 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2689 trying to rename aggregates into ssa form directly, which is a no no.
2691 Thus, this routine doesn't create temporaries, it just builds a
2692 single access expression for the array, calling
2693 find_or_generate_expression to build the innermost pieces.
2695 This function is a subroutine of create_expression_by_pieces, and
2696 should not be called on it's own unless you really know what you
2697 are doing. */
2699 static tree
2700 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2701 gimple_seq *stmts)
2703 unsigned int op = 0;
2704 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2707 /* Find a simple leader for an expression, or generate one using
2708 create_expression_by_pieces from a NARY expression for the value.
2709 BLOCK is the basic_block we are looking for leaders in.
2710 OP is the tree expression to find a leader for or generate.
2711 Returns the leader or NULL_TREE on failure. */
2713 static tree
2714 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2716 pre_expr expr = get_or_alloc_expr_for (op);
2717 unsigned int lookfor = get_expr_value_id (expr);
2718 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2719 if (leader)
2721 if (leader->kind == NAME)
2722 return PRE_EXPR_NAME (leader);
2723 else if (leader->kind == CONSTANT)
2724 return PRE_EXPR_CONSTANT (leader);
2726 /* Defer. */
2727 return NULL_TREE;
2730 /* It must be a complex expression, so generate it recursively. Note
2731 that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2732 where the insert algorithm fails to insert a required expression. */
2733 bitmap exprset = value_expressions[lookfor];
2734 bitmap_iterator bi;
2735 unsigned int i;
2736 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2738 pre_expr temp = expression_for_id (i);
2739 /* We cannot insert random REFERENCE expressions at arbitrary
2740 places. We can insert NARYs which eventually re-materializes
2741 its operand values. */
2742 if (temp->kind == NARY)
2743 return create_expression_by_pieces (block, temp, stmts,
2744 get_expr_type (expr));
2747 /* Defer. */
2748 return NULL_TREE;
2751 #define NECESSARY GF_PLF_1
2753 /* Create an expression in pieces, so that we can handle very complex
2754 expressions that may be ANTIC, but not necessary GIMPLE.
2755 BLOCK is the basic block the expression will be inserted into,
2756 EXPR is the expression to insert (in value form)
2757 STMTS is a statement list to append the necessary insertions into.
2759 This function will die if we hit some value that shouldn't be
2760 ANTIC but is (IE there is no leader for it, or its components).
2761 The function returns NULL_TREE in case a different antic expression
2762 has to be inserted first.
2763 This function may also generate expressions that are themselves
2764 partially or fully redundant. Those that are will be either made
2765 fully redundant during the next iteration of insert (for partially
2766 redundant ones), or eliminated by eliminate (for fully redundant
2767 ones). */
2769 static tree
2770 create_expression_by_pieces (basic_block block, pre_expr expr,
2771 gimple_seq *stmts, tree type)
2773 tree name;
2774 tree folded;
2775 gimple_seq forced_stmts = NULL;
2776 unsigned int value_id;
2777 gimple_stmt_iterator gsi;
2778 tree exprtype = type ? type : get_expr_type (expr);
2779 pre_expr nameexpr;
2780 gassign *newstmt;
2782 switch (expr->kind)
2784 /* We may hit the NAME/CONSTANT case if we have to convert types
2785 that value numbering saw through. */
2786 case NAME:
2787 folded = PRE_EXPR_NAME (expr);
2788 if (useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2789 return folded;
2790 break;
2791 case CONSTANT:
2793 folded = PRE_EXPR_CONSTANT (expr);
2794 tree tem = fold_convert (exprtype, folded);
2795 if (is_gimple_min_invariant (tem))
2796 return tem;
2797 break;
2799 case REFERENCE:
2800 if (PRE_EXPR_REFERENCE (expr)->operands[0].opcode == CALL_EXPR)
2802 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2803 unsigned int operand = 1;
2804 vn_reference_op_t currop = &ref->operands[0];
2805 tree sc = NULL_TREE;
2806 tree fn;
2807 if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2808 fn = currop->op0;
2809 else
2810 fn = find_or_generate_expression (block, currop->op0, stmts);
2811 if (!fn)
2812 return NULL_TREE;
2813 if (currop->op1)
2815 sc = find_or_generate_expression (block, currop->op1, stmts);
2816 if (!sc)
2817 return NULL_TREE;
2819 auto_vec<tree> args (ref->operands.length () - 1);
2820 while (operand < ref->operands.length ())
2822 tree arg = create_component_ref_by_pieces_1 (block, ref,
2823 &operand, stmts);
2824 if (!arg)
2825 return NULL_TREE;
2826 args.quick_push (arg);
2828 gcall *call
2829 = gimple_build_call_vec ((TREE_CODE (fn) == FUNCTION_DECL
2830 ? build_fold_addr_expr (fn) : fn), args);
2831 gimple_call_set_with_bounds (call, currop->with_bounds);
2832 if (sc)
2833 gimple_call_set_chain (call, sc);
2834 tree forcedname = make_ssa_name (currop->type);
2835 gimple_call_set_lhs (call, forcedname);
2836 gimple_set_vuse (call, BB_LIVE_VOP_ON_EXIT (block));
2837 gimple_seq_add_stmt_without_update (&forced_stmts, call);
2838 folded = forcedname;
2840 else
2842 folded = create_component_ref_by_pieces (block,
2843 PRE_EXPR_REFERENCE (expr),
2844 stmts);
2845 if (!folded)
2846 return NULL_TREE;
2847 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2848 newstmt = gimple_build_assign (name, folded);
2849 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2850 gimple_set_vuse (newstmt, BB_LIVE_VOP_ON_EXIT (block));
2851 folded = name;
2853 break;
2854 case NARY:
2856 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2857 tree *genop = XALLOCAVEC (tree, nary->length);
2858 unsigned i;
2859 for (i = 0; i < nary->length; ++i)
2861 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2862 if (!genop[i])
2863 return NULL_TREE;
2864 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2865 may have conversions stripped. */
2866 if (nary->opcode == POINTER_PLUS_EXPR)
2868 if (i == 0)
2869 genop[i] = gimple_convert (&forced_stmts,
2870 nary->type, genop[i]);
2871 else if (i == 1)
2872 genop[i] = gimple_convert (&forced_stmts,
2873 sizetype, genop[i]);
2875 else
2876 genop[i] = gimple_convert (&forced_stmts,
2877 TREE_TYPE (nary->op[i]), genop[i]);
2879 if (nary->opcode == CONSTRUCTOR)
2881 vec<constructor_elt, va_gc> *elts = NULL;
2882 for (i = 0; i < nary->length; ++i)
2883 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2884 folded = build_constructor (nary->type, elts);
2885 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2886 newstmt = gimple_build_assign (name, folded);
2887 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2888 folded = name;
2890 else
2892 switch (nary->length)
2894 case 1:
2895 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2896 genop[0]);
2897 break;
2898 case 2:
2899 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2900 genop[0], genop[1]);
2901 break;
2902 case 3:
2903 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2904 genop[0], genop[1], genop[2]);
2905 break;
2906 default:
2907 gcc_unreachable ();
2911 break;
2912 default:
2913 gcc_unreachable ();
2916 folded = gimple_convert (&forced_stmts, exprtype, folded);
2918 /* If there is nothing to insert, return the simplified result. */
2919 if (gimple_seq_empty_p (forced_stmts))
2920 return folded;
2921 /* If we simplified to a constant return it and discard eventually
2922 built stmts. */
2923 if (is_gimple_min_invariant (folded))
2925 gimple_seq_discard (forced_stmts);
2926 return folded;
2928 /* Likewise if we simplified to sth not queued for insertion. */
2929 bool found = false;
2930 gsi = gsi_last (forced_stmts);
2931 for (; !gsi_end_p (gsi); gsi_prev (&gsi))
2933 gimple *stmt = gsi_stmt (gsi);
2934 tree forcedname = gimple_get_lhs (stmt);
2935 if (forcedname == folded)
2937 found = true;
2938 break;
2941 if (! found)
2943 gimple_seq_discard (forced_stmts);
2944 return folded;
2946 gcc_assert (TREE_CODE (folded) == SSA_NAME);
2948 /* If we have any intermediate expressions to the value sets, add them
2949 to the value sets and chain them in the instruction stream. */
2950 if (forced_stmts)
2952 gsi = gsi_start (forced_stmts);
2953 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2955 gimple *stmt = gsi_stmt (gsi);
2956 tree forcedname = gimple_get_lhs (stmt);
2957 pre_expr nameexpr;
2959 if (forcedname != folded)
2961 VN_INFO_GET (forcedname)->valnum = forcedname;
2962 VN_INFO (forcedname)->value_id = get_next_value_id ();
2963 nameexpr = get_or_alloc_expr_for_name (forcedname);
2964 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2965 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2966 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2969 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2970 gimple_set_plf (stmt, NECESSARY, false);
2972 gimple_seq_add_seq (stmts, forced_stmts);
2975 name = folded;
2977 /* Fold the last statement. */
2978 gsi = gsi_last (*stmts);
2979 if (fold_stmt_inplace (&gsi))
2980 update_stmt (gsi_stmt (gsi));
2982 /* Add a value number to the temporary.
2983 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2984 we are creating the expression by pieces, and this particular piece of
2985 the expression may have been represented. There is no harm in replacing
2986 here. */
2987 value_id = get_expr_value_id (expr);
2988 VN_INFO_GET (name)->value_id = value_id;
2989 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2990 if (VN_INFO (name)->valnum == NULL_TREE)
2991 VN_INFO (name)->valnum = name;
2992 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2993 nameexpr = get_or_alloc_expr_for_name (name);
2994 add_to_value (value_id, nameexpr);
2995 if (NEW_SETS (block))
2996 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2997 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2999 pre_stats.insertions++;
3000 if (dump_file && (dump_flags & TDF_DETAILS))
3002 fprintf (dump_file, "Inserted ");
3003 print_gimple_stmt (dump_file, gsi_stmt (gsi_last (*stmts)), 0);
3004 fprintf (dump_file, " in predecessor %d (%04d)\n",
3005 block->index, value_id);
3008 return name;
3012 /* Insert the to-be-made-available values of expression EXPRNUM for each
3013 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
3014 merge the result with a phi node, given the same value number as
3015 NODE. Return true if we have inserted new stuff. */
3017 static bool
3018 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
3019 vec<pre_expr> avail)
3021 pre_expr expr = expression_for_id (exprnum);
3022 pre_expr newphi;
3023 unsigned int val = get_expr_value_id (expr);
3024 edge pred;
3025 bool insertions = false;
3026 bool nophi = false;
3027 basic_block bprime;
3028 pre_expr eprime;
3029 edge_iterator ei;
3030 tree type = get_expr_type (expr);
3031 tree temp;
3032 gphi *phi;
3034 /* Make sure we aren't creating an induction variable. */
3035 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
3037 bool firstinsideloop = false;
3038 bool secondinsideloop = false;
3039 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
3040 EDGE_PRED (block, 0)->src);
3041 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
3042 EDGE_PRED (block, 1)->src);
3043 /* Induction variables only have one edge inside the loop. */
3044 if ((firstinsideloop ^ secondinsideloop)
3045 && expr->kind != REFERENCE)
3047 if (dump_file && (dump_flags & TDF_DETAILS))
3048 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
3049 nophi = true;
3053 /* Make the necessary insertions. */
3054 FOR_EACH_EDGE (pred, ei, block->preds)
3056 gimple_seq stmts = NULL;
3057 tree builtexpr;
3058 bprime = pred->src;
3059 eprime = avail[pred->dest_idx];
3060 builtexpr = create_expression_by_pieces (bprime, eprime,
3061 &stmts, type);
3062 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
3063 if (!gimple_seq_empty_p (stmts))
3065 gsi_insert_seq_on_edge (pred, stmts);
3066 insertions = true;
3068 if (!builtexpr)
3070 /* We cannot insert a PHI node if we failed to insert
3071 on one edge. */
3072 nophi = true;
3073 continue;
3075 if (is_gimple_min_invariant (builtexpr))
3076 avail[pred->dest_idx] = get_or_alloc_expr_for_constant (builtexpr);
3077 else
3078 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
3080 /* If we didn't want a phi node, and we made insertions, we still have
3081 inserted new stuff, and thus return true. If we didn't want a phi node,
3082 and didn't make insertions, we haven't added anything new, so return
3083 false. */
3084 if (nophi && insertions)
3085 return true;
3086 else if (nophi && !insertions)
3087 return false;
3089 /* Now build a phi for the new variable. */
3090 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3091 phi = create_phi_node (temp, block);
3093 gimple_set_plf (phi, NECESSARY, false);
3094 VN_INFO_GET (temp)->value_id = val;
3095 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3096 if (VN_INFO (temp)->valnum == NULL_TREE)
3097 VN_INFO (temp)->valnum = temp;
3098 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3099 FOR_EACH_EDGE (pred, ei, block->preds)
3101 pre_expr ae = avail[pred->dest_idx];
3102 gcc_assert (get_expr_type (ae) == type
3103 || useless_type_conversion_p (type, get_expr_type (ae)));
3104 if (ae->kind == CONSTANT)
3105 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3106 pred, UNKNOWN_LOCATION);
3107 else
3108 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3111 newphi = get_or_alloc_expr_for_name (temp);
3112 add_to_value (val, newphi);
3114 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3115 this insertion, since we test for the existence of this value in PHI_GEN
3116 before proceeding with the partial redundancy checks in insert_aux.
3118 The value may exist in AVAIL_OUT, in particular, it could be represented
3119 by the expression we are trying to eliminate, in which case we want the
3120 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3121 inserted there.
3123 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3124 this block, because if it did, it would have existed in our dominator's
3125 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3128 bitmap_insert_into_set (PHI_GEN (block), newphi);
3129 bitmap_value_replace_in_set (AVAIL_OUT (block),
3130 newphi);
3131 bitmap_insert_into_set (NEW_SETS (block),
3132 newphi);
3134 /* If we insert a PHI node for a conversion of another PHI node
3135 in the same basic-block try to preserve range information.
3136 This is important so that followup loop passes receive optimal
3137 number of iteration analysis results. See PR61743. */
3138 if (expr->kind == NARY
3139 && CONVERT_EXPR_CODE_P (expr->u.nary->opcode)
3140 && TREE_CODE (expr->u.nary->op[0]) == SSA_NAME
3141 && gimple_bb (SSA_NAME_DEF_STMT (expr->u.nary->op[0])) == block
3142 && INTEGRAL_TYPE_P (type)
3143 && INTEGRAL_TYPE_P (TREE_TYPE (expr->u.nary->op[0]))
3144 && (TYPE_PRECISION (type)
3145 >= TYPE_PRECISION (TREE_TYPE (expr->u.nary->op[0])))
3146 && SSA_NAME_RANGE_INFO (expr->u.nary->op[0]))
3148 wide_int min, max;
3149 if (get_range_info (expr->u.nary->op[0], &min, &max) == VR_RANGE
3150 && !wi::neg_p (min, SIGNED)
3151 && !wi::neg_p (max, SIGNED))
3152 /* Just handle extension and sign-changes of all-positive ranges. */
3153 set_range_info (temp,
3154 SSA_NAME_RANGE_TYPE (expr->u.nary->op[0]),
3155 wide_int_storage::from (min, TYPE_PRECISION (type),
3156 TYPE_SIGN (type)),
3157 wide_int_storage::from (max, TYPE_PRECISION (type),
3158 TYPE_SIGN (type)));
3161 if (dump_file && (dump_flags & TDF_DETAILS))
3163 fprintf (dump_file, "Created phi ");
3164 print_gimple_stmt (dump_file, phi, 0);
3165 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3167 pre_stats.phis++;
3168 return true;
3173 /* Perform insertion of partially redundant or hoistable values.
3174 For BLOCK, do the following:
3175 1. Propagate the NEW_SETS of the dominator into the current block.
3176 If the block has multiple predecessors,
3177 2a. Iterate over the ANTIC expressions for the block to see if
3178 any of them are partially redundant.
3179 2b. If so, insert them into the necessary predecessors to make
3180 the expression fully redundant.
3181 2c. Insert a new PHI merging the values of the predecessors.
3182 2d. Insert the new PHI, and the new expressions, into the
3183 NEW_SETS set.
3184 If the block has multiple successors,
3185 3a. Iterate over the ANTIC values for the block to see if
3186 any of them are good candidates for hoisting.
3187 3b. If so, insert expressions computing the values in BLOCK,
3188 and add the new expressions into the NEW_SETS set.
3189 4. Recursively call ourselves on the dominator children of BLOCK.
3191 Steps 1, 2a, and 4 are done by insert_aux. 2b, 2c and 2d are done by
3192 do_pre_regular_insertion and do_partial_insertion. 3a and 3b are
3193 done in do_hoist_insertion.
3196 static bool
3197 do_pre_regular_insertion (basic_block block, basic_block dom)
3199 bool new_stuff = false;
3200 vec<pre_expr> exprs;
3201 pre_expr expr;
3202 auto_vec<pre_expr> avail;
3203 int i;
3205 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3206 avail.safe_grow (EDGE_COUNT (block->preds));
3208 FOR_EACH_VEC_ELT (exprs, i, expr)
3210 if (expr->kind == NARY
3211 || expr->kind == REFERENCE)
3213 unsigned int val;
3214 bool by_some = false;
3215 bool cant_insert = false;
3216 bool all_same = true;
3217 pre_expr first_s = NULL;
3218 edge pred;
3219 basic_block bprime;
3220 pre_expr eprime = NULL;
3221 edge_iterator ei;
3222 pre_expr edoubleprime = NULL;
3223 bool do_insertion = false;
3225 val = get_expr_value_id (expr);
3226 if (bitmap_set_contains_value (PHI_GEN (block), val))
3227 continue;
3228 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3230 if (dump_file && (dump_flags & TDF_DETAILS))
3232 fprintf (dump_file, "Found fully redundant value: ");
3233 print_pre_expr (dump_file, expr);
3234 fprintf (dump_file, "\n");
3236 continue;
3239 FOR_EACH_EDGE (pred, ei, block->preds)
3241 unsigned int vprime;
3243 /* We should never run insertion for the exit block
3244 and so not come across fake pred edges. */
3245 gcc_assert (!(pred->flags & EDGE_FAKE));
3246 bprime = pred->src;
3247 /* We are looking at ANTIC_OUT of bprime. */
3248 eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3249 bprime, block);
3251 /* eprime will generally only be NULL if the
3252 value of the expression, translated
3253 through the PHI for this predecessor, is
3254 undefined. If that is the case, we can't
3255 make the expression fully redundant,
3256 because its value is undefined along a
3257 predecessor path. We can thus break out
3258 early because it doesn't matter what the
3259 rest of the results are. */
3260 if (eprime == NULL)
3262 avail[pred->dest_idx] = NULL;
3263 cant_insert = true;
3264 break;
3267 vprime = get_expr_value_id (eprime);
3268 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3269 vprime);
3270 if (edoubleprime == NULL)
3272 avail[pred->dest_idx] = eprime;
3273 all_same = false;
3275 else
3277 avail[pred->dest_idx] = edoubleprime;
3278 by_some = true;
3279 /* We want to perform insertions to remove a redundancy on
3280 a path in the CFG we want to optimize for speed. */
3281 if (optimize_edge_for_speed_p (pred))
3282 do_insertion = true;
3283 if (first_s == NULL)
3284 first_s = edoubleprime;
3285 else if (!pre_expr_d::equal (first_s, edoubleprime))
3286 all_same = false;
3289 /* If we can insert it, it's not the same value
3290 already existing along every predecessor, and
3291 it's defined by some predecessor, it is
3292 partially redundant. */
3293 if (!cant_insert && !all_same && by_some)
3295 if (!do_insertion)
3297 if (dump_file && (dump_flags & TDF_DETAILS))
3299 fprintf (dump_file, "Skipping partial redundancy for "
3300 "expression ");
3301 print_pre_expr (dump_file, expr);
3302 fprintf (dump_file, " (%04d), no redundancy on to be "
3303 "optimized for speed edge\n", val);
3306 else if (dbg_cnt (treepre_insert))
3308 if (dump_file && (dump_flags & TDF_DETAILS))
3310 fprintf (dump_file, "Found partial redundancy for "
3311 "expression ");
3312 print_pre_expr (dump_file, expr);
3313 fprintf (dump_file, " (%04d)\n",
3314 get_expr_value_id (expr));
3316 if (insert_into_preds_of_block (block,
3317 get_expression_id (expr),
3318 avail))
3319 new_stuff = true;
3322 /* If all edges produce the same value and that value is
3323 an invariant, then the PHI has the same value on all
3324 edges. Note this. */
3325 else if (!cant_insert && all_same)
3327 gcc_assert (edoubleprime->kind == CONSTANT
3328 || edoubleprime->kind == NAME);
3330 tree temp = make_temp_ssa_name (get_expr_type (expr),
3331 NULL, "pretmp");
3332 gassign *assign
3333 = gimple_build_assign (temp,
3334 edoubleprime->kind == CONSTANT ?
3335 PRE_EXPR_CONSTANT (edoubleprime) :
3336 PRE_EXPR_NAME (edoubleprime));
3337 gimple_stmt_iterator gsi = gsi_after_labels (block);
3338 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3340 gimple_set_plf (assign, NECESSARY, false);
3341 VN_INFO_GET (temp)->value_id = val;
3342 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3343 if (VN_INFO (temp)->valnum == NULL_TREE)
3344 VN_INFO (temp)->valnum = temp;
3345 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3346 pre_expr newe = get_or_alloc_expr_for_name (temp);
3347 add_to_value (val, newe);
3348 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3349 bitmap_insert_into_set (NEW_SETS (block), newe);
3354 exprs.release ();
3355 return new_stuff;
3359 /* Perform insertion for partially anticipatable expressions. There
3360 is only one case we will perform insertion for these. This case is
3361 if the expression is partially anticipatable, and fully available.
3362 In this case, we know that putting it earlier will enable us to
3363 remove the later computation. */
3365 static bool
3366 do_pre_partial_partial_insertion (basic_block block, basic_block dom)
3368 bool new_stuff = false;
3369 vec<pre_expr> exprs;
3370 pre_expr expr;
3371 auto_vec<pre_expr> avail;
3372 int i;
3374 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3375 avail.safe_grow (EDGE_COUNT (block->preds));
3377 FOR_EACH_VEC_ELT (exprs, i, expr)
3379 if (expr->kind == NARY
3380 || expr->kind == REFERENCE)
3382 unsigned int val;
3383 bool by_all = true;
3384 bool cant_insert = false;
3385 edge pred;
3386 basic_block bprime;
3387 pre_expr eprime = NULL;
3388 edge_iterator ei;
3390 val = get_expr_value_id (expr);
3391 if (bitmap_set_contains_value (PHI_GEN (block), val))
3392 continue;
3393 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3394 continue;
3396 FOR_EACH_EDGE (pred, ei, block->preds)
3398 unsigned int vprime;
3399 pre_expr edoubleprime;
3401 /* We should never run insertion for the exit block
3402 and so not come across fake pred edges. */
3403 gcc_assert (!(pred->flags & EDGE_FAKE));
3404 bprime = pred->src;
3405 eprime = phi_translate (expr, ANTIC_IN (block),
3406 PA_IN (block),
3407 bprime, block);
3409 /* eprime will generally only be NULL if the
3410 value of the expression, translated
3411 through the PHI for this predecessor, is
3412 undefined. If that is the case, we can't
3413 make the expression fully redundant,
3414 because its value is undefined along a
3415 predecessor path. We can thus break out
3416 early because it doesn't matter what the
3417 rest of the results are. */
3418 if (eprime == NULL)
3420 avail[pred->dest_idx] = NULL;
3421 cant_insert = true;
3422 break;
3425 vprime = get_expr_value_id (eprime);
3426 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3427 avail[pred->dest_idx] = edoubleprime;
3428 if (edoubleprime == NULL)
3430 by_all = false;
3431 break;
3435 /* If we can insert it, it's not the same value
3436 already existing along every predecessor, and
3437 it's defined by some predecessor, it is
3438 partially redundant. */
3439 if (!cant_insert && by_all)
3441 edge succ;
3442 bool do_insertion = false;
3444 /* Insert only if we can remove a later expression on a path
3445 that we want to optimize for speed.
3446 The phi node that we will be inserting in BLOCK is not free,
3447 and inserting it for the sake of !optimize_for_speed successor
3448 may cause regressions on the speed path. */
3449 FOR_EACH_EDGE (succ, ei, block->succs)
3451 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3452 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3454 if (optimize_edge_for_speed_p (succ))
3455 do_insertion = true;
3459 if (!do_insertion)
3461 if (dump_file && (dump_flags & TDF_DETAILS))
3463 fprintf (dump_file, "Skipping partial partial redundancy "
3464 "for expression ");
3465 print_pre_expr (dump_file, expr);
3466 fprintf (dump_file, " (%04d), not (partially) anticipated "
3467 "on any to be optimized for speed edges\n", val);
3470 else if (dbg_cnt (treepre_insert))
3472 pre_stats.pa_insert++;
3473 if (dump_file && (dump_flags & TDF_DETAILS))
3475 fprintf (dump_file, "Found partial partial redundancy "
3476 "for expression ");
3477 print_pre_expr (dump_file, expr);
3478 fprintf (dump_file, " (%04d)\n",
3479 get_expr_value_id (expr));
3481 if (insert_into_preds_of_block (block,
3482 get_expression_id (expr),
3483 avail))
3484 new_stuff = true;
3490 exprs.release ();
3491 return new_stuff;
3494 /* Insert expressions in BLOCK to compute hoistable values up.
3495 Return TRUE if something was inserted, otherwise return FALSE.
3496 The caller has to make sure that BLOCK has at least two successors. */
3498 static bool
3499 do_hoist_insertion (basic_block block)
3501 edge e;
3502 edge_iterator ei;
3503 bool new_stuff = false;
3504 unsigned i;
3505 gimple_stmt_iterator last;
3507 /* At least two successors, or else... */
3508 gcc_assert (EDGE_COUNT (block->succs) >= 2);
3510 /* Check that all successors of BLOCK are dominated by block.
3511 We could use dominated_by_p() for this, but actually there is a much
3512 quicker check: any successor that is dominated by BLOCK can't have
3513 more than one predecessor edge. */
3514 FOR_EACH_EDGE (e, ei, block->succs)
3515 if (! single_pred_p (e->dest))
3516 return false;
3518 /* Determine the insertion point. If we cannot safely insert before
3519 the last stmt if we'd have to, bail out. */
3520 last = gsi_last_bb (block);
3521 if (!gsi_end_p (last)
3522 && !is_ctrl_stmt (gsi_stmt (last))
3523 && stmt_ends_bb_p (gsi_stmt (last)))
3524 return false;
3526 /* Compute the set of hoistable expressions from ANTIC_IN. First compute
3527 hoistable values. */
3528 bitmap_set hoistable_set;
3530 /* A hoistable value must be in ANTIC_IN(block)
3531 but not in AVAIL_OUT(BLOCK). */
3532 bitmap_initialize (&hoistable_set.values, &grand_bitmap_obstack);
3533 bitmap_and_compl (&hoistable_set.values,
3534 &ANTIC_IN (block)->values, &AVAIL_OUT (block)->values);
3536 /* Short-cut for a common case: hoistable_set is empty. */
3537 if (bitmap_empty_p (&hoistable_set.values))
3538 return false;
3540 /* Compute which of the hoistable values is in AVAIL_OUT of
3541 at least one of the successors of BLOCK. */
3542 bitmap_head availout_in_some;
3543 bitmap_initialize (&availout_in_some, &grand_bitmap_obstack);
3544 FOR_EACH_EDGE (e, ei, block->succs)
3545 /* Do not consider expressions solely because their availability
3546 on loop exits. They'd be ANTIC-IN throughout the whole loop
3547 and thus effectively hoisted across loops by combination of
3548 PRE and hoisting. */
3549 if (! loop_exit_edge_p (block->loop_father, e))
3550 bitmap_ior_and_into (&availout_in_some, &hoistable_set.values,
3551 &AVAIL_OUT (e->dest)->values);
3552 bitmap_clear (&hoistable_set.values);
3554 /* Short-cut for a common case: availout_in_some is empty. */
3555 if (bitmap_empty_p (&availout_in_some))
3556 return false;
3558 /* Hack hoitable_set in-place so we can use sorted_array_from_bitmap_set. */
3559 hoistable_set.values = availout_in_some;
3560 hoistable_set.expressions = ANTIC_IN (block)->expressions;
3562 /* Now finally construct the topological-ordered expression set. */
3563 vec<pre_expr> exprs = sorted_array_from_bitmap_set (&hoistable_set);
3565 bitmap_clear (&hoistable_set.values);
3567 /* If there are candidate values for hoisting, insert expressions
3568 strategically to make the hoistable expressions fully redundant. */
3569 pre_expr expr;
3570 FOR_EACH_VEC_ELT (exprs, i, expr)
3572 /* While we try to sort expressions topologically above the
3573 sorting doesn't work out perfectly. Catch expressions we
3574 already inserted. */
3575 unsigned int value_id = get_expr_value_id (expr);
3576 if (bitmap_set_contains_value (AVAIL_OUT (block), value_id))
3578 if (dump_file && (dump_flags & TDF_DETAILS))
3580 fprintf (dump_file,
3581 "Already inserted expression for ");
3582 print_pre_expr (dump_file, expr);
3583 fprintf (dump_file, " (%04d)\n", value_id);
3585 continue;
3588 /* OK, we should hoist this value. Perform the transformation. */
3589 pre_stats.hoist_insert++;
3590 if (dump_file && (dump_flags & TDF_DETAILS))
3592 fprintf (dump_file,
3593 "Inserting expression in block %d for code hoisting: ",
3594 block->index);
3595 print_pre_expr (dump_file, expr);
3596 fprintf (dump_file, " (%04d)\n", value_id);
3599 gimple_seq stmts = NULL;
3600 tree res = create_expression_by_pieces (block, expr, &stmts,
3601 get_expr_type (expr));
3603 /* Do not return true if expression creation ultimately
3604 did not insert any statements. */
3605 if (gimple_seq_empty_p (stmts))
3606 res = NULL_TREE;
3607 else
3609 if (gsi_end_p (last) || is_ctrl_stmt (gsi_stmt (last)))
3610 gsi_insert_seq_before (&last, stmts, GSI_SAME_STMT);
3611 else
3612 gsi_insert_seq_after (&last, stmts, GSI_NEW_STMT);
3615 /* Make sure to not return true if expression creation ultimately
3616 failed but also make sure to insert any stmts produced as they
3617 are tracked in inserted_exprs. */
3618 if (! res)
3619 continue;
3621 new_stuff = true;
3624 exprs.release ();
3626 return new_stuff;
3629 /* Do a dominator walk on the control flow graph, and insert computations
3630 of values as necessary for PRE and hoisting. */
3632 static bool
3633 insert_aux (basic_block block, bool do_pre, bool do_hoist)
3635 basic_block son;
3636 bool new_stuff = false;
3638 if (block)
3640 basic_block dom;
3641 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3642 if (dom)
3644 unsigned i;
3645 bitmap_iterator bi;
3646 bitmap_set_t newset;
3648 /* First, update the AVAIL_OUT set with anything we may have
3649 inserted higher up in the dominator tree. */
3650 newset = NEW_SETS (dom);
3651 if (newset)
3653 /* Note that we need to value_replace both NEW_SETS, and
3654 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3655 represented by some non-simple expression here that we want
3656 to replace it with. */
3657 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3659 pre_expr expr = expression_for_id (i);
3660 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3661 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3665 /* Insert expressions for partial redundancies. */
3666 if (do_pre && !single_pred_p (block))
3668 new_stuff |= do_pre_regular_insertion (block, dom);
3669 if (do_partial_partial)
3670 new_stuff |= do_pre_partial_partial_insertion (block, dom);
3673 /* Insert expressions for hoisting. */
3674 if (do_hoist && EDGE_COUNT (block->succs) >= 2)
3675 new_stuff |= do_hoist_insertion (block);
3678 for (son = first_dom_son (CDI_DOMINATORS, block);
3679 son;
3680 son = next_dom_son (CDI_DOMINATORS, son))
3682 new_stuff |= insert_aux (son, do_pre, do_hoist);
3685 return new_stuff;
3688 /* Perform insertion of partially redundant and hoistable values. */
3690 static void
3691 insert (void)
3693 bool new_stuff = true;
3694 basic_block bb;
3695 int num_iterations = 0;
3697 FOR_ALL_BB_FN (bb, cfun)
3698 NEW_SETS (bb) = bitmap_set_new ();
3700 while (new_stuff)
3702 num_iterations++;
3703 if (dump_file && dump_flags & TDF_DETAILS)
3704 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3705 new_stuff = insert_aux (ENTRY_BLOCK_PTR_FOR_FN (cfun), flag_tree_pre,
3706 flag_code_hoisting);
3708 /* Clear the NEW sets before the next iteration. We have already
3709 fully propagated its contents. */
3710 if (new_stuff)
3711 FOR_ALL_BB_FN (bb, cfun)
3712 bitmap_set_free (NEW_SETS (bb));
3714 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3718 /* Compute the AVAIL set for all basic blocks.
3720 This function performs value numbering of the statements in each basic
3721 block. The AVAIL sets are built from information we glean while doing
3722 this value numbering, since the AVAIL sets contain only one entry per
3723 value.
3725 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3726 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3728 static void
3729 compute_avail (void)
3732 basic_block block, son;
3733 basic_block *worklist;
3734 size_t sp = 0;
3735 unsigned i;
3736 tree name;
3738 /* We pretend that default definitions are defined in the entry block.
3739 This includes function arguments and the static chain decl. */
3740 FOR_EACH_SSA_NAME (i, name, cfun)
3742 pre_expr e;
3743 if (!SSA_NAME_IS_DEFAULT_DEF (name)
3744 || has_zero_uses (name)
3745 || virtual_operand_p (name))
3746 continue;
3748 e = get_or_alloc_expr_for_name (name);
3749 add_to_value (get_expr_value_id (e), e);
3750 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)), e);
3751 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3755 if (dump_file && (dump_flags & TDF_DETAILS))
3757 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3758 "tmp_gen", ENTRY_BLOCK);
3759 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3760 "avail_out", ENTRY_BLOCK);
3763 /* Allocate the worklist. */
3764 worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
3766 /* Seed the algorithm by putting the dominator children of the entry
3767 block on the worklist. */
3768 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
3769 son;
3770 son = next_dom_son (CDI_DOMINATORS, son))
3771 worklist[sp++] = son;
3773 BB_LIVE_VOP_ON_EXIT (ENTRY_BLOCK_PTR_FOR_FN (cfun))
3774 = ssa_default_def (cfun, gimple_vop (cfun));
3776 /* Loop until the worklist is empty. */
3777 while (sp)
3779 gimple *stmt;
3780 basic_block dom;
3782 /* Pick a block from the worklist. */
3783 block = worklist[--sp];
3785 /* Initially, the set of available values in BLOCK is that of
3786 its immediate dominator. */
3787 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3788 if (dom)
3790 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3791 BB_LIVE_VOP_ON_EXIT (block) = BB_LIVE_VOP_ON_EXIT (dom);
3794 /* Generate values for PHI nodes. */
3795 for (gphi_iterator gsi = gsi_start_phis (block); !gsi_end_p (gsi);
3796 gsi_next (&gsi))
3798 tree result = gimple_phi_result (gsi.phi ());
3800 /* We have no need for virtual phis, as they don't represent
3801 actual computations. */
3802 if (virtual_operand_p (result))
3804 BB_LIVE_VOP_ON_EXIT (block) = result;
3805 continue;
3808 pre_expr e = get_or_alloc_expr_for_name (result);
3809 add_to_value (get_expr_value_id (e), e);
3810 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3811 bitmap_insert_into_set (PHI_GEN (block), e);
3814 BB_MAY_NOTRETURN (block) = 0;
3816 /* Now compute value numbers and populate value sets with all
3817 the expressions computed in BLOCK. */
3818 for (gimple_stmt_iterator gsi = gsi_start_bb (block); !gsi_end_p (gsi);
3819 gsi_next (&gsi))
3821 ssa_op_iter iter;
3822 tree op;
3824 stmt = gsi_stmt (gsi);
3826 /* Cache whether the basic-block has any non-visible side-effect
3827 or control flow.
3828 If this isn't a call or it is the last stmt in the
3829 basic-block then the CFG represents things correctly. */
3830 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3832 /* Non-looping const functions always return normally.
3833 Otherwise the call might not return or have side-effects
3834 that forbids hoisting possibly trapping expressions
3835 before it. */
3836 int flags = gimple_call_flags (stmt);
3837 if (!(flags & ECF_CONST)
3838 || (flags & ECF_LOOPING_CONST_OR_PURE))
3839 BB_MAY_NOTRETURN (block) = 1;
3842 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3844 pre_expr e = get_or_alloc_expr_for_name (op);
3846 add_to_value (get_expr_value_id (e), e);
3847 bitmap_insert_into_set (TMP_GEN (block), e);
3848 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3851 if (gimple_vdef (stmt))
3852 BB_LIVE_VOP_ON_EXIT (block) = gimple_vdef (stmt);
3854 if (gimple_has_side_effects (stmt)
3855 || stmt_could_throw_p (stmt)
3856 || is_gimple_debug (stmt))
3857 continue;
3859 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3861 if (ssa_undefined_value_p (op))
3862 continue;
3863 pre_expr e = get_or_alloc_expr_for_name (op);
3864 bitmap_value_insert_into_set (EXP_GEN (block), e);
3867 switch (gimple_code (stmt))
3869 case GIMPLE_RETURN:
3870 continue;
3872 case GIMPLE_CALL:
3874 vn_reference_t ref;
3875 vn_reference_s ref1;
3876 pre_expr result = NULL;
3878 /* We can value number only calls to real functions. */
3879 if (gimple_call_internal_p (stmt))
3880 continue;
3882 vn_reference_lookup_call (as_a <gcall *> (stmt), &ref, &ref1);
3883 if (!ref)
3884 continue;
3886 /* If the value of the call is not invalidated in
3887 this block until it is computed, add the expression
3888 to EXP_GEN. */
3889 if (!gimple_vuse (stmt)
3890 || gimple_code
3891 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3892 || gimple_bb (SSA_NAME_DEF_STMT
3893 (gimple_vuse (stmt))) != block)
3895 result = pre_expr_pool.allocate ();
3896 result->kind = REFERENCE;
3897 result->id = 0;
3898 PRE_EXPR_REFERENCE (result) = ref;
3900 get_or_alloc_expression_id (result);
3901 add_to_value (get_expr_value_id (result), result);
3902 bitmap_value_insert_into_set (EXP_GEN (block), result);
3904 continue;
3907 case GIMPLE_ASSIGN:
3909 pre_expr result = NULL;
3910 switch (vn_get_stmt_kind (stmt))
3912 case VN_NARY:
3914 enum tree_code code = gimple_assign_rhs_code (stmt);
3915 vn_nary_op_t nary;
3917 /* COND_EXPR and VEC_COND_EXPR are awkward in
3918 that they contain an embedded complex expression.
3919 Don't even try to shove those through PRE. */
3920 if (code == COND_EXPR
3921 || code == VEC_COND_EXPR)
3922 continue;
3924 vn_nary_op_lookup_stmt (stmt, &nary);
3925 if (!nary)
3926 continue;
3928 /* If the NARY traps and there was a preceding
3929 point in the block that might not return avoid
3930 adding the nary to EXP_GEN. */
3931 if (BB_MAY_NOTRETURN (block)
3932 && vn_nary_may_trap (nary))
3933 continue;
3935 result = pre_expr_pool.allocate ();
3936 result->kind = NARY;
3937 result->id = 0;
3938 PRE_EXPR_NARY (result) = nary;
3939 break;
3942 case VN_REFERENCE:
3944 tree rhs1 = gimple_assign_rhs1 (stmt);
3945 alias_set_type set = get_alias_set (rhs1);
3946 vec<vn_reference_op_s> operands
3947 = vn_reference_operands_for_lookup (rhs1);
3948 vn_reference_t ref;
3949 vn_reference_lookup_pieces (gimple_vuse (stmt), set,
3950 TREE_TYPE (rhs1),
3951 operands, &ref, VN_WALK);
3952 if (!ref)
3954 operands.release ();
3955 continue;
3958 /* If the value of the reference is not invalidated in
3959 this block until it is computed, add the expression
3960 to EXP_GEN. */
3961 if (gimple_vuse (stmt))
3963 gimple *def_stmt;
3964 bool ok = true;
3965 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3966 while (!gimple_nop_p (def_stmt)
3967 && gimple_code (def_stmt) != GIMPLE_PHI
3968 && gimple_bb (def_stmt) == block)
3970 if (stmt_may_clobber_ref_p
3971 (def_stmt, gimple_assign_rhs1 (stmt)))
3973 ok = false;
3974 break;
3976 def_stmt
3977 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3979 if (!ok)
3981 operands.release ();
3982 continue;
3986 /* If the load was value-numbered to another
3987 load make sure we do not use its expression
3988 for insertion if it wouldn't be a valid
3989 replacement. */
3990 /* At the momemt we have a testcase
3991 for hoist insertion of aligned vs. misaligned
3992 variants in gcc.dg/torture/pr65270-1.c thus
3993 with just alignment to be considered we can
3994 simply replace the expression in the hashtable
3995 with the most conservative one. */
3996 vn_reference_op_t ref1 = &ref->operands.last ();
3997 while (ref1->opcode != TARGET_MEM_REF
3998 && ref1->opcode != MEM_REF
3999 && ref1 != &ref->operands[0])
4000 --ref1;
4001 vn_reference_op_t ref2 = &operands.last ();
4002 while (ref2->opcode != TARGET_MEM_REF
4003 && ref2->opcode != MEM_REF
4004 && ref2 != &operands[0])
4005 --ref2;
4006 if ((ref1->opcode == TARGET_MEM_REF
4007 || ref1->opcode == MEM_REF)
4008 && (TYPE_ALIGN (ref1->type)
4009 > TYPE_ALIGN (ref2->type)))
4010 ref1->type
4011 = build_aligned_type (ref1->type,
4012 TYPE_ALIGN (ref2->type));
4013 /* TBAA behavior is an obvious part so make sure
4014 that the hashtable one covers this as well
4015 by adjusting the ref alias set and its base. */
4016 if (ref->set == set
4017 || alias_set_subset_of (set, ref->set))
4019 else if (alias_set_subset_of (ref->set, set))
4021 ref->set = set;
4022 if (ref1->opcode == MEM_REF)
4023 ref1->op0 = wide_int_to_tree (TREE_TYPE (ref2->op0),
4024 ref1->op0);
4025 else
4026 ref1->op2 = wide_int_to_tree (TREE_TYPE (ref2->op2),
4027 ref1->op2);
4029 else
4031 ref->set = 0;
4032 if (ref1->opcode == MEM_REF)
4033 ref1->op0 = wide_int_to_tree (ptr_type_node,
4034 ref1->op0);
4035 else
4036 ref1->op2 = wide_int_to_tree (ptr_type_node,
4037 ref1->op2);
4039 operands.release ();
4041 result = pre_expr_pool.allocate ();
4042 result->kind = REFERENCE;
4043 result->id = 0;
4044 PRE_EXPR_REFERENCE (result) = ref;
4045 break;
4048 default:
4049 continue;
4052 get_or_alloc_expression_id (result);
4053 add_to_value (get_expr_value_id (result), result);
4054 bitmap_value_insert_into_set (EXP_GEN (block), result);
4055 continue;
4057 default:
4058 break;
4062 if (dump_file && (dump_flags & TDF_DETAILS))
4064 print_bitmap_set (dump_file, EXP_GEN (block),
4065 "exp_gen", block->index);
4066 print_bitmap_set (dump_file, PHI_GEN (block),
4067 "phi_gen", block->index);
4068 print_bitmap_set (dump_file, TMP_GEN (block),
4069 "tmp_gen", block->index);
4070 print_bitmap_set (dump_file, AVAIL_OUT (block),
4071 "avail_out", block->index);
4074 /* Put the dominator children of BLOCK on the worklist of blocks
4075 to compute available sets for. */
4076 for (son = first_dom_son (CDI_DOMINATORS, block);
4077 son;
4078 son = next_dom_son (CDI_DOMINATORS, son))
4079 worklist[sp++] = son;
4082 free (worklist);
4086 /* Local state for the eliminate domwalk. */
4087 static vec<gimple *> el_to_remove;
4088 static vec<gimple *> el_to_fixup;
4089 static unsigned int el_todo;
4090 static vec<tree> el_avail;
4091 static vec<tree> el_avail_stack;
4093 /* Return a leader for OP that is available at the current point of the
4094 eliminate domwalk. */
4096 static tree
4097 eliminate_avail (tree op)
4099 tree valnum = VN_INFO (op)->valnum;
4100 if (TREE_CODE (valnum) == SSA_NAME)
4102 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
4103 return valnum;
4104 if (el_avail.length () > SSA_NAME_VERSION (valnum))
4105 return el_avail[SSA_NAME_VERSION (valnum)];
4107 else if (is_gimple_min_invariant (valnum))
4108 return valnum;
4109 return NULL_TREE;
4112 /* At the current point of the eliminate domwalk make OP available. */
4114 static void
4115 eliminate_push_avail (tree op)
4117 tree valnum = VN_INFO (op)->valnum;
4118 if (TREE_CODE (valnum) == SSA_NAME)
4120 if (el_avail.length () <= SSA_NAME_VERSION (valnum))
4121 el_avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1);
4122 tree pushop = op;
4123 if (el_avail[SSA_NAME_VERSION (valnum)])
4124 pushop = el_avail[SSA_NAME_VERSION (valnum)];
4125 el_avail_stack.safe_push (pushop);
4126 el_avail[SSA_NAME_VERSION (valnum)] = op;
4130 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
4131 the leader for the expression if insertion was successful. */
4133 static tree
4134 eliminate_insert (gimple_stmt_iterator *gsi, tree val)
4136 /* We can insert a sequence with a single assignment only. */
4137 gimple_seq stmts = VN_INFO (val)->expr;
4138 if (!gimple_seq_singleton_p (stmts))
4139 return NULL_TREE;
4140 gassign *stmt = dyn_cast <gassign *> (gimple_seq_first_stmt (stmts));
4141 if (!stmt
4142 || (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt))
4143 && gimple_assign_rhs_code (stmt) != VIEW_CONVERT_EXPR
4144 && gimple_assign_rhs_code (stmt) != BIT_FIELD_REF
4145 && (gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
4146 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)))
4147 return NULL_TREE;
4149 tree op = gimple_assign_rhs1 (stmt);
4150 if (gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR
4151 || gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
4152 op = TREE_OPERAND (op, 0);
4153 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (op) : op;
4154 if (!leader)
4155 return NULL_TREE;
4157 tree res;
4158 stmts = NULL;
4159 if (gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
4160 res = gimple_build (&stmts, BIT_FIELD_REF,
4161 TREE_TYPE (val), leader,
4162 TREE_OPERAND (gimple_assign_rhs1 (stmt), 1),
4163 TREE_OPERAND (gimple_assign_rhs1 (stmt), 2));
4164 else if (gimple_assign_rhs_code (stmt) == BIT_AND_EXPR)
4165 res = gimple_build (&stmts, BIT_AND_EXPR,
4166 TREE_TYPE (val), leader, gimple_assign_rhs2 (stmt));
4167 else
4168 res = gimple_build (&stmts, gimple_assign_rhs_code (stmt),
4169 TREE_TYPE (val), leader);
4170 if (TREE_CODE (res) != SSA_NAME
4171 || SSA_NAME_IS_DEFAULT_DEF (res)
4172 || gimple_bb (SSA_NAME_DEF_STMT (res)))
4174 gimple_seq_discard (stmts);
4176 /* During propagation we have to treat SSA info conservatively
4177 and thus we can end up simplifying the inserted expression
4178 at elimination time to sth not defined in stmts. */
4179 /* But then this is a redundancy we failed to detect. Which means
4180 res now has two values. That doesn't play well with how
4181 we track availability here, so give up. */
4182 if (dump_file && (dump_flags & TDF_DETAILS))
4184 if (TREE_CODE (res) == SSA_NAME)
4185 res = eliminate_avail (res);
4186 if (res)
4188 fprintf (dump_file, "Failed to insert expression for value ");
4189 print_generic_expr (dump_file, val);
4190 fprintf (dump_file, " which is really fully redundant to ");
4191 print_generic_expr (dump_file, res);
4192 fprintf (dump_file, "\n");
4196 return NULL_TREE;
4198 else
4200 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
4201 VN_INFO_GET (res)->valnum = val;
4203 if (TREE_CODE (leader) == SSA_NAME)
4204 gimple_set_plf (SSA_NAME_DEF_STMT (leader), NECESSARY, true);
4207 pre_stats.insertions++;
4208 if (dump_file && (dump_flags & TDF_DETAILS))
4210 fprintf (dump_file, "Inserted ");
4211 print_gimple_stmt (dump_file, SSA_NAME_DEF_STMT (res), 0);
4214 return res;
4217 class eliminate_dom_walker : public dom_walker
4219 public:
4220 eliminate_dom_walker (cdi_direction direction, bool do_pre_)
4221 : dom_walker (direction), do_pre (do_pre_) {}
4223 virtual edge before_dom_children (basic_block);
4224 virtual void after_dom_children (basic_block);
4226 bool do_pre;
4229 /* Perform elimination for the basic-block B during the domwalk. */
4231 edge
4232 eliminate_dom_walker::before_dom_children (basic_block b)
4234 /* Mark new bb. */
4235 el_avail_stack.safe_push (NULL_TREE);
4237 /* Skip unreachable blocks marked unreachable during the SCCVN domwalk. */
4238 edge_iterator ei;
4239 edge e;
4240 FOR_EACH_EDGE (e, ei, b->preds)
4241 if (e->flags & EDGE_EXECUTABLE)
4242 break;
4243 if (! e)
4244 return NULL;
4246 for (gphi_iterator gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
4248 gphi *phi = gsi.phi ();
4249 tree res = PHI_RESULT (phi);
4251 if (virtual_operand_p (res))
4253 gsi_next (&gsi);
4254 continue;
4257 tree sprime = eliminate_avail (res);
4258 if (sprime
4259 && sprime != res)
4261 if (dump_file && (dump_flags & TDF_DETAILS))
4263 fprintf (dump_file, "Replaced redundant PHI node defining ");
4264 print_generic_expr (dump_file, res);
4265 fprintf (dump_file, " with ");
4266 print_generic_expr (dump_file, sprime);
4267 fprintf (dump_file, "\n");
4270 /* If we inserted this PHI node ourself, it's not an elimination. */
4271 if (inserted_exprs
4272 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
4273 pre_stats.phis--;
4274 else
4275 pre_stats.eliminations++;
4277 /* If we will propagate into all uses don't bother to do
4278 anything. */
4279 if (may_propagate_copy (res, sprime))
4281 /* Mark the PHI for removal. */
4282 el_to_remove.safe_push (phi);
4283 gsi_next (&gsi);
4284 continue;
4287 remove_phi_node (&gsi, false);
4289 if (inserted_exprs
4290 && !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res))
4291 && TREE_CODE (sprime) == SSA_NAME)
4292 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4294 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
4295 sprime = fold_convert (TREE_TYPE (res), sprime);
4296 gimple *stmt = gimple_build_assign (res, sprime);
4297 /* ??? It cannot yet be necessary (DOM walk). */
4298 gimple_set_plf (stmt, NECESSARY, gimple_plf (phi, NECESSARY));
4300 gimple_stmt_iterator gsi2 = gsi_after_labels (b);
4301 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
4302 continue;
4305 eliminate_push_avail (res);
4306 gsi_next (&gsi);
4309 for (gimple_stmt_iterator gsi = gsi_start_bb (b);
4310 !gsi_end_p (gsi);
4311 gsi_next (&gsi))
4313 tree sprime = NULL_TREE;
4314 gimple *stmt = gsi_stmt (gsi);
4315 tree lhs = gimple_get_lhs (stmt);
4316 if (lhs && TREE_CODE (lhs) == SSA_NAME
4317 && !gimple_has_volatile_ops (stmt)
4318 /* See PR43491. Do not replace a global register variable when
4319 it is a the RHS of an assignment. Do replace local register
4320 variables since gcc does not guarantee a local variable will
4321 be allocated in register.
4322 ??? The fix isn't effective here. This should instead
4323 be ensured by not value-numbering them the same but treating
4324 them like volatiles? */
4325 && !(gimple_assign_single_p (stmt)
4326 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == VAR_DECL
4327 && DECL_HARD_REGISTER (gimple_assign_rhs1 (stmt))
4328 && is_global_var (gimple_assign_rhs1 (stmt)))))
4330 sprime = eliminate_avail (lhs);
4331 if (!sprime)
4333 /* If there is no existing usable leader but SCCVN thinks
4334 it has an expression it wants to use as replacement,
4335 insert that. */
4336 tree val = VN_INFO (lhs)->valnum;
4337 if (val != VN_TOP
4338 && TREE_CODE (val) == SSA_NAME
4339 && VN_INFO (val)->needs_insertion
4340 && VN_INFO (val)->expr != NULL
4341 && (sprime = eliminate_insert (&gsi, val)) != NULL_TREE)
4342 eliminate_push_avail (sprime);
4345 /* If this now constitutes a copy duplicate points-to
4346 and range info appropriately. This is especially
4347 important for inserted code. See tree-ssa-copy.c
4348 for similar code. */
4349 if (sprime
4350 && TREE_CODE (sprime) == SSA_NAME)
4352 basic_block sprime_b = gimple_bb (SSA_NAME_DEF_STMT (sprime));
4353 if (POINTER_TYPE_P (TREE_TYPE (lhs))
4354 && VN_INFO_PTR_INFO (lhs)
4355 && ! VN_INFO_PTR_INFO (sprime))
4357 duplicate_ssa_name_ptr_info (sprime,
4358 VN_INFO_PTR_INFO (lhs));
4359 if (b != sprime_b)
4360 mark_ptr_info_alignment_unknown
4361 (SSA_NAME_PTR_INFO (sprime));
4363 else if (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
4364 && VN_INFO_RANGE_INFO (lhs)
4365 && ! VN_INFO_RANGE_INFO (sprime)
4366 && b == sprime_b)
4367 duplicate_ssa_name_range_info (sprime,
4368 VN_INFO_RANGE_TYPE (lhs),
4369 VN_INFO_RANGE_INFO (lhs));
4372 /* Inhibit the use of an inserted PHI on a loop header when
4373 the address of the memory reference is a simple induction
4374 variable. In other cases the vectorizer won't do anything
4375 anyway (either it's loop invariant or a complicated
4376 expression). */
4377 if (sprime
4378 && TREE_CODE (sprime) == SSA_NAME
4379 && do_pre
4380 && (flag_tree_loop_vectorize || flag_tree_parallelize_loops > 1)
4381 && loop_outer (b->loop_father)
4382 && has_zero_uses (sprime)
4383 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))
4384 && gimple_assign_load_p (stmt))
4386 gimple *def_stmt = SSA_NAME_DEF_STMT (sprime);
4387 basic_block def_bb = gimple_bb (def_stmt);
4388 if (gimple_code (def_stmt) == GIMPLE_PHI
4389 && def_bb->loop_father->header == def_bb)
4391 loop_p loop = def_bb->loop_father;
4392 ssa_op_iter iter;
4393 tree op;
4394 bool found = false;
4395 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
4397 affine_iv iv;
4398 def_bb = gimple_bb (SSA_NAME_DEF_STMT (op));
4399 if (def_bb
4400 && flow_bb_inside_loop_p (loop, def_bb)
4401 && simple_iv (loop, loop, op, &iv, true))
4403 found = true;
4404 break;
4407 if (found)
4409 if (dump_file && (dump_flags & TDF_DETAILS))
4411 fprintf (dump_file, "Not replacing ");
4412 print_gimple_expr (dump_file, stmt, 0);
4413 fprintf (dump_file, " with ");
4414 print_generic_expr (dump_file, sprime);
4415 fprintf (dump_file, " which would add a loop"
4416 " carried dependence to loop %d\n",
4417 loop->num);
4419 /* Don't keep sprime available. */
4420 sprime = NULL_TREE;
4425 if (sprime)
4427 /* If we can propagate the value computed for LHS into
4428 all uses don't bother doing anything with this stmt. */
4429 if (may_propagate_copy (lhs, sprime))
4431 /* Mark it for removal. */
4432 el_to_remove.safe_push (stmt);
4434 /* ??? Don't count copy/constant propagations. */
4435 if (gimple_assign_single_p (stmt)
4436 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4437 || gimple_assign_rhs1 (stmt) == sprime))
4438 continue;
4440 if (dump_file && (dump_flags & TDF_DETAILS))
4442 fprintf (dump_file, "Replaced ");
4443 print_gimple_expr (dump_file, stmt, 0);
4444 fprintf (dump_file, " with ");
4445 print_generic_expr (dump_file, sprime);
4446 fprintf (dump_file, " in all uses of ");
4447 print_gimple_stmt (dump_file, stmt, 0);
4450 pre_stats.eliminations++;
4451 continue;
4454 /* If this is an assignment from our leader (which
4455 happens in the case the value-number is a constant)
4456 then there is nothing to do. */
4457 if (gimple_assign_single_p (stmt)
4458 && sprime == gimple_assign_rhs1 (stmt))
4459 continue;
4461 /* Else replace its RHS. */
4462 bool can_make_abnormal_goto
4463 = is_gimple_call (stmt)
4464 && stmt_can_make_abnormal_goto (stmt);
4466 if (dump_file && (dump_flags & TDF_DETAILS))
4468 fprintf (dump_file, "Replaced ");
4469 print_gimple_expr (dump_file, stmt, 0);
4470 fprintf (dump_file, " with ");
4471 print_generic_expr (dump_file, sprime);
4472 fprintf (dump_file, " in ");
4473 print_gimple_stmt (dump_file, stmt, 0);
4476 if (TREE_CODE (sprime) == SSA_NAME)
4477 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4478 NECESSARY, true);
4480 pre_stats.eliminations++;
4481 gimple *orig_stmt = stmt;
4482 if (!useless_type_conversion_p (TREE_TYPE (lhs),
4483 TREE_TYPE (sprime)))
4484 sprime = fold_convert (TREE_TYPE (lhs), sprime);
4485 tree vdef = gimple_vdef (stmt);
4486 tree vuse = gimple_vuse (stmt);
4487 propagate_tree_value_into_stmt (&gsi, sprime);
4488 stmt = gsi_stmt (gsi);
4489 update_stmt (stmt);
4490 if (vdef != gimple_vdef (stmt))
4491 VN_INFO (vdef)->valnum = vuse;
4493 /* If we removed EH side-effects from the statement, clean
4494 its EH information. */
4495 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4497 bitmap_set_bit (need_eh_cleanup,
4498 gimple_bb (stmt)->index);
4499 if (dump_file && (dump_flags & TDF_DETAILS))
4500 fprintf (dump_file, " Removed EH side-effects.\n");
4503 /* Likewise for AB side-effects. */
4504 if (can_make_abnormal_goto
4505 && !stmt_can_make_abnormal_goto (stmt))
4507 bitmap_set_bit (need_ab_cleanup,
4508 gimple_bb (stmt)->index);
4509 if (dump_file && (dump_flags & TDF_DETAILS))
4510 fprintf (dump_file, " Removed AB side-effects.\n");
4513 continue;
4517 /* If the statement is a scalar store, see if the expression
4518 has the same value number as its rhs. If so, the store is
4519 dead. */
4520 if (gimple_assign_single_p (stmt)
4521 && !gimple_has_volatile_ops (stmt)
4522 && !is_gimple_reg (gimple_assign_lhs (stmt))
4523 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4524 || is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
4526 tree val;
4527 tree rhs = gimple_assign_rhs1 (stmt);
4528 vn_reference_t vnresult;
4529 val = vn_reference_lookup (lhs, gimple_vuse (stmt), VN_WALKREWRITE,
4530 &vnresult, false);
4531 if (TREE_CODE (rhs) == SSA_NAME)
4532 rhs = VN_INFO (rhs)->valnum;
4533 if (val
4534 && operand_equal_p (val, rhs, 0))
4536 /* We can only remove the later store if the former aliases
4537 at least all accesses the later one does or if the store
4538 was to readonly memory storing the same value. */
4539 alias_set_type set = get_alias_set (lhs);
4540 if (! vnresult
4541 || vnresult->set == set
4542 || alias_set_subset_of (set, vnresult->set))
4544 if (dump_file && (dump_flags & TDF_DETAILS))
4546 fprintf (dump_file, "Deleted redundant store ");
4547 print_gimple_stmt (dump_file, stmt, 0);
4550 /* Queue stmt for removal. */
4551 el_to_remove.safe_push (stmt);
4552 continue;
4557 /* If this is a control statement value numbering left edges
4558 unexecuted on force the condition in a way consistent with
4559 that. */
4560 if (gcond *cond = dyn_cast <gcond *> (stmt))
4562 if ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE)
4563 ^ (EDGE_SUCC (b, 1)->flags & EDGE_EXECUTABLE))
4565 if (dump_file && (dump_flags & TDF_DETAILS))
4567 fprintf (dump_file, "Removing unexecutable edge from ");
4568 print_gimple_stmt (dump_file, stmt, 0);
4570 if (((EDGE_SUCC (b, 0)->flags & EDGE_TRUE_VALUE) != 0)
4571 == ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE) != 0))
4572 gimple_cond_make_true (cond);
4573 else
4574 gimple_cond_make_false (cond);
4575 update_stmt (cond);
4576 el_todo |= TODO_cleanup_cfg;
4577 continue;
4581 bool can_make_abnormal_goto = stmt_can_make_abnormal_goto (stmt);
4582 bool was_noreturn = (is_gimple_call (stmt)
4583 && gimple_call_noreturn_p (stmt));
4584 tree vdef = gimple_vdef (stmt);
4585 tree vuse = gimple_vuse (stmt);
4587 /* If we didn't replace the whole stmt (or propagate the result
4588 into all uses), replace all uses on this stmt with their
4589 leaders. */
4590 use_operand_p use_p;
4591 ssa_op_iter iter;
4592 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
4594 tree use = USE_FROM_PTR (use_p);
4595 /* ??? The call code above leaves stmt operands un-updated. */
4596 if (TREE_CODE (use) != SSA_NAME)
4597 continue;
4598 tree sprime = eliminate_avail (use);
4599 if (sprime && sprime != use
4600 && may_propagate_copy (use, sprime)
4601 /* We substitute into debug stmts to avoid excessive
4602 debug temporaries created by removed stmts, but we need
4603 to avoid doing so for inserted sprimes as we never want
4604 to create debug temporaries for them. */
4605 && (!inserted_exprs
4606 || TREE_CODE (sprime) != SSA_NAME
4607 || !is_gimple_debug (stmt)
4608 || !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))))
4610 propagate_value (use_p, sprime);
4611 gimple_set_modified (stmt, true);
4612 if (TREE_CODE (sprime) == SSA_NAME
4613 && !is_gimple_debug (stmt))
4614 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4615 NECESSARY, true);
4619 /* Visit indirect calls and turn them into direct calls if
4620 possible using the devirtualization machinery. */
4621 if (gcall *call_stmt = dyn_cast <gcall *> (stmt))
4623 tree fn = gimple_call_fn (call_stmt);
4624 if (fn
4625 && flag_devirtualize
4626 && virtual_method_call_p (fn))
4628 tree otr_type = obj_type_ref_class (fn);
4629 tree instance;
4630 ipa_polymorphic_call_context context (current_function_decl, fn, stmt, &instance);
4631 bool final;
4633 context.get_dynamic_type (instance, OBJ_TYPE_REF_OBJECT (fn), otr_type, stmt);
4635 vec <cgraph_node *>targets
4636 = possible_polymorphic_call_targets (obj_type_ref_class (fn),
4637 tree_to_uhwi
4638 (OBJ_TYPE_REF_TOKEN (fn)),
4639 context,
4640 &final);
4641 if (dump_file)
4642 dump_possible_polymorphic_call_targets (dump_file,
4643 obj_type_ref_class (fn),
4644 tree_to_uhwi
4645 (OBJ_TYPE_REF_TOKEN (fn)),
4646 context);
4647 if (final && targets.length () <= 1 && dbg_cnt (devirt))
4649 tree fn;
4650 if (targets.length () == 1)
4651 fn = targets[0]->decl;
4652 else
4653 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
4654 if (dump_enabled_p ())
4656 location_t loc = gimple_location_safe (stmt);
4657 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
4658 "converting indirect call to "
4659 "function %s\n",
4660 lang_hooks.decl_printable_name (fn, 2));
4662 gimple_call_set_fndecl (call_stmt, fn);
4663 /* If changing the call to __builtin_unreachable
4664 or similar noreturn function, adjust gimple_call_fntype
4665 too. */
4666 if (gimple_call_noreturn_p (call_stmt)
4667 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fn)))
4668 && TYPE_ARG_TYPES (TREE_TYPE (fn))
4669 && (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fn)))
4670 == void_type_node))
4671 gimple_call_set_fntype (call_stmt, TREE_TYPE (fn));
4672 maybe_remove_unused_call_args (cfun, call_stmt);
4673 gimple_set_modified (stmt, true);
4678 if (gimple_modified_p (stmt))
4680 /* If a formerly non-invariant ADDR_EXPR is turned into an
4681 invariant one it was on a separate stmt. */
4682 if (gimple_assign_single_p (stmt)
4683 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
4684 recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
4685 gimple *old_stmt = stmt;
4686 gimple_stmt_iterator prev = gsi;
4687 gsi_prev (&prev);
4688 if (fold_stmt (&gsi))
4690 /* fold_stmt may have created new stmts inbetween
4691 the previous stmt and the folded stmt. Mark
4692 all defs created there as varying to not confuse
4693 the SCCVN machinery as we're using that even during
4694 elimination. */
4695 if (gsi_end_p (prev))
4696 prev = gsi_start_bb (b);
4697 else
4698 gsi_next (&prev);
4699 if (gsi_stmt (prev) != gsi_stmt (gsi))
4702 tree def;
4703 ssa_op_iter dit;
4704 FOR_EACH_SSA_TREE_OPERAND (def, gsi_stmt (prev),
4705 dit, SSA_OP_ALL_DEFS)
4706 /* As existing DEFs may move between stmts
4707 we have to guard VN_INFO_GET. */
4708 if (! has_VN_INFO (def))
4709 VN_INFO_GET (def)->valnum = def;
4710 if (gsi_stmt (prev) == gsi_stmt (gsi))
4711 break;
4712 gsi_next (&prev);
4714 while (1);
4716 stmt = gsi_stmt (gsi);
4717 /* When changing a call into a noreturn call, cfg cleanup
4718 is needed to fix up the noreturn call. */
4719 if (!was_noreturn
4720 && is_gimple_call (stmt) && gimple_call_noreturn_p (stmt))
4721 el_to_fixup.safe_push (stmt);
4722 /* When changing a condition or switch into one we know what
4723 edge will be executed, schedule a cfg cleanup. */
4724 if ((gimple_code (stmt) == GIMPLE_COND
4725 && (gimple_cond_true_p (as_a <gcond *> (stmt))
4726 || gimple_cond_false_p (as_a <gcond *> (stmt))))
4727 || (gimple_code (stmt) == GIMPLE_SWITCH
4728 && TREE_CODE (gimple_switch_index
4729 (as_a <gswitch *> (stmt))) == INTEGER_CST))
4730 el_todo |= TODO_cleanup_cfg;
4731 /* If we removed EH side-effects from the statement, clean
4732 its EH information. */
4733 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
4735 bitmap_set_bit (need_eh_cleanup,
4736 gimple_bb (stmt)->index);
4737 if (dump_file && (dump_flags & TDF_DETAILS))
4738 fprintf (dump_file, " Removed EH side-effects.\n");
4740 /* Likewise for AB side-effects. */
4741 if (can_make_abnormal_goto
4742 && !stmt_can_make_abnormal_goto (stmt))
4744 bitmap_set_bit (need_ab_cleanup,
4745 gimple_bb (stmt)->index);
4746 if (dump_file && (dump_flags & TDF_DETAILS))
4747 fprintf (dump_file, " Removed AB side-effects.\n");
4749 update_stmt (stmt);
4750 if (vdef != gimple_vdef (stmt))
4751 VN_INFO (vdef)->valnum = vuse;
4754 /* Make new values available - for fully redundant LHS we
4755 continue with the next stmt above and skip this. */
4756 def_operand_p defp;
4757 FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_DEF)
4758 eliminate_push_avail (DEF_FROM_PTR (defp));
4761 /* Replace destination PHI arguments. */
4762 FOR_EACH_EDGE (e, ei, b->succs)
4763 if (e->flags & EDGE_EXECUTABLE)
4764 for (gphi_iterator gsi = gsi_start_phis (e->dest);
4765 !gsi_end_p (gsi);
4766 gsi_next (&gsi))
4768 gphi *phi = gsi.phi ();
4769 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
4770 tree arg = USE_FROM_PTR (use_p);
4771 if (TREE_CODE (arg) != SSA_NAME
4772 || virtual_operand_p (arg))
4773 continue;
4774 tree sprime = eliminate_avail (arg);
4775 if (sprime && may_propagate_copy (arg, sprime))
4777 propagate_value (use_p, sprime);
4778 if (TREE_CODE (sprime) == SSA_NAME)
4779 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4782 return NULL;
4785 /* Make no longer available leaders no longer available. */
4787 void
4788 eliminate_dom_walker::after_dom_children (basic_block)
4790 tree entry;
4791 while ((entry = el_avail_stack.pop ()) != NULL_TREE)
4793 tree valnum = VN_INFO (entry)->valnum;
4794 tree old = el_avail[SSA_NAME_VERSION (valnum)];
4795 if (old == entry)
4796 el_avail[SSA_NAME_VERSION (valnum)] = NULL_TREE;
4797 else
4798 el_avail[SSA_NAME_VERSION (valnum)] = entry;
4802 /* Eliminate fully redundant computations. */
4804 static unsigned int
4805 eliminate (bool do_pre)
4807 need_eh_cleanup = BITMAP_ALLOC (NULL);
4808 need_ab_cleanup = BITMAP_ALLOC (NULL);
4810 el_to_remove.create (0);
4811 el_to_fixup.create (0);
4812 el_todo = 0;
4813 el_avail.create (num_ssa_names);
4814 el_avail_stack.create (0);
4816 eliminate_dom_walker (CDI_DOMINATORS,
4817 do_pre).walk (cfun->cfg->x_entry_block_ptr);
4819 el_avail.release ();
4820 el_avail_stack.release ();
4822 return el_todo;
4825 /* Perform CFG cleanups made necessary by elimination. */
4827 static unsigned
4828 fini_eliminate (void)
4830 gimple_stmt_iterator gsi;
4831 gimple *stmt;
4832 unsigned todo = 0;
4834 /* We cannot remove stmts during BB walk, especially not release SSA
4835 names there as this confuses the VN machinery. The stmts ending
4836 up in el_to_remove are either stores or simple copies.
4837 Remove stmts in reverse order to make debug stmt creation possible. */
4838 while (!el_to_remove.is_empty ())
4840 stmt = el_to_remove.pop ();
4842 tree lhs;
4843 if (gimple_code (stmt) == GIMPLE_PHI)
4844 lhs = gimple_phi_result (stmt);
4845 else
4846 lhs = gimple_get_lhs (stmt);
4848 if (inserted_exprs
4849 && TREE_CODE (lhs) == SSA_NAME
4850 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (lhs)))
4851 continue;
4853 if (dump_file && (dump_flags & TDF_DETAILS))
4855 fprintf (dump_file, "Removing dead stmt ");
4856 print_gimple_stmt (dump_file, stmt, 0, 0);
4859 gsi = gsi_for_stmt (stmt);
4860 if (gimple_code (stmt) == GIMPLE_PHI)
4861 remove_phi_node (&gsi, true);
4862 else
4864 basic_block bb = gimple_bb (stmt);
4865 unlink_stmt_vdef (stmt);
4866 if (gsi_remove (&gsi, true))
4867 bitmap_set_bit (need_eh_cleanup, bb->index);
4868 if (is_gimple_call (stmt) && stmt_can_make_abnormal_goto (stmt))
4869 bitmap_set_bit (need_ab_cleanup, bb->index);
4870 release_defs (stmt);
4873 /* Removing a stmt may expose a forwarder block. */
4874 todo |= TODO_cleanup_cfg;
4876 el_to_remove.release ();
4878 /* Fixup stmts that became noreturn calls. This may require splitting
4879 blocks and thus isn't possible during the dominator walk. Do this
4880 in reverse order so we don't inadvertedly remove a stmt we want to
4881 fixup by visiting a dominating now noreturn call first. */
4882 while (!el_to_fixup.is_empty ())
4884 stmt = el_to_fixup.pop ();
4886 if (dump_file && (dump_flags & TDF_DETAILS))
4888 fprintf (dump_file, "Fixing up noreturn call ");
4889 print_gimple_stmt (dump_file, stmt, 0);
4892 if (fixup_noreturn_call (stmt))
4893 todo |= TODO_cleanup_cfg;
4895 el_to_fixup.release ();
4897 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
4898 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
4900 if (do_eh_cleanup)
4901 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
4903 if (do_ab_cleanup)
4904 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
4906 BITMAP_FREE (need_eh_cleanup);
4907 BITMAP_FREE (need_ab_cleanup);
4909 if (do_eh_cleanup || do_ab_cleanup)
4910 todo |= TODO_cleanup_cfg;
4911 return todo;
4914 /* Borrow a bit of tree-ssa-dce.c for the moment.
4915 XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
4916 this may be a bit faster, and we may want critical edges kept split. */
4918 /* If OP's defining statement has not already been determined to be necessary,
4919 mark that statement necessary. Return the stmt, if it is newly
4920 necessary. */
4922 static inline gimple *
4923 mark_operand_necessary (tree op)
4925 gimple *stmt;
4927 gcc_assert (op);
4929 if (TREE_CODE (op) != SSA_NAME)
4930 return NULL;
4932 stmt = SSA_NAME_DEF_STMT (op);
4933 gcc_assert (stmt);
4935 if (gimple_plf (stmt, NECESSARY)
4936 || gimple_nop_p (stmt))
4937 return NULL;
4939 gimple_set_plf (stmt, NECESSARY, true);
4940 return stmt;
4943 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4944 to insert PHI nodes sometimes, and because value numbering of casts isn't
4945 perfect, we sometimes end up inserting dead code. This simple DCE-like
4946 pass removes any insertions we made that weren't actually used. */
4948 static void
4949 remove_dead_inserted_code (void)
4951 unsigned i;
4952 bitmap_iterator bi;
4953 gimple *t;
4955 auto_bitmap worklist;
4956 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4958 t = SSA_NAME_DEF_STMT (ssa_name (i));
4959 if (gimple_plf (t, NECESSARY))
4960 bitmap_set_bit (worklist, i);
4962 while (!bitmap_empty_p (worklist))
4964 i = bitmap_first_set_bit (worklist);
4965 bitmap_clear_bit (worklist, i);
4966 t = SSA_NAME_DEF_STMT (ssa_name (i));
4968 /* PHI nodes are somewhat special in that each PHI alternative has
4969 data and control dependencies. All the statements feeding the
4970 PHI node's arguments are always necessary. */
4971 if (gimple_code (t) == GIMPLE_PHI)
4973 unsigned k;
4975 for (k = 0; k < gimple_phi_num_args (t); k++)
4977 tree arg = PHI_ARG_DEF (t, k);
4978 if (TREE_CODE (arg) == SSA_NAME)
4980 gimple *n = mark_operand_necessary (arg);
4981 if (n)
4982 bitmap_set_bit (worklist, SSA_NAME_VERSION (arg));
4986 else
4988 /* Propagate through the operands. Examine all the USE, VUSE and
4989 VDEF operands in this statement. Mark all the statements
4990 which feed this statement's uses as necessary. */
4991 ssa_op_iter iter;
4992 tree use;
4994 /* The operands of VDEF expressions are also needed as they
4995 represent potential definitions that may reach this
4996 statement (VDEF operands allow us to follow def-def
4997 links). */
4999 FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
5001 gimple *n = mark_operand_necessary (use);
5002 if (n)
5003 bitmap_set_bit (worklist, SSA_NAME_VERSION (use));
5008 unsigned int to_clear = -1U;
5009 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
5011 if (to_clear != -1U)
5013 bitmap_clear_bit (inserted_exprs, to_clear);
5014 to_clear = -1U;
5016 t = SSA_NAME_DEF_STMT (ssa_name (i));
5017 if (!gimple_plf (t, NECESSARY))
5019 gimple_stmt_iterator gsi;
5021 if (dump_file && (dump_flags & TDF_DETAILS))
5023 fprintf (dump_file, "Removing unnecessary insertion:");
5024 print_gimple_stmt (dump_file, t, 0);
5027 gsi = gsi_for_stmt (t);
5028 if (gimple_code (t) == GIMPLE_PHI)
5029 remove_phi_node (&gsi, true);
5030 else
5032 gsi_remove (&gsi, true);
5033 release_defs (t);
5036 else
5037 /* eliminate_fini will skip stmts marked for removal if we
5038 already removed it and uses inserted_exprs for this, so
5039 clear those we didn't end up removing. */
5040 to_clear = i;
5042 if (to_clear != -1U)
5043 bitmap_clear_bit (inserted_exprs, to_clear);
5047 /* Initialize data structures used by PRE. */
5049 static void
5050 init_pre (void)
5052 basic_block bb;
5054 next_expression_id = 1;
5055 expressions.create (0);
5056 expressions.safe_push (NULL);
5057 value_expressions.create (get_max_value_id () + 1);
5058 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
5059 name_to_id.create (0);
5061 inserted_exprs = BITMAP_ALLOC (NULL);
5063 connect_infinite_loops_to_exit ();
5064 memset (&pre_stats, 0, sizeof (pre_stats));
5066 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
5068 calculate_dominance_info (CDI_DOMINATORS);
5070 bitmap_obstack_initialize (&grand_bitmap_obstack);
5071 phi_translate_table = new hash_table<expr_pred_trans_d> (5110);
5072 expression_to_id = new hash_table<pre_expr_d> (num_ssa_names * 3);
5073 FOR_ALL_BB_FN (bb, cfun)
5075 EXP_GEN (bb) = bitmap_set_new ();
5076 PHI_GEN (bb) = bitmap_set_new ();
5077 TMP_GEN (bb) = bitmap_set_new ();
5078 AVAIL_OUT (bb) = bitmap_set_new ();
5083 /* Deallocate data structures used by PRE. */
5085 static void
5086 fini_pre ()
5088 value_expressions.release ();
5089 BITMAP_FREE (inserted_exprs);
5090 bitmap_obstack_release (&grand_bitmap_obstack);
5091 bitmap_set_pool.release ();
5092 pre_expr_pool.release ();
5093 delete phi_translate_table;
5094 phi_translate_table = NULL;
5095 delete expression_to_id;
5096 expression_to_id = NULL;
5097 name_to_id.release ();
5099 free_aux_for_blocks ();
5102 namespace {
5104 const pass_data pass_data_pre =
5106 GIMPLE_PASS, /* type */
5107 "pre", /* name */
5108 OPTGROUP_NONE, /* optinfo_flags */
5109 TV_TREE_PRE, /* tv_id */
5110 /* PROP_no_crit_edges is ensured by placing pass_split_crit_edges before
5111 pass_pre. */
5112 ( PROP_no_crit_edges | PROP_cfg | PROP_ssa ), /* properties_required */
5113 0, /* properties_provided */
5114 PROP_no_crit_edges, /* properties_destroyed */
5115 TODO_rebuild_alias, /* todo_flags_start */
5116 0, /* todo_flags_finish */
5119 class pass_pre : public gimple_opt_pass
5121 public:
5122 pass_pre (gcc::context *ctxt)
5123 : gimple_opt_pass (pass_data_pre, ctxt)
5126 /* opt_pass methods: */
5127 virtual bool gate (function *)
5128 { return flag_tree_pre != 0 || flag_code_hoisting != 0; }
5129 virtual unsigned int execute (function *);
5131 }; // class pass_pre
5133 unsigned int
5134 pass_pre::execute (function *fun)
5136 unsigned int todo = 0;
5138 do_partial_partial =
5139 flag_tree_partial_pre && optimize_function_for_speed_p (fun);
5141 /* This has to happen before SCCVN runs because
5142 loop_optimizer_init may create new phis, etc. */
5143 loop_optimizer_init (LOOPS_NORMAL);
5145 run_scc_vn (VN_WALK);
5147 init_pre ();
5148 scev_initialize ();
5150 /* Collect and value number expressions computed in each basic block. */
5151 compute_avail ();
5153 /* Insert can get quite slow on an incredibly large number of basic
5154 blocks due to some quadratic behavior. Until this behavior is
5155 fixed, don't run it when he have an incredibly large number of
5156 bb's. If we aren't going to run insert, there is no point in
5157 computing ANTIC, either, even though it's plenty fast. */
5158 if (n_basic_blocks_for_fn (fun) < 4000)
5160 compute_antic ();
5161 insert ();
5164 /* Make sure to remove fake edges before committing our inserts.
5165 This makes sure we don't end up with extra critical edges that
5166 we would need to split. */
5167 remove_fake_exit_edges ();
5168 gsi_commit_edge_inserts ();
5170 /* Eliminate folds statements which might (should not...) end up
5171 not keeping virtual operands up-to-date. */
5172 gcc_assert (!need_ssa_update_p (fun));
5174 /* Remove all the redundant expressions. */
5175 todo |= eliminate (true);
5177 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
5178 statistics_counter_event (fun, "PA inserted", pre_stats.pa_insert);
5179 statistics_counter_event (fun, "HOIST inserted", pre_stats.hoist_insert);
5180 statistics_counter_event (fun, "New PHIs", pre_stats.phis);
5181 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
5183 clear_expression_ids ();
5184 remove_dead_inserted_code ();
5186 scev_finalize ();
5187 todo |= fini_eliminate ();
5188 fini_pre ();
5189 loop_optimizer_finalize ();
5191 /* Restore SSA info before tail-merging as that resets it as well. */
5192 scc_vn_restore_ssa_info ();
5194 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
5195 case we can merge the block with the remaining predecessor of the block.
5196 It should either:
5197 - call merge_blocks after each tail merge iteration
5198 - call merge_blocks after all tail merge iterations
5199 - mark TODO_cleanup_cfg when necessary
5200 - share the cfg cleanup with fini_pre. */
5201 todo |= tail_merge_optimize (todo);
5203 free_scc_vn ();
5205 /* Tail merging invalidates the virtual SSA web, together with
5206 cfg-cleanup opportunities exposed by PRE this will wreck the
5207 SSA updating machinery. So make sure to run update-ssa
5208 manually, before eventually scheduling cfg-cleanup as part of
5209 the todo. */
5210 update_ssa (TODO_update_ssa_only_virtuals);
5212 return todo;
5215 } // anon namespace
5217 gimple_opt_pass *
5218 make_pass_pre (gcc::context *ctxt)
5220 return new pass_pre (ctxt);
5223 namespace {
5225 const pass_data pass_data_fre =
5227 GIMPLE_PASS, /* type */
5228 "fre", /* name */
5229 OPTGROUP_NONE, /* optinfo_flags */
5230 TV_TREE_FRE, /* tv_id */
5231 ( PROP_cfg | PROP_ssa ), /* properties_required */
5232 0, /* properties_provided */
5233 0, /* properties_destroyed */
5234 0, /* todo_flags_start */
5235 0, /* todo_flags_finish */
5238 class pass_fre : public gimple_opt_pass
5240 public:
5241 pass_fre (gcc::context *ctxt)
5242 : gimple_opt_pass (pass_data_fre, ctxt)
5245 /* opt_pass methods: */
5246 opt_pass * clone () { return new pass_fre (m_ctxt); }
5247 virtual bool gate (function *) { return flag_tree_fre != 0; }
5248 virtual unsigned int execute (function *);
5250 }; // class pass_fre
5252 unsigned int
5253 pass_fre::execute (function *fun)
5255 unsigned int todo = 0;
5257 run_scc_vn (VN_WALKREWRITE);
5259 memset (&pre_stats, 0, sizeof (pre_stats));
5261 /* Remove all the redundant expressions. */
5262 todo |= eliminate (false);
5264 todo |= fini_eliminate ();
5266 scc_vn_restore_ssa_info ();
5267 free_scc_vn ();
5269 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
5270 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
5272 return todo;
5275 } // anon namespace
5277 gimple_opt_pass *
5278 make_pass_fre (gcc::context *ctxt)
5280 return new pass_fre (ctxt);