PR libstdc++/87308 adjust regex used in std::any pretty printer
[official-gcc.git] / gcc / tree-ssa-sccvn.c
blobe0ff40555ea3cc0790133bbcb4f6fbc5d13681af
1 /* SCC value numbering for trees
2 Copyright (C) 2006-2018 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <dan@dberlin.org>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "ssa.h"
29 #include "expmed.h"
30 #include "insn-config.h"
31 #include "memmodel.h"
32 #include "emit-rtl.h"
33 #include "cgraph.h"
34 #include "gimple-pretty-print.h"
35 #include "alias.h"
36 #include "fold-const.h"
37 #include "stor-layout.h"
38 #include "cfganal.h"
39 #include "tree-inline.h"
40 #include "internal-fn.h"
41 #include "gimple-fold.h"
42 #include "tree-eh.h"
43 #include "gimplify.h"
44 #include "flags.h"
45 #include "dojump.h"
46 #include "explow.h"
47 #include "calls.h"
48 #include "varasm.h"
49 #include "stmt.h"
50 #include "expr.h"
51 #include "tree-dfa.h"
52 #include "tree-ssa.h"
53 #include "dumpfile.h"
54 #include "cfgloop.h"
55 #include "params.h"
56 #include "tree-ssa-propagate.h"
57 #include "tree-cfg.h"
58 #include "domwalk.h"
59 #include "gimple-iterator.h"
60 #include "gimple-match.h"
61 #include "stringpool.h"
62 #include "attribs.h"
63 #include "tree-pass.h"
64 #include "statistics.h"
65 #include "langhooks.h"
66 #include "ipa-utils.h"
67 #include "dbgcnt.h"
68 #include "tree-cfgcleanup.h"
69 #include "tree-ssa-loop.h"
70 #include "tree-scalar-evolution.h"
71 #include "tree-ssa-loop-niter.h"
72 #include "tree-ssa-sccvn.h"
74 /* This algorithm is based on the SCC algorithm presented by Keith
75 Cooper and L. Taylor Simpson in "SCC-Based Value numbering"
76 (http://citeseer.ist.psu.edu/41805.html). In
77 straight line code, it is equivalent to a regular hash based value
78 numbering that is performed in reverse postorder.
80 For code with cycles, there are two alternatives, both of which
81 require keeping the hashtables separate from the actual list of
82 value numbers for SSA names.
84 1. Iterate value numbering in an RPO walk of the blocks, removing
85 all the entries from the hashtable after each iteration (but
86 keeping the SSA name->value number mapping between iterations).
87 Iterate until it does not change.
89 2. Perform value numbering as part of an SCC walk on the SSA graph,
90 iterating only the cycles in the SSA graph until they do not change
91 (using a separate, optimistic hashtable for value numbering the SCC
92 operands).
94 The second is not just faster in practice (because most SSA graph
95 cycles do not involve all the variables in the graph), it also has
96 some nice properties.
98 One of these nice properties is that when we pop an SCC off the
99 stack, we are guaranteed to have processed all the operands coming from
100 *outside of that SCC*, so we do not need to do anything special to
101 ensure they have value numbers.
103 Another nice property is that the SCC walk is done as part of a DFS
104 of the SSA graph, which makes it easy to perform combining and
105 simplifying operations at the same time.
107 The code below is deliberately written in a way that makes it easy
108 to separate the SCC walk from the other work it does.
110 In order to propagate constants through the code, we track which
111 expressions contain constants, and use those while folding. In
112 theory, we could also track expressions whose value numbers are
113 replaced, in case we end up folding based on expression
114 identities.
116 In order to value number memory, we assign value numbers to vuses.
117 This enables us to note that, for example, stores to the same
118 address of the same value from the same starting memory states are
119 equivalent.
120 TODO:
122 1. We can iterate only the changing portions of the SCC's, but
123 I have not seen an SCC big enough for this to be a win.
124 2. If you differentiate between phi nodes for loops and phi nodes
125 for if-then-else, you can properly consider phi nodes in different
126 blocks for equivalence.
127 3. We could value number vuses in more cases, particularly, whole
128 structure copies.
131 /* There's no BB_EXECUTABLE but we can use BB_VISITED. */
132 #define BB_EXECUTABLE BB_VISITED
134 static tree *last_vuse_ptr;
135 static vn_lookup_kind vn_walk_kind;
136 static vn_lookup_kind default_vn_walk_kind;
138 /* vn_nary_op hashtable helpers. */
140 struct vn_nary_op_hasher : nofree_ptr_hash <vn_nary_op_s>
142 typedef vn_nary_op_s *compare_type;
143 static inline hashval_t hash (const vn_nary_op_s *);
144 static inline bool equal (const vn_nary_op_s *, const vn_nary_op_s *);
147 /* Return the computed hashcode for nary operation P1. */
149 inline hashval_t
150 vn_nary_op_hasher::hash (const vn_nary_op_s *vno1)
152 return vno1->hashcode;
155 /* Compare nary operations P1 and P2 and return true if they are
156 equivalent. */
158 inline bool
159 vn_nary_op_hasher::equal (const vn_nary_op_s *vno1, const vn_nary_op_s *vno2)
161 return vno1 == vno2 || vn_nary_op_eq (vno1, vno2);
164 typedef hash_table<vn_nary_op_hasher> vn_nary_op_table_type;
165 typedef vn_nary_op_table_type::iterator vn_nary_op_iterator_type;
168 /* vn_phi hashtable helpers. */
170 static int
171 vn_phi_eq (const_vn_phi_t const vp1, const_vn_phi_t const vp2);
173 struct vn_phi_hasher : nofree_ptr_hash <vn_phi_s>
175 static inline hashval_t hash (const vn_phi_s *);
176 static inline bool equal (const vn_phi_s *, const vn_phi_s *);
179 /* Return the computed hashcode for phi operation P1. */
181 inline hashval_t
182 vn_phi_hasher::hash (const vn_phi_s *vp1)
184 return vp1->hashcode;
187 /* Compare two phi entries for equality, ignoring VN_TOP arguments. */
189 inline bool
190 vn_phi_hasher::equal (const vn_phi_s *vp1, const vn_phi_s *vp2)
192 return vp1 == vp2 || vn_phi_eq (vp1, vp2);
195 typedef hash_table<vn_phi_hasher> vn_phi_table_type;
196 typedef vn_phi_table_type::iterator vn_phi_iterator_type;
199 /* Compare two reference operands P1 and P2 for equality. Return true if
200 they are equal, and false otherwise. */
202 static int
203 vn_reference_op_eq (const void *p1, const void *p2)
205 const_vn_reference_op_t const vro1 = (const_vn_reference_op_t) p1;
206 const_vn_reference_op_t const vro2 = (const_vn_reference_op_t) p2;
208 return (vro1->opcode == vro2->opcode
209 /* We do not care for differences in type qualification. */
210 && (vro1->type == vro2->type
211 || (vro1->type && vro2->type
212 && types_compatible_p (TYPE_MAIN_VARIANT (vro1->type),
213 TYPE_MAIN_VARIANT (vro2->type))))
214 && expressions_equal_p (vro1->op0, vro2->op0)
215 && expressions_equal_p (vro1->op1, vro2->op1)
216 && expressions_equal_p (vro1->op2, vro2->op2));
219 /* Free a reference operation structure VP. */
221 static inline void
222 free_reference (vn_reference_s *vr)
224 vr->operands.release ();
228 /* vn_reference hashtable helpers. */
230 struct vn_reference_hasher : nofree_ptr_hash <vn_reference_s>
232 static inline hashval_t hash (const vn_reference_s *);
233 static inline bool equal (const vn_reference_s *, const vn_reference_s *);
236 /* Return the hashcode for a given reference operation P1. */
238 inline hashval_t
239 vn_reference_hasher::hash (const vn_reference_s *vr1)
241 return vr1->hashcode;
244 inline bool
245 vn_reference_hasher::equal (const vn_reference_s *v, const vn_reference_s *c)
247 return v == c || vn_reference_eq (v, c);
250 typedef hash_table<vn_reference_hasher> vn_reference_table_type;
251 typedef vn_reference_table_type::iterator vn_reference_iterator_type;
254 /* The set of VN hashtables. */
256 typedef struct vn_tables_s
258 vn_nary_op_table_type *nary;
259 vn_phi_table_type *phis;
260 vn_reference_table_type *references;
261 } *vn_tables_t;
264 /* vn_constant hashtable helpers. */
266 struct vn_constant_hasher : free_ptr_hash <vn_constant_s>
268 static inline hashval_t hash (const vn_constant_s *);
269 static inline bool equal (const vn_constant_s *, const vn_constant_s *);
272 /* Hash table hash function for vn_constant_t. */
274 inline hashval_t
275 vn_constant_hasher::hash (const vn_constant_s *vc1)
277 return vc1->hashcode;
280 /* Hash table equality function for vn_constant_t. */
282 inline bool
283 vn_constant_hasher::equal (const vn_constant_s *vc1, const vn_constant_s *vc2)
285 if (vc1->hashcode != vc2->hashcode)
286 return false;
288 return vn_constant_eq_with_type (vc1->constant, vc2->constant);
291 static hash_table<vn_constant_hasher> *constant_to_value_id;
292 static bitmap constant_value_ids;
295 /* Obstack we allocate the vn-tables elements from. */
296 static obstack vn_tables_obstack;
297 /* Special obstack we never unwind. */
298 static obstack vn_tables_insert_obstack;
300 static vn_reference_t last_inserted_ref;
301 static vn_phi_t last_inserted_phi;
302 static vn_nary_op_t last_inserted_nary;
304 /* Valid hashtables storing information we have proven to be
305 correct. */
306 static vn_tables_t valid_info;
309 /* Valueization hook. Valueize NAME if it is an SSA name, otherwise
310 just return it. */
311 tree (*vn_valueize) (tree);
314 /* This represents the top of the VN lattice, which is the universal
315 value. */
317 tree VN_TOP;
319 /* Unique counter for our value ids. */
321 static unsigned int next_value_id;
324 /* Table of vn_ssa_aux_t's, one per ssa_name. The vn_ssa_aux_t objects
325 are allocated on an obstack for locality reasons, and to free them
326 without looping over the vec. */
328 struct vn_ssa_aux_hasher : typed_noop_remove <vn_ssa_aux_t>
330 typedef vn_ssa_aux_t value_type;
331 typedef tree compare_type;
332 static inline hashval_t hash (const value_type &);
333 static inline bool equal (const value_type &, const compare_type &);
334 static inline void mark_deleted (value_type &) {}
335 static inline void mark_empty (value_type &e) { e = NULL; }
336 static inline bool is_deleted (value_type &) { return false; }
337 static inline bool is_empty (value_type &e) { return e == NULL; }
340 hashval_t
341 vn_ssa_aux_hasher::hash (const value_type &entry)
343 return SSA_NAME_VERSION (entry->name);
346 bool
347 vn_ssa_aux_hasher::equal (const value_type &entry, const compare_type &name)
349 return name == entry->name;
352 static hash_table<vn_ssa_aux_hasher> *vn_ssa_aux_hash;
353 typedef hash_table<vn_ssa_aux_hasher>::iterator vn_ssa_aux_iterator_type;
354 static struct obstack vn_ssa_aux_obstack;
356 static vn_nary_op_t vn_nary_op_insert_stmt (gimple *, tree);
357 static unsigned int vn_nary_length_from_stmt (gimple *);
358 static vn_nary_op_t alloc_vn_nary_op_noinit (unsigned int, obstack *);
359 static vn_nary_op_t vn_nary_op_insert_into (vn_nary_op_t,
360 vn_nary_op_table_type *, bool);
361 static void init_vn_nary_op_from_stmt (vn_nary_op_t, gimple *);
362 static void init_vn_nary_op_from_pieces (vn_nary_op_t, unsigned int,
363 enum tree_code, tree, tree *);
364 static tree vn_lookup_simplify_result (gimple_match_op *);
366 /* Return whether there is value numbering information for a given SSA name. */
368 bool
369 has_VN_INFO (tree name)
371 return vn_ssa_aux_hash->find_with_hash (name, SSA_NAME_VERSION (name));
374 vn_ssa_aux_t
375 VN_INFO (tree name)
377 vn_ssa_aux_t *res
378 = vn_ssa_aux_hash->find_slot_with_hash (name, SSA_NAME_VERSION (name),
379 INSERT);
380 if (*res != NULL)
381 return *res;
383 vn_ssa_aux_t newinfo = *res = XOBNEW (&vn_ssa_aux_obstack, struct vn_ssa_aux);
384 memset (newinfo, 0, sizeof (struct vn_ssa_aux));
385 newinfo->name = name;
386 newinfo->valnum = VN_TOP;
387 /* We are using the visited flag to handle uses with defs not within the
388 region being value-numbered. */
389 newinfo->visited = false;
391 /* Given we create the VN_INFOs on-demand now we have to do initialization
392 different than VN_TOP here. */
393 if (SSA_NAME_IS_DEFAULT_DEF (name))
394 switch (TREE_CODE (SSA_NAME_VAR (name)))
396 case VAR_DECL:
397 /* All undefined vars are VARYING. */
398 newinfo->valnum = name;
399 newinfo->visited = true;
400 break;
402 case PARM_DECL:
403 /* Parameters are VARYING but we can record a condition
404 if we know it is a non-NULL pointer. */
405 newinfo->visited = true;
406 newinfo->valnum = name;
407 if (POINTER_TYPE_P (TREE_TYPE (name))
408 && nonnull_arg_p (SSA_NAME_VAR (name)))
410 tree ops[2];
411 ops[0] = name;
412 ops[1] = build_int_cst (TREE_TYPE (name), 0);
413 vn_nary_op_t nary;
414 /* Allocate from non-unwinding stack. */
415 nary = alloc_vn_nary_op_noinit (2, &vn_tables_insert_obstack);
416 init_vn_nary_op_from_pieces (nary, 2, NE_EXPR,
417 boolean_type_node, ops);
418 nary->predicated_values = 0;
419 nary->u.result = boolean_true_node;
420 vn_nary_op_insert_into (nary, valid_info->nary, true);
421 gcc_assert (nary->unwind_to == NULL);
422 /* Also do not link it into the undo chain. */
423 last_inserted_nary = nary->next;
424 nary->next = (vn_nary_op_t)(void *)-1;
425 nary = alloc_vn_nary_op_noinit (2, &vn_tables_insert_obstack);
426 init_vn_nary_op_from_pieces (nary, 2, EQ_EXPR,
427 boolean_type_node, ops);
428 nary->predicated_values = 0;
429 nary->u.result = boolean_false_node;
430 vn_nary_op_insert_into (nary, valid_info->nary, true);
431 gcc_assert (nary->unwind_to == NULL);
432 last_inserted_nary = nary->next;
433 nary->next = (vn_nary_op_t)(void *)-1;
434 if (dump_file && (dump_flags & TDF_DETAILS))
436 fprintf (dump_file, "Recording ");
437 print_generic_expr (dump_file, name, TDF_SLIM);
438 fprintf (dump_file, " != 0\n");
441 break;
443 case RESULT_DECL:
444 /* If the result is passed by invisible reference the default
445 def is initialized, otherwise it's uninitialized. Still
446 undefined is varying. */
447 newinfo->visited = true;
448 newinfo->valnum = name;
449 break;
451 default:
452 gcc_unreachable ();
454 return newinfo;
457 /* Return the SSA value of X. */
459 inline tree
460 SSA_VAL (tree x, bool *visited = NULL)
462 vn_ssa_aux_t tem = vn_ssa_aux_hash->find_with_hash (x, SSA_NAME_VERSION (x));
463 if (visited)
464 *visited = tem && tem->visited;
465 return tem && tem->visited ? tem->valnum : x;
468 /* Return the SSA value of the VUSE x, supporting released VDEFs
469 during elimination which will value-number the VDEF to the
470 associated VUSE (but not substitute in the whole lattice). */
472 static inline tree
473 vuse_ssa_val (tree x)
475 if (!x)
476 return NULL_TREE;
480 x = SSA_VAL (x);
481 gcc_assert (x != VN_TOP);
483 while (SSA_NAME_IN_FREE_LIST (x));
485 return x;
488 /* Similar to the above but used as callback for walk_non_aliases_vuses
489 and thus should stop at unvisited VUSE to not walk across region
490 boundaries. */
492 static tree
493 vuse_valueize (tree vuse)
497 bool visited;
498 vuse = SSA_VAL (vuse, &visited);
499 if (!visited)
500 return NULL_TREE;
501 gcc_assert (vuse != VN_TOP);
503 while (SSA_NAME_IN_FREE_LIST (vuse));
504 return vuse;
508 /* Return the vn_kind the expression computed by the stmt should be
509 associated with. */
511 enum vn_kind
512 vn_get_stmt_kind (gimple *stmt)
514 switch (gimple_code (stmt))
516 case GIMPLE_CALL:
517 return VN_REFERENCE;
518 case GIMPLE_PHI:
519 return VN_PHI;
520 case GIMPLE_ASSIGN:
522 enum tree_code code = gimple_assign_rhs_code (stmt);
523 tree rhs1 = gimple_assign_rhs1 (stmt);
524 switch (get_gimple_rhs_class (code))
526 case GIMPLE_UNARY_RHS:
527 case GIMPLE_BINARY_RHS:
528 case GIMPLE_TERNARY_RHS:
529 return VN_NARY;
530 case GIMPLE_SINGLE_RHS:
531 switch (TREE_CODE_CLASS (code))
533 case tcc_reference:
534 /* VOP-less references can go through unary case. */
535 if ((code == REALPART_EXPR
536 || code == IMAGPART_EXPR
537 || code == VIEW_CONVERT_EXPR
538 || code == BIT_FIELD_REF)
539 && TREE_CODE (TREE_OPERAND (rhs1, 0)) == SSA_NAME)
540 return VN_NARY;
542 /* Fallthrough. */
543 case tcc_declaration:
544 return VN_REFERENCE;
546 case tcc_constant:
547 return VN_CONSTANT;
549 default:
550 if (code == ADDR_EXPR)
551 return (is_gimple_min_invariant (rhs1)
552 ? VN_CONSTANT : VN_REFERENCE);
553 else if (code == CONSTRUCTOR)
554 return VN_NARY;
555 return VN_NONE;
557 default:
558 return VN_NONE;
561 default:
562 return VN_NONE;
566 /* Lookup a value id for CONSTANT and return it. If it does not
567 exist returns 0. */
569 unsigned int
570 get_constant_value_id (tree constant)
572 vn_constant_s **slot;
573 struct vn_constant_s vc;
575 vc.hashcode = vn_hash_constant_with_type (constant);
576 vc.constant = constant;
577 slot = constant_to_value_id->find_slot (&vc, NO_INSERT);
578 if (slot)
579 return (*slot)->value_id;
580 return 0;
583 /* Lookup a value id for CONSTANT, and if it does not exist, create a
584 new one and return it. If it does exist, return it. */
586 unsigned int
587 get_or_alloc_constant_value_id (tree constant)
589 vn_constant_s **slot;
590 struct vn_constant_s vc;
591 vn_constant_t vcp;
593 /* If the hashtable isn't initialized we're not running from PRE and thus
594 do not need value-ids. */
595 if (!constant_to_value_id)
596 return 0;
598 vc.hashcode = vn_hash_constant_with_type (constant);
599 vc.constant = constant;
600 slot = constant_to_value_id->find_slot (&vc, INSERT);
601 if (*slot)
602 return (*slot)->value_id;
604 vcp = XNEW (struct vn_constant_s);
605 vcp->hashcode = vc.hashcode;
606 vcp->constant = constant;
607 vcp->value_id = get_next_value_id ();
608 *slot = vcp;
609 bitmap_set_bit (constant_value_ids, vcp->value_id);
610 return vcp->value_id;
613 /* Return true if V is a value id for a constant. */
615 bool
616 value_id_constant_p (unsigned int v)
618 return bitmap_bit_p (constant_value_ids, v);
621 /* Compute the hash for a reference operand VRO1. */
623 static void
624 vn_reference_op_compute_hash (const vn_reference_op_t vro1, inchash::hash &hstate)
626 hstate.add_int (vro1->opcode);
627 if (vro1->op0)
628 inchash::add_expr (vro1->op0, hstate);
629 if (vro1->op1)
630 inchash::add_expr (vro1->op1, hstate);
631 if (vro1->op2)
632 inchash::add_expr (vro1->op2, hstate);
635 /* Compute a hash for the reference operation VR1 and return it. */
637 static hashval_t
638 vn_reference_compute_hash (const vn_reference_t vr1)
640 inchash::hash hstate;
641 hashval_t result;
642 int i;
643 vn_reference_op_t vro;
644 poly_int64 off = -1;
645 bool deref = false;
647 FOR_EACH_VEC_ELT (vr1->operands, i, vro)
649 if (vro->opcode == MEM_REF)
650 deref = true;
651 else if (vro->opcode != ADDR_EXPR)
652 deref = false;
653 if (maybe_ne (vro->off, -1))
655 if (known_eq (off, -1))
656 off = 0;
657 off += vro->off;
659 else
661 if (maybe_ne (off, -1)
662 && maybe_ne (off, 0))
663 hstate.add_poly_int (off);
664 off = -1;
665 if (deref
666 && vro->opcode == ADDR_EXPR)
668 if (vro->op0)
670 tree op = TREE_OPERAND (vro->op0, 0);
671 hstate.add_int (TREE_CODE (op));
672 inchash::add_expr (op, hstate);
675 else
676 vn_reference_op_compute_hash (vro, hstate);
679 result = hstate.end ();
680 /* ??? We would ICE later if we hash instead of adding that in. */
681 if (vr1->vuse)
682 result += SSA_NAME_VERSION (vr1->vuse);
684 return result;
687 /* Return true if reference operations VR1 and VR2 are equivalent. This
688 means they have the same set of operands and vuses. */
690 bool
691 vn_reference_eq (const_vn_reference_t const vr1, const_vn_reference_t const vr2)
693 unsigned i, j;
695 /* Early out if this is not a hash collision. */
696 if (vr1->hashcode != vr2->hashcode)
697 return false;
699 /* The VOP needs to be the same. */
700 if (vr1->vuse != vr2->vuse)
701 return false;
703 /* If the operands are the same we are done. */
704 if (vr1->operands == vr2->operands)
705 return true;
707 if (!expressions_equal_p (TYPE_SIZE (vr1->type), TYPE_SIZE (vr2->type)))
708 return false;
710 if (INTEGRAL_TYPE_P (vr1->type)
711 && INTEGRAL_TYPE_P (vr2->type))
713 if (TYPE_PRECISION (vr1->type) != TYPE_PRECISION (vr2->type))
714 return false;
716 else if (INTEGRAL_TYPE_P (vr1->type)
717 && (TYPE_PRECISION (vr1->type)
718 != TREE_INT_CST_LOW (TYPE_SIZE (vr1->type))))
719 return false;
720 else if (INTEGRAL_TYPE_P (vr2->type)
721 && (TYPE_PRECISION (vr2->type)
722 != TREE_INT_CST_LOW (TYPE_SIZE (vr2->type))))
723 return false;
725 i = 0;
726 j = 0;
729 poly_int64 off1 = 0, off2 = 0;
730 vn_reference_op_t vro1, vro2;
731 vn_reference_op_s tem1, tem2;
732 bool deref1 = false, deref2 = false;
733 for (; vr1->operands.iterate (i, &vro1); i++)
735 if (vro1->opcode == MEM_REF)
736 deref1 = true;
737 /* Do not look through a storage order barrier. */
738 else if (vro1->opcode == VIEW_CONVERT_EXPR && vro1->reverse)
739 return false;
740 if (known_eq (vro1->off, -1))
741 break;
742 off1 += vro1->off;
744 for (; vr2->operands.iterate (j, &vro2); j++)
746 if (vro2->opcode == MEM_REF)
747 deref2 = true;
748 /* Do not look through a storage order barrier. */
749 else if (vro2->opcode == VIEW_CONVERT_EXPR && vro2->reverse)
750 return false;
751 if (known_eq (vro2->off, -1))
752 break;
753 off2 += vro2->off;
755 if (maybe_ne (off1, off2))
756 return false;
757 if (deref1 && vro1->opcode == ADDR_EXPR)
759 memset (&tem1, 0, sizeof (tem1));
760 tem1.op0 = TREE_OPERAND (vro1->op0, 0);
761 tem1.type = TREE_TYPE (tem1.op0);
762 tem1.opcode = TREE_CODE (tem1.op0);
763 vro1 = &tem1;
764 deref1 = false;
766 if (deref2 && vro2->opcode == ADDR_EXPR)
768 memset (&tem2, 0, sizeof (tem2));
769 tem2.op0 = TREE_OPERAND (vro2->op0, 0);
770 tem2.type = TREE_TYPE (tem2.op0);
771 tem2.opcode = TREE_CODE (tem2.op0);
772 vro2 = &tem2;
773 deref2 = false;
775 if (deref1 != deref2)
776 return false;
777 if (!vn_reference_op_eq (vro1, vro2))
778 return false;
779 ++j;
780 ++i;
782 while (vr1->operands.length () != i
783 || vr2->operands.length () != j);
785 return true;
788 /* Copy the operations present in load/store REF into RESULT, a vector of
789 vn_reference_op_s's. */
791 static void
792 copy_reference_ops_from_ref (tree ref, vec<vn_reference_op_s> *result)
794 if (TREE_CODE (ref) == TARGET_MEM_REF)
796 vn_reference_op_s temp;
798 result->reserve (3);
800 memset (&temp, 0, sizeof (temp));
801 temp.type = TREE_TYPE (ref);
802 temp.opcode = TREE_CODE (ref);
803 temp.op0 = TMR_INDEX (ref);
804 temp.op1 = TMR_STEP (ref);
805 temp.op2 = TMR_OFFSET (ref);
806 temp.off = -1;
807 temp.clique = MR_DEPENDENCE_CLIQUE (ref);
808 temp.base = MR_DEPENDENCE_BASE (ref);
809 result->quick_push (temp);
811 memset (&temp, 0, sizeof (temp));
812 temp.type = NULL_TREE;
813 temp.opcode = ERROR_MARK;
814 temp.op0 = TMR_INDEX2 (ref);
815 temp.off = -1;
816 result->quick_push (temp);
818 memset (&temp, 0, sizeof (temp));
819 temp.type = NULL_TREE;
820 temp.opcode = TREE_CODE (TMR_BASE (ref));
821 temp.op0 = TMR_BASE (ref);
822 temp.off = -1;
823 result->quick_push (temp);
824 return;
827 /* For non-calls, store the information that makes up the address. */
828 tree orig = ref;
829 while (ref)
831 vn_reference_op_s temp;
833 memset (&temp, 0, sizeof (temp));
834 temp.type = TREE_TYPE (ref);
835 temp.opcode = TREE_CODE (ref);
836 temp.off = -1;
838 switch (temp.opcode)
840 case MODIFY_EXPR:
841 temp.op0 = TREE_OPERAND (ref, 1);
842 break;
843 case WITH_SIZE_EXPR:
844 temp.op0 = TREE_OPERAND (ref, 1);
845 temp.off = 0;
846 break;
847 case MEM_REF:
848 /* The base address gets its own vn_reference_op_s structure. */
849 temp.op0 = TREE_OPERAND (ref, 1);
850 if (!mem_ref_offset (ref).to_shwi (&temp.off))
851 temp.off = -1;
852 temp.clique = MR_DEPENDENCE_CLIQUE (ref);
853 temp.base = MR_DEPENDENCE_BASE (ref);
854 temp.reverse = REF_REVERSE_STORAGE_ORDER (ref);
855 break;
856 case BIT_FIELD_REF:
857 /* Record bits, position and storage order. */
858 temp.op0 = TREE_OPERAND (ref, 1);
859 temp.op1 = TREE_OPERAND (ref, 2);
860 if (!multiple_p (bit_field_offset (ref), BITS_PER_UNIT, &temp.off))
861 temp.off = -1;
862 temp.reverse = REF_REVERSE_STORAGE_ORDER (ref);
863 break;
864 case COMPONENT_REF:
865 /* The field decl is enough to unambiguously specify the field,
866 a matching type is not necessary and a mismatching type
867 is always a spurious difference. */
868 temp.type = NULL_TREE;
869 temp.op0 = TREE_OPERAND (ref, 1);
870 temp.op1 = TREE_OPERAND (ref, 2);
872 tree this_offset = component_ref_field_offset (ref);
873 if (this_offset
874 && poly_int_tree_p (this_offset))
876 tree bit_offset = DECL_FIELD_BIT_OFFSET (TREE_OPERAND (ref, 1));
877 if (TREE_INT_CST_LOW (bit_offset) % BITS_PER_UNIT == 0)
879 poly_offset_int off
880 = (wi::to_poly_offset (this_offset)
881 + (wi::to_offset (bit_offset) >> LOG2_BITS_PER_UNIT));
882 /* Probibit value-numbering zero offset components
883 of addresses the same before the pass folding
884 __builtin_object_size had a chance to run
885 (checking cfun->after_inlining does the
886 trick here). */
887 if (TREE_CODE (orig) != ADDR_EXPR
888 || maybe_ne (off, 0)
889 || cfun->after_inlining)
890 off.to_shwi (&temp.off);
894 break;
895 case ARRAY_RANGE_REF:
896 case ARRAY_REF:
898 tree eltype = TREE_TYPE (TREE_TYPE (TREE_OPERAND (ref, 0)));
899 /* Record index as operand. */
900 temp.op0 = TREE_OPERAND (ref, 1);
901 /* Always record lower bounds and element size. */
902 temp.op1 = array_ref_low_bound (ref);
903 /* But record element size in units of the type alignment. */
904 temp.op2 = TREE_OPERAND (ref, 3);
905 temp.align = eltype->type_common.align;
906 if (! temp.op2)
907 temp.op2 = size_binop (EXACT_DIV_EXPR, TYPE_SIZE_UNIT (eltype),
908 size_int (TYPE_ALIGN_UNIT (eltype)));
909 if (poly_int_tree_p (temp.op0)
910 && poly_int_tree_p (temp.op1)
911 && TREE_CODE (temp.op2) == INTEGER_CST)
913 poly_offset_int off = ((wi::to_poly_offset (temp.op0)
914 - wi::to_poly_offset (temp.op1))
915 * wi::to_offset (temp.op2)
916 * vn_ref_op_align_unit (&temp));
917 off.to_shwi (&temp.off);
920 break;
921 case VAR_DECL:
922 if (DECL_HARD_REGISTER (ref))
924 temp.op0 = ref;
925 break;
927 /* Fallthru. */
928 case PARM_DECL:
929 case CONST_DECL:
930 case RESULT_DECL:
931 /* Canonicalize decls to MEM[&decl] which is what we end up with
932 when valueizing MEM[ptr] with ptr = &decl. */
933 temp.opcode = MEM_REF;
934 temp.op0 = build_int_cst (build_pointer_type (TREE_TYPE (ref)), 0);
935 temp.off = 0;
936 result->safe_push (temp);
937 temp.opcode = ADDR_EXPR;
938 temp.op0 = build1 (ADDR_EXPR, TREE_TYPE (temp.op0), ref);
939 temp.type = TREE_TYPE (temp.op0);
940 temp.off = -1;
941 break;
942 case STRING_CST:
943 case INTEGER_CST:
944 case COMPLEX_CST:
945 case VECTOR_CST:
946 case REAL_CST:
947 case FIXED_CST:
948 case CONSTRUCTOR:
949 case SSA_NAME:
950 temp.op0 = ref;
951 break;
952 case ADDR_EXPR:
953 if (is_gimple_min_invariant (ref))
955 temp.op0 = ref;
956 break;
958 break;
959 /* These are only interesting for their operands, their
960 existence, and their type. They will never be the last
961 ref in the chain of references (IE they require an
962 operand), so we don't have to put anything
963 for op* as it will be handled by the iteration */
964 case REALPART_EXPR:
965 temp.off = 0;
966 break;
967 case VIEW_CONVERT_EXPR:
968 temp.off = 0;
969 temp.reverse = storage_order_barrier_p (ref);
970 break;
971 case IMAGPART_EXPR:
972 /* This is only interesting for its constant offset. */
973 temp.off = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (TREE_TYPE (ref)));
974 break;
975 default:
976 gcc_unreachable ();
978 result->safe_push (temp);
980 if (REFERENCE_CLASS_P (ref)
981 || TREE_CODE (ref) == MODIFY_EXPR
982 || TREE_CODE (ref) == WITH_SIZE_EXPR
983 || (TREE_CODE (ref) == ADDR_EXPR
984 && !is_gimple_min_invariant (ref)))
985 ref = TREE_OPERAND (ref, 0);
986 else
987 ref = NULL_TREE;
991 /* Build a alias-oracle reference abstraction in *REF from the vn_reference
992 operands in *OPS, the reference alias set SET and the reference type TYPE.
993 Return true if something useful was produced. */
995 bool
996 ao_ref_init_from_vn_reference (ao_ref *ref,
997 alias_set_type set, tree type,
998 vec<vn_reference_op_s> ops)
1000 vn_reference_op_t op;
1001 unsigned i;
1002 tree base = NULL_TREE;
1003 tree *op0_p = &base;
1004 poly_offset_int offset = 0;
1005 poly_offset_int max_size;
1006 poly_offset_int size = -1;
1007 tree size_tree = NULL_TREE;
1008 alias_set_type base_alias_set = -1;
1010 /* First get the final access size from just the outermost expression. */
1011 op = &ops[0];
1012 if (op->opcode == COMPONENT_REF)
1013 size_tree = DECL_SIZE (op->op0);
1014 else if (op->opcode == BIT_FIELD_REF)
1015 size_tree = op->op0;
1016 else
1018 machine_mode mode = TYPE_MODE (type);
1019 if (mode == BLKmode)
1020 size_tree = TYPE_SIZE (type);
1021 else
1022 size = GET_MODE_BITSIZE (mode);
1024 if (size_tree != NULL_TREE
1025 && poly_int_tree_p (size_tree))
1026 size = wi::to_poly_offset (size_tree);
1028 /* Initially, maxsize is the same as the accessed element size.
1029 In the following it will only grow (or become -1). */
1030 max_size = size;
1032 /* Compute cumulative bit-offset for nested component-refs and array-refs,
1033 and find the ultimate containing object. */
1034 FOR_EACH_VEC_ELT (ops, i, op)
1036 switch (op->opcode)
1038 /* These may be in the reference ops, but we cannot do anything
1039 sensible with them here. */
1040 case ADDR_EXPR:
1041 /* Apart from ADDR_EXPR arguments to MEM_REF. */
1042 if (base != NULL_TREE
1043 && TREE_CODE (base) == MEM_REF
1044 && op->op0
1045 && DECL_P (TREE_OPERAND (op->op0, 0)))
1047 vn_reference_op_t pop = &ops[i-1];
1048 base = TREE_OPERAND (op->op0, 0);
1049 if (known_eq (pop->off, -1))
1051 max_size = -1;
1052 offset = 0;
1054 else
1055 offset += pop->off * BITS_PER_UNIT;
1056 op0_p = NULL;
1057 break;
1059 /* Fallthru. */
1060 case CALL_EXPR:
1061 return false;
1063 /* Record the base objects. */
1064 case MEM_REF:
1065 base_alias_set = get_deref_alias_set (op->op0);
1066 *op0_p = build2 (MEM_REF, op->type,
1067 NULL_TREE, op->op0);
1068 MR_DEPENDENCE_CLIQUE (*op0_p) = op->clique;
1069 MR_DEPENDENCE_BASE (*op0_p) = op->base;
1070 op0_p = &TREE_OPERAND (*op0_p, 0);
1071 break;
1073 case VAR_DECL:
1074 case PARM_DECL:
1075 case RESULT_DECL:
1076 case SSA_NAME:
1077 *op0_p = op->op0;
1078 op0_p = NULL;
1079 break;
1081 /* And now the usual component-reference style ops. */
1082 case BIT_FIELD_REF:
1083 offset += wi::to_poly_offset (op->op1);
1084 break;
1086 case COMPONENT_REF:
1088 tree field = op->op0;
1089 /* We do not have a complete COMPONENT_REF tree here so we
1090 cannot use component_ref_field_offset. Do the interesting
1091 parts manually. */
1092 tree this_offset = DECL_FIELD_OFFSET (field);
1094 if (op->op1 || !poly_int_tree_p (this_offset))
1095 max_size = -1;
1096 else
1098 poly_offset_int woffset = (wi::to_poly_offset (this_offset)
1099 << LOG2_BITS_PER_UNIT);
1100 woffset += wi::to_offset (DECL_FIELD_BIT_OFFSET (field));
1101 offset += woffset;
1103 break;
1106 case ARRAY_RANGE_REF:
1107 case ARRAY_REF:
1108 /* We recorded the lower bound and the element size. */
1109 if (!poly_int_tree_p (op->op0)
1110 || !poly_int_tree_p (op->op1)
1111 || TREE_CODE (op->op2) != INTEGER_CST)
1112 max_size = -1;
1113 else
1115 poly_offset_int woffset
1116 = wi::sext (wi::to_poly_offset (op->op0)
1117 - wi::to_poly_offset (op->op1),
1118 TYPE_PRECISION (TREE_TYPE (op->op0)));
1119 woffset *= wi::to_offset (op->op2) * vn_ref_op_align_unit (op);
1120 woffset <<= LOG2_BITS_PER_UNIT;
1121 offset += woffset;
1123 break;
1125 case REALPART_EXPR:
1126 break;
1128 case IMAGPART_EXPR:
1129 offset += size;
1130 break;
1132 case VIEW_CONVERT_EXPR:
1133 break;
1135 case STRING_CST:
1136 case INTEGER_CST:
1137 case COMPLEX_CST:
1138 case VECTOR_CST:
1139 case REAL_CST:
1140 case CONSTRUCTOR:
1141 case CONST_DECL:
1142 return false;
1144 default:
1145 return false;
1149 if (base == NULL_TREE)
1150 return false;
1152 ref->ref = NULL_TREE;
1153 ref->base = base;
1154 ref->ref_alias_set = set;
1155 if (base_alias_set != -1)
1156 ref->base_alias_set = base_alias_set;
1157 else
1158 ref->base_alias_set = get_alias_set (base);
1159 /* We discount volatiles from value-numbering elsewhere. */
1160 ref->volatile_p = false;
1162 if (!size.to_shwi (&ref->size) || maybe_lt (ref->size, 0))
1164 ref->offset = 0;
1165 ref->size = -1;
1166 ref->max_size = -1;
1167 return true;
1170 if (!offset.to_shwi (&ref->offset))
1172 ref->offset = 0;
1173 ref->max_size = -1;
1174 return true;
1177 if (!max_size.to_shwi (&ref->max_size) || maybe_lt (ref->max_size, 0))
1178 ref->max_size = -1;
1180 return true;
1183 /* Copy the operations present in load/store/call REF into RESULT, a vector of
1184 vn_reference_op_s's. */
1186 static void
1187 copy_reference_ops_from_call (gcall *call,
1188 vec<vn_reference_op_s> *result)
1190 vn_reference_op_s temp;
1191 unsigned i;
1192 tree lhs = gimple_call_lhs (call);
1193 int lr;
1195 /* If 2 calls have a different non-ssa lhs, vdef value numbers should be
1196 different. By adding the lhs here in the vector, we ensure that the
1197 hashcode is different, guaranteeing a different value number. */
1198 if (lhs && TREE_CODE (lhs) != SSA_NAME)
1200 memset (&temp, 0, sizeof (temp));
1201 temp.opcode = MODIFY_EXPR;
1202 temp.type = TREE_TYPE (lhs);
1203 temp.op0 = lhs;
1204 temp.off = -1;
1205 result->safe_push (temp);
1208 /* Copy the type, opcode, function, static chain and EH region, if any. */
1209 memset (&temp, 0, sizeof (temp));
1210 temp.type = gimple_call_fntype (call);
1211 temp.opcode = CALL_EXPR;
1212 temp.op0 = gimple_call_fn (call);
1213 temp.op1 = gimple_call_chain (call);
1214 if (stmt_could_throw_p (cfun, call) && (lr = lookup_stmt_eh_lp (call)) > 0)
1215 temp.op2 = size_int (lr);
1216 temp.off = -1;
1217 result->safe_push (temp);
1219 /* Copy the call arguments. As they can be references as well,
1220 just chain them together. */
1221 for (i = 0; i < gimple_call_num_args (call); ++i)
1223 tree callarg = gimple_call_arg (call, i);
1224 copy_reference_ops_from_ref (callarg, result);
1228 /* Fold *& at position *I_P in a vn_reference_op_s vector *OPS. Updates
1229 *I_P to point to the last element of the replacement. */
1230 static bool
1231 vn_reference_fold_indirect (vec<vn_reference_op_s> *ops,
1232 unsigned int *i_p)
1234 unsigned int i = *i_p;
1235 vn_reference_op_t op = &(*ops)[i];
1236 vn_reference_op_t mem_op = &(*ops)[i - 1];
1237 tree addr_base;
1238 poly_int64 addr_offset = 0;
1240 /* The only thing we have to do is from &OBJ.foo.bar add the offset
1241 from .foo.bar to the preceding MEM_REF offset and replace the
1242 address with &OBJ. */
1243 addr_base = get_addr_base_and_unit_offset (TREE_OPERAND (op->op0, 0),
1244 &addr_offset);
1245 gcc_checking_assert (addr_base && TREE_CODE (addr_base) != MEM_REF);
1246 if (addr_base != TREE_OPERAND (op->op0, 0))
1248 poly_offset_int off
1249 = (poly_offset_int::from (wi::to_poly_wide (mem_op->op0),
1250 SIGNED)
1251 + addr_offset);
1252 mem_op->op0 = wide_int_to_tree (TREE_TYPE (mem_op->op0), off);
1253 op->op0 = build_fold_addr_expr (addr_base);
1254 if (tree_fits_shwi_p (mem_op->op0))
1255 mem_op->off = tree_to_shwi (mem_op->op0);
1256 else
1257 mem_op->off = -1;
1258 return true;
1260 return false;
1263 /* Fold *& at position *I_P in a vn_reference_op_s vector *OPS. Updates
1264 *I_P to point to the last element of the replacement. */
1265 static bool
1266 vn_reference_maybe_forwprop_address (vec<vn_reference_op_s> *ops,
1267 unsigned int *i_p)
1269 unsigned int i = *i_p;
1270 vn_reference_op_t op = &(*ops)[i];
1271 vn_reference_op_t mem_op = &(*ops)[i - 1];
1272 gimple *def_stmt;
1273 enum tree_code code;
1274 poly_offset_int off;
1276 def_stmt = SSA_NAME_DEF_STMT (op->op0);
1277 if (!is_gimple_assign (def_stmt))
1278 return false;
1280 code = gimple_assign_rhs_code (def_stmt);
1281 if (code != ADDR_EXPR
1282 && code != POINTER_PLUS_EXPR)
1283 return false;
1285 off = poly_offset_int::from (wi::to_poly_wide (mem_op->op0), SIGNED);
1287 /* The only thing we have to do is from &OBJ.foo.bar add the offset
1288 from .foo.bar to the preceding MEM_REF offset and replace the
1289 address with &OBJ. */
1290 if (code == ADDR_EXPR)
1292 tree addr, addr_base;
1293 poly_int64 addr_offset;
1295 addr = gimple_assign_rhs1 (def_stmt);
1296 addr_base = get_addr_base_and_unit_offset (TREE_OPERAND (addr, 0),
1297 &addr_offset);
1298 /* If that didn't work because the address isn't invariant propagate
1299 the reference tree from the address operation in case the current
1300 dereference isn't offsetted. */
1301 if (!addr_base
1302 && *i_p == ops->length () - 1
1303 && known_eq (off, 0)
1304 /* This makes us disable this transform for PRE where the
1305 reference ops might be also used for code insertion which
1306 is invalid. */
1307 && default_vn_walk_kind == VN_WALKREWRITE)
1309 auto_vec<vn_reference_op_s, 32> tem;
1310 copy_reference_ops_from_ref (TREE_OPERAND (addr, 0), &tem);
1311 /* Make sure to preserve TBAA info. The only objects not
1312 wrapped in MEM_REFs that can have their address taken are
1313 STRING_CSTs. */
1314 if (tem.length () >= 2
1315 && tem[tem.length () - 2].opcode == MEM_REF)
1317 vn_reference_op_t new_mem_op = &tem[tem.length () - 2];
1318 new_mem_op->op0
1319 = wide_int_to_tree (TREE_TYPE (mem_op->op0),
1320 wi::to_poly_wide (new_mem_op->op0));
1322 else
1323 gcc_assert (tem.last ().opcode == STRING_CST);
1324 ops->pop ();
1325 ops->pop ();
1326 ops->safe_splice (tem);
1327 --*i_p;
1328 return true;
1330 if (!addr_base
1331 || TREE_CODE (addr_base) != MEM_REF
1332 || (TREE_CODE (TREE_OPERAND (addr_base, 0)) == SSA_NAME
1333 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (addr_base, 0))))
1334 return false;
1336 off += addr_offset;
1337 off += mem_ref_offset (addr_base);
1338 op->op0 = TREE_OPERAND (addr_base, 0);
1340 else
1342 tree ptr, ptroff;
1343 ptr = gimple_assign_rhs1 (def_stmt);
1344 ptroff = gimple_assign_rhs2 (def_stmt);
1345 if (TREE_CODE (ptr) != SSA_NAME
1346 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ptr)
1347 /* Make sure to not endlessly recurse.
1348 See gcc.dg/tree-ssa/20040408-1.c for an example. Can easily
1349 happen when we value-number a PHI to its backedge value. */
1350 || SSA_VAL (ptr) == op->op0
1351 || !poly_int_tree_p (ptroff))
1352 return false;
1354 off += wi::to_poly_offset (ptroff);
1355 op->op0 = ptr;
1358 mem_op->op0 = wide_int_to_tree (TREE_TYPE (mem_op->op0), off);
1359 if (tree_fits_shwi_p (mem_op->op0))
1360 mem_op->off = tree_to_shwi (mem_op->op0);
1361 else
1362 mem_op->off = -1;
1363 /* ??? Can end up with endless recursion here!?
1364 gcc.c-torture/execute/strcmp-1.c */
1365 if (TREE_CODE (op->op0) == SSA_NAME)
1366 op->op0 = SSA_VAL (op->op0);
1367 if (TREE_CODE (op->op0) != SSA_NAME)
1368 op->opcode = TREE_CODE (op->op0);
1370 /* And recurse. */
1371 if (TREE_CODE (op->op0) == SSA_NAME)
1372 vn_reference_maybe_forwprop_address (ops, i_p);
1373 else if (TREE_CODE (op->op0) == ADDR_EXPR)
1374 vn_reference_fold_indirect (ops, i_p);
1375 return true;
1378 /* Optimize the reference REF to a constant if possible or return
1379 NULL_TREE if not. */
1381 tree
1382 fully_constant_vn_reference_p (vn_reference_t ref)
1384 vec<vn_reference_op_s> operands = ref->operands;
1385 vn_reference_op_t op;
1387 /* Try to simplify the translated expression if it is
1388 a call to a builtin function with at most two arguments. */
1389 op = &operands[0];
1390 if (op->opcode == CALL_EXPR
1391 && TREE_CODE (op->op0) == ADDR_EXPR
1392 && TREE_CODE (TREE_OPERAND (op->op0, 0)) == FUNCTION_DECL
1393 && fndecl_built_in_p (TREE_OPERAND (op->op0, 0))
1394 && operands.length () >= 2
1395 && operands.length () <= 3)
1397 vn_reference_op_t arg0, arg1 = NULL;
1398 bool anyconst = false;
1399 arg0 = &operands[1];
1400 if (operands.length () > 2)
1401 arg1 = &operands[2];
1402 if (TREE_CODE_CLASS (arg0->opcode) == tcc_constant
1403 || (arg0->opcode == ADDR_EXPR
1404 && is_gimple_min_invariant (arg0->op0)))
1405 anyconst = true;
1406 if (arg1
1407 && (TREE_CODE_CLASS (arg1->opcode) == tcc_constant
1408 || (arg1->opcode == ADDR_EXPR
1409 && is_gimple_min_invariant (arg1->op0))))
1410 anyconst = true;
1411 if (anyconst)
1413 tree folded = build_call_expr (TREE_OPERAND (op->op0, 0),
1414 arg1 ? 2 : 1,
1415 arg0->op0,
1416 arg1 ? arg1->op0 : NULL);
1417 if (folded
1418 && TREE_CODE (folded) == NOP_EXPR)
1419 folded = TREE_OPERAND (folded, 0);
1420 if (folded
1421 && is_gimple_min_invariant (folded))
1422 return folded;
1426 /* Simplify reads from constants or constant initializers. */
1427 else if (BITS_PER_UNIT == 8
1428 && COMPLETE_TYPE_P (ref->type)
1429 && is_gimple_reg_type (ref->type))
1431 poly_int64 off = 0;
1432 HOST_WIDE_INT size;
1433 if (INTEGRAL_TYPE_P (ref->type))
1434 size = TYPE_PRECISION (ref->type);
1435 else if (tree_fits_shwi_p (TYPE_SIZE (ref->type)))
1436 size = tree_to_shwi (TYPE_SIZE (ref->type));
1437 else
1438 return NULL_TREE;
1439 if (size % BITS_PER_UNIT != 0
1440 || size > MAX_BITSIZE_MODE_ANY_MODE)
1441 return NULL_TREE;
1442 size /= BITS_PER_UNIT;
1443 unsigned i;
1444 for (i = 0; i < operands.length (); ++i)
1446 if (TREE_CODE_CLASS (operands[i].opcode) == tcc_constant)
1448 ++i;
1449 break;
1451 if (known_eq (operands[i].off, -1))
1452 return NULL_TREE;
1453 off += operands[i].off;
1454 if (operands[i].opcode == MEM_REF)
1456 ++i;
1457 break;
1460 vn_reference_op_t base = &operands[--i];
1461 tree ctor = error_mark_node;
1462 tree decl = NULL_TREE;
1463 if (TREE_CODE_CLASS (base->opcode) == tcc_constant)
1464 ctor = base->op0;
1465 else if (base->opcode == MEM_REF
1466 && base[1].opcode == ADDR_EXPR
1467 && (TREE_CODE (TREE_OPERAND (base[1].op0, 0)) == VAR_DECL
1468 || TREE_CODE (TREE_OPERAND (base[1].op0, 0)) == CONST_DECL
1469 || TREE_CODE (TREE_OPERAND (base[1].op0, 0)) == STRING_CST))
1471 decl = TREE_OPERAND (base[1].op0, 0);
1472 if (TREE_CODE (decl) == STRING_CST)
1473 ctor = decl;
1474 else
1475 ctor = ctor_for_folding (decl);
1477 if (ctor == NULL_TREE)
1478 return build_zero_cst (ref->type);
1479 else if (ctor != error_mark_node)
1481 HOST_WIDE_INT const_off;
1482 if (decl)
1484 tree res = fold_ctor_reference (ref->type, ctor,
1485 off * BITS_PER_UNIT,
1486 size * BITS_PER_UNIT, decl);
1487 if (res)
1489 STRIP_USELESS_TYPE_CONVERSION (res);
1490 if (is_gimple_min_invariant (res))
1491 return res;
1494 else if (off.is_constant (&const_off))
1496 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
1497 int len = native_encode_expr (ctor, buf, size, const_off);
1498 if (len > 0)
1499 return native_interpret_expr (ref->type, buf, len);
1504 return NULL_TREE;
1507 /* Return true if OPS contain a storage order barrier. */
1509 static bool
1510 contains_storage_order_barrier_p (vec<vn_reference_op_s> ops)
1512 vn_reference_op_t op;
1513 unsigned i;
1515 FOR_EACH_VEC_ELT (ops, i, op)
1516 if (op->opcode == VIEW_CONVERT_EXPR && op->reverse)
1517 return true;
1519 return false;
1522 /* Transform any SSA_NAME's in a vector of vn_reference_op_s
1523 structures into their value numbers. This is done in-place, and
1524 the vector passed in is returned. *VALUEIZED_ANYTHING will specify
1525 whether any operands were valueized. */
1527 static vec<vn_reference_op_s>
1528 valueize_refs_1 (vec<vn_reference_op_s> orig, bool *valueized_anything,
1529 bool with_avail = false)
1531 vn_reference_op_t vro;
1532 unsigned int i;
1534 *valueized_anything = false;
1536 FOR_EACH_VEC_ELT (orig, i, vro)
1538 if (vro->opcode == SSA_NAME
1539 || (vro->op0 && TREE_CODE (vro->op0) == SSA_NAME))
1541 tree tem = with_avail ? vn_valueize (vro->op0) : SSA_VAL (vro->op0);
1542 if (tem != vro->op0)
1544 *valueized_anything = true;
1545 vro->op0 = tem;
1547 /* If it transforms from an SSA_NAME to a constant, update
1548 the opcode. */
1549 if (TREE_CODE (vro->op0) != SSA_NAME && vro->opcode == SSA_NAME)
1550 vro->opcode = TREE_CODE (vro->op0);
1552 if (vro->op1 && TREE_CODE (vro->op1) == SSA_NAME)
1554 tree tem = with_avail ? vn_valueize (vro->op1) : SSA_VAL (vro->op1);
1555 if (tem != vro->op1)
1557 *valueized_anything = true;
1558 vro->op1 = tem;
1561 if (vro->op2 && TREE_CODE (vro->op2) == SSA_NAME)
1563 tree tem = with_avail ? vn_valueize (vro->op2) : SSA_VAL (vro->op2);
1564 if (tem != vro->op2)
1566 *valueized_anything = true;
1567 vro->op2 = tem;
1570 /* If it transforms from an SSA_NAME to an address, fold with
1571 a preceding indirect reference. */
1572 if (i > 0
1573 && vro->op0
1574 && TREE_CODE (vro->op0) == ADDR_EXPR
1575 && orig[i - 1].opcode == MEM_REF)
1577 if (vn_reference_fold_indirect (&orig, &i))
1578 *valueized_anything = true;
1580 else if (i > 0
1581 && vro->opcode == SSA_NAME
1582 && orig[i - 1].opcode == MEM_REF)
1584 if (vn_reference_maybe_forwprop_address (&orig, &i))
1585 *valueized_anything = true;
1587 /* If it transforms a non-constant ARRAY_REF into a constant
1588 one, adjust the constant offset. */
1589 else if (vro->opcode == ARRAY_REF
1590 && known_eq (vro->off, -1)
1591 && poly_int_tree_p (vro->op0)
1592 && poly_int_tree_p (vro->op1)
1593 && TREE_CODE (vro->op2) == INTEGER_CST)
1595 poly_offset_int off = ((wi::to_poly_offset (vro->op0)
1596 - wi::to_poly_offset (vro->op1))
1597 * wi::to_offset (vro->op2)
1598 * vn_ref_op_align_unit (vro));
1599 off.to_shwi (&vro->off);
1603 return orig;
1606 static vec<vn_reference_op_s>
1607 valueize_refs (vec<vn_reference_op_s> orig)
1609 bool tem;
1610 return valueize_refs_1 (orig, &tem);
1613 static vec<vn_reference_op_s> shared_lookup_references;
1615 /* Create a vector of vn_reference_op_s structures from REF, a
1616 REFERENCE_CLASS_P tree. The vector is shared among all callers of
1617 this function. *VALUEIZED_ANYTHING will specify whether any
1618 operands were valueized. */
1620 static vec<vn_reference_op_s>
1621 valueize_shared_reference_ops_from_ref (tree ref, bool *valueized_anything)
1623 if (!ref)
1624 return vNULL;
1625 shared_lookup_references.truncate (0);
1626 copy_reference_ops_from_ref (ref, &shared_lookup_references);
1627 shared_lookup_references = valueize_refs_1 (shared_lookup_references,
1628 valueized_anything);
1629 return shared_lookup_references;
1632 /* Create a vector of vn_reference_op_s structures from CALL, a
1633 call statement. The vector is shared among all callers of
1634 this function. */
1636 static vec<vn_reference_op_s>
1637 valueize_shared_reference_ops_from_call (gcall *call)
1639 if (!call)
1640 return vNULL;
1641 shared_lookup_references.truncate (0);
1642 copy_reference_ops_from_call (call, &shared_lookup_references);
1643 shared_lookup_references = valueize_refs (shared_lookup_references);
1644 return shared_lookup_references;
1647 /* Lookup a SCCVN reference operation VR in the current hash table.
1648 Returns the resulting value number if it exists in the hash table,
1649 NULL_TREE otherwise. VNRESULT will be filled in with the actual
1650 vn_reference_t stored in the hashtable if something is found. */
1652 static tree
1653 vn_reference_lookup_1 (vn_reference_t vr, vn_reference_t *vnresult)
1655 vn_reference_s **slot;
1656 hashval_t hash;
1658 hash = vr->hashcode;
1659 slot = valid_info->references->find_slot_with_hash (vr, hash, NO_INSERT);
1660 if (slot)
1662 if (vnresult)
1663 *vnresult = (vn_reference_t)*slot;
1664 return ((vn_reference_t)*slot)->result;
1667 return NULL_TREE;
1670 /* Callback for walk_non_aliased_vuses. Adjusts the vn_reference_t VR_
1671 with the current VUSE and performs the expression lookup. */
1673 static void *
1674 vn_reference_lookup_2 (ao_ref *op ATTRIBUTE_UNUSED, tree vuse,
1675 unsigned int cnt, void *vr_)
1677 vn_reference_t vr = (vn_reference_t)vr_;
1678 vn_reference_s **slot;
1679 hashval_t hash;
1681 /* This bounds the stmt walks we perform on reference lookups
1682 to O(1) instead of O(N) where N is the number of dominating
1683 stores. */
1684 if (cnt > (unsigned) PARAM_VALUE (PARAM_SCCVN_MAX_ALIAS_QUERIES_PER_ACCESS))
1685 return (void *)-1;
1687 if (last_vuse_ptr)
1688 *last_vuse_ptr = vuse;
1690 /* Fixup vuse and hash. */
1691 if (vr->vuse)
1692 vr->hashcode = vr->hashcode - SSA_NAME_VERSION (vr->vuse);
1693 vr->vuse = vuse_ssa_val (vuse);
1694 if (vr->vuse)
1695 vr->hashcode = vr->hashcode + SSA_NAME_VERSION (vr->vuse);
1697 hash = vr->hashcode;
1698 slot = valid_info->references->find_slot_with_hash (vr, hash, NO_INSERT);
1699 if (slot)
1700 return *slot;
1702 return NULL;
1705 /* Lookup an existing or insert a new vn_reference entry into the
1706 value table for the VUSE, SET, TYPE, OPERANDS reference which
1707 has the value VALUE which is either a constant or an SSA name. */
1709 static vn_reference_t
1710 vn_reference_lookup_or_insert_for_pieces (tree vuse,
1711 alias_set_type set,
1712 tree type,
1713 vec<vn_reference_op_s,
1714 va_heap> operands,
1715 tree value)
1717 vn_reference_s vr1;
1718 vn_reference_t result;
1719 unsigned value_id;
1720 vr1.vuse = vuse ? SSA_VAL (vuse) : NULL_TREE;
1721 vr1.operands = operands;
1722 vr1.type = type;
1723 vr1.set = set;
1724 vr1.hashcode = vn_reference_compute_hash (&vr1);
1725 if (vn_reference_lookup_1 (&vr1, &result))
1726 return result;
1727 if (TREE_CODE (value) == SSA_NAME)
1728 value_id = VN_INFO (value)->value_id;
1729 else
1730 value_id = get_or_alloc_constant_value_id (value);
1731 return vn_reference_insert_pieces (vuse, set, type,
1732 operands.copy (), value, value_id);
1735 /* Return a value-number for RCODE OPS... either by looking up an existing
1736 value-number for the simplified result or by inserting the operation if
1737 INSERT is true. */
1739 static tree
1740 vn_nary_build_or_lookup_1 (gimple_match_op *res_op, bool insert)
1742 tree result = NULL_TREE;
1743 /* We will be creating a value number for
1744 RCODE (OPS...).
1745 So first simplify and lookup this expression to see if it
1746 is already available. */
1747 mprts_hook = vn_lookup_simplify_result;
1748 bool res = false;
1749 switch (TREE_CODE_LENGTH ((tree_code) res_op->code))
1751 case 1:
1752 res = gimple_resimplify1 (NULL, res_op, vn_valueize);
1753 break;
1754 case 2:
1755 res = gimple_resimplify2 (NULL, res_op, vn_valueize);
1756 break;
1757 case 3:
1758 res = gimple_resimplify3 (NULL, res_op, vn_valueize);
1759 break;
1761 mprts_hook = NULL;
1762 gimple *new_stmt = NULL;
1763 if (res
1764 && gimple_simplified_result_is_gimple_val (res_op))
1766 /* The expression is already available. */
1767 result = res_op->ops[0];
1768 /* Valueize it, simplification returns sth in AVAIL only. */
1769 if (TREE_CODE (result) == SSA_NAME)
1770 result = SSA_VAL (result);
1772 else
1774 tree val = vn_lookup_simplify_result (res_op);
1775 if (!val && insert)
1777 gimple_seq stmts = NULL;
1778 result = maybe_push_res_to_seq (res_op, &stmts);
1779 if (result)
1781 gcc_assert (gimple_seq_singleton_p (stmts));
1782 new_stmt = gimple_seq_first_stmt (stmts);
1785 else
1786 /* The expression is already available. */
1787 result = val;
1789 if (new_stmt)
1791 /* The expression is not yet available, value-number lhs to
1792 the new SSA_NAME we created. */
1793 /* Initialize value-number information properly. */
1794 vn_ssa_aux_t result_info = VN_INFO (result);
1795 result_info->valnum = result;
1796 result_info->value_id = get_next_value_id ();
1797 result_info->visited = 1;
1798 gimple_seq_add_stmt_without_update (&VN_INFO (result)->expr,
1799 new_stmt);
1800 result_info->needs_insertion = true;
1801 /* ??? PRE phi-translation inserts NARYs without corresponding
1802 SSA name result. Re-use those but set their result according
1803 to the stmt we just built. */
1804 vn_nary_op_t nary = NULL;
1805 vn_nary_op_lookup_stmt (new_stmt, &nary);
1806 if (nary)
1808 gcc_assert (! nary->predicated_values && nary->u.result == NULL_TREE);
1809 nary->u.result = gimple_assign_lhs (new_stmt);
1811 /* As all "inserted" statements are singleton SCCs, insert
1812 to the valid table. This is strictly needed to
1813 avoid re-generating new value SSA_NAMEs for the same
1814 expression during SCC iteration over and over (the
1815 optimistic table gets cleared after each iteration).
1816 We do not need to insert into the optimistic table, as
1817 lookups there will fall back to the valid table. */
1818 else
1820 unsigned int length = vn_nary_length_from_stmt (new_stmt);
1821 vn_nary_op_t vno1
1822 = alloc_vn_nary_op_noinit (length, &vn_tables_insert_obstack);
1823 vno1->value_id = result_info->value_id;
1824 vno1->length = length;
1825 vno1->predicated_values = 0;
1826 vno1->u.result = result;
1827 init_vn_nary_op_from_stmt (vno1, new_stmt);
1828 vn_nary_op_insert_into (vno1, valid_info->nary, true);
1829 /* Also do not link it into the undo chain. */
1830 last_inserted_nary = vno1->next;
1831 vno1->next = (vn_nary_op_t)(void *)-1;
1833 if (dump_file && (dump_flags & TDF_DETAILS))
1835 fprintf (dump_file, "Inserting name ");
1836 print_generic_expr (dump_file, result);
1837 fprintf (dump_file, " for expression ");
1838 print_gimple_expr (dump_file, new_stmt, 0, TDF_SLIM);
1839 fprintf (dump_file, "\n");
1842 return result;
1845 /* Return a value-number for RCODE OPS... either by looking up an existing
1846 value-number for the simplified result or by inserting the operation. */
1848 static tree
1849 vn_nary_build_or_lookup (gimple_match_op *res_op)
1851 return vn_nary_build_or_lookup_1 (res_op, true);
1854 /* Try to simplify the expression RCODE OPS... of type TYPE and return
1855 its value if present. */
1857 tree
1858 vn_nary_simplify (vn_nary_op_t nary)
1860 if (nary->length > gimple_match_op::MAX_NUM_OPS)
1861 return NULL_TREE;
1862 gimple_match_op op (gimple_match_cond::UNCOND, nary->opcode,
1863 nary->type, nary->length);
1864 memcpy (op.ops, nary->op, sizeof (tree) * nary->length);
1865 return vn_nary_build_or_lookup_1 (&op, false);
1868 basic_block vn_context_bb;
1870 /* Callback for walk_non_aliased_vuses. Tries to perform a lookup
1871 from the statement defining VUSE and if not successful tries to
1872 translate *REFP and VR_ through an aggregate copy at the definition
1873 of VUSE. If *DISAMBIGUATE_ONLY is true then do not perform translation
1874 of *REF and *VR. If only disambiguation was performed then
1875 *DISAMBIGUATE_ONLY is set to true. */
1877 static void *
1878 vn_reference_lookup_3 (ao_ref *ref, tree vuse, void *vr_,
1879 bool *disambiguate_only)
1881 vn_reference_t vr = (vn_reference_t)vr_;
1882 gimple *def_stmt = SSA_NAME_DEF_STMT (vuse);
1883 tree base = ao_ref_base (ref);
1884 HOST_WIDE_INT offseti, maxsizei;
1885 static vec<vn_reference_op_s> lhs_ops;
1886 ao_ref lhs_ref;
1887 bool lhs_ref_ok = false;
1888 poly_int64 copy_size;
1890 /* First try to disambiguate after value-replacing in the definitions LHS. */
1891 if (is_gimple_assign (def_stmt))
1893 tree lhs = gimple_assign_lhs (def_stmt);
1894 bool valueized_anything = false;
1895 /* Avoid re-allocation overhead. */
1896 lhs_ops.truncate (0);
1897 basic_block saved_rpo_bb = vn_context_bb;
1898 vn_context_bb = gimple_bb (def_stmt);
1899 copy_reference_ops_from_ref (lhs, &lhs_ops);
1900 lhs_ops = valueize_refs_1 (lhs_ops, &valueized_anything, true);
1901 vn_context_bb = saved_rpo_bb;
1902 if (valueized_anything)
1904 lhs_ref_ok = ao_ref_init_from_vn_reference (&lhs_ref,
1905 get_alias_set (lhs),
1906 TREE_TYPE (lhs), lhs_ops);
1907 if (lhs_ref_ok
1908 && !refs_may_alias_p_1 (ref, &lhs_ref, true))
1910 *disambiguate_only = true;
1911 return NULL;
1914 else
1916 ao_ref_init (&lhs_ref, lhs);
1917 lhs_ref_ok = true;
1920 /* If we reach a clobbering statement try to skip it and see if
1921 we find a VN result with exactly the same value as the
1922 possible clobber. In this case we can ignore the clobber
1923 and return the found value.
1924 Note that we don't need to worry about partial overlapping
1925 accesses as we then can use TBAA to disambiguate against the
1926 clobbering statement when looking up a load (thus the
1927 VN_WALKREWRITE guard). */
1928 if (vn_walk_kind == VN_WALKREWRITE
1929 && is_gimple_reg_type (TREE_TYPE (lhs))
1930 && types_compatible_p (TREE_TYPE (lhs), vr->type))
1932 tree *saved_last_vuse_ptr = last_vuse_ptr;
1933 /* Do not update last_vuse_ptr in vn_reference_lookup_2. */
1934 last_vuse_ptr = NULL;
1935 tree saved_vuse = vr->vuse;
1936 hashval_t saved_hashcode = vr->hashcode;
1937 void *res = vn_reference_lookup_2 (ref,
1938 gimple_vuse (def_stmt), 0, vr);
1939 /* Need to restore vr->vuse and vr->hashcode. */
1940 vr->vuse = saved_vuse;
1941 vr->hashcode = saved_hashcode;
1942 last_vuse_ptr = saved_last_vuse_ptr;
1943 if (res && res != (void *)-1)
1945 vn_reference_t vnresult = (vn_reference_t) res;
1946 if (vnresult->result
1947 && operand_equal_p (vnresult->result,
1948 gimple_assign_rhs1 (def_stmt), 0))
1949 return res;
1953 else if (gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL)
1954 && gimple_call_num_args (def_stmt) <= 4)
1956 /* For builtin calls valueize its arguments and call the
1957 alias oracle again. Valueization may improve points-to
1958 info of pointers and constify size and position arguments.
1959 Originally this was motivated by PR61034 which has
1960 conditional calls to free falsely clobbering ref because
1961 of imprecise points-to info of the argument. */
1962 tree oldargs[4];
1963 bool valueized_anything = false;
1964 for (unsigned i = 0; i < gimple_call_num_args (def_stmt); ++i)
1966 oldargs[i] = gimple_call_arg (def_stmt, i);
1967 tree val = vn_valueize (oldargs[i]);
1968 if (val != oldargs[i])
1970 gimple_call_set_arg (def_stmt, i, val);
1971 valueized_anything = true;
1974 if (valueized_anything)
1976 bool res = call_may_clobber_ref_p_1 (as_a <gcall *> (def_stmt),
1977 ref);
1978 for (unsigned i = 0; i < gimple_call_num_args (def_stmt); ++i)
1979 gimple_call_set_arg (def_stmt, i, oldargs[i]);
1980 if (!res)
1982 *disambiguate_only = true;
1983 return NULL;
1988 if (*disambiguate_only)
1989 return (void *)-1;
1991 /* If we cannot constrain the size of the reference we cannot
1992 test if anything kills it. */
1993 if (!ref->max_size_known_p ())
1994 return (void *)-1;
1996 poly_int64 offset = ref->offset;
1997 poly_int64 maxsize = ref->max_size;
1999 /* We can't deduce anything useful from clobbers. */
2000 if (gimple_clobber_p (def_stmt))
2001 return (void *)-1;
2003 /* def_stmt may-defs *ref. See if we can derive a value for *ref
2004 from that definition.
2005 1) Memset. */
2006 if (is_gimple_reg_type (vr->type)
2007 && gimple_call_builtin_p (def_stmt, BUILT_IN_MEMSET)
2008 && (integer_zerop (gimple_call_arg (def_stmt, 1))
2009 || ((TREE_CODE (gimple_call_arg (def_stmt, 1)) == INTEGER_CST
2010 || (INTEGRAL_TYPE_P (vr->type) && known_eq (ref->size, 8)))
2011 && CHAR_BIT == 8 && BITS_PER_UNIT == 8
2012 && offset.is_constant (&offseti)
2013 && offseti % BITS_PER_UNIT == 0))
2014 && poly_int_tree_p (gimple_call_arg (def_stmt, 2))
2015 && (TREE_CODE (gimple_call_arg (def_stmt, 0)) == ADDR_EXPR
2016 || TREE_CODE (gimple_call_arg (def_stmt, 0)) == SSA_NAME))
2018 tree base2;
2019 poly_int64 offset2, size2, maxsize2;
2020 bool reverse;
2021 tree ref2 = gimple_call_arg (def_stmt, 0);
2022 if (TREE_CODE (ref2) == SSA_NAME)
2024 ref2 = SSA_VAL (ref2);
2025 if (TREE_CODE (ref2) == SSA_NAME
2026 && (TREE_CODE (base) != MEM_REF
2027 || TREE_OPERAND (base, 0) != ref2))
2029 gimple *def_stmt = SSA_NAME_DEF_STMT (ref2);
2030 if (gimple_assign_single_p (def_stmt)
2031 && gimple_assign_rhs_code (def_stmt) == ADDR_EXPR)
2032 ref2 = gimple_assign_rhs1 (def_stmt);
2035 if (TREE_CODE (ref2) == ADDR_EXPR)
2037 ref2 = TREE_OPERAND (ref2, 0);
2038 base2 = get_ref_base_and_extent (ref2, &offset2, &size2, &maxsize2,
2039 &reverse);
2040 if (!known_size_p (maxsize2)
2041 || !known_eq (maxsize2, size2)
2042 || !operand_equal_p (base, base2, OEP_ADDRESS_OF))
2043 return (void *)-1;
2045 else if (TREE_CODE (ref2) == SSA_NAME)
2047 poly_int64 soff;
2048 if (TREE_CODE (base) != MEM_REF
2049 || !(mem_ref_offset (base) << LOG2_BITS_PER_UNIT).to_shwi (&soff))
2050 return (void *)-1;
2051 offset += soff;
2052 offset2 = 0;
2053 if (TREE_OPERAND (base, 0) != ref2)
2055 gimple *def = SSA_NAME_DEF_STMT (ref2);
2056 if (is_gimple_assign (def)
2057 && gimple_assign_rhs_code (def) == POINTER_PLUS_EXPR
2058 && gimple_assign_rhs1 (def) == TREE_OPERAND (base, 0)
2059 && poly_int_tree_p (gimple_assign_rhs2 (def))
2060 && (wi::to_poly_offset (gimple_assign_rhs2 (def))
2061 << LOG2_BITS_PER_UNIT).to_shwi (&offset2))
2063 ref2 = gimple_assign_rhs1 (def);
2064 if (TREE_CODE (ref2) == SSA_NAME)
2065 ref2 = SSA_VAL (ref2);
2067 else
2068 return (void *)-1;
2071 else
2072 return (void *)-1;
2073 tree len = gimple_call_arg (def_stmt, 2);
2074 if (known_subrange_p (offset, maxsize, offset2,
2075 wi::to_poly_offset (len) << LOG2_BITS_PER_UNIT))
2077 tree val;
2078 if (integer_zerop (gimple_call_arg (def_stmt, 1)))
2079 val = build_zero_cst (vr->type);
2080 else if (INTEGRAL_TYPE_P (vr->type)
2081 && known_eq (ref->size, 8))
2083 gimple_match_op res_op (gimple_match_cond::UNCOND, NOP_EXPR,
2084 vr->type, gimple_call_arg (def_stmt, 1));
2085 val = vn_nary_build_or_lookup (&res_op);
2086 if (!val
2087 || (TREE_CODE (val) == SSA_NAME
2088 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (val)))
2089 return (void *)-1;
2091 else
2093 unsigned len = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (vr->type));
2094 unsigned char *buf = XALLOCAVEC (unsigned char, len);
2095 memset (buf, TREE_INT_CST_LOW (gimple_call_arg (def_stmt, 1)),
2096 len);
2097 val = native_interpret_expr (vr->type, buf, len);
2098 if (!val)
2099 return (void *)-1;
2101 return vn_reference_lookup_or_insert_for_pieces
2102 (vuse, vr->set, vr->type, vr->operands, val);
2106 /* 2) Assignment from an empty CONSTRUCTOR. */
2107 else if (is_gimple_reg_type (vr->type)
2108 && gimple_assign_single_p (def_stmt)
2109 && gimple_assign_rhs_code (def_stmt) == CONSTRUCTOR
2110 && CONSTRUCTOR_NELTS (gimple_assign_rhs1 (def_stmt)) == 0)
2112 tree base2;
2113 poly_int64 offset2, size2, maxsize2;
2114 bool reverse;
2115 base2 = get_ref_base_and_extent (gimple_assign_lhs (def_stmt),
2116 &offset2, &size2, &maxsize2, &reverse);
2117 if (known_size_p (maxsize2)
2118 && operand_equal_p (base, base2, 0)
2119 && known_subrange_p (offset, maxsize, offset2, size2))
2121 tree val = build_zero_cst (vr->type);
2122 return vn_reference_lookup_or_insert_for_pieces
2123 (vuse, vr->set, vr->type, vr->operands, val);
2127 /* 3) Assignment from a constant. We can use folds native encode/interpret
2128 routines to extract the assigned bits. */
2129 else if (known_eq (ref->size, maxsize)
2130 && is_gimple_reg_type (vr->type)
2131 && !contains_storage_order_barrier_p (vr->operands)
2132 && gimple_assign_single_p (def_stmt)
2133 && CHAR_BIT == 8 && BITS_PER_UNIT == 8
2134 /* native_encode and native_decode operate on arrays of bytes
2135 and so fundamentally need a compile-time size and offset. */
2136 && maxsize.is_constant (&maxsizei)
2137 && maxsizei % BITS_PER_UNIT == 0
2138 && offset.is_constant (&offseti)
2139 && offseti % BITS_PER_UNIT == 0
2140 && (is_gimple_min_invariant (gimple_assign_rhs1 (def_stmt))
2141 || (TREE_CODE (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
2142 && is_gimple_min_invariant (SSA_VAL (gimple_assign_rhs1 (def_stmt))))))
2144 tree base2;
2145 HOST_WIDE_INT offset2, size2;
2146 bool reverse;
2147 base2 = get_ref_base_and_extent_hwi (gimple_assign_lhs (def_stmt),
2148 &offset2, &size2, &reverse);
2149 if (base2
2150 && !reverse
2151 && size2 % BITS_PER_UNIT == 0
2152 && offset2 % BITS_PER_UNIT == 0
2153 && operand_equal_p (base, base2, 0)
2154 && known_subrange_p (offseti, maxsizei, offset2, size2))
2156 /* We support up to 512-bit values (for V8DFmode). */
2157 unsigned char buffer[64];
2158 int len;
2160 tree rhs = gimple_assign_rhs1 (def_stmt);
2161 if (TREE_CODE (rhs) == SSA_NAME)
2162 rhs = SSA_VAL (rhs);
2163 len = native_encode_expr (gimple_assign_rhs1 (def_stmt),
2164 buffer, sizeof (buffer),
2165 (offseti - offset2) / BITS_PER_UNIT);
2166 if (len > 0 && len * BITS_PER_UNIT >= maxsizei)
2168 tree type = vr->type;
2169 /* Make sure to interpret in a type that has a range
2170 covering the whole access size. */
2171 if (INTEGRAL_TYPE_P (vr->type)
2172 && maxsizei != TYPE_PRECISION (vr->type))
2173 type = build_nonstandard_integer_type (maxsizei,
2174 TYPE_UNSIGNED (type));
2175 tree val = native_interpret_expr (type, buffer,
2176 maxsizei / BITS_PER_UNIT);
2177 /* If we chop off bits because the types precision doesn't
2178 match the memory access size this is ok when optimizing
2179 reads but not when called from the DSE code during
2180 elimination. */
2181 if (val
2182 && type != vr->type)
2184 if (! int_fits_type_p (val, vr->type))
2185 val = NULL_TREE;
2186 else
2187 val = fold_convert (vr->type, val);
2190 if (val)
2191 return vn_reference_lookup_or_insert_for_pieces
2192 (vuse, vr->set, vr->type, vr->operands, val);
2197 /* 4) Assignment from an SSA name which definition we may be able
2198 to access pieces from. */
2199 else if (known_eq (ref->size, maxsize)
2200 && is_gimple_reg_type (vr->type)
2201 && !contains_storage_order_barrier_p (vr->operands)
2202 && gimple_assign_single_p (def_stmt)
2203 && TREE_CODE (gimple_assign_rhs1 (def_stmt)) == SSA_NAME)
2205 tree base2;
2206 poly_int64 offset2, size2, maxsize2;
2207 bool reverse;
2208 base2 = get_ref_base_and_extent (gimple_assign_lhs (def_stmt),
2209 &offset2, &size2, &maxsize2,
2210 &reverse);
2211 if (!reverse
2212 && known_size_p (maxsize2)
2213 && known_eq (maxsize2, size2)
2214 && operand_equal_p (base, base2, 0)
2215 && known_subrange_p (offset, maxsize, offset2, size2)
2216 /* ??? We can't handle bitfield precision extracts without
2217 either using an alternate type for the BIT_FIELD_REF and
2218 then doing a conversion or possibly adjusting the offset
2219 according to endianness. */
2220 && (! INTEGRAL_TYPE_P (vr->type)
2221 || known_eq (ref->size, TYPE_PRECISION (vr->type)))
2222 && multiple_p (ref->size, BITS_PER_UNIT))
2224 gimple_match_op op (gimple_match_cond::UNCOND,
2225 BIT_FIELD_REF, vr->type,
2226 vn_valueize (gimple_assign_rhs1 (def_stmt)),
2227 bitsize_int (ref->size),
2228 bitsize_int (offset - offset2));
2229 tree val = vn_nary_build_or_lookup (&op);
2230 if (val
2231 && (TREE_CODE (val) != SSA_NAME
2232 || ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (val)))
2234 vn_reference_t res = vn_reference_lookup_or_insert_for_pieces
2235 (vuse, vr->set, vr->type, vr->operands, val);
2236 return res;
2241 /* 5) For aggregate copies translate the reference through them if
2242 the copy kills ref. */
2243 else if (vn_walk_kind == VN_WALKREWRITE
2244 && gimple_assign_single_p (def_stmt)
2245 && (DECL_P (gimple_assign_rhs1 (def_stmt))
2246 || TREE_CODE (gimple_assign_rhs1 (def_stmt)) == MEM_REF
2247 || handled_component_p (gimple_assign_rhs1 (def_stmt))))
2249 tree base2;
2250 int i, j, k;
2251 auto_vec<vn_reference_op_s> rhs;
2252 vn_reference_op_t vro;
2253 ao_ref r;
2255 if (!lhs_ref_ok)
2256 return (void *)-1;
2258 /* See if the assignment kills REF. */
2259 base2 = ao_ref_base (&lhs_ref);
2260 if (!lhs_ref.max_size_known_p ()
2261 || (base != base2
2262 && (TREE_CODE (base) != MEM_REF
2263 || TREE_CODE (base2) != MEM_REF
2264 || TREE_OPERAND (base, 0) != TREE_OPERAND (base2, 0)
2265 || !tree_int_cst_equal (TREE_OPERAND (base, 1),
2266 TREE_OPERAND (base2, 1))))
2267 || !stmt_kills_ref_p (def_stmt, ref))
2268 return (void *)-1;
2270 /* Find the common base of ref and the lhs. lhs_ops already
2271 contains valueized operands for the lhs. */
2272 i = vr->operands.length () - 1;
2273 j = lhs_ops.length () - 1;
2274 while (j >= 0 && i >= 0
2275 && vn_reference_op_eq (&vr->operands[i], &lhs_ops[j]))
2277 i--;
2278 j--;
2281 /* ??? The innermost op should always be a MEM_REF and we already
2282 checked that the assignment to the lhs kills vr. Thus for
2283 aggregate copies using char[] types the vn_reference_op_eq
2284 may fail when comparing types for compatibility. But we really
2285 don't care here - further lookups with the rewritten operands
2286 will simply fail if we messed up types too badly. */
2287 poly_int64 extra_off = 0;
2288 if (j == 0 && i >= 0
2289 && lhs_ops[0].opcode == MEM_REF
2290 && maybe_ne (lhs_ops[0].off, -1))
2292 if (known_eq (lhs_ops[0].off, vr->operands[i].off))
2293 i--, j--;
2294 else if (vr->operands[i].opcode == MEM_REF
2295 && maybe_ne (vr->operands[i].off, -1))
2297 extra_off = vr->operands[i].off - lhs_ops[0].off;
2298 i--, j--;
2302 /* i now points to the first additional op.
2303 ??? LHS may not be completely contained in VR, one or more
2304 VIEW_CONVERT_EXPRs could be in its way. We could at least
2305 try handling outermost VIEW_CONVERT_EXPRs. */
2306 if (j != -1)
2307 return (void *)-1;
2309 /* Punt if the additional ops contain a storage order barrier. */
2310 for (k = i; k >= 0; k--)
2312 vro = &vr->operands[k];
2313 if (vro->opcode == VIEW_CONVERT_EXPR && vro->reverse)
2314 return (void *)-1;
2317 /* Now re-write REF to be based on the rhs of the assignment. */
2318 copy_reference_ops_from_ref (gimple_assign_rhs1 (def_stmt), &rhs);
2320 /* Apply an extra offset to the inner MEM_REF of the RHS. */
2321 if (maybe_ne (extra_off, 0))
2323 if (rhs.length () < 2)
2324 return (void *)-1;
2325 int ix = rhs.length () - 2;
2326 if (rhs[ix].opcode != MEM_REF
2327 || known_eq (rhs[ix].off, -1))
2328 return (void *)-1;
2329 rhs[ix].off += extra_off;
2330 rhs[ix].op0 = int_const_binop (PLUS_EXPR, rhs[ix].op0,
2331 build_int_cst (TREE_TYPE (rhs[ix].op0),
2332 extra_off));
2335 /* We need to pre-pend vr->operands[0..i] to rhs. */
2336 vec<vn_reference_op_s> old = vr->operands;
2337 if (i + 1 + rhs.length () > vr->operands.length ())
2338 vr->operands.safe_grow (i + 1 + rhs.length ());
2339 else
2340 vr->operands.truncate (i + 1 + rhs.length ());
2341 FOR_EACH_VEC_ELT (rhs, j, vro)
2342 vr->operands[i + 1 + j] = *vro;
2343 vr->operands = valueize_refs (vr->operands);
2344 if (old == shared_lookup_references)
2345 shared_lookup_references = vr->operands;
2346 vr->hashcode = vn_reference_compute_hash (vr);
2348 /* Try folding the new reference to a constant. */
2349 tree val = fully_constant_vn_reference_p (vr);
2350 if (val)
2351 return vn_reference_lookup_or_insert_for_pieces
2352 (vuse, vr->set, vr->type, vr->operands, val);
2354 /* Adjust *ref from the new operands. */
2355 if (!ao_ref_init_from_vn_reference (&r, vr->set, vr->type, vr->operands))
2356 return (void *)-1;
2357 /* This can happen with bitfields. */
2358 if (maybe_ne (ref->size, r.size))
2359 return (void *)-1;
2360 *ref = r;
2362 /* Do not update last seen VUSE after translating. */
2363 last_vuse_ptr = NULL;
2365 /* Keep looking for the adjusted *REF / VR pair. */
2366 return NULL;
2369 /* 6) For memcpy copies translate the reference through them if
2370 the copy kills ref. */
2371 else if (vn_walk_kind == VN_WALKREWRITE
2372 && is_gimple_reg_type (vr->type)
2373 /* ??? Handle BCOPY as well. */
2374 && (gimple_call_builtin_p (def_stmt, BUILT_IN_MEMCPY)
2375 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMPCPY)
2376 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMMOVE))
2377 && (TREE_CODE (gimple_call_arg (def_stmt, 0)) == ADDR_EXPR
2378 || TREE_CODE (gimple_call_arg (def_stmt, 0)) == SSA_NAME)
2379 && (TREE_CODE (gimple_call_arg (def_stmt, 1)) == ADDR_EXPR
2380 || TREE_CODE (gimple_call_arg (def_stmt, 1)) == SSA_NAME)
2381 && poly_int_tree_p (gimple_call_arg (def_stmt, 2), &copy_size))
2383 tree lhs, rhs;
2384 ao_ref r;
2385 poly_int64 rhs_offset, lhs_offset;
2386 vn_reference_op_s op;
2387 poly_uint64 mem_offset;
2388 poly_int64 at, byte_maxsize;
2390 /* Only handle non-variable, addressable refs. */
2391 if (maybe_ne (ref->size, maxsize)
2392 || !multiple_p (offset, BITS_PER_UNIT, &at)
2393 || !multiple_p (maxsize, BITS_PER_UNIT, &byte_maxsize))
2394 return (void *)-1;
2396 /* Extract a pointer base and an offset for the destination. */
2397 lhs = gimple_call_arg (def_stmt, 0);
2398 lhs_offset = 0;
2399 if (TREE_CODE (lhs) == SSA_NAME)
2401 lhs = vn_valueize (lhs);
2402 if (TREE_CODE (lhs) == SSA_NAME)
2404 gimple *def_stmt = SSA_NAME_DEF_STMT (lhs);
2405 if (gimple_assign_single_p (def_stmt)
2406 && gimple_assign_rhs_code (def_stmt) == ADDR_EXPR)
2407 lhs = gimple_assign_rhs1 (def_stmt);
2410 if (TREE_CODE (lhs) == ADDR_EXPR)
2412 tree tem = get_addr_base_and_unit_offset (TREE_OPERAND (lhs, 0),
2413 &lhs_offset);
2414 if (!tem)
2415 return (void *)-1;
2416 if (TREE_CODE (tem) == MEM_REF
2417 && poly_int_tree_p (TREE_OPERAND (tem, 1), &mem_offset))
2419 lhs = TREE_OPERAND (tem, 0);
2420 if (TREE_CODE (lhs) == SSA_NAME)
2421 lhs = vn_valueize (lhs);
2422 lhs_offset += mem_offset;
2424 else if (DECL_P (tem))
2425 lhs = build_fold_addr_expr (tem);
2426 else
2427 return (void *)-1;
2429 if (TREE_CODE (lhs) != SSA_NAME
2430 && TREE_CODE (lhs) != ADDR_EXPR)
2431 return (void *)-1;
2433 /* Extract a pointer base and an offset for the source. */
2434 rhs = gimple_call_arg (def_stmt, 1);
2435 rhs_offset = 0;
2436 if (TREE_CODE (rhs) == SSA_NAME)
2437 rhs = vn_valueize (rhs);
2438 if (TREE_CODE (rhs) == ADDR_EXPR)
2440 tree tem = get_addr_base_and_unit_offset (TREE_OPERAND (rhs, 0),
2441 &rhs_offset);
2442 if (!tem)
2443 return (void *)-1;
2444 if (TREE_CODE (tem) == MEM_REF
2445 && poly_int_tree_p (TREE_OPERAND (tem, 1), &mem_offset))
2447 rhs = TREE_OPERAND (tem, 0);
2448 rhs_offset += mem_offset;
2450 else if (DECL_P (tem)
2451 || TREE_CODE (tem) == STRING_CST)
2452 rhs = build_fold_addr_expr (tem);
2453 else
2454 return (void *)-1;
2456 if (TREE_CODE (rhs) != SSA_NAME
2457 && TREE_CODE (rhs) != ADDR_EXPR)
2458 return (void *)-1;
2460 /* The bases of the destination and the references have to agree. */
2461 if (TREE_CODE (base) == MEM_REF)
2463 if (TREE_OPERAND (base, 0) != lhs
2464 || !poly_int_tree_p (TREE_OPERAND (base, 1), &mem_offset))
2465 return (void *) -1;
2466 at += mem_offset;
2468 else if (!DECL_P (base)
2469 || TREE_CODE (lhs) != ADDR_EXPR
2470 || TREE_OPERAND (lhs, 0) != base)
2471 return (void *)-1;
2473 /* If the access is completely outside of the memcpy destination
2474 area there is no aliasing. */
2475 if (!ranges_maybe_overlap_p (lhs_offset, copy_size, at, byte_maxsize))
2476 return NULL;
2477 /* And the access has to be contained within the memcpy destination. */
2478 if (!known_subrange_p (at, byte_maxsize, lhs_offset, copy_size))
2479 return (void *)-1;
2481 /* Make room for 2 operands in the new reference. */
2482 if (vr->operands.length () < 2)
2484 vec<vn_reference_op_s> old = vr->operands;
2485 vr->operands.safe_grow_cleared (2);
2486 if (old == shared_lookup_references)
2487 shared_lookup_references = vr->operands;
2489 else
2490 vr->operands.truncate (2);
2492 /* The looked-through reference is a simple MEM_REF. */
2493 memset (&op, 0, sizeof (op));
2494 op.type = vr->type;
2495 op.opcode = MEM_REF;
2496 op.op0 = build_int_cst (ptr_type_node, at - lhs_offset + rhs_offset);
2497 op.off = at - lhs_offset + rhs_offset;
2498 vr->operands[0] = op;
2499 op.type = TREE_TYPE (rhs);
2500 op.opcode = TREE_CODE (rhs);
2501 op.op0 = rhs;
2502 op.off = -1;
2503 vr->operands[1] = op;
2504 vr->hashcode = vn_reference_compute_hash (vr);
2506 /* Try folding the new reference to a constant. */
2507 tree val = fully_constant_vn_reference_p (vr);
2508 if (val)
2509 return vn_reference_lookup_or_insert_for_pieces
2510 (vuse, vr->set, vr->type, vr->operands, val);
2512 /* Adjust *ref from the new operands. */
2513 if (!ao_ref_init_from_vn_reference (&r, vr->set, vr->type, vr->operands))
2514 return (void *)-1;
2515 /* This can happen with bitfields. */
2516 if (maybe_ne (ref->size, r.size))
2517 return (void *)-1;
2518 *ref = r;
2520 /* Do not update last seen VUSE after translating. */
2521 last_vuse_ptr = NULL;
2523 /* Keep looking for the adjusted *REF / VR pair. */
2524 return NULL;
2527 /* Bail out and stop walking. */
2528 return (void *)-1;
2531 /* Return a reference op vector from OP that can be used for
2532 vn_reference_lookup_pieces. The caller is responsible for releasing
2533 the vector. */
2535 vec<vn_reference_op_s>
2536 vn_reference_operands_for_lookup (tree op)
2538 bool valueized;
2539 return valueize_shared_reference_ops_from_ref (op, &valueized).copy ();
2542 /* Lookup a reference operation by it's parts, in the current hash table.
2543 Returns the resulting value number if it exists in the hash table,
2544 NULL_TREE otherwise. VNRESULT will be filled in with the actual
2545 vn_reference_t stored in the hashtable if something is found. */
2547 tree
2548 vn_reference_lookup_pieces (tree vuse, alias_set_type set, tree type,
2549 vec<vn_reference_op_s> operands,
2550 vn_reference_t *vnresult, vn_lookup_kind kind)
2552 struct vn_reference_s vr1;
2553 vn_reference_t tmp;
2554 tree cst;
2556 if (!vnresult)
2557 vnresult = &tmp;
2558 *vnresult = NULL;
2560 vr1.vuse = vuse_ssa_val (vuse);
2561 shared_lookup_references.truncate (0);
2562 shared_lookup_references.safe_grow (operands.length ());
2563 memcpy (shared_lookup_references.address (),
2564 operands.address (),
2565 sizeof (vn_reference_op_s)
2566 * operands.length ());
2567 vr1.operands = operands = shared_lookup_references
2568 = valueize_refs (shared_lookup_references);
2569 vr1.type = type;
2570 vr1.set = set;
2571 vr1.hashcode = vn_reference_compute_hash (&vr1);
2572 if ((cst = fully_constant_vn_reference_p (&vr1)))
2573 return cst;
2575 vn_reference_lookup_1 (&vr1, vnresult);
2576 if (!*vnresult
2577 && kind != VN_NOWALK
2578 && vr1.vuse)
2580 ao_ref r;
2581 vn_walk_kind = kind;
2582 if (ao_ref_init_from_vn_reference (&r, set, type, vr1.operands))
2583 *vnresult =
2584 (vn_reference_t)walk_non_aliased_vuses (&r, vr1.vuse,
2585 vn_reference_lookup_2,
2586 vn_reference_lookup_3,
2587 vuse_valueize, &vr1);
2588 gcc_checking_assert (vr1.operands == shared_lookup_references);
2591 if (*vnresult)
2592 return (*vnresult)->result;
2594 return NULL_TREE;
2597 /* Lookup OP in the current hash table, and return the resulting value
2598 number if it exists in the hash table. Return NULL_TREE if it does
2599 not exist in the hash table or if the result field of the structure
2600 was NULL.. VNRESULT will be filled in with the vn_reference_t
2601 stored in the hashtable if one exists. When TBAA_P is false assume
2602 we are looking up a store and treat it as having alias-set zero. */
2604 tree
2605 vn_reference_lookup (tree op, tree vuse, vn_lookup_kind kind,
2606 vn_reference_t *vnresult, bool tbaa_p)
2608 vec<vn_reference_op_s> operands;
2609 struct vn_reference_s vr1;
2610 tree cst;
2611 bool valuezied_anything;
2613 if (vnresult)
2614 *vnresult = NULL;
2616 vr1.vuse = vuse_ssa_val (vuse);
2617 vr1.operands = operands
2618 = valueize_shared_reference_ops_from_ref (op, &valuezied_anything);
2619 vr1.type = TREE_TYPE (op);
2620 vr1.set = tbaa_p ? get_alias_set (op) : 0;
2621 vr1.hashcode = vn_reference_compute_hash (&vr1);
2622 if ((cst = fully_constant_vn_reference_p (&vr1)))
2623 return cst;
2625 if (kind != VN_NOWALK
2626 && vr1.vuse)
2628 vn_reference_t wvnresult;
2629 ao_ref r;
2630 /* Make sure to use a valueized reference if we valueized anything.
2631 Otherwise preserve the full reference for advanced TBAA. */
2632 if (!valuezied_anything
2633 || !ao_ref_init_from_vn_reference (&r, vr1.set, vr1.type,
2634 vr1.operands))
2635 ao_ref_init (&r, op);
2636 if (! tbaa_p)
2637 r.ref_alias_set = r.base_alias_set = 0;
2638 vn_walk_kind = kind;
2639 wvnresult =
2640 (vn_reference_t)walk_non_aliased_vuses (&r, vr1.vuse,
2641 vn_reference_lookup_2,
2642 vn_reference_lookup_3,
2643 vuse_valueize, &vr1);
2644 gcc_checking_assert (vr1.operands == shared_lookup_references);
2645 if (wvnresult)
2647 if (vnresult)
2648 *vnresult = wvnresult;
2649 return wvnresult->result;
2652 return NULL_TREE;
2655 return vn_reference_lookup_1 (&vr1, vnresult);
2658 /* Lookup CALL in the current hash table and return the entry in
2659 *VNRESULT if found. Populates *VR for the hashtable lookup. */
2661 void
2662 vn_reference_lookup_call (gcall *call, vn_reference_t *vnresult,
2663 vn_reference_t vr)
2665 if (vnresult)
2666 *vnresult = NULL;
2668 tree vuse = gimple_vuse (call);
2670 vr->vuse = vuse ? SSA_VAL (vuse) : NULL_TREE;
2671 vr->operands = valueize_shared_reference_ops_from_call (call);
2672 vr->type = gimple_expr_type (call);
2673 vr->set = 0;
2674 vr->hashcode = vn_reference_compute_hash (vr);
2675 vn_reference_lookup_1 (vr, vnresult);
2678 /* Insert OP into the current hash table with a value number of RESULT. */
2680 static void
2681 vn_reference_insert (tree op, tree result, tree vuse, tree vdef)
2683 vn_reference_s **slot;
2684 vn_reference_t vr1;
2685 bool tem;
2687 vr1 = XOBNEW (&vn_tables_obstack, vn_reference_s);
2688 if (TREE_CODE (result) == SSA_NAME)
2689 vr1->value_id = VN_INFO (result)->value_id;
2690 else
2691 vr1->value_id = get_or_alloc_constant_value_id (result);
2692 vr1->vuse = vuse_ssa_val (vuse);
2693 vr1->operands = valueize_shared_reference_ops_from_ref (op, &tem).copy ();
2694 vr1->type = TREE_TYPE (op);
2695 vr1->set = get_alias_set (op);
2696 vr1->hashcode = vn_reference_compute_hash (vr1);
2697 vr1->result = TREE_CODE (result) == SSA_NAME ? SSA_VAL (result) : result;
2698 vr1->result_vdef = vdef;
2700 slot = valid_info->references->find_slot_with_hash (vr1, vr1->hashcode,
2701 INSERT);
2703 /* Because IL walking on reference lookup can end up visiting
2704 a def that is only to be visited later in iteration order
2705 when we are about to make an irreducible region reducible
2706 the def can be effectively processed and its ref being inserted
2707 by vn_reference_lookup_3 already. So we cannot assert (!*slot)
2708 but save a lookup if we deal with already inserted refs here. */
2709 if (*slot)
2711 /* We cannot assert that we have the same value either because
2712 when disentangling an irreducible region we may end up visiting
2713 a use before the corresponding def. That's a missed optimization
2714 only though. See gcc.dg/tree-ssa/pr87126.c for example. */
2715 if (dump_file && (dump_flags & TDF_DETAILS)
2716 && !operand_equal_p ((*slot)->result, vr1->result, 0))
2718 fprintf (dump_file, "Keeping old value ");
2719 print_generic_expr (dump_file, (*slot)->result);
2720 fprintf (dump_file, " because of collision\n");
2722 free_reference (vr1);
2723 obstack_free (&vn_tables_obstack, vr1);
2724 return;
2727 *slot = vr1;
2728 vr1->next = last_inserted_ref;
2729 last_inserted_ref = vr1;
2732 /* Insert a reference by it's pieces into the current hash table with
2733 a value number of RESULT. Return the resulting reference
2734 structure we created. */
2736 vn_reference_t
2737 vn_reference_insert_pieces (tree vuse, alias_set_type set, tree type,
2738 vec<vn_reference_op_s> operands,
2739 tree result, unsigned int value_id)
2742 vn_reference_s **slot;
2743 vn_reference_t vr1;
2745 vr1 = XOBNEW (&vn_tables_obstack, vn_reference_s);
2746 vr1->value_id = value_id;
2747 vr1->vuse = vuse_ssa_val (vuse);
2748 vr1->operands = valueize_refs (operands);
2749 vr1->type = type;
2750 vr1->set = set;
2751 vr1->hashcode = vn_reference_compute_hash (vr1);
2752 if (result && TREE_CODE (result) == SSA_NAME)
2753 result = SSA_VAL (result);
2754 vr1->result = result;
2756 slot = valid_info->references->find_slot_with_hash (vr1, vr1->hashcode,
2757 INSERT);
2759 /* At this point we should have all the things inserted that we have
2760 seen before, and we should never try inserting something that
2761 already exists. */
2762 gcc_assert (!*slot);
2764 *slot = vr1;
2765 vr1->next = last_inserted_ref;
2766 last_inserted_ref = vr1;
2767 return vr1;
2770 /* Compute and return the hash value for nary operation VBO1. */
2772 static hashval_t
2773 vn_nary_op_compute_hash (const vn_nary_op_t vno1)
2775 inchash::hash hstate;
2776 unsigned i;
2778 for (i = 0; i < vno1->length; ++i)
2779 if (TREE_CODE (vno1->op[i]) == SSA_NAME)
2780 vno1->op[i] = SSA_VAL (vno1->op[i]);
2782 if (((vno1->length == 2
2783 && commutative_tree_code (vno1->opcode))
2784 || (vno1->length == 3
2785 && commutative_ternary_tree_code (vno1->opcode)))
2786 && tree_swap_operands_p (vno1->op[0], vno1->op[1]))
2787 std::swap (vno1->op[0], vno1->op[1]);
2788 else if (TREE_CODE_CLASS (vno1->opcode) == tcc_comparison
2789 && tree_swap_operands_p (vno1->op[0], vno1->op[1]))
2791 std::swap (vno1->op[0], vno1->op[1]);
2792 vno1->opcode = swap_tree_comparison (vno1->opcode);
2795 hstate.add_int (vno1->opcode);
2796 for (i = 0; i < vno1->length; ++i)
2797 inchash::add_expr (vno1->op[i], hstate);
2799 return hstate.end ();
2802 /* Compare nary operations VNO1 and VNO2 and return true if they are
2803 equivalent. */
2805 bool
2806 vn_nary_op_eq (const_vn_nary_op_t const vno1, const_vn_nary_op_t const vno2)
2808 unsigned i;
2810 if (vno1->hashcode != vno2->hashcode)
2811 return false;
2813 if (vno1->length != vno2->length)
2814 return false;
2816 if (vno1->opcode != vno2->opcode
2817 || !types_compatible_p (vno1->type, vno2->type))
2818 return false;
2820 for (i = 0; i < vno1->length; ++i)
2821 if (!expressions_equal_p (vno1->op[i], vno2->op[i]))
2822 return false;
2824 /* BIT_INSERT_EXPR has an implict operand as the type precision
2825 of op1. Need to check to make sure they are the same. */
2826 if (vno1->opcode == BIT_INSERT_EXPR
2827 && TREE_CODE (vno1->op[1]) == INTEGER_CST
2828 && TYPE_PRECISION (TREE_TYPE (vno1->op[1]))
2829 != TYPE_PRECISION (TREE_TYPE (vno2->op[1])))
2830 return false;
2832 return true;
2835 /* Initialize VNO from the pieces provided. */
2837 static void
2838 init_vn_nary_op_from_pieces (vn_nary_op_t vno, unsigned int length,
2839 enum tree_code code, tree type, tree *ops)
2841 vno->opcode = code;
2842 vno->length = length;
2843 vno->type = type;
2844 memcpy (&vno->op[0], ops, sizeof (tree) * length);
2847 /* Initialize VNO from OP. */
2849 static void
2850 init_vn_nary_op_from_op (vn_nary_op_t vno, tree op)
2852 unsigned i;
2854 vno->opcode = TREE_CODE (op);
2855 vno->length = TREE_CODE_LENGTH (TREE_CODE (op));
2856 vno->type = TREE_TYPE (op);
2857 for (i = 0; i < vno->length; ++i)
2858 vno->op[i] = TREE_OPERAND (op, i);
2861 /* Return the number of operands for a vn_nary ops structure from STMT. */
2863 static unsigned int
2864 vn_nary_length_from_stmt (gimple *stmt)
2866 switch (gimple_assign_rhs_code (stmt))
2868 case REALPART_EXPR:
2869 case IMAGPART_EXPR:
2870 case VIEW_CONVERT_EXPR:
2871 return 1;
2873 case BIT_FIELD_REF:
2874 return 3;
2876 case CONSTRUCTOR:
2877 return CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt));
2879 default:
2880 return gimple_num_ops (stmt) - 1;
2884 /* Initialize VNO from STMT. */
2886 static void
2887 init_vn_nary_op_from_stmt (vn_nary_op_t vno, gimple *stmt)
2889 unsigned i;
2891 vno->opcode = gimple_assign_rhs_code (stmt);
2892 vno->type = gimple_expr_type (stmt);
2893 switch (vno->opcode)
2895 case REALPART_EXPR:
2896 case IMAGPART_EXPR:
2897 case VIEW_CONVERT_EXPR:
2898 vno->length = 1;
2899 vno->op[0] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 0);
2900 break;
2902 case BIT_FIELD_REF:
2903 vno->length = 3;
2904 vno->op[0] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 0);
2905 vno->op[1] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 1);
2906 vno->op[2] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 2);
2907 break;
2909 case CONSTRUCTOR:
2910 vno->length = CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt));
2911 for (i = 0; i < vno->length; ++i)
2912 vno->op[i] = CONSTRUCTOR_ELT (gimple_assign_rhs1 (stmt), i)->value;
2913 break;
2915 default:
2916 gcc_checking_assert (!gimple_assign_single_p (stmt));
2917 vno->length = gimple_num_ops (stmt) - 1;
2918 for (i = 0; i < vno->length; ++i)
2919 vno->op[i] = gimple_op (stmt, i + 1);
2923 /* Compute the hashcode for VNO and look for it in the hash table;
2924 return the resulting value number if it exists in the hash table.
2925 Return NULL_TREE if it does not exist in the hash table or if the
2926 result field of the operation is NULL. VNRESULT will contain the
2927 vn_nary_op_t from the hashtable if it exists. */
2929 static tree
2930 vn_nary_op_lookup_1 (vn_nary_op_t vno, vn_nary_op_t *vnresult)
2932 vn_nary_op_s **slot;
2934 if (vnresult)
2935 *vnresult = NULL;
2937 vno->hashcode = vn_nary_op_compute_hash (vno);
2938 slot = valid_info->nary->find_slot_with_hash (vno, vno->hashcode, NO_INSERT);
2939 if (!slot)
2940 return NULL_TREE;
2941 if (vnresult)
2942 *vnresult = *slot;
2943 return (*slot)->predicated_values ? NULL_TREE : (*slot)->u.result;
2946 /* Lookup a n-ary operation by its pieces and return the resulting value
2947 number if it exists in the hash table. Return NULL_TREE if it does
2948 not exist in the hash table or if the result field of the operation
2949 is NULL. VNRESULT will contain the vn_nary_op_t from the hashtable
2950 if it exists. */
2952 tree
2953 vn_nary_op_lookup_pieces (unsigned int length, enum tree_code code,
2954 tree type, tree *ops, vn_nary_op_t *vnresult)
2956 vn_nary_op_t vno1 = XALLOCAVAR (struct vn_nary_op_s,
2957 sizeof_vn_nary_op (length));
2958 init_vn_nary_op_from_pieces (vno1, length, code, type, ops);
2959 return vn_nary_op_lookup_1 (vno1, vnresult);
2962 /* Lookup OP in the current hash table, and return the resulting value
2963 number if it exists in the hash table. Return NULL_TREE if it does
2964 not exist in the hash table or if the result field of the operation
2965 is NULL. VNRESULT will contain the vn_nary_op_t from the hashtable
2966 if it exists. */
2968 tree
2969 vn_nary_op_lookup (tree op, vn_nary_op_t *vnresult)
2971 vn_nary_op_t vno1
2972 = XALLOCAVAR (struct vn_nary_op_s,
2973 sizeof_vn_nary_op (TREE_CODE_LENGTH (TREE_CODE (op))));
2974 init_vn_nary_op_from_op (vno1, op);
2975 return vn_nary_op_lookup_1 (vno1, vnresult);
2978 /* Lookup the rhs of STMT in the current hash table, and return the resulting
2979 value number if it exists in the hash table. Return NULL_TREE if
2980 it does not exist in the hash table. VNRESULT will contain the
2981 vn_nary_op_t from the hashtable if it exists. */
2983 tree
2984 vn_nary_op_lookup_stmt (gimple *stmt, vn_nary_op_t *vnresult)
2986 vn_nary_op_t vno1
2987 = XALLOCAVAR (struct vn_nary_op_s,
2988 sizeof_vn_nary_op (vn_nary_length_from_stmt (stmt)));
2989 init_vn_nary_op_from_stmt (vno1, stmt);
2990 return vn_nary_op_lookup_1 (vno1, vnresult);
2993 /* Allocate a vn_nary_op_t with LENGTH operands on STACK. */
2995 static vn_nary_op_t
2996 alloc_vn_nary_op_noinit (unsigned int length, struct obstack *stack)
2998 return (vn_nary_op_t) obstack_alloc (stack, sizeof_vn_nary_op (length));
3001 /* Allocate and initialize a vn_nary_op_t on CURRENT_INFO's
3002 obstack. */
3004 static vn_nary_op_t
3005 alloc_vn_nary_op (unsigned int length, tree result, unsigned int value_id)
3007 vn_nary_op_t vno1 = alloc_vn_nary_op_noinit (length, &vn_tables_obstack);
3009 vno1->value_id = value_id;
3010 vno1->length = length;
3011 vno1->predicated_values = 0;
3012 vno1->u.result = result;
3014 return vno1;
3017 /* Insert VNO into TABLE. If COMPUTE_HASH is true, then compute
3018 VNO->HASHCODE first. */
3020 static vn_nary_op_t
3021 vn_nary_op_insert_into (vn_nary_op_t vno, vn_nary_op_table_type *table,
3022 bool compute_hash)
3024 vn_nary_op_s **slot;
3026 if (compute_hash)
3028 vno->hashcode = vn_nary_op_compute_hash (vno);
3029 gcc_assert (! vno->predicated_values
3030 || (! vno->u.values->next
3031 && vno->u.values->n == 1));
3034 slot = table->find_slot_with_hash (vno, vno->hashcode, INSERT);
3035 vno->unwind_to = *slot;
3036 if (*slot)
3038 /* Prefer non-predicated values.
3039 ??? Only if those are constant, otherwise, with constant predicated
3040 value, turn them into predicated values with entry-block validity
3041 (??? but we always find the first valid result currently). */
3042 if ((*slot)->predicated_values
3043 && ! vno->predicated_values)
3045 /* ??? We cannot remove *slot from the unwind stack list.
3046 For the moment we deal with this by skipping not found
3047 entries but this isn't ideal ... */
3048 *slot = vno;
3049 /* ??? Maintain a stack of states we can unwind in
3050 vn_nary_op_s? But how far do we unwind? In reality
3051 we need to push change records somewhere... Or not
3052 unwind vn_nary_op_s and linking them but instead
3053 unwind the results "list", linking that, which also
3054 doesn't move on hashtable resize. */
3055 /* We can also have a ->unwind_to recording *slot there.
3056 That way we can make u.values a fixed size array with
3057 recording the number of entries but of course we then
3058 have always N copies for each unwind_to-state. Or we
3059 make sure to only ever append and each unwinding will
3060 pop off one entry (but how to deal with predicated
3061 replaced with non-predicated here?) */
3062 vno->next = last_inserted_nary;
3063 last_inserted_nary = vno;
3064 return vno;
3066 else if (vno->predicated_values
3067 && ! (*slot)->predicated_values)
3068 return *slot;
3069 else if (vno->predicated_values
3070 && (*slot)->predicated_values)
3072 /* ??? Factor this all into a insert_single_predicated_value
3073 routine. */
3074 gcc_assert (!vno->u.values->next && vno->u.values->n == 1);
3075 basic_block vno_bb
3076 = BASIC_BLOCK_FOR_FN (cfun, vno->u.values->valid_dominated_by_p[0]);
3077 vn_pval *nval = vno->u.values;
3078 vn_pval **next = &vno->u.values;
3079 bool found = false;
3080 for (vn_pval *val = (*slot)->u.values; val; val = val->next)
3082 if (expressions_equal_p (val->result, vno->u.values->result))
3084 found = true;
3085 for (unsigned i = 0; i < val->n; ++i)
3087 basic_block val_bb
3088 = BASIC_BLOCK_FOR_FN (cfun,
3089 val->valid_dominated_by_p[i]);
3090 if (dominated_by_p (CDI_DOMINATORS, vno_bb, val_bb))
3091 /* Value registered with more generic predicate. */
3092 return *slot;
3093 else if (dominated_by_p (CDI_DOMINATORS, val_bb, vno_bb))
3094 /* Shouldn't happen, we insert in RPO order. */
3095 gcc_unreachable ();
3097 /* Append value. */
3098 *next = (vn_pval *) obstack_alloc (&vn_tables_obstack,
3099 sizeof (vn_pval)
3100 + val->n * sizeof (int));
3101 (*next)->next = NULL;
3102 (*next)->result = val->result;
3103 (*next)->n = val->n + 1;
3104 memcpy ((*next)->valid_dominated_by_p,
3105 val->valid_dominated_by_p,
3106 val->n * sizeof (int));
3107 (*next)->valid_dominated_by_p[val->n] = vno_bb->index;
3108 next = &(*next)->next;
3109 if (dump_file && (dump_flags & TDF_DETAILS))
3110 fprintf (dump_file, "Appending predicate to value.\n");
3111 continue;
3113 /* Copy other predicated values. */
3114 *next = (vn_pval *) obstack_alloc (&vn_tables_obstack,
3115 sizeof (vn_pval)
3116 + (val->n-1) * sizeof (int));
3117 memcpy (*next, val, sizeof (vn_pval) + (val->n-1) * sizeof (int));
3118 (*next)->next = NULL;
3119 next = &(*next)->next;
3121 if (!found)
3122 *next = nval;
3124 *slot = vno;
3125 vno->next = last_inserted_nary;
3126 last_inserted_nary = vno;
3127 return vno;
3130 /* While we do not want to insert things twice it's awkward to
3131 avoid it in the case where visit_nary_op pattern-matches stuff
3132 and ends up simplifying the replacement to itself. We then
3133 get two inserts, one from visit_nary_op and one from
3134 vn_nary_build_or_lookup.
3135 So allow inserts with the same value number. */
3136 if ((*slot)->u.result == vno->u.result)
3137 return *slot;
3140 /* ??? There's also optimistic vs. previous commited state merging
3141 that is problematic for the case of unwinding. */
3143 /* ??? We should return NULL if we do not use 'vno' and have the
3144 caller release it. */
3145 gcc_assert (!*slot);
3147 *slot = vno;
3148 vno->next = last_inserted_nary;
3149 last_inserted_nary = vno;
3150 return vno;
3153 /* Insert a n-ary operation into the current hash table using it's
3154 pieces. Return the vn_nary_op_t structure we created and put in
3155 the hashtable. */
3157 vn_nary_op_t
3158 vn_nary_op_insert_pieces (unsigned int length, enum tree_code code,
3159 tree type, tree *ops,
3160 tree result, unsigned int value_id)
3162 vn_nary_op_t vno1 = alloc_vn_nary_op (length, result, value_id);
3163 init_vn_nary_op_from_pieces (vno1, length, code, type, ops);
3164 return vn_nary_op_insert_into (vno1, valid_info->nary, true);
3167 static vn_nary_op_t
3168 vn_nary_op_insert_pieces_predicated (unsigned int length, enum tree_code code,
3169 tree type, tree *ops,
3170 tree result, unsigned int value_id,
3171 edge pred_e)
3173 /* ??? Currently tracking BBs. */
3174 if (! single_pred_p (pred_e->dest))
3176 /* Never record for backedges. */
3177 if (pred_e->flags & EDGE_DFS_BACK)
3178 return NULL;
3179 edge_iterator ei;
3180 edge e;
3181 int cnt = 0;
3182 /* Ignore backedges. */
3183 FOR_EACH_EDGE (e, ei, pred_e->dest->preds)
3184 if (! dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
3185 cnt++;
3186 if (cnt != 1)
3187 return NULL;
3189 if (dump_file && (dump_flags & TDF_DETAILS)
3190 /* ??? Fix dumping, but currently we only get comparisons. */
3191 && TREE_CODE_CLASS (code) == tcc_comparison)
3193 fprintf (dump_file, "Recording on edge %d->%d ", pred_e->src->index,
3194 pred_e->dest->index);
3195 print_generic_expr (dump_file, ops[0], TDF_SLIM);
3196 fprintf (dump_file, " %s ", get_tree_code_name (code));
3197 print_generic_expr (dump_file, ops[1], TDF_SLIM);
3198 fprintf (dump_file, " == %s\n",
3199 integer_zerop (result) ? "false" : "true");
3201 vn_nary_op_t vno1 = alloc_vn_nary_op (length, NULL_TREE, value_id);
3202 init_vn_nary_op_from_pieces (vno1, length, code, type, ops);
3203 vno1->predicated_values = 1;
3204 vno1->u.values = (vn_pval *) obstack_alloc (&vn_tables_obstack,
3205 sizeof (vn_pval));
3206 vno1->u.values->next = NULL;
3207 vno1->u.values->result = result;
3208 vno1->u.values->n = 1;
3209 vno1->u.values->valid_dominated_by_p[0] = pred_e->dest->index;
3210 return vn_nary_op_insert_into (vno1, valid_info->nary, true);
3213 static bool
3214 dominated_by_p_w_unex (basic_block bb1, basic_block bb2);
3216 static tree
3217 vn_nary_op_get_predicated_value (vn_nary_op_t vno, basic_block bb)
3219 if (! vno->predicated_values)
3220 return vno->u.result;
3221 for (vn_pval *val = vno->u.values; val; val = val->next)
3222 for (unsigned i = 0; i < val->n; ++i)
3223 if (dominated_by_p_w_unex (bb,
3224 BASIC_BLOCK_FOR_FN
3225 (cfun, val->valid_dominated_by_p[i])))
3226 return val->result;
3227 return NULL_TREE;
3230 /* Insert OP into the current hash table with a value number of
3231 RESULT. Return the vn_nary_op_t structure we created and put in
3232 the hashtable. */
3234 vn_nary_op_t
3235 vn_nary_op_insert (tree op, tree result)
3237 unsigned length = TREE_CODE_LENGTH (TREE_CODE (op));
3238 vn_nary_op_t vno1;
3240 vno1 = alloc_vn_nary_op (length, result, VN_INFO (result)->value_id);
3241 init_vn_nary_op_from_op (vno1, op);
3242 return vn_nary_op_insert_into (vno1, valid_info->nary, true);
3245 /* Insert the rhs of STMT into the current hash table with a value number of
3246 RESULT. */
3248 static vn_nary_op_t
3249 vn_nary_op_insert_stmt (gimple *stmt, tree result)
3251 vn_nary_op_t vno1
3252 = alloc_vn_nary_op (vn_nary_length_from_stmt (stmt),
3253 result, VN_INFO (result)->value_id);
3254 init_vn_nary_op_from_stmt (vno1, stmt);
3255 return vn_nary_op_insert_into (vno1, valid_info->nary, true);
3258 /* Compute a hashcode for PHI operation VP1 and return it. */
3260 static inline hashval_t
3261 vn_phi_compute_hash (vn_phi_t vp1)
3263 inchash::hash hstate (EDGE_COUNT (vp1->block->preds) > 2
3264 ? vp1->block->index : EDGE_COUNT (vp1->block->preds));
3265 tree phi1op;
3266 tree type;
3267 edge e;
3268 edge_iterator ei;
3270 /* If all PHI arguments are constants we need to distinguish
3271 the PHI node via its type. */
3272 type = vp1->type;
3273 hstate.merge_hash (vn_hash_type (type));
3275 FOR_EACH_EDGE (e, ei, vp1->block->preds)
3277 /* Don't hash backedge values they need to be handled as VN_TOP
3278 for optimistic value-numbering. */
3279 if (e->flags & EDGE_DFS_BACK)
3280 continue;
3282 phi1op = vp1->phiargs[e->dest_idx];
3283 if (phi1op == VN_TOP)
3284 continue;
3285 inchash::add_expr (phi1op, hstate);
3288 return hstate.end ();
3292 /* Return true if COND1 and COND2 represent the same condition, set
3293 *INVERTED_P if one needs to be inverted to make it the same as
3294 the other. */
3296 static bool
3297 cond_stmts_equal_p (gcond *cond1, tree lhs1, tree rhs1,
3298 gcond *cond2, tree lhs2, tree rhs2, bool *inverted_p)
3300 enum tree_code code1 = gimple_cond_code (cond1);
3301 enum tree_code code2 = gimple_cond_code (cond2);
3303 *inverted_p = false;
3304 if (code1 == code2)
3306 else if (code1 == swap_tree_comparison (code2))
3307 std::swap (lhs2, rhs2);
3308 else if (code1 == invert_tree_comparison (code2, HONOR_NANS (lhs2)))
3309 *inverted_p = true;
3310 else if (code1 == invert_tree_comparison
3311 (swap_tree_comparison (code2), HONOR_NANS (lhs2)))
3313 std::swap (lhs2, rhs2);
3314 *inverted_p = true;
3316 else
3317 return false;
3319 return ((expressions_equal_p (lhs1, lhs2)
3320 && expressions_equal_p (rhs1, rhs2))
3321 || (commutative_tree_code (code1)
3322 && expressions_equal_p (lhs1, rhs2)
3323 && expressions_equal_p (rhs1, lhs2)));
3326 /* Compare two phi entries for equality, ignoring VN_TOP arguments. */
3328 static int
3329 vn_phi_eq (const_vn_phi_t const vp1, const_vn_phi_t const vp2)
3331 if (vp1->hashcode != vp2->hashcode)
3332 return false;
3334 if (vp1->block != vp2->block)
3336 if (EDGE_COUNT (vp1->block->preds) != EDGE_COUNT (vp2->block->preds))
3337 return false;
3339 switch (EDGE_COUNT (vp1->block->preds))
3341 case 1:
3342 /* Single-arg PHIs are just copies. */
3343 break;
3345 case 2:
3347 /* Rule out backedges into the PHI. */
3348 if (vp1->block->loop_father->header == vp1->block
3349 || vp2->block->loop_father->header == vp2->block)
3350 return false;
3352 /* If the PHI nodes do not have compatible types
3353 they are not the same. */
3354 if (!types_compatible_p (vp1->type, vp2->type))
3355 return false;
3357 basic_block idom1
3358 = get_immediate_dominator (CDI_DOMINATORS, vp1->block);
3359 basic_block idom2
3360 = get_immediate_dominator (CDI_DOMINATORS, vp2->block);
3361 /* If the immediate dominator end in switch stmts multiple
3362 values may end up in the same PHI arg via intermediate
3363 CFG merges. */
3364 if (EDGE_COUNT (idom1->succs) != 2
3365 || EDGE_COUNT (idom2->succs) != 2)
3366 return false;
3368 /* Verify the controlling stmt is the same. */
3369 gcond *last1 = safe_dyn_cast <gcond *> (last_stmt (idom1));
3370 gcond *last2 = safe_dyn_cast <gcond *> (last_stmt (idom2));
3371 if (! last1 || ! last2)
3372 return false;
3373 bool inverted_p;
3374 if (! cond_stmts_equal_p (last1, vp1->cclhs, vp1->ccrhs,
3375 last2, vp2->cclhs, vp2->ccrhs,
3376 &inverted_p))
3377 return false;
3379 /* Get at true/false controlled edges into the PHI. */
3380 edge te1, te2, fe1, fe2;
3381 if (! extract_true_false_controlled_edges (idom1, vp1->block,
3382 &te1, &fe1)
3383 || ! extract_true_false_controlled_edges (idom2, vp2->block,
3384 &te2, &fe2))
3385 return false;
3387 /* Swap edges if the second condition is the inverted of the
3388 first. */
3389 if (inverted_p)
3390 std::swap (te2, fe2);
3392 /* ??? Handle VN_TOP specially. */
3393 if (! expressions_equal_p (vp1->phiargs[te1->dest_idx],
3394 vp2->phiargs[te2->dest_idx])
3395 || ! expressions_equal_p (vp1->phiargs[fe1->dest_idx],
3396 vp2->phiargs[fe2->dest_idx]))
3397 return false;
3399 return true;
3402 default:
3403 return false;
3407 /* If the PHI nodes do not have compatible types
3408 they are not the same. */
3409 if (!types_compatible_p (vp1->type, vp2->type))
3410 return false;
3412 /* Any phi in the same block will have it's arguments in the
3413 same edge order, because of how we store phi nodes. */
3414 for (unsigned i = 0; i < EDGE_COUNT (vp1->block->preds); ++i)
3416 tree phi1op = vp1->phiargs[i];
3417 tree phi2op = vp2->phiargs[i];
3418 if (phi1op == VN_TOP || phi2op == VN_TOP)
3419 continue;
3420 if (!expressions_equal_p (phi1op, phi2op))
3421 return false;
3424 return true;
3427 /* Lookup PHI in the current hash table, and return the resulting
3428 value number if it exists in the hash table. Return NULL_TREE if
3429 it does not exist in the hash table. */
3431 static tree
3432 vn_phi_lookup (gimple *phi, bool backedges_varying_p)
3434 vn_phi_s **slot;
3435 struct vn_phi_s *vp1;
3436 edge e;
3437 edge_iterator ei;
3439 vp1 = XALLOCAVAR (struct vn_phi_s,
3440 sizeof (struct vn_phi_s)
3441 + (gimple_phi_num_args (phi) - 1) * sizeof (tree));
3443 /* Canonicalize the SSA_NAME's to their value number. */
3444 FOR_EACH_EDGE (e, ei, gimple_bb (phi)->preds)
3446 tree def = PHI_ARG_DEF_FROM_EDGE (phi, e);
3447 if (TREE_CODE (def) == SSA_NAME
3448 && (!backedges_varying_p || !(e->flags & EDGE_DFS_BACK)))
3449 def = SSA_VAL (def);
3450 vp1->phiargs[e->dest_idx] = def;
3452 vp1->type = TREE_TYPE (gimple_phi_result (phi));
3453 vp1->block = gimple_bb (phi);
3454 /* Extract values of the controlling condition. */
3455 vp1->cclhs = NULL_TREE;
3456 vp1->ccrhs = NULL_TREE;
3457 basic_block idom1 = get_immediate_dominator (CDI_DOMINATORS, vp1->block);
3458 if (EDGE_COUNT (idom1->succs) == 2)
3459 if (gcond *last1 = safe_dyn_cast <gcond *> (last_stmt (idom1)))
3461 /* ??? We want to use SSA_VAL here. But possibly not
3462 allow VN_TOP. */
3463 vp1->cclhs = vn_valueize (gimple_cond_lhs (last1));
3464 vp1->ccrhs = vn_valueize (gimple_cond_rhs (last1));
3466 vp1->hashcode = vn_phi_compute_hash (vp1);
3467 slot = valid_info->phis->find_slot_with_hash (vp1, vp1->hashcode, NO_INSERT);
3468 if (!slot)
3469 return NULL_TREE;
3470 return (*slot)->result;
3473 /* Insert PHI into the current hash table with a value number of
3474 RESULT. */
3476 static vn_phi_t
3477 vn_phi_insert (gimple *phi, tree result, bool backedges_varying_p)
3479 vn_phi_s **slot;
3480 vn_phi_t vp1 = (vn_phi_t) obstack_alloc (&vn_tables_obstack,
3481 sizeof (vn_phi_s)
3482 + ((gimple_phi_num_args (phi) - 1)
3483 * sizeof (tree)));
3484 edge e;
3485 edge_iterator ei;
3487 /* Canonicalize the SSA_NAME's to their value number. */
3488 FOR_EACH_EDGE (e, ei, gimple_bb (phi)->preds)
3490 tree def = PHI_ARG_DEF_FROM_EDGE (phi, e);
3491 if (TREE_CODE (def) == SSA_NAME
3492 && (!backedges_varying_p || !(e->flags & EDGE_DFS_BACK)))
3493 def = SSA_VAL (def);
3494 vp1->phiargs[e->dest_idx] = def;
3496 vp1->value_id = VN_INFO (result)->value_id;
3497 vp1->type = TREE_TYPE (gimple_phi_result (phi));
3498 vp1->block = gimple_bb (phi);
3499 /* Extract values of the controlling condition. */
3500 vp1->cclhs = NULL_TREE;
3501 vp1->ccrhs = NULL_TREE;
3502 basic_block idom1 = get_immediate_dominator (CDI_DOMINATORS, vp1->block);
3503 if (EDGE_COUNT (idom1->succs) == 2)
3504 if (gcond *last1 = safe_dyn_cast <gcond *> (last_stmt (idom1)))
3506 /* ??? We want to use SSA_VAL here. But possibly not
3507 allow VN_TOP. */
3508 vp1->cclhs = vn_valueize (gimple_cond_lhs (last1));
3509 vp1->ccrhs = vn_valueize (gimple_cond_rhs (last1));
3511 vp1->result = result;
3512 vp1->hashcode = vn_phi_compute_hash (vp1);
3514 slot = valid_info->phis->find_slot_with_hash (vp1, vp1->hashcode, INSERT);
3515 gcc_assert (!*slot);
3517 *slot = vp1;
3518 vp1->next = last_inserted_phi;
3519 last_inserted_phi = vp1;
3520 return vp1;
3524 /* Return true if BB1 is dominated by BB2 taking into account edges
3525 that are not executable. */
3527 static bool
3528 dominated_by_p_w_unex (basic_block bb1, basic_block bb2)
3530 edge_iterator ei;
3531 edge e;
3533 if (dominated_by_p (CDI_DOMINATORS, bb1, bb2))
3534 return true;
3536 /* Before iterating we'd like to know if there exists a
3537 (executable) path from bb2 to bb1 at all, if not we can
3538 directly return false. For now simply iterate once. */
3540 /* Iterate to the single executable bb1 predecessor. */
3541 if (EDGE_COUNT (bb1->preds) > 1)
3543 edge prede = NULL;
3544 FOR_EACH_EDGE (e, ei, bb1->preds)
3545 if (e->flags & EDGE_EXECUTABLE)
3547 if (prede)
3549 prede = NULL;
3550 break;
3552 prede = e;
3554 if (prede)
3556 bb1 = prede->src;
3558 /* Re-do the dominance check with changed bb1. */
3559 if (dominated_by_p (CDI_DOMINATORS, bb1, bb2))
3560 return true;
3564 /* Iterate to the single executable bb2 successor. */
3565 edge succe = NULL;
3566 FOR_EACH_EDGE (e, ei, bb2->succs)
3567 if (e->flags & EDGE_EXECUTABLE)
3569 if (succe)
3571 succe = NULL;
3572 break;
3574 succe = e;
3576 if (succe)
3578 /* Verify the reached block is only reached through succe.
3579 If there is only one edge we can spare us the dominator
3580 check and iterate directly. */
3581 if (EDGE_COUNT (succe->dest->preds) > 1)
3583 FOR_EACH_EDGE (e, ei, succe->dest->preds)
3584 if (e != succe
3585 && (e->flags & EDGE_EXECUTABLE))
3587 succe = NULL;
3588 break;
3591 if (succe)
3593 bb2 = succe->dest;
3595 /* Re-do the dominance check with changed bb2. */
3596 if (dominated_by_p (CDI_DOMINATORS, bb1, bb2))
3597 return true;
3601 /* We could now iterate updating bb1 / bb2. */
3602 return false;
3605 /* Set the value number of FROM to TO, return true if it has changed
3606 as a result. */
3608 static inline bool
3609 set_ssa_val_to (tree from, tree to)
3611 vn_ssa_aux_t from_info = VN_INFO (from);
3612 tree currval = from_info->valnum; // SSA_VAL (from)
3613 poly_int64 toff, coff;
3615 /* The only thing we allow as value numbers are ssa_names
3616 and invariants. So assert that here. We don't allow VN_TOP
3617 as visiting a stmt should produce a value-number other than
3618 that.
3619 ??? Still VN_TOP can happen for unreachable code, so force
3620 it to varying in that case. Not all code is prepared to
3621 get VN_TOP on valueization. */
3622 if (to == VN_TOP)
3624 /* ??? When iterating and visiting PHI <undef, backedge-value>
3625 for the first time we rightfully get VN_TOP and we need to
3626 preserve that to optimize for example gcc.dg/tree-ssa/ssa-sccvn-2.c.
3627 With SCCVN we were simply lucky we iterated the other PHI
3628 cycles first and thus visited the backedge-value DEF. */
3629 if (currval == VN_TOP)
3630 goto set_and_exit;
3631 if (dump_file && (dump_flags & TDF_DETAILS))
3632 fprintf (dump_file, "Forcing value number to varying on "
3633 "receiving VN_TOP\n");
3634 to = from;
3637 gcc_checking_assert (to != NULL_TREE
3638 && ((TREE_CODE (to) == SSA_NAME
3639 && (to == from || SSA_VAL (to) == to))
3640 || is_gimple_min_invariant (to)));
3642 if (from != to)
3644 if (currval == from)
3646 if (dump_file && (dump_flags & TDF_DETAILS))
3648 fprintf (dump_file, "Not changing value number of ");
3649 print_generic_expr (dump_file, from);
3650 fprintf (dump_file, " from VARYING to ");
3651 print_generic_expr (dump_file, to);
3652 fprintf (dump_file, "\n");
3654 return false;
3656 else if (currval != VN_TOP
3657 && ! is_gimple_min_invariant (currval)
3658 && ! ssa_undefined_value_p (currval, false)
3659 && is_gimple_min_invariant (to))
3661 if (dump_file && (dump_flags & TDF_DETAILS))
3663 fprintf (dump_file, "Forcing VARYING instead of changing "
3664 "value number of ");
3665 print_generic_expr (dump_file, from);
3666 fprintf (dump_file, " from ");
3667 print_generic_expr (dump_file, currval);
3668 fprintf (dump_file, " (non-constant) to ");
3669 print_generic_expr (dump_file, to);
3670 fprintf (dump_file, " (constant)\n");
3672 to = from;
3674 else if (TREE_CODE (to) == SSA_NAME
3675 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (to))
3676 to = from;
3679 set_and_exit:
3680 if (dump_file && (dump_flags & TDF_DETAILS))
3682 fprintf (dump_file, "Setting value number of ");
3683 print_generic_expr (dump_file, from);
3684 fprintf (dump_file, " to ");
3685 print_generic_expr (dump_file, to);
3688 if (currval != to
3689 && !operand_equal_p (currval, to, 0)
3690 /* Different undefined SSA names are not actually different. See
3691 PR82320 for a testcase were we'd otherwise not terminate iteration. */
3692 && !(TREE_CODE (currval) == SSA_NAME
3693 && TREE_CODE (to) == SSA_NAME
3694 && ssa_undefined_value_p (currval, false)
3695 && ssa_undefined_value_p (to, false))
3696 /* ??? For addresses involving volatile objects or types operand_equal_p
3697 does not reliably detect ADDR_EXPRs as equal. We know we are only
3698 getting invariant gimple addresses here, so can use
3699 get_addr_base_and_unit_offset to do this comparison. */
3700 && !(TREE_CODE (currval) == ADDR_EXPR
3701 && TREE_CODE (to) == ADDR_EXPR
3702 && (get_addr_base_and_unit_offset (TREE_OPERAND (currval, 0), &coff)
3703 == get_addr_base_and_unit_offset (TREE_OPERAND (to, 0), &toff))
3704 && known_eq (coff, toff)))
3706 if (dump_file && (dump_flags & TDF_DETAILS))
3707 fprintf (dump_file, " (changed)\n");
3708 from_info->valnum = to;
3709 return true;
3711 if (dump_file && (dump_flags & TDF_DETAILS))
3712 fprintf (dump_file, "\n");
3713 return false;
3716 /* Set all definitions in STMT to value number to themselves.
3717 Return true if a value number changed. */
3719 static bool
3720 defs_to_varying (gimple *stmt)
3722 bool changed = false;
3723 ssa_op_iter iter;
3724 def_operand_p defp;
3726 FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_ALL_DEFS)
3728 tree def = DEF_FROM_PTR (defp);
3729 changed |= set_ssa_val_to (def, def);
3731 return changed;
3734 /* Visit a copy between LHS and RHS, return true if the value number
3735 changed. */
3737 static bool
3738 visit_copy (tree lhs, tree rhs)
3740 /* Valueize. */
3741 rhs = SSA_VAL (rhs);
3743 return set_ssa_val_to (lhs, rhs);
3746 /* Lookup a value for OP in type WIDE_TYPE where the value in type of OP
3747 is the same. */
3749 static tree
3750 valueized_wider_op (tree wide_type, tree op)
3752 if (TREE_CODE (op) == SSA_NAME)
3753 op = vn_valueize (op);
3755 /* Either we have the op widened available. */
3756 tree ops[3] = {};
3757 ops[0] = op;
3758 tree tem = vn_nary_op_lookup_pieces (1, NOP_EXPR,
3759 wide_type, ops, NULL);
3760 if (tem)
3761 return tem;
3763 /* Or the op is truncated from some existing value. */
3764 if (TREE_CODE (op) == SSA_NAME)
3766 gimple *def = SSA_NAME_DEF_STMT (op);
3767 if (is_gimple_assign (def)
3768 && CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def)))
3770 tem = gimple_assign_rhs1 (def);
3771 if (useless_type_conversion_p (wide_type, TREE_TYPE (tem)))
3773 if (TREE_CODE (tem) == SSA_NAME)
3774 tem = vn_valueize (tem);
3775 return tem;
3780 /* For constants simply extend it. */
3781 if (TREE_CODE (op) == INTEGER_CST)
3782 return wide_int_to_tree (wide_type, wi::to_wide (op));
3784 return NULL_TREE;
3787 /* Visit a nary operator RHS, value number it, and return true if the
3788 value number of LHS has changed as a result. */
3790 static bool
3791 visit_nary_op (tree lhs, gassign *stmt)
3793 vn_nary_op_t vnresult;
3794 tree result = vn_nary_op_lookup_stmt (stmt, &vnresult);
3795 if (! result && vnresult)
3796 result = vn_nary_op_get_predicated_value (vnresult, gimple_bb (stmt));
3797 if (result)
3798 return set_ssa_val_to (lhs, result);
3800 /* Do some special pattern matching for redundancies of operations
3801 in different types. */
3802 enum tree_code code = gimple_assign_rhs_code (stmt);
3803 tree type = TREE_TYPE (lhs);
3804 tree rhs1 = gimple_assign_rhs1 (stmt);
3805 switch (code)
3807 CASE_CONVERT:
3808 /* Match arithmetic done in a different type where we can easily
3809 substitute the result from some earlier sign-changed or widened
3810 operation. */
3811 if (INTEGRAL_TYPE_P (type)
3812 && TREE_CODE (rhs1) == SSA_NAME
3813 /* We only handle sign-changes or zero-extension -> & mask. */
3814 && ((TYPE_UNSIGNED (TREE_TYPE (rhs1))
3815 && TYPE_PRECISION (type) > TYPE_PRECISION (TREE_TYPE (rhs1)))
3816 || TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (rhs1))))
3818 gassign *def = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (rhs1));
3819 if (def
3820 && (gimple_assign_rhs_code (def) == PLUS_EXPR
3821 || gimple_assign_rhs_code (def) == MINUS_EXPR
3822 || gimple_assign_rhs_code (def) == MULT_EXPR))
3824 tree ops[3] = {};
3825 /* Either we have the op widened available. */
3826 ops[0] = valueized_wider_op (type,
3827 gimple_assign_rhs1 (def));
3828 if (ops[0])
3829 ops[1] = valueized_wider_op (type,
3830 gimple_assign_rhs2 (def));
3831 if (ops[0] && ops[1])
3833 ops[0] = vn_nary_op_lookup_pieces
3834 (2, gimple_assign_rhs_code (def), type, ops, NULL);
3835 /* We have wider operation available. */
3836 if (ops[0])
3838 unsigned lhs_prec = TYPE_PRECISION (type);
3839 unsigned rhs_prec = TYPE_PRECISION (TREE_TYPE (rhs1));
3840 if (lhs_prec == rhs_prec)
3842 gimple_match_op match_op (gimple_match_cond::UNCOND,
3843 NOP_EXPR, type, ops[0]);
3844 result = vn_nary_build_or_lookup (&match_op);
3845 if (result)
3847 bool changed = set_ssa_val_to (lhs, result);
3848 vn_nary_op_insert_stmt (stmt, result);
3849 return changed;
3852 else
3854 tree mask = wide_int_to_tree
3855 (type, wi::mask (rhs_prec, false, lhs_prec));
3856 gimple_match_op match_op (gimple_match_cond::UNCOND,
3857 BIT_AND_EXPR,
3858 TREE_TYPE (lhs),
3859 ops[0], mask);
3860 result = vn_nary_build_or_lookup (&match_op);
3861 if (result)
3863 bool changed = set_ssa_val_to (lhs, result);
3864 vn_nary_op_insert_stmt (stmt, result);
3865 return changed;
3872 default:;
3875 bool changed = set_ssa_val_to (lhs, lhs);
3876 vn_nary_op_insert_stmt (stmt, lhs);
3877 return changed;
3880 /* Visit a call STMT storing into LHS. Return true if the value number
3881 of the LHS has changed as a result. */
3883 static bool
3884 visit_reference_op_call (tree lhs, gcall *stmt)
3886 bool changed = false;
3887 struct vn_reference_s vr1;
3888 vn_reference_t vnresult = NULL;
3889 tree vdef = gimple_vdef (stmt);
3891 /* Non-ssa lhs is handled in copy_reference_ops_from_call. */
3892 if (lhs && TREE_CODE (lhs) != SSA_NAME)
3893 lhs = NULL_TREE;
3895 vn_reference_lookup_call (stmt, &vnresult, &vr1);
3896 if (vnresult)
3898 if (vnresult->result_vdef && vdef)
3899 changed |= set_ssa_val_to (vdef, vnresult->result_vdef);
3900 else if (vdef)
3901 /* If the call was discovered to be pure or const reflect
3902 that as far as possible. */
3903 changed |= set_ssa_val_to (vdef, vuse_ssa_val (gimple_vuse (stmt)));
3905 if (!vnresult->result && lhs)
3906 vnresult->result = lhs;
3908 if (vnresult->result && lhs)
3909 changed |= set_ssa_val_to (lhs, vnresult->result);
3911 else
3913 vn_reference_t vr2;
3914 vn_reference_s **slot;
3915 tree vdef_val = vdef;
3916 if (vdef)
3918 /* If we value numbered an indirect functions function to
3919 one not clobbering memory value number its VDEF to its
3920 VUSE. */
3921 tree fn = gimple_call_fn (stmt);
3922 if (fn && TREE_CODE (fn) == SSA_NAME)
3924 fn = SSA_VAL (fn);
3925 if (TREE_CODE (fn) == ADDR_EXPR
3926 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
3927 && (flags_from_decl_or_type (TREE_OPERAND (fn, 0))
3928 & (ECF_CONST | ECF_PURE)))
3929 vdef_val = vuse_ssa_val (gimple_vuse (stmt));
3931 changed |= set_ssa_val_to (vdef, vdef_val);
3933 if (lhs)
3934 changed |= set_ssa_val_to (lhs, lhs);
3935 vr2 = XOBNEW (&vn_tables_obstack, vn_reference_s);
3936 vr2->vuse = vr1.vuse;
3937 /* As we are not walking the virtual operand chain we know the
3938 shared_lookup_references are still original so we can re-use
3939 them here. */
3940 vr2->operands = vr1.operands.copy ();
3941 vr2->type = vr1.type;
3942 vr2->set = vr1.set;
3943 vr2->hashcode = vr1.hashcode;
3944 vr2->result = lhs;
3945 vr2->result_vdef = vdef_val;
3946 slot = valid_info->references->find_slot_with_hash (vr2, vr2->hashcode,
3947 INSERT);
3948 gcc_assert (!*slot);
3949 *slot = vr2;
3950 vr2->next = last_inserted_ref;
3951 last_inserted_ref = vr2;
3954 return changed;
3957 /* Visit a load from a reference operator RHS, part of STMT, value number it,
3958 and return true if the value number of the LHS has changed as a result. */
3960 static bool
3961 visit_reference_op_load (tree lhs, tree op, gimple *stmt)
3963 bool changed = false;
3964 tree last_vuse;
3965 tree result;
3967 last_vuse = gimple_vuse (stmt);
3968 last_vuse_ptr = &last_vuse;
3969 result = vn_reference_lookup (op, gimple_vuse (stmt),
3970 default_vn_walk_kind, NULL, true);
3971 last_vuse_ptr = NULL;
3973 /* We handle type-punning through unions by value-numbering based
3974 on offset and size of the access. Be prepared to handle a
3975 type-mismatch here via creating a VIEW_CONVERT_EXPR. */
3976 if (result
3977 && !useless_type_conversion_p (TREE_TYPE (result), TREE_TYPE (op)))
3979 /* We will be setting the value number of lhs to the value number
3980 of VIEW_CONVERT_EXPR <TREE_TYPE (result)> (result).
3981 So first simplify and lookup this expression to see if it
3982 is already available. */
3983 gimple_match_op res_op (gimple_match_cond::UNCOND,
3984 VIEW_CONVERT_EXPR, TREE_TYPE (op), result);
3985 result = vn_nary_build_or_lookup (&res_op);
3986 /* When building the conversion fails avoid inserting the reference
3987 again. */
3988 if (!result)
3989 return set_ssa_val_to (lhs, lhs);
3992 if (result)
3993 changed = set_ssa_val_to (lhs, result);
3994 else
3996 changed = set_ssa_val_to (lhs, lhs);
3997 vn_reference_insert (op, lhs, last_vuse, NULL_TREE);
4000 return changed;
4004 /* Visit a store to a reference operator LHS, part of STMT, value number it,
4005 and return true if the value number of the LHS has changed as a result. */
4007 static bool
4008 visit_reference_op_store (tree lhs, tree op, gimple *stmt)
4010 bool changed = false;
4011 vn_reference_t vnresult = NULL;
4012 tree assign;
4013 bool resultsame = false;
4014 tree vuse = gimple_vuse (stmt);
4015 tree vdef = gimple_vdef (stmt);
4017 if (TREE_CODE (op) == SSA_NAME)
4018 op = SSA_VAL (op);
4020 /* First we want to lookup using the *vuses* from the store and see
4021 if there the last store to this location with the same address
4022 had the same value.
4024 The vuses represent the memory state before the store. If the
4025 memory state, address, and value of the store is the same as the
4026 last store to this location, then this store will produce the
4027 same memory state as that store.
4029 In this case the vdef versions for this store are value numbered to those
4030 vuse versions, since they represent the same memory state after
4031 this store.
4033 Otherwise, the vdefs for the store are used when inserting into
4034 the table, since the store generates a new memory state. */
4036 vn_reference_lookup (lhs, vuse, VN_NOWALK, &vnresult, false);
4037 if (vnresult
4038 && vnresult->result)
4040 tree result = vnresult->result;
4041 gcc_checking_assert (TREE_CODE (result) != SSA_NAME
4042 || result == SSA_VAL (result));
4043 resultsame = expressions_equal_p (result, op);
4044 if (resultsame)
4046 /* If the TBAA state isn't compatible for downstream reads
4047 we cannot value-number the VDEFs the same. */
4048 alias_set_type set = get_alias_set (lhs);
4049 if (vnresult->set != set
4050 && ! alias_set_subset_of (set, vnresult->set))
4051 resultsame = false;
4055 if (!resultsame)
4057 /* Only perform the following when being called from PRE
4058 which embeds tail merging. */
4059 if (default_vn_walk_kind == VN_WALK)
4061 assign = build2 (MODIFY_EXPR, TREE_TYPE (lhs), lhs, op);
4062 vn_reference_lookup (assign, vuse, VN_NOWALK, &vnresult, false);
4063 if (vnresult)
4065 VN_INFO (vdef)->visited = true;
4066 return set_ssa_val_to (vdef, vnresult->result_vdef);
4070 if (dump_file && (dump_flags & TDF_DETAILS))
4072 fprintf (dump_file, "No store match\n");
4073 fprintf (dump_file, "Value numbering store ");
4074 print_generic_expr (dump_file, lhs);
4075 fprintf (dump_file, " to ");
4076 print_generic_expr (dump_file, op);
4077 fprintf (dump_file, "\n");
4079 /* Have to set value numbers before insert, since insert is
4080 going to valueize the references in-place. */
4081 if (vdef)
4082 changed |= set_ssa_val_to (vdef, vdef);
4084 /* Do not insert structure copies into the tables. */
4085 if (is_gimple_min_invariant (op)
4086 || is_gimple_reg (op))
4087 vn_reference_insert (lhs, op, vdef, NULL);
4089 /* Only perform the following when being called from PRE
4090 which embeds tail merging. */
4091 if (default_vn_walk_kind == VN_WALK)
4093 assign = build2 (MODIFY_EXPR, TREE_TYPE (lhs), lhs, op);
4094 vn_reference_insert (assign, lhs, vuse, vdef);
4097 else
4099 /* We had a match, so value number the vdef to have the value
4100 number of the vuse it came from. */
4102 if (dump_file && (dump_flags & TDF_DETAILS))
4103 fprintf (dump_file, "Store matched earlier value, "
4104 "value numbering store vdefs to matching vuses.\n");
4106 changed |= set_ssa_val_to (vdef, SSA_VAL (vuse));
4109 return changed;
4112 /* Visit and value number PHI, return true if the value number
4113 changed. When BACKEDGES_VARYING_P is true then assume all
4114 backedge values are varying. When INSERTED is not NULL then
4115 this is just a ahead query for a possible iteration, set INSERTED
4116 to true if we'd insert into the hashtable. */
4118 static bool
4119 visit_phi (gimple *phi, bool *inserted, bool backedges_varying_p)
4121 tree result, sameval = VN_TOP, seen_undef = NULL_TREE;
4122 tree backedge_val = NULL_TREE;
4123 bool seen_non_backedge = false;
4124 tree sameval_base = NULL_TREE;
4125 poly_int64 soff, doff;
4126 unsigned n_executable = 0;
4127 edge_iterator ei;
4128 edge e;
4130 /* TODO: We could check for this in initialization, and replace this
4131 with a gcc_assert. */
4132 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)))
4133 return set_ssa_val_to (PHI_RESULT (phi), PHI_RESULT (phi));
4135 /* We track whether a PHI was CSEd to to avoid excessive iterations
4136 that would be necessary only because the PHI changed arguments
4137 but not value. */
4138 if (!inserted)
4139 gimple_set_plf (phi, GF_PLF_1, false);
4141 /* See if all non-TOP arguments have the same value. TOP is
4142 equivalent to everything, so we can ignore it. */
4143 FOR_EACH_EDGE (e, ei, gimple_bb (phi)->preds)
4144 if (e->flags & EDGE_EXECUTABLE)
4146 tree def = PHI_ARG_DEF_FROM_EDGE (phi, e);
4148 ++n_executable;
4149 if (TREE_CODE (def) == SSA_NAME)
4151 if (!backedges_varying_p || !(e->flags & EDGE_DFS_BACK))
4152 def = SSA_VAL (def);
4153 if (e->flags & EDGE_DFS_BACK)
4154 backedge_val = def;
4156 if (!(e->flags & EDGE_DFS_BACK))
4157 seen_non_backedge = true;
4158 if (def == VN_TOP)
4160 /* Ignore undefined defs for sameval but record one. */
4161 else if (TREE_CODE (def) == SSA_NAME
4162 && ! virtual_operand_p (def)
4163 && ssa_undefined_value_p (def, false))
4164 seen_undef = def;
4165 else if (sameval == VN_TOP)
4166 sameval = def;
4167 else if (!expressions_equal_p (def, sameval))
4169 /* We know we're arriving only with invariant addresses here,
4170 try harder comparing them. We can do some caching here
4171 which we cannot do in expressions_equal_p. */
4172 if (TREE_CODE (def) == ADDR_EXPR
4173 && TREE_CODE (sameval) == ADDR_EXPR
4174 && sameval_base != (void *)-1)
4176 if (!sameval_base)
4177 sameval_base = get_addr_base_and_unit_offset
4178 (TREE_OPERAND (sameval, 0), &soff);
4179 if (!sameval_base)
4180 sameval_base = (tree)(void *)-1;
4181 else if ((get_addr_base_and_unit_offset
4182 (TREE_OPERAND (def, 0), &doff) == sameval_base)
4183 && known_eq (soff, doff))
4184 continue;
4186 sameval = NULL_TREE;
4187 break;
4191 /* If the value we want to use is flowing over the backedge and we
4192 should take it as VARYING but it has a non-VARYING value drop to
4193 VARYING.
4194 If we value-number a virtual operand never value-number to the
4195 value from the backedge as that confuses the alias-walking code.
4196 See gcc.dg/torture/pr87176.c. If the value is the same on a
4197 non-backedge everything is OK though. */
4198 bool visited_p;
4199 if ((backedge_val
4200 && !seen_non_backedge
4201 && TREE_CODE (backedge_val) == SSA_NAME
4202 && sameval == backedge_val
4203 && (SSA_NAME_IS_VIRTUAL_OPERAND (backedge_val)
4204 || SSA_VAL (backedge_val) != backedge_val))
4205 /* Do not value-number a virtual operand to sth not visited though
4206 given that allows us to escape a region in alias walking. */
4207 || (sameval
4208 && TREE_CODE (sameval) == SSA_NAME
4209 && !SSA_NAME_IS_DEFAULT_DEF (sameval)
4210 && SSA_NAME_IS_VIRTUAL_OPERAND (sameval)
4211 && (SSA_VAL (sameval, &visited_p), !visited_p)))
4212 /* Note this just drops to VARYING without inserting the PHI into
4213 the hashes. */
4214 result = PHI_RESULT (phi);
4215 /* If none of the edges was executable keep the value-number at VN_TOP,
4216 if only a single edge is exectuable use its value. */
4217 else if (n_executable <= 1)
4218 result = seen_undef ? seen_undef : sameval;
4219 /* If we saw only undefined values and VN_TOP use one of the
4220 undefined values. */
4221 else if (sameval == VN_TOP)
4222 result = seen_undef ? seen_undef : sameval;
4223 /* First see if it is equivalent to a phi node in this block. We prefer
4224 this as it allows IV elimination - see PRs 66502 and 67167. */
4225 else if ((result = vn_phi_lookup (phi, backedges_varying_p)))
4227 if (!inserted
4228 && TREE_CODE (result) == SSA_NAME
4229 && gimple_code (SSA_NAME_DEF_STMT (result)) == GIMPLE_PHI)
4231 gimple_set_plf (SSA_NAME_DEF_STMT (result), GF_PLF_1, true);
4232 if (dump_file && (dump_flags & TDF_DETAILS))
4234 fprintf (dump_file, "Marking CSEd to PHI node ");
4235 print_gimple_expr (dump_file, SSA_NAME_DEF_STMT (result),
4236 0, TDF_SLIM);
4237 fprintf (dump_file, "\n");
4241 /* If all values are the same use that, unless we've seen undefined
4242 values as well and the value isn't constant.
4243 CCP/copyprop have the same restriction to not remove uninit warnings. */
4244 else if (sameval
4245 && (! seen_undef || is_gimple_min_invariant (sameval)))
4246 result = sameval;
4247 else
4249 result = PHI_RESULT (phi);
4250 /* Only insert PHIs that are varying, for constant value numbers
4251 we mess up equivalences otherwise as we are only comparing
4252 the immediate controlling predicates. */
4253 vn_phi_insert (phi, result, backedges_varying_p);
4254 if (inserted)
4255 *inserted = true;
4258 return set_ssa_val_to (PHI_RESULT (phi), result);
4261 /* Try to simplify RHS using equivalences and constant folding. */
4263 static tree
4264 try_to_simplify (gassign *stmt)
4266 enum tree_code code = gimple_assign_rhs_code (stmt);
4267 tree tem;
4269 /* For stores we can end up simplifying a SSA_NAME rhs. Just return
4270 in this case, there is no point in doing extra work. */
4271 if (code == SSA_NAME)
4272 return NULL_TREE;
4274 /* First try constant folding based on our current lattice. */
4275 mprts_hook = vn_lookup_simplify_result;
4276 tem = gimple_fold_stmt_to_constant_1 (stmt, vn_valueize, vn_valueize);
4277 mprts_hook = NULL;
4278 if (tem
4279 && (TREE_CODE (tem) == SSA_NAME
4280 || is_gimple_min_invariant (tem)))
4281 return tem;
4283 return NULL_TREE;
4286 /* Visit and value number STMT, return true if the value number
4287 changed. */
4289 static bool
4290 visit_stmt (gimple *stmt, bool backedges_varying_p = false)
4292 bool changed = false;
4294 if (dump_file && (dump_flags & TDF_DETAILS))
4296 fprintf (dump_file, "Value numbering stmt = ");
4297 print_gimple_stmt (dump_file, stmt, 0);
4300 if (gimple_code (stmt) == GIMPLE_PHI)
4301 changed = visit_phi (stmt, NULL, backedges_varying_p);
4302 else if (gimple_has_volatile_ops (stmt))
4303 changed = defs_to_varying (stmt);
4304 else if (gassign *ass = dyn_cast <gassign *> (stmt))
4306 enum tree_code code = gimple_assign_rhs_code (ass);
4307 tree lhs = gimple_assign_lhs (ass);
4308 tree rhs1 = gimple_assign_rhs1 (ass);
4309 tree simplified;
4311 /* Shortcut for copies. Simplifying copies is pointless,
4312 since we copy the expression and value they represent. */
4313 if (code == SSA_NAME
4314 && TREE_CODE (lhs) == SSA_NAME)
4316 changed = visit_copy (lhs, rhs1);
4317 goto done;
4319 simplified = try_to_simplify (ass);
4320 if (simplified)
4322 if (dump_file && (dump_flags & TDF_DETAILS))
4324 fprintf (dump_file, "RHS ");
4325 print_gimple_expr (dump_file, ass, 0);
4326 fprintf (dump_file, " simplified to ");
4327 print_generic_expr (dump_file, simplified);
4328 fprintf (dump_file, "\n");
4331 /* Setting value numbers to constants will occasionally
4332 screw up phi congruence because constants are not
4333 uniquely associated with a single ssa name that can be
4334 looked up. */
4335 if (simplified
4336 && is_gimple_min_invariant (simplified)
4337 && TREE_CODE (lhs) == SSA_NAME)
4339 changed = set_ssa_val_to (lhs, simplified);
4340 goto done;
4342 else if (simplified
4343 && TREE_CODE (simplified) == SSA_NAME
4344 && TREE_CODE (lhs) == SSA_NAME)
4346 changed = visit_copy (lhs, simplified);
4347 goto done;
4350 if ((TREE_CODE (lhs) == SSA_NAME
4351 /* We can substitute SSA_NAMEs that are live over
4352 abnormal edges with their constant value. */
4353 && !(gimple_assign_copy_p (ass)
4354 && is_gimple_min_invariant (rhs1))
4355 && !(simplified
4356 && is_gimple_min_invariant (simplified))
4357 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
4358 /* Stores or copies from SSA_NAMEs that are live over
4359 abnormal edges are a problem. */
4360 || (code == SSA_NAME
4361 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs1)))
4362 changed = defs_to_varying (ass);
4363 else if (REFERENCE_CLASS_P (lhs)
4364 || DECL_P (lhs))
4365 changed = visit_reference_op_store (lhs, rhs1, ass);
4366 else if (TREE_CODE (lhs) == SSA_NAME)
4368 if ((gimple_assign_copy_p (ass)
4369 && is_gimple_min_invariant (rhs1))
4370 || (simplified
4371 && is_gimple_min_invariant (simplified)))
4373 if (simplified)
4374 changed = set_ssa_val_to (lhs, simplified);
4375 else
4376 changed = set_ssa_val_to (lhs, rhs1);
4378 else
4380 /* Visit the original statement. */
4381 switch (vn_get_stmt_kind (ass))
4383 case VN_NARY:
4384 changed = visit_nary_op (lhs, ass);
4385 break;
4386 case VN_REFERENCE:
4387 changed = visit_reference_op_load (lhs, rhs1, ass);
4388 break;
4389 default:
4390 changed = defs_to_varying (ass);
4391 break;
4395 else
4396 changed = defs_to_varying (ass);
4398 else if (gcall *call_stmt = dyn_cast <gcall *> (stmt))
4400 tree lhs = gimple_call_lhs (call_stmt);
4401 if (lhs && TREE_CODE (lhs) == SSA_NAME)
4403 /* Try constant folding based on our current lattice. */
4404 tree simplified = gimple_fold_stmt_to_constant_1 (call_stmt,
4405 vn_valueize);
4406 if (simplified)
4408 if (dump_file && (dump_flags & TDF_DETAILS))
4410 fprintf (dump_file, "call ");
4411 print_gimple_expr (dump_file, call_stmt, 0);
4412 fprintf (dump_file, " simplified to ");
4413 print_generic_expr (dump_file, simplified);
4414 fprintf (dump_file, "\n");
4417 /* Setting value numbers to constants will occasionally
4418 screw up phi congruence because constants are not
4419 uniquely associated with a single ssa name that can be
4420 looked up. */
4421 if (simplified
4422 && is_gimple_min_invariant (simplified))
4424 changed = set_ssa_val_to (lhs, simplified);
4425 if (gimple_vdef (call_stmt))
4426 changed |= set_ssa_val_to (gimple_vdef (call_stmt),
4427 SSA_VAL (gimple_vuse (call_stmt)));
4428 goto done;
4430 else if (simplified
4431 && TREE_CODE (simplified) == SSA_NAME)
4433 changed = visit_copy (lhs, simplified);
4434 if (gimple_vdef (call_stmt))
4435 changed |= set_ssa_val_to (gimple_vdef (call_stmt),
4436 SSA_VAL (gimple_vuse (call_stmt)));
4437 goto done;
4439 else if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
4441 changed = defs_to_varying (call_stmt);
4442 goto done;
4446 /* Pick up flags from a devirtualization target. */
4447 tree fn = gimple_call_fn (stmt);
4448 int extra_fnflags = 0;
4449 if (fn && TREE_CODE (fn) == SSA_NAME)
4451 fn = SSA_VAL (fn);
4452 if (TREE_CODE (fn) == ADDR_EXPR
4453 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL)
4454 extra_fnflags = flags_from_decl_or_type (TREE_OPERAND (fn, 0));
4456 if (!gimple_call_internal_p (call_stmt)
4457 && (/* Calls to the same function with the same vuse
4458 and the same operands do not necessarily return the same
4459 value, unless they're pure or const. */
4460 ((gimple_call_flags (call_stmt) | extra_fnflags)
4461 & (ECF_PURE | ECF_CONST))
4462 /* If calls have a vdef, subsequent calls won't have
4463 the same incoming vuse. So, if 2 calls with vdef have the
4464 same vuse, we know they're not subsequent.
4465 We can value number 2 calls to the same function with the
4466 same vuse and the same operands which are not subsequent
4467 the same, because there is no code in the program that can
4468 compare the 2 values... */
4469 || (gimple_vdef (call_stmt)
4470 /* ... unless the call returns a pointer which does
4471 not alias with anything else. In which case the
4472 information that the values are distinct are encoded
4473 in the IL. */
4474 && !(gimple_call_return_flags (call_stmt) & ERF_NOALIAS)
4475 /* Only perform the following when being called from PRE
4476 which embeds tail merging. */
4477 && default_vn_walk_kind == VN_WALK)))
4478 changed = visit_reference_op_call (lhs, call_stmt);
4479 else
4480 changed = defs_to_varying (call_stmt);
4482 else
4483 changed = defs_to_varying (stmt);
4484 done:
4485 return changed;
4489 /* Allocate a value number table. */
4491 static void
4492 allocate_vn_table (vn_tables_t table, unsigned size)
4494 table->phis = new vn_phi_table_type (size);
4495 table->nary = new vn_nary_op_table_type (size);
4496 table->references = new vn_reference_table_type (size);
4499 /* Free a value number table. */
4501 static void
4502 free_vn_table (vn_tables_t table)
4504 /* Walk over elements and release vectors. */
4505 vn_reference_iterator_type hir;
4506 vn_reference_t vr;
4507 FOR_EACH_HASH_TABLE_ELEMENT (*table->references, vr, vn_reference_t, hir)
4508 vr->operands.release ();
4509 delete table->phis;
4510 table->phis = NULL;
4511 delete table->nary;
4512 table->nary = NULL;
4513 delete table->references;
4514 table->references = NULL;
4517 /* Set *ID according to RESULT. */
4519 static void
4520 set_value_id_for_result (tree result, unsigned int *id)
4522 if (result && TREE_CODE (result) == SSA_NAME)
4523 *id = VN_INFO (result)->value_id;
4524 else if (result && is_gimple_min_invariant (result))
4525 *id = get_or_alloc_constant_value_id (result);
4526 else
4527 *id = get_next_value_id ();
4530 /* Set the value ids in the valid hash tables. */
4532 static void
4533 set_hashtable_value_ids (void)
4535 vn_nary_op_iterator_type hin;
4536 vn_phi_iterator_type hip;
4537 vn_reference_iterator_type hir;
4538 vn_nary_op_t vno;
4539 vn_reference_t vr;
4540 vn_phi_t vp;
4542 /* Now set the value ids of the things we had put in the hash
4543 table. */
4545 FOR_EACH_HASH_TABLE_ELEMENT (*valid_info->nary, vno, vn_nary_op_t, hin)
4546 if (! vno->predicated_values)
4547 set_value_id_for_result (vno->u.result, &vno->value_id);
4549 FOR_EACH_HASH_TABLE_ELEMENT (*valid_info->phis, vp, vn_phi_t, hip)
4550 set_value_id_for_result (vp->result, &vp->value_id);
4552 FOR_EACH_HASH_TABLE_ELEMENT (*valid_info->references, vr, vn_reference_t,
4553 hir)
4554 set_value_id_for_result (vr->result, &vr->value_id);
4557 /* Return the maximum value id we have ever seen. */
4559 unsigned int
4560 get_max_value_id (void)
4562 return next_value_id;
4565 /* Return the next unique value id. */
4567 unsigned int
4568 get_next_value_id (void)
4570 return next_value_id++;
4574 /* Compare two expressions E1 and E2 and return true if they are equal. */
4576 bool
4577 expressions_equal_p (tree e1, tree e2)
4579 /* The obvious case. */
4580 if (e1 == e2)
4581 return true;
4583 /* If either one is VN_TOP consider them equal. */
4584 if (e1 == VN_TOP || e2 == VN_TOP)
4585 return true;
4587 /* If only one of them is null, they cannot be equal. */
4588 if (!e1 || !e2)
4589 return false;
4591 /* Now perform the actual comparison. */
4592 if (TREE_CODE (e1) == TREE_CODE (e2)
4593 && operand_equal_p (e1, e2, OEP_PURE_SAME))
4594 return true;
4596 return false;
4600 /* Return true if the nary operation NARY may trap. This is a copy
4601 of stmt_could_throw_1_p adjusted to the SCCVN IL. */
4603 bool
4604 vn_nary_may_trap (vn_nary_op_t nary)
4606 tree type;
4607 tree rhs2 = NULL_TREE;
4608 bool honor_nans = false;
4609 bool honor_snans = false;
4610 bool fp_operation = false;
4611 bool honor_trapv = false;
4612 bool handled, ret;
4613 unsigned i;
4615 if (TREE_CODE_CLASS (nary->opcode) == tcc_comparison
4616 || TREE_CODE_CLASS (nary->opcode) == tcc_unary
4617 || TREE_CODE_CLASS (nary->opcode) == tcc_binary)
4619 type = nary->type;
4620 fp_operation = FLOAT_TYPE_P (type);
4621 if (fp_operation)
4623 honor_nans = flag_trapping_math && !flag_finite_math_only;
4624 honor_snans = flag_signaling_nans != 0;
4626 else if (INTEGRAL_TYPE_P (type)
4627 && TYPE_OVERFLOW_TRAPS (type))
4628 honor_trapv = true;
4630 if (nary->length >= 2)
4631 rhs2 = nary->op[1];
4632 ret = operation_could_trap_helper_p (nary->opcode, fp_operation,
4633 honor_trapv,
4634 honor_nans, honor_snans, rhs2,
4635 &handled);
4636 if (handled
4637 && ret)
4638 return true;
4640 for (i = 0; i < nary->length; ++i)
4641 if (tree_could_trap_p (nary->op[i]))
4642 return true;
4644 return false;
4648 class eliminate_dom_walker : public dom_walker
4650 public:
4651 eliminate_dom_walker (cdi_direction, bitmap);
4652 ~eliminate_dom_walker ();
4654 virtual edge before_dom_children (basic_block);
4655 virtual void after_dom_children (basic_block);
4657 virtual tree eliminate_avail (basic_block, tree op);
4658 virtual void eliminate_push_avail (basic_block, tree op);
4659 tree eliminate_insert (basic_block, gimple_stmt_iterator *gsi, tree val);
4661 void eliminate_stmt (basic_block, gimple_stmt_iterator *);
4663 unsigned eliminate_cleanup (bool region_p = false);
4665 bool do_pre;
4666 unsigned int el_todo;
4667 unsigned int eliminations;
4668 unsigned int insertions;
4670 /* SSA names that had their defs inserted by PRE if do_pre. */
4671 bitmap inserted_exprs;
4673 /* Blocks with statements that have had their EH properties changed. */
4674 bitmap need_eh_cleanup;
4676 /* Blocks with statements that have had their AB properties changed. */
4677 bitmap need_ab_cleanup;
4679 /* Local state for the eliminate domwalk. */
4680 auto_vec<gimple *> to_remove;
4681 auto_vec<gimple *> to_fixup;
4682 auto_vec<tree> avail;
4683 auto_vec<tree> avail_stack;
4686 eliminate_dom_walker::eliminate_dom_walker (cdi_direction direction,
4687 bitmap inserted_exprs_)
4688 : dom_walker (direction), do_pre (inserted_exprs_ != NULL),
4689 el_todo (0), eliminations (0), insertions (0),
4690 inserted_exprs (inserted_exprs_)
4692 need_eh_cleanup = BITMAP_ALLOC (NULL);
4693 need_ab_cleanup = BITMAP_ALLOC (NULL);
4696 eliminate_dom_walker::~eliminate_dom_walker ()
4698 BITMAP_FREE (need_eh_cleanup);
4699 BITMAP_FREE (need_ab_cleanup);
4702 /* Return a leader for OP that is available at the current point of the
4703 eliminate domwalk. */
4705 tree
4706 eliminate_dom_walker::eliminate_avail (basic_block, tree op)
4708 tree valnum = VN_INFO (op)->valnum;
4709 if (TREE_CODE (valnum) == SSA_NAME)
4711 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
4712 return valnum;
4713 if (avail.length () > SSA_NAME_VERSION (valnum))
4714 return avail[SSA_NAME_VERSION (valnum)];
4716 else if (is_gimple_min_invariant (valnum))
4717 return valnum;
4718 return NULL_TREE;
4721 /* At the current point of the eliminate domwalk make OP available. */
4723 void
4724 eliminate_dom_walker::eliminate_push_avail (basic_block, tree op)
4726 tree valnum = VN_INFO (op)->valnum;
4727 if (TREE_CODE (valnum) == SSA_NAME)
4729 if (avail.length () <= SSA_NAME_VERSION (valnum))
4730 avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1);
4731 tree pushop = op;
4732 if (avail[SSA_NAME_VERSION (valnum)])
4733 pushop = avail[SSA_NAME_VERSION (valnum)];
4734 avail_stack.safe_push (pushop);
4735 avail[SSA_NAME_VERSION (valnum)] = op;
4739 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
4740 the leader for the expression if insertion was successful. */
4742 tree
4743 eliminate_dom_walker::eliminate_insert (basic_block bb,
4744 gimple_stmt_iterator *gsi, tree val)
4746 /* We can insert a sequence with a single assignment only. */
4747 gimple_seq stmts = VN_INFO (val)->expr;
4748 if (!gimple_seq_singleton_p (stmts))
4749 return NULL_TREE;
4750 gassign *stmt = dyn_cast <gassign *> (gimple_seq_first_stmt (stmts));
4751 if (!stmt
4752 || (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt))
4753 && gimple_assign_rhs_code (stmt) != VIEW_CONVERT_EXPR
4754 && gimple_assign_rhs_code (stmt) != BIT_FIELD_REF
4755 && (gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
4756 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)))
4757 return NULL_TREE;
4759 tree op = gimple_assign_rhs1 (stmt);
4760 if (gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR
4761 || gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
4762 op = TREE_OPERAND (op, 0);
4763 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (bb, op) : op;
4764 if (!leader)
4765 return NULL_TREE;
4767 tree res;
4768 stmts = NULL;
4769 if (gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
4770 res = gimple_build (&stmts, BIT_FIELD_REF,
4771 TREE_TYPE (val), leader,
4772 TREE_OPERAND (gimple_assign_rhs1 (stmt), 1),
4773 TREE_OPERAND (gimple_assign_rhs1 (stmt), 2));
4774 else if (gimple_assign_rhs_code (stmt) == BIT_AND_EXPR)
4775 res = gimple_build (&stmts, BIT_AND_EXPR,
4776 TREE_TYPE (val), leader, gimple_assign_rhs2 (stmt));
4777 else
4778 res = gimple_build (&stmts, gimple_assign_rhs_code (stmt),
4779 TREE_TYPE (val), leader);
4780 if (TREE_CODE (res) != SSA_NAME
4781 || SSA_NAME_IS_DEFAULT_DEF (res)
4782 || gimple_bb (SSA_NAME_DEF_STMT (res)))
4784 gimple_seq_discard (stmts);
4786 /* During propagation we have to treat SSA info conservatively
4787 and thus we can end up simplifying the inserted expression
4788 at elimination time to sth not defined in stmts. */
4789 /* But then this is a redundancy we failed to detect. Which means
4790 res now has two values. That doesn't play well with how
4791 we track availability here, so give up. */
4792 if (dump_file && (dump_flags & TDF_DETAILS))
4794 if (TREE_CODE (res) == SSA_NAME)
4795 res = eliminate_avail (bb, res);
4796 if (res)
4798 fprintf (dump_file, "Failed to insert expression for value ");
4799 print_generic_expr (dump_file, val);
4800 fprintf (dump_file, " which is really fully redundant to ");
4801 print_generic_expr (dump_file, res);
4802 fprintf (dump_file, "\n");
4806 return NULL_TREE;
4808 else
4810 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
4811 VN_INFO (res)->valnum = val;
4812 VN_INFO (res)->visited = true;
4815 insertions++;
4816 if (dump_file && (dump_flags & TDF_DETAILS))
4818 fprintf (dump_file, "Inserted ");
4819 print_gimple_stmt (dump_file, SSA_NAME_DEF_STMT (res), 0);
4822 return res;
4825 void
4826 eliminate_dom_walker::eliminate_stmt (basic_block b, gimple_stmt_iterator *gsi)
4828 tree sprime = NULL_TREE;
4829 gimple *stmt = gsi_stmt (*gsi);
4830 tree lhs = gimple_get_lhs (stmt);
4831 if (lhs && TREE_CODE (lhs) == SSA_NAME
4832 && !gimple_has_volatile_ops (stmt)
4833 /* See PR43491. Do not replace a global register variable when
4834 it is a the RHS of an assignment. Do replace local register
4835 variables since gcc does not guarantee a local variable will
4836 be allocated in register.
4837 ??? The fix isn't effective here. This should instead
4838 be ensured by not value-numbering them the same but treating
4839 them like volatiles? */
4840 && !(gimple_assign_single_p (stmt)
4841 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == VAR_DECL
4842 && DECL_HARD_REGISTER (gimple_assign_rhs1 (stmt))
4843 && is_global_var (gimple_assign_rhs1 (stmt)))))
4845 sprime = eliminate_avail (b, lhs);
4846 if (!sprime)
4848 /* If there is no existing usable leader but SCCVN thinks
4849 it has an expression it wants to use as replacement,
4850 insert that. */
4851 tree val = VN_INFO (lhs)->valnum;
4852 if (val != VN_TOP
4853 && TREE_CODE (val) == SSA_NAME
4854 && VN_INFO (val)->needs_insertion
4855 && VN_INFO (val)->expr != NULL
4856 && (sprime = eliminate_insert (b, gsi, val)) != NULL_TREE)
4857 eliminate_push_avail (b, sprime);
4860 /* If this now constitutes a copy duplicate points-to
4861 and range info appropriately. This is especially
4862 important for inserted code. See tree-ssa-copy.c
4863 for similar code. */
4864 if (sprime
4865 && TREE_CODE (sprime) == SSA_NAME)
4867 basic_block sprime_b = gimple_bb (SSA_NAME_DEF_STMT (sprime));
4868 if (POINTER_TYPE_P (TREE_TYPE (lhs))
4869 && SSA_NAME_PTR_INFO (lhs)
4870 && ! SSA_NAME_PTR_INFO (sprime))
4872 duplicate_ssa_name_ptr_info (sprime,
4873 SSA_NAME_PTR_INFO (lhs));
4874 if (b != sprime_b)
4875 mark_ptr_info_alignment_unknown
4876 (SSA_NAME_PTR_INFO (sprime));
4878 else if (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
4879 && SSA_NAME_RANGE_INFO (lhs)
4880 && ! SSA_NAME_RANGE_INFO (sprime)
4881 && b == sprime_b)
4882 duplicate_ssa_name_range_info (sprime,
4883 SSA_NAME_RANGE_TYPE (lhs),
4884 SSA_NAME_RANGE_INFO (lhs));
4887 /* Inhibit the use of an inserted PHI on a loop header when
4888 the address of the memory reference is a simple induction
4889 variable. In other cases the vectorizer won't do anything
4890 anyway (either it's loop invariant or a complicated
4891 expression). */
4892 if (sprime
4893 && TREE_CODE (sprime) == SSA_NAME
4894 && do_pre
4895 && (flag_tree_loop_vectorize || flag_tree_parallelize_loops > 1)
4896 && loop_outer (b->loop_father)
4897 && has_zero_uses (sprime)
4898 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))
4899 && gimple_assign_load_p (stmt))
4901 gimple *def_stmt = SSA_NAME_DEF_STMT (sprime);
4902 basic_block def_bb = gimple_bb (def_stmt);
4903 if (gimple_code (def_stmt) == GIMPLE_PHI
4904 && def_bb->loop_father->header == def_bb)
4906 loop_p loop = def_bb->loop_father;
4907 ssa_op_iter iter;
4908 tree op;
4909 bool found = false;
4910 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
4912 affine_iv iv;
4913 def_bb = gimple_bb (SSA_NAME_DEF_STMT (op));
4914 if (def_bb
4915 && flow_bb_inside_loop_p (loop, def_bb)
4916 && simple_iv (loop, loop, op, &iv, true))
4918 found = true;
4919 break;
4922 if (found)
4924 if (dump_file && (dump_flags & TDF_DETAILS))
4926 fprintf (dump_file, "Not replacing ");
4927 print_gimple_expr (dump_file, stmt, 0);
4928 fprintf (dump_file, " with ");
4929 print_generic_expr (dump_file, sprime);
4930 fprintf (dump_file, " which would add a loop"
4931 " carried dependence to loop %d\n",
4932 loop->num);
4934 /* Don't keep sprime available. */
4935 sprime = NULL_TREE;
4940 if (sprime)
4942 /* If we can propagate the value computed for LHS into
4943 all uses don't bother doing anything with this stmt. */
4944 if (may_propagate_copy (lhs, sprime))
4946 /* Mark it for removal. */
4947 to_remove.safe_push (stmt);
4949 /* ??? Don't count copy/constant propagations. */
4950 if (gimple_assign_single_p (stmt)
4951 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4952 || gimple_assign_rhs1 (stmt) == sprime))
4953 return;
4955 if (dump_file && (dump_flags & TDF_DETAILS))
4957 fprintf (dump_file, "Replaced ");
4958 print_gimple_expr (dump_file, stmt, 0);
4959 fprintf (dump_file, " with ");
4960 print_generic_expr (dump_file, sprime);
4961 fprintf (dump_file, " in all uses of ");
4962 print_gimple_stmt (dump_file, stmt, 0);
4965 eliminations++;
4966 return;
4969 /* If this is an assignment from our leader (which
4970 happens in the case the value-number is a constant)
4971 then there is nothing to do. */
4972 if (gimple_assign_single_p (stmt)
4973 && sprime == gimple_assign_rhs1 (stmt))
4974 return;
4976 /* Else replace its RHS. */
4977 bool can_make_abnormal_goto
4978 = is_gimple_call (stmt)
4979 && stmt_can_make_abnormal_goto (stmt);
4981 if (dump_file && (dump_flags & TDF_DETAILS))
4983 fprintf (dump_file, "Replaced ");
4984 print_gimple_expr (dump_file, stmt, 0);
4985 fprintf (dump_file, " with ");
4986 print_generic_expr (dump_file, sprime);
4987 fprintf (dump_file, " in ");
4988 print_gimple_stmt (dump_file, stmt, 0);
4991 eliminations++;
4992 gimple *orig_stmt = stmt;
4993 if (!useless_type_conversion_p (TREE_TYPE (lhs),
4994 TREE_TYPE (sprime)))
4995 sprime = fold_convert (TREE_TYPE (lhs), sprime);
4996 tree vdef = gimple_vdef (stmt);
4997 tree vuse = gimple_vuse (stmt);
4998 propagate_tree_value_into_stmt (gsi, sprime);
4999 stmt = gsi_stmt (*gsi);
5000 update_stmt (stmt);
5001 /* In case the VDEF on the original stmt was released, value-number
5002 it to the VUSE. This is to make vuse_ssa_val able to skip
5003 released virtual operands. */
5004 if (vdef != gimple_vdef (stmt))
5006 gcc_assert (SSA_NAME_IN_FREE_LIST (vdef));
5007 VN_INFO (vdef)->valnum = vuse;
5010 /* If we removed EH side-effects from the statement, clean
5011 its EH information. */
5012 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
5014 bitmap_set_bit (need_eh_cleanup,
5015 gimple_bb (stmt)->index);
5016 if (dump_file && (dump_flags & TDF_DETAILS))
5017 fprintf (dump_file, " Removed EH side-effects.\n");
5020 /* Likewise for AB side-effects. */
5021 if (can_make_abnormal_goto
5022 && !stmt_can_make_abnormal_goto (stmt))
5024 bitmap_set_bit (need_ab_cleanup,
5025 gimple_bb (stmt)->index);
5026 if (dump_file && (dump_flags & TDF_DETAILS))
5027 fprintf (dump_file, " Removed AB side-effects.\n");
5030 return;
5034 /* If the statement is a scalar store, see if the expression
5035 has the same value number as its rhs. If so, the store is
5036 dead. */
5037 if (gimple_assign_single_p (stmt)
5038 && !gimple_has_volatile_ops (stmt)
5039 && !is_gimple_reg (gimple_assign_lhs (stmt))
5040 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
5041 || is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
5043 tree val;
5044 tree rhs = gimple_assign_rhs1 (stmt);
5045 vn_reference_t vnresult;
5046 val = vn_reference_lookup (lhs, gimple_vuse (stmt), VN_WALKREWRITE,
5047 &vnresult, false);
5048 if (TREE_CODE (rhs) == SSA_NAME)
5049 rhs = VN_INFO (rhs)->valnum;
5050 if (val
5051 && operand_equal_p (val, rhs, 0))
5053 /* We can only remove the later store if the former aliases
5054 at least all accesses the later one does or if the store
5055 was to readonly memory storing the same value. */
5056 alias_set_type set = get_alias_set (lhs);
5057 if (! vnresult
5058 || vnresult->set == set
5059 || alias_set_subset_of (set, vnresult->set))
5061 if (dump_file && (dump_flags & TDF_DETAILS))
5063 fprintf (dump_file, "Deleted redundant store ");
5064 print_gimple_stmt (dump_file, stmt, 0);
5067 /* Queue stmt for removal. */
5068 to_remove.safe_push (stmt);
5069 return;
5074 /* If this is a control statement value numbering left edges
5075 unexecuted on force the condition in a way consistent with
5076 that. */
5077 if (gcond *cond = dyn_cast <gcond *> (stmt))
5079 if ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE)
5080 ^ (EDGE_SUCC (b, 1)->flags & EDGE_EXECUTABLE))
5082 if (dump_file && (dump_flags & TDF_DETAILS))
5084 fprintf (dump_file, "Removing unexecutable edge from ");
5085 print_gimple_stmt (dump_file, stmt, 0);
5087 if (((EDGE_SUCC (b, 0)->flags & EDGE_TRUE_VALUE) != 0)
5088 == ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE) != 0))
5089 gimple_cond_make_true (cond);
5090 else
5091 gimple_cond_make_false (cond);
5092 update_stmt (cond);
5093 el_todo |= TODO_cleanup_cfg;
5094 return;
5098 bool can_make_abnormal_goto = stmt_can_make_abnormal_goto (stmt);
5099 bool was_noreturn = (is_gimple_call (stmt)
5100 && gimple_call_noreturn_p (stmt));
5101 tree vdef = gimple_vdef (stmt);
5102 tree vuse = gimple_vuse (stmt);
5104 /* If we didn't replace the whole stmt (or propagate the result
5105 into all uses), replace all uses on this stmt with their
5106 leaders. */
5107 bool modified = false;
5108 use_operand_p use_p;
5109 ssa_op_iter iter;
5110 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
5112 tree use = USE_FROM_PTR (use_p);
5113 /* ??? The call code above leaves stmt operands un-updated. */
5114 if (TREE_CODE (use) != SSA_NAME)
5115 continue;
5116 tree sprime;
5117 if (SSA_NAME_IS_DEFAULT_DEF (use))
5118 /* ??? For default defs BB shouldn't matter, but we have to
5119 solve the inconsistency between rpo eliminate and
5120 dom eliminate avail valueization first. */
5121 sprime = eliminate_avail (b, use);
5122 else
5123 /* Look for sth available at the definition block of the argument.
5124 This avoids inconsistencies between availability there which
5125 decides if the stmt can be removed and availability at the
5126 use site. The SSA property ensures that things available
5127 at the definition are also available at uses. */
5128 sprime = eliminate_avail (gimple_bb (SSA_NAME_DEF_STMT (use)), use);
5129 if (sprime && sprime != use
5130 && may_propagate_copy (use, sprime)
5131 /* We substitute into debug stmts to avoid excessive
5132 debug temporaries created by removed stmts, but we need
5133 to avoid doing so for inserted sprimes as we never want
5134 to create debug temporaries for them. */
5135 && (!inserted_exprs
5136 || TREE_CODE (sprime) != SSA_NAME
5137 || !is_gimple_debug (stmt)
5138 || !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))))
5140 propagate_value (use_p, sprime);
5141 modified = true;
5145 /* Fold the stmt if modified, this canonicalizes MEM_REFs we propagated
5146 into which is a requirement for the IPA devirt machinery. */
5147 gimple *old_stmt = stmt;
5148 if (modified)
5150 /* If a formerly non-invariant ADDR_EXPR is turned into an
5151 invariant one it was on a separate stmt. */
5152 if (gimple_assign_single_p (stmt)
5153 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
5154 recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
5155 gimple_stmt_iterator prev = *gsi;
5156 gsi_prev (&prev);
5157 if (fold_stmt (gsi))
5159 /* fold_stmt may have created new stmts inbetween
5160 the previous stmt and the folded stmt. Mark
5161 all defs created there as varying to not confuse
5162 the SCCVN machinery as we're using that even during
5163 elimination. */
5164 if (gsi_end_p (prev))
5165 prev = gsi_start_bb (b);
5166 else
5167 gsi_next (&prev);
5168 if (gsi_stmt (prev) != gsi_stmt (*gsi))
5171 tree def;
5172 ssa_op_iter dit;
5173 FOR_EACH_SSA_TREE_OPERAND (def, gsi_stmt (prev),
5174 dit, SSA_OP_ALL_DEFS)
5175 /* As existing DEFs may move between stmts
5176 only process new ones. */
5177 if (! has_VN_INFO (def))
5179 VN_INFO (def)->valnum = def;
5180 VN_INFO (def)->visited = true;
5182 if (gsi_stmt (prev) == gsi_stmt (*gsi))
5183 break;
5184 gsi_next (&prev);
5186 while (1);
5188 stmt = gsi_stmt (*gsi);
5189 /* In case we folded the stmt away schedule the NOP for removal. */
5190 if (gimple_nop_p (stmt))
5191 to_remove.safe_push (stmt);
5194 /* Visit indirect calls and turn them into direct calls if
5195 possible using the devirtualization machinery. Do this before
5196 checking for required EH/abnormal/noreturn cleanup as devird
5197 may expose more of those. */
5198 if (gcall *call_stmt = dyn_cast <gcall *> (stmt))
5200 tree fn = gimple_call_fn (call_stmt);
5201 if (fn
5202 && flag_devirtualize
5203 && virtual_method_call_p (fn))
5205 tree otr_type = obj_type_ref_class (fn);
5206 unsigned HOST_WIDE_INT otr_tok
5207 = tree_to_uhwi (OBJ_TYPE_REF_TOKEN (fn));
5208 tree instance;
5209 ipa_polymorphic_call_context context (current_function_decl,
5210 fn, stmt, &instance);
5211 context.get_dynamic_type (instance, OBJ_TYPE_REF_OBJECT (fn),
5212 otr_type, stmt);
5213 bool final;
5214 vec <cgraph_node *> targets
5215 = possible_polymorphic_call_targets (obj_type_ref_class (fn),
5216 otr_tok, context, &final);
5217 if (dump_file)
5218 dump_possible_polymorphic_call_targets (dump_file,
5219 obj_type_ref_class (fn),
5220 otr_tok, context);
5221 if (final && targets.length () <= 1 && dbg_cnt (devirt))
5223 tree fn;
5224 if (targets.length () == 1)
5225 fn = targets[0]->decl;
5226 else
5227 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
5228 if (dump_enabled_p ())
5230 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, stmt,
5231 "converting indirect call to "
5232 "function %s\n",
5233 lang_hooks.decl_printable_name (fn, 2));
5235 gimple_call_set_fndecl (call_stmt, fn);
5236 /* If changing the call to __builtin_unreachable
5237 or similar noreturn function, adjust gimple_call_fntype
5238 too. */
5239 if (gimple_call_noreturn_p (call_stmt)
5240 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fn)))
5241 && TYPE_ARG_TYPES (TREE_TYPE (fn))
5242 && (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fn)))
5243 == void_type_node))
5244 gimple_call_set_fntype (call_stmt, TREE_TYPE (fn));
5245 maybe_remove_unused_call_args (cfun, call_stmt);
5246 modified = true;
5251 if (modified)
5253 /* When changing a call into a noreturn call, cfg cleanup
5254 is needed to fix up the noreturn call. */
5255 if (!was_noreturn
5256 && is_gimple_call (stmt) && gimple_call_noreturn_p (stmt))
5257 to_fixup.safe_push (stmt);
5258 /* When changing a condition or switch into one we know what
5259 edge will be executed, schedule a cfg cleanup. */
5260 if ((gimple_code (stmt) == GIMPLE_COND
5261 && (gimple_cond_true_p (as_a <gcond *> (stmt))
5262 || gimple_cond_false_p (as_a <gcond *> (stmt))))
5263 || (gimple_code (stmt) == GIMPLE_SWITCH
5264 && TREE_CODE (gimple_switch_index
5265 (as_a <gswitch *> (stmt))) == INTEGER_CST))
5266 el_todo |= TODO_cleanup_cfg;
5267 /* If we removed EH side-effects from the statement, clean
5268 its EH information. */
5269 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
5271 bitmap_set_bit (need_eh_cleanup,
5272 gimple_bb (stmt)->index);
5273 if (dump_file && (dump_flags & TDF_DETAILS))
5274 fprintf (dump_file, " Removed EH side-effects.\n");
5276 /* Likewise for AB side-effects. */
5277 if (can_make_abnormal_goto
5278 && !stmt_can_make_abnormal_goto (stmt))
5280 bitmap_set_bit (need_ab_cleanup,
5281 gimple_bb (stmt)->index);
5282 if (dump_file && (dump_flags & TDF_DETAILS))
5283 fprintf (dump_file, " Removed AB side-effects.\n");
5285 update_stmt (stmt);
5286 /* In case the VDEF on the original stmt was released, value-number
5287 it to the VUSE. This is to make vuse_ssa_val able to skip
5288 released virtual operands. */
5289 if (vdef && SSA_NAME_IN_FREE_LIST (vdef))
5290 VN_INFO (vdef)->valnum = vuse;
5293 /* Make new values available - for fully redundant LHS we
5294 continue with the next stmt above and skip this. */
5295 def_operand_p defp;
5296 FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_DEF)
5297 eliminate_push_avail (b, DEF_FROM_PTR (defp));
5300 /* Perform elimination for the basic-block B during the domwalk. */
5302 edge
5303 eliminate_dom_walker::before_dom_children (basic_block b)
5305 /* Mark new bb. */
5306 avail_stack.safe_push (NULL_TREE);
5308 /* Skip unreachable blocks marked unreachable during the SCCVN domwalk. */
5309 if (!(b->flags & BB_EXECUTABLE))
5310 return NULL;
5312 vn_context_bb = b;
5314 for (gphi_iterator gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
5316 gphi *phi = gsi.phi ();
5317 tree res = PHI_RESULT (phi);
5319 if (virtual_operand_p (res))
5321 gsi_next (&gsi);
5322 continue;
5325 tree sprime = eliminate_avail (b, res);
5326 if (sprime
5327 && sprime != res)
5329 if (dump_file && (dump_flags & TDF_DETAILS))
5331 fprintf (dump_file, "Replaced redundant PHI node defining ");
5332 print_generic_expr (dump_file, res);
5333 fprintf (dump_file, " with ");
5334 print_generic_expr (dump_file, sprime);
5335 fprintf (dump_file, "\n");
5338 /* If we inserted this PHI node ourself, it's not an elimination. */
5339 if (! inserted_exprs
5340 || ! bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
5341 eliminations++;
5343 /* If we will propagate into all uses don't bother to do
5344 anything. */
5345 if (may_propagate_copy (res, sprime))
5347 /* Mark the PHI for removal. */
5348 to_remove.safe_push (phi);
5349 gsi_next (&gsi);
5350 continue;
5353 remove_phi_node (&gsi, false);
5355 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
5356 sprime = fold_convert (TREE_TYPE (res), sprime);
5357 gimple *stmt = gimple_build_assign (res, sprime);
5358 gimple_stmt_iterator gsi2 = gsi_after_labels (b);
5359 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
5360 continue;
5363 eliminate_push_avail (b, res);
5364 gsi_next (&gsi);
5367 for (gimple_stmt_iterator gsi = gsi_start_bb (b);
5368 !gsi_end_p (gsi);
5369 gsi_next (&gsi))
5370 eliminate_stmt (b, &gsi);
5372 /* Replace destination PHI arguments. */
5373 edge_iterator ei;
5374 edge e;
5375 FOR_EACH_EDGE (e, ei, b->succs)
5376 if (e->flags & EDGE_EXECUTABLE)
5377 for (gphi_iterator gsi = gsi_start_phis (e->dest);
5378 !gsi_end_p (gsi);
5379 gsi_next (&gsi))
5381 gphi *phi = gsi.phi ();
5382 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
5383 tree arg = USE_FROM_PTR (use_p);
5384 if (TREE_CODE (arg) != SSA_NAME
5385 || virtual_operand_p (arg))
5386 continue;
5387 tree sprime = eliminate_avail (b, arg);
5388 if (sprime && may_propagate_copy (arg, sprime))
5389 propagate_value (use_p, sprime);
5392 vn_context_bb = NULL;
5394 return NULL;
5397 /* Make no longer available leaders no longer available. */
5399 void
5400 eliminate_dom_walker::after_dom_children (basic_block)
5402 tree entry;
5403 while ((entry = avail_stack.pop ()) != NULL_TREE)
5405 tree valnum = VN_INFO (entry)->valnum;
5406 tree old = avail[SSA_NAME_VERSION (valnum)];
5407 if (old == entry)
5408 avail[SSA_NAME_VERSION (valnum)] = NULL_TREE;
5409 else
5410 avail[SSA_NAME_VERSION (valnum)] = entry;
5414 /* Remove queued stmts and perform delayed cleanups. */
5416 unsigned
5417 eliminate_dom_walker::eliminate_cleanup (bool region_p)
5419 statistics_counter_event (cfun, "Eliminated", eliminations);
5420 statistics_counter_event (cfun, "Insertions", insertions);
5422 /* We cannot remove stmts during BB walk, especially not release SSA
5423 names there as this confuses the VN machinery. The stmts ending
5424 up in to_remove are either stores or simple copies.
5425 Remove stmts in reverse order to make debug stmt creation possible. */
5426 while (!to_remove.is_empty ())
5428 bool do_release_defs = true;
5429 gimple *stmt = to_remove.pop ();
5431 /* When we are value-numbering a region we do not require exit PHIs to
5432 be present so we have to make sure to deal with uses outside of the
5433 region of stmts that we thought are eliminated.
5434 ??? Note we may be confused by uses in dead regions we didn't run
5435 elimination on. Rather than checking individual uses we accept
5436 dead copies to be generated here (gcc.c-torture/execute/20060905-1.c
5437 contains such example). */
5438 if (region_p)
5440 if (gphi *phi = dyn_cast <gphi *> (stmt))
5442 tree lhs = gimple_phi_result (phi);
5443 if (!has_zero_uses (lhs))
5445 if (dump_file && (dump_flags & TDF_DETAILS))
5446 fprintf (dump_file, "Keeping eliminated stmt live "
5447 "as copy because of out-of-region uses\n");
5448 tree sprime = eliminate_avail (gimple_bb (stmt), lhs);
5449 gimple *copy = gimple_build_assign (lhs, sprime);
5450 gimple_stmt_iterator gsi
5451 = gsi_after_labels (gimple_bb (stmt));
5452 gsi_insert_before (&gsi, copy, GSI_SAME_STMT);
5453 do_release_defs = false;
5456 else if (tree lhs = gimple_get_lhs (stmt))
5457 if (TREE_CODE (lhs) == SSA_NAME
5458 && !has_zero_uses (lhs))
5460 if (dump_file && (dump_flags & TDF_DETAILS))
5461 fprintf (dump_file, "Keeping eliminated stmt live "
5462 "as copy because of out-of-region uses\n");
5463 tree sprime = eliminate_avail (gimple_bb (stmt), lhs);
5464 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
5465 if (is_gimple_assign (stmt))
5467 gimple_assign_set_rhs_from_tree (&gsi, sprime);
5468 stmt = gsi_stmt (gsi);
5469 update_stmt (stmt);
5470 if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
5471 bitmap_set_bit (need_eh_cleanup, gimple_bb (stmt)->index);
5472 continue;
5474 else
5476 gimple *copy = gimple_build_assign (lhs, sprime);
5477 gsi_insert_before (&gsi, copy, GSI_SAME_STMT);
5478 do_release_defs = false;
5483 if (dump_file && (dump_flags & TDF_DETAILS))
5485 fprintf (dump_file, "Removing dead stmt ");
5486 print_gimple_stmt (dump_file, stmt, 0, TDF_NONE);
5489 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
5490 if (gimple_code (stmt) == GIMPLE_PHI)
5491 remove_phi_node (&gsi, do_release_defs);
5492 else
5494 basic_block bb = gimple_bb (stmt);
5495 unlink_stmt_vdef (stmt);
5496 if (gsi_remove (&gsi, true))
5497 bitmap_set_bit (need_eh_cleanup, bb->index);
5498 if (is_gimple_call (stmt) && stmt_can_make_abnormal_goto (stmt))
5499 bitmap_set_bit (need_ab_cleanup, bb->index);
5500 if (do_release_defs)
5501 release_defs (stmt);
5504 /* Removing a stmt may expose a forwarder block. */
5505 el_todo |= TODO_cleanup_cfg;
5508 /* Fixup stmts that became noreturn calls. This may require splitting
5509 blocks and thus isn't possible during the dominator walk. Do this
5510 in reverse order so we don't inadvertedly remove a stmt we want to
5511 fixup by visiting a dominating now noreturn call first. */
5512 while (!to_fixup.is_empty ())
5514 gimple *stmt = to_fixup.pop ();
5516 if (dump_file && (dump_flags & TDF_DETAILS))
5518 fprintf (dump_file, "Fixing up noreturn call ");
5519 print_gimple_stmt (dump_file, stmt, 0);
5522 if (fixup_noreturn_call (stmt))
5523 el_todo |= TODO_cleanup_cfg;
5526 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
5527 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
5529 if (do_eh_cleanup)
5530 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
5532 if (do_ab_cleanup)
5533 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
5535 if (do_eh_cleanup || do_ab_cleanup)
5536 el_todo |= TODO_cleanup_cfg;
5538 return el_todo;
5541 /* Eliminate fully redundant computations. */
5543 unsigned
5544 eliminate_with_rpo_vn (bitmap inserted_exprs)
5546 eliminate_dom_walker walker (CDI_DOMINATORS, inserted_exprs);
5548 walker.walk (cfun->cfg->x_entry_block_ptr);
5549 return walker.eliminate_cleanup ();
5552 static unsigned
5553 do_rpo_vn (function *fn, edge entry, bitmap exit_bbs,
5554 bool iterate, bool eliminate);
5556 void
5557 run_rpo_vn (vn_lookup_kind kind)
5559 default_vn_walk_kind = kind;
5560 do_rpo_vn (cfun, NULL, NULL, true, false);
5562 /* ??? Prune requirement of these. */
5563 constant_to_value_id = new hash_table<vn_constant_hasher> (23);
5564 constant_value_ids = BITMAP_ALLOC (NULL);
5566 /* Initialize the value ids and prune out remaining VN_TOPs
5567 from dead code. */
5568 tree name;
5569 unsigned i;
5570 FOR_EACH_SSA_NAME (i, name, cfun)
5572 vn_ssa_aux_t info = VN_INFO (name);
5573 if (!info->visited
5574 || info->valnum == VN_TOP)
5575 info->valnum = name;
5576 if (info->valnum == name)
5577 info->value_id = get_next_value_id ();
5578 else if (is_gimple_min_invariant (info->valnum))
5579 info->value_id = get_or_alloc_constant_value_id (info->valnum);
5582 /* Propagate. */
5583 FOR_EACH_SSA_NAME (i, name, cfun)
5585 vn_ssa_aux_t info = VN_INFO (name);
5586 if (TREE_CODE (info->valnum) == SSA_NAME
5587 && info->valnum != name
5588 && info->value_id != VN_INFO (info->valnum)->value_id)
5589 info->value_id = VN_INFO (info->valnum)->value_id;
5592 set_hashtable_value_ids ();
5594 if (dump_file && (dump_flags & TDF_DETAILS))
5596 fprintf (dump_file, "Value numbers:\n");
5597 FOR_EACH_SSA_NAME (i, name, cfun)
5599 if (VN_INFO (name)->visited
5600 && SSA_VAL (name) != name)
5602 print_generic_expr (dump_file, name);
5603 fprintf (dump_file, " = ");
5604 print_generic_expr (dump_file, SSA_VAL (name));
5605 fprintf (dump_file, " (%04d)\n", VN_INFO (name)->value_id);
5611 /* Free VN associated data structures. */
5613 void
5614 free_rpo_vn (void)
5616 free_vn_table (valid_info);
5617 XDELETE (valid_info);
5618 obstack_free (&vn_tables_obstack, NULL);
5619 obstack_free (&vn_tables_insert_obstack, NULL);
5621 vn_ssa_aux_iterator_type it;
5622 vn_ssa_aux_t info;
5623 FOR_EACH_HASH_TABLE_ELEMENT (*vn_ssa_aux_hash, info, vn_ssa_aux_t, it)
5624 if (info->needs_insertion)
5625 release_ssa_name (info->name);
5626 obstack_free (&vn_ssa_aux_obstack, NULL);
5627 delete vn_ssa_aux_hash;
5629 delete constant_to_value_id;
5630 constant_to_value_id = NULL;
5631 BITMAP_FREE (constant_value_ids);
5634 /* Adaptor to the elimination engine using RPO availability. */
5636 class rpo_elim : public eliminate_dom_walker
5638 public:
5639 rpo_elim(basic_block entry_)
5640 : eliminate_dom_walker (CDI_DOMINATORS, NULL), entry (entry_) {}
5641 ~rpo_elim();
5643 virtual tree eliminate_avail (basic_block, tree op);
5645 virtual void eliminate_push_avail (basic_block, tree);
5647 basic_block entry;
5648 /* Instead of having a local availability lattice for each
5649 basic-block and availability at X defined as union of
5650 the local availabilities at X and its dominators we're
5651 turning this upside down and track availability per
5652 value given values are usually made available at very
5653 few points (at least one).
5654 So we have a value -> vec<location, leader> map where
5655 LOCATION is specifying the basic-block LEADER is made
5656 available for VALUE. We push to this vector in RPO
5657 order thus for iteration we can simply pop the last
5658 entries.
5659 LOCATION is the basic-block index and LEADER is its
5660 SSA name version. */
5661 /* ??? We'd like to use auto_vec here with embedded storage
5662 but that doesn't play well until we can provide move
5663 constructors and use std::move on hash-table expansion.
5664 So for now this is a bit more expensive than necessary.
5665 We eventually want to switch to a chaining scheme like
5666 for hashtable entries for unwinding which would make
5667 making the vector part of the vn_ssa_aux structure possible. */
5668 typedef hash_map<tree, vec<std::pair<int, int> > > rpo_avail_t;
5669 rpo_avail_t m_rpo_avail;
5672 /* Global RPO state for access from hooks. */
5673 static rpo_elim *rpo_avail;
5675 /* Hook for maybe_push_res_to_seq, lookup the expression in the VN tables. */
5677 static tree
5678 vn_lookup_simplify_result (gimple_match_op *res_op)
5680 if (!res_op->code.is_tree_code ())
5681 return NULL_TREE;
5682 tree *ops = res_op->ops;
5683 unsigned int length = res_op->num_ops;
5684 if (res_op->code == CONSTRUCTOR
5685 /* ??? We're arriving here with SCCVNs view, decomposed CONSTRUCTOR
5686 and GIMPLEs / match-and-simplifies, CONSTRUCTOR as GENERIC tree. */
5687 && TREE_CODE (res_op->ops[0]) == CONSTRUCTOR)
5689 length = CONSTRUCTOR_NELTS (res_op->ops[0]);
5690 ops = XALLOCAVEC (tree, length);
5691 for (unsigned i = 0; i < length; ++i)
5692 ops[i] = CONSTRUCTOR_ELT (res_op->ops[0], i)->value;
5694 vn_nary_op_t vnresult = NULL;
5695 tree res = vn_nary_op_lookup_pieces (length, (tree_code) res_op->code,
5696 res_op->type, ops, &vnresult);
5697 /* If this is used from expression simplification make sure to
5698 return an available expression. */
5699 if (res && TREE_CODE (res) == SSA_NAME && mprts_hook && rpo_avail)
5700 res = rpo_avail->eliminate_avail (vn_context_bb, res);
5701 return res;
5704 rpo_elim::~rpo_elim ()
5706 /* Release the avail vectors. */
5707 for (rpo_avail_t::iterator i = m_rpo_avail.begin ();
5708 i != m_rpo_avail.end (); ++i)
5709 (*i).second.release ();
5712 /* Return a leader for OPs value that is valid at BB. */
5714 tree
5715 rpo_elim::eliminate_avail (basic_block bb, tree op)
5717 bool visited;
5718 tree valnum = SSA_VAL (op, &visited);
5719 /* If we didn't visit OP then it must be defined outside of the
5720 region we process and also dominate it. So it is available. */
5721 if (!visited)
5722 return op;
5723 if (TREE_CODE (valnum) == SSA_NAME)
5725 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
5726 return valnum;
5727 vec<std::pair<int, int> > *av = m_rpo_avail.get (valnum);
5728 if (!av || av->is_empty ())
5729 return NULL_TREE;
5730 int i = av->length () - 1;
5731 if ((*av)[i].first == bb->index)
5732 /* On tramp3d 90% of the cases are here. */
5733 return ssa_name ((*av)[i].second);
5736 basic_block abb = BASIC_BLOCK_FOR_FN (cfun, (*av)[i].first);
5737 /* ??? During elimination we have to use availability at the
5738 definition site of a use we try to replace. This
5739 is required to not run into inconsistencies because
5740 of dominated_by_p_w_unex behavior and removing a definition
5741 while not replacing all uses.
5742 ??? We could try to consistently walk dominators
5743 ignoring non-executable regions. The nearest common
5744 dominator of bb and abb is where we can stop walking. We
5745 may also be able to "pre-compute" (bits of) the next immediate
5746 (non-)dominator during the RPO walk when marking edges as
5747 executable. */
5748 if (dominated_by_p_w_unex (bb, abb))
5750 tree leader = ssa_name ((*av)[i].second);
5751 /* Prevent eliminations that break loop-closed SSA. */
5752 if (loops_state_satisfies_p (LOOP_CLOSED_SSA)
5753 && ! SSA_NAME_IS_DEFAULT_DEF (leader)
5754 && ! flow_bb_inside_loop_p (gimple_bb (SSA_NAME_DEF_STMT
5755 (leader))->loop_father,
5756 bb))
5757 return NULL_TREE;
5758 if (dump_file && (dump_flags & TDF_DETAILS))
5760 print_generic_expr (dump_file, leader);
5761 fprintf (dump_file, " is available for ");
5762 print_generic_expr (dump_file, valnum);
5763 fprintf (dump_file, "\n");
5765 /* On tramp3d 99% of the _remaining_ cases succeed at
5766 the first enty. */
5767 return leader;
5769 /* ??? Can we somehow skip to the immediate dominator
5770 RPO index (bb_to_rpo)? Again, maybe not worth, on
5771 tramp3d the worst number of elements in the vector is 9. */
5773 while (--i >= 0);
5775 else if (valnum != VN_TOP)
5776 /* valnum is is_gimple_min_invariant. */
5777 return valnum;
5778 return NULL_TREE;
5781 /* Make LEADER a leader for its value at BB. */
5783 void
5784 rpo_elim::eliminate_push_avail (basic_block bb, tree leader)
5786 tree valnum = VN_INFO (leader)->valnum;
5787 if (valnum == VN_TOP)
5788 return;
5789 if (dump_file && (dump_flags & TDF_DETAILS))
5791 fprintf (dump_file, "Making available beyond BB%d ", bb->index);
5792 print_generic_expr (dump_file, leader);
5793 fprintf (dump_file, " for value ");
5794 print_generic_expr (dump_file, valnum);
5795 fprintf (dump_file, "\n");
5797 bool existed;
5798 vec<std::pair<int, int> > &av = m_rpo_avail.get_or_insert (valnum, &existed);
5799 if (!existed)
5801 new (&av) vec<std::pair<int, int> >;
5802 av = vNULL;
5803 av.reserve_exact (2);
5805 av.safe_push (std::make_pair (bb->index, SSA_NAME_VERSION (leader)));
5808 /* Valueization hook for RPO VN plus required state. */
5810 tree
5811 rpo_vn_valueize (tree name)
5813 if (TREE_CODE (name) == SSA_NAME)
5815 vn_ssa_aux_t val = VN_INFO (name);
5816 if (val)
5818 tree tem = val->valnum;
5819 if (tem != VN_TOP && tem != name)
5821 if (TREE_CODE (tem) != SSA_NAME)
5822 return tem;
5823 /* For all values we only valueize to an available leader
5824 which means we can use SSA name info without restriction. */
5825 tem = rpo_avail->eliminate_avail (vn_context_bb, tem);
5826 if (tem)
5827 return tem;
5831 return name;
5834 /* Insert on PRED_E predicates derived from CODE OPS being true besides the
5835 inverted condition. */
5837 static void
5838 insert_related_predicates_on_edge (enum tree_code code, tree *ops, edge pred_e)
5840 switch (code)
5842 case LT_EXPR:
5843 /* a < b -> a {!,<}= b */
5844 vn_nary_op_insert_pieces_predicated (2, NE_EXPR, boolean_type_node,
5845 ops, boolean_true_node, 0, pred_e);
5846 vn_nary_op_insert_pieces_predicated (2, LE_EXPR, boolean_type_node,
5847 ops, boolean_true_node, 0, pred_e);
5848 /* a < b -> ! a {>,=} b */
5849 vn_nary_op_insert_pieces_predicated (2, GT_EXPR, boolean_type_node,
5850 ops, boolean_false_node, 0, pred_e);
5851 vn_nary_op_insert_pieces_predicated (2, EQ_EXPR, boolean_type_node,
5852 ops, boolean_false_node, 0, pred_e);
5853 break;
5854 case GT_EXPR:
5855 /* a > b -> a {!,>}= b */
5856 vn_nary_op_insert_pieces_predicated (2, NE_EXPR, boolean_type_node,
5857 ops, boolean_true_node, 0, pred_e);
5858 vn_nary_op_insert_pieces_predicated (2, GE_EXPR, boolean_type_node,
5859 ops, boolean_true_node, 0, pred_e);
5860 /* a > b -> ! a {<,=} b */
5861 vn_nary_op_insert_pieces_predicated (2, LT_EXPR, boolean_type_node,
5862 ops, boolean_false_node, 0, pred_e);
5863 vn_nary_op_insert_pieces_predicated (2, EQ_EXPR, boolean_type_node,
5864 ops, boolean_false_node, 0, pred_e);
5865 break;
5866 case EQ_EXPR:
5867 /* a == b -> ! a {<,>} b */
5868 vn_nary_op_insert_pieces_predicated (2, LT_EXPR, boolean_type_node,
5869 ops, boolean_false_node, 0, pred_e);
5870 vn_nary_op_insert_pieces_predicated (2, GT_EXPR, boolean_type_node,
5871 ops, boolean_false_node, 0, pred_e);
5872 break;
5873 case LE_EXPR:
5874 case GE_EXPR:
5875 case NE_EXPR:
5876 /* Nothing besides inverted condition. */
5877 break;
5878 default:;
5882 /* Main stmt worker for RPO VN, process BB. */
5884 static unsigned
5885 process_bb (rpo_elim &avail, basic_block bb,
5886 bool bb_visited, bool iterate_phis, bool iterate, bool eliminate,
5887 bool do_region, bitmap exit_bbs)
5889 unsigned todo = 0;
5890 edge_iterator ei;
5891 edge e;
5893 vn_context_bb = bb;
5895 /* If we are in loop-closed SSA preserve this state. This is
5896 relevant when called on regions from outside of FRE/PRE. */
5897 bool lc_phi_nodes = false;
5898 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
5899 FOR_EACH_EDGE (e, ei, bb->preds)
5900 if (e->src->loop_father != e->dest->loop_father
5901 && flow_loop_nested_p (e->dest->loop_father,
5902 e->src->loop_father))
5904 lc_phi_nodes = true;
5905 break;
5908 /* When we visit a loop header substitute into loop info. */
5909 if (!iterate && eliminate && bb->loop_father->header == bb)
5911 /* Keep fields in sync with substitute_in_loop_info. */
5912 if (bb->loop_father->nb_iterations)
5913 bb->loop_father->nb_iterations
5914 = simplify_replace_tree (bb->loop_father->nb_iterations,
5915 NULL_TREE, NULL_TREE, vn_valueize);
5918 /* Value-number all defs in the basic-block. */
5919 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
5920 gsi_next (&gsi))
5922 gphi *phi = gsi.phi ();
5923 tree res = PHI_RESULT (phi);
5924 vn_ssa_aux_t res_info = VN_INFO (res);
5925 if (!bb_visited)
5927 gcc_assert (!res_info->visited);
5928 res_info->valnum = VN_TOP;
5929 res_info->visited = true;
5932 /* When not iterating force backedge values to varying. */
5933 visit_stmt (phi, !iterate_phis);
5934 if (virtual_operand_p (res))
5935 continue;
5937 /* Eliminate */
5938 /* The interesting case is gcc.dg/tree-ssa/pr22230.c for correctness
5939 how we handle backedges and availability.
5940 And gcc.dg/tree-ssa/ssa-sccvn-2.c for optimization. */
5941 tree val = res_info->valnum;
5942 if (res != val && !iterate && eliminate)
5944 if (tree leader = avail.eliminate_avail (bb, res))
5946 if (leader != res
5947 /* Preserve loop-closed SSA form. */
5948 && (! lc_phi_nodes
5949 || is_gimple_min_invariant (leader)))
5951 if (dump_file && (dump_flags & TDF_DETAILS))
5953 fprintf (dump_file, "Replaced redundant PHI node "
5954 "defining ");
5955 print_generic_expr (dump_file, res);
5956 fprintf (dump_file, " with ");
5957 print_generic_expr (dump_file, leader);
5958 fprintf (dump_file, "\n");
5960 avail.eliminations++;
5962 if (may_propagate_copy (res, leader))
5964 /* Schedule for removal. */
5965 avail.to_remove.safe_push (phi);
5966 continue;
5968 /* ??? Else generate a copy stmt. */
5972 /* Only make defs available that not already are. But make
5973 sure loop-closed SSA PHI node defs are picked up for
5974 downstream uses. */
5975 if (lc_phi_nodes
5976 || res == val
5977 || ! avail.eliminate_avail (bb, res))
5978 avail.eliminate_push_avail (bb, res);
5981 /* For empty BBs mark outgoing edges executable. For non-empty BBs
5982 we do this when processing the last stmt as we have to do this
5983 before elimination which otherwise forces GIMPLE_CONDs to
5984 if (1 != 0) style when seeing non-executable edges. */
5985 if (gsi_end_p (gsi_start_bb (bb)))
5987 FOR_EACH_EDGE (e, ei, bb->succs)
5989 if (!(e->flags & EDGE_EXECUTABLE))
5991 if (dump_file && (dump_flags & TDF_DETAILS))
5992 fprintf (dump_file,
5993 "marking outgoing edge %d -> %d executable\n",
5994 e->src->index, e->dest->index);
5995 e->flags |= EDGE_EXECUTABLE;
5996 e->dest->flags |= BB_EXECUTABLE;
5998 else if (!(e->dest->flags & BB_EXECUTABLE))
6000 if (dump_file && (dump_flags & TDF_DETAILS))
6001 fprintf (dump_file,
6002 "marking destination block %d reachable\n",
6003 e->dest->index);
6004 e->dest->flags |= BB_EXECUTABLE;
6008 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
6009 !gsi_end_p (gsi); gsi_next (&gsi))
6011 ssa_op_iter i;
6012 tree op;
6013 if (!bb_visited)
6015 FOR_EACH_SSA_TREE_OPERAND (op, gsi_stmt (gsi), i, SSA_OP_ALL_DEFS)
6017 vn_ssa_aux_t op_info = VN_INFO (op);
6018 gcc_assert (!op_info->visited);
6019 op_info->valnum = VN_TOP;
6020 op_info->visited = true;
6023 /* We somehow have to deal with uses that are not defined
6024 in the processed region. Forcing unvisited uses to
6025 varying here doesn't play well with def-use following during
6026 expression simplification, so we deal with this by checking
6027 the visited flag in SSA_VAL. */
6030 visit_stmt (gsi_stmt (gsi));
6032 gimple *last = gsi_stmt (gsi);
6033 e = NULL;
6034 switch (gimple_code (last))
6036 case GIMPLE_SWITCH:
6037 e = find_taken_edge (bb, vn_valueize (gimple_switch_index
6038 (as_a <gswitch *> (last))));
6039 break;
6040 case GIMPLE_COND:
6042 tree lhs = vn_valueize (gimple_cond_lhs (last));
6043 tree rhs = vn_valueize (gimple_cond_rhs (last));
6044 tree val = gimple_simplify (gimple_cond_code (last),
6045 boolean_type_node, lhs, rhs,
6046 NULL, vn_valueize);
6047 /* If the condition didn't simplfy see if we have recorded
6048 an expression from sofar taken edges. */
6049 if (! val || TREE_CODE (val) != INTEGER_CST)
6051 vn_nary_op_t vnresult;
6052 tree ops[2];
6053 ops[0] = lhs;
6054 ops[1] = rhs;
6055 val = vn_nary_op_lookup_pieces (2, gimple_cond_code (last),
6056 boolean_type_node, ops,
6057 &vnresult);
6058 /* Did we get a predicated value? */
6059 if (! val && vnresult && vnresult->predicated_values)
6061 val = vn_nary_op_get_predicated_value (vnresult, bb);
6062 if (val && dump_file && (dump_flags & TDF_DETAILS))
6064 fprintf (dump_file, "Got predicated value ");
6065 print_generic_expr (dump_file, val, TDF_NONE);
6066 fprintf (dump_file, " for ");
6067 print_gimple_stmt (dump_file, last, TDF_SLIM);
6071 if (val)
6072 e = find_taken_edge (bb, val);
6073 if (! e)
6075 /* If we didn't manage to compute the taken edge then
6076 push predicated expressions for the condition itself
6077 and related conditions to the hashtables. This allows
6078 simplification of redundant conditions which is
6079 important as early cleanup. */
6080 edge true_e, false_e;
6081 extract_true_false_edges_from_block (bb, &true_e, &false_e);
6082 enum tree_code code = gimple_cond_code (last);
6083 enum tree_code icode
6084 = invert_tree_comparison (code, HONOR_NANS (lhs));
6085 tree ops[2];
6086 ops[0] = lhs;
6087 ops[1] = rhs;
6088 if (do_region
6089 && bitmap_bit_p (exit_bbs, true_e->dest->index))
6090 true_e = NULL;
6091 if (do_region
6092 && bitmap_bit_p (exit_bbs, false_e->dest->index))
6093 false_e = NULL;
6094 if (true_e)
6095 vn_nary_op_insert_pieces_predicated
6096 (2, code, boolean_type_node, ops,
6097 boolean_true_node, 0, true_e);
6098 if (false_e)
6099 vn_nary_op_insert_pieces_predicated
6100 (2, code, boolean_type_node, ops,
6101 boolean_false_node, 0, false_e);
6102 if (icode != ERROR_MARK)
6104 if (true_e)
6105 vn_nary_op_insert_pieces_predicated
6106 (2, icode, boolean_type_node, ops,
6107 boolean_false_node, 0, true_e);
6108 if (false_e)
6109 vn_nary_op_insert_pieces_predicated
6110 (2, icode, boolean_type_node, ops,
6111 boolean_true_node, 0, false_e);
6113 /* Relax for non-integers, inverted condition handled
6114 above. */
6115 if (INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
6117 if (true_e)
6118 insert_related_predicates_on_edge (code, ops, true_e);
6119 if (false_e)
6120 insert_related_predicates_on_edge (icode, ops, false_e);
6123 break;
6125 case GIMPLE_GOTO:
6126 e = find_taken_edge (bb, vn_valueize (gimple_goto_dest (last)));
6127 break;
6128 default:
6129 e = NULL;
6131 if (e)
6133 todo = TODO_cleanup_cfg;
6134 if (!(e->flags & EDGE_EXECUTABLE))
6136 if (dump_file && (dump_flags & TDF_DETAILS))
6137 fprintf (dump_file,
6138 "marking known outgoing %sedge %d -> %d executable\n",
6139 e->flags & EDGE_DFS_BACK ? "back-" : "",
6140 e->src->index, e->dest->index);
6141 e->flags |= EDGE_EXECUTABLE;
6142 e->dest->flags |= BB_EXECUTABLE;
6144 else if (!(e->dest->flags & BB_EXECUTABLE))
6146 if (dump_file && (dump_flags & TDF_DETAILS))
6147 fprintf (dump_file,
6148 "marking destination block %d reachable\n",
6149 e->dest->index);
6150 e->dest->flags |= BB_EXECUTABLE;
6153 else if (gsi_one_before_end_p (gsi))
6155 FOR_EACH_EDGE (e, ei, bb->succs)
6157 if (!(e->flags & EDGE_EXECUTABLE))
6159 if (dump_file && (dump_flags & TDF_DETAILS))
6160 fprintf (dump_file,
6161 "marking outgoing edge %d -> %d executable\n",
6162 e->src->index, e->dest->index);
6163 e->flags |= EDGE_EXECUTABLE;
6164 e->dest->flags |= BB_EXECUTABLE;
6166 else if (!(e->dest->flags & BB_EXECUTABLE))
6168 if (dump_file && (dump_flags & TDF_DETAILS))
6169 fprintf (dump_file,
6170 "marking destination block %d reachable\n",
6171 e->dest->index);
6172 e->dest->flags |= BB_EXECUTABLE;
6177 /* Eliminate. That also pushes to avail. */
6178 if (eliminate && ! iterate)
6179 avail.eliminate_stmt (bb, &gsi);
6180 else
6181 /* If not eliminating, make all not already available defs
6182 available. */
6183 FOR_EACH_SSA_TREE_OPERAND (op, gsi_stmt (gsi), i, SSA_OP_DEF)
6184 if (! avail.eliminate_avail (bb, op))
6185 avail.eliminate_push_avail (bb, op);
6188 /* Eliminate in destination PHI arguments. Always substitute in dest
6189 PHIs, even for non-executable edges. This handles region
6190 exits PHIs. */
6191 if (!iterate && eliminate)
6192 FOR_EACH_EDGE (e, ei, bb->succs)
6193 for (gphi_iterator gsi = gsi_start_phis (e->dest);
6194 !gsi_end_p (gsi); gsi_next (&gsi))
6196 gphi *phi = gsi.phi ();
6197 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
6198 tree arg = USE_FROM_PTR (use_p);
6199 if (TREE_CODE (arg) != SSA_NAME
6200 || virtual_operand_p (arg))
6201 continue;
6202 tree sprime;
6203 if (SSA_NAME_IS_DEFAULT_DEF (arg))
6205 sprime = SSA_VAL (arg);
6206 gcc_assert (TREE_CODE (sprime) != SSA_NAME
6207 || SSA_NAME_IS_DEFAULT_DEF (sprime));
6209 else
6210 /* Look for sth available at the definition block of the argument.
6211 This avoids inconsistencies between availability there which
6212 decides if the stmt can be removed and availability at the
6213 use site. The SSA property ensures that things available
6214 at the definition are also available at uses. */
6215 sprime = avail.eliminate_avail (gimple_bb (SSA_NAME_DEF_STMT (arg)),
6216 arg);
6217 if (sprime
6218 && sprime != arg
6219 && may_propagate_copy (arg, sprime))
6220 propagate_value (use_p, sprime);
6223 vn_context_bb = NULL;
6224 return todo;
6227 /* Unwind state per basic-block. */
6229 struct unwind_state
6231 /* Times this block has been visited. */
6232 unsigned visited;
6233 /* Whether to handle this as iteration point or whether to treat
6234 incoming backedge PHI values as varying. */
6235 bool iterate;
6236 /* Maximum RPO index this block is reachable from. */
6237 int max_rpo;
6238 /* Unwind state. */
6239 void *ob_top;
6240 vn_reference_t ref_top;
6241 vn_phi_t phi_top;
6242 vn_nary_op_t nary_top;
6245 /* Unwind the RPO VN state for iteration. */
6247 static void
6248 do_unwind (unwind_state *to, int rpo_idx, rpo_elim &avail, int *bb_to_rpo)
6250 gcc_assert (to->iterate);
6251 for (; last_inserted_nary != to->nary_top;
6252 last_inserted_nary = last_inserted_nary->next)
6254 vn_nary_op_t *slot;
6255 slot = valid_info->nary->find_slot_with_hash
6256 (last_inserted_nary, last_inserted_nary->hashcode, NO_INSERT);
6257 /* Predication causes the need to restore previous state. */
6258 if ((*slot)->unwind_to)
6259 *slot = (*slot)->unwind_to;
6260 else
6261 valid_info->nary->clear_slot (slot);
6263 for (; last_inserted_phi != to->phi_top;
6264 last_inserted_phi = last_inserted_phi->next)
6266 vn_phi_t *slot;
6267 slot = valid_info->phis->find_slot_with_hash
6268 (last_inserted_phi, last_inserted_phi->hashcode, NO_INSERT);
6269 valid_info->phis->clear_slot (slot);
6271 for (; last_inserted_ref != to->ref_top;
6272 last_inserted_ref = last_inserted_ref->next)
6274 vn_reference_t *slot;
6275 slot = valid_info->references->find_slot_with_hash
6276 (last_inserted_ref, last_inserted_ref->hashcode, NO_INSERT);
6277 (*slot)->operands.release ();
6278 valid_info->references->clear_slot (slot);
6280 obstack_free (&vn_tables_obstack, to->ob_top);
6282 /* Prune [rpo_idx, ] from avail. */
6283 /* ??? This is O(number-of-values-in-region) which is
6284 O(region-size) rather than O(iteration-piece). */
6285 for (rpo_elim::rpo_avail_t::iterator i
6286 = avail.m_rpo_avail.begin ();
6287 i != avail.m_rpo_avail.end (); ++i)
6289 while (! (*i).second.is_empty ())
6291 if (bb_to_rpo[(*i).second.last ().first] < rpo_idx)
6292 break;
6293 (*i).second.pop ();
6298 /* Do VN on a SEME region specified by ENTRY and EXIT_BBS in FN.
6299 If ITERATE is true then treat backedges optimistically as not
6300 executed and iterate. If ELIMINATE is true then perform
6301 elimination, otherwise leave that to the caller. */
6303 static unsigned
6304 do_rpo_vn (function *fn, edge entry, bitmap exit_bbs,
6305 bool iterate, bool eliminate)
6307 unsigned todo = 0;
6309 /* We currently do not support region-based iteration when
6310 elimination is requested. */
6311 gcc_assert (!entry || !iterate || !eliminate);
6312 /* When iterating we need loop info up-to-date. */
6313 gcc_assert (!iterate || !loops_state_satisfies_p (LOOPS_NEED_FIXUP));
6315 bool do_region = entry != NULL;
6316 if (!do_region)
6318 entry = single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (fn));
6319 exit_bbs = BITMAP_ALLOC (NULL);
6320 bitmap_set_bit (exit_bbs, EXIT_BLOCK);
6323 int *rpo = XNEWVEC (int, n_basic_blocks_for_fn (fn) - NUM_FIXED_BLOCKS);
6324 int n = rev_post_order_and_mark_dfs_back_seme
6325 (fn, entry, exit_bbs, !loops_state_satisfies_p (LOOPS_NEED_FIXUP), rpo);
6326 /* rev_post_order_and_mark_dfs_back_seme fills RPO in reverse order. */
6327 for (int i = 0; i < n / 2; ++i)
6328 std::swap (rpo[i], rpo[n-i-1]);
6330 if (!do_region)
6331 BITMAP_FREE (exit_bbs);
6333 int *bb_to_rpo = XNEWVEC (int, last_basic_block_for_fn (fn));
6334 for (int i = 0; i < n; ++i)
6335 bb_to_rpo[rpo[i]] = i;
6337 unwind_state *rpo_state = XNEWVEC (unwind_state, n);
6339 rpo_elim avail (entry->dest);
6340 rpo_avail = &avail;
6342 /* Verify we have no extra entries into the region. */
6343 if (flag_checking && do_region)
6345 auto_bb_flag bb_in_region (fn);
6346 for (int i = 0; i < n; ++i)
6348 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
6349 bb->flags |= bb_in_region;
6351 /* We can't merge the first two loops because we cannot rely
6352 on EDGE_DFS_BACK for edges not within the region. But if
6353 we decide to always have the bb_in_region flag we can
6354 do the checking during the RPO walk itself (but then it's
6355 also easy to handle MEME conservatively). */
6356 for (int i = 0; i < n; ++i)
6358 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
6359 edge e;
6360 edge_iterator ei;
6361 FOR_EACH_EDGE (e, ei, bb->preds)
6362 gcc_assert (e == entry || (e->src->flags & bb_in_region));
6364 for (int i = 0; i < n; ++i)
6366 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
6367 bb->flags &= ~bb_in_region;
6371 /* Create the VN state. For the initial size of the various hashtables
6372 use a heuristic based on region size and number of SSA names. */
6373 unsigned region_size = (((unsigned HOST_WIDE_INT)n * num_ssa_names)
6374 / (n_basic_blocks_for_fn (fn) - NUM_FIXED_BLOCKS));
6375 VN_TOP = create_tmp_var_raw (void_type_node, "vn_top");
6377 vn_ssa_aux_hash = new hash_table <vn_ssa_aux_hasher> (region_size * 2);
6378 gcc_obstack_init (&vn_ssa_aux_obstack);
6380 gcc_obstack_init (&vn_tables_obstack);
6381 gcc_obstack_init (&vn_tables_insert_obstack);
6382 valid_info = XCNEW (struct vn_tables_s);
6383 allocate_vn_table (valid_info, region_size);
6384 last_inserted_ref = NULL;
6385 last_inserted_phi = NULL;
6386 last_inserted_nary = NULL;
6388 vn_valueize = rpo_vn_valueize;
6390 /* Initialize the unwind state and edge/BB executable state. */
6391 bool need_max_rpo_iterate = false;
6392 for (int i = 0; i < n; ++i)
6394 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
6395 rpo_state[i].visited = 0;
6396 rpo_state[i].max_rpo = i;
6397 bb->flags &= ~BB_EXECUTABLE;
6398 bool has_backedges = false;
6399 edge e;
6400 edge_iterator ei;
6401 FOR_EACH_EDGE (e, ei, bb->preds)
6403 if (e->flags & EDGE_DFS_BACK)
6404 has_backedges = true;
6405 e->flags &= ~EDGE_EXECUTABLE;
6406 if (iterate || e == entry)
6407 continue;
6408 if (bb_to_rpo[e->src->index] > i)
6410 rpo_state[i].max_rpo = MAX (rpo_state[i].max_rpo,
6411 bb_to_rpo[e->src->index]);
6412 need_max_rpo_iterate = true;
6414 else
6415 rpo_state[i].max_rpo
6416 = MAX (rpo_state[i].max_rpo,
6417 rpo_state[bb_to_rpo[e->src->index]].max_rpo);
6419 rpo_state[i].iterate = iterate && has_backedges;
6421 entry->flags |= EDGE_EXECUTABLE;
6422 entry->dest->flags |= BB_EXECUTABLE;
6424 /* When there are irreducible regions the simplistic max_rpo computation
6425 above for the case of backedges doesn't work and we need to iterate
6426 until there are no more changes. */
6427 unsigned nit = 0;
6428 while (need_max_rpo_iterate)
6430 nit++;
6431 need_max_rpo_iterate = false;
6432 for (int i = 0; i < n; ++i)
6434 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
6435 edge e;
6436 edge_iterator ei;
6437 FOR_EACH_EDGE (e, ei, bb->preds)
6439 if (e == entry)
6440 continue;
6441 int max_rpo = MAX (rpo_state[i].max_rpo,
6442 rpo_state[bb_to_rpo[e->src->index]].max_rpo);
6443 if (rpo_state[i].max_rpo != max_rpo)
6445 rpo_state[i].max_rpo = max_rpo;
6446 need_max_rpo_iterate = true;
6451 statistics_histogram_event (cfun, "RPO max_rpo iterations", nit);
6453 /* As heuristic to improve compile-time we handle only the N innermost
6454 loops and the outermost one optimistically. */
6455 if (iterate)
6457 loop_p loop;
6458 unsigned max_depth = PARAM_VALUE (PARAM_RPO_VN_MAX_LOOP_DEPTH);
6459 FOR_EACH_LOOP (loop, LI_ONLY_INNERMOST)
6460 if (loop_depth (loop) > max_depth)
6461 for (unsigned i = 2;
6462 i < loop_depth (loop) - max_depth; ++i)
6464 basic_block header = superloop_at_depth (loop, i)->header;
6465 bool non_latch_backedge = false;
6466 edge e;
6467 edge_iterator ei;
6468 FOR_EACH_EDGE (e, ei, header->preds)
6469 if (e->flags & EDGE_DFS_BACK)
6471 /* There can be a non-latch backedge into the header
6472 which is part of an outer irreducible region. We
6473 cannot avoid iterating this block then. */
6474 if (!dominated_by_p (CDI_DOMINATORS,
6475 e->src, e->dest))
6477 if (dump_file && (dump_flags & TDF_DETAILS))
6478 fprintf (dump_file, "non-latch backedge %d -> %d "
6479 "forces iteration of loop %d\n",
6480 e->src->index, e->dest->index, loop->num);
6481 non_latch_backedge = true;
6483 else
6484 e->flags |= EDGE_EXECUTABLE;
6486 rpo_state[bb_to_rpo[header->index]].iterate = non_latch_backedge;
6490 uint64_t nblk = 0;
6491 int idx = 0;
6492 if (iterate)
6493 /* Go and process all blocks, iterating as necessary. */
6496 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[idx]);
6498 /* If the block has incoming backedges remember unwind state. This
6499 is required even for non-executable blocks since in irreducible
6500 regions we might reach them via the backedge and re-start iterating
6501 from there.
6502 Note we can individually mark blocks with incoming backedges to
6503 not iterate where we then handle PHIs conservatively. We do that
6504 heuristically to reduce compile-time for degenerate cases. */
6505 if (rpo_state[idx].iterate)
6507 rpo_state[idx].ob_top = obstack_alloc (&vn_tables_obstack, 0);
6508 rpo_state[idx].ref_top = last_inserted_ref;
6509 rpo_state[idx].phi_top = last_inserted_phi;
6510 rpo_state[idx].nary_top = last_inserted_nary;
6513 if (!(bb->flags & BB_EXECUTABLE))
6515 if (dump_file && (dump_flags & TDF_DETAILS))
6516 fprintf (dump_file, "Block %d: BB%d found not executable\n",
6517 idx, bb->index);
6518 idx++;
6519 continue;
6522 if (dump_file && (dump_flags & TDF_DETAILS))
6523 fprintf (dump_file, "Processing block %d: BB%d\n", idx, bb->index);
6524 nblk++;
6525 todo |= process_bb (avail, bb,
6526 rpo_state[idx].visited != 0,
6527 rpo_state[idx].iterate,
6528 iterate, eliminate, do_region, exit_bbs);
6529 rpo_state[idx].visited++;
6531 /* Verify if changed values flow over executable outgoing backedges
6532 and those change destination PHI values (that's the thing we
6533 can easily verify). Reduce over all such edges to the farthest
6534 away PHI. */
6535 int iterate_to = -1;
6536 edge_iterator ei;
6537 edge e;
6538 FOR_EACH_EDGE (e, ei, bb->succs)
6539 if ((e->flags & (EDGE_DFS_BACK|EDGE_EXECUTABLE))
6540 == (EDGE_DFS_BACK|EDGE_EXECUTABLE)
6541 && rpo_state[bb_to_rpo[e->dest->index]].iterate)
6543 int destidx = bb_to_rpo[e->dest->index];
6544 if (!rpo_state[destidx].visited)
6546 if (dump_file && (dump_flags & TDF_DETAILS))
6547 fprintf (dump_file, "Unvisited destination %d\n",
6548 e->dest->index);
6549 if (iterate_to == -1 || destidx < iterate_to)
6550 iterate_to = destidx;
6551 continue;
6553 if (dump_file && (dump_flags & TDF_DETAILS))
6554 fprintf (dump_file, "Looking for changed values of backedge"
6555 " %d->%d destination PHIs\n",
6556 e->src->index, e->dest->index);
6557 vn_context_bb = e->dest;
6558 gphi_iterator gsi;
6559 for (gsi = gsi_start_phis (e->dest);
6560 !gsi_end_p (gsi); gsi_next (&gsi))
6562 bool inserted = false;
6563 /* While we'd ideally just iterate on value changes
6564 we CSE PHIs and do that even across basic-block
6565 boundaries. So even hashtable state changes can
6566 be important (which is roughly equivalent to
6567 PHI argument value changes). To not excessively
6568 iterate because of that we track whether a PHI
6569 was CSEd to with GF_PLF_1. */
6570 bool phival_changed;
6571 if ((phival_changed = visit_phi (gsi.phi (),
6572 &inserted, false))
6573 || (inserted && gimple_plf (gsi.phi (), GF_PLF_1)))
6575 if (!phival_changed
6576 && dump_file && (dump_flags & TDF_DETAILS))
6577 fprintf (dump_file, "PHI was CSEd and hashtable "
6578 "state (changed)\n");
6579 if (iterate_to == -1 || destidx < iterate_to)
6580 iterate_to = destidx;
6581 break;
6584 vn_context_bb = NULL;
6586 if (iterate_to != -1)
6588 do_unwind (&rpo_state[iterate_to], iterate_to, avail, bb_to_rpo);
6589 idx = iterate_to;
6590 if (dump_file && (dump_flags & TDF_DETAILS))
6591 fprintf (dump_file, "Iterating to %d BB%d\n",
6592 iterate_to, rpo[iterate_to]);
6593 continue;
6596 idx++;
6598 while (idx < n);
6600 else /* !iterate */
6602 /* Process all blocks greedily with a worklist that enforces RPO
6603 processing of reachable blocks. */
6604 auto_bitmap worklist;
6605 bitmap_set_bit (worklist, 0);
6606 while (!bitmap_empty_p (worklist))
6608 int idx = bitmap_first_set_bit (worklist);
6609 bitmap_clear_bit (worklist, idx);
6610 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[idx]);
6611 gcc_assert ((bb->flags & BB_EXECUTABLE)
6612 && !rpo_state[idx].visited);
6614 if (dump_file && (dump_flags & TDF_DETAILS))
6615 fprintf (dump_file, "Processing block %d: BB%d\n", idx, bb->index);
6617 /* When we run into predecessor edges where we cannot trust its
6618 executable state mark them executable so PHI processing will
6619 be conservative.
6620 ??? Do we need to force arguments flowing over that edge
6621 to be varying or will they even always be? */
6622 edge_iterator ei;
6623 edge e;
6624 FOR_EACH_EDGE (e, ei, bb->preds)
6625 if (!(e->flags & EDGE_EXECUTABLE)
6626 && !rpo_state[bb_to_rpo[e->src->index]].visited
6627 && rpo_state[bb_to_rpo[e->src->index]].max_rpo >= (int)idx)
6629 if (dump_file && (dump_flags & TDF_DETAILS))
6630 fprintf (dump_file, "Cannot trust state of predecessor "
6631 "edge %d -> %d, marking executable\n",
6632 e->src->index, e->dest->index);
6633 e->flags |= EDGE_EXECUTABLE;
6636 nblk++;
6637 todo |= process_bb (avail, bb, false, false, false, eliminate,
6638 do_region, exit_bbs);
6639 rpo_state[idx].visited++;
6641 FOR_EACH_EDGE (e, ei, bb->succs)
6642 if ((e->flags & EDGE_EXECUTABLE)
6643 && e->dest->index != EXIT_BLOCK
6644 && (!do_region || !bitmap_bit_p (exit_bbs, e->dest->index))
6645 && !rpo_state[bb_to_rpo[e->dest->index]].visited)
6646 bitmap_set_bit (worklist, bb_to_rpo[e->dest->index]);
6650 /* If statistics or dump file active. */
6651 int nex = 0;
6652 unsigned max_visited = 1;
6653 for (int i = 0; i < n; ++i)
6655 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
6656 if (bb->flags & BB_EXECUTABLE)
6657 nex++;
6658 statistics_histogram_event (cfun, "RPO block visited times",
6659 rpo_state[i].visited);
6660 if (rpo_state[i].visited > max_visited)
6661 max_visited = rpo_state[i].visited;
6663 unsigned nvalues = 0, navail = 0;
6664 for (rpo_elim::rpo_avail_t::iterator i = avail.m_rpo_avail.begin ();
6665 i != avail.m_rpo_avail.end (); ++i)
6667 nvalues++;
6668 navail += (*i).second.length ();
6670 statistics_counter_event (cfun, "RPO blocks", n);
6671 statistics_counter_event (cfun, "RPO blocks visited", nblk);
6672 statistics_counter_event (cfun, "RPO blocks executable", nex);
6673 statistics_histogram_event (cfun, "RPO iterations", 10*nblk / nex);
6674 statistics_histogram_event (cfun, "RPO num values", nvalues);
6675 statistics_histogram_event (cfun, "RPO num avail", navail);
6676 statistics_histogram_event (cfun, "RPO num lattice",
6677 vn_ssa_aux_hash->elements ());
6678 if (dump_file && (dump_flags & (TDF_DETAILS|TDF_STATS)))
6680 fprintf (dump_file, "RPO iteration over %d blocks visited %" PRIu64
6681 " blocks in total discovering %d executable blocks iterating "
6682 "%d.%d times, a block was visited max. %u times\n",
6683 n, nblk, nex,
6684 (int)((10*nblk / nex)/10), (int)((10*nblk / nex)%10),
6685 max_visited);
6686 fprintf (dump_file, "RPO tracked %d values available at %d locations "
6687 "and %" PRIu64 " lattice elements\n",
6688 nvalues, navail, (uint64_t) vn_ssa_aux_hash->elements ());
6691 if (eliminate)
6693 /* When !iterate we already performed elimination during the RPO
6694 walk. */
6695 if (iterate)
6697 /* Elimination for region-based VN needs to be done within the
6698 RPO walk. */
6699 gcc_assert (! do_region);
6700 /* Note we can't use avail.walk here because that gets confused
6701 by the existing availability and it will be less efficient
6702 as well. */
6703 todo |= eliminate_with_rpo_vn (NULL);
6705 else
6706 todo |= avail.eliminate_cleanup (do_region);
6709 vn_valueize = NULL;
6710 rpo_avail = NULL;
6712 XDELETEVEC (bb_to_rpo);
6713 XDELETEVEC (rpo);
6714 XDELETEVEC (rpo_state);
6716 return todo;
6719 /* Region-based entry for RPO VN. Performs value-numbering and elimination
6720 on the SEME region specified by ENTRY and EXIT_BBS. */
6722 unsigned
6723 do_rpo_vn (function *fn, edge entry, bitmap exit_bbs)
6725 default_vn_walk_kind = VN_WALKREWRITE;
6726 unsigned todo = do_rpo_vn (fn, entry, exit_bbs, false, true);
6727 free_rpo_vn ();
6728 return todo;
6732 namespace {
6734 const pass_data pass_data_fre =
6736 GIMPLE_PASS, /* type */
6737 "fre", /* name */
6738 OPTGROUP_NONE, /* optinfo_flags */
6739 TV_TREE_FRE, /* tv_id */
6740 ( PROP_cfg | PROP_ssa ), /* properties_required */
6741 0, /* properties_provided */
6742 0, /* properties_destroyed */
6743 0, /* todo_flags_start */
6744 0, /* todo_flags_finish */
6747 class pass_fre : public gimple_opt_pass
6749 public:
6750 pass_fre (gcc::context *ctxt)
6751 : gimple_opt_pass (pass_data_fre, ctxt)
6754 /* opt_pass methods: */
6755 opt_pass * clone () { return new pass_fre (m_ctxt); }
6756 virtual bool gate (function *) { return flag_tree_fre != 0; }
6757 virtual unsigned int execute (function *);
6759 }; // class pass_fre
6761 unsigned int
6762 pass_fre::execute (function *fun)
6764 unsigned todo = 0;
6766 /* At -O[1g] use the cheap non-iterating mode. */
6767 calculate_dominance_info (CDI_DOMINATORS);
6768 if (optimize > 1)
6769 loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
6771 default_vn_walk_kind = VN_WALKREWRITE;
6772 todo = do_rpo_vn (fun, NULL, NULL, optimize > 1, true);
6773 free_rpo_vn ();
6775 if (optimize > 1)
6776 loop_optimizer_finalize ();
6778 return todo;
6781 } // anon namespace
6783 gimple_opt_pass *
6784 make_pass_fre (gcc::context *ctxt)
6786 return new pass_fre (ctxt);
6789 #undef BB_EXECUTABLE