jit.exp: support C++ testcases
[official-gcc.git] / gcc / tree-ssa-pre.c
blobb1bd93f236ea60fd404e16cc8d7f33f06a9c0a5e
1 /* SSA-PRE for trees.
2 Copyright (C) 2001-2015 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <dan@dberlin.org> and Steven Bosscher
4 <stevenb@suse.de>
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "predict.h"
28 #include "vec.h"
29 #include "hashtab.h"
30 #include "hash-set.h"
31 #include "machmode.h"
32 #include "hard-reg-set.h"
33 #include "input.h"
34 #include "function.h"
35 #include "dominance.h"
36 #include "cfg.h"
37 #include "cfganal.h"
38 #include "basic-block.h"
39 #include "gimple-pretty-print.h"
40 #include "tree-inline.h"
41 #include "inchash.h"
42 #include "hash-table.h"
43 #include "tree-ssa-alias.h"
44 #include "internal-fn.h"
45 #include "gimple-fold.h"
46 #include "tree-eh.h"
47 #include "gimple-expr.h"
48 #include "is-a.h"
49 #include "gimple.h"
50 #include "gimplify.h"
51 #include "gimple-iterator.h"
52 #include "gimplify-me.h"
53 #include "gimple-ssa.h"
54 #include "tree-cfg.h"
55 #include "tree-phinodes.h"
56 #include "ssa-iterators.h"
57 #include "stringpool.h"
58 #include "tree-ssanames.h"
59 #include "tree-ssa-loop.h"
60 #include "tree-into-ssa.h"
61 #include "expr.h"
62 #include "tree-dfa.h"
63 #include "tree-ssa.h"
64 #include "tree-iterator.h"
65 #include "alloc-pool.h"
66 #include "obstack.h"
67 #include "tree-pass.h"
68 #include "flags.h"
69 #include "langhooks.h"
70 #include "cfgloop.h"
71 #include "tree-ssa-sccvn.h"
72 #include "tree-scalar-evolution.h"
73 #include "params.h"
74 #include "dbgcnt.h"
75 #include "domwalk.h"
76 #include "hash-map.h"
77 #include "plugin-api.h"
78 #include "ipa-ref.h"
79 #include "cgraph.h"
80 #include "symbol-summary.h"
81 #include "ipa-prop.h"
82 #include "tree-ssa-propagate.h"
83 #include "ipa-utils.h"
85 /* TODO:
87 1. Avail sets can be shared by making an avail_find_leader that
88 walks up the dominator tree and looks in those avail sets.
89 This might affect code optimality, it's unclear right now.
90 2. Strength reduction can be performed by anticipating expressions
91 we can repair later on.
92 3. We can do back-substitution or smarter value numbering to catch
93 commutative expressions split up over multiple statements.
96 /* For ease of terminology, "expression node" in the below refers to
97 every expression node but GIMPLE_ASSIGN, because GIMPLE_ASSIGNs
98 represent the actual statement containing the expressions we care about,
99 and we cache the value number by putting it in the expression. */
101 /* Basic algorithm
103 First we walk the statements to generate the AVAIL sets, the
104 EXP_GEN sets, and the tmp_gen sets. EXP_GEN sets represent the
105 generation of values/expressions by a given block. We use them
106 when computing the ANTIC sets. The AVAIL sets consist of
107 SSA_NAME's that represent values, so we know what values are
108 available in what blocks. AVAIL is a forward dataflow problem. In
109 SSA, values are never killed, so we don't need a kill set, or a
110 fixpoint iteration, in order to calculate the AVAIL sets. In
111 traditional parlance, AVAIL sets tell us the downsafety of the
112 expressions/values.
114 Next, we generate the ANTIC sets. These sets represent the
115 anticipatable expressions. ANTIC is a backwards dataflow
116 problem. An expression is anticipatable in a given block if it could
117 be generated in that block. This means that if we had to perform
118 an insertion in that block, of the value of that expression, we
119 could. Calculating the ANTIC sets requires phi translation of
120 expressions, because the flow goes backwards through phis. We must
121 iterate to a fixpoint of the ANTIC sets, because we have a kill
122 set. Even in SSA form, values are not live over the entire
123 function, only from their definition point onwards. So we have to
124 remove values from the ANTIC set once we go past the definition
125 point of the leaders that make them up.
126 compute_antic/compute_antic_aux performs this computation.
128 Third, we perform insertions to make partially redundant
129 expressions fully redundant.
131 An expression is partially redundant (excluding partial
132 anticipation) if:
134 1. It is AVAIL in some, but not all, of the predecessors of a
135 given block.
136 2. It is ANTIC in all the predecessors.
138 In order to make it fully redundant, we insert the expression into
139 the predecessors where it is not available, but is ANTIC.
141 For the partial anticipation case, we only perform insertion if it
142 is partially anticipated in some block, and fully available in all
143 of the predecessors.
145 insert/insert_aux/do_regular_insertion/do_partial_partial_insertion
146 performs these steps.
148 Fourth, we eliminate fully redundant expressions.
149 This is a simple statement walk that replaces redundant
150 calculations with the now available values. */
152 /* Representations of value numbers:
154 Value numbers are represented by a representative SSA_NAME. We
155 will create fake SSA_NAME's in situations where we need a
156 representative but do not have one (because it is a complex
157 expression). In order to facilitate storing the value numbers in
158 bitmaps, and keep the number of wasted SSA_NAME's down, we also
159 associate a value_id with each value number, and create full blown
160 ssa_name's only where we actually need them (IE in operands of
161 existing expressions).
163 Theoretically you could replace all the value_id's with
164 SSA_NAME_VERSION, but this would allocate a large number of
165 SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
166 It would also require an additional indirection at each point we
167 use the value id. */
169 /* Representation of expressions on value numbers:
171 Expressions consisting of value numbers are represented the same
172 way as our VN internally represents them, with an additional
173 "pre_expr" wrapping around them in order to facilitate storing all
174 of the expressions in the same sets. */
176 /* Representation of sets:
178 The dataflow sets do not need to be sorted in any particular order
179 for the majority of their lifetime, are simply represented as two
180 bitmaps, one that keeps track of values present in the set, and one
181 that keeps track of expressions present in the set.
183 When we need them in topological order, we produce it on demand by
184 transforming the bitmap into an array and sorting it into topo
185 order. */
187 /* Type of expression, used to know which member of the PRE_EXPR union
188 is valid. */
190 enum pre_expr_kind
192 NAME,
193 NARY,
194 REFERENCE,
195 CONSTANT
198 typedef union pre_expr_union_d
200 tree name;
201 tree constant;
202 vn_nary_op_t nary;
203 vn_reference_t reference;
204 } pre_expr_union;
206 typedef struct pre_expr_d : typed_noop_remove <pre_expr_d>
208 enum pre_expr_kind kind;
209 unsigned int id;
210 pre_expr_union u;
212 /* hash_table support. */
213 typedef pre_expr_d value_type;
214 typedef pre_expr_d compare_type;
215 static inline hashval_t hash (const pre_expr_d *);
216 static inline int equal (const pre_expr_d *, const pre_expr_d *);
217 } *pre_expr;
219 #define PRE_EXPR_NAME(e) (e)->u.name
220 #define PRE_EXPR_NARY(e) (e)->u.nary
221 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
222 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
224 /* Compare E1 and E1 for equality. */
226 inline int
227 pre_expr_d::equal (const value_type *e1, const compare_type *e2)
229 if (e1->kind != e2->kind)
230 return false;
232 switch (e1->kind)
234 case CONSTANT:
235 return vn_constant_eq_with_type (PRE_EXPR_CONSTANT (e1),
236 PRE_EXPR_CONSTANT (e2));
237 case NAME:
238 return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
239 case NARY:
240 return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
241 case REFERENCE:
242 return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
243 PRE_EXPR_REFERENCE (e2));
244 default:
245 gcc_unreachable ();
249 /* Hash E. */
251 inline hashval_t
252 pre_expr_d::hash (const value_type *e)
254 switch (e->kind)
256 case CONSTANT:
257 return vn_hash_constant_with_type (PRE_EXPR_CONSTANT (e));
258 case NAME:
259 return SSA_NAME_VERSION (PRE_EXPR_NAME (e));
260 case NARY:
261 return PRE_EXPR_NARY (e)->hashcode;
262 case REFERENCE:
263 return PRE_EXPR_REFERENCE (e)->hashcode;
264 default:
265 gcc_unreachable ();
269 /* Next global expression id number. */
270 static unsigned int next_expression_id;
272 /* Mapping from expression to id number we can use in bitmap sets. */
273 static vec<pre_expr> expressions;
274 static hash_table<pre_expr_d> *expression_to_id;
275 static vec<unsigned> name_to_id;
277 /* Allocate an expression id for EXPR. */
279 static inline unsigned int
280 alloc_expression_id (pre_expr expr)
282 struct pre_expr_d **slot;
283 /* Make sure we won't overflow. */
284 gcc_assert (next_expression_id + 1 > next_expression_id);
285 expr->id = next_expression_id++;
286 expressions.safe_push (expr);
287 if (expr->kind == NAME)
289 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
290 /* vec::safe_grow_cleared allocates no headroom. Avoid frequent
291 re-allocations by using vec::reserve upfront. */
292 unsigned old_len = name_to_id.length ();
293 name_to_id.reserve (num_ssa_names - old_len);
294 name_to_id.quick_grow_cleared (num_ssa_names);
295 gcc_assert (name_to_id[version] == 0);
296 name_to_id[version] = expr->id;
298 else
300 slot = expression_to_id->find_slot (expr, INSERT);
301 gcc_assert (!*slot);
302 *slot = expr;
304 return next_expression_id - 1;
307 /* Return the expression id for tree EXPR. */
309 static inline unsigned int
310 get_expression_id (const pre_expr expr)
312 return expr->id;
315 static inline unsigned int
316 lookup_expression_id (const pre_expr expr)
318 struct pre_expr_d **slot;
320 if (expr->kind == NAME)
322 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
323 if (name_to_id.length () <= version)
324 return 0;
325 return name_to_id[version];
327 else
329 slot = expression_to_id->find_slot (expr, NO_INSERT);
330 if (!slot)
331 return 0;
332 return ((pre_expr)*slot)->id;
336 /* Return the existing expression id for EXPR, or create one if one
337 does not exist yet. */
339 static inline unsigned int
340 get_or_alloc_expression_id (pre_expr expr)
342 unsigned int id = lookup_expression_id (expr);
343 if (id == 0)
344 return alloc_expression_id (expr);
345 return expr->id = id;
348 /* Return the expression that has expression id ID */
350 static inline pre_expr
351 expression_for_id (unsigned int id)
353 return expressions[id];
356 /* Free the expression id field in all of our expressions,
357 and then destroy the expressions array. */
359 static void
360 clear_expression_ids (void)
362 expressions.release ();
365 static alloc_pool pre_expr_pool;
367 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it. */
369 static pre_expr
370 get_or_alloc_expr_for_name (tree name)
372 struct pre_expr_d expr;
373 pre_expr result;
374 unsigned int result_id;
376 expr.kind = NAME;
377 expr.id = 0;
378 PRE_EXPR_NAME (&expr) = name;
379 result_id = lookup_expression_id (&expr);
380 if (result_id != 0)
381 return expression_for_id (result_id);
383 result = (pre_expr) pool_alloc (pre_expr_pool);
384 result->kind = NAME;
385 PRE_EXPR_NAME (result) = name;
386 alloc_expression_id (result);
387 return result;
390 /* An unordered bitmap set. One bitmap tracks values, the other,
391 expressions. */
392 typedef struct bitmap_set
394 bitmap_head expressions;
395 bitmap_head values;
396 } *bitmap_set_t;
398 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi) \
399 EXECUTE_IF_SET_IN_BITMAP (&(set)->expressions, 0, (id), (bi))
401 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi) \
402 EXECUTE_IF_SET_IN_BITMAP (&(set)->values, 0, (id), (bi))
404 /* Mapping from value id to expressions with that value_id. */
405 static vec<bitmap> value_expressions;
407 /* Sets that we need to keep track of. */
408 typedef struct bb_bitmap_sets
410 /* The EXP_GEN set, which represents expressions/values generated in
411 a basic block. */
412 bitmap_set_t exp_gen;
414 /* The PHI_GEN set, which represents PHI results generated in a
415 basic block. */
416 bitmap_set_t phi_gen;
418 /* The TMP_GEN set, which represents results/temporaries generated
419 in a basic block. IE the LHS of an expression. */
420 bitmap_set_t tmp_gen;
422 /* The AVAIL_OUT set, which represents which values are available in
423 a given basic block. */
424 bitmap_set_t avail_out;
426 /* The ANTIC_IN set, which represents which values are anticipatable
427 in a given basic block. */
428 bitmap_set_t antic_in;
430 /* The PA_IN set, which represents which values are
431 partially anticipatable in a given basic block. */
432 bitmap_set_t pa_in;
434 /* The NEW_SETS set, which is used during insertion to augment the
435 AVAIL_OUT set of blocks with the new insertions performed during
436 the current iteration. */
437 bitmap_set_t new_sets;
439 /* A cache for value_dies_in_block_x. */
440 bitmap expr_dies;
442 /* The live virtual operand on successor edges. */
443 tree vop_on_exit;
445 /* True if we have visited this block during ANTIC calculation. */
446 unsigned int visited : 1;
448 /* True when the block contains a call that might not return. */
449 unsigned int contains_may_not_return_call : 1;
450 } *bb_value_sets_t;
452 #define EXP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->exp_gen
453 #define PHI_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->phi_gen
454 #define TMP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->tmp_gen
455 #define AVAIL_OUT(BB) ((bb_value_sets_t) ((BB)->aux))->avail_out
456 #define ANTIC_IN(BB) ((bb_value_sets_t) ((BB)->aux))->antic_in
457 #define PA_IN(BB) ((bb_value_sets_t) ((BB)->aux))->pa_in
458 #define NEW_SETS(BB) ((bb_value_sets_t) ((BB)->aux))->new_sets
459 #define EXPR_DIES(BB) ((bb_value_sets_t) ((BB)->aux))->expr_dies
460 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
461 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
462 #define BB_LIVE_VOP_ON_EXIT(BB) ((bb_value_sets_t) ((BB)->aux))->vop_on_exit
465 /* Basic block list in postorder. */
466 static int *postorder;
467 static int postorder_num;
469 /* This structure is used to keep track of statistics on what
470 optimization PRE was able to perform. */
471 static struct
473 /* The number of RHS computations eliminated by PRE. */
474 int eliminations;
476 /* The number of new expressions/temporaries generated by PRE. */
477 int insertions;
479 /* The number of inserts found due to partial anticipation */
480 int pa_insert;
482 /* The number of new PHI nodes added by PRE. */
483 int phis;
484 } pre_stats;
486 static bool do_partial_partial;
487 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
488 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
489 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
490 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
491 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
492 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
493 static void bitmap_insert_into_set_1 (bitmap_set_t, pre_expr,
494 unsigned int, bool);
495 static bitmap_set_t bitmap_set_new (void);
496 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
497 tree);
498 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
499 static unsigned int get_expr_value_id (pre_expr);
501 /* We can add and remove elements and entries to and from sets
502 and hash tables, so we use alloc pools for them. */
504 static alloc_pool bitmap_set_pool;
505 static bitmap_obstack grand_bitmap_obstack;
507 /* Set of blocks with statements that have had their EH properties changed. */
508 static bitmap need_eh_cleanup;
510 /* Set of blocks with statements that have had their AB properties changed. */
511 static bitmap need_ab_cleanup;
513 /* A three tuple {e, pred, v} used to cache phi translations in the
514 phi_translate_table. */
516 typedef struct expr_pred_trans_d : typed_free_remove<expr_pred_trans_d>
518 /* The expression. */
519 pre_expr e;
521 /* The predecessor block along which we translated the expression. */
522 basic_block pred;
524 /* The value that resulted from the translation. */
525 pre_expr v;
527 /* The hashcode for the expression, pred pair. This is cached for
528 speed reasons. */
529 hashval_t hashcode;
531 /* hash_table support. */
532 typedef expr_pred_trans_d value_type;
533 typedef expr_pred_trans_d compare_type;
534 static inline hashval_t hash (const value_type *);
535 static inline int equal (const value_type *, const compare_type *);
536 } *expr_pred_trans_t;
537 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
539 inline hashval_t
540 expr_pred_trans_d::hash (const expr_pred_trans_d *e)
542 return e->hashcode;
545 inline int
546 expr_pred_trans_d::equal (const value_type *ve1,
547 const compare_type *ve2)
549 basic_block b1 = ve1->pred;
550 basic_block b2 = ve2->pred;
552 /* If they are not translations for the same basic block, they can't
553 be equal. */
554 if (b1 != b2)
555 return false;
556 return pre_expr_d::equal (ve1->e, ve2->e);
559 /* The phi_translate_table caches phi translations for a given
560 expression and predecessor. */
561 static hash_table<expr_pred_trans_d> *phi_translate_table;
563 /* Add the tuple mapping from {expression E, basic block PRED} to
564 the phi translation table and return whether it pre-existed. */
566 static inline bool
567 phi_trans_add (expr_pred_trans_t *entry, pre_expr e, basic_block pred)
569 expr_pred_trans_t *slot;
570 expr_pred_trans_d tem;
571 hashval_t hash = iterative_hash_hashval_t (pre_expr_d::hash (e),
572 pred->index);
573 tem.e = e;
574 tem.pred = pred;
575 tem.hashcode = hash;
576 slot = phi_translate_table->find_slot_with_hash (&tem, hash, INSERT);
577 if (*slot)
579 *entry = *slot;
580 return true;
583 *entry = *slot = XNEW (struct expr_pred_trans_d);
584 (*entry)->e = e;
585 (*entry)->pred = pred;
586 (*entry)->hashcode = hash;
587 return false;
591 /* Add expression E to the expression set of value id V. */
593 static void
594 add_to_value (unsigned int v, pre_expr e)
596 bitmap set;
598 gcc_checking_assert (get_expr_value_id (e) == v);
600 if (v >= value_expressions.length ())
602 value_expressions.safe_grow_cleared (v + 1);
605 set = value_expressions[v];
606 if (!set)
608 set = BITMAP_ALLOC (&grand_bitmap_obstack);
609 value_expressions[v] = set;
612 bitmap_set_bit (set, get_or_alloc_expression_id (e));
615 /* Create a new bitmap set and return it. */
617 static bitmap_set_t
618 bitmap_set_new (void)
620 bitmap_set_t ret = (bitmap_set_t) pool_alloc (bitmap_set_pool);
621 bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
622 bitmap_initialize (&ret->values, &grand_bitmap_obstack);
623 return ret;
626 /* Return the value id for a PRE expression EXPR. */
628 static unsigned int
629 get_expr_value_id (pre_expr expr)
631 unsigned int id;
632 switch (expr->kind)
634 case CONSTANT:
635 id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
636 break;
637 case NAME:
638 id = VN_INFO (PRE_EXPR_NAME (expr))->value_id;
639 break;
640 case NARY:
641 id = PRE_EXPR_NARY (expr)->value_id;
642 break;
643 case REFERENCE:
644 id = PRE_EXPR_REFERENCE (expr)->value_id;
645 break;
646 default:
647 gcc_unreachable ();
649 /* ??? We cannot assert that expr has a value-id (it can be 0), because
650 we assign value-ids only to expressions that have a result
651 in set_hashtable_value_ids. */
652 return id;
655 /* Return a SCCVN valnum (SSA name or constant) for the PRE value-id VAL. */
657 static tree
658 sccvn_valnum_from_value_id (unsigned int val)
660 bitmap_iterator bi;
661 unsigned int i;
662 bitmap exprset = value_expressions[val];
663 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
665 pre_expr vexpr = expression_for_id (i);
666 if (vexpr->kind == NAME)
667 return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
668 else if (vexpr->kind == CONSTANT)
669 return PRE_EXPR_CONSTANT (vexpr);
671 return NULL_TREE;
674 /* Remove an expression EXPR from a bitmapped set. */
676 static void
677 bitmap_remove_from_set (bitmap_set_t set, pre_expr expr)
679 unsigned int val = get_expr_value_id (expr);
680 if (!value_id_constant_p (val))
682 bitmap_clear_bit (&set->values, val);
683 bitmap_clear_bit (&set->expressions, get_expression_id (expr));
687 static void
688 bitmap_insert_into_set_1 (bitmap_set_t set, pre_expr expr,
689 unsigned int val, bool allow_constants)
691 if (allow_constants || !value_id_constant_p (val))
693 /* We specifically expect this and only this function to be able to
694 insert constants into a set. */
695 bitmap_set_bit (&set->values, val);
696 bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
700 /* Insert an expression EXPR into a bitmapped set. */
702 static void
703 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
705 bitmap_insert_into_set_1 (set, expr, get_expr_value_id (expr), false);
708 /* Copy a bitmapped set ORIG, into bitmapped set DEST. */
710 static void
711 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
713 bitmap_copy (&dest->expressions, &orig->expressions);
714 bitmap_copy (&dest->values, &orig->values);
718 /* Free memory used up by SET. */
719 static void
720 bitmap_set_free (bitmap_set_t set)
722 bitmap_clear (&set->expressions);
723 bitmap_clear (&set->values);
727 /* Generate an topological-ordered array of bitmap set SET. */
729 static vec<pre_expr>
730 sorted_array_from_bitmap_set (bitmap_set_t set)
732 unsigned int i, j;
733 bitmap_iterator bi, bj;
734 vec<pre_expr> result;
736 /* Pre-allocate enough space for the array. */
737 result.create (bitmap_count_bits (&set->expressions));
739 FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
741 /* The number of expressions having a given value is usually
742 relatively small. Thus, rather than making a vector of all
743 the expressions and sorting it by value-id, we walk the values
744 and check in the reverse mapping that tells us what expressions
745 have a given value, to filter those in our set. As a result,
746 the expressions are inserted in value-id order, which means
747 topological order.
749 If this is somehow a significant lose for some cases, we can
750 choose which set to walk based on the set size. */
751 bitmap exprset = value_expressions[i];
752 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bj)
754 if (bitmap_bit_p (&set->expressions, j))
755 result.quick_push (expression_for_id (j));
759 return result;
762 /* Perform bitmapped set operation DEST &= ORIG. */
764 static void
765 bitmap_set_and (bitmap_set_t dest, bitmap_set_t orig)
767 bitmap_iterator bi;
768 unsigned int i;
770 if (dest != orig)
772 bitmap_head temp;
773 bitmap_initialize (&temp, &grand_bitmap_obstack);
775 bitmap_and_into (&dest->values, &orig->values);
776 bitmap_copy (&temp, &dest->expressions);
777 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
779 pre_expr expr = expression_for_id (i);
780 unsigned int value_id = get_expr_value_id (expr);
781 if (!bitmap_bit_p (&dest->values, value_id))
782 bitmap_clear_bit (&dest->expressions, i);
784 bitmap_clear (&temp);
788 /* Subtract all values and expressions contained in ORIG from DEST. */
790 static bitmap_set_t
791 bitmap_set_subtract (bitmap_set_t dest, bitmap_set_t orig)
793 bitmap_set_t result = bitmap_set_new ();
794 bitmap_iterator bi;
795 unsigned int i;
797 bitmap_and_compl (&result->expressions, &dest->expressions,
798 &orig->expressions);
800 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
802 pre_expr expr = expression_for_id (i);
803 unsigned int value_id = get_expr_value_id (expr);
804 bitmap_set_bit (&result->values, value_id);
807 return result;
810 /* Subtract all the values in bitmap set B from bitmap set A. */
812 static void
813 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
815 unsigned int i;
816 bitmap_iterator bi;
817 bitmap_head temp;
819 bitmap_initialize (&temp, &grand_bitmap_obstack);
821 bitmap_copy (&temp, &a->expressions);
822 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
824 pre_expr expr = expression_for_id (i);
825 if (bitmap_set_contains_value (b, get_expr_value_id (expr)))
826 bitmap_remove_from_set (a, expr);
828 bitmap_clear (&temp);
832 /* Return true if bitmapped set SET contains the value VALUE_ID. */
834 static bool
835 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
837 if (value_id_constant_p (value_id))
838 return true;
840 if (!set || bitmap_empty_p (&set->expressions))
841 return false;
843 return bitmap_bit_p (&set->values, value_id);
846 static inline bool
847 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
849 return bitmap_bit_p (&set->expressions, get_expression_id (expr));
852 /* Replace an instance of value LOOKFOR with expression EXPR in SET. */
854 static void
855 bitmap_set_replace_value (bitmap_set_t set, unsigned int lookfor,
856 const pre_expr expr)
858 bitmap exprset;
859 unsigned int i;
860 bitmap_iterator bi;
862 if (value_id_constant_p (lookfor))
863 return;
865 if (!bitmap_set_contains_value (set, lookfor))
866 return;
868 /* The number of expressions having a given value is usually
869 significantly less than the total number of expressions in SET.
870 Thus, rather than check, for each expression in SET, whether it
871 has the value LOOKFOR, we walk the reverse mapping that tells us
872 what expressions have a given value, and see if any of those
873 expressions are in our set. For large testcases, this is about
874 5-10x faster than walking the bitmap. If this is somehow a
875 significant lose for some cases, we can choose which set to walk
876 based on the set size. */
877 exprset = value_expressions[lookfor];
878 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
880 if (bitmap_clear_bit (&set->expressions, i))
882 bitmap_set_bit (&set->expressions, get_expression_id (expr));
883 return;
887 gcc_unreachable ();
890 /* Return true if two bitmap sets are equal. */
892 static bool
893 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
895 return bitmap_equal_p (&a->values, &b->values);
898 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
899 and add it otherwise. */
901 static void
902 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
904 unsigned int val = get_expr_value_id (expr);
906 if (bitmap_set_contains_value (set, val))
907 bitmap_set_replace_value (set, val, expr);
908 else
909 bitmap_insert_into_set (set, expr);
912 /* Insert EXPR into SET if EXPR's value is not already present in
913 SET. */
915 static void
916 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
918 unsigned int val = get_expr_value_id (expr);
920 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
922 /* Constant values are always considered to be part of the set. */
923 if (value_id_constant_p (val))
924 return;
926 /* If the value membership changed, add the expression. */
927 if (bitmap_set_bit (&set->values, val))
928 bitmap_set_bit (&set->expressions, expr->id);
931 /* Print out EXPR to outfile. */
933 static void
934 print_pre_expr (FILE *outfile, const pre_expr expr)
936 switch (expr->kind)
938 case CONSTANT:
939 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr), 0);
940 break;
941 case NAME:
942 print_generic_expr (outfile, PRE_EXPR_NAME (expr), 0);
943 break;
944 case NARY:
946 unsigned int i;
947 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
948 fprintf (outfile, "{%s,", get_tree_code_name (nary->opcode));
949 for (i = 0; i < nary->length; i++)
951 print_generic_expr (outfile, nary->op[i], 0);
952 if (i != (unsigned) nary->length - 1)
953 fprintf (outfile, ",");
955 fprintf (outfile, "}");
957 break;
959 case REFERENCE:
961 vn_reference_op_t vro;
962 unsigned int i;
963 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
964 fprintf (outfile, "{");
965 for (i = 0;
966 ref->operands.iterate (i, &vro);
967 i++)
969 bool closebrace = false;
970 if (vro->opcode != SSA_NAME
971 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
973 fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
974 if (vro->op0)
976 fprintf (outfile, "<");
977 closebrace = true;
980 if (vro->op0)
982 print_generic_expr (outfile, vro->op0, 0);
983 if (vro->op1)
985 fprintf (outfile, ",");
986 print_generic_expr (outfile, vro->op1, 0);
988 if (vro->op2)
990 fprintf (outfile, ",");
991 print_generic_expr (outfile, vro->op2, 0);
994 if (closebrace)
995 fprintf (outfile, ">");
996 if (i != ref->operands.length () - 1)
997 fprintf (outfile, ",");
999 fprintf (outfile, "}");
1000 if (ref->vuse)
1002 fprintf (outfile, "@");
1003 print_generic_expr (outfile, ref->vuse, 0);
1006 break;
1009 void debug_pre_expr (pre_expr);
1011 /* Like print_pre_expr but always prints to stderr. */
1012 DEBUG_FUNCTION void
1013 debug_pre_expr (pre_expr e)
1015 print_pre_expr (stderr, e);
1016 fprintf (stderr, "\n");
1019 /* Print out SET to OUTFILE. */
1021 static void
1022 print_bitmap_set (FILE *outfile, bitmap_set_t set,
1023 const char *setname, int blockindex)
1025 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
1026 if (set)
1028 bool first = true;
1029 unsigned i;
1030 bitmap_iterator bi;
1032 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1034 const pre_expr expr = expression_for_id (i);
1036 if (!first)
1037 fprintf (outfile, ", ");
1038 first = false;
1039 print_pre_expr (outfile, expr);
1041 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1044 fprintf (outfile, " }\n");
1047 void debug_bitmap_set (bitmap_set_t);
1049 DEBUG_FUNCTION void
1050 debug_bitmap_set (bitmap_set_t set)
1052 print_bitmap_set (stderr, set, "debug", 0);
1055 void debug_bitmap_sets_for (basic_block);
1057 DEBUG_FUNCTION void
1058 debug_bitmap_sets_for (basic_block bb)
1060 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1061 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1062 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1063 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1064 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1065 if (do_partial_partial)
1066 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1067 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1070 /* Print out the expressions that have VAL to OUTFILE. */
1072 static void
1073 print_value_expressions (FILE *outfile, unsigned int val)
1075 bitmap set = value_expressions[val];
1076 if (set)
1078 bitmap_set x;
1079 char s[10];
1080 sprintf (s, "%04d", val);
1081 x.expressions = *set;
1082 print_bitmap_set (outfile, &x, s, 0);
1087 DEBUG_FUNCTION void
1088 debug_value_expressions (unsigned int val)
1090 print_value_expressions (stderr, val);
1093 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1094 represent it. */
1096 static pre_expr
1097 get_or_alloc_expr_for_constant (tree constant)
1099 unsigned int result_id;
1100 unsigned int value_id;
1101 struct pre_expr_d expr;
1102 pre_expr newexpr;
1104 expr.kind = CONSTANT;
1105 PRE_EXPR_CONSTANT (&expr) = constant;
1106 result_id = lookup_expression_id (&expr);
1107 if (result_id != 0)
1108 return expression_for_id (result_id);
1110 newexpr = (pre_expr) pool_alloc (pre_expr_pool);
1111 newexpr->kind = CONSTANT;
1112 PRE_EXPR_CONSTANT (newexpr) = constant;
1113 alloc_expression_id (newexpr);
1114 value_id = get_or_alloc_constant_value_id (constant);
1115 add_to_value (value_id, newexpr);
1116 return newexpr;
1119 /* Given a value id V, find the actual tree representing the constant
1120 value if there is one, and return it. Return NULL if we can't find
1121 a constant. */
1123 static tree
1124 get_constant_for_value_id (unsigned int v)
1126 if (value_id_constant_p (v))
1128 unsigned int i;
1129 bitmap_iterator bi;
1130 bitmap exprset = value_expressions[v];
1132 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1134 pre_expr expr = expression_for_id (i);
1135 if (expr->kind == CONSTANT)
1136 return PRE_EXPR_CONSTANT (expr);
1139 return NULL;
1142 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1143 Currently only supports constants and SSA_NAMES. */
1144 static pre_expr
1145 get_or_alloc_expr_for (tree t)
1147 if (TREE_CODE (t) == SSA_NAME)
1148 return get_or_alloc_expr_for_name (t);
1149 else if (is_gimple_min_invariant (t))
1150 return get_or_alloc_expr_for_constant (t);
1151 else
1153 /* More complex expressions can result from SCCVN expression
1154 simplification that inserts values for them. As they all
1155 do not have VOPs the get handled by the nary ops struct. */
1156 vn_nary_op_t result;
1157 unsigned int result_id;
1158 vn_nary_op_lookup (t, &result);
1159 if (result != NULL)
1161 pre_expr e = (pre_expr) pool_alloc (pre_expr_pool);
1162 e->kind = NARY;
1163 PRE_EXPR_NARY (e) = result;
1164 result_id = lookup_expression_id (e);
1165 if (result_id != 0)
1167 pool_free (pre_expr_pool, e);
1168 e = expression_for_id (result_id);
1169 return e;
1171 alloc_expression_id (e);
1172 return e;
1175 return NULL;
1178 /* Return the folded version of T if T, when folded, is a gimple
1179 min_invariant. Otherwise, return T. */
1181 static pre_expr
1182 fully_constant_expression (pre_expr e)
1184 switch (e->kind)
1186 case CONSTANT:
1187 return e;
1188 case NARY:
1190 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1191 switch (TREE_CODE_CLASS (nary->opcode))
1193 case tcc_binary:
1194 case tcc_comparison:
1196 /* We have to go from trees to pre exprs to value ids to
1197 constants. */
1198 tree naryop0 = nary->op[0];
1199 tree naryop1 = nary->op[1];
1200 tree result;
1201 if (!is_gimple_min_invariant (naryop0))
1203 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1204 unsigned int vrep0 = get_expr_value_id (rep0);
1205 tree const0 = get_constant_for_value_id (vrep0);
1206 if (const0)
1207 naryop0 = fold_convert (TREE_TYPE (naryop0), const0);
1209 if (!is_gimple_min_invariant (naryop1))
1211 pre_expr rep1 = get_or_alloc_expr_for (naryop1);
1212 unsigned int vrep1 = get_expr_value_id (rep1);
1213 tree const1 = get_constant_for_value_id (vrep1);
1214 if (const1)
1215 naryop1 = fold_convert (TREE_TYPE (naryop1), const1);
1217 result = fold_binary (nary->opcode, nary->type,
1218 naryop0, naryop1);
1219 if (result && is_gimple_min_invariant (result))
1220 return get_or_alloc_expr_for_constant (result);
1221 /* We might have simplified the expression to a
1222 SSA_NAME for example from x_1 * 1. But we cannot
1223 insert a PHI for x_1 unconditionally as x_1 might
1224 not be available readily. */
1225 return e;
1227 case tcc_reference:
1228 if (nary->opcode != REALPART_EXPR
1229 && nary->opcode != IMAGPART_EXPR
1230 && nary->opcode != VIEW_CONVERT_EXPR)
1231 return e;
1232 /* Fallthrough. */
1233 case tcc_unary:
1235 /* We have to go from trees to pre exprs to value ids to
1236 constants. */
1237 tree naryop0 = nary->op[0];
1238 tree const0, result;
1239 if (is_gimple_min_invariant (naryop0))
1240 const0 = naryop0;
1241 else
1243 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1244 unsigned int vrep0 = get_expr_value_id (rep0);
1245 const0 = get_constant_for_value_id (vrep0);
1247 result = NULL;
1248 if (const0)
1250 tree type1 = TREE_TYPE (nary->op[0]);
1251 const0 = fold_convert (type1, const0);
1252 result = fold_unary (nary->opcode, nary->type, const0);
1254 if (result && is_gimple_min_invariant (result))
1255 return get_or_alloc_expr_for_constant (result);
1256 return e;
1258 default:
1259 return e;
1262 case REFERENCE:
1264 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1265 tree folded;
1266 if ((folded = fully_constant_vn_reference_p (ref)))
1267 return get_or_alloc_expr_for_constant (folded);
1268 return e;
1270 default:
1271 return e;
1273 return e;
1276 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1277 it has the value it would have in BLOCK. Set *SAME_VALID to true
1278 in case the new vuse doesn't change the value id of the OPERANDS. */
1280 static tree
1281 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1282 alias_set_type set, tree type, tree vuse,
1283 basic_block phiblock,
1284 basic_block block, bool *same_valid)
1286 gimple phi = SSA_NAME_DEF_STMT (vuse);
1287 ao_ref ref;
1288 edge e = NULL;
1289 bool use_oracle;
1291 *same_valid = true;
1293 if (gimple_bb (phi) != phiblock)
1294 return vuse;
1296 use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1298 /* Use the alias-oracle to find either the PHI node in this block,
1299 the first VUSE used in this block that is equivalent to vuse or
1300 the first VUSE which definition in this block kills the value. */
1301 if (gimple_code (phi) == GIMPLE_PHI)
1302 e = find_edge (block, phiblock);
1303 else if (use_oracle)
1304 while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1306 vuse = gimple_vuse (phi);
1307 phi = SSA_NAME_DEF_STMT (vuse);
1308 if (gimple_bb (phi) != phiblock)
1309 return vuse;
1310 if (gimple_code (phi) == GIMPLE_PHI)
1312 e = find_edge (block, phiblock);
1313 break;
1316 else
1317 return NULL_TREE;
1319 if (e)
1321 if (use_oracle)
1323 bitmap visited = NULL;
1324 unsigned int cnt;
1325 /* Try to find a vuse that dominates this phi node by skipping
1326 non-clobbering statements. */
1327 vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false,
1328 NULL, NULL);
1329 if (visited)
1330 BITMAP_FREE (visited);
1332 else
1333 vuse = NULL_TREE;
1334 if (!vuse)
1336 /* If we didn't find any, the value ID can't stay the same,
1337 but return the translated vuse. */
1338 *same_valid = false;
1339 vuse = PHI_ARG_DEF (phi, e->dest_idx);
1341 /* ??? We would like to return vuse here as this is the canonical
1342 upmost vdef that this reference is associated with. But during
1343 insertion of the references into the hash tables we only ever
1344 directly insert with their direct gimple_vuse, hence returning
1345 something else would make us not find the other expression. */
1346 return PHI_ARG_DEF (phi, e->dest_idx);
1349 return NULL_TREE;
1352 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1353 SET2. This is used to avoid making a set consisting of the union
1354 of PA_IN and ANTIC_IN during insert. */
1356 static inline pre_expr
1357 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2)
1359 pre_expr result;
1361 result = bitmap_find_leader (set1, val);
1362 if (!result && set2)
1363 result = bitmap_find_leader (set2, val);
1364 return result;
1367 /* Get the tree type for our PRE expression e. */
1369 static tree
1370 get_expr_type (const pre_expr e)
1372 switch (e->kind)
1374 case NAME:
1375 return TREE_TYPE (PRE_EXPR_NAME (e));
1376 case CONSTANT:
1377 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1378 case REFERENCE:
1379 return PRE_EXPR_REFERENCE (e)->type;
1380 case NARY:
1381 return PRE_EXPR_NARY (e)->type;
1383 gcc_unreachable ();
1386 /* Get a representative SSA_NAME for a given expression.
1387 Since all of our sub-expressions are treated as values, we require
1388 them to be SSA_NAME's for simplicity.
1389 Prior versions of GVNPRE used to use "value handles" here, so that
1390 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1391 either case, the operands are really values (IE we do not expect
1392 them to be usable without finding leaders). */
1394 static tree
1395 get_representative_for (const pre_expr e)
1397 tree name;
1398 unsigned int value_id = get_expr_value_id (e);
1400 switch (e->kind)
1402 case NAME:
1403 return PRE_EXPR_NAME (e);
1404 case CONSTANT:
1405 return PRE_EXPR_CONSTANT (e);
1406 case NARY:
1407 case REFERENCE:
1409 /* Go through all of the expressions representing this value
1410 and pick out an SSA_NAME. */
1411 unsigned int i;
1412 bitmap_iterator bi;
1413 bitmap exprs = value_expressions[value_id];
1414 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1416 pre_expr rep = expression_for_id (i);
1417 if (rep->kind == NAME)
1418 return PRE_EXPR_NAME (rep);
1419 else if (rep->kind == CONSTANT)
1420 return PRE_EXPR_CONSTANT (rep);
1423 break;
1426 /* If we reached here we couldn't find an SSA_NAME. This can
1427 happen when we've discovered a value that has never appeared in
1428 the program as set to an SSA_NAME, as the result of phi translation.
1429 Create one here.
1430 ??? We should be able to re-use this when we insert the statement
1431 to compute it. */
1432 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1433 VN_INFO_GET (name)->value_id = value_id;
1434 VN_INFO (name)->valnum = name;
1435 /* ??? For now mark this SSA name for release by SCCVN. */
1436 VN_INFO (name)->needs_insertion = true;
1437 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1438 if (dump_file && (dump_flags & TDF_DETAILS))
1440 fprintf (dump_file, "Created SSA_NAME representative ");
1441 print_generic_expr (dump_file, name, 0);
1442 fprintf (dump_file, " for expression:");
1443 print_pre_expr (dump_file, e);
1444 fprintf (dump_file, " (%04d)\n", value_id);
1447 return name;
1452 static pre_expr
1453 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1454 basic_block pred, basic_block phiblock);
1456 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1457 the phis in PRED. Return NULL if we can't find a leader for each part
1458 of the translated expression. */
1460 static pre_expr
1461 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1462 basic_block pred, basic_block phiblock)
1464 switch (expr->kind)
1466 case NARY:
1468 unsigned int i;
1469 bool changed = false;
1470 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1471 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1472 sizeof_vn_nary_op (nary->length));
1473 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1475 for (i = 0; i < newnary->length; i++)
1477 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1478 continue;
1479 else
1481 pre_expr leader, result;
1482 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1483 leader = find_leader_in_sets (op_val_id, set1, set2);
1484 result = phi_translate (leader, set1, set2, pred, phiblock);
1485 if (result && result != leader)
1487 tree name = get_representative_for (result);
1488 if (!name)
1489 return NULL;
1490 newnary->op[i] = name;
1492 else if (!result)
1493 return NULL;
1495 changed |= newnary->op[i] != nary->op[i];
1498 if (changed)
1500 pre_expr constant;
1501 unsigned int new_val_id;
1503 tree result = vn_nary_op_lookup_pieces (newnary->length,
1504 newnary->opcode,
1505 newnary->type,
1506 &newnary->op[0],
1507 &nary);
1508 if (result && is_gimple_min_invariant (result))
1509 return get_or_alloc_expr_for_constant (result);
1511 expr = (pre_expr) pool_alloc (pre_expr_pool);
1512 expr->kind = NARY;
1513 expr->id = 0;
1514 if (nary)
1516 PRE_EXPR_NARY (expr) = nary;
1517 constant = fully_constant_expression (expr);
1518 if (constant != expr)
1519 return constant;
1521 new_val_id = nary->value_id;
1522 get_or_alloc_expression_id (expr);
1524 else
1526 new_val_id = get_next_value_id ();
1527 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
1528 nary = vn_nary_op_insert_pieces (newnary->length,
1529 newnary->opcode,
1530 newnary->type,
1531 &newnary->op[0],
1532 result, new_val_id);
1533 PRE_EXPR_NARY (expr) = nary;
1534 constant = fully_constant_expression (expr);
1535 if (constant != expr)
1536 return constant;
1537 get_or_alloc_expression_id (expr);
1539 add_to_value (new_val_id, expr);
1541 return expr;
1543 break;
1545 case REFERENCE:
1547 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1548 vec<vn_reference_op_s> operands = ref->operands;
1549 tree vuse = ref->vuse;
1550 tree newvuse = vuse;
1551 vec<vn_reference_op_s> newoperands = vNULL;
1552 bool changed = false, same_valid = true;
1553 unsigned int i, n;
1554 vn_reference_op_t operand;
1555 vn_reference_t newref;
1557 for (i = 0; operands.iterate (i, &operand); i++)
1559 pre_expr opresult;
1560 pre_expr leader;
1561 tree op[3];
1562 tree type = operand->type;
1563 vn_reference_op_s newop = *operand;
1564 op[0] = operand->op0;
1565 op[1] = operand->op1;
1566 op[2] = operand->op2;
1567 for (n = 0; n < 3; ++n)
1569 unsigned int op_val_id;
1570 if (!op[n])
1571 continue;
1572 if (TREE_CODE (op[n]) != SSA_NAME)
1574 /* We can't possibly insert these. */
1575 if (n != 0
1576 && !is_gimple_min_invariant (op[n]))
1577 break;
1578 continue;
1580 op_val_id = VN_INFO (op[n])->value_id;
1581 leader = find_leader_in_sets (op_val_id, set1, set2);
1582 if (!leader)
1583 break;
1584 opresult = phi_translate (leader, set1, set2, pred, phiblock);
1585 if (!opresult)
1586 break;
1587 if (opresult != leader)
1589 tree name = get_representative_for (opresult);
1590 if (!name)
1591 break;
1592 changed |= name != op[n];
1593 op[n] = name;
1596 if (n != 3)
1598 newoperands.release ();
1599 return NULL;
1601 if (!changed)
1602 continue;
1603 if (!newoperands.exists ())
1604 newoperands = operands.copy ();
1605 /* We may have changed from an SSA_NAME to a constant */
1606 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1607 newop.opcode = TREE_CODE (op[0]);
1608 newop.type = type;
1609 newop.op0 = op[0];
1610 newop.op1 = op[1];
1611 newop.op2 = op[2];
1612 newoperands[i] = newop;
1614 gcc_checking_assert (i == operands.length ());
1616 if (vuse)
1618 newvuse = translate_vuse_through_block (newoperands.exists ()
1619 ? newoperands : operands,
1620 ref->set, ref->type,
1621 vuse, phiblock, pred,
1622 &same_valid);
1623 if (newvuse == NULL_TREE)
1625 newoperands.release ();
1626 return NULL;
1630 if (changed || newvuse != vuse)
1632 unsigned int new_val_id;
1633 pre_expr constant;
1635 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1636 ref->type,
1637 newoperands.exists ()
1638 ? newoperands : operands,
1639 &newref, VN_WALK);
1640 if (result)
1641 newoperands.release ();
1643 /* We can always insert constants, so if we have a partial
1644 redundant constant load of another type try to translate it
1645 to a constant of appropriate type. */
1646 if (result && is_gimple_min_invariant (result))
1648 tree tem = result;
1649 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1651 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1652 if (tem && !is_gimple_min_invariant (tem))
1653 tem = NULL_TREE;
1655 if (tem)
1656 return get_or_alloc_expr_for_constant (tem);
1659 /* If we'd have to convert things we would need to validate
1660 if we can insert the translated expression. So fail
1661 here for now - we cannot insert an alias with a different
1662 type in the VN tables either, as that would assert. */
1663 if (result
1664 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1665 return NULL;
1666 else if (!result && newref
1667 && !useless_type_conversion_p (ref->type, newref->type))
1669 newoperands.release ();
1670 return NULL;
1673 expr = (pre_expr) pool_alloc (pre_expr_pool);
1674 expr->kind = REFERENCE;
1675 expr->id = 0;
1677 if (newref)
1679 PRE_EXPR_REFERENCE (expr) = newref;
1680 constant = fully_constant_expression (expr);
1681 if (constant != expr)
1682 return constant;
1684 new_val_id = newref->value_id;
1685 get_or_alloc_expression_id (expr);
1687 else
1689 if (changed || !same_valid)
1691 new_val_id = get_next_value_id ();
1692 value_expressions.safe_grow_cleared
1693 (get_max_value_id () + 1);
1695 else
1696 new_val_id = ref->value_id;
1697 if (!newoperands.exists ())
1698 newoperands = operands.copy ();
1699 newref = vn_reference_insert_pieces (newvuse, ref->set,
1700 ref->type,
1701 newoperands,
1702 result, new_val_id);
1703 newoperands = vNULL;
1704 PRE_EXPR_REFERENCE (expr) = newref;
1705 constant = fully_constant_expression (expr);
1706 if (constant != expr)
1707 return constant;
1708 get_or_alloc_expression_id (expr);
1710 add_to_value (new_val_id, expr);
1712 newoperands.release ();
1713 return expr;
1715 break;
1717 case NAME:
1719 tree name = PRE_EXPR_NAME (expr);
1720 gimple def_stmt = SSA_NAME_DEF_STMT (name);
1721 /* If the SSA name is defined by a PHI node in this block,
1722 translate it. */
1723 if (gimple_code (def_stmt) == GIMPLE_PHI
1724 && gimple_bb (def_stmt) == phiblock)
1726 edge e = find_edge (pred, gimple_bb (def_stmt));
1727 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1729 /* Handle constant. */
1730 if (is_gimple_min_invariant (def))
1731 return get_or_alloc_expr_for_constant (def);
1733 return get_or_alloc_expr_for_name (def);
1735 /* Otherwise return it unchanged - it will get removed if its
1736 value is not available in PREDs AVAIL_OUT set of expressions
1737 by the subtraction of TMP_GEN. */
1738 return expr;
1741 default:
1742 gcc_unreachable ();
1746 /* Wrapper around phi_translate_1 providing caching functionality. */
1748 static pre_expr
1749 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1750 basic_block pred, basic_block phiblock)
1752 expr_pred_trans_t slot = NULL;
1753 pre_expr phitrans;
1755 if (!expr)
1756 return NULL;
1758 /* Constants contain no values that need translation. */
1759 if (expr->kind == CONSTANT)
1760 return expr;
1762 if (value_id_constant_p (get_expr_value_id (expr)))
1763 return expr;
1765 /* Don't add translations of NAMEs as those are cheap to translate. */
1766 if (expr->kind != NAME)
1768 if (phi_trans_add (&slot, expr, pred))
1769 return slot->v;
1770 /* Store NULL for the value we want to return in the case of
1771 recursing. */
1772 slot->v = NULL;
1775 /* Translate. */
1776 phitrans = phi_translate_1 (expr, set1, set2, pred, phiblock);
1778 if (slot)
1780 if (phitrans)
1781 slot->v = phitrans;
1782 else
1783 /* Remove failed translations again, they cause insert
1784 iteration to not pick up new opportunities reliably. */
1785 phi_translate_table->remove_elt_with_hash (slot, slot->hashcode);
1788 return phitrans;
1792 /* For each expression in SET, translate the values through phi nodes
1793 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1794 expressions in DEST. */
1796 static void
1797 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1798 basic_block phiblock)
1800 vec<pre_expr> exprs;
1801 pre_expr expr;
1802 int i;
1804 if (gimple_seq_empty_p (phi_nodes (phiblock)))
1806 bitmap_set_copy (dest, set);
1807 return;
1810 exprs = sorted_array_from_bitmap_set (set);
1811 FOR_EACH_VEC_ELT (exprs, i, expr)
1813 pre_expr translated;
1814 translated = phi_translate (expr, set, NULL, pred, phiblock);
1815 if (!translated)
1816 continue;
1818 /* We might end up with multiple expressions from SET being
1819 translated to the same value. In this case we do not want
1820 to retain the NARY or REFERENCE expression but prefer a NAME
1821 which would be the leader. */
1822 if (translated->kind == NAME)
1823 bitmap_value_replace_in_set (dest, translated);
1824 else
1825 bitmap_value_insert_into_set (dest, translated);
1827 exprs.release ();
1830 /* Find the leader for a value (i.e., the name representing that
1831 value) in a given set, and return it. Return NULL if no leader
1832 is found. */
1834 static pre_expr
1835 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1837 if (value_id_constant_p (val))
1839 unsigned int i;
1840 bitmap_iterator bi;
1841 bitmap exprset = value_expressions[val];
1843 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1845 pre_expr expr = expression_for_id (i);
1846 if (expr->kind == CONSTANT)
1847 return expr;
1850 if (bitmap_set_contains_value (set, val))
1852 /* Rather than walk the entire bitmap of expressions, and see
1853 whether any of them has the value we are looking for, we look
1854 at the reverse mapping, which tells us the set of expressions
1855 that have a given value (IE value->expressions with that
1856 value) and see if any of those expressions are in our set.
1857 The number of expressions per value is usually significantly
1858 less than the number of expressions in the set. In fact, for
1859 large testcases, doing it this way is roughly 5-10x faster
1860 than walking the bitmap.
1861 If this is somehow a significant lose for some cases, we can
1862 choose which set to walk based on which set is smaller. */
1863 unsigned int i;
1864 bitmap_iterator bi;
1865 bitmap exprset = value_expressions[val];
1867 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1868 return expression_for_id (i);
1870 return NULL;
1873 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1874 BLOCK by seeing if it is not killed in the block. Note that we are
1875 only determining whether there is a store that kills it. Because
1876 of the order in which clean iterates over values, we are guaranteed
1877 that altered operands will have caused us to be eliminated from the
1878 ANTIC_IN set already. */
1880 static bool
1881 value_dies_in_block_x (pre_expr expr, basic_block block)
1883 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1884 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1885 gimple def;
1886 gimple_stmt_iterator gsi;
1887 unsigned id = get_expression_id (expr);
1888 bool res = false;
1889 ao_ref ref;
1891 if (!vuse)
1892 return false;
1894 /* Lookup a previously calculated result. */
1895 if (EXPR_DIES (block)
1896 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1897 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1899 /* A memory expression {e, VUSE} dies in the block if there is a
1900 statement that may clobber e. If, starting statement walk from the
1901 top of the basic block, a statement uses VUSE there can be no kill
1902 inbetween that use and the original statement that loaded {e, VUSE},
1903 so we can stop walking. */
1904 ref.base = NULL_TREE;
1905 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1907 tree def_vuse, def_vdef;
1908 def = gsi_stmt (gsi);
1909 def_vuse = gimple_vuse (def);
1910 def_vdef = gimple_vdef (def);
1912 /* Not a memory statement. */
1913 if (!def_vuse)
1914 continue;
1916 /* Not a may-def. */
1917 if (!def_vdef)
1919 /* A load with the same VUSE, we're done. */
1920 if (def_vuse == vuse)
1921 break;
1923 continue;
1926 /* Init ref only if we really need it. */
1927 if (ref.base == NULL_TREE
1928 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1929 refx->operands))
1931 res = true;
1932 break;
1934 /* If the statement may clobber expr, it dies. */
1935 if (stmt_may_clobber_ref_p_1 (def, &ref))
1937 res = true;
1938 break;
1942 /* Remember the result. */
1943 if (!EXPR_DIES (block))
1944 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1945 bitmap_set_bit (EXPR_DIES (block), id * 2);
1946 if (res)
1947 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1949 return res;
1953 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1954 contains its value-id. */
1956 static bool
1957 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1959 if (op && TREE_CODE (op) == SSA_NAME)
1961 unsigned int value_id = VN_INFO (op)->value_id;
1962 if (!(bitmap_set_contains_value (set1, value_id)
1963 || (set2 && bitmap_set_contains_value (set2, value_id))))
1964 return false;
1966 return true;
1969 /* Determine if the expression EXPR is valid in SET1 U SET2.
1970 ONLY SET2 CAN BE NULL.
1971 This means that we have a leader for each part of the expression
1972 (if it consists of values), or the expression is an SSA_NAME.
1973 For loads/calls, we also see if the vuse is killed in this block. */
1975 static bool
1976 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr)
1978 switch (expr->kind)
1980 case NAME:
1981 /* By construction all NAMEs are available. Non-available
1982 NAMEs are removed by subtracting TMP_GEN from the sets. */
1983 return true;
1984 case NARY:
1986 unsigned int i;
1987 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1988 for (i = 0; i < nary->length; i++)
1989 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1990 return false;
1991 return true;
1993 break;
1994 case REFERENCE:
1996 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1997 vn_reference_op_t vro;
1998 unsigned int i;
2000 FOR_EACH_VEC_ELT (ref->operands, i, vro)
2002 if (!op_valid_in_sets (set1, set2, vro->op0)
2003 || !op_valid_in_sets (set1, set2, vro->op1)
2004 || !op_valid_in_sets (set1, set2, vro->op2))
2005 return false;
2007 return true;
2009 default:
2010 gcc_unreachable ();
2014 /* Clean the set of expressions that are no longer valid in SET1 or
2015 SET2. This means expressions that are made up of values we have no
2016 leaders for in SET1 or SET2. This version is used for partial
2017 anticipation, which means it is not valid in either ANTIC_IN or
2018 PA_IN. */
2020 static void
2021 dependent_clean (bitmap_set_t set1, bitmap_set_t set2)
2023 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
2024 pre_expr expr;
2025 int i;
2027 FOR_EACH_VEC_ELT (exprs, i, expr)
2029 if (!valid_in_sets (set1, set2, expr))
2030 bitmap_remove_from_set (set1, expr);
2032 exprs.release ();
2035 /* Clean the set of expressions that are no longer valid in SET. This
2036 means expressions that are made up of values we have no leaders for
2037 in SET. */
2039 static void
2040 clean (bitmap_set_t set)
2042 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set);
2043 pre_expr expr;
2044 int i;
2046 FOR_EACH_VEC_ELT (exprs, i, expr)
2048 if (!valid_in_sets (set, NULL, expr))
2049 bitmap_remove_from_set (set, expr);
2051 exprs.release ();
2054 /* Clean the set of expressions that are no longer valid in SET because
2055 they are clobbered in BLOCK or because they trap and may not be executed. */
2057 static void
2058 prune_clobbered_mems (bitmap_set_t set, basic_block block)
2060 bitmap_iterator bi;
2061 unsigned i;
2063 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2065 pre_expr expr = expression_for_id (i);
2066 if (expr->kind == REFERENCE)
2068 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2069 if (ref->vuse)
2071 gimple def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
2072 if (!gimple_nop_p (def_stmt)
2073 && ((gimple_bb (def_stmt) != block
2074 && !dominated_by_p (CDI_DOMINATORS,
2075 block, gimple_bb (def_stmt)))
2076 || (gimple_bb (def_stmt) == block
2077 && value_dies_in_block_x (expr, block))))
2078 bitmap_remove_from_set (set, expr);
2081 else if (expr->kind == NARY)
2083 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2084 /* If the NARY may trap make sure the block does not contain
2085 a possible exit point.
2086 ??? This is overly conservative if we translate AVAIL_OUT
2087 as the available expression might be after the exit point. */
2088 if (BB_MAY_NOTRETURN (block)
2089 && vn_nary_may_trap (nary))
2090 bitmap_remove_from_set (set, expr);
2095 static sbitmap has_abnormal_preds;
2097 /* List of blocks that may have changed during ANTIC computation and
2098 thus need to be iterated over. */
2100 static sbitmap changed_blocks;
2102 /* Compute the ANTIC set for BLOCK.
2104 If succs(BLOCK) > 1 then
2105 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2106 else if succs(BLOCK) == 1 then
2107 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2109 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2112 static bool
2113 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2115 bool changed = false;
2116 bitmap_set_t S, old, ANTIC_OUT;
2117 bitmap_iterator bi;
2118 unsigned int bii;
2119 edge e;
2120 edge_iterator ei;
2122 old = ANTIC_OUT = S = NULL;
2123 BB_VISITED (block) = 1;
2125 /* If any edges from predecessors are abnormal, antic_in is empty,
2126 so do nothing. */
2127 if (block_has_abnormal_pred_edge)
2128 goto maybe_dump_sets;
2130 old = ANTIC_IN (block);
2131 ANTIC_OUT = bitmap_set_new ();
2133 /* If the block has no successors, ANTIC_OUT is empty. */
2134 if (EDGE_COUNT (block->succs) == 0)
2136 /* If we have one successor, we could have some phi nodes to
2137 translate through. */
2138 else if (single_succ_p (block))
2140 basic_block succ_bb = single_succ (block);
2141 gcc_assert (BB_VISITED (succ_bb));
2142 phi_translate_set (ANTIC_OUT, ANTIC_IN (succ_bb), block, succ_bb);
2144 /* If we have multiple successors, we take the intersection of all of
2145 them. Note that in the case of loop exit phi nodes, we may have
2146 phis to translate through. */
2147 else
2149 size_t i;
2150 basic_block bprime, first = NULL;
2152 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2153 FOR_EACH_EDGE (e, ei, block->succs)
2155 if (!first
2156 && BB_VISITED (e->dest))
2157 first = e->dest;
2158 else if (BB_VISITED (e->dest))
2159 worklist.quick_push (e->dest);
2162 /* Of multiple successors we have to have visited one already
2163 which is guaranteed by iteration order. */
2164 gcc_assert (first != NULL);
2166 phi_translate_set (ANTIC_OUT, ANTIC_IN (first), block, first);
2168 FOR_EACH_VEC_ELT (worklist, i, bprime)
2170 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2172 bitmap_set_t tmp = bitmap_set_new ();
2173 phi_translate_set (tmp, ANTIC_IN (bprime), block, bprime);
2174 bitmap_set_and (ANTIC_OUT, tmp);
2175 bitmap_set_free (tmp);
2177 else
2178 bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2182 /* Prune expressions that are clobbered in block and thus become
2183 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2184 prune_clobbered_mems (ANTIC_OUT, block);
2186 /* Generate ANTIC_OUT - TMP_GEN. */
2187 S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2189 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2190 ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2191 TMP_GEN (block));
2193 /* Then union in the ANTIC_OUT - TMP_GEN values,
2194 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2195 FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2196 bitmap_value_insert_into_set (ANTIC_IN (block),
2197 expression_for_id (bii));
2199 clean (ANTIC_IN (block));
2201 if (!bitmap_set_equal (old, ANTIC_IN (block)))
2203 changed = true;
2204 bitmap_set_bit (changed_blocks, block->index);
2205 FOR_EACH_EDGE (e, ei, block->preds)
2206 bitmap_set_bit (changed_blocks, e->src->index);
2208 else
2209 bitmap_clear_bit (changed_blocks, block->index);
2211 maybe_dump_sets:
2212 if (dump_file && (dump_flags & TDF_DETAILS))
2214 if (ANTIC_OUT)
2215 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2217 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2218 block->index);
2220 if (S)
2221 print_bitmap_set (dump_file, S, "S", block->index);
2223 if (old)
2224 bitmap_set_free (old);
2225 if (S)
2226 bitmap_set_free (S);
2227 if (ANTIC_OUT)
2228 bitmap_set_free (ANTIC_OUT);
2229 return changed;
2232 /* Compute PARTIAL_ANTIC for BLOCK.
2234 If succs(BLOCK) > 1 then
2235 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2236 in ANTIC_OUT for all succ(BLOCK)
2237 else if succs(BLOCK) == 1 then
2238 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2240 PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2241 - ANTIC_IN[BLOCK])
2244 static bool
2245 compute_partial_antic_aux (basic_block block,
2246 bool block_has_abnormal_pred_edge)
2248 bool changed = false;
2249 bitmap_set_t old_PA_IN;
2250 bitmap_set_t PA_OUT;
2251 edge e;
2252 edge_iterator ei;
2253 unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2255 old_PA_IN = PA_OUT = NULL;
2257 /* If any edges from predecessors are abnormal, antic_in is empty,
2258 so do nothing. */
2259 if (block_has_abnormal_pred_edge)
2260 goto maybe_dump_sets;
2262 /* If there are too many partially anticipatable values in the
2263 block, phi_translate_set can take an exponential time: stop
2264 before the translation starts. */
2265 if (max_pa
2266 && single_succ_p (block)
2267 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2268 goto maybe_dump_sets;
2270 old_PA_IN = PA_IN (block);
2271 PA_OUT = bitmap_set_new ();
2273 /* If the block has no successors, ANTIC_OUT is empty. */
2274 if (EDGE_COUNT (block->succs) == 0)
2276 /* If we have one successor, we could have some phi nodes to
2277 translate through. Note that we can't phi translate across DFS
2278 back edges in partial antic, because it uses a union operation on
2279 the successors. For recurrences like IV's, we will end up
2280 generating a new value in the set on each go around (i + 3 (VH.1)
2281 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2282 else if (single_succ_p (block))
2284 basic_block succ = single_succ (block);
2285 if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2286 phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2288 /* If we have multiple successors, we take the union of all of
2289 them. */
2290 else
2292 size_t i;
2293 basic_block bprime;
2295 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2296 FOR_EACH_EDGE (e, ei, block->succs)
2298 if (e->flags & EDGE_DFS_BACK)
2299 continue;
2300 worklist.quick_push (e->dest);
2302 if (worklist.length () > 0)
2304 FOR_EACH_VEC_ELT (worklist, i, bprime)
2306 unsigned int i;
2307 bitmap_iterator bi;
2309 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2310 bitmap_value_insert_into_set (PA_OUT,
2311 expression_for_id (i));
2312 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2314 bitmap_set_t pa_in = bitmap_set_new ();
2315 phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2316 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2317 bitmap_value_insert_into_set (PA_OUT,
2318 expression_for_id (i));
2319 bitmap_set_free (pa_in);
2321 else
2322 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2323 bitmap_value_insert_into_set (PA_OUT,
2324 expression_for_id (i));
2329 /* Prune expressions that are clobbered in block and thus become
2330 invalid if translated from PA_OUT to PA_IN. */
2331 prune_clobbered_mems (PA_OUT, block);
2333 /* PA_IN starts with PA_OUT - TMP_GEN.
2334 Then we subtract things from ANTIC_IN. */
2335 PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2337 /* For partial antic, we want to put back in the phi results, since
2338 we will properly avoid making them partially antic over backedges. */
2339 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2340 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2342 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2343 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2345 dependent_clean (PA_IN (block), ANTIC_IN (block));
2347 if (!bitmap_set_equal (old_PA_IN, PA_IN (block)))
2349 changed = true;
2350 bitmap_set_bit (changed_blocks, block->index);
2351 FOR_EACH_EDGE (e, ei, block->preds)
2352 bitmap_set_bit (changed_blocks, e->src->index);
2354 else
2355 bitmap_clear_bit (changed_blocks, block->index);
2357 maybe_dump_sets:
2358 if (dump_file && (dump_flags & TDF_DETAILS))
2360 if (PA_OUT)
2361 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2363 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2365 if (old_PA_IN)
2366 bitmap_set_free (old_PA_IN);
2367 if (PA_OUT)
2368 bitmap_set_free (PA_OUT);
2369 return changed;
2372 /* Compute ANTIC and partial ANTIC sets. */
2374 static void
2375 compute_antic (void)
2377 bool changed = true;
2378 int num_iterations = 0;
2379 basic_block block;
2380 int i;
2382 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2383 We pre-build the map of blocks with incoming abnormal edges here. */
2384 has_abnormal_preds = sbitmap_alloc (last_basic_block_for_fn (cfun));
2385 bitmap_clear (has_abnormal_preds);
2387 FOR_ALL_BB_FN (block, cfun)
2389 edge_iterator ei;
2390 edge e;
2392 FOR_EACH_EDGE (e, ei, block->preds)
2394 e->flags &= ~EDGE_DFS_BACK;
2395 if (e->flags & EDGE_ABNORMAL)
2397 bitmap_set_bit (has_abnormal_preds, block->index);
2398 break;
2402 BB_VISITED (block) = 0;
2404 /* While we are here, give empty ANTIC_IN sets to each block. */
2405 ANTIC_IN (block) = bitmap_set_new ();
2406 PA_IN (block) = bitmap_set_new ();
2409 /* At the exit block we anticipate nothing. */
2410 BB_VISITED (EXIT_BLOCK_PTR_FOR_FN (cfun)) = 1;
2412 changed_blocks = sbitmap_alloc (last_basic_block_for_fn (cfun) + 1);
2413 bitmap_ones (changed_blocks);
2414 while (changed)
2416 if (dump_file && (dump_flags & TDF_DETAILS))
2417 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2418 /* ??? We need to clear our PHI translation cache here as the
2419 ANTIC sets shrink and we restrict valid translations to
2420 those having operands with leaders in ANTIC. Same below
2421 for PA ANTIC computation. */
2422 num_iterations++;
2423 changed = false;
2424 for (i = postorder_num - 1; i >= 0; i--)
2426 if (bitmap_bit_p (changed_blocks, postorder[i]))
2428 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2429 changed |= compute_antic_aux (block,
2430 bitmap_bit_p (has_abnormal_preds,
2431 block->index));
2434 /* Theoretically possible, but *highly* unlikely. */
2435 gcc_checking_assert (num_iterations < 500);
2438 statistics_histogram_event (cfun, "compute_antic iterations",
2439 num_iterations);
2441 if (do_partial_partial)
2443 bitmap_ones (changed_blocks);
2444 mark_dfs_back_edges ();
2445 num_iterations = 0;
2446 changed = true;
2447 while (changed)
2449 if (dump_file && (dump_flags & TDF_DETAILS))
2450 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2451 num_iterations++;
2452 changed = false;
2453 for (i = postorder_num - 1 ; i >= 0; i--)
2455 if (bitmap_bit_p (changed_blocks, postorder[i]))
2457 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2458 changed
2459 |= compute_partial_antic_aux (block,
2460 bitmap_bit_p (has_abnormal_preds,
2461 block->index));
2464 /* Theoretically possible, but *highly* unlikely. */
2465 gcc_checking_assert (num_iterations < 500);
2467 statistics_histogram_event (cfun, "compute_partial_antic iterations",
2468 num_iterations);
2470 sbitmap_free (has_abnormal_preds);
2471 sbitmap_free (changed_blocks);
2475 /* Inserted expressions are placed onto this worklist, which is used
2476 for performing quick dead code elimination of insertions we made
2477 that didn't turn out to be necessary. */
2478 static bitmap inserted_exprs;
2480 /* The actual worker for create_component_ref_by_pieces. */
2482 static tree
2483 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2484 unsigned int *operand, gimple_seq *stmts)
2486 vn_reference_op_t currop = &ref->operands[*operand];
2487 tree genop;
2488 ++*operand;
2489 switch (currop->opcode)
2491 case CALL_EXPR:
2493 tree folded, sc = NULL_TREE;
2494 unsigned int nargs = 0;
2495 tree fn, *args;
2496 if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2497 fn = currop->op0;
2498 else
2499 fn = find_or_generate_expression (block, currop->op0, stmts);
2500 if (!fn)
2501 return NULL_TREE;
2502 if (currop->op1)
2504 sc = find_or_generate_expression (block, currop->op1, stmts);
2505 if (!sc)
2506 return NULL_TREE;
2508 args = XNEWVEC (tree, ref->operands.length () - 1);
2509 while (*operand < ref->operands.length ())
2511 args[nargs] = create_component_ref_by_pieces_1 (block, ref,
2512 operand, stmts);
2513 if (!args[nargs])
2514 return NULL_TREE;
2515 nargs++;
2517 folded = build_call_array (currop->type,
2518 (TREE_CODE (fn) == FUNCTION_DECL
2519 ? build_fold_addr_expr (fn) : fn),
2520 nargs, args);
2521 if (currop->with_bounds)
2522 CALL_WITH_BOUNDS_P (folded) = true;
2523 free (args);
2524 if (sc)
2525 CALL_EXPR_STATIC_CHAIN (folded) = sc;
2526 return folded;
2529 case MEM_REF:
2531 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2532 stmts);
2533 if (!baseop)
2534 return NULL_TREE;
2535 tree offset = currop->op0;
2536 if (TREE_CODE (baseop) == ADDR_EXPR
2537 && handled_component_p (TREE_OPERAND (baseop, 0)))
2539 HOST_WIDE_INT off;
2540 tree base;
2541 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2542 &off);
2543 gcc_assert (base);
2544 offset = int_const_binop (PLUS_EXPR, offset,
2545 build_int_cst (TREE_TYPE (offset),
2546 off));
2547 baseop = build_fold_addr_expr (base);
2549 return fold_build2 (MEM_REF, currop->type, baseop, offset);
2552 case TARGET_MEM_REF:
2554 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2555 vn_reference_op_t nextop = &ref->operands[++*operand];
2556 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2557 stmts);
2558 if (!baseop)
2559 return NULL_TREE;
2560 if (currop->op0)
2562 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2563 if (!genop0)
2564 return NULL_TREE;
2566 if (nextop->op0)
2568 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2569 if (!genop1)
2570 return NULL_TREE;
2572 return build5 (TARGET_MEM_REF, currop->type,
2573 baseop, currop->op2, genop0, currop->op1, genop1);
2576 case ADDR_EXPR:
2577 if (currop->op0)
2579 gcc_assert (is_gimple_min_invariant (currop->op0));
2580 return currop->op0;
2582 /* Fallthrough. */
2583 case REALPART_EXPR:
2584 case IMAGPART_EXPR:
2585 case VIEW_CONVERT_EXPR:
2587 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2588 stmts);
2589 if (!genop0)
2590 return NULL_TREE;
2591 return fold_build1 (currop->opcode, currop->type, genop0);
2594 case WITH_SIZE_EXPR:
2596 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2597 stmts);
2598 if (!genop0)
2599 return NULL_TREE;
2600 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2601 if (!genop1)
2602 return NULL_TREE;
2603 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2606 case BIT_FIELD_REF:
2608 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2609 stmts);
2610 if (!genop0)
2611 return NULL_TREE;
2612 tree op1 = currop->op0;
2613 tree op2 = currop->op1;
2614 return fold_build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2617 /* For array ref vn_reference_op's, operand 1 of the array ref
2618 is op0 of the reference op and operand 3 of the array ref is
2619 op1. */
2620 case ARRAY_RANGE_REF:
2621 case ARRAY_REF:
2623 tree genop0;
2624 tree genop1 = currop->op0;
2625 tree genop2 = currop->op1;
2626 tree genop3 = currop->op2;
2627 genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2628 stmts);
2629 if (!genop0)
2630 return NULL_TREE;
2631 genop1 = find_or_generate_expression (block, genop1, stmts);
2632 if (!genop1)
2633 return NULL_TREE;
2634 if (genop2)
2636 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2637 /* Drop zero minimum index if redundant. */
2638 if (integer_zerop (genop2)
2639 && (!domain_type
2640 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2641 genop2 = NULL_TREE;
2642 else
2644 genop2 = find_or_generate_expression (block, genop2, stmts);
2645 if (!genop2)
2646 return NULL_TREE;
2649 if (genop3)
2651 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2652 /* We can't always put a size in units of the element alignment
2653 here as the element alignment may be not visible. See
2654 PR43783. Simply drop the element size for constant
2655 sizes. */
2656 if (tree_int_cst_equal (genop3, TYPE_SIZE_UNIT (elmt_type)))
2657 genop3 = NULL_TREE;
2658 else
2660 genop3 = size_binop (EXACT_DIV_EXPR, genop3,
2661 size_int (TYPE_ALIGN_UNIT (elmt_type)));
2662 genop3 = find_or_generate_expression (block, genop3, stmts);
2663 if (!genop3)
2664 return NULL_TREE;
2667 return build4 (currop->opcode, currop->type, genop0, genop1,
2668 genop2, genop3);
2670 case COMPONENT_REF:
2672 tree op0;
2673 tree op1;
2674 tree genop2 = currop->op1;
2675 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2676 if (!op0)
2677 return NULL_TREE;
2678 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2679 op1 = currop->op0;
2680 if (genop2)
2682 genop2 = find_or_generate_expression (block, genop2, stmts);
2683 if (!genop2)
2684 return NULL_TREE;
2686 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2689 case SSA_NAME:
2691 genop = find_or_generate_expression (block, currop->op0, stmts);
2692 return genop;
2694 case STRING_CST:
2695 case INTEGER_CST:
2696 case COMPLEX_CST:
2697 case VECTOR_CST:
2698 case REAL_CST:
2699 case CONSTRUCTOR:
2700 case VAR_DECL:
2701 case PARM_DECL:
2702 case CONST_DECL:
2703 case RESULT_DECL:
2704 case FUNCTION_DECL:
2705 return currop->op0;
2707 default:
2708 gcc_unreachable ();
2712 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2713 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2714 trying to rename aggregates into ssa form directly, which is a no no.
2716 Thus, this routine doesn't create temporaries, it just builds a
2717 single access expression for the array, calling
2718 find_or_generate_expression to build the innermost pieces.
2720 This function is a subroutine of create_expression_by_pieces, and
2721 should not be called on it's own unless you really know what you
2722 are doing. */
2724 static tree
2725 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2726 gimple_seq *stmts)
2728 unsigned int op = 0;
2729 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2732 /* Find a simple leader for an expression, or generate one using
2733 create_expression_by_pieces from a NARY expression for the value.
2734 BLOCK is the basic_block we are looking for leaders in.
2735 OP is the tree expression to find a leader for or generate.
2736 Returns the leader or NULL_TREE on failure. */
2738 static tree
2739 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2741 pre_expr expr = get_or_alloc_expr_for (op);
2742 unsigned int lookfor = get_expr_value_id (expr);
2743 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2744 if (leader)
2746 if (leader->kind == NAME)
2747 return PRE_EXPR_NAME (leader);
2748 else if (leader->kind == CONSTANT)
2749 return PRE_EXPR_CONSTANT (leader);
2751 /* Defer. */
2752 return NULL_TREE;
2755 /* It must be a complex expression, so generate it recursively. Note
2756 that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2757 where the insert algorithm fails to insert a required expression. */
2758 bitmap exprset = value_expressions[lookfor];
2759 bitmap_iterator bi;
2760 unsigned int i;
2761 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2763 pre_expr temp = expression_for_id (i);
2764 /* We cannot insert random REFERENCE expressions at arbitrary
2765 places. We can insert NARYs which eventually re-materializes
2766 its operand values. */
2767 if (temp->kind == NARY)
2768 return create_expression_by_pieces (block, temp, stmts,
2769 get_expr_type (expr));
2772 /* Defer. */
2773 return NULL_TREE;
2776 #define NECESSARY GF_PLF_1
2778 /* Create an expression in pieces, so that we can handle very complex
2779 expressions that may be ANTIC, but not necessary GIMPLE.
2780 BLOCK is the basic block the expression will be inserted into,
2781 EXPR is the expression to insert (in value form)
2782 STMTS is a statement list to append the necessary insertions into.
2784 This function will die if we hit some value that shouldn't be
2785 ANTIC but is (IE there is no leader for it, or its components).
2786 The function returns NULL_TREE in case a different antic expression
2787 has to be inserted first.
2788 This function may also generate expressions that are themselves
2789 partially or fully redundant. Those that are will be either made
2790 fully redundant during the next iteration of insert (for partially
2791 redundant ones), or eliminated by eliminate (for fully redundant
2792 ones). */
2794 static tree
2795 create_expression_by_pieces (basic_block block, pre_expr expr,
2796 gimple_seq *stmts, tree type)
2798 tree name;
2799 tree folded;
2800 gimple_seq forced_stmts = NULL;
2801 unsigned int value_id;
2802 gimple_stmt_iterator gsi;
2803 tree exprtype = type ? type : get_expr_type (expr);
2804 pre_expr nameexpr;
2805 gassign *newstmt;
2807 switch (expr->kind)
2809 /* We may hit the NAME/CONSTANT case if we have to convert types
2810 that value numbering saw through. */
2811 case NAME:
2812 folded = PRE_EXPR_NAME (expr);
2813 break;
2814 case CONSTANT:
2815 folded = PRE_EXPR_CONSTANT (expr);
2816 break;
2817 case REFERENCE:
2819 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2820 folded = create_component_ref_by_pieces (block, ref, stmts);
2821 if (!folded)
2822 return NULL_TREE;
2824 break;
2825 case NARY:
2827 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2828 tree *genop = XALLOCAVEC (tree, nary->length);
2829 unsigned i;
2830 for (i = 0; i < nary->length; ++i)
2832 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2833 if (!genop[i])
2834 return NULL_TREE;
2835 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2836 may have conversions stripped. */
2837 if (nary->opcode == POINTER_PLUS_EXPR)
2839 if (i == 0)
2840 genop[i] = gimple_convert (&forced_stmts,
2841 nary->type, genop[i]);
2842 else if (i == 1)
2843 genop[i] = gimple_convert (&forced_stmts,
2844 sizetype, genop[i]);
2846 else
2847 genop[i] = gimple_convert (&forced_stmts,
2848 TREE_TYPE (nary->op[i]), genop[i]);
2850 if (nary->opcode == CONSTRUCTOR)
2852 vec<constructor_elt, va_gc> *elts = NULL;
2853 for (i = 0; i < nary->length; ++i)
2854 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2855 folded = build_constructor (nary->type, elts);
2857 else
2859 switch (nary->length)
2861 case 1:
2862 folded = fold_build1 (nary->opcode, nary->type,
2863 genop[0]);
2864 break;
2865 case 2:
2866 folded = fold_build2 (nary->opcode, nary->type,
2867 genop[0], genop[1]);
2868 break;
2869 case 3:
2870 folded = fold_build3 (nary->opcode, nary->type,
2871 genop[0], genop[1], genop[2]);
2872 break;
2873 default:
2874 gcc_unreachable ();
2878 break;
2879 default:
2880 gcc_unreachable ();
2883 if (!useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2884 folded = fold_convert (exprtype, folded);
2886 /* Force the generated expression to be a sequence of GIMPLE
2887 statements.
2888 We have to call unshare_expr because force_gimple_operand may
2889 modify the tree we pass to it. */
2890 gimple_seq tem = NULL;
2891 folded = force_gimple_operand (unshare_expr (folded), &tem,
2892 false, NULL);
2893 gimple_seq_add_seq_without_update (&forced_stmts, tem);
2895 /* If we have any intermediate expressions to the value sets, add them
2896 to the value sets and chain them in the instruction stream. */
2897 if (forced_stmts)
2899 gsi = gsi_start (forced_stmts);
2900 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2902 gimple stmt = gsi_stmt (gsi);
2903 tree forcedname = gimple_get_lhs (stmt);
2904 pre_expr nameexpr;
2906 if (TREE_CODE (forcedname) == SSA_NAME)
2908 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2909 VN_INFO_GET (forcedname)->valnum = forcedname;
2910 VN_INFO (forcedname)->value_id = get_next_value_id ();
2911 nameexpr = get_or_alloc_expr_for_name (forcedname);
2912 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2913 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2914 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2917 gimple_set_vuse (stmt, BB_LIVE_VOP_ON_EXIT (block));
2918 gimple_set_modified (stmt, true);
2920 gimple_seq_add_seq (stmts, forced_stmts);
2923 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2924 newstmt = gimple_build_assign (name, folded);
2925 gimple_set_vuse (newstmt, BB_LIVE_VOP_ON_EXIT (block));
2926 gimple_set_modified (newstmt, true);
2927 gimple_set_plf (newstmt, NECESSARY, false);
2929 gimple_seq_add_stmt (stmts, newstmt);
2930 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
2932 /* Fold the last statement. */
2933 gsi = gsi_last (*stmts);
2934 if (fold_stmt_inplace (&gsi))
2935 update_stmt (gsi_stmt (gsi));
2937 /* Add a value number to the temporary.
2938 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2939 we are creating the expression by pieces, and this particular piece of
2940 the expression may have been represented. There is no harm in replacing
2941 here. */
2942 value_id = get_expr_value_id (expr);
2943 VN_INFO_GET (name)->value_id = value_id;
2944 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2945 if (VN_INFO (name)->valnum == NULL_TREE)
2946 VN_INFO (name)->valnum = name;
2947 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2948 nameexpr = get_or_alloc_expr_for_name (name);
2949 add_to_value (value_id, nameexpr);
2950 if (NEW_SETS (block))
2951 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2952 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2954 pre_stats.insertions++;
2955 if (dump_file && (dump_flags & TDF_DETAILS))
2957 fprintf (dump_file, "Inserted ");
2958 print_gimple_stmt (dump_file, newstmt, 0, 0);
2959 fprintf (dump_file, " in predecessor %d (%04d)\n",
2960 block->index, value_id);
2963 return name;
2967 /* Insert the to-be-made-available values of expression EXPRNUM for each
2968 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
2969 merge the result with a phi node, given the same value number as
2970 NODE. Return true if we have inserted new stuff. */
2972 static bool
2973 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
2974 vec<pre_expr> avail)
2976 pre_expr expr = expression_for_id (exprnum);
2977 pre_expr newphi;
2978 unsigned int val = get_expr_value_id (expr);
2979 edge pred;
2980 bool insertions = false;
2981 bool nophi = false;
2982 basic_block bprime;
2983 pre_expr eprime;
2984 edge_iterator ei;
2985 tree type = get_expr_type (expr);
2986 tree temp;
2987 gphi *phi;
2989 /* Make sure we aren't creating an induction variable. */
2990 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
2992 bool firstinsideloop = false;
2993 bool secondinsideloop = false;
2994 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
2995 EDGE_PRED (block, 0)->src);
2996 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
2997 EDGE_PRED (block, 1)->src);
2998 /* Induction variables only have one edge inside the loop. */
2999 if ((firstinsideloop ^ secondinsideloop)
3000 && expr->kind != REFERENCE)
3002 if (dump_file && (dump_flags & TDF_DETAILS))
3003 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
3004 nophi = true;
3008 /* Make the necessary insertions. */
3009 FOR_EACH_EDGE (pred, ei, block->preds)
3011 gimple_seq stmts = NULL;
3012 tree builtexpr;
3013 bprime = pred->src;
3014 eprime = avail[pred->dest_idx];
3016 if (eprime->kind != NAME && eprime->kind != CONSTANT)
3018 builtexpr = create_expression_by_pieces (bprime, eprime,
3019 &stmts, type);
3020 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
3021 gsi_insert_seq_on_edge (pred, stmts);
3022 if (!builtexpr)
3024 /* We cannot insert a PHI node if we failed to insert
3025 on one edge. */
3026 nophi = true;
3027 continue;
3029 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
3030 insertions = true;
3032 else if (eprime->kind == CONSTANT)
3034 /* Constants may not have the right type, fold_convert
3035 should give us back a constant with the right type. */
3036 tree constant = PRE_EXPR_CONSTANT (eprime);
3037 if (!useless_type_conversion_p (type, TREE_TYPE (constant)))
3039 tree builtexpr = fold_convert (type, constant);
3040 if (!is_gimple_min_invariant (builtexpr))
3042 tree forcedexpr = force_gimple_operand (builtexpr,
3043 &stmts, true,
3044 NULL);
3045 if (!is_gimple_min_invariant (forcedexpr))
3047 if (forcedexpr != builtexpr)
3049 VN_INFO_GET (forcedexpr)->valnum = PRE_EXPR_CONSTANT (eprime);
3050 VN_INFO (forcedexpr)->value_id = get_expr_value_id (eprime);
3052 if (stmts)
3054 gimple_stmt_iterator gsi;
3055 gsi = gsi_start (stmts);
3056 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3058 gimple stmt = gsi_stmt (gsi);
3059 tree lhs = gimple_get_lhs (stmt);
3060 if (TREE_CODE (lhs) == SSA_NAME)
3061 bitmap_set_bit (inserted_exprs,
3062 SSA_NAME_VERSION (lhs));
3063 gimple_set_plf (stmt, NECESSARY, false);
3065 gsi_insert_seq_on_edge (pred, stmts);
3067 avail[pred->dest_idx]
3068 = get_or_alloc_expr_for_name (forcedexpr);
3071 else
3072 avail[pred->dest_idx]
3073 = get_or_alloc_expr_for_constant (builtexpr);
3076 else if (eprime->kind == NAME)
3078 /* We may have to do a conversion because our value
3079 numbering can look through types in certain cases, but
3080 our IL requires all operands of a phi node have the same
3081 type. */
3082 tree name = PRE_EXPR_NAME (eprime);
3083 if (!useless_type_conversion_p (type, TREE_TYPE (name)))
3085 tree builtexpr;
3086 tree forcedexpr;
3087 builtexpr = fold_convert (type, name);
3088 forcedexpr = force_gimple_operand (builtexpr,
3089 &stmts, true,
3090 NULL);
3092 if (forcedexpr != name)
3094 VN_INFO_GET (forcedexpr)->valnum = VN_INFO (name)->valnum;
3095 VN_INFO (forcedexpr)->value_id = VN_INFO (name)->value_id;
3098 if (stmts)
3100 gimple_stmt_iterator gsi;
3101 gsi = gsi_start (stmts);
3102 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3104 gimple stmt = gsi_stmt (gsi);
3105 tree lhs = gimple_get_lhs (stmt);
3106 if (TREE_CODE (lhs) == SSA_NAME)
3107 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
3108 gimple_set_plf (stmt, NECESSARY, false);
3110 gsi_insert_seq_on_edge (pred, stmts);
3112 avail[pred->dest_idx] = get_or_alloc_expr_for_name (forcedexpr);
3116 /* If we didn't want a phi node, and we made insertions, we still have
3117 inserted new stuff, and thus return true. If we didn't want a phi node,
3118 and didn't make insertions, we haven't added anything new, so return
3119 false. */
3120 if (nophi && insertions)
3121 return true;
3122 else if (nophi && !insertions)
3123 return false;
3125 /* Now build a phi for the new variable. */
3126 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3127 phi = create_phi_node (temp, block);
3129 gimple_set_plf (phi, NECESSARY, false);
3130 VN_INFO_GET (temp)->value_id = val;
3131 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3132 if (VN_INFO (temp)->valnum == NULL_TREE)
3133 VN_INFO (temp)->valnum = temp;
3134 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3135 FOR_EACH_EDGE (pred, ei, block->preds)
3137 pre_expr ae = avail[pred->dest_idx];
3138 gcc_assert (get_expr_type (ae) == type
3139 || useless_type_conversion_p (type, get_expr_type (ae)));
3140 if (ae->kind == CONSTANT)
3141 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3142 pred, UNKNOWN_LOCATION);
3143 else
3144 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3147 newphi = get_or_alloc_expr_for_name (temp);
3148 add_to_value (val, newphi);
3150 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3151 this insertion, since we test for the existence of this value in PHI_GEN
3152 before proceeding with the partial redundancy checks in insert_aux.
3154 The value may exist in AVAIL_OUT, in particular, it could be represented
3155 by the expression we are trying to eliminate, in which case we want the
3156 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3157 inserted there.
3159 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3160 this block, because if it did, it would have existed in our dominator's
3161 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3164 bitmap_insert_into_set (PHI_GEN (block), newphi);
3165 bitmap_value_replace_in_set (AVAIL_OUT (block),
3166 newphi);
3167 bitmap_insert_into_set (NEW_SETS (block),
3168 newphi);
3170 if (dump_file && (dump_flags & TDF_DETAILS))
3172 fprintf (dump_file, "Created phi ");
3173 print_gimple_stmt (dump_file, phi, 0, 0);
3174 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3176 pre_stats.phis++;
3177 return true;
3182 /* Perform insertion of partially redundant values.
3183 For BLOCK, do the following:
3184 1. Propagate the NEW_SETS of the dominator into the current block.
3185 If the block has multiple predecessors,
3186 2a. Iterate over the ANTIC expressions for the block to see if
3187 any of them are partially redundant.
3188 2b. If so, insert them into the necessary predecessors to make
3189 the expression fully redundant.
3190 2c. Insert a new PHI merging the values of the predecessors.
3191 2d. Insert the new PHI, and the new expressions, into the
3192 NEW_SETS set.
3193 3. Recursively call ourselves on the dominator children of BLOCK.
3195 Steps 1, 2a, and 3 are done by insert_aux. 2b, 2c and 2d are done by
3196 do_regular_insertion and do_partial_insertion.
3200 static bool
3201 do_regular_insertion (basic_block block, basic_block dom)
3203 bool new_stuff = false;
3204 vec<pre_expr> exprs;
3205 pre_expr expr;
3206 auto_vec<pre_expr> avail;
3207 int i;
3209 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3210 avail.safe_grow (EDGE_COUNT (block->preds));
3212 FOR_EACH_VEC_ELT (exprs, i, expr)
3214 if (expr->kind == NARY
3215 || expr->kind == REFERENCE)
3217 unsigned int val;
3218 bool by_some = false;
3219 bool cant_insert = false;
3220 bool all_same = true;
3221 pre_expr first_s = NULL;
3222 edge pred;
3223 basic_block bprime;
3224 pre_expr eprime = NULL;
3225 edge_iterator ei;
3226 pre_expr edoubleprime = NULL;
3227 bool do_insertion = false;
3229 val = get_expr_value_id (expr);
3230 if (bitmap_set_contains_value (PHI_GEN (block), val))
3231 continue;
3232 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3234 if (dump_file && (dump_flags & TDF_DETAILS))
3236 fprintf (dump_file, "Found fully redundant value: ");
3237 print_pre_expr (dump_file, expr);
3238 fprintf (dump_file, "\n");
3240 continue;
3243 FOR_EACH_EDGE (pred, ei, block->preds)
3245 unsigned int vprime;
3247 /* We should never run insertion for the exit block
3248 and so not come across fake pred edges. */
3249 gcc_assert (!(pred->flags & EDGE_FAKE));
3250 bprime = pred->src;
3251 eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3252 bprime, block);
3254 /* eprime will generally only be NULL if the
3255 value of the expression, translated
3256 through the PHI for this predecessor, is
3257 undefined. If that is the case, we can't
3258 make the expression fully redundant,
3259 because its value is undefined along a
3260 predecessor path. We can thus break out
3261 early because it doesn't matter what the
3262 rest of the results are. */
3263 if (eprime == NULL)
3265 avail[pred->dest_idx] = NULL;
3266 cant_insert = true;
3267 break;
3270 eprime = fully_constant_expression (eprime);
3271 vprime = get_expr_value_id (eprime);
3272 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3273 vprime);
3274 if (edoubleprime == NULL)
3276 avail[pred->dest_idx] = eprime;
3277 all_same = false;
3279 else
3281 avail[pred->dest_idx] = edoubleprime;
3282 by_some = true;
3283 /* We want to perform insertions to remove a redundancy on
3284 a path in the CFG we want to optimize for speed. */
3285 if (optimize_edge_for_speed_p (pred))
3286 do_insertion = true;
3287 if (first_s == NULL)
3288 first_s = edoubleprime;
3289 else if (!pre_expr_d::equal (first_s, edoubleprime))
3290 all_same = false;
3293 /* If we can insert it, it's not the same value
3294 already existing along every predecessor, and
3295 it's defined by some predecessor, it is
3296 partially redundant. */
3297 if (!cant_insert && !all_same && by_some)
3299 if (!do_insertion)
3301 if (dump_file && (dump_flags & TDF_DETAILS))
3303 fprintf (dump_file, "Skipping partial redundancy for "
3304 "expression ");
3305 print_pre_expr (dump_file, expr);
3306 fprintf (dump_file, " (%04d), no redundancy on to be "
3307 "optimized for speed edge\n", val);
3310 else if (dbg_cnt (treepre_insert))
3312 if (dump_file && (dump_flags & TDF_DETAILS))
3314 fprintf (dump_file, "Found partial redundancy for "
3315 "expression ");
3316 print_pre_expr (dump_file, expr);
3317 fprintf (dump_file, " (%04d)\n",
3318 get_expr_value_id (expr));
3320 if (insert_into_preds_of_block (block,
3321 get_expression_id (expr),
3322 avail))
3323 new_stuff = true;
3326 /* If all edges produce the same value and that value is
3327 an invariant, then the PHI has the same value on all
3328 edges. Note this. */
3329 else if (!cant_insert && all_same)
3331 gcc_assert (edoubleprime->kind == CONSTANT
3332 || edoubleprime->kind == NAME);
3334 tree temp = make_temp_ssa_name (get_expr_type (expr),
3335 NULL, "pretmp");
3336 gassign *assign
3337 = gimple_build_assign (temp,
3338 edoubleprime->kind == CONSTANT ?
3339 PRE_EXPR_CONSTANT (edoubleprime) :
3340 PRE_EXPR_NAME (edoubleprime));
3341 gimple_stmt_iterator gsi = gsi_after_labels (block);
3342 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3344 gimple_set_plf (assign, NECESSARY, false);
3345 VN_INFO_GET (temp)->value_id = val;
3346 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3347 if (VN_INFO (temp)->valnum == NULL_TREE)
3348 VN_INFO (temp)->valnum = temp;
3349 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3350 pre_expr newe = get_or_alloc_expr_for_name (temp);
3351 add_to_value (val, newe);
3352 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3353 bitmap_insert_into_set (NEW_SETS (block), newe);
3358 exprs.release ();
3359 return new_stuff;
3363 /* Perform insertion for partially anticipatable expressions. There
3364 is only one case we will perform insertion for these. This case is
3365 if the expression is partially anticipatable, and fully available.
3366 In this case, we know that putting it earlier will enable us to
3367 remove the later computation. */
3370 static bool
3371 do_partial_partial_insertion (basic_block block, basic_block dom)
3373 bool new_stuff = false;
3374 vec<pre_expr> exprs;
3375 pre_expr expr;
3376 auto_vec<pre_expr> avail;
3377 int i;
3379 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3380 avail.safe_grow (EDGE_COUNT (block->preds));
3382 FOR_EACH_VEC_ELT (exprs, i, expr)
3384 if (expr->kind == NARY
3385 || expr->kind == REFERENCE)
3387 unsigned int val;
3388 bool by_all = true;
3389 bool cant_insert = false;
3390 edge pred;
3391 basic_block bprime;
3392 pre_expr eprime = NULL;
3393 edge_iterator ei;
3395 val = get_expr_value_id (expr);
3396 if (bitmap_set_contains_value (PHI_GEN (block), val))
3397 continue;
3398 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3399 continue;
3401 FOR_EACH_EDGE (pred, ei, block->preds)
3403 unsigned int vprime;
3404 pre_expr edoubleprime;
3406 /* We should never run insertion for the exit block
3407 and so not come across fake pred edges. */
3408 gcc_assert (!(pred->flags & EDGE_FAKE));
3409 bprime = pred->src;
3410 eprime = phi_translate (expr, ANTIC_IN (block),
3411 PA_IN (block),
3412 bprime, block);
3414 /* eprime will generally only be NULL if the
3415 value of the expression, translated
3416 through the PHI for this predecessor, is
3417 undefined. If that is the case, we can't
3418 make the expression fully redundant,
3419 because its value is undefined along a
3420 predecessor path. We can thus break out
3421 early because it doesn't matter what the
3422 rest of the results are. */
3423 if (eprime == NULL)
3425 avail[pred->dest_idx] = NULL;
3426 cant_insert = true;
3427 break;
3430 eprime = fully_constant_expression (eprime);
3431 vprime = get_expr_value_id (eprime);
3432 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3433 avail[pred->dest_idx] = edoubleprime;
3434 if (edoubleprime == NULL)
3436 by_all = false;
3437 break;
3441 /* If we can insert it, it's not the same value
3442 already existing along every predecessor, and
3443 it's defined by some predecessor, it is
3444 partially redundant. */
3445 if (!cant_insert && by_all)
3447 edge succ;
3448 bool do_insertion = false;
3450 /* Insert only if we can remove a later expression on a path
3451 that we want to optimize for speed.
3452 The phi node that we will be inserting in BLOCK is not free,
3453 and inserting it for the sake of !optimize_for_speed successor
3454 may cause regressions on the speed path. */
3455 FOR_EACH_EDGE (succ, ei, block->succs)
3457 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3458 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3460 if (optimize_edge_for_speed_p (succ))
3461 do_insertion = true;
3465 if (!do_insertion)
3467 if (dump_file && (dump_flags & TDF_DETAILS))
3469 fprintf (dump_file, "Skipping partial partial redundancy "
3470 "for expression ");
3471 print_pre_expr (dump_file, expr);
3472 fprintf (dump_file, " (%04d), not (partially) anticipated "
3473 "on any to be optimized for speed edges\n", val);
3476 else if (dbg_cnt (treepre_insert))
3478 pre_stats.pa_insert++;
3479 if (dump_file && (dump_flags & TDF_DETAILS))
3481 fprintf (dump_file, "Found partial partial redundancy "
3482 "for expression ");
3483 print_pre_expr (dump_file, expr);
3484 fprintf (dump_file, " (%04d)\n",
3485 get_expr_value_id (expr));
3487 if (insert_into_preds_of_block (block,
3488 get_expression_id (expr),
3489 avail))
3490 new_stuff = true;
3496 exprs.release ();
3497 return new_stuff;
3500 static bool
3501 insert_aux (basic_block block)
3503 basic_block son;
3504 bool new_stuff = false;
3506 if (block)
3508 basic_block dom;
3509 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3510 if (dom)
3512 unsigned i;
3513 bitmap_iterator bi;
3514 bitmap_set_t newset = NEW_SETS (dom);
3515 if (newset)
3517 /* Note that we need to value_replace both NEW_SETS, and
3518 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3519 represented by some non-simple expression here that we want
3520 to replace it with. */
3521 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3523 pre_expr expr = expression_for_id (i);
3524 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3525 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3528 if (!single_pred_p (block))
3530 new_stuff |= do_regular_insertion (block, dom);
3531 if (do_partial_partial)
3532 new_stuff |= do_partial_partial_insertion (block, dom);
3536 for (son = first_dom_son (CDI_DOMINATORS, block);
3537 son;
3538 son = next_dom_son (CDI_DOMINATORS, son))
3540 new_stuff |= insert_aux (son);
3543 return new_stuff;
3546 /* Perform insertion of partially redundant values. */
3548 static void
3549 insert (void)
3551 bool new_stuff = true;
3552 basic_block bb;
3553 int num_iterations = 0;
3555 FOR_ALL_BB_FN (bb, cfun)
3556 NEW_SETS (bb) = bitmap_set_new ();
3558 while (new_stuff)
3560 num_iterations++;
3561 if (dump_file && dump_flags & TDF_DETAILS)
3562 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3563 new_stuff = insert_aux (ENTRY_BLOCK_PTR_FOR_FN (cfun));
3565 /* Clear the NEW sets before the next iteration. We have already
3566 fully propagated its contents. */
3567 if (new_stuff)
3568 FOR_ALL_BB_FN (bb, cfun)
3569 bitmap_set_free (NEW_SETS (bb));
3571 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3575 /* Compute the AVAIL set for all basic blocks.
3577 This function performs value numbering of the statements in each basic
3578 block. The AVAIL sets are built from information we glean while doing
3579 this value numbering, since the AVAIL sets contain only one entry per
3580 value.
3582 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3583 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3585 static void
3586 compute_avail (void)
3589 basic_block block, son;
3590 basic_block *worklist;
3591 size_t sp = 0;
3592 unsigned i;
3594 /* We pretend that default definitions are defined in the entry block.
3595 This includes function arguments and the static chain decl. */
3596 for (i = 1; i < num_ssa_names; ++i)
3598 tree name = ssa_name (i);
3599 pre_expr e;
3600 if (!name
3601 || !SSA_NAME_IS_DEFAULT_DEF (name)
3602 || has_zero_uses (name)
3603 || virtual_operand_p (name))
3604 continue;
3606 e = get_or_alloc_expr_for_name (name);
3607 add_to_value (get_expr_value_id (e), e);
3608 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)), e);
3609 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3613 if (dump_file && (dump_flags & TDF_DETAILS))
3615 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3616 "tmp_gen", ENTRY_BLOCK);
3617 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3618 "avail_out", ENTRY_BLOCK);
3621 /* Allocate the worklist. */
3622 worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
3624 /* Seed the algorithm by putting the dominator children of the entry
3625 block on the worklist. */
3626 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
3627 son;
3628 son = next_dom_son (CDI_DOMINATORS, son))
3629 worklist[sp++] = son;
3631 BB_LIVE_VOP_ON_EXIT (ENTRY_BLOCK_PTR_FOR_FN (cfun))
3632 = ssa_default_def (cfun, gimple_vop (cfun));
3634 /* Loop until the worklist is empty. */
3635 while (sp)
3637 gimple stmt;
3638 basic_block dom;
3640 /* Pick a block from the worklist. */
3641 block = worklist[--sp];
3643 /* Initially, the set of available values in BLOCK is that of
3644 its immediate dominator. */
3645 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3646 if (dom)
3648 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3649 BB_LIVE_VOP_ON_EXIT (block) = BB_LIVE_VOP_ON_EXIT (dom);
3652 /* Generate values for PHI nodes. */
3653 for (gphi_iterator gsi = gsi_start_phis (block); !gsi_end_p (gsi);
3654 gsi_next (&gsi))
3656 tree result = gimple_phi_result (gsi.phi ());
3658 /* We have no need for virtual phis, as they don't represent
3659 actual computations. */
3660 if (virtual_operand_p (result))
3662 BB_LIVE_VOP_ON_EXIT (block) = result;
3663 continue;
3666 pre_expr e = get_or_alloc_expr_for_name (result);
3667 add_to_value (get_expr_value_id (e), e);
3668 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3669 bitmap_insert_into_set (PHI_GEN (block), e);
3672 BB_MAY_NOTRETURN (block) = 0;
3674 /* Now compute value numbers and populate value sets with all
3675 the expressions computed in BLOCK. */
3676 for (gimple_stmt_iterator gsi = gsi_start_bb (block); !gsi_end_p (gsi);
3677 gsi_next (&gsi))
3679 ssa_op_iter iter;
3680 tree op;
3682 stmt = gsi_stmt (gsi);
3684 /* Cache whether the basic-block has any non-visible side-effect
3685 or control flow.
3686 If this isn't a call or it is the last stmt in the
3687 basic-block then the CFG represents things correctly. */
3688 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3690 /* Non-looping const functions always return normally.
3691 Otherwise the call might not return or have side-effects
3692 that forbids hoisting possibly trapping expressions
3693 before it. */
3694 int flags = gimple_call_flags (stmt);
3695 if (!(flags & ECF_CONST)
3696 || (flags & ECF_LOOPING_CONST_OR_PURE))
3697 BB_MAY_NOTRETURN (block) = 1;
3700 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3702 pre_expr e = get_or_alloc_expr_for_name (op);
3704 add_to_value (get_expr_value_id (e), e);
3705 bitmap_insert_into_set (TMP_GEN (block), e);
3706 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3709 if (gimple_vdef (stmt))
3710 BB_LIVE_VOP_ON_EXIT (block) = gimple_vdef (stmt);
3712 if (gimple_has_side_effects (stmt)
3713 || stmt_could_throw_p (stmt)
3714 || is_gimple_debug (stmt))
3715 continue;
3717 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3719 if (ssa_undefined_value_p (op))
3720 continue;
3721 pre_expr e = get_or_alloc_expr_for_name (op);
3722 bitmap_value_insert_into_set (EXP_GEN (block), e);
3725 switch (gimple_code (stmt))
3727 case GIMPLE_RETURN:
3728 continue;
3730 case GIMPLE_CALL:
3732 vn_reference_t ref;
3733 vn_reference_s ref1;
3734 pre_expr result = NULL;
3736 /* We can value number only calls to real functions. */
3737 if (gimple_call_internal_p (stmt))
3738 continue;
3740 vn_reference_lookup_call (as_a <gcall *> (stmt), &ref, &ref1);
3741 if (!ref)
3742 continue;
3744 /* If the value of the call is not invalidated in
3745 this block until it is computed, add the expression
3746 to EXP_GEN. */
3747 if (!gimple_vuse (stmt)
3748 || gimple_code
3749 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3750 || gimple_bb (SSA_NAME_DEF_STMT
3751 (gimple_vuse (stmt))) != block)
3753 result = (pre_expr) pool_alloc (pre_expr_pool);
3754 result->kind = REFERENCE;
3755 result->id = 0;
3756 PRE_EXPR_REFERENCE (result) = ref;
3758 get_or_alloc_expression_id (result);
3759 add_to_value (get_expr_value_id (result), result);
3760 bitmap_value_insert_into_set (EXP_GEN (block), result);
3762 continue;
3765 case GIMPLE_ASSIGN:
3767 pre_expr result = NULL;
3768 switch (vn_get_stmt_kind (stmt))
3770 case VN_NARY:
3772 enum tree_code code = gimple_assign_rhs_code (stmt);
3773 vn_nary_op_t nary;
3775 /* COND_EXPR and VEC_COND_EXPR are awkward in
3776 that they contain an embedded complex expression.
3777 Don't even try to shove those through PRE. */
3778 if (code == COND_EXPR
3779 || code == VEC_COND_EXPR)
3780 continue;
3782 vn_nary_op_lookup_stmt (stmt, &nary);
3783 if (!nary)
3784 continue;
3786 /* If the NARY traps and there was a preceding
3787 point in the block that might not return avoid
3788 adding the nary to EXP_GEN. */
3789 if (BB_MAY_NOTRETURN (block)
3790 && vn_nary_may_trap (nary))
3791 continue;
3793 result = (pre_expr) pool_alloc (pre_expr_pool);
3794 result->kind = NARY;
3795 result->id = 0;
3796 PRE_EXPR_NARY (result) = nary;
3797 break;
3800 case VN_REFERENCE:
3802 vn_reference_t ref;
3803 vn_reference_lookup (gimple_assign_rhs1 (stmt),
3804 gimple_vuse (stmt),
3805 VN_WALK, &ref);
3806 if (!ref)
3807 continue;
3809 /* If the value of the reference is not invalidated in
3810 this block until it is computed, add the expression
3811 to EXP_GEN. */
3812 if (gimple_vuse (stmt))
3814 gimple def_stmt;
3815 bool ok = true;
3816 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3817 while (!gimple_nop_p (def_stmt)
3818 && gimple_code (def_stmt) != GIMPLE_PHI
3819 && gimple_bb (def_stmt) == block)
3821 if (stmt_may_clobber_ref_p
3822 (def_stmt, gimple_assign_rhs1 (stmt)))
3824 ok = false;
3825 break;
3827 def_stmt
3828 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3830 if (!ok)
3831 continue;
3834 result = (pre_expr) pool_alloc (pre_expr_pool);
3835 result->kind = REFERENCE;
3836 result->id = 0;
3837 PRE_EXPR_REFERENCE (result) = ref;
3838 break;
3841 default:
3842 continue;
3845 get_or_alloc_expression_id (result);
3846 add_to_value (get_expr_value_id (result), result);
3847 bitmap_value_insert_into_set (EXP_GEN (block), result);
3848 continue;
3850 default:
3851 break;
3855 if (dump_file && (dump_flags & TDF_DETAILS))
3857 print_bitmap_set (dump_file, EXP_GEN (block),
3858 "exp_gen", block->index);
3859 print_bitmap_set (dump_file, PHI_GEN (block),
3860 "phi_gen", block->index);
3861 print_bitmap_set (dump_file, TMP_GEN (block),
3862 "tmp_gen", block->index);
3863 print_bitmap_set (dump_file, AVAIL_OUT (block),
3864 "avail_out", block->index);
3867 /* Put the dominator children of BLOCK on the worklist of blocks
3868 to compute available sets for. */
3869 for (son = first_dom_son (CDI_DOMINATORS, block);
3870 son;
3871 son = next_dom_son (CDI_DOMINATORS, son))
3872 worklist[sp++] = son;
3875 free (worklist);
3879 /* Local state for the eliminate domwalk. */
3880 static vec<gimple> el_to_remove;
3881 static unsigned int el_todo;
3882 static vec<tree> el_avail;
3883 static vec<tree> el_avail_stack;
3885 /* Return a leader for OP that is available at the current point of the
3886 eliminate domwalk. */
3888 static tree
3889 eliminate_avail (tree op)
3891 tree valnum = VN_INFO (op)->valnum;
3892 if (TREE_CODE (valnum) == SSA_NAME)
3894 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
3895 return valnum;
3896 if (el_avail.length () > SSA_NAME_VERSION (valnum))
3897 return el_avail[SSA_NAME_VERSION (valnum)];
3899 else if (is_gimple_min_invariant (valnum))
3900 return valnum;
3901 return NULL_TREE;
3904 /* At the current point of the eliminate domwalk make OP available. */
3906 static void
3907 eliminate_push_avail (tree op)
3909 tree valnum = VN_INFO (op)->valnum;
3910 if (TREE_CODE (valnum) == SSA_NAME)
3912 if (el_avail.length () <= SSA_NAME_VERSION (valnum))
3913 el_avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1);
3914 tree pushop = op;
3915 if (el_avail[SSA_NAME_VERSION (valnum)])
3916 pushop = el_avail[SSA_NAME_VERSION (valnum)];
3917 el_avail_stack.safe_push (pushop);
3918 el_avail[SSA_NAME_VERSION (valnum)] = op;
3922 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
3923 the leader for the expression if insertion was successful. */
3925 static tree
3926 eliminate_insert (gimple_stmt_iterator *gsi, tree val)
3928 tree expr = vn_get_expr_for (val);
3929 if (!CONVERT_EXPR_P (expr)
3930 && TREE_CODE (expr) != VIEW_CONVERT_EXPR)
3931 return NULL_TREE;
3933 tree op = TREE_OPERAND (expr, 0);
3934 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (op) : op;
3935 if (!leader)
3936 return NULL_TREE;
3938 tree res = make_temp_ssa_name (TREE_TYPE (val), NULL, "pretmp");
3939 gassign *tem = gimple_build_assign (res,
3940 fold_build1 (TREE_CODE (expr),
3941 TREE_TYPE (expr), leader));
3942 gsi_insert_before (gsi, tem, GSI_SAME_STMT);
3943 VN_INFO_GET (res)->valnum = val;
3945 if (TREE_CODE (leader) == SSA_NAME)
3946 gimple_set_plf (SSA_NAME_DEF_STMT (leader), NECESSARY, true);
3948 pre_stats.insertions++;
3949 if (dump_file && (dump_flags & TDF_DETAILS))
3951 fprintf (dump_file, "Inserted ");
3952 print_gimple_stmt (dump_file, tem, 0, 0);
3955 return res;
3958 class eliminate_dom_walker : public dom_walker
3960 public:
3961 eliminate_dom_walker (cdi_direction direction, bool do_pre_)
3962 : dom_walker (direction), do_pre (do_pre_) {}
3964 virtual void before_dom_children (basic_block);
3965 virtual void after_dom_children (basic_block);
3967 bool do_pre;
3970 /* Perform elimination for the basic-block B during the domwalk. */
3972 void
3973 eliminate_dom_walker::before_dom_children (basic_block b)
3975 /* Mark new bb. */
3976 el_avail_stack.safe_push (NULL_TREE);
3978 /* ??? If we do nothing for unreachable blocks then this will confuse
3979 tailmerging. Eventually we can reduce its reliance on SCCVN now
3980 that we fully copy/constant-propagate (most) things. */
3982 for (gphi_iterator gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
3984 gphi *phi = gsi.phi ();
3985 tree res = PHI_RESULT (phi);
3987 if (virtual_operand_p (res))
3989 gsi_next (&gsi);
3990 continue;
3993 tree sprime = eliminate_avail (res);
3994 if (sprime
3995 && sprime != res)
3997 if (dump_file && (dump_flags & TDF_DETAILS))
3999 fprintf (dump_file, "Replaced redundant PHI node defining ");
4000 print_generic_expr (dump_file, res, 0);
4001 fprintf (dump_file, " with ");
4002 print_generic_expr (dump_file, sprime, 0);
4003 fprintf (dump_file, "\n");
4006 /* If we inserted this PHI node ourself, it's not an elimination. */
4007 if (inserted_exprs
4008 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
4009 pre_stats.phis--;
4010 else
4011 pre_stats.eliminations++;
4013 /* If we will propagate into all uses don't bother to do
4014 anything. */
4015 if (may_propagate_copy (res, sprime))
4017 /* Mark the PHI for removal. */
4018 el_to_remove.safe_push (phi);
4019 gsi_next (&gsi);
4020 continue;
4023 remove_phi_node (&gsi, false);
4025 if (inserted_exprs
4026 && !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res))
4027 && TREE_CODE (sprime) == SSA_NAME)
4028 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4030 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
4031 sprime = fold_convert (TREE_TYPE (res), sprime);
4032 gimple stmt = gimple_build_assign (res, sprime);
4033 /* ??? It cannot yet be necessary (DOM walk). */
4034 gimple_set_plf (stmt, NECESSARY, gimple_plf (phi, NECESSARY));
4036 gimple_stmt_iterator gsi2 = gsi_after_labels (b);
4037 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
4038 continue;
4041 eliminate_push_avail (res);
4042 gsi_next (&gsi);
4045 for (gimple_stmt_iterator gsi = gsi_start_bb (b);
4046 !gsi_end_p (gsi);
4047 gsi_next (&gsi))
4049 tree sprime = NULL_TREE;
4050 gimple stmt = gsi_stmt (gsi);
4051 tree lhs = gimple_get_lhs (stmt);
4052 if (lhs && TREE_CODE (lhs) == SSA_NAME
4053 && !gimple_has_volatile_ops (stmt)
4054 /* See PR43491. Do not replace a global register variable when
4055 it is a the RHS of an assignment. Do replace local register
4056 variables since gcc does not guarantee a local variable will
4057 be allocated in register.
4058 ??? The fix isn't effective here. This should instead
4059 be ensured by not value-numbering them the same but treating
4060 them like volatiles? */
4061 && !(gimple_assign_single_p (stmt)
4062 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == VAR_DECL
4063 && DECL_HARD_REGISTER (gimple_assign_rhs1 (stmt))
4064 && is_global_var (gimple_assign_rhs1 (stmt)))))
4066 sprime = eliminate_avail (lhs);
4067 if (!sprime)
4069 /* If there is no existing usable leader but SCCVN thinks
4070 it has an expression it wants to use as replacement,
4071 insert that. */
4072 tree val = VN_INFO (lhs)->valnum;
4073 if (val != VN_TOP
4074 && TREE_CODE (val) == SSA_NAME
4075 && VN_INFO (val)->needs_insertion
4076 && VN_INFO (val)->expr != NULL_TREE
4077 && (sprime = eliminate_insert (&gsi, val)) != NULL_TREE)
4078 eliminate_push_avail (sprime);
4081 /* If this now constitutes a copy duplicate points-to
4082 and range info appropriately. This is especially
4083 important for inserted code. See tree-ssa-copy.c
4084 for similar code. */
4085 if (sprime
4086 && TREE_CODE (sprime) == SSA_NAME)
4088 basic_block sprime_b = gimple_bb (SSA_NAME_DEF_STMT (sprime));
4089 if (POINTER_TYPE_P (TREE_TYPE (lhs))
4090 && SSA_NAME_PTR_INFO (lhs)
4091 && !SSA_NAME_PTR_INFO (sprime))
4093 duplicate_ssa_name_ptr_info (sprime,
4094 SSA_NAME_PTR_INFO (lhs));
4095 if (b != sprime_b)
4096 mark_ptr_info_alignment_unknown
4097 (SSA_NAME_PTR_INFO (sprime));
4099 else if (!POINTER_TYPE_P (TREE_TYPE (lhs))
4100 && SSA_NAME_RANGE_INFO (lhs)
4101 && !SSA_NAME_RANGE_INFO (sprime)
4102 && b == sprime_b)
4103 duplicate_ssa_name_range_info (sprime,
4104 SSA_NAME_RANGE_TYPE (lhs),
4105 SSA_NAME_RANGE_INFO (lhs));
4108 /* Inhibit the use of an inserted PHI on a loop header when
4109 the address of the memory reference is a simple induction
4110 variable. In other cases the vectorizer won't do anything
4111 anyway (either it's loop invariant or a complicated
4112 expression). */
4113 if (sprime
4114 && TREE_CODE (sprime) == SSA_NAME
4115 && do_pre
4116 && flag_tree_loop_vectorize
4117 && loop_outer (b->loop_father)
4118 && has_zero_uses (sprime)
4119 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))
4120 && gimple_assign_load_p (stmt))
4122 gimple def_stmt = SSA_NAME_DEF_STMT (sprime);
4123 basic_block def_bb = gimple_bb (def_stmt);
4124 if (gimple_code (def_stmt) == GIMPLE_PHI
4125 && b->loop_father->header == def_bb)
4127 ssa_op_iter iter;
4128 tree op;
4129 bool found = false;
4130 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
4132 affine_iv iv;
4133 def_bb = gimple_bb (SSA_NAME_DEF_STMT (op));
4134 if (def_bb
4135 && flow_bb_inside_loop_p (b->loop_father, def_bb)
4136 && simple_iv (b->loop_father,
4137 b->loop_father, op, &iv, true))
4139 found = true;
4140 break;
4143 if (found)
4145 if (dump_file && (dump_flags & TDF_DETAILS))
4147 fprintf (dump_file, "Not replacing ");
4148 print_gimple_expr (dump_file, stmt, 0, 0);
4149 fprintf (dump_file, " with ");
4150 print_generic_expr (dump_file, sprime, 0);
4151 fprintf (dump_file, " which would add a loop"
4152 " carried dependence to loop %d\n",
4153 b->loop_father->num);
4155 /* Don't keep sprime available. */
4156 sprime = NULL_TREE;
4161 if (sprime)
4163 /* If we can propagate the value computed for LHS into
4164 all uses don't bother doing anything with this stmt. */
4165 if (may_propagate_copy (lhs, sprime))
4167 /* Mark it for removal. */
4168 el_to_remove.safe_push (stmt);
4170 /* ??? Don't count copy/constant propagations. */
4171 if (gimple_assign_single_p (stmt)
4172 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4173 || gimple_assign_rhs1 (stmt) == sprime))
4174 continue;
4176 if (dump_file && (dump_flags & TDF_DETAILS))
4178 fprintf (dump_file, "Replaced ");
4179 print_gimple_expr (dump_file, stmt, 0, 0);
4180 fprintf (dump_file, " with ");
4181 print_generic_expr (dump_file, sprime, 0);
4182 fprintf (dump_file, " in all uses of ");
4183 print_gimple_stmt (dump_file, stmt, 0, 0);
4186 pre_stats.eliminations++;
4187 continue;
4190 /* If this is an assignment from our leader (which
4191 happens in the case the value-number is a constant)
4192 then there is nothing to do. */
4193 if (gimple_assign_single_p (stmt)
4194 && sprime == gimple_assign_rhs1 (stmt))
4195 continue;
4197 /* Else replace its RHS. */
4198 bool can_make_abnormal_goto
4199 = is_gimple_call (stmt)
4200 && stmt_can_make_abnormal_goto (stmt);
4202 if (dump_file && (dump_flags & TDF_DETAILS))
4204 fprintf (dump_file, "Replaced ");
4205 print_gimple_expr (dump_file, stmt, 0, 0);
4206 fprintf (dump_file, " with ");
4207 print_generic_expr (dump_file, sprime, 0);
4208 fprintf (dump_file, " in ");
4209 print_gimple_stmt (dump_file, stmt, 0, 0);
4212 if (TREE_CODE (sprime) == SSA_NAME)
4213 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4214 NECESSARY, true);
4216 pre_stats.eliminations++;
4217 gimple orig_stmt = stmt;
4218 if (!useless_type_conversion_p (TREE_TYPE (lhs),
4219 TREE_TYPE (sprime)))
4220 sprime = fold_convert (TREE_TYPE (lhs), sprime);
4221 tree vdef = gimple_vdef (stmt);
4222 tree vuse = gimple_vuse (stmt);
4223 propagate_tree_value_into_stmt (&gsi, sprime);
4224 stmt = gsi_stmt (gsi);
4225 update_stmt (stmt);
4226 if (vdef != gimple_vdef (stmt))
4227 VN_INFO (vdef)->valnum = vuse;
4229 /* If we removed EH side-effects from the statement, clean
4230 its EH information. */
4231 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4233 bitmap_set_bit (need_eh_cleanup,
4234 gimple_bb (stmt)->index);
4235 if (dump_file && (dump_flags & TDF_DETAILS))
4236 fprintf (dump_file, " Removed EH side-effects.\n");
4239 /* Likewise for AB side-effects. */
4240 if (can_make_abnormal_goto
4241 && !stmt_can_make_abnormal_goto (stmt))
4243 bitmap_set_bit (need_ab_cleanup,
4244 gimple_bb (stmt)->index);
4245 if (dump_file && (dump_flags & TDF_DETAILS))
4246 fprintf (dump_file, " Removed AB side-effects.\n");
4249 continue;
4253 /* If the statement is a scalar store, see if the expression
4254 has the same value number as its rhs. If so, the store is
4255 dead. */
4256 if (gimple_assign_single_p (stmt)
4257 && !gimple_has_volatile_ops (stmt)
4258 && !is_gimple_reg (gimple_assign_lhs (stmt))
4259 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4260 || is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
4262 tree val;
4263 tree rhs = gimple_assign_rhs1 (stmt);
4264 val = vn_reference_lookup (gimple_assign_lhs (stmt),
4265 gimple_vuse (stmt), VN_WALK, NULL);
4266 if (TREE_CODE (rhs) == SSA_NAME)
4267 rhs = VN_INFO (rhs)->valnum;
4268 if (val
4269 && operand_equal_p (val, rhs, 0))
4271 if (dump_file && (dump_flags & TDF_DETAILS))
4273 fprintf (dump_file, "Deleted redundant store ");
4274 print_gimple_stmt (dump_file, stmt, 0, 0);
4277 /* Queue stmt for removal. */
4278 el_to_remove.safe_push (stmt);
4279 continue;
4283 bool can_make_abnormal_goto = stmt_can_make_abnormal_goto (stmt);
4284 bool was_noreturn = (is_gimple_call (stmt)
4285 && gimple_call_noreturn_p (stmt));
4286 tree vdef = gimple_vdef (stmt);
4287 tree vuse = gimple_vuse (stmt);
4289 /* If we didn't replace the whole stmt (or propagate the result
4290 into all uses), replace all uses on this stmt with their
4291 leaders. */
4292 use_operand_p use_p;
4293 ssa_op_iter iter;
4294 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
4296 tree use = USE_FROM_PTR (use_p);
4297 /* ??? The call code above leaves stmt operands un-updated. */
4298 if (TREE_CODE (use) != SSA_NAME)
4299 continue;
4300 tree sprime = eliminate_avail (use);
4301 if (sprime && sprime != use
4302 && may_propagate_copy (use, sprime)
4303 /* We substitute into debug stmts to avoid excessive
4304 debug temporaries created by removed stmts, but we need
4305 to avoid doing so for inserted sprimes as we never want
4306 to create debug temporaries for them. */
4307 && (!inserted_exprs
4308 || TREE_CODE (sprime) != SSA_NAME
4309 || !is_gimple_debug (stmt)
4310 || !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))))
4312 propagate_value (use_p, sprime);
4313 gimple_set_modified (stmt, true);
4314 if (TREE_CODE (sprime) == SSA_NAME
4315 && !is_gimple_debug (stmt))
4316 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4317 NECESSARY, true);
4321 /* Visit indirect calls and turn them into direct calls if
4322 possible using the devirtualization machinery. */
4323 if (gcall *call_stmt = dyn_cast <gcall *> (stmt))
4325 tree fn = gimple_call_fn (call_stmt);
4326 if (fn
4327 && flag_devirtualize
4328 && virtual_method_call_p (fn))
4330 tree otr_type = obj_type_ref_class (fn);
4331 tree instance;
4332 ipa_polymorphic_call_context context (current_function_decl, fn, stmt, &instance);
4333 bool final;
4335 context.get_dynamic_type (instance, OBJ_TYPE_REF_OBJECT (fn), otr_type, stmt);
4337 vec <cgraph_node *>targets
4338 = possible_polymorphic_call_targets (obj_type_ref_class (fn),
4339 tree_to_uhwi
4340 (OBJ_TYPE_REF_TOKEN (fn)),
4341 context,
4342 &final);
4343 if (dump_enabled_p ())
4344 dump_possible_polymorphic_call_targets (dump_file,
4345 obj_type_ref_class (fn),
4346 tree_to_uhwi
4347 (OBJ_TYPE_REF_TOKEN (fn)),
4348 context);
4349 if (final && targets.length () <= 1 && dbg_cnt (devirt))
4351 tree fn;
4352 if (targets.length () == 1)
4353 fn = targets[0]->decl;
4354 else
4355 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
4356 if (dump_enabled_p ())
4358 location_t loc = gimple_location_safe (stmt);
4359 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
4360 "converting indirect call to "
4361 "function %s\n",
4362 cgraph_node::get (fn)->name ());
4364 gimple_call_set_fndecl (call_stmt, fn);
4365 gimple_set_modified (stmt, true);
4370 if (gimple_modified_p (stmt))
4372 /* If a formerly non-invariant ADDR_EXPR is turned into an
4373 invariant one it was on a separate stmt. */
4374 if (gimple_assign_single_p (stmt)
4375 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
4376 recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
4377 gimple old_stmt = stmt;
4378 if (is_gimple_call (stmt))
4380 /* ??? Only fold calls inplace for now, this may create new
4381 SSA names which in turn will confuse free_scc_vn SSA name
4382 release code. */
4383 fold_stmt_inplace (&gsi);
4384 /* When changing a call into a noreturn call, cfg cleanup
4385 is needed to fix up the noreturn call. */
4386 if (!was_noreturn && gimple_call_noreturn_p (stmt))
4387 el_todo |= TODO_cleanup_cfg;
4389 else
4391 fold_stmt (&gsi);
4392 stmt = gsi_stmt (gsi);
4393 if ((gimple_code (stmt) == GIMPLE_COND
4394 && (gimple_cond_true_p (as_a <gcond *> (stmt))
4395 || gimple_cond_false_p (as_a <gcond *> (stmt))))
4396 || (gimple_code (stmt) == GIMPLE_SWITCH
4397 && TREE_CODE (gimple_switch_index (
4398 as_a <gswitch *> (stmt)))
4399 == INTEGER_CST))
4400 el_todo |= TODO_cleanup_cfg;
4402 /* If we removed EH side-effects from the statement, clean
4403 its EH information. */
4404 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
4406 bitmap_set_bit (need_eh_cleanup,
4407 gimple_bb (stmt)->index);
4408 if (dump_file && (dump_flags & TDF_DETAILS))
4409 fprintf (dump_file, " Removed EH side-effects.\n");
4411 /* Likewise for AB side-effects. */
4412 if (can_make_abnormal_goto
4413 && !stmt_can_make_abnormal_goto (stmt))
4415 bitmap_set_bit (need_ab_cleanup,
4416 gimple_bb (stmt)->index);
4417 if (dump_file && (dump_flags & TDF_DETAILS))
4418 fprintf (dump_file, " Removed AB side-effects.\n");
4420 update_stmt (stmt);
4421 if (vdef != gimple_vdef (stmt))
4422 VN_INFO (vdef)->valnum = vuse;
4425 /* Make new values available - for fully redundant LHS we
4426 continue with the next stmt above and skip this. */
4427 def_operand_p defp;
4428 FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_DEF)
4429 eliminate_push_avail (DEF_FROM_PTR (defp));
4432 /* Replace destination PHI arguments. */
4433 edge_iterator ei;
4434 edge e;
4435 FOR_EACH_EDGE (e, ei, b->succs)
4437 for (gphi_iterator gsi = gsi_start_phis (e->dest);
4438 !gsi_end_p (gsi);
4439 gsi_next (&gsi))
4441 gphi *phi = gsi.phi ();
4442 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
4443 tree arg = USE_FROM_PTR (use_p);
4444 if (TREE_CODE (arg) != SSA_NAME
4445 || virtual_operand_p (arg))
4446 continue;
4447 tree sprime = eliminate_avail (arg);
4448 if (sprime && may_propagate_copy (arg, sprime))
4450 propagate_value (use_p, sprime);
4451 if (TREE_CODE (sprime) == SSA_NAME)
4452 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4458 /* Make no longer available leaders no longer available. */
4460 void
4461 eliminate_dom_walker::after_dom_children (basic_block)
4463 tree entry;
4464 while ((entry = el_avail_stack.pop ()) != NULL_TREE)
4466 tree valnum = VN_INFO (entry)->valnum;
4467 tree old = el_avail[SSA_NAME_VERSION (valnum)];
4468 if (old == entry)
4469 el_avail[SSA_NAME_VERSION (valnum)] = NULL_TREE;
4470 else
4471 el_avail[SSA_NAME_VERSION (valnum)] = entry;
4475 /* Eliminate fully redundant computations. */
4477 static unsigned int
4478 eliminate (bool do_pre)
4480 gimple_stmt_iterator gsi;
4481 gimple stmt;
4483 need_eh_cleanup = BITMAP_ALLOC (NULL);
4484 need_ab_cleanup = BITMAP_ALLOC (NULL);
4486 el_to_remove.create (0);
4487 el_todo = 0;
4488 el_avail.create (num_ssa_names);
4489 el_avail_stack.create (0);
4491 eliminate_dom_walker (CDI_DOMINATORS,
4492 do_pre).walk (cfun->cfg->x_entry_block_ptr);
4494 el_avail.release ();
4495 el_avail_stack.release ();
4497 /* We cannot remove stmts during BB walk, especially not release SSA
4498 names there as this confuses the VN machinery. The stmts ending
4499 up in el_to_remove are either stores or simple copies.
4500 Remove stmts in reverse order to make debug stmt creation possible. */
4501 while (!el_to_remove.is_empty ())
4503 stmt = el_to_remove.pop ();
4505 if (dump_file && (dump_flags & TDF_DETAILS))
4507 fprintf (dump_file, "Removing dead stmt ");
4508 print_gimple_stmt (dump_file, stmt, 0, 0);
4511 tree lhs;
4512 if (gimple_code (stmt) == GIMPLE_PHI)
4513 lhs = gimple_phi_result (stmt);
4514 else
4515 lhs = gimple_get_lhs (stmt);
4517 if (inserted_exprs
4518 && TREE_CODE (lhs) == SSA_NAME)
4519 bitmap_clear_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
4521 gsi = gsi_for_stmt (stmt);
4522 if (gimple_code (stmt) == GIMPLE_PHI)
4523 remove_phi_node (&gsi, true);
4524 else
4526 basic_block bb = gimple_bb (stmt);
4527 unlink_stmt_vdef (stmt);
4528 if (gsi_remove (&gsi, true))
4529 bitmap_set_bit (need_eh_cleanup, bb->index);
4530 release_defs (stmt);
4533 /* Removing a stmt may expose a forwarder block. */
4534 el_todo |= TODO_cleanup_cfg;
4536 el_to_remove.release ();
4538 return el_todo;
4541 /* Perform CFG cleanups made necessary by elimination. */
4543 static unsigned
4544 fini_eliminate (void)
4546 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
4547 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
4549 if (do_eh_cleanup)
4550 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
4552 if (do_ab_cleanup)
4553 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
4555 BITMAP_FREE (need_eh_cleanup);
4556 BITMAP_FREE (need_ab_cleanup);
4558 if (do_eh_cleanup || do_ab_cleanup)
4559 return TODO_cleanup_cfg;
4560 return 0;
4563 /* Borrow a bit of tree-ssa-dce.c for the moment.
4564 XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
4565 this may be a bit faster, and we may want critical edges kept split. */
4567 /* If OP's defining statement has not already been determined to be necessary,
4568 mark that statement necessary. Return the stmt, if it is newly
4569 necessary. */
4571 static inline gimple
4572 mark_operand_necessary (tree op)
4574 gimple stmt;
4576 gcc_assert (op);
4578 if (TREE_CODE (op) != SSA_NAME)
4579 return NULL;
4581 stmt = SSA_NAME_DEF_STMT (op);
4582 gcc_assert (stmt);
4584 if (gimple_plf (stmt, NECESSARY)
4585 || gimple_nop_p (stmt))
4586 return NULL;
4588 gimple_set_plf (stmt, NECESSARY, true);
4589 return stmt;
4592 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4593 to insert PHI nodes sometimes, and because value numbering of casts isn't
4594 perfect, we sometimes end up inserting dead code. This simple DCE-like
4595 pass removes any insertions we made that weren't actually used. */
4597 static void
4598 remove_dead_inserted_code (void)
4600 bitmap worklist;
4601 unsigned i;
4602 bitmap_iterator bi;
4603 gimple t;
4605 worklist = BITMAP_ALLOC (NULL);
4606 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4608 t = SSA_NAME_DEF_STMT (ssa_name (i));
4609 if (gimple_plf (t, NECESSARY))
4610 bitmap_set_bit (worklist, i);
4612 while (!bitmap_empty_p (worklist))
4614 i = bitmap_first_set_bit (worklist);
4615 bitmap_clear_bit (worklist, i);
4616 t = SSA_NAME_DEF_STMT (ssa_name (i));
4618 /* PHI nodes are somewhat special in that each PHI alternative has
4619 data and control dependencies. All the statements feeding the
4620 PHI node's arguments are always necessary. */
4621 if (gimple_code (t) == GIMPLE_PHI)
4623 unsigned k;
4625 for (k = 0; k < gimple_phi_num_args (t); k++)
4627 tree arg = PHI_ARG_DEF (t, k);
4628 if (TREE_CODE (arg) == SSA_NAME)
4630 gimple n = mark_operand_necessary (arg);
4631 if (n)
4632 bitmap_set_bit (worklist, SSA_NAME_VERSION (arg));
4636 else
4638 /* Propagate through the operands. Examine all the USE, VUSE and
4639 VDEF operands in this statement. Mark all the statements
4640 which feed this statement's uses as necessary. */
4641 ssa_op_iter iter;
4642 tree use;
4644 /* The operands of VDEF expressions are also needed as they
4645 represent potential definitions that may reach this
4646 statement (VDEF operands allow us to follow def-def
4647 links). */
4649 FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
4651 gimple n = mark_operand_necessary (use);
4652 if (n)
4653 bitmap_set_bit (worklist, SSA_NAME_VERSION (use));
4658 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4660 t = SSA_NAME_DEF_STMT (ssa_name (i));
4661 if (!gimple_plf (t, NECESSARY))
4663 gimple_stmt_iterator gsi;
4665 if (dump_file && (dump_flags & TDF_DETAILS))
4667 fprintf (dump_file, "Removing unnecessary insertion:");
4668 print_gimple_stmt (dump_file, t, 0, 0);
4671 gsi = gsi_for_stmt (t);
4672 if (gimple_code (t) == GIMPLE_PHI)
4673 remove_phi_node (&gsi, true);
4674 else
4676 gsi_remove (&gsi, true);
4677 release_defs (t);
4681 BITMAP_FREE (worklist);
4685 /* Initialize data structures used by PRE. */
4687 static void
4688 init_pre (void)
4690 basic_block bb;
4692 next_expression_id = 1;
4693 expressions.create (0);
4694 expressions.safe_push (NULL);
4695 value_expressions.create (get_max_value_id () + 1);
4696 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
4697 name_to_id.create (0);
4699 inserted_exprs = BITMAP_ALLOC (NULL);
4701 connect_infinite_loops_to_exit ();
4702 memset (&pre_stats, 0, sizeof (pre_stats));
4704 postorder = XNEWVEC (int, n_basic_blocks_for_fn (cfun));
4705 postorder_num = inverted_post_order_compute (postorder);
4707 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4709 calculate_dominance_info (CDI_POST_DOMINATORS);
4710 calculate_dominance_info (CDI_DOMINATORS);
4712 bitmap_obstack_initialize (&grand_bitmap_obstack);
4713 phi_translate_table = new hash_table<expr_pred_trans_d> (5110);
4714 expression_to_id = new hash_table<pre_expr_d> (num_ssa_names * 3);
4715 bitmap_set_pool = create_alloc_pool ("Bitmap sets",
4716 sizeof (struct bitmap_set), 30);
4717 pre_expr_pool = create_alloc_pool ("pre_expr nodes",
4718 sizeof (struct pre_expr_d), 30);
4719 FOR_ALL_BB_FN (bb, cfun)
4721 EXP_GEN (bb) = bitmap_set_new ();
4722 PHI_GEN (bb) = bitmap_set_new ();
4723 TMP_GEN (bb) = bitmap_set_new ();
4724 AVAIL_OUT (bb) = bitmap_set_new ();
4729 /* Deallocate data structures used by PRE. */
4731 static void
4732 fini_pre ()
4734 free (postorder);
4735 value_expressions.release ();
4736 BITMAP_FREE (inserted_exprs);
4737 bitmap_obstack_release (&grand_bitmap_obstack);
4738 free_alloc_pool (bitmap_set_pool);
4739 free_alloc_pool (pre_expr_pool);
4740 delete phi_translate_table;
4741 phi_translate_table = NULL;
4742 delete expression_to_id;
4743 expression_to_id = NULL;
4744 name_to_id.release ();
4746 free_aux_for_blocks ();
4748 free_dominance_info (CDI_POST_DOMINATORS);
4751 namespace {
4753 const pass_data pass_data_pre =
4755 GIMPLE_PASS, /* type */
4756 "pre", /* name */
4757 OPTGROUP_NONE, /* optinfo_flags */
4758 TV_TREE_PRE, /* tv_id */
4759 /* PROP_no_crit_edges is ensured by placing pass_split_crit_edges before
4760 pass_pre. */
4761 ( PROP_no_crit_edges | PROP_cfg | PROP_ssa ), /* properties_required */
4762 0, /* properties_provided */
4763 PROP_no_crit_edges, /* properties_destroyed */
4764 TODO_rebuild_alias, /* todo_flags_start */
4765 0, /* todo_flags_finish */
4768 class pass_pre : public gimple_opt_pass
4770 public:
4771 pass_pre (gcc::context *ctxt)
4772 : gimple_opt_pass (pass_data_pre, ctxt)
4775 /* opt_pass methods: */
4776 virtual bool gate (function *) { return flag_tree_pre != 0; }
4777 virtual unsigned int execute (function *);
4779 }; // class pass_pre
4781 unsigned int
4782 pass_pre::execute (function *fun)
4784 unsigned int todo = 0;
4786 do_partial_partial =
4787 flag_tree_partial_pre && optimize_function_for_speed_p (fun);
4789 /* This has to happen before SCCVN runs because
4790 loop_optimizer_init may create new phis, etc. */
4791 loop_optimizer_init (LOOPS_NORMAL);
4793 if (!run_scc_vn (VN_WALK))
4795 loop_optimizer_finalize ();
4796 return 0;
4799 init_pre ();
4800 scev_initialize ();
4802 /* Collect and value number expressions computed in each basic block. */
4803 compute_avail ();
4805 /* Insert can get quite slow on an incredibly large number of basic
4806 blocks due to some quadratic behavior. Until this behavior is
4807 fixed, don't run it when he have an incredibly large number of
4808 bb's. If we aren't going to run insert, there is no point in
4809 computing ANTIC, either, even though it's plenty fast. */
4810 if (n_basic_blocks_for_fn (fun) < 4000)
4812 compute_antic ();
4813 insert ();
4816 /* Make sure to remove fake edges before committing our inserts.
4817 This makes sure we don't end up with extra critical edges that
4818 we would need to split. */
4819 remove_fake_exit_edges ();
4820 gsi_commit_edge_inserts ();
4822 /* Eliminate folds statements which might (should not...) end up
4823 not keeping virtual operands up-to-date. */
4824 gcc_assert (!need_ssa_update_p (fun));
4826 /* Remove all the redundant expressions. */
4827 todo |= eliminate (true);
4829 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
4830 statistics_counter_event (fun, "PA inserted", pre_stats.pa_insert);
4831 statistics_counter_event (fun, "New PHIs", pre_stats.phis);
4832 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
4834 clear_expression_ids ();
4835 remove_dead_inserted_code ();
4837 scev_finalize ();
4838 fini_pre ();
4839 todo |= fini_eliminate ();
4840 loop_optimizer_finalize ();
4842 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
4843 case we can merge the block with the remaining predecessor of the block.
4844 It should either:
4845 - call merge_blocks after each tail merge iteration
4846 - call merge_blocks after all tail merge iterations
4847 - mark TODO_cleanup_cfg when necessary
4848 - share the cfg cleanup with fini_pre. */
4849 todo |= tail_merge_optimize (todo);
4851 free_scc_vn ();
4853 /* Tail merging invalidates the virtual SSA web, together with
4854 cfg-cleanup opportunities exposed by PRE this will wreck the
4855 SSA updating machinery. So make sure to run update-ssa
4856 manually, before eventually scheduling cfg-cleanup as part of
4857 the todo. */
4858 update_ssa (TODO_update_ssa_only_virtuals);
4860 return todo;
4863 } // anon namespace
4865 gimple_opt_pass *
4866 make_pass_pre (gcc::context *ctxt)
4868 return new pass_pre (ctxt);
4871 namespace {
4873 const pass_data pass_data_fre =
4875 GIMPLE_PASS, /* type */
4876 "fre", /* name */
4877 OPTGROUP_NONE, /* optinfo_flags */
4878 TV_TREE_FRE, /* tv_id */
4879 ( PROP_cfg | PROP_ssa ), /* properties_required */
4880 0, /* properties_provided */
4881 0, /* properties_destroyed */
4882 0, /* todo_flags_start */
4883 0, /* todo_flags_finish */
4886 class pass_fre : public gimple_opt_pass
4888 public:
4889 pass_fre (gcc::context *ctxt)
4890 : gimple_opt_pass (pass_data_fre, ctxt)
4893 /* opt_pass methods: */
4894 opt_pass * clone () { return new pass_fre (m_ctxt); }
4895 virtual bool gate (function *) { return flag_tree_fre != 0; }
4896 virtual unsigned int execute (function *);
4898 }; // class pass_fre
4900 unsigned int
4901 pass_fre::execute (function *fun)
4903 unsigned int todo = 0;
4905 if (!run_scc_vn (VN_WALKREWRITE))
4906 return 0;
4908 memset (&pre_stats, 0, sizeof (pre_stats));
4910 /* Remove all the redundant expressions. */
4911 todo |= eliminate (false);
4913 todo |= fini_eliminate ();
4915 free_scc_vn ();
4917 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
4918 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
4920 return todo;
4923 } // anon namespace
4925 gimple_opt_pass *
4926 make_pass_fre (gcc::context *ctxt)
4928 return new pass_fre (ctxt);