* testsuite/26_numerics/headers/cmath/hypot.cc: XFAIL on AIX.
[official-gcc.git] / gcc / tree-ssa-pre.c
blob4f172005f2633af2e40a0b44d9f3aacd4cbd7309
1 /* Full and partial redundancy elimination and code hoisting on SSA GIMPLE.
2 Copyright (C) 2001-2016 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_head temp;
821 bitmap_initialize (&temp, &grand_bitmap_obstack);
823 bitmap_and_into (&dest->values, &orig->values);
824 bitmap_copy (&temp, &dest->expressions);
825 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
827 pre_expr expr = expression_for_id (i);
828 unsigned int value_id = get_expr_value_id (expr);
829 if (!bitmap_bit_p (&dest->values, value_id))
830 bitmap_clear_bit (&dest->expressions, i);
832 bitmap_clear (&temp);
836 /* Subtract all values and expressions contained in ORIG from DEST. */
838 static bitmap_set_t
839 bitmap_set_subtract (bitmap_set_t dest, bitmap_set_t orig)
841 bitmap_set_t result = bitmap_set_new ();
842 bitmap_iterator bi;
843 unsigned int i;
845 bitmap_and_compl (&result->expressions, &dest->expressions,
846 &orig->expressions);
848 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
850 pre_expr expr = expression_for_id (i);
851 unsigned int value_id = get_expr_value_id (expr);
852 bitmap_set_bit (&result->values, value_id);
855 return result;
858 /* Subtract all the values in bitmap set B from bitmap set A. */
860 static void
861 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
863 unsigned int i;
864 bitmap_iterator bi;
865 bitmap_head temp;
867 bitmap_initialize (&temp, &grand_bitmap_obstack);
869 bitmap_copy (&temp, &a->expressions);
870 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
872 pre_expr expr = expression_for_id (i);
873 if (bitmap_set_contains_value (b, get_expr_value_id (expr)))
874 bitmap_remove_from_set (a, expr);
876 bitmap_clear (&temp);
880 /* Return true if bitmapped set SET contains the value VALUE_ID. */
882 static bool
883 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
885 if (value_id_constant_p (value_id))
886 return true;
888 if (!set || bitmap_empty_p (&set->expressions))
889 return false;
891 return bitmap_bit_p (&set->values, value_id);
894 static inline bool
895 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
897 return bitmap_bit_p (&set->expressions, get_expression_id (expr));
900 /* Replace an instance of value LOOKFOR with expression EXPR in SET. */
902 static void
903 bitmap_set_replace_value (bitmap_set_t set, unsigned int lookfor,
904 const pre_expr expr)
906 bitmap exprset;
907 unsigned int i;
908 bitmap_iterator bi;
910 if (value_id_constant_p (lookfor))
911 return;
913 if (!bitmap_set_contains_value (set, lookfor))
914 return;
916 /* The number of expressions having a given value is usually
917 significantly less than the total number of expressions in SET.
918 Thus, rather than check, for each expression in SET, whether it
919 has the value LOOKFOR, we walk the reverse mapping that tells us
920 what expressions have a given value, and see if any of those
921 expressions are in our set. For large testcases, this is about
922 5-10x faster than walking the bitmap. If this is somehow a
923 significant lose for some cases, we can choose which set to walk
924 based on the set size. */
925 exprset = value_expressions[lookfor];
926 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
928 if (bitmap_clear_bit (&set->expressions, i))
930 bitmap_set_bit (&set->expressions, get_expression_id (expr));
931 return;
935 gcc_unreachable ();
938 /* Return true if two bitmap sets are equal. */
940 static bool
941 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
943 return bitmap_equal_p (&a->values, &b->values);
946 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
947 and add it otherwise. */
949 static void
950 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
952 unsigned int val = get_expr_value_id (expr);
954 if (bitmap_set_contains_value (set, val))
955 bitmap_set_replace_value (set, val, expr);
956 else
957 bitmap_insert_into_set (set, expr);
960 /* Insert EXPR into SET if EXPR's value is not already present in
961 SET. */
963 static void
964 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
966 unsigned int val = get_expr_value_id (expr);
968 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
970 /* Constant values are always considered to be part of the set. */
971 if (value_id_constant_p (val))
972 return;
974 /* If the value membership changed, add the expression. */
975 if (bitmap_set_bit (&set->values, val))
976 bitmap_set_bit (&set->expressions, expr->id);
979 /* Print out EXPR to outfile. */
981 static void
982 print_pre_expr (FILE *outfile, const pre_expr expr)
984 switch (expr->kind)
986 case CONSTANT:
987 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr), 0);
988 break;
989 case NAME:
990 print_generic_expr (outfile, PRE_EXPR_NAME (expr), 0);
991 break;
992 case NARY:
994 unsigned int i;
995 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
996 fprintf (outfile, "{%s,", get_tree_code_name (nary->opcode));
997 for (i = 0; i < nary->length; i++)
999 print_generic_expr (outfile, nary->op[i], 0);
1000 if (i != (unsigned) nary->length - 1)
1001 fprintf (outfile, ",");
1003 fprintf (outfile, "}");
1005 break;
1007 case REFERENCE:
1009 vn_reference_op_t vro;
1010 unsigned int i;
1011 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1012 fprintf (outfile, "{");
1013 for (i = 0;
1014 ref->operands.iterate (i, &vro);
1015 i++)
1017 bool closebrace = false;
1018 if (vro->opcode != SSA_NAME
1019 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
1021 fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
1022 if (vro->op0)
1024 fprintf (outfile, "<");
1025 closebrace = true;
1028 if (vro->op0)
1030 print_generic_expr (outfile, vro->op0, 0);
1031 if (vro->op1)
1033 fprintf (outfile, ",");
1034 print_generic_expr (outfile, vro->op1, 0);
1036 if (vro->op2)
1038 fprintf (outfile, ",");
1039 print_generic_expr (outfile, vro->op2, 0);
1042 if (closebrace)
1043 fprintf (outfile, ">");
1044 if (i != ref->operands.length () - 1)
1045 fprintf (outfile, ",");
1047 fprintf (outfile, "}");
1048 if (ref->vuse)
1050 fprintf (outfile, "@");
1051 print_generic_expr (outfile, ref->vuse, 0);
1054 break;
1057 void debug_pre_expr (pre_expr);
1059 /* Like print_pre_expr but always prints to stderr. */
1060 DEBUG_FUNCTION void
1061 debug_pre_expr (pre_expr e)
1063 print_pre_expr (stderr, e);
1064 fprintf (stderr, "\n");
1067 /* Print out SET to OUTFILE. */
1069 static void
1070 print_bitmap_set (FILE *outfile, bitmap_set_t set,
1071 const char *setname, int blockindex)
1073 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
1074 if (set)
1076 bool first = true;
1077 unsigned i;
1078 bitmap_iterator bi;
1080 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1082 const pre_expr expr = expression_for_id (i);
1084 if (!first)
1085 fprintf (outfile, ", ");
1086 first = false;
1087 print_pre_expr (outfile, expr);
1089 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1092 fprintf (outfile, " }\n");
1095 void debug_bitmap_set (bitmap_set_t);
1097 DEBUG_FUNCTION void
1098 debug_bitmap_set (bitmap_set_t set)
1100 print_bitmap_set (stderr, set, "debug", 0);
1103 void debug_bitmap_sets_for (basic_block);
1105 DEBUG_FUNCTION void
1106 debug_bitmap_sets_for (basic_block bb)
1108 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1109 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1110 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1111 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1112 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1113 if (do_partial_partial)
1114 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1115 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1118 /* Print out the expressions that have VAL to OUTFILE. */
1120 static void
1121 print_value_expressions (FILE *outfile, unsigned int val)
1123 bitmap set = value_expressions[val];
1124 if (set)
1126 bitmap_set x;
1127 char s[10];
1128 sprintf (s, "%04d", val);
1129 x.expressions = *set;
1130 print_bitmap_set (outfile, &x, s, 0);
1135 DEBUG_FUNCTION void
1136 debug_value_expressions (unsigned int val)
1138 print_value_expressions (stderr, val);
1141 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1142 represent it. */
1144 static pre_expr
1145 get_or_alloc_expr_for_constant (tree constant)
1147 unsigned int result_id;
1148 unsigned int value_id;
1149 struct pre_expr_d expr;
1150 pre_expr newexpr;
1152 expr.kind = CONSTANT;
1153 PRE_EXPR_CONSTANT (&expr) = constant;
1154 result_id = lookup_expression_id (&expr);
1155 if (result_id != 0)
1156 return expression_for_id (result_id);
1158 newexpr = pre_expr_pool.allocate ();
1159 newexpr->kind = CONSTANT;
1160 PRE_EXPR_CONSTANT (newexpr) = constant;
1161 alloc_expression_id (newexpr);
1162 value_id = get_or_alloc_constant_value_id (constant);
1163 add_to_value (value_id, newexpr);
1164 return newexpr;
1167 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1168 Currently only supports constants and SSA_NAMES. */
1169 static pre_expr
1170 get_or_alloc_expr_for (tree t)
1172 if (TREE_CODE (t) == SSA_NAME)
1173 return get_or_alloc_expr_for_name (t);
1174 else if (is_gimple_min_invariant (t))
1175 return get_or_alloc_expr_for_constant (t);
1176 else
1178 /* More complex expressions can result from SCCVN expression
1179 simplification that inserts values for them. As they all
1180 do not have VOPs the get handled by the nary ops struct. */
1181 vn_nary_op_t result;
1182 unsigned int result_id;
1183 vn_nary_op_lookup (t, &result);
1184 if (result != NULL)
1186 pre_expr e = pre_expr_pool.allocate ();
1187 e->kind = NARY;
1188 PRE_EXPR_NARY (e) = result;
1189 result_id = lookup_expression_id (e);
1190 if (result_id != 0)
1192 pre_expr_pool.remove (e);
1193 e = expression_for_id (result_id);
1194 return e;
1196 alloc_expression_id (e);
1197 return e;
1200 return NULL;
1203 /* Return the folded version of T if T, when folded, is a gimple
1204 min_invariant or an SSA name. Otherwise, return T. */
1206 static pre_expr
1207 fully_constant_expression (pre_expr e)
1209 switch (e->kind)
1211 case CONSTANT:
1212 return e;
1213 case NARY:
1215 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1216 tree res = vn_nary_simplify (nary);
1217 if (!res)
1218 return e;
1219 if (is_gimple_min_invariant (res))
1220 return get_or_alloc_expr_for_constant (res);
1221 if (TREE_CODE (res) == SSA_NAME)
1222 return get_or_alloc_expr_for_name (res);
1223 return e;
1225 case REFERENCE:
1227 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1228 tree folded;
1229 if ((folded = fully_constant_vn_reference_p (ref)))
1230 return get_or_alloc_expr_for_constant (folded);
1231 return e;
1233 default:
1234 return e;
1236 return e;
1239 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1240 it has the value it would have in BLOCK. Set *SAME_VALID to true
1241 in case the new vuse doesn't change the value id of the OPERANDS. */
1243 static tree
1244 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1245 alias_set_type set, tree type, tree vuse,
1246 basic_block phiblock,
1247 basic_block block, bool *same_valid)
1249 gimple *phi = SSA_NAME_DEF_STMT (vuse);
1250 ao_ref ref;
1251 edge e = NULL;
1252 bool use_oracle;
1254 *same_valid = true;
1256 if (gimple_bb (phi) != phiblock)
1257 return vuse;
1259 use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1261 /* Use the alias-oracle to find either the PHI node in this block,
1262 the first VUSE used in this block that is equivalent to vuse or
1263 the first VUSE which definition in this block kills the value. */
1264 if (gimple_code (phi) == GIMPLE_PHI)
1265 e = find_edge (block, phiblock);
1266 else if (use_oracle)
1267 while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1269 vuse = gimple_vuse (phi);
1270 phi = SSA_NAME_DEF_STMT (vuse);
1271 if (gimple_bb (phi) != phiblock)
1272 return vuse;
1273 if (gimple_code (phi) == GIMPLE_PHI)
1275 e = find_edge (block, phiblock);
1276 break;
1279 else
1280 return NULL_TREE;
1282 if (e)
1284 if (use_oracle)
1286 bitmap visited = NULL;
1287 unsigned int cnt;
1288 /* Try to find a vuse that dominates this phi node by skipping
1289 non-clobbering statements. */
1290 vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false,
1291 NULL, NULL);
1292 if (visited)
1293 BITMAP_FREE (visited);
1295 else
1296 vuse = NULL_TREE;
1297 if (!vuse)
1299 /* If we didn't find any, the value ID can't stay the same,
1300 but return the translated vuse. */
1301 *same_valid = false;
1302 vuse = PHI_ARG_DEF (phi, e->dest_idx);
1304 /* ??? We would like to return vuse here as this is the canonical
1305 upmost vdef that this reference is associated with. But during
1306 insertion of the references into the hash tables we only ever
1307 directly insert with their direct gimple_vuse, hence returning
1308 something else would make us not find the other expression. */
1309 return PHI_ARG_DEF (phi, e->dest_idx);
1312 return NULL_TREE;
1315 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1316 SET2. This is used to avoid making a set consisting of the union
1317 of PA_IN and ANTIC_IN during insert. */
1319 static inline pre_expr
1320 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2)
1322 pre_expr result;
1324 result = bitmap_find_leader (set1, val);
1325 if (!result && set2)
1326 result = bitmap_find_leader (set2, val);
1327 return result;
1330 /* Get the tree type for our PRE expression e. */
1332 static tree
1333 get_expr_type (const pre_expr e)
1335 switch (e->kind)
1337 case NAME:
1338 return TREE_TYPE (PRE_EXPR_NAME (e));
1339 case CONSTANT:
1340 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1341 case REFERENCE:
1342 return PRE_EXPR_REFERENCE (e)->type;
1343 case NARY:
1344 return PRE_EXPR_NARY (e)->type;
1346 gcc_unreachable ();
1349 /* Get a representative SSA_NAME for a given expression.
1350 Since all of our sub-expressions are treated as values, we require
1351 them to be SSA_NAME's for simplicity.
1352 Prior versions of GVNPRE used to use "value handles" here, so that
1353 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1354 either case, the operands are really values (IE we do not expect
1355 them to be usable without finding leaders). */
1357 static tree
1358 get_representative_for (const pre_expr e)
1360 tree name;
1361 unsigned int value_id = get_expr_value_id (e);
1363 switch (e->kind)
1365 case NAME:
1366 return VN_INFO (PRE_EXPR_NAME (e))->valnum;
1367 case CONSTANT:
1368 return PRE_EXPR_CONSTANT (e);
1369 case NARY:
1370 case REFERENCE:
1372 /* Go through all of the expressions representing this value
1373 and pick out an SSA_NAME. */
1374 unsigned int i;
1375 bitmap_iterator bi;
1376 bitmap exprs = value_expressions[value_id];
1377 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1379 pre_expr rep = expression_for_id (i);
1380 if (rep->kind == NAME)
1381 return VN_INFO (PRE_EXPR_NAME (rep))->valnum;
1382 else if (rep->kind == CONSTANT)
1383 return PRE_EXPR_CONSTANT (rep);
1386 break;
1389 /* If we reached here we couldn't find an SSA_NAME. This can
1390 happen when we've discovered a value that has never appeared in
1391 the program as set to an SSA_NAME, as the result of phi translation.
1392 Create one here.
1393 ??? We should be able to re-use this when we insert the statement
1394 to compute it. */
1395 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1396 VN_INFO_GET (name)->value_id = value_id;
1397 VN_INFO (name)->valnum = name;
1398 /* ??? For now mark this SSA name for release by SCCVN. */
1399 VN_INFO (name)->needs_insertion = true;
1400 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1401 if (dump_file && (dump_flags & TDF_DETAILS))
1403 fprintf (dump_file, "Created SSA_NAME representative ");
1404 print_generic_expr (dump_file, name, 0);
1405 fprintf (dump_file, " for expression:");
1406 print_pre_expr (dump_file, e);
1407 fprintf (dump_file, " (%04d)\n", value_id);
1410 return name;
1415 static pre_expr
1416 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1417 basic_block pred, basic_block phiblock);
1419 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1420 the phis in PRED. Return NULL if we can't find a leader for each part
1421 of the translated expression. */
1423 static pre_expr
1424 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1425 basic_block pred, basic_block phiblock)
1427 switch (expr->kind)
1429 case NARY:
1431 unsigned int i;
1432 bool changed = false;
1433 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1434 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1435 sizeof_vn_nary_op (nary->length));
1436 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1438 for (i = 0; i < newnary->length; i++)
1440 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1441 continue;
1442 else
1444 pre_expr leader, result;
1445 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1446 leader = find_leader_in_sets (op_val_id, set1, set2);
1447 result = phi_translate (leader, set1, set2, pred, phiblock);
1448 if (result && result != leader)
1449 newnary->op[i] = get_representative_for (result);
1450 else if (!result)
1451 return NULL;
1453 changed |= newnary->op[i] != nary->op[i];
1456 if (changed)
1458 pre_expr constant;
1459 unsigned int new_val_id;
1461 PRE_EXPR_NARY (expr) = newnary;
1462 constant = fully_constant_expression (expr);
1463 PRE_EXPR_NARY (expr) = nary;
1464 if (constant != expr)
1466 /* For non-CONSTANTs we have to make sure we can eventually
1467 insert the expression. Which means we need to have a
1468 leader for it. */
1469 if (constant->kind != CONSTANT)
1471 unsigned value_id = get_expr_value_id (constant);
1472 constant = find_leader_in_sets (value_id, set1, set2);
1473 if (constant)
1474 return constant;
1476 else
1477 return constant;
1480 tree result = vn_nary_op_lookup_pieces (newnary->length,
1481 newnary->opcode,
1482 newnary->type,
1483 &newnary->op[0],
1484 &nary);
1485 if (result && is_gimple_min_invariant (result))
1486 return get_or_alloc_expr_for_constant (result);
1488 expr = pre_expr_pool.allocate ();
1489 expr->kind = NARY;
1490 expr->id = 0;
1491 if (nary)
1493 PRE_EXPR_NARY (expr) = nary;
1494 new_val_id = nary->value_id;
1495 get_or_alloc_expression_id (expr);
1497 else
1499 new_val_id = get_next_value_id ();
1500 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
1501 nary = vn_nary_op_insert_pieces (newnary->length,
1502 newnary->opcode,
1503 newnary->type,
1504 &newnary->op[0],
1505 result, new_val_id);
1506 PRE_EXPR_NARY (expr) = nary;
1507 get_or_alloc_expression_id (expr);
1509 add_to_value (new_val_id, expr);
1511 return expr;
1513 break;
1515 case REFERENCE:
1517 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1518 vec<vn_reference_op_s> operands = ref->operands;
1519 tree vuse = ref->vuse;
1520 tree newvuse = vuse;
1521 vec<vn_reference_op_s> newoperands = vNULL;
1522 bool changed = false, same_valid = true;
1523 unsigned int i, n;
1524 vn_reference_op_t operand;
1525 vn_reference_t newref;
1527 for (i = 0; operands.iterate (i, &operand); i++)
1529 pre_expr opresult;
1530 pre_expr leader;
1531 tree op[3];
1532 tree type = operand->type;
1533 vn_reference_op_s newop = *operand;
1534 op[0] = operand->op0;
1535 op[1] = operand->op1;
1536 op[2] = operand->op2;
1537 for (n = 0; n < 3; ++n)
1539 unsigned int op_val_id;
1540 if (!op[n])
1541 continue;
1542 if (TREE_CODE (op[n]) != SSA_NAME)
1544 /* We can't possibly insert these. */
1545 if (n != 0
1546 && !is_gimple_min_invariant (op[n]))
1547 break;
1548 continue;
1550 op_val_id = VN_INFO (op[n])->value_id;
1551 leader = find_leader_in_sets (op_val_id, set1, set2);
1552 opresult = phi_translate (leader, set1, set2, pred, phiblock);
1553 if (opresult && opresult != leader)
1555 tree name = get_representative_for (opresult);
1556 changed |= name != op[n];
1557 op[n] = name;
1559 else if (!opresult)
1560 break;
1562 if (n != 3)
1564 newoperands.release ();
1565 return NULL;
1567 if (!changed)
1568 continue;
1569 if (!newoperands.exists ())
1570 newoperands = operands.copy ();
1571 /* We may have changed from an SSA_NAME to a constant */
1572 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1573 newop.opcode = TREE_CODE (op[0]);
1574 newop.type = type;
1575 newop.op0 = op[0];
1576 newop.op1 = op[1];
1577 newop.op2 = op[2];
1578 newoperands[i] = newop;
1580 gcc_checking_assert (i == operands.length ());
1582 if (vuse)
1584 newvuse = translate_vuse_through_block (newoperands.exists ()
1585 ? newoperands : operands,
1586 ref->set, ref->type,
1587 vuse, phiblock, pred,
1588 &same_valid);
1589 if (newvuse == NULL_TREE)
1591 newoperands.release ();
1592 return NULL;
1596 if (changed || newvuse != vuse)
1598 unsigned int new_val_id;
1599 pre_expr constant;
1601 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1602 ref->type,
1603 newoperands.exists ()
1604 ? newoperands : operands,
1605 &newref, VN_WALK);
1606 if (result)
1607 newoperands.release ();
1609 /* We can always insert constants, so if we have a partial
1610 redundant constant load of another type try to translate it
1611 to a constant of appropriate type. */
1612 if (result && is_gimple_min_invariant (result))
1614 tree tem = result;
1615 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1617 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1618 if (tem && !is_gimple_min_invariant (tem))
1619 tem = NULL_TREE;
1621 if (tem)
1622 return get_or_alloc_expr_for_constant (tem);
1625 /* If we'd have to convert things we would need to validate
1626 if we can insert the translated expression. So fail
1627 here for now - we cannot insert an alias with a different
1628 type in the VN tables either, as that would assert. */
1629 if (result
1630 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1631 return NULL;
1632 else if (!result && newref
1633 && !useless_type_conversion_p (ref->type, newref->type))
1635 newoperands.release ();
1636 return NULL;
1639 expr = pre_expr_pool.allocate ();
1640 expr->kind = REFERENCE;
1641 expr->id = 0;
1643 if (newref)
1645 PRE_EXPR_REFERENCE (expr) = newref;
1646 constant = fully_constant_expression (expr);
1647 if (constant != expr)
1648 return constant;
1650 new_val_id = newref->value_id;
1651 get_or_alloc_expression_id (expr);
1653 else
1655 if (changed || !same_valid)
1657 new_val_id = get_next_value_id ();
1658 value_expressions.safe_grow_cleared
1659 (get_max_value_id () + 1);
1661 else
1662 new_val_id = ref->value_id;
1663 if (!newoperands.exists ())
1664 newoperands = operands.copy ();
1665 newref = vn_reference_insert_pieces (newvuse, ref->set,
1666 ref->type,
1667 newoperands,
1668 result, new_val_id);
1669 newoperands = vNULL;
1670 PRE_EXPR_REFERENCE (expr) = newref;
1671 constant = fully_constant_expression (expr);
1672 if (constant != expr)
1673 return constant;
1674 get_or_alloc_expression_id (expr);
1676 add_to_value (new_val_id, expr);
1678 newoperands.release ();
1679 return expr;
1681 break;
1683 case NAME:
1685 tree name = PRE_EXPR_NAME (expr);
1686 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1687 /* If the SSA name is defined by a PHI node in this block,
1688 translate it. */
1689 if (gimple_code (def_stmt) == GIMPLE_PHI
1690 && gimple_bb (def_stmt) == phiblock)
1692 edge e = find_edge (pred, gimple_bb (def_stmt));
1693 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1695 /* Handle constant. */
1696 if (is_gimple_min_invariant (def))
1697 return get_or_alloc_expr_for_constant (def);
1699 return get_or_alloc_expr_for_name (def);
1701 /* Otherwise return it unchanged - it will get removed if its
1702 value is not available in PREDs AVAIL_OUT set of expressions
1703 by the subtraction of TMP_GEN. */
1704 return expr;
1707 default:
1708 gcc_unreachable ();
1712 /* Wrapper around phi_translate_1 providing caching functionality. */
1714 static pre_expr
1715 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1716 basic_block pred, basic_block phiblock)
1718 expr_pred_trans_t slot = NULL;
1719 pre_expr phitrans;
1721 if (!expr)
1722 return NULL;
1724 /* Constants contain no values that need translation. */
1725 if (expr->kind == CONSTANT)
1726 return expr;
1728 if (value_id_constant_p (get_expr_value_id (expr)))
1729 return expr;
1731 /* Don't add translations of NAMEs as those are cheap to translate. */
1732 if (expr->kind != NAME)
1734 if (phi_trans_add (&slot, expr, pred))
1735 return slot->v;
1736 /* Store NULL for the value we want to return in the case of
1737 recursing. */
1738 slot->v = NULL;
1741 /* Translate. */
1742 phitrans = phi_translate_1 (expr, set1, set2, pred, phiblock);
1744 if (slot)
1746 if (phitrans)
1747 slot->v = phitrans;
1748 else
1749 /* Remove failed translations again, they cause insert
1750 iteration to not pick up new opportunities reliably. */
1751 phi_translate_table->remove_elt_with_hash (slot, slot->hashcode);
1754 return phitrans;
1758 /* For each expression in SET, translate the values through phi nodes
1759 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1760 expressions in DEST. */
1762 static void
1763 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1764 basic_block phiblock)
1766 vec<pre_expr> exprs;
1767 pre_expr expr;
1768 int i;
1770 if (gimple_seq_empty_p (phi_nodes (phiblock)))
1772 bitmap_set_copy (dest, set);
1773 return;
1776 exprs = sorted_array_from_bitmap_set (set);
1777 FOR_EACH_VEC_ELT (exprs, i, expr)
1779 pre_expr translated;
1780 translated = phi_translate (expr, set, NULL, pred, phiblock);
1781 if (!translated)
1782 continue;
1784 /* We might end up with multiple expressions from SET being
1785 translated to the same value. In this case we do not want
1786 to retain the NARY or REFERENCE expression but prefer a NAME
1787 which would be the leader. */
1788 if (translated->kind == NAME)
1789 bitmap_value_replace_in_set (dest, translated);
1790 else
1791 bitmap_value_insert_into_set (dest, translated);
1793 exprs.release ();
1796 /* Find the leader for a value (i.e., the name representing that
1797 value) in a given set, and return it. Return NULL if no leader
1798 is found. */
1800 static pre_expr
1801 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1803 if (value_id_constant_p (val))
1805 unsigned int i;
1806 bitmap_iterator bi;
1807 bitmap exprset = value_expressions[val];
1809 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1811 pre_expr expr = expression_for_id (i);
1812 if (expr->kind == CONSTANT)
1813 return expr;
1816 if (bitmap_set_contains_value (set, val))
1818 /* Rather than walk the entire bitmap of expressions, and see
1819 whether any of them has the value we are looking for, we look
1820 at the reverse mapping, which tells us the set of expressions
1821 that have a given value (IE value->expressions with that
1822 value) and see if any of those expressions are in our set.
1823 The number of expressions per value is usually significantly
1824 less than the number of expressions in the set. In fact, for
1825 large testcases, doing it this way is roughly 5-10x faster
1826 than walking the bitmap.
1827 If this is somehow a significant lose for some cases, we can
1828 choose which set to walk based on which set is smaller. */
1829 unsigned int i;
1830 bitmap_iterator bi;
1831 bitmap exprset = value_expressions[val];
1833 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1834 return expression_for_id (i);
1836 return NULL;
1839 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1840 BLOCK by seeing if it is not killed in the block. Note that we are
1841 only determining whether there is a store that kills it. Because
1842 of the order in which clean iterates over values, we are guaranteed
1843 that altered operands will have caused us to be eliminated from the
1844 ANTIC_IN set already. */
1846 static bool
1847 value_dies_in_block_x (pre_expr expr, basic_block block)
1849 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1850 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1851 gimple *def;
1852 gimple_stmt_iterator gsi;
1853 unsigned id = get_expression_id (expr);
1854 bool res = false;
1855 ao_ref ref;
1857 if (!vuse)
1858 return false;
1860 /* Lookup a previously calculated result. */
1861 if (EXPR_DIES (block)
1862 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1863 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1865 /* A memory expression {e, VUSE} dies in the block if there is a
1866 statement that may clobber e. If, starting statement walk from the
1867 top of the basic block, a statement uses VUSE there can be no kill
1868 inbetween that use and the original statement that loaded {e, VUSE},
1869 so we can stop walking. */
1870 ref.base = NULL_TREE;
1871 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1873 tree def_vuse, def_vdef;
1874 def = gsi_stmt (gsi);
1875 def_vuse = gimple_vuse (def);
1876 def_vdef = gimple_vdef (def);
1878 /* Not a memory statement. */
1879 if (!def_vuse)
1880 continue;
1882 /* Not a may-def. */
1883 if (!def_vdef)
1885 /* A load with the same VUSE, we're done. */
1886 if (def_vuse == vuse)
1887 break;
1889 continue;
1892 /* Init ref only if we really need it. */
1893 if (ref.base == NULL_TREE
1894 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1895 refx->operands))
1897 res = true;
1898 break;
1900 /* If the statement may clobber expr, it dies. */
1901 if (stmt_may_clobber_ref_p_1 (def, &ref))
1903 res = true;
1904 break;
1908 /* Remember the result. */
1909 if (!EXPR_DIES (block))
1910 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1911 bitmap_set_bit (EXPR_DIES (block), id * 2);
1912 if (res)
1913 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1915 return res;
1919 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1920 contains its value-id. */
1922 static bool
1923 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1925 if (op && TREE_CODE (op) == SSA_NAME)
1927 unsigned int value_id = VN_INFO (op)->value_id;
1928 if (!(bitmap_set_contains_value (set1, value_id)
1929 || (set2 && bitmap_set_contains_value (set2, value_id))))
1930 return false;
1932 return true;
1935 /* Determine if the expression EXPR is valid in SET1 U SET2.
1936 ONLY SET2 CAN BE NULL.
1937 This means that we have a leader for each part of the expression
1938 (if it consists of values), or the expression is an SSA_NAME.
1939 For loads/calls, we also see if the vuse is killed in this block. */
1941 static bool
1942 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr)
1944 switch (expr->kind)
1946 case NAME:
1947 /* By construction all NAMEs are available. Non-available
1948 NAMEs are removed by subtracting TMP_GEN from the sets. */
1949 return true;
1950 case NARY:
1952 unsigned int i;
1953 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1954 for (i = 0; i < nary->length; i++)
1955 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1956 return false;
1957 return true;
1959 break;
1960 case REFERENCE:
1962 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1963 vn_reference_op_t vro;
1964 unsigned int i;
1966 FOR_EACH_VEC_ELT (ref->operands, i, vro)
1968 if (!op_valid_in_sets (set1, set2, vro->op0)
1969 || !op_valid_in_sets (set1, set2, vro->op1)
1970 || !op_valid_in_sets (set1, set2, vro->op2))
1971 return false;
1973 return true;
1975 default:
1976 gcc_unreachable ();
1980 /* Clean the set of expressions that are no longer valid in SET1 or
1981 SET2. This means expressions that are made up of values we have no
1982 leaders for in SET1 or SET2. This version is used for partial
1983 anticipation, which means it is not valid in either ANTIC_IN or
1984 PA_IN. */
1986 static void
1987 dependent_clean (bitmap_set_t set1, bitmap_set_t set2)
1989 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
1990 pre_expr expr;
1991 int i;
1993 FOR_EACH_VEC_ELT (exprs, i, expr)
1995 if (!valid_in_sets (set1, set2, expr))
1996 bitmap_remove_from_set (set1, expr);
1998 exprs.release ();
2001 /* Clean the set of expressions that are no longer valid in SET. This
2002 means expressions that are made up of values we have no leaders for
2003 in SET. */
2005 static void
2006 clean (bitmap_set_t set)
2008 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set);
2009 pre_expr expr;
2010 int i;
2012 FOR_EACH_VEC_ELT (exprs, i, expr)
2014 if (!valid_in_sets (set, NULL, expr))
2015 bitmap_remove_from_set (set, expr);
2017 exprs.release ();
2020 /* Clean the set of expressions that are no longer valid in SET because
2021 they are clobbered in BLOCK or because they trap and may not be executed. */
2023 static void
2024 prune_clobbered_mems (bitmap_set_t set, basic_block block)
2026 bitmap_iterator bi;
2027 unsigned i;
2028 pre_expr to_remove = NULL;
2030 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2032 /* Remove queued expr. */
2033 if (to_remove)
2035 bitmap_remove_from_set (set, to_remove);
2036 to_remove = NULL;
2039 pre_expr expr = expression_for_id (i);
2040 if (expr->kind == REFERENCE)
2042 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2043 if (ref->vuse)
2045 gimple *def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
2046 if (!gimple_nop_p (def_stmt)
2047 && ((gimple_bb (def_stmt) != block
2048 && !dominated_by_p (CDI_DOMINATORS,
2049 block, gimple_bb (def_stmt)))
2050 || (gimple_bb (def_stmt) == block
2051 && value_dies_in_block_x (expr, block))))
2052 to_remove = expr;
2055 else if (expr->kind == NARY)
2057 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2058 /* If the NARY may trap make sure the block does not contain
2059 a possible exit point.
2060 ??? This is overly conservative if we translate AVAIL_OUT
2061 as the available expression might be after the exit point. */
2062 if (BB_MAY_NOTRETURN (block)
2063 && vn_nary_may_trap (nary))
2064 to_remove = expr;
2068 /* Remove queued expr. */
2069 if (to_remove)
2070 bitmap_remove_from_set (set, to_remove);
2073 static sbitmap has_abnormal_preds;
2075 /* Compute the ANTIC set for BLOCK.
2077 If succs(BLOCK) > 1 then
2078 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2079 else if succs(BLOCK) == 1 then
2080 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2082 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2085 static bool
2086 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2088 bool changed = false;
2089 bitmap_set_t S, old, ANTIC_OUT;
2090 bitmap_iterator bi;
2091 unsigned int bii;
2092 edge e;
2093 edge_iterator ei;
2094 bool was_visited = BB_VISITED (block);
2096 old = ANTIC_OUT = S = NULL;
2097 BB_VISITED (block) = 1;
2099 /* If any edges from predecessors are abnormal, antic_in is empty,
2100 so do nothing. */
2101 if (block_has_abnormal_pred_edge)
2102 goto maybe_dump_sets;
2104 old = ANTIC_IN (block);
2105 ANTIC_OUT = bitmap_set_new ();
2107 /* If the block has no successors, ANTIC_OUT is empty. */
2108 if (EDGE_COUNT (block->succs) == 0)
2110 /* If we have one successor, we could have some phi nodes to
2111 translate through. */
2112 else if (single_succ_p (block))
2114 basic_block succ_bb = single_succ (block);
2115 gcc_assert (BB_VISITED (succ_bb));
2116 phi_translate_set (ANTIC_OUT, ANTIC_IN (succ_bb), block, succ_bb);
2118 /* If we have multiple successors, we take the intersection of all of
2119 them. Note that in the case of loop exit phi nodes, we may have
2120 phis to translate through. */
2121 else
2123 size_t i;
2124 basic_block bprime, first = NULL;
2126 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2127 FOR_EACH_EDGE (e, ei, block->succs)
2129 if (!first
2130 && BB_VISITED (e->dest))
2131 first = e->dest;
2132 else if (BB_VISITED (e->dest))
2133 worklist.quick_push (e->dest);
2134 else
2136 /* Unvisited successors get their ANTIC_IN replaced by the
2137 maximal set to arrive at a maximum ANTIC_IN solution.
2138 We can ignore them in the intersection operation and thus
2139 need not explicitely represent that maximum solution. */
2140 if (dump_file && (dump_flags & TDF_DETAILS))
2141 fprintf (dump_file, "ANTIC_IN is MAX on %d->%d\n",
2142 e->src->index, e->dest->index);
2146 /* Of multiple successors we have to have visited one already
2147 which is guaranteed by iteration order. */
2148 gcc_assert (first != NULL);
2150 phi_translate_set (ANTIC_OUT, ANTIC_IN (first), block, first);
2152 FOR_EACH_VEC_ELT (worklist, i, bprime)
2154 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2156 bitmap_set_t tmp = bitmap_set_new ();
2157 phi_translate_set (tmp, ANTIC_IN (bprime), block, bprime);
2158 bitmap_set_and (ANTIC_OUT, tmp);
2159 bitmap_set_free (tmp);
2161 else
2162 bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2166 /* Prune expressions that are clobbered in block and thus become
2167 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2168 prune_clobbered_mems (ANTIC_OUT, block);
2170 /* Generate ANTIC_OUT - TMP_GEN. */
2171 S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2173 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2174 ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2175 TMP_GEN (block));
2177 /* Then union in the ANTIC_OUT - TMP_GEN values,
2178 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2179 FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2180 bitmap_value_insert_into_set (ANTIC_IN (block),
2181 expression_for_id (bii));
2183 clean (ANTIC_IN (block));
2185 if (!was_visited || !bitmap_set_equal (old, ANTIC_IN (block)))
2186 changed = true;
2188 maybe_dump_sets:
2189 if (dump_file && (dump_flags & TDF_DETAILS))
2191 if (ANTIC_OUT)
2192 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2194 if (changed)
2195 fprintf (dump_file, "[changed] ");
2196 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2197 block->index);
2199 if (S)
2200 print_bitmap_set (dump_file, S, "S", block->index);
2202 if (old)
2203 bitmap_set_free (old);
2204 if (S)
2205 bitmap_set_free (S);
2206 if (ANTIC_OUT)
2207 bitmap_set_free (ANTIC_OUT);
2208 return changed;
2211 /* Compute PARTIAL_ANTIC for BLOCK.
2213 If succs(BLOCK) > 1 then
2214 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2215 in ANTIC_OUT for all succ(BLOCK)
2216 else if succs(BLOCK) == 1 then
2217 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2219 PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2220 - ANTIC_IN[BLOCK])
2223 static void
2224 compute_partial_antic_aux (basic_block block,
2225 bool block_has_abnormal_pred_edge)
2227 bitmap_set_t old_PA_IN;
2228 bitmap_set_t PA_OUT;
2229 edge e;
2230 edge_iterator ei;
2231 unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2233 old_PA_IN = PA_OUT = NULL;
2235 /* If any edges from predecessors are abnormal, antic_in is empty,
2236 so do nothing. */
2237 if (block_has_abnormal_pred_edge)
2238 goto maybe_dump_sets;
2240 /* If there are too many partially anticipatable values in the
2241 block, phi_translate_set can take an exponential time: stop
2242 before the translation starts. */
2243 if (max_pa
2244 && single_succ_p (block)
2245 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2246 goto maybe_dump_sets;
2248 old_PA_IN = PA_IN (block);
2249 PA_OUT = bitmap_set_new ();
2251 /* If the block has no successors, ANTIC_OUT is empty. */
2252 if (EDGE_COUNT (block->succs) == 0)
2254 /* If we have one successor, we could have some phi nodes to
2255 translate through. Note that we can't phi translate across DFS
2256 back edges in partial antic, because it uses a union operation on
2257 the successors. For recurrences like IV's, we will end up
2258 generating a new value in the set on each go around (i + 3 (VH.1)
2259 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2260 else if (single_succ_p (block))
2262 basic_block succ = single_succ (block);
2263 if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2264 phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2266 /* If we have multiple successors, we take the union of all of
2267 them. */
2268 else
2270 size_t i;
2271 basic_block bprime;
2273 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2274 FOR_EACH_EDGE (e, ei, block->succs)
2276 if (e->flags & EDGE_DFS_BACK)
2277 continue;
2278 worklist.quick_push (e->dest);
2280 if (worklist.length () > 0)
2282 FOR_EACH_VEC_ELT (worklist, i, bprime)
2284 unsigned int i;
2285 bitmap_iterator bi;
2287 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2288 bitmap_value_insert_into_set (PA_OUT,
2289 expression_for_id (i));
2290 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2292 bitmap_set_t pa_in = bitmap_set_new ();
2293 phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2294 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2295 bitmap_value_insert_into_set (PA_OUT,
2296 expression_for_id (i));
2297 bitmap_set_free (pa_in);
2299 else
2300 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2301 bitmap_value_insert_into_set (PA_OUT,
2302 expression_for_id (i));
2307 /* Prune expressions that are clobbered in block and thus become
2308 invalid if translated from PA_OUT to PA_IN. */
2309 prune_clobbered_mems (PA_OUT, block);
2311 /* PA_IN starts with PA_OUT - TMP_GEN.
2312 Then we subtract things from ANTIC_IN. */
2313 PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2315 /* For partial antic, we want to put back in the phi results, since
2316 we will properly avoid making them partially antic over backedges. */
2317 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2318 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2320 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2321 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2323 dependent_clean (PA_IN (block), ANTIC_IN (block));
2325 maybe_dump_sets:
2326 if (dump_file && (dump_flags & TDF_DETAILS))
2328 if (PA_OUT)
2329 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2331 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2333 if (old_PA_IN)
2334 bitmap_set_free (old_PA_IN);
2335 if (PA_OUT)
2336 bitmap_set_free (PA_OUT);
2339 /* Compute ANTIC and partial ANTIC sets. */
2341 static void
2342 compute_antic (void)
2344 bool changed = true;
2345 int num_iterations = 0;
2346 basic_block block;
2347 int i;
2348 edge_iterator ei;
2349 edge e;
2351 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2352 We pre-build the map of blocks with incoming abnormal edges here. */
2353 has_abnormal_preds = sbitmap_alloc (last_basic_block_for_fn (cfun));
2354 bitmap_clear (has_abnormal_preds);
2356 FOR_ALL_BB_FN (block, cfun)
2358 BB_VISITED (block) = 0;
2360 FOR_EACH_EDGE (e, ei, block->preds)
2361 if (e->flags & EDGE_ABNORMAL)
2363 bitmap_set_bit (has_abnormal_preds, block->index);
2365 /* We also anticipate nothing. */
2366 BB_VISITED (block) = 1;
2367 break;
2370 /* While we are here, give empty ANTIC_IN sets to each block. */
2371 ANTIC_IN (block) = bitmap_set_new ();
2372 if (do_partial_partial)
2373 PA_IN (block) = bitmap_set_new ();
2376 /* At the exit block we anticipate nothing. */
2377 BB_VISITED (EXIT_BLOCK_PTR_FOR_FN (cfun)) = 1;
2379 /* For ANTIC computation we need a postorder that also guarantees that
2380 a block with a single successor is visited after its successor.
2381 RPO on the inverted CFG has this property. */
2382 int *postorder = XNEWVEC (int, n_basic_blocks_for_fn (cfun));
2383 int postorder_num = inverted_post_order_compute (postorder);
2385 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
2386 bitmap_ones (worklist);
2387 while (changed)
2389 if (dump_file && (dump_flags & TDF_DETAILS))
2390 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2391 /* ??? We need to clear our PHI translation cache here as the
2392 ANTIC sets shrink and we restrict valid translations to
2393 those having operands with leaders in ANTIC. Same below
2394 for PA ANTIC computation. */
2395 num_iterations++;
2396 changed = false;
2397 for (i = postorder_num - 1; i >= 0; i--)
2399 if (bitmap_bit_p (worklist, postorder[i]))
2401 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2402 bitmap_clear_bit (worklist, block->index);
2403 if (compute_antic_aux (block,
2404 bitmap_bit_p (has_abnormal_preds,
2405 block->index)))
2407 FOR_EACH_EDGE (e, ei, block->preds)
2408 bitmap_set_bit (worklist, e->src->index);
2409 changed = true;
2413 /* Theoretically possible, but *highly* unlikely. */
2414 gcc_checking_assert (num_iterations < 500);
2417 statistics_histogram_event (cfun, "compute_antic iterations",
2418 num_iterations);
2420 if (do_partial_partial)
2422 /* For partial antic we ignore backedges and thus we do not need
2423 to perform any iteration when we process blocks in postorder. */
2424 postorder_num = pre_and_rev_post_order_compute (NULL, postorder, false);
2425 for (i = postorder_num - 1 ; i >= 0; i--)
2427 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2428 compute_partial_antic_aux (block,
2429 bitmap_bit_p (has_abnormal_preds,
2430 block->index));
2434 sbitmap_free (has_abnormal_preds);
2435 free (postorder);
2439 /* Inserted expressions are placed onto this worklist, which is used
2440 for performing quick dead code elimination of insertions we made
2441 that didn't turn out to be necessary. */
2442 static bitmap inserted_exprs;
2444 /* The actual worker for create_component_ref_by_pieces. */
2446 static tree
2447 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2448 unsigned int *operand, gimple_seq *stmts)
2450 vn_reference_op_t currop = &ref->operands[*operand];
2451 tree genop;
2452 ++*operand;
2453 switch (currop->opcode)
2455 case CALL_EXPR:
2456 gcc_unreachable ();
2458 case MEM_REF:
2460 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2461 stmts);
2462 if (!baseop)
2463 return NULL_TREE;
2464 tree offset = currop->op0;
2465 if (TREE_CODE (baseop) == ADDR_EXPR
2466 && handled_component_p (TREE_OPERAND (baseop, 0)))
2468 HOST_WIDE_INT off;
2469 tree base;
2470 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2471 &off);
2472 gcc_assert (base);
2473 offset = int_const_binop (PLUS_EXPR, offset,
2474 build_int_cst (TREE_TYPE (offset),
2475 off));
2476 baseop = build_fold_addr_expr (base);
2478 genop = build2 (MEM_REF, currop->type, baseop, offset);
2479 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2480 MR_DEPENDENCE_BASE (genop) = currop->base;
2481 REF_REVERSE_STORAGE_ORDER (genop) = currop->reverse;
2482 return genop;
2485 case TARGET_MEM_REF:
2487 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2488 vn_reference_op_t nextop = &ref->operands[++*operand];
2489 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2490 stmts);
2491 if (!baseop)
2492 return NULL_TREE;
2493 if (currop->op0)
2495 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2496 if (!genop0)
2497 return NULL_TREE;
2499 if (nextop->op0)
2501 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2502 if (!genop1)
2503 return NULL_TREE;
2505 genop = build5 (TARGET_MEM_REF, currop->type,
2506 baseop, currop->op2, genop0, currop->op1, genop1);
2508 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2509 MR_DEPENDENCE_BASE (genop) = currop->base;
2510 return genop;
2513 case ADDR_EXPR:
2514 if (currop->op0)
2516 gcc_assert (is_gimple_min_invariant (currop->op0));
2517 return currop->op0;
2519 /* Fallthrough. */
2520 case REALPART_EXPR:
2521 case IMAGPART_EXPR:
2522 case VIEW_CONVERT_EXPR:
2524 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2525 stmts);
2526 if (!genop0)
2527 return NULL_TREE;
2528 return fold_build1 (currop->opcode, currop->type, genop0);
2531 case WITH_SIZE_EXPR:
2533 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2534 stmts);
2535 if (!genop0)
2536 return NULL_TREE;
2537 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2538 if (!genop1)
2539 return NULL_TREE;
2540 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2543 case BIT_FIELD_REF:
2545 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2546 stmts);
2547 if (!genop0)
2548 return NULL_TREE;
2549 tree op1 = currop->op0;
2550 tree op2 = currop->op1;
2551 tree t = build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2552 REF_REVERSE_STORAGE_ORDER (t) = currop->reverse;
2553 return fold (t);
2556 /* For array ref vn_reference_op's, operand 1 of the array ref
2557 is op0 of the reference op and operand 3 of the array ref is
2558 op1. */
2559 case ARRAY_RANGE_REF:
2560 case ARRAY_REF:
2562 tree genop0;
2563 tree genop1 = currop->op0;
2564 tree genop2 = currop->op1;
2565 tree genop3 = currop->op2;
2566 genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2567 stmts);
2568 if (!genop0)
2569 return NULL_TREE;
2570 genop1 = find_or_generate_expression (block, genop1, stmts);
2571 if (!genop1)
2572 return NULL_TREE;
2573 if (genop2)
2575 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2576 /* Drop zero minimum index if redundant. */
2577 if (integer_zerop (genop2)
2578 && (!domain_type
2579 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2580 genop2 = NULL_TREE;
2581 else
2583 genop2 = find_or_generate_expression (block, genop2, stmts);
2584 if (!genop2)
2585 return NULL_TREE;
2588 if (genop3)
2590 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2591 /* We can't always put a size in units of the element alignment
2592 here as the element alignment may be not visible. See
2593 PR43783. Simply drop the element size for constant
2594 sizes. */
2595 if (TREE_CODE (genop3) == INTEGER_CST
2596 && TREE_CODE (TYPE_SIZE_UNIT (elmt_type)) == INTEGER_CST
2597 && wi::eq_p (wi::to_offset (TYPE_SIZE_UNIT (elmt_type)),
2598 (wi::to_offset (genop3)
2599 * vn_ref_op_align_unit (currop))))
2600 genop3 = NULL_TREE;
2601 else
2603 genop3 = find_or_generate_expression (block, genop3, stmts);
2604 if (!genop3)
2605 return NULL_TREE;
2608 return build4 (currop->opcode, currop->type, genop0, genop1,
2609 genop2, genop3);
2611 case COMPONENT_REF:
2613 tree op0;
2614 tree op1;
2615 tree genop2 = currop->op1;
2616 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2617 if (!op0)
2618 return NULL_TREE;
2619 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2620 op1 = currop->op0;
2621 if (genop2)
2623 genop2 = find_or_generate_expression (block, genop2, stmts);
2624 if (!genop2)
2625 return NULL_TREE;
2627 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2630 case SSA_NAME:
2632 genop = find_or_generate_expression (block, currop->op0, stmts);
2633 return genop;
2635 case STRING_CST:
2636 case INTEGER_CST:
2637 case COMPLEX_CST:
2638 case VECTOR_CST:
2639 case REAL_CST:
2640 case CONSTRUCTOR:
2641 case VAR_DECL:
2642 case PARM_DECL:
2643 case CONST_DECL:
2644 case RESULT_DECL:
2645 case FUNCTION_DECL:
2646 return currop->op0;
2648 default:
2649 gcc_unreachable ();
2653 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2654 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2655 trying to rename aggregates into ssa form directly, which is a no no.
2657 Thus, this routine doesn't create temporaries, it just builds a
2658 single access expression for the array, calling
2659 find_or_generate_expression to build the innermost pieces.
2661 This function is a subroutine of create_expression_by_pieces, and
2662 should not be called on it's own unless you really know what you
2663 are doing. */
2665 static tree
2666 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2667 gimple_seq *stmts)
2669 unsigned int op = 0;
2670 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2673 /* Find a simple leader for an expression, or generate one using
2674 create_expression_by_pieces from a NARY expression for the value.
2675 BLOCK is the basic_block we are looking for leaders in.
2676 OP is the tree expression to find a leader for or generate.
2677 Returns the leader or NULL_TREE on failure. */
2679 static tree
2680 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2682 pre_expr expr = get_or_alloc_expr_for (op);
2683 unsigned int lookfor = get_expr_value_id (expr);
2684 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2685 if (leader)
2687 if (leader->kind == NAME)
2688 return PRE_EXPR_NAME (leader);
2689 else if (leader->kind == CONSTANT)
2690 return PRE_EXPR_CONSTANT (leader);
2692 /* Defer. */
2693 return NULL_TREE;
2696 /* It must be a complex expression, so generate it recursively. Note
2697 that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2698 where the insert algorithm fails to insert a required expression. */
2699 bitmap exprset = value_expressions[lookfor];
2700 bitmap_iterator bi;
2701 unsigned int i;
2702 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2704 pre_expr temp = expression_for_id (i);
2705 /* We cannot insert random REFERENCE expressions at arbitrary
2706 places. We can insert NARYs which eventually re-materializes
2707 its operand values. */
2708 if (temp->kind == NARY)
2709 return create_expression_by_pieces (block, temp, stmts,
2710 get_expr_type (expr));
2713 /* Defer. */
2714 return NULL_TREE;
2717 #define NECESSARY GF_PLF_1
2719 /* Create an expression in pieces, so that we can handle very complex
2720 expressions that may be ANTIC, but not necessary GIMPLE.
2721 BLOCK is the basic block the expression will be inserted into,
2722 EXPR is the expression to insert (in value form)
2723 STMTS is a statement list to append the necessary insertions into.
2725 This function will die if we hit some value that shouldn't be
2726 ANTIC but is (IE there is no leader for it, or its components).
2727 The function returns NULL_TREE in case a different antic expression
2728 has to be inserted first.
2729 This function may also generate expressions that are themselves
2730 partially or fully redundant. Those that are will be either made
2731 fully redundant during the next iteration of insert (for partially
2732 redundant ones), or eliminated by eliminate (for fully redundant
2733 ones). */
2735 static tree
2736 create_expression_by_pieces (basic_block block, pre_expr expr,
2737 gimple_seq *stmts, tree type)
2739 tree name;
2740 tree folded;
2741 gimple_seq forced_stmts = NULL;
2742 unsigned int value_id;
2743 gimple_stmt_iterator gsi;
2744 tree exprtype = type ? type : get_expr_type (expr);
2745 pre_expr nameexpr;
2746 gassign *newstmt;
2748 switch (expr->kind)
2750 /* We may hit the NAME/CONSTANT case if we have to convert types
2751 that value numbering saw through. */
2752 case NAME:
2753 folded = PRE_EXPR_NAME (expr);
2754 if (useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2755 return folded;
2756 break;
2757 case CONSTANT:
2759 folded = PRE_EXPR_CONSTANT (expr);
2760 tree tem = fold_convert (exprtype, folded);
2761 if (is_gimple_min_invariant (tem))
2762 return tem;
2763 break;
2765 case REFERENCE:
2766 if (PRE_EXPR_REFERENCE (expr)->operands[0].opcode == CALL_EXPR)
2768 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2769 unsigned int operand = 1;
2770 vn_reference_op_t currop = &ref->operands[0];
2771 tree sc = NULL_TREE;
2772 tree fn;
2773 if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2774 fn = currop->op0;
2775 else
2776 fn = find_or_generate_expression (block, currop->op0, stmts);
2777 if (!fn)
2778 return NULL_TREE;
2779 if (currop->op1)
2781 sc = find_or_generate_expression (block, currop->op1, stmts);
2782 if (!sc)
2783 return NULL_TREE;
2785 auto_vec<tree> args (ref->operands.length () - 1);
2786 while (operand < ref->operands.length ())
2788 tree arg = create_component_ref_by_pieces_1 (block, ref,
2789 &operand, stmts);
2790 if (!arg)
2791 return NULL_TREE;
2792 args.quick_push (arg);
2794 gcall *call
2795 = gimple_build_call_vec ((TREE_CODE (fn) == FUNCTION_DECL
2796 ? build_fold_addr_expr (fn) : fn), args);
2797 gimple_call_set_with_bounds (call, currop->with_bounds);
2798 if (sc)
2799 gimple_call_set_chain (call, sc);
2800 tree forcedname = make_ssa_name (currop->type);
2801 gimple_call_set_lhs (call, forcedname);
2802 gimple_set_vuse (call, BB_LIVE_VOP_ON_EXIT (block));
2803 gimple_seq_add_stmt_without_update (&forced_stmts, call);
2804 folded = forcedname;
2806 else
2808 folded = create_component_ref_by_pieces (block,
2809 PRE_EXPR_REFERENCE (expr),
2810 stmts);
2811 if (!folded)
2812 return NULL_TREE;
2813 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2814 newstmt = gimple_build_assign (name, folded);
2815 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2816 gimple_set_vuse (newstmt, BB_LIVE_VOP_ON_EXIT (block));
2817 folded = name;
2819 break;
2820 case NARY:
2822 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2823 tree *genop = XALLOCAVEC (tree, nary->length);
2824 unsigned i;
2825 for (i = 0; i < nary->length; ++i)
2827 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2828 if (!genop[i])
2829 return NULL_TREE;
2830 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2831 may have conversions stripped. */
2832 if (nary->opcode == POINTER_PLUS_EXPR)
2834 if (i == 0)
2835 genop[i] = gimple_convert (&forced_stmts,
2836 nary->type, genop[i]);
2837 else if (i == 1)
2838 genop[i] = gimple_convert (&forced_stmts,
2839 sizetype, genop[i]);
2841 else
2842 genop[i] = gimple_convert (&forced_stmts,
2843 TREE_TYPE (nary->op[i]), genop[i]);
2845 if (nary->opcode == CONSTRUCTOR)
2847 vec<constructor_elt, va_gc> *elts = NULL;
2848 for (i = 0; i < nary->length; ++i)
2849 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2850 folded = build_constructor (nary->type, elts);
2851 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2852 newstmt = gimple_build_assign (name, folded);
2853 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2854 folded = name;
2856 else
2858 switch (nary->length)
2860 case 1:
2861 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2862 genop[0]);
2863 break;
2864 case 2:
2865 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2866 genop[0], genop[1]);
2867 break;
2868 case 3:
2869 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2870 genop[0], genop[1], genop[2]);
2871 break;
2872 default:
2873 gcc_unreachable ();
2877 break;
2878 default:
2879 gcc_unreachable ();
2882 folded = gimple_convert (&forced_stmts, exprtype, folded);
2884 /* If there is nothing to insert, return the simplified result. */
2885 if (gimple_seq_empty_p (forced_stmts))
2886 return folded;
2887 /* If we simplified to a constant return it and discard eventually
2888 built stmts. */
2889 if (is_gimple_min_invariant (folded))
2891 gimple_seq_discard (forced_stmts);
2892 return folded;
2894 /* Likewise if we simplified to sth not queued for insertion. */
2895 bool found = false;
2896 gsi = gsi_last (forced_stmts);
2897 for (; !gsi_end_p (gsi); gsi_prev (&gsi))
2899 gimple *stmt = gsi_stmt (gsi);
2900 tree forcedname = gimple_get_lhs (stmt);
2901 if (forcedname == folded)
2903 found = true;
2904 break;
2907 if (! found)
2909 gimple_seq_discard (forced_stmts);
2910 return folded;
2912 gcc_assert (TREE_CODE (folded) == SSA_NAME);
2914 /* If we have any intermediate expressions to the value sets, add them
2915 to the value sets and chain them in the instruction stream. */
2916 if (forced_stmts)
2918 gsi = gsi_start (forced_stmts);
2919 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2921 gimple *stmt = gsi_stmt (gsi);
2922 tree forcedname = gimple_get_lhs (stmt);
2923 pre_expr nameexpr;
2925 if (forcedname != folded)
2927 VN_INFO_GET (forcedname)->valnum = forcedname;
2928 VN_INFO (forcedname)->value_id = get_next_value_id ();
2929 nameexpr = get_or_alloc_expr_for_name (forcedname);
2930 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2931 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2932 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2935 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2936 gimple_set_plf (stmt, NECESSARY, false);
2938 gimple_seq_add_seq (stmts, forced_stmts);
2941 name = folded;
2943 /* Fold the last statement. */
2944 gsi = gsi_last (*stmts);
2945 if (fold_stmt_inplace (&gsi))
2946 update_stmt (gsi_stmt (gsi));
2948 /* Add a value number to the temporary.
2949 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2950 we are creating the expression by pieces, and this particular piece of
2951 the expression may have been represented. There is no harm in replacing
2952 here. */
2953 value_id = get_expr_value_id (expr);
2954 VN_INFO_GET (name)->value_id = value_id;
2955 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2956 if (VN_INFO (name)->valnum == NULL_TREE)
2957 VN_INFO (name)->valnum = name;
2958 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2959 nameexpr = get_or_alloc_expr_for_name (name);
2960 add_to_value (value_id, nameexpr);
2961 if (NEW_SETS (block))
2962 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2963 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2965 pre_stats.insertions++;
2966 if (dump_file && (dump_flags & TDF_DETAILS))
2968 fprintf (dump_file, "Inserted ");
2969 print_gimple_stmt (dump_file, gsi_stmt (gsi_last (*stmts)), 0, 0);
2970 fprintf (dump_file, " in predecessor %d (%04d)\n",
2971 block->index, value_id);
2974 return name;
2978 /* Insert the to-be-made-available values of expression EXPRNUM for each
2979 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
2980 merge the result with a phi node, given the same value number as
2981 NODE. Return true if we have inserted new stuff. */
2983 static bool
2984 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
2985 vec<pre_expr> avail)
2987 pre_expr expr = expression_for_id (exprnum);
2988 pre_expr newphi;
2989 unsigned int val = get_expr_value_id (expr);
2990 edge pred;
2991 bool insertions = false;
2992 bool nophi = false;
2993 basic_block bprime;
2994 pre_expr eprime;
2995 edge_iterator ei;
2996 tree type = get_expr_type (expr);
2997 tree temp;
2998 gphi *phi;
3000 /* Make sure we aren't creating an induction variable. */
3001 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
3003 bool firstinsideloop = false;
3004 bool secondinsideloop = false;
3005 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
3006 EDGE_PRED (block, 0)->src);
3007 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
3008 EDGE_PRED (block, 1)->src);
3009 /* Induction variables only have one edge inside the loop. */
3010 if ((firstinsideloop ^ secondinsideloop)
3011 && expr->kind != REFERENCE)
3013 if (dump_file && (dump_flags & TDF_DETAILS))
3014 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
3015 nophi = true;
3019 /* Make the necessary insertions. */
3020 FOR_EACH_EDGE (pred, ei, block->preds)
3022 gimple_seq stmts = NULL;
3023 tree builtexpr;
3024 bprime = pred->src;
3025 eprime = avail[pred->dest_idx];
3026 builtexpr = create_expression_by_pieces (bprime, eprime,
3027 &stmts, type);
3028 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
3029 if (!gimple_seq_empty_p (stmts))
3031 gsi_insert_seq_on_edge (pred, stmts);
3032 insertions = true;
3034 if (!builtexpr)
3036 /* We cannot insert a PHI node if we failed to insert
3037 on one edge. */
3038 nophi = true;
3039 continue;
3041 if (is_gimple_min_invariant (builtexpr))
3042 avail[pred->dest_idx] = get_or_alloc_expr_for_constant (builtexpr);
3043 else
3044 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
3046 /* If we didn't want a phi node, and we made insertions, we still have
3047 inserted new stuff, and thus return true. If we didn't want a phi node,
3048 and didn't make insertions, we haven't added anything new, so return
3049 false. */
3050 if (nophi && insertions)
3051 return true;
3052 else if (nophi && !insertions)
3053 return false;
3055 /* Now build a phi for the new variable. */
3056 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3057 phi = create_phi_node (temp, block);
3059 gimple_set_plf (phi, NECESSARY, false);
3060 VN_INFO_GET (temp)->value_id = val;
3061 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3062 if (VN_INFO (temp)->valnum == NULL_TREE)
3063 VN_INFO (temp)->valnum = temp;
3064 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3065 FOR_EACH_EDGE (pred, ei, block->preds)
3067 pre_expr ae = avail[pred->dest_idx];
3068 gcc_assert (get_expr_type (ae) == type
3069 || useless_type_conversion_p (type, get_expr_type (ae)));
3070 if (ae->kind == CONSTANT)
3071 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3072 pred, UNKNOWN_LOCATION);
3073 else
3074 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3077 newphi = get_or_alloc_expr_for_name (temp);
3078 add_to_value (val, newphi);
3080 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3081 this insertion, since we test for the existence of this value in PHI_GEN
3082 before proceeding with the partial redundancy checks in insert_aux.
3084 The value may exist in AVAIL_OUT, in particular, it could be represented
3085 by the expression we are trying to eliminate, in which case we want the
3086 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3087 inserted there.
3089 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3090 this block, because if it did, it would have existed in our dominator's
3091 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3094 bitmap_insert_into_set (PHI_GEN (block), newphi);
3095 bitmap_value_replace_in_set (AVAIL_OUT (block),
3096 newphi);
3097 bitmap_insert_into_set (NEW_SETS (block),
3098 newphi);
3100 /* If we insert a PHI node for a conversion of another PHI node
3101 in the same basic-block try to preserve range information.
3102 This is important so that followup loop passes receive optimal
3103 number of iteration analysis results. See PR61743. */
3104 if (expr->kind == NARY
3105 && CONVERT_EXPR_CODE_P (expr->u.nary->opcode)
3106 && TREE_CODE (expr->u.nary->op[0]) == SSA_NAME
3107 && gimple_bb (SSA_NAME_DEF_STMT (expr->u.nary->op[0])) == block
3108 && INTEGRAL_TYPE_P (type)
3109 && INTEGRAL_TYPE_P (TREE_TYPE (expr->u.nary->op[0]))
3110 && (TYPE_PRECISION (type)
3111 >= TYPE_PRECISION (TREE_TYPE (expr->u.nary->op[0])))
3112 && SSA_NAME_RANGE_INFO (expr->u.nary->op[0]))
3114 wide_int min, max;
3115 if (get_range_info (expr->u.nary->op[0], &min, &max) == VR_RANGE
3116 && !wi::neg_p (min, SIGNED)
3117 && !wi::neg_p (max, SIGNED))
3118 /* Just handle extension and sign-changes of all-positive ranges. */
3119 set_range_info (temp,
3120 SSA_NAME_RANGE_TYPE (expr->u.nary->op[0]),
3121 wide_int_storage::from (min, TYPE_PRECISION (type),
3122 TYPE_SIGN (type)),
3123 wide_int_storage::from (max, TYPE_PRECISION (type),
3124 TYPE_SIGN (type)));
3127 if (dump_file && (dump_flags & TDF_DETAILS))
3129 fprintf (dump_file, "Created phi ");
3130 print_gimple_stmt (dump_file, phi, 0, 0);
3131 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3133 pre_stats.phis++;
3134 return true;
3139 /* Perform insertion of partially redundant or hoistable values.
3140 For BLOCK, do the following:
3141 1. Propagate the NEW_SETS of the dominator into the current block.
3142 If the block has multiple predecessors,
3143 2a. Iterate over the ANTIC expressions for the block to see if
3144 any of them are partially redundant.
3145 2b. If so, insert them into the necessary predecessors to make
3146 the expression fully redundant.
3147 2c. Insert a new PHI merging the values of the predecessors.
3148 2d. Insert the new PHI, and the new expressions, into the
3149 NEW_SETS set.
3150 If the block has multiple successors,
3151 3a. Iterate over the ANTIC values for the block to see if
3152 any of them are good candidates for hoisting.
3153 3b. If so, insert expressions computing the values in BLOCK,
3154 and add the new expressions into the NEW_SETS set.
3155 4. Recursively call ourselves on the dominator children of BLOCK.
3157 Steps 1, 2a, and 4 are done by insert_aux. 2b, 2c and 2d are done by
3158 do_pre_regular_insertion and do_partial_insertion. 3a and 3b are
3159 done in do_hoist_insertion.
3162 static bool
3163 do_pre_regular_insertion (basic_block block, basic_block dom)
3165 bool new_stuff = false;
3166 vec<pre_expr> exprs;
3167 pre_expr expr;
3168 auto_vec<pre_expr> avail;
3169 int i;
3171 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3172 avail.safe_grow (EDGE_COUNT (block->preds));
3174 FOR_EACH_VEC_ELT (exprs, i, expr)
3176 if (expr->kind == NARY
3177 || expr->kind == REFERENCE)
3179 unsigned int val;
3180 bool by_some = false;
3181 bool cant_insert = false;
3182 bool all_same = true;
3183 pre_expr first_s = NULL;
3184 edge pred;
3185 basic_block bprime;
3186 pre_expr eprime = NULL;
3187 edge_iterator ei;
3188 pre_expr edoubleprime = NULL;
3189 bool do_insertion = false;
3191 val = get_expr_value_id (expr);
3192 if (bitmap_set_contains_value (PHI_GEN (block), val))
3193 continue;
3194 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3196 if (dump_file && (dump_flags & TDF_DETAILS))
3198 fprintf (dump_file, "Found fully redundant value: ");
3199 print_pre_expr (dump_file, expr);
3200 fprintf (dump_file, "\n");
3202 continue;
3205 FOR_EACH_EDGE (pred, ei, block->preds)
3207 unsigned int vprime;
3209 /* We should never run insertion for the exit block
3210 and so not come across fake pred edges. */
3211 gcc_assert (!(pred->flags & EDGE_FAKE));
3212 bprime = pred->src;
3213 /* We are looking at ANTIC_OUT of bprime. */
3214 eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3215 bprime, block);
3217 /* eprime will generally only be NULL if the
3218 value of the expression, translated
3219 through the PHI for this predecessor, is
3220 undefined. If that is the case, we can't
3221 make the expression fully redundant,
3222 because its value is undefined along a
3223 predecessor path. We can thus break out
3224 early because it doesn't matter what the
3225 rest of the results are. */
3226 if (eprime == NULL)
3228 avail[pred->dest_idx] = NULL;
3229 cant_insert = true;
3230 break;
3233 vprime = get_expr_value_id (eprime);
3234 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3235 vprime);
3236 if (edoubleprime == NULL)
3238 avail[pred->dest_idx] = eprime;
3239 all_same = false;
3241 else
3243 avail[pred->dest_idx] = edoubleprime;
3244 by_some = true;
3245 /* We want to perform insertions to remove a redundancy on
3246 a path in the CFG we want to optimize for speed. */
3247 if (optimize_edge_for_speed_p (pred))
3248 do_insertion = true;
3249 if (first_s == NULL)
3250 first_s = edoubleprime;
3251 else if (!pre_expr_d::equal (first_s, edoubleprime))
3252 all_same = false;
3255 /* If we can insert it, it's not the same value
3256 already existing along every predecessor, and
3257 it's defined by some predecessor, it is
3258 partially redundant. */
3259 if (!cant_insert && !all_same && by_some)
3261 if (!do_insertion)
3263 if (dump_file && (dump_flags & TDF_DETAILS))
3265 fprintf (dump_file, "Skipping partial redundancy for "
3266 "expression ");
3267 print_pre_expr (dump_file, expr);
3268 fprintf (dump_file, " (%04d), no redundancy on to be "
3269 "optimized for speed edge\n", val);
3272 else if (dbg_cnt (treepre_insert))
3274 if (dump_file && (dump_flags & TDF_DETAILS))
3276 fprintf (dump_file, "Found partial redundancy for "
3277 "expression ");
3278 print_pre_expr (dump_file, expr);
3279 fprintf (dump_file, " (%04d)\n",
3280 get_expr_value_id (expr));
3282 if (insert_into_preds_of_block (block,
3283 get_expression_id (expr),
3284 avail))
3285 new_stuff = true;
3288 /* If all edges produce the same value and that value is
3289 an invariant, then the PHI has the same value on all
3290 edges. Note this. */
3291 else if (!cant_insert && all_same)
3293 gcc_assert (edoubleprime->kind == CONSTANT
3294 || edoubleprime->kind == NAME);
3296 tree temp = make_temp_ssa_name (get_expr_type (expr),
3297 NULL, "pretmp");
3298 gassign *assign
3299 = gimple_build_assign (temp,
3300 edoubleprime->kind == CONSTANT ?
3301 PRE_EXPR_CONSTANT (edoubleprime) :
3302 PRE_EXPR_NAME (edoubleprime));
3303 gimple_stmt_iterator gsi = gsi_after_labels (block);
3304 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3306 gimple_set_plf (assign, NECESSARY, false);
3307 VN_INFO_GET (temp)->value_id = val;
3308 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3309 if (VN_INFO (temp)->valnum == NULL_TREE)
3310 VN_INFO (temp)->valnum = temp;
3311 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3312 pre_expr newe = get_or_alloc_expr_for_name (temp);
3313 add_to_value (val, newe);
3314 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3315 bitmap_insert_into_set (NEW_SETS (block), newe);
3320 exprs.release ();
3321 return new_stuff;
3325 /* Perform insertion for partially anticipatable expressions. There
3326 is only one case we will perform insertion for these. This case is
3327 if the expression is partially anticipatable, and fully available.
3328 In this case, we know that putting it earlier will enable us to
3329 remove the later computation. */
3331 static bool
3332 do_pre_partial_partial_insertion (basic_block block, basic_block dom)
3334 bool new_stuff = false;
3335 vec<pre_expr> exprs;
3336 pre_expr expr;
3337 auto_vec<pre_expr> avail;
3338 int i;
3340 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3341 avail.safe_grow (EDGE_COUNT (block->preds));
3343 FOR_EACH_VEC_ELT (exprs, i, expr)
3345 if (expr->kind == NARY
3346 || expr->kind == REFERENCE)
3348 unsigned int val;
3349 bool by_all = true;
3350 bool cant_insert = false;
3351 edge pred;
3352 basic_block bprime;
3353 pre_expr eprime = NULL;
3354 edge_iterator ei;
3356 val = get_expr_value_id (expr);
3357 if (bitmap_set_contains_value (PHI_GEN (block), val))
3358 continue;
3359 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3360 continue;
3362 FOR_EACH_EDGE (pred, ei, block->preds)
3364 unsigned int vprime;
3365 pre_expr edoubleprime;
3367 /* We should never run insertion for the exit block
3368 and so not come across fake pred edges. */
3369 gcc_assert (!(pred->flags & EDGE_FAKE));
3370 bprime = pred->src;
3371 eprime = phi_translate (expr, ANTIC_IN (block),
3372 PA_IN (block),
3373 bprime, block);
3375 /* eprime will generally only be NULL if the
3376 value of the expression, translated
3377 through the PHI for this predecessor, is
3378 undefined. If that is the case, we can't
3379 make the expression fully redundant,
3380 because its value is undefined along a
3381 predecessor path. We can thus break out
3382 early because it doesn't matter what the
3383 rest of the results are. */
3384 if (eprime == NULL)
3386 avail[pred->dest_idx] = NULL;
3387 cant_insert = true;
3388 break;
3391 vprime = get_expr_value_id (eprime);
3392 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3393 avail[pred->dest_idx] = edoubleprime;
3394 if (edoubleprime == NULL)
3396 by_all = false;
3397 break;
3401 /* If we can insert it, it's not the same value
3402 already existing along every predecessor, and
3403 it's defined by some predecessor, it is
3404 partially redundant. */
3405 if (!cant_insert && by_all)
3407 edge succ;
3408 bool do_insertion = false;
3410 /* Insert only if we can remove a later expression on a path
3411 that we want to optimize for speed.
3412 The phi node that we will be inserting in BLOCK is not free,
3413 and inserting it for the sake of !optimize_for_speed successor
3414 may cause regressions on the speed path. */
3415 FOR_EACH_EDGE (succ, ei, block->succs)
3417 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3418 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3420 if (optimize_edge_for_speed_p (succ))
3421 do_insertion = true;
3425 if (!do_insertion)
3427 if (dump_file && (dump_flags & TDF_DETAILS))
3429 fprintf (dump_file, "Skipping partial partial redundancy "
3430 "for expression ");
3431 print_pre_expr (dump_file, expr);
3432 fprintf (dump_file, " (%04d), not (partially) anticipated "
3433 "on any to be optimized for speed edges\n", val);
3436 else if (dbg_cnt (treepre_insert))
3438 pre_stats.pa_insert++;
3439 if (dump_file && (dump_flags & TDF_DETAILS))
3441 fprintf (dump_file, "Found partial partial redundancy "
3442 "for expression ");
3443 print_pre_expr (dump_file, expr);
3444 fprintf (dump_file, " (%04d)\n",
3445 get_expr_value_id (expr));
3447 if (insert_into_preds_of_block (block,
3448 get_expression_id (expr),
3449 avail))
3450 new_stuff = true;
3456 exprs.release ();
3457 return new_stuff;
3460 /* Insert expressions in BLOCK to compute hoistable values up.
3461 Return TRUE if something was inserted, otherwise return FALSE.
3462 The caller has to make sure that BLOCK has at least two successors. */
3464 static bool
3465 do_hoist_insertion (basic_block block)
3467 edge e;
3468 edge_iterator ei;
3469 bool new_stuff = false;
3470 unsigned i;
3471 gimple_stmt_iterator last;
3473 /* At least two successors, or else... */
3474 gcc_assert (EDGE_COUNT (block->succs) >= 2);
3476 /* Check that all successors of BLOCK are dominated by block.
3477 We could use dominated_by_p() for this, but actually there is a much
3478 quicker check: any successor that is dominated by BLOCK can't have
3479 more than one predecessor edge. */
3480 FOR_EACH_EDGE (e, ei, block->succs)
3481 if (! single_pred_p (e->dest))
3482 return false;
3484 /* Determine the insertion point. If we cannot safely insert before
3485 the last stmt if we'd have to, bail out. */
3486 last = gsi_last_bb (block);
3487 if (!gsi_end_p (last)
3488 && !is_ctrl_stmt (gsi_stmt (last))
3489 && stmt_ends_bb_p (gsi_stmt (last)))
3490 return false;
3492 /* Compute the set of hoistable expressions from ANTIC_IN. First compute
3493 hoistable values. */
3494 bitmap_set hoistable_set;
3496 /* A hoistable value must be in ANTIC_IN(block)
3497 but not in AVAIL_OUT(BLOCK). */
3498 bitmap_initialize (&hoistable_set.values, &grand_bitmap_obstack);
3499 bitmap_and_compl (&hoistable_set.values,
3500 &ANTIC_IN (block)->values, &AVAIL_OUT (block)->values);
3502 /* Short-cut for a common case: hoistable_set is empty. */
3503 if (bitmap_empty_p (&hoistable_set.values))
3504 return false;
3506 /* Compute which of the hoistable values is in AVAIL_OUT of
3507 at least one of the successors of BLOCK. */
3508 bitmap_head availout_in_some;
3509 bitmap_initialize (&availout_in_some, &grand_bitmap_obstack);
3510 FOR_EACH_EDGE (e, ei, block->succs)
3511 /* Do not consider expressions solely because their availability
3512 on loop exits. They'd be ANTIC-IN throughout the whole loop
3513 and thus effectively hoisted across loops by combination of
3514 PRE and hoisting. */
3515 if (! loop_exit_edge_p (block->loop_father, e))
3516 bitmap_ior_and_into (&availout_in_some, &hoistable_set.values,
3517 &AVAIL_OUT (e->dest)->values);
3518 bitmap_clear (&hoistable_set.values);
3520 /* Short-cut for a common case: availout_in_some is empty. */
3521 if (bitmap_empty_p (&availout_in_some))
3522 return false;
3524 /* Hack hoitable_set in-place so we can use sorted_array_from_bitmap_set. */
3525 hoistable_set.values = availout_in_some;
3526 hoistable_set.expressions = ANTIC_IN (block)->expressions;
3528 /* Now finally construct the topological-ordered expression set. */
3529 vec<pre_expr> exprs = sorted_array_from_bitmap_set (&hoistable_set);
3531 bitmap_clear (&hoistable_set.values);
3533 /* If there are candidate values for hoisting, insert expressions
3534 strategically to make the hoistable expressions fully redundant. */
3535 pre_expr expr;
3536 FOR_EACH_VEC_ELT (exprs, i, expr)
3538 /* While we try to sort expressions topologically above the
3539 sorting doesn't work out perfectly. Catch expressions we
3540 already inserted. */
3541 unsigned int value_id = get_expr_value_id (expr);
3542 if (bitmap_set_contains_value (AVAIL_OUT (block), value_id))
3544 if (dump_file && (dump_flags & TDF_DETAILS))
3546 fprintf (dump_file,
3547 "Already inserted expression for ");
3548 print_pre_expr (dump_file, expr);
3549 fprintf (dump_file, " (%04d)\n", value_id);
3551 continue;
3554 /* OK, we should hoist this value. Perform the transformation. */
3555 pre_stats.hoist_insert++;
3556 if (dump_file && (dump_flags & TDF_DETAILS))
3558 fprintf (dump_file,
3559 "Inserting expression in block %d for code hoisting: ",
3560 block->index);
3561 print_pre_expr (dump_file, expr);
3562 fprintf (dump_file, " (%04d)\n", value_id);
3565 gimple_seq stmts = NULL;
3566 tree res = create_expression_by_pieces (block, expr, &stmts,
3567 get_expr_type (expr));
3569 /* Do not return true if expression creation ultimately
3570 did not insert any statements. */
3571 if (gimple_seq_empty_p (stmts))
3572 res = NULL_TREE;
3573 else
3575 if (gsi_end_p (last) || is_ctrl_stmt (gsi_stmt (last)))
3576 gsi_insert_seq_before (&last, stmts, GSI_SAME_STMT);
3577 else
3578 gsi_insert_seq_after (&last, stmts, GSI_NEW_STMT);
3581 /* Make sure to not return true if expression creation ultimately
3582 failed but also make sure to insert any stmts produced as they
3583 are tracked in inserted_exprs. */
3584 if (! res)
3585 continue;
3587 new_stuff = true;
3590 exprs.release ();
3592 return new_stuff;
3595 /* Do a dominator walk on the control flow graph, and insert computations
3596 of values as necessary for PRE and hoisting. */
3598 static bool
3599 insert_aux (basic_block block, bool do_pre, bool do_hoist)
3601 basic_block son;
3602 bool new_stuff = false;
3604 if (block)
3606 basic_block dom;
3607 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3608 if (dom)
3610 unsigned i;
3611 bitmap_iterator bi;
3612 bitmap_set_t newset;
3614 /* First, update the AVAIL_OUT set with anything we may have
3615 inserted higher up in the dominator tree. */
3616 newset = NEW_SETS (dom);
3617 if (newset)
3619 /* Note that we need to value_replace both NEW_SETS, and
3620 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3621 represented by some non-simple expression here that we want
3622 to replace it with. */
3623 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3625 pre_expr expr = expression_for_id (i);
3626 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3627 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3631 /* Insert expressions for partial redundancies. */
3632 if (do_pre && !single_pred_p (block))
3634 new_stuff |= do_pre_regular_insertion (block, dom);
3635 if (do_partial_partial)
3636 new_stuff |= do_pre_partial_partial_insertion (block, dom);
3639 /* Insert expressions for hoisting. */
3640 if (do_hoist && EDGE_COUNT (block->succs) >= 2)
3641 new_stuff |= do_hoist_insertion (block);
3644 for (son = first_dom_son (CDI_DOMINATORS, block);
3645 son;
3646 son = next_dom_son (CDI_DOMINATORS, son))
3648 new_stuff |= insert_aux (son, do_pre, do_hoist);
3651 return new_stuff;
3654 /* Perform insertion of partially redundant and hoistable values. */
3656 static void
3657 insert (void)
3659 bool new_stuff = true;
3660 basic_block bb;
3661 int num_iterations = 0;
3663 FOR_ALL_BB_FN (bb, cfun)
3664 NEW_SETS (bb) = bitmap_set_new ();
3666 while (new_stuff)
3668 num_iterations++;
3669 if (dump_file && dump_flags & TDF_DETAILS)
3670 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3671 new_stuff = insert_aux (ENTRY_BLOCK_PTR_FOR_FN (cfun), flag_tree_pre,
3672 flag_code_hoisting);
3674 /* Clear the NEW sets before the next iteration. We have already
3675 fully propagated its contents. */
3676 if (new_stuff)
3677 FOR_ALL_BB_FN (bb, cfun)
3678 bitmap_set_free (NEW_SETS (bb));
3680 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3684 /* Compute the AVAIL set for all basic blocks.
3686 This function performs value numbering of the statements in each basic
3687 block. The AVAIL sets are built from information we glean while doing
3688 this value numbering, since the AVAIL sets contain only one entry per
3689 value.
3691 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3692 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3694 static void
3695 compute_avail (void)
3698 basic_block block, son;
3699 basic_block *worklist;
3700 size_t sp = 0;
3701 unsigned i;
3702 tree name;
3704 /* We pretend that default definitions are defined in the entry block.
3705 This includes function arguments and the static chain decl. */
3706 FOR_EACH_SSA_NAME (i, name, cfun)
3708 pre_expr e;
3709 if (!SSA_NAME_IS_DEFAULT_DEF (name)
3710 || has_zero_uses (name)
3711 || virtual_operand_p (name))
3712 continue;
3714 e = get_or_alloc_expr_for_name (name);
3715 add_to_value (get_expr_value_id (e), e);
3716 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)), e);
3717 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3721 if (dump_file && (dump_flags & TDF_DETAILS))
3723 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3724 "tmp_gen", ENTRY_BLOCK);
3725 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3726 "avail_out", ENTRY_BLOCK);
3729 /* Allocate the worklist. */
3730 worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
3732 /* Seed the algorithm by putting the dominator children of the entry
3733 block on the worklist. */
3734 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
3735 son;
3736 son = next_dom_son (CDI_DOMINATORS, son))
3737 worklist[sp++] = son;
3739 BB_LIVE_VOP_ON_EXIT (ENTRY_BLOCK_PTR_FOR_FN (cfun))
3740 = ssa_default_def (cfun, gimple_vop (cfun));
3742 /* Loop until the worklist is empty. */
3743 while (sp)
3745 gimple *stmt;
3746 basic_block dom;
3748 /* Pick a block from the worklist. */
3749 block = worklist[--sp];
3751 /* Initially, the set of available values in BLOCK is that of
3752 its immediate dominator. */
3753 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3754 if (dom)
3756 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3757 BB_LIVE_VOP_ON_EXIT (block) = BB_LIVE_VOP_ON_EXIT (dom);
3760 /* Generate values for PHI nodes. */
3761 for (gphi_iterator gsi = gsi_start_phis (block); !gsi_end_p (gsi);
3762 gsi_next (&gsi))
3764 tree result = gimple_phi_result (gsi.phi ());
3766 /* We have no need for virtual phis, as they don't represent
3767 actual computations. */
3768 if (virtual_operand_p (result))
3770 BB_LIVE_VOP_ON_EXIT (block) = result;
3771 continue;
3774 pre_expr e = get_or_alloc_expr_for_name (result);
3775 add_to_value (get_expr_value_id (e), e);
3776 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3777 bitmap_insert_into_set (PHI_GEN (block), e);
3780 BB_MAY_NOTRETURN (block) = 0;
3782 /* Now compute value numbers and populate value sets with all
3783 the expressions computed in BLOCK. */
3784 for (gimple_stmt_iterator gsi = gsi_start_bb (block); !gsi_end_p (gsi);
3785 gsi_next (&gsi))
3787 ssa_op_iter iter;
3788 tree op;
3790 stmt = gsi_stmt (gsi);
3792 /* Cache whether the basic-block has any non-visible side-effect
3793 or control flow.
3794 If this isn't a call or it is the last stmt in the
3795 basic-block then the CFG represents things correctly. */
3796 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3798 /* Non-looping const functions always return normally.
3799 Otherwise the call might not return or have side-effects
3800 that forbids hoisting possibly trapping expressions
3801 before it. */
3802 int flags = gimple_call_flags (stmt);
3803 if (!(flags & ECF_CONST)
3804 || (flags & ECF_LOOPING_CONST_OR_PURE))
3805 BB_MAY_NOTRETURN (block) = 1;
3808 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3810 pre_expr e = get_or_alloc_expr_for_name (op);
3812 add_to_value (get_expr_value_id (e), e);
3813 bitmap_insert_into_set (TMP_GEN (block), e);
3814 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3817 if (gimple_vdef (stmt))
3818 BB_LIVE_VOP_ON_EXIT (block) = gimple_vdef (stmt);
3820 if (gimple_has_side_effects (stmt)
3821 || stmt_could_throw_p (stmt)
3822 || is_gimple_debug (stmt))
3823 continue;
3825 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3827 if (ssa_undefined_value_p (op))
3828 continue;
3829 pre_expr e = get_or_alloc_expr_for_name (op);
3830 bitmap_value_insert_into_set (EXP_GEN (block), e);
3833 switch (gimple_code (stmt))
3835 case GIMPLE_RETURN:
3836 continue;
3838 case GIMPLE_CALL:
3840 vn_reference_t ref;
3841 vn_reference_s ref1;
3842 pre_expr result = NULL;
3844 /* We can value number only calls to real functions. */
3845 if (gimple_call_internal_p (stmt))
3846 continue;
3848 vn_reference_lookup_call (as_a <gcall *> (stmt), &ref, &ref1);
3849 if (!ref)
3850 continue;
3852 /* If the value of the call is not invalidated in
3853 this block until it is computed, add the expression
3854 to EXP_GEN. */
3855 if (!gimple_vuse (stmt)
3856 || gimple_code
3857 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3858 || gimple_bb (SSA_NAME_DEF_STMT
3859 (gimple_vuse (stmt))) != block)
3861 result = pre_expr_pool.allocate ();
3862 result->kind = REFERENCE;
3863 result->id = 0;
3864 PRE_EXPR_REFERENCE (result) = ref;
3866 get_or_alloc_expression_id (result);
3867 add_to_value (get_expr_value_id (result), result);
3868 bitmap_value_insert_into_set (EXP_GEN (block), result);
3870 continue;
3873 case GIMPLE_ASSIGN:
3875 pre_expr result = NULL;
3876 switch (vn_get_stmt_kind (stmt))
3878 case VN_NARY:
3880 enum tree_code code = gimple_assign_rhs_code (stmt);
3881 vn_nary_op_t nary;
3883 /* COND_EXPR and VEC_COND_EXPR are awkward in
3884 that they contain an embedded complex expression.
3885 Don't even try to shove those through PRE. */
3886 if (code == COND_EXPR
3887 || code == VEC_COND_EXPR)
3888 continue;
3890 vn_nary_op_lookup_stmt (stmt, &nary);
3891 if (!nary)
3892 continue;
3894 /* If the NARY traps and there was a preceding
3895 point in the block that might not return avoid
3896 adding the nary to EXP_GEN. */
3897 if (BB_MAY_NOTRETURN (block)
3898 && vn_nary_may_trap (nary))
3899 continue;
3901 result = pre_expr_pool.allocate ();
3902 result->kind = NARY;
3903 result->id = 0;
3904 PRE_EXPR_NARY (result) = nary;
3905 break;
3908 case VN_REFERENCE:
3910 tree rhs1 = gimple_assign_rhs1 (stmt);
3911 alias_set_type set = get_alias_set (rhs1);
3912 vec<vn_reference_op_s> operands
3913 = vn_reference_operands_for_lookup (rhs1);
3914 vn_reference_t ref;
3915 vn_reference_lookup_pieces (gimple_vuse (stmt), set,
3916 TREE_TYPE (rhs1),
3917 operands, &ref, VN_WALK);
3918 if (!ref)
3920 operands.release ();
3921 continue;
3924 /* If the value of the reference is not invalidated in
3925 this block until it is computed, add the expression
3926 to EXP_GEN. */
3927 if (gimple_vuse (stmt))
3929 gimple *def_stmt;
3930 bool ok = true;
3931 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3932 while (!gimple_nop_p (def_stmt)
3933 && gimple_code (def_stmt) != GIMPLE_PHI
3934 && gimple_bb (def_stmt) == block)
3936 if (stmt_may_clobber_ref_p
3937 (def_stmt, gimple_assign_rhs1 (stmt)))
3939 ok = false;
3940 break;
3942 def_stmt
3943 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3945 if (!ok)
3947 operands.release ();
3948 continue;
3952 /* If the load was value-numbered to another
3953 load make sure we do not use its expression
3954 for insertion if it wouldn't be a valid
3955 replacement. */
3956 /* At the momemt we have a testcase
3957 for hoist insertion of aligned vs. misaligned
3958 variants in gcc.dg/torture/pr65270-1.c thus
3959 with just alignment to be considered we can
3960 simply replace the expression in the hashtable
3961 with the most conservative one. */
3962 vn_reference_op_t ref1 = &ref->operands.last ();
3963 while (ref1->opcode != TARGET_MEM_REF
3964 && ref1->opcode != MEM_REF
3965 && ref1 != &ref->operands[0])
3966 --ref1;
3967 vn_reference_op_t ref2 = &operands.last ();
3968 while (ref2->opcode != TARGET_MEM_REF
3969 && ref2->opcode != MEM_REF
3970 && ref2 != &operands[0])
3971 --ref2;
3972 if ((ref1->opcode == TARGET_MEM_REF
3973 || ref1->opcode == MEM_REF)
3974 && (TYPE_ALIGN (ref1->type)
3975 > TYPE_ALIGN (ref2->type)))
3976 ref1->type
3977 = build_aligned_type (ref1->type,
3978 TYPE_ALIGN (ref2->type));
3979 /* TBAA behavior is an obvious part so make sure
3980 that the hashtable one covers this as well
3981 by adjusting the ref alias set and its base. */
3982 if (ref->set == set
3983 || alias_set_subset_of (set, ref->set))
3985 else if (alias_set_subset_of (ref->set, set))
3987 ref->set = set;
3988 if (ref1->opcode == MEM_REF)
3989 ref1->op0 = fold_convert (TREE_TYPE (ref2->op0),
3990 ref1->op0);
3991 else
3992 ref1->op2 = fold_convert (TREE_TYPE (ref2->op2),
3993 ref1->op2);
3995 else
3997 ref->set = 0;
3998 if (ref1->opcode == MEM_REF)
3999 ref1->op0 = fold_convert (ptr_type_node,
4000 ref1->op0);
4001 else
4002 ref1->op2 = fold_convert (ptr_type_node,
4003 ref1->op2);
4005 operands.release ();
4007 result = pre_expr_pool.allocate ();
4008 result->kind = REFERENCE;
4009 result->id = 0;
4010 PRE_EXPR_REFERENCE (result) = ref;
4011 break;
4014 default:
4015 continue;
4018 get_or_alloc_expression_id (result);
4019 add_to_value (get_expr_value_id (result), result);
4020 bitmap_value_insert_into_set (EXP_GEN (block), result);
4021 continue;
4023 default:
4024 break;
4028 if (dump_file && (dump_flags & TDF_DETAILS))
4030 print_bitmap_set (dump_file, EXP_GEN (block),
4031 "exp_gen", block->index);
4032 print_bitmap_set (dump_file, PHI_GEN (block),
4033 "phi_gen", block->index);
4034 print_bitmap_set (dump_file, TMP_GEN (block),
4035 "tmp_gen", block->index);
4036 print_bitmap_set (dump_file, AVAIL_OUT (block),
4037 "avail_out", block->index);
4040 /* Put the dominator children of BLOCK on the worklist of blocks
4041 to compute available sets for. */
4042 for (son = first_dom_son (CDI_DOMINATORS, block);
4043 son;
4044 son = next_dom_son (CDI_DOMINATORS, son))
4045 worklist[sp++] = son;
4048 free (worklist);
4052 /* Local state for the eliminate domwalk. */
4053 static vec<gimple *> el_to_remove;
4054 static vec<gimple *> el_to_fixup;
4055 static unsigned int el_todo;
4056 static vec<tree> el_avail;
4057 static vec<tree> el_avail_stack;
4059 /* Return a leader for OP that is available at the current point of the
4060 eliminate domwalk. */
4062 static tree
4063 eliminate_avail (tree op)
4065 tree valnum = VN_INFO (op)->valnum;
4066 if (TREE_CODE (valnum) == SSA_NAME)
4068 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
4069 return valnum;
4070 if (el_avail.length () > SSA_NAME_VERSION (valnum))
4071 return el_avail[SSA_NAME_VERSION (valnum)];
4073 else if (is_gimple_min_invariant (valnum))
4074 return valnum;
4075 return NULL_TREE;
4078 /* At the current point of the eliminate domwalk make OP available. */
4080 static void
4081 eliminate_push_avail (tree op)
4083 tree valnum = VN_INFO (op)->valnum;
4084 if (TREE_CODE (valnum) == SSA_NAME)
4086 if (el_avail.length () <= SSA_NAME_VERSION (valnum))
4087 el_avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1);
4088 tree pushop = op;
4089 if (el_avail[SSA_NAME_VERSION (valnum)])
4090 pushop = el_avail[SSA_NAME_VERSION (valnum)];
4091 el_avail_stack.safe_push (pushop);
4092 el_avail[SSA_NAME_VERSION (valnum)] = op;
4096 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
4097 the leader for the expression if insertion was successful. */
4099 static tree
4100 eliminate_insert (gimple_stmt_iterator *gsi, tree val)
4102 gimple *stmt = gimple_seq_first_stmt (VN_INFO (val)->expr);
4103 if (!is_gimple_assign (stmt)
4104 || (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt))
4105 && gimple_assign_rhs_code (stmt) != VIEW_CONVERT_EXPR
4106 && gimple_assign_rhs_code (stmt) != BIT_FIELD_REF))
4107 return NULL_TREE;
4109 tree op = gimple_assign_rhs1 (stmt);
4110 if (gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR
4111 || gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
4112 op = TREE_OPERAND (op, 0);
4113 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (op) : op;
4114 if (!leader)
4115 return NULL_TREE;
4117 gimple_seq stmts = NULL;
4118 tree res;
4119 if (gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
4120 res = gimple_build (&stmts, BIT_FIELD_REF,
4121 TREE_TYPE (val), leader,
4122 TREE_OPERAND (gimple_assign_rhs1 (stmt), 1),
4123 TREE_OPERAND (gimple_assign_rhs1 (stmt), 2));
4124 else
4125 res = gimple_build (&stmts, gimple_assign_rhs_code (stmt),
4126 TREE_TYPE (val), leader);
4127 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
4128 VN_INFO_GET (res)->valnum = val;
4130 if (TREE_CODE (leader) == SSA_NAME)
4131 gimple_set_plf (SSA_NAME_DEF_STMT (leader), NECESSARY, true);
4133 pre_stats.insertions++;
4134 if (dump_file && (dump_flags & TDF_DETAILS))
4136 fprintf (dump_file, "Inserted ");
4137 print_gimple_stmt (dump_file, SSA_NAME_DEF_STMT (res), 0, 0);
4140 return res;
4143 class eliminate_dom_walker : public dom_walker
4145 public:
4146 eliminate_dom_walker (cdi_direction direction, bool do_pre_)
4147 : dom_walker (direction), do_pre (do_pre_) {}
4149 virtual edge before_dom_children (basic_block);
4150 virtual void after_dom_children (basic_block);
4152 bool do_pre;
4155 /* Perform elimination for the basic-block B during the domwalk. */
4157 edge
4158 eliminate_dom_walker::before_dom_children (basic_block b)
4160 /* Mark new bb. */
4161 el_avail_stack.safe_push (NULL_TREE);
4163 /* ??? If we do nothing for unreachable blocks then this will confuse
4164 tailmerging. Eventually we can reduce its reliance on SCCVN now
4165 that we fully copy/constant-propagate (most) things. */
4167 for (gphi_iterator gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
4169 gphi *phi = gsi.phi ();
4170 tree res = PHI_RESULT (phi);
4172 if (virtual_operand_p (res))
4174 gsi_next (&gsi);
4175 continue;
4178 tree sprime = eliminate_avail (res);
4179 if (sprime
4180 && sprime != res)
4182 if (dump_file && (dump_flags & TDF_DETAILS))
4184 fprintf (dump_file, "Replaced redundant PHI node defining ");
4185 print_generic_expr (dump_file, res, 0);
4186 fprintf (dump_file, " with ");
4187 print_generic_expr (dump_file, sprime, 0);
4188 fprintf (dump_file, "\n");
4191 /* If we inserted this PHI node ourself, it's not an elimination. */
4192 if (inserted_exprs
4193 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
4194 pre_stats.phis--;
4195 else
4196 pre_stats.eliminations++;
4198 /* If we will propagate into all uses don't bother to do
4199 anything. */
4200 if (may_propagate_copy (res, sprime))
4202 /* Mark the PHI for removal. */
4203 el_to_remove.safe_push (phi);
4204 gsi_next (&gsi);
4205 continue;
4208 remove_phi_node (&gsi, false);
4210 if (inserted_exprs
4211 && !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res))
4212 && TREE_CODE (sprime) == SSA_NAME)
4213 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4215 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
4216 sprime = fold_convert (TREE_TYPE (res), sprime);
4217 gimple *stmt = gimple_build_assign (res, sprime);
4218 /* ??? It cannot yet be necessary (DOM walk). */
4219 gimple_set_plf (stmt, NECESSARY, gimple_plf (phi, NECESSARY));
4221 gimple_stmt_iterator gsi2 = gsi_after_labels (b);
4222 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
4223 continue;
4226 eliminate_push_avail (res);
4227 gsi_next (&gsi);
4230 for (gimple_stmt_iterator gsi = gsi_start_bb (b);
4231 !gsi_end_p (gsi);
4232 gsi_next (&gsi))
4234 tree sprime = NULL_TREE;
4235 gimple *stmt = gsi_stmt (gsi);
4236 tree lhs = gimple_get_lhs (stmt);
4237 if (lhs && TREE_CODE (lhs) == SSA_NAME
4238 && !gimple_has_volatile_ops (stmt)
4239 /* See PR43491. Do not replace a global register variable when
4240 it is a the RHS of an assignment. Do replace local register
4241 variables since gcc does not guarantee a local variable will
4242 be allocated in register.
4243 ??? The fix isn't effective here. This should instead
4244 be ensured by not value-numbering them the same but treating
4245 them like volatiles? */
4246 && !(gimple_assign_single_p (stmt)
4247 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == VAR_DECL
4248 && DECL_HARD_REGISTER (gimple_assign_rhs1 (stmt))
4249 && is_global_var (gimple_assign_rhs1 (stmt)))))
4251 sprime = eliminate_avail (lhs);
4252 if (!sprime)
4254 /* If there is no existing usable leader but SCCVN thinks
4255 it has an expression it wants to use as replacement,
4256 insert that. */
4257 tree val = VN_INFO (lhs)->valnum;
4258 if (val != VN_TOP
4259 && TREE_CODE (val) == SSA_NAME
4260 && VN_INFO (val)->needs_insertion
4261 && VN_INFO (val)->expr != NULL
4262 && (sprime = eliminate_insert (&gsi, val)) != NULL_TREE)
4263 eliminate_push_avail (sprime);
4266 /* If this now constitutes a copy duplicate points-to
4267 and range info appropriately. This is especially
4268 important for inserted code. See tree-ssa-copy.c
4269 for similar code. */
4270 if (sprime
4271 && TREE_CODE (sprime) == SSA_NAME)
4273 basic_block sprime_b = gimple_bb (SSA_NAME_DEF_STMT (sprime));
4274 if (POINTER_TYPE_P (TREE_TYPE (lhs))
4275 && VN_INFO_PTR_INFO (lhs)
4276 && ! VN_INFO_PTR_INFO (sprime))
4278 duplicate_ssa_name_ptr_info (sprime,
4279 VN_INFO_PTR_INFO (lhs));
4280 if (b != sprime_b)
4281 mark_ptr_info_alignment_unknown
4282 (SSA_NAME_PTR_INFO (sprime));
4284 else if (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
4285 && VN_INFO_RANGE_INFO (lhs)
4286 && ! VN_INFO_RANGE_INFO (sprime)
4287 && b == sprime_b)
4288 duplicate_ssa_name_range_info (sprime,
4289 VN_INFO_RANGE_TYPE (lhs),
4290 VN_INFO_RANGE_INFO (lhs));
4293 /* Inhibit the use of an inserted PHI on a loop header when
4294 the address of the memory reference is a simple induction
4295 variable. In other cases the vectorizer won't do anything
4296 anyway (either it's loop invariant or a complicated
4297 expression). */
4298 if (sprime
4299 && TREE_CODE (sprime) == SSA_NAME
4300 && do_pre
4301 && (flag_tree_loop_vectorize || flag_tree_parallelize_loops > 1)
4302 && loop_outer (b->loop_father)
4303 && has_zero_uses (sprime)
4304 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))
4305 && gimple_assign_load_p (stmt))
4307 gimple *def_stmt = SSA_NAME_DEF_STMT (sprime);
4308 basic_block def_bb = gimple_bb (def_stmt);
4309 if (gimple_code (def_stmt) == GIMPLE_PHI
4310 && def_bb->loop_father->header == def_bb)
4312 loop_p loop = def_bb->loop_father;
4313 ssa_op_iter iter;
4314 tree op;
4315 bool found = false;
4316 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
4318 affine_iv iv;
4319 def_bb = gimple_bb (SSA_NAME_DEF_STMT (op));
4320 if (def_bb
4321 && flow_bb_inside_loop_p (loop, def_bb)
4322 && simple_iv (loop, loop, op, &iv, true))
4324 found = true;
4325 break;
4328 if (found)
4330 if (dump_file && (dump_flags & TDF_DETAILS))
4332 fprintf (dump_file, "Not replacing ");
4333 print_gimple_expr (dump_file, stmt, 0, 0);
4334 fprintf (dump_file, " with ");
4335 print_generic_expr (dump_file, sprime, 0);
4336 fprintf (dump_file, " which would add a loop"
4337 " carried dependence to loop %d\n",
4338 loop->num);
4340 /* Don't keep sprime available. */
4341 sprime = NULL_TREE;
4346 if (sprime)
4348 /* If we can propagate the value computed for LHS into
4349 all uses don't bother doing anything with this stmt. */
4350 if (may_propagate_copy (lhs, sprime))
4352 /* Mark it for removal. */
4353 el_to_remove.safe_push (stmt);
4355 /* ??? Don't count copy/constant propagations. */
4356 if (gimple_assign_single_p (stmt)
4357 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4358 || gimple_assign_rhs1 (stmt) == sprime))
4359 continue;
4361 if (dump_file && (dump_flags & TDF_DETAILS))
4363 fprintf (dump_file, "Replaced ");
4364 print_gimple_expr (dump_file, stmt, 0, 0);
4365 fprintf (dump_file, " with ");
4366 print_generic_expr (dump_file, sprime, 0);
4367 fprintf (dump_file, " in all uses of ");
4368 print_gimple_stmt (dump_file, stmt, 0, 0);
4371 pre_stats.eliminations++;
4372 continue;
4375 /* If this is an assignment from our leader (which
4376 happens in the case the value-number is a constant)
4377 then there is nothing to do. */
4378 if (gimple_assign_single_p (stmt)
4379 && sprime == gimple_assign_rhs1 (stmt))
4380 continue;
4382 /* Else replace its RHS. */
4383 bool can_make_abnormal_goto
4384 = is_gimple_call (stmt)
4385 && stmt_can_make_abnormal_goto (stmt);
4387 if (dump_file && (dump_flags & TDF_DETAILS))
4389 fprintf (dump_file, "Replaced ");
4390 print_gimple_expr (dump_file, stmt, 0, 0);
4391 fprintf (dump_file, " with ");
4392 print_generic_expr (dump_file, sprime, 0);
4393 fprintf (dump_file, " in ");
4394 print_gimple_stmt (dump_file, stmt, 0, 0);
4397 if (TREE_CODE (sprime) == SSA_NAME)
4398 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4399 NECESSARY, true);
4401 pre_stats.eliminations++;
4402 gimple *orig_stmt = stmt;
4403 if (!useless_type_conversion_p (TREE_TYPE (lhs),
4404 TREE_TYPE (sprime)))
4405 sprime = fold_convert (TREE_TYPE (lhs), sprime);
4406 tree vdef = gimple_vdef (stmt);
4407 tree vuse = gimple_vuse (stmt);
4408 propagate_tree_value_into_stmt (&gsi, sprime);
4409 stmt = gsi_stmt (gsi);
4410 update_stmt (stmt);
4411 if (vdef != gimple_vdef (stmt))
4412 VN_INFO (vdef)->valnum = vuse;
4414 /* If we removed EH side-effects from the statement, clean
4415 its EH information. */
4416 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4418 bitmap_set_bit (need_eh_cleanup,
4419 gimple_bb (stmt)->index);
4420 if (dump_file && (dump_flags & TDF_DETAILS))
4421 fprintf (dump_file, " Removed EH side-effects.\n");
4424 /* Likewise for AB side-effects. */
4425 if (can_make_abnormal_goto
4426 && !stmt_can_make_abnormal_goto (stmt))
4428 bitmap_set_bit (need_ab_cleanup,
4429 gimple_bb (stmt)->index);
4430 if (dump_file && (dump_flags & TDF_DETAILS))
4431 fprintf (dump_file, " Removed AB side-effects.\n");
4434 continue;
4438 /* If the statement is a scalar store, see if the expression
4439 has the same value number as its rhs. If so, the store is
4440 dead. */
4441 if (gimple_assign_single_p (stmt)
4442 && !gimple_has_volatile_ops (stmt)
4443 && !is_gimple_reg (gimple_assign_lhs (stmt))
4444 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4445 || is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
4447 tree val;
4448 tree rhs = gimple_assign_rhs1 (stmt);
4449 vn_reference_t vnresult;
4450 val = vn_reference_lookup (lhs, gimple_vuse (stmt), VN_WALKREWRITE,
4451 &vnresult, false);
4452 if (TREE_CODE (rhs) == SSA_NAME)
4453 rhs = VN_INFO (rhs)->valnum;
4454 if (val
4455 && operand_equal_p (val, rhs, 0))
4457 /* We can only remove the later store if the former aliases
4458 at least all accesses the later one does or if the store
4459 was to readonly memory storing the same value. */
4460 alias_set_type set = get_alias_set (lhs);
4461 if (! vnresult
4462 || vnresult->set == set
4463 || alias_set_subset_of (set, vnresult->set))
4465 if (dump_file && (dump_flags & TDF_DETAILS))
4467 fprintf (dump_file, "Deleted redundant store ");
4468 print_gimple_stmt (dump_file, stmt, 0, 0);
4471 /* Queue stmt for removal. */
4472 el_to_remove.safe_push (stmt);
4473 continue;
4478 /* If this is a control statement value numbering left edges
4479 unexecuted on force the condition in a way consistent with
4480 that. */
4481 if (gcond *cond = dyn_cast <gcond *> (stmt))
4483 if ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE)
4484 ^ (EDGE_SUCC (b, 1)->flags & EDGE_EXECUTABLE))
4486 if (dump_file && (dump_flags & TDF_DETAILS))
4488 fprintf (dump_file, "Removing unexecutable edge from ");
4489 print_gimple_stmt (dump_file, stmt, 0, 0);
4491 if (((EDGE_SUCC (b, 0)->flags & EDGE_TRUE_VALUE) != 0)
4492 == ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE) != 0))
4493 gimple_cond_make_true (cond);
4494 else
4495 gimple_cond_make_false (cond);
4496 update_stmt (cond);
4497 el_todo |= TODO_cleanup_cfg;
4498 continue;
4502 bool can_make_abnormal_goto = stmt_can_make_abnormal_goto (stmt);
4503 bool was_noreturn = (is_gimple_call (stmt)
4504 && gimple_call_noreturn_p (stmt));
4505 tree vdef = gimple_vdef (stmt);
4506 tree vuse = gimple_vuse (stmt);
4508 /* If we didn't replace the whole stmt (or propagate the result
4509 into all uses), replace all uses on this stmt with their
4510 leaders. */
4511 use_operand_p use_p;
4512 ssa_op_iter iter;
4513 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
4515 tree use = USE_FROM_PTR (use_p);
4516 /* ??? The call code above leaves stmt operands un-updated. */
4517 if (TREE_CODE (use) != SSA_NAME)
4518 continue;
4519 tree sprime = eliminate_avail (use);
4520 if (sprime && sprime != use
4521 && may_propagate_copy (use, sprime)
4522 /* We substitute into debug stmts to avoid excessive
4523 debug temporaries created by removed stmts, but we need
4524 to avoid doing so for inserted sprimes as we never want
4525 to create debug temporaries for them. */
4526 && (!inserted_exprs
4527 || TREE_CODE (sprime) != SSA_NAME
4528 || !is_gimple_debug (stmt)
4529 || !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))))
4531 propagate_value (use_p, sprime);
4532 gimple_set_modified (stmt, true);
4533 if (TREE_CODE (sprime) == SSA_NAME
4534 && !is_gimple_debug (stmt))
4535 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4536 NECESSARY, true);
4540 /* Visit indirect calls and turn them into direct calls if
4541 possible using the devirtualization machinery. */
4542 if (gcall *call_stmt = dyn_cast <gcall *> (stmt))
4544 tree fn = gimple_call_fn (call_stmt);
4545 if (fn
4546 && flag_devirtualize
4547 && virtual_method_call_p (fn))
4549 tree otr_type = obj_type_ref_class (fn);
4550 tree instance;
4551 ipa_polymorphic_call_context context (current_function_decl, fn, stmt, &instance);
4552 bool final;
4554 context.get_dynamic_type (instance, OBJ_TYPE_REF_OBJECT (fn), otr_type, stmt);
4556 vec <cgraph_node *>targets
4557 = possible_polymorphic_call_targets (obj_type_ref_class (fn),
4558 tree_to_uhwi
4559 (OBJ_TYPE_REF_TOKEN (fn)),
4560 context,
4561 &final);
4562 if (dump_file)
4563 dump_possible_polymorphic_call_targets (dump_file,
4564 obj_type_ref_class (fn),
4565 tree_to_uhwi
4566 (OBJ_TYPE_REF_TOKEN (fn)),
4567 context);
4568 if (final && targets.length () <= 1 && dbg_cnt (devirt))
4570 tree fn;
4571 if (targets.length () == 1)
4572 fn = targets[0]->decl;
4573 else
4574 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
4575 if (dump_enabled_p ())
4577 location_t loc = gimple_location_safe (stmt);
4578 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
4579 "converting indirect call to "
4580 "function %s\n",
4581 lang_hooks.decl_printable_name (fn, 2));
4583 gimple_call_set_fndecl (call_stmt, fn);
4584 /* If changing the call to __builtin_unreachable
4585 or similar noreturn function, adjust gimple_call_fntype
4586 too. */
4587 if (gimple_call_noreturn_p (call_stmt)
4588 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fn)))
4589 && TYPE_ARG_TYPES (TREE_TYPE (fn))
4590 && (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fn)))
4591 == void_type_node))
4592 gimple_call_set_fntype (call_stmt, TREE_TYPE (fn));
4593 maybe_remove_unused_call_args (cfun, call_stmt);
4594 gimple_set_modified (stmt, true);
4599 if (gimple_modified_p (stmt))
4601 /* If a formerly non-invariant ADDR_EXPR is turned into an
4602 invariant one it was on a separate stmt. */
4603 if (gimple_assign_single_p (stmt)
4604 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
4605 recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
4606 gimple *old_stmt = stmt;
4607 if (is_gimple_call (stmt))
4609 /* ??? Only fold calls inplace for now, this may create new
4610 SSA names which in turn will confuse free_scc_vn SSA name
4611 release code. */
4612 fold_stmt_inplace (&gsi);
4613 /* When changing a call into a noreturn call, cfg cleanup
4614 is needed to fix up the noreturn call. */
4615 if (!was_noreturn && gimple_call_noreturn_p (stmt))
4616 el_to_fixup.safe_push (stmt);
4618 else
4620 fold_stmt (&gsi);
4621 stmt = gsi_stmt (gsi);
4622 if ((gimple_code (stmt) == GIMPLE_COND
4623 && (gimple_cond_true_p (as_a <gcond *> (stmt))
4624 || gimple_cond_false_p (as_a <gcond *> (stmt))))
4625 || (gimple_code (stmt) == GIMPLE_SWITCH
4626 && TREE_CODE (gimple_switch_index (
4627 as_a <gswitch *> (stmt)))
4628 == INTEGER_CST))
4629 el_todo |= TODO_cleanup_cfg;
4631 /* If we removed EH side-effects from the statement, clean
4632 its EH information. */
4633 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
4635 bitmap_set_bit (need_eh_cleanup,
4636 gimple_bb (stmt)->index);
4637 if (dump_file && (dump_flags & TDF_DETAILS))
4638 fprintf (dump_file, " Removed EH side-effects.\n");
4640 /* Likewise for AB side-effects. */
4641 if (can_make_abnormal_goto
4642 && !stmt_can_make_abnormal_goto (stmt))
4644 bitmap_set_bit (need_ab_cleanup,
4645 gimple_bb (stmt)->index);
4646 if (dump_file && (dump_flags & TDF_DETAILS))
4647 fprintf (dump_file, " Removed AB side-effects.\n");
4649 update_stmt (stmt);
4650 if (vdef != gimple_vdef (stmt))
4651 VN_INFO (vdef)->valnum = vuse;
4654 /* Make new values available - for fully redundant LHS we
4655 continue with the next stmt above and skip this. */
4656 def_operand_p defp;
4657 FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_DEF)
4658 eliminate_push_avail (DEF_FROM_PTR (defp));
4661 /* Replace destination PHI arguments. */
4662 edge_iterator ei;
4663 edge e;
4664 FOR_EACH_EDGE (e, ei, b->succs)
4666 for (gphi_iterator gsi = gsi_start_phis (e->dest);
4667 !gsi_end_p (gsi);
4668 gsi_next (&gsi))
4670 gphi *phi = gsi.phi ();
4671 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
4672 tree arg = USE_FROM_PTR (use_p);
4673 if (TREE_CODE (arg) != SSA_NAME
4674 || virtual_operand_p (arg))
4675 continue;
4676 tree sprime = eliminate_avail (arg);
4677 if (sprime && may_propagate_copy (arg, sprime))
4679 propagate_value (use_p, sprime);
4680 if (TREE_CODE (sprime) == SSA_NAME)
4681 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4685 return NULL;
4688 /* Make no longer available leaders no longer available. */
4690 void
4691 eliminate_dom_walker::after_dom_children (basic_block)
4693 tree entry;
4694 while ((entry = el_avail_stack.pop ()) != NULL_TREE)
4696 tree valnum = VN_INFO (entry)->valnum;
4697 tree old = el_avail[SSA_NAME_VERSION (valnum)];
4698 if (old == entry)
4699 el_avail[SSA_NAME_VERSION (valnum)] = NULL_TREE;
4700 else
4701 el_avail[SSA_NAME_VERSION (valnum)] = entry;
4705 /* Eliminate fully redundant computations. */
4707 static unsigned int
4708 eliminate (bool do_pre)
4710 gimple_stmt_iterator gsi;
4711 gimple *stmt;
4713 need_eh_cleanup = BITMAP_ALLOC (NULL);
4714 need_ab_cleanup = BITMAP_ALLOC (NULL);
4716 el_to_remove.create (0);
4717 el_to_fixup.create (0);
4718 el_todo = 0;
4719 el_avail.create (num_ssa_names);
4720 el_avail_stack.create (0);
4722 eliminate_dom_walker (CDI_DOMINATORS,
4723 do_pre).walk (cfun->cfg->x_entry_block_ptr);
4725 el_avail.release ();
4726 el_avail_stack.release ();
4728 /* We cannot remove stmts during BB walk, especially not release SSA
4729 names there as this confuses the VN machinery. The stmts ending
4730 up in el_to_remove are either stores or simple copies.
4731 Remove stmts in reverse order to make debug stmt creation possible. */
4732 while (!el_to_remove.is_empty ())
4734 stmt = el_to_remove.pop ();
4736 if (dump_file && (dump_flags & TDF_DETAILS))
4738 fprintf (dump_file, "Removing dead stmt ");
4739 print_gimple_stmt (dump_file, stmt, 0, 0);
4742 tree lhs;
4743 if (gimple_code (stmt) == GIMPLE_PHI)
4744 lhs = gimple_phi_result (stmt);
4745 else
4746 lhs = gimple_get_lhs (stmt);
4748 if (inserted_exprs
4749 && TREE_CODE (lhs) == SSA_NAME)
4750 bitmap_clear_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
4752 gsi = gsi_for_stmt (stmt);
4753 if (gimple_code (stmt) == GIMPLE_PHI)
4754 remove_phi_node (&gsi, true);
4755 else
4757 basic_block bb = gimple_bb (stmt);
4758 unlink_stmt_vdef (stmt);
4759 if (gsi_remove (&gsi, true))
4760 bitmap_set_bit (need_eh_cleanup, bb->index);
4761 if (is_gimple_call (stmt) && stmt_can_make_abnormal_goto (stmt))
4762 bitmap_set_bit (need_ab_cleanup, bb->index);
4763 release_defs (stmt);
4766 /* Removing a stmt may expose a forwarder block. */
4767 el_todo |= TODO_cleanup_cfg;
4769 el_to_remove.release ();
4771 /* Fixup stmts that became noreturn calls. This may require splitting
4772 blocks and thus isn't possible during the dominator walk. Do this
4773 in reverse order so we don't inadvertedly remove a stmt we want to
4774 fixup by visiting a dominating now noreturn call first. */
4775 while (!el_to_fixup.is_empty ())
4777 stmt = el_to_fixup.pop ();
4779 if (dump_file && (dump_flags & TDF_DETAILS))
4781 fprintf (dump_file, "Fixing up noreturn call ");
4782 print_gimple_stmt (dump_file, stmt, 0, 0);
4785 if (fixup_noreturn_call (stmt))
4786 el_todo |= TODO_cleanup_cfg;
4788 el_to_fixup.release ();
4790 return el_todo;
4793 /* Perform CFG cleanups made necessary by elimination. */
4795 static unsigned
4796 fini_eliminate (void)
4798 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
4799 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
4801 if (do_eh_cleanup)
4802 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
4804 if (do_ab_cleanup)
4805 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
4807 BITMAP_FREE (need_eh_cleanup);
4808 BITMAP_FREE (need_ab_cleanup);
4810 if (do_eh_cleanup || do_ab_cleanup)
4811 return TODO_cleanup_cfg;
4812 return 0;
4815 /* Borrow a bit of tree-ssa-dce.c for the moment.
4816 XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
4817 this may be a bit faster, and we may want critical edges kept split. */
4819 /* If OP's defining statement has not already been determined to be necessary,
4820 mark that statement necessary. Return the stmt, if it is newly
4821 necessary. */
4823 static inline gimple *
4824 mark_operand_necessary (tree op)
4826 gimple *stmt;
4828 gcc_assert (op);
4830 if (TREE_CODE (op) != SSA_NAME)
4831 return NULL;
4833 stmt = SSA_NAME_DEF_STMT (op);
4834 gcc_assert (stmt);
4836 if (gimple_plf (stmt, NECESSARY)
4837 || gimple_nop_p (stmt))
4838 return NULL;
4840 gimple_set_plf (stmt, NECESSARY, true);
4841 return stmt;
4844 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4845 to insert PHI nodes sometimes, and because value numbering of casts isn't
4846 perfect, we sometimes end up inserting dead code. This simple DCE-like
4847 pass removes any insertions we made that weren't actually used. */
4849 static void
4850 remove_dead_inserted_code (void)
4852 bitmap worklist;
4853 unsigned i;
4854 bitmap_iterator bi;
4855 gimple *t;
4857 worklist = BITMAP_ALLOC (NULL);
4858 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4860 t = SSA_NAME_DEF_STMT (ssa_name (i));
4861 if (gimple_plf (t, NECESSARY))
4862 bitmap_set_bit (worklist, i);
4864 while (!bitmap_empty_p (worklist))
4866 i = bitmap_first_set_bit (worklist);
4867 bitmap_clear_bit (worklist, i);
4868 t = SSA_NAME_DEF_STMT (ssa_name (i));
4870 /* PHI nodes are somewhat special in that each PHI alternative has
4871 data and control dependencies. All the statements feeding the
4872 PHI node's arguments are always necessary. */
4873 if (gimple_code (t) == GIMPLE_PHI)
4875 unsigned k;
4877 for (k = 0; k < gimple_phi_num_args (t); k++)
4879 tree arg = PHI_ARG_DEF (t, k);
4880 if (TREE_CODE (arg) == SSA_NAME)
4882 gimple *n = mark_operand_necessary (arg);
4883 if (n)
4884 bitmap_set_bit (worklist, SSA_NAME_VERSION (arg));
4888 else
4890 /* Propagate through the operands. Examine all the USE, VUSE and
4891 VDEF operands in this statement. Mark all the statements
4892 which feed this statement's uses as necessary. */
4893 ssa_op_iter iter;
4894 tree use;
4896 /* The operands of VDEF expressions are also needed as they
4897 represent potential definitions that may reach this
4898 statement (VDEF operands allow us to follow def-def
4899 links). */
4901 FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
4903 gimple *n = mark_operand_necessary (use);
4904 if (n)
4905 bitmap_set_bit (worklist, SSA_NAME_VERSION (use));
4910 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4912 t = SSA_NAME_DEF_STMT (ssa_name (i));
4913 if (!gimple_plf (t, NECESSARY))
4915 gimple_stmt_iterator gsi;
4917 if (dump_file && (dump_flags & TDF_DETAILS))
4919 fprintf (dump_file, "Removing unnecessary insertion:");
4920 print_gimple_stmt (dump_file, t, 0, 0);
4923 gsi = gsi_for_stmt (t);
4924 if (gimple_code (t) == GIMPLE_PHI)
4925 remove_phi_node (&gsi, true);
4926 else
4928 gsi_remove (&gsi, true);
4929 release_defs (t);
4933 BITMAP_FREE (worklist);
4937 /* Initialize data structures used by PRE. */
4939 static void
4940 init_pre (void)
4942 basic_block bb;
4944 next_expression_id = 1;
4945 expressions.create (0);
4946 expressions.safe_push (NULL);
4947 value_expressions.create (get_max_value_id () + 1);
4948 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
4949 name_to_id.create (0);
4951 inserted_exprs = BITMAP_ALLOC (NULL);
4953 connect_infinite_loops_to_exit ();
4954 memset (&pre_stats, 0, sizeof (pre_stats));
4956 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4958 calculate_dominance_info (CDI_DOMINATORS);
4960 bitmap_obstack_initialize (&grand_bitmap_obstack);
4961 phi_translate_table = new hash_table<expr_pred_trans_d> (5110);
4962 expression_to_id = new hash_table<pre_expr_d> (num_ssa_names * 3);
4963 FOR_ALL_BB_FN (bb, cfun)
4965 EXP_GEN (bb) = bitmap_set_new ();
4966 PHI_GEN (bb) = bitmap_set_new ();
4967 TMP_GEN (bb) = bitmap_set_new ();
4968 AVAIL_OUT (bb) = bitmap_set_new ();
4973 /* Deallocate data structures used by PRE. */
4975 static void
4976 fini_pre ()
4978 value_expressions.release ();
4979 BITMAP_FREE (inserted_exprs);
4980 bitmap_obstack_release (&grand_bitmap_obstack);
4981 bitmap_set_pool.release ();
4982 pre_expr_pool.release ();
4983 delete phi_translate_table;
4984 phi_translate_table = NULL;
4985 delete expression_to_id;
4986 expression_to_id = NULL;
4987 name_to_id.release ();
4989 free_aux_for_blocks ();
4992 namespace {
4994 const pass_data pass_data_pre =
4996 GIMPLE_PASS, /* type */
4997 "pre", /* name */
4998 OPTGROUP_NONE, /* optinfo_flags */
4999 TV_TREE_PRE, /* tv_id */
5000 /* PROP_no_crit_edges is ensured by placing pass_split_crit_edges before
5001 pass_pre. */
5002 ( PROP_no_crit_edges | PROP_cfg | PROP_ssa ), /* properties_required */
5003 0, /* properties_provided */
5004 PROP_no_crit_edges, /* properties_destroyed */
5005 TODO_rebuild_alias, /* todo_flags_start */
5006 0, /* todo_flags_finish */
5009 class pass_pre : public gimple_opt_pass
5011 public:
5012 pass_pre (gcc::context *ctxt)
5013 : gimple_opt_pass (pass_data_pre, ctxt)
5016 /* opt_pass methods: */
5017 virtual bool gate (function *)
5018 { return flag_tree_pre != 0 || flag_code_hoisting != 0; }
5019 virtual unsigned int execute (function *);
5021 }; // class pass_pre
5023 unsigned int
5024 pass_pre::execute (function *fun)
5026 unsigned int todo = 0;
5028 do_partial_partial =
5029 flag_tree_partial_pre && optimize_function_for_speed_p (fun);
5031 /* This has to happen before SCCVN runs because
5032 loop_optimizer_init may create new phis, etc. */
5033 loop_optimizer_init (LOOPS_NORMAL);
5035 if (!run_scc_vn (VN_WALK))
5037 loop_optimizer_finalize ();
5038 return 0;
5041 init_pre ();
5042 scev_initialize ();
5044 /* Collect and value number expressions computed in each basic block. */
5045 compute_avail ();
5047 /* Insert can get quite slow on an incredibly large number of basic
5048 blocks due to some quadratic behavior. Until this behavior is
5049 fixed, don't run it when he have an incredibly large number of
5050 bb's. If we aren't going to run insert, there is no point in
5051 computing ANTIC, either, even though it's plenty fast. */
5052 if (n_basic_blocks_for_fn (fun) < 4000)
5054 compute_antic ();
5055 insert ();
5058 /* Make sure to remove fake edges before committing our inserts.
5059 This makes sure we don't end up with extra critical edges that
5060 we would need to split. */
5061 remove_fake_exit_edges ();
5062 gsi_commit_edge_inserts ();
5064 /* Eliminate folds statements which might (should not...) end up
5065 not keeping virtual operands up-to-date. */
5066 gcc_assert (!need_ssa_update_p (fun));
5068 /* Remove all the redundant expressions. */
5069 todo |= eliminate (true);
5071 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
5072 statistics_counter_event (fun, "PA inserted", pre_stats.pa_insert);
5073 statistics_counter_event (fun, "HOIST inserted", pre_stats.hoist_insert);
5074 statistics_counter_event (fun, "New PHIs", pre_stats.phis);
5075 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
5077 clear_expression_ids ();
5078 remove_dead_inserted_code ();
5080 scev_finalize ();
5081 fini_pre ();
5082 todo |= fini_eliminate ();
5083 loop_optimizer_finalize ();
5085 /* Restore SSA info before tail-merging as that resets it as well. */
5086 scc_vn_restore_ssa_info ();
5088 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
5089 case we can merge the block with the remaining predecessor of the block.
5090 It should either:
5091 - call merge_blocks after each tail merge iteration
5092 - call merge_blocks after all tail merge iterations
5093 - mark TODO_cleanup_cfg when necessary
5094 - share the cfg cleanup with fini_pre. */
5095 todo |= tail_merge_optimize (todo);
5097 free_scc_vn ();
5099 /* Tail merging invalidates the virtual SSA web, together with
5100 cfg-cleanup opportunities exposed by PRE this will wreck the
5101 SSA updating machinery. So make sure to run update-ssa
5102 manually, before eventually scheduling cfg-cleanup as part of
5103 the todo. */
5104 update_ssa (TODO_update_ssa_only_virtuals);
5106 return todo;
5109 } // anon namespace
5111 gimple_opt_pass *
5112 make_pass_pre (gcc::context *ctxt)
5114 return new pass_pre (ctxt);
5117 namespace {
5119 const pass_data pass_data_fre =
5121 GIMPLE_PASS, /* type */
5122 "fre", /* name */
5123 OPTGROUP_NONE, /* optinfo_flags */
5124 TV_TREE_FRE, /* tv_id */
5125 ( PROP_cfg | PROP_ssa ), /* properties_required */
5126 0, /* properties_provided */
5127 0, /* properties_destroyed */
5128 0, /* todo_flags_start */
5129 0, /* todo_flags_finish */
5132 class pass_fre : public gimple_opt_pass
5134 public:
5135 pass_fre (gcc::context *ctxt)
5136 : gimple_opt_pass (pass_data_fre, ctxt)
5139 /* opt_pass methods: */
5140 opt_pass * clone () { return new pass_fre (m_ctxt); }
5141 virtual bool gate (function *) { return flag_tree_fre != 0; }
5142 virtual unsigned int execute (function *);
5144 }; // class pass_fre
5146 unsigned int
5147 pass_fre::execute (function *fun)
5149 unsigned int todo = 0;
5151 if (!run_scc_vn (VN_WALKREWRITE))
5152 return 0;
5154 memset (&pre_stats, 0, sizeof (pre_stats));
5156 /* Remove all the redundant expressions. */
5157 todo |= eliminate (false);
5159 todo |= fini_eliminate ();
5161 scc_vn_restore_ssa_info ();
5162 free_scc_vn ();
5164 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
5165 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
5167 return todo;
5170 } // anon namespace
5172 gimple_opt_pass *
5173 make_pass_fre (gcc::context *ctxt)
5175 return new pass_fre (ctxt);