Merge from trunk @222673.
[official-gcc.git] / gcc / gimple-ssa-strength-reduction.c
blob99fbba51a2df7b94fa1ba664c816a234fb56d208
1 /* Straight-line strength reduction.
2 Copyright (C) 2012-2015 Free Software Foundation, Inc.
3 Contributed by Bill Schmidt, IBM <wschmidt@linux.ibm.com>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 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 /* There are many algorithms for performing strength reduction on
22 loops. This is not one of them. IVOPTS handles strength reduction
23 of induction variables just fine. This pass is intended to pick
24 up the crumbs it leaves behind, by considering opportunities for
25 strength reduction along dominator paths.
27 Strength reduction addresses explicit multiplies, and certain
28 multiplies implicit in addressing expressions. It would also be
29 possible to apply strength reduction to divisions and modulos,
30 but such opportunities are relatively uncommon.
32 Strength reduction is also currently restricted to integer operations.
33 If desired, it could be extended to floating-point operations under
34 control of something like -funsafe-math-optimizations. */
36 #include "config.h"
37 #include "system.h"
38 #include "coretypes.h"
39 #include "hash-set.h"
40 #include "machmode.h"
41 #include "vec.h"
42 #include "double-int.h"
43 #include "input.h"
44 #include "alias.h"
45 #include "symtab.h"
46 #include "options.h"
47 #include "wide-int.h"
48 #include "inchash.h"
49 #include "tree.h"
50 #include "fold-const.h"
51 #include "predict.h"
52 #include "tm.h"
53 #include "hard-reg-set.h"
54 #include "function.h"
55 #include "dominance.h"
56 #include "cfg.h"
57 #include "basic-block.h"
58 #include "tree-ssa-alias.h"
59 #include "internal-fn.h"
60 #include "gimple-expr.h"
61 #include "is-a.h"
62 #include "gimple.h"
63 #include "gimple-iterator.h"
64 #include "gimplify-me.h"
65 #include "stor-layout.h"
66 #include "hashtab.h"
67 #include "rtl.h"
68 #include "flags.h"
69 #include "statistics.h"
70 #include "real.h"
71 #include "fixed-value.h"
72 #include "insn-config.h"
73 #include "expmed.h"
74 #include "dojump.h"
75 #include "explow.h"
76 #include "calls.h"
77 #include "emit-rtl.h"
78 #include "varasm.h"
79 #include "stmt.h"
80 #include "expr.h"
81 #include "tree-pass.h"
82 #include "cfgloop.h"
83 #include "gimple-pretty-print.h"
84 #include "gimple-ssa.h"
85 #include "tree-cfg.h"
86 #include "tree-phinodes.h"
87 #include "ssa-iterators.h"
88 #include "stringpool.h"
89 #include "tree-ssanames.h"
90 #include "domwalk.h"
91 #include "params.h"
92 #include "tree-ssa-address.h"
93 #include "tree-affine.h"
94 #include "wide-int-print.h"
95 #include "builtins.h"
97 /* Information about a strength reduction candidate. Each statement
98 in the candidate table represents an expression of one of the
99 following forms (the special case of CAND_REF will be described
100 later):
102 (CAND_MULT) S1: X = (B + i) * S
103 (CAND_ADD) S1: X = B + (i * S)
105 Here X and B are SSA names, i is an integer constant, and S is
106 either an SSA name or a constant. We call B the "base," i the
107 "index", and S the "stride."
109 Any statement S0 that dominates S1 and is of the form:
111 (CAND_MULT) S0: Y = (B + i') * S
112 (CAND_ADD) S0: Y = B + (i' * S)
114 is called a "basis" for S1. In both cases, S1 may be replaced by
116 S1': X = Y + (i - i') * S,
118 where (i - i') * S is folded to the extent possible.
120 All gimple statements are visited in dominator order, and each
121 statement that may contribute to one of the forms of S1 above is
122 given at least one entry in the candidate table. Such statements
123 include addition, pointer addition, subtraction, multiplication,
124 negation, copies, and nontrivial type casts. If a statement may
125 represent more than one expression of the forms of S1 above,
126 multiple "interpretations" are stored in the table and chained
127 together. Examples:
129 * An add of two SSA names may treat either operand as the base.
130 * A multiply of two SSA names, likewise.
131 * A copy or cast may be thought of as either a CAND_MULT with
132 i = 0 and S = 1, or as a CAND_ADD with i = 0 or S = 0.
134 Candidate records are allocated from an obstack. They are addressed
135 both from a hash table keyed on S1, and from a vector of candidate
136 pointers arranged in predominator order.
138 Opportunity note
139 ----------------
140 Currently we don't recognize:
142 S0: Y = (S * i') - B
143 S1: X = (S * i) - B
145 as a strength reduction opportunity, even though this S1 would
146 also be replaceable by the S1' above. This can be added if it
147 comes up in practice.
149 Strength reduction in addressing
150 --------------------------------
151 There is another kind of candidate known as CAND_REF. A CAND_REF
152 describes a statement containing a memory reference having
153 complex addressing that might benefit from strength reduction.
154 Specifically, we are interested in references for which
155 get_inner_reference returns a base address, offset, and bitpos as
156 follows:
158 base: MEM_REF (T1, C1)
159 offset: MULT_EXPR (PLUS_EXPR (T2, C2), C3)
160 bitpos: C4 * BITS_PER_UNIT
162 Here T1 and T2 are arbitrary trees, and C1, C2, C3, C4 are
163 arbitrary integer constants. Note that C2 may be zero, in which
164 case the offset will be MULT_EXPR (T2, C3).
166 When this pattern is recognized, the original memory reference
167 can be replaced with:
169 MEM_REF (POINTER_PLUS_EXPR (T1, MULT_EXPR (T2, C3)),
170 C1 + (C2 * C3) + C4)
172 which distributes the multiply to allow constant folding. When
173 two or more addressing expressions can be represented by MEM_REFs
174 of this form, differing only in the constants C1, C2, and C4,
175 making this substitution produces more efficient addressing during
176 the RTL phases. When there are not at least two expressions with
177 the same values of T1, T2, and C3, there is nothing to be gained
178 by the replacement.
180 Strength reduction of CAND_REFs uses the same infrastructure as
181 that used by CAND_MULTs and CAND_ADDs. We record T1 in the base (B)
182 field, MULT_EXPR (T2, C3) in the stride (S) field, and
183 C1 + (C2 * C3) + C4 in the index (i) field. A basis for a CAND_REF
184 is thus another CAND_REF with the same B and S values. When at
185 least two CAND_REFs are chained together using the basis relation,
186 each of them is replaced as above, resulting in improved code
187 generation for addressing.
189 Conditional candidates
190 ======================
192 Conditional candidates are best illustrated with an example.
193 Consider the code sequence:
195 (1) x_0 = ...;
196 (2) a_0 = x_0 * 5; MULT (B: x_0; i: 0; S: 5)
197 if (...)
198 (3) x_1 = x_0 + 1; ADD (B: x_0, i: 1; S: 1)
199 (4) x_2 = PHI <x_0, x_1>; PHI (B: x_0, i: 0, S: 1)
200 (5) x_3 = x_2 + 1; ADD (B: x_2, i: 1, S: 1)
201 (6) a_1 = x_3 * 5; MULT (B: x_2, i: 1; S: 5)
203 Here strength reduction is complicated by the uncertain value of x_2.
204 A legitimate transformation is:
206 (1) x_0 = ...;
207 (2) a_0 = x_0 * 5;
208 if (...)
210 (3) [x_1 = x_0 + 1;]
211 (3a) t_1 = a_0 + 5;
213 (4) [x_2 = PHI <x_0, x_1>;]
214 (4a) t_2 = PHI <a_0, t_1>;
215 (5) [x_3 = x_2 + 1;]
216 (6r) a_1 = t_2 + 5;
218 where the bracketed instructions may go dead.
220 To recognize this opportunity, we have to observe that statement (6)
221 has a "hidden basis" (2). The hidden basis is unlike a normal basis
222 in that the statement and the hidden basis have different base SSA
223 names (x_2 and x_0, respectively). The relationship is established
224 when a statement's base name (x_2) is defined by a phi statement (4),
225 each argument of which (x_0, x_1) has an identical "derived base name."
226 If the argument is defined by a candidate (as x_1 is by (3)) that is a
227 CAND_ADD having a stride of 1, the derived base name of the argument is
228 the base name of the candidate (x_0). Otherwise, the argument itself
229 is its derived base name (as is the case with argument x_0).
231 The hidden basis for statement (6) is the nearest dominating candidate
232 whose base name is the derived base name (x_0) of the feeding phi (4),
233 and whose stride is identical to that of the statement. We can then
234 create the new "phi basis" (4a) and feeding adds along incoming arcs (3a),
235 allowing the final replacement of (6) by the strength-reduced (6r).
237 To facilitate this, a new kind of candidate (CAND_PHI) is introduced.
238 A CAND_PHI is not a candidate for replacement, but is maintained in the
239 candidate table to ease discovery of hidden bases. Any phi statement
240 whose arguments share a common derived base name is entered into the
241 table with the derived base name, an (arbitrary) index of zero, and a
242 stride of 1. A statement with a hidden basis can then be detected by
243 simply looking up its feeding phi definition in the candidate table,
244 extracting the derived base name, and searching for a basis in the
245 usual manner after substituting the derived base name.
247 Note that the transformation is only valid when the original phi and
248 the statements that define the phi's arguments are all at the same
249 position in the loop hierarchy. */
252 /* Index into the candidate vector, offset by 1. VECs are zero-based,
253 while cand_idx's are one-based, with zero indicating null. */
254 typedef unsigned cand_idx;
256 /* The kind of candidate. */
257 enum cand_kind
259 CAND_MULT,
260 CAND_ADD,
261 CAND_REF,
262 CAND_PHI
265 struct slsr_cand_d
267 /* The candidate statement S1. */
268 gimple cand_stmt;
270 /* The base expression B: often an SSA name, but not always. */
271 tree base_expr;
273 /* The stride S. */
274 tree stride;
276 /* The index constant i. */
277 widest_int index;
279 /* The type of the candidate. This is normally the type of base_expr,
280 but casts may have occurred when combining feeding instructions.
281 A candidate can only be a basis for candidates of the same final type.
282 (For CAND_REFs, this is the type to be used for operand 1 of the
283 replacement MEM_REF.) */
284 tree cand_type;
286 /* The kind of candidate (CAND_MULT, etc.). */
287 enum cand_kind kind;
289 /* Index of this candidate in the candidate vector. */
290 cand_idx cand_num;
292 /* Index of the next candidate record for the same statement.
293 A statement may be useful in more than one way (e.g., due to
294 commutativity). So we can have multiple "interpretations"
295 of a statement. */
296 cand_idx next_interp;
298 /* Index of the basis statement S0, if any, in the candidate vector. */
299 cand_idx basis;
301 /* First candidate for which this candidate is a basis, if one exists. */
302 cand_idx dependent;
304 /* Next candidate having the same basis as this one. */
305 cand_idx sibling;
307 /* If this is a conditional candidate, the CAND_PHI candidate
308 that defines the base SSA name B. */
309 cand_idx def_phi;
311 /* Savings that can be expected from eliminating dead code if this
312 candidate is replaced. */
313 int dead_savings;
316 typedef struct slsr_cand_d slsr_cand, *slsr_cand_t;
317 typedef const struct slsr_cand_d *const_slsr_cand_t;
319 /* Pointers to candidates are chained together as part of a mapping
320 from base expressions to the candidates that use them. */
322 struct cand_chain_d
324 /* Base expression for the chain of candidates: often, but not
325 always, an SSA name. */
326 tree base_expr;
328 /* Pointer to a candidate. */
329 slsr_cand_t cand;
331 /* Chain pointer. */
332 struct cand_chain_d *next;
336 typedef struct cand_chain_d cand_chain, *cand_chain_t;
337 typedef const struct cand_chain_d *const_cand_chain_t;
339 /* Information about a unique "increment" associated with candidates
340 having an SSA name for a stride. An increment is the difference
341 between the index of the candidate and the index of its basis,
342 i.e., (i - i') as discussed in the module commentary.
344 When we are not going to generate address arithmetic we treat
345 increments that differ only in sign as the same, allowing sharing
346 of the cost of initializers. The absolute value of the increment
347 is stored in the incr_info. */
349 struct incr_info_d
351 /* The increment that relates a candidate to its basis. */
352 widest_int incr;
354 /* How many times the increment occurs in the candidate tree. */
355 unsigned count;
357 /* Cost of replacing candidates using this increment. Negative and
358 zero costs indicate replacement should be performed. */
359 int cost;
361 /* If this increment is profitable but is not -1, 0, or 1, it requires
362 an initializer T_0 = stride * incr to be found or introduced in the
363 nearest common dominator of all candidates. This field holds T_0
364 for subsequent use. */
365 tree initializer;
367 /* If the initializer was found to already exist, this is the block
368 where it was found. */
369 basic_block init_bb;
372 typedef struct incr_info_d incr_info, *incr_info_t;
374 /* Candidates are maintained in a vector. If candidate X dominates
375 candidate Y, then X appears before Y in the vector; but the
376 converse does not necessarily hold. */
377 static vec<slsr_cand_t> cand_vec;
379 enum cost_consts
381 COST_NEUTRAL = 0,
382 COST_INFINITE = 1000
385 enum stride_status
387 UNKNOWN_STRIDE = 0,
388 KNOWN_STRIDE = 1
391 enum phi_adjust_status
393 NOT_PHI_ADJUST = 0,
394 PHI_ADJUST = 1
397 enum count_phis_status
399 DONT_COUNT_PHIS = 0,
400 COUNT_PHIS = 1
403 /* Pointer map embodying a mapping from statements to candidates. */
404 static hash_map<gimple, slsr_cand_t> *stmt_cand_map;
406 /* Obstack for candidates. */
407 static struct obstack cand_obstack;
409 /* Obstack for candidate chains. */
410 static struct obstack chain_obstack;
412 /* An array INCR_VEC of incr_infos is used during analysis of related
413 candidates having an SSA name for a stride. INCR_VEC_LEN describes
414 its current length. MAX_INCR_VEC_LEN is used to avoid costly
415 pathological cases. */
416 static incr_info_t incr_vec;
417 static unsigned incr_vec_len;
418 const int MAX_INCR_VEC_LEN = 16;
420 /* For a chain of candidates with unknown stride, indicates whether or not
421 we must generate pointer arithmetic when replacing statements. */
422 static bool address_arithmetic_p;
424 /* Forward function declarations. */
425 static slsr_cand_t base_cand_from_table (tree);
426 static tree introduce_cast_before_cand (slsr_cand_t, tree, tree);
427 static bool legal_cast_p_1 (tree, tree);
429 /* Produce a pointer to the IDX'th candidate in the candidate vector. */
431 static slsr_cand_t
432 lookup_cand (cand_idx idx)
434 return cand_vec[idx - 1];
437 /* Helper for hashing a candidate chain header. */
439 struct cand_chain_hasher : typed_noop_remove <cand_chain>
441 typedef cand_chain *value_type;
442 typedef cand_chain *compare_type;
443 static inline hashval_t hash (const cand_chain *);
444 static inline bool equal (const cand_chain *, const cand_chain *);
447 inline hashval_t
448 cand_chain_hasher::hash (const cand_chain *p)
450 tree base_expr = p->base_expr;
451 return iterative_hash_expr (base_expr, 0);
454 inline bool
455 cand_chain_hasher::equal (const cand_chain *chain1, const cand_chain *chain2)
457 return operand_equal_p (chain1->base_expr, chain2->base_expr, 0);
460 /* Hash table embodying a mapping from base exprs to chains of candidates. */
461 static hash_table<cand_chain_hasher> *base_cand_map;
463 /* Pointer map used by tree_to_aff_combination_expand. */
464 static hash_map<tree, name_expansion *> *name_expansions;
465 /* Pointer map embodying a mapping from bases to alternative bases. */
466 static hash_map<tree, tree> *alt_base_map;
468 /* Given BASE, use the tree affine combiniation facilities to
469 find the underlying tree expression for BASE, with any
470 immediate offset excluded.
472 N.B. we should eliminate this backtracking with better forward
473 analysis in a future release. */
475 static tree
476 get_alternative_base (tree base)
478 tree *result = alt_base_map->get (base);
480 if (result == NULL)
482 tree expr;
483 aff_tree aff;
485 tree_to_aff_combination_expand (base, TREE_TYPE (base),
486 &aff, &name_expansions);
487 aff.offset = 0;
488 expr = aff_combination_to_tree (&aff);
490 gcc_assert (!alt_base_map->put (base, base == expr ? NULL : expr));
492 return expr == base ? NULL : expr;
495 return *result;
498 /* Look in the candidate table for a CAND_PHI that defines BASE and
499 return it if found; otherwise return NULL. */
501 static cand_idx
502 find_phi_def (tree base)
504 slsr_cand_t c;
506 if (TREE_CODE (base) != SSA_NAME)
507 return 0;
509 c = base_cand_from_table (base);
511 if (!c || c->kind != CAND_PHI)
512 return 0;
514 return c->cand_num;
517 /* Helper routine for find_basis_for_candidate. May be called twice:
518 once for the candidate's base expr, and optionally again either for
519 the candidate's phi definition or for a CAND_REF's alternative base
520 expression. */
522 static slsr_cand_t
523 find_basis_for_base_expr (slsr_cand_t c, tree base_expr)
525 cand_chain mapping_key;
526 cand_chain_t chain;
527 slsr_cand_t basis = NULL;
529 // Limit potential of N^2 behavior for long candidate chains.
530 int iters = 0;
531 int max_iters = PARAM_VALUE (PARAM_MAX_SLSR_CANDIDATE_SCAN);
533 mapping_key.base_expr = base_expr;
534 chain = base_cand_map->find (&mapping_key);
536 for (; chain && iters < max_iters; chain = chain->next, ++iters)
538 slsr_cand_t one_basis = chain->cand;
540 if (one_basis->kind != c->kind
541 || one_basis->cand_stmt == c->cand_stmt
542 || !operand_equal_p (one_basis->stride, c->stride, 0)
543 || !types_compatible_p (one_basis->cand_type, c->cand_type)
544 || !dominated_by_p (CDI_DOMINATORS,
545 gimple_bb (c->cand_stmt),
546 gimple_bb (one_basis->cand_stmt)))
547 continue;
549 if (!basis || basis->cand_num < one_basis->cand_num)
550 basis = one_basis;
553 return basis;
556 /* Use the base expr from candidate C to look for possible candidates
557 that can serve as a basis for C. Each potential basis must also
558 appear in a block that dominates the candidate statement and have
559 the same stride and type. If more than one possible basis exists,
560 the one with highest index in the vector is chosen; this will be
561 the most immediately dominating basis. */
563 static int
564 find_basis_for_candidate (slsr_cand_t c)
566 slsr_cand_t basis = find_basis_for_base_expr (c, c->base_expr);
568 /* If a candidate doesn't have a basis using its base expression,
569 it may have a basis hidden by one or more intervening phis. */
570 if (!basis && c->def_phi)
572 basic_block basis_bb, phi_bb;
573 slsr_cand_t phi_cand = lookup_cand (c->def_phi);
574 basis = find_basis_for_base_expr (c, phi_cand->base_expr);
576 if (basis)
578 /* A hidden basis must dominate the phi-definition of the
579 candidate's base name. */
580 phi_bb = gimple_bb (phi_cand->cand_stmt);
581 basis_bb = gimple_bb (basis->cand_stmt);
583 if (phi_bb == basis_bb
584 || !dominated_by_p (CDI_DOMINATORS, phi_bb, basis_bb))
586 basis = NULL;
587 c->basis = 0;
590 /* If we found a hidden basis, estimate additional dead-code
591 savings if the phi and its feeding statements can be removed. */
592 if (basis && has_single_use (gimple_phi_result (phi_cand->cand_stmt)))
593 c->dead_savings += phi_cand->dead_savings;
597 if (flag_expensive_optimizations && !basis && c->kind == CAND_REF)
599 tree alt_base_expr = get_alternative_base (c->base_expr);
600 if (alt_base_expr)
601 basis = find_basis_for_base_expr (c, alt_base_expr);
604 if (basis)
606 c->sibling = basis->dependent;
607 basis->dependent = c->cand_num;
608 return basis->cand_num;
611 return 0;
614 /* Record a mapping from BASE to C, indicating that C may potentially serve
615 as a basis using that base expression. BASE may be the same as
616 C->BASE_EXPR; alternatively BASE can be a different tree that share the
617 underlining expression of C->BASE_EXPR. */
619 static void
620 record_potential_basis (slsr_cand_t c, tree base)
622 cand_chain_t node;
623 cand_chain **slot;
625 gcc_assert (base);
627 node = (cand_chain_t) obstack_alloc (&chain_obstack, sizeof (cand_chain));
628 node->base_expr = base;
629 node->cand = c;
630 node->next = NULL;
631 slot = base_cand_map->find_slot (node, INSERT);
633 if (*slot)
635 cand_chain_t head = (cand_chain_t) (*slot);
636 node->next = head->next;
637 head->next = node;
639 else
640 *slot = node;
643 /* Allocate storage for a new candidate and initialize its fields.
644 Attempt to find a basis for the candidate.
646 For CAND_REF, an alternative base may also be recorded and used
647 to find a basis. This helps cases where the expression hidden
648 behind BASE (which is usually an SSA_NAME) has immediate offset,
649 e.g.
651 a2[i][j] = 1;
652 a2[i + 20][j] = 2; */
654 static slsr_cand_t
655 alloc_cand_and_find_basis (enum cand_kind kind, gimple gs, tree base,
656 const widest_int &index, tree stride, tree ctype,
657 unsigned savings)
659 slsr_cand_t c = (slsr_cand_t) obstack_alloc (&cand_obstack,
660 sizeof (slsr_cand));
661 c->cand_stmt = gs;
662 c->base_expr = base;
663 c->stride = stride;
664 c->index = index;
665 c->cand_type = ctype;
666 c->kind = kind;
667 c->cand_num = cand_vec.length () + 1;
668 c->next_interp = 0;
669 c->dependent = 0;
670 c->sibling = 0;
671 c->def_phi = kind == CAND_MULT ? find_phi_def (base) : 0;
672 c->dead_savings = savings;
674 cand_vec.safe_push (c);
676 if (kind == CAND_PHI)
677 c->basis = 0;
678 else
679 c->basis = find_basis_for_candidate (c);
681 record_potential_basis (c, base);
682 if (flag_expensive_optimizations && kind == CAND_REF)
684 tree alt_base = get_alternative_base (base);
685 if (alt_base)
686 record_potential_basis (c, alt_base);
689 return c;
692 /* Determine the target cost of statement GS when compiling according
693 to SPEED. */
695 static int
696 stmt_cost (gimple gs, bool speed)
698 tree lhs, rhs1, rhs2;
699 machine_mode lhs_mode;
701 gcc_assert (is_gimple_assign (gs));
702 lhs = gimple_assign_lhs (gs);
703 rhs1 = gimple_assign_rhs1 (gs);
704 lhs_mode = TYPE_MODE (TREE_TYPE (lhs));
706 switch (gimple_assign_rhs_code (gs))
708 case MULT_EXPR:
709 rhs2 = gimple_assign_rhs2 (gs);
711 if (tree_fits_shwi_p (rhs2))
712 return mult_by_coeff_cost (tree_to_shwi (rhs2), lhs_mode, speed);
714 gcc_assert (TREE_CODE (rhs1) != INTEGER_CST);
715 return mul_cost (speed, lhs_mode);
717 case PLUS_EXPR:
718 case POINTER_PLUS_EXPR:
719 case MINUS_EXPR:
720 return add_cost (speed, lhs_mode);
722 case NEGATE_EXPR:
723 return neg_cost (speed, lhs_mode);
725 CASE_CONVERT:
726 return convert_cost (lhs_mode, TYPE_MODE (TREE_TYPE (rhs1)), speed);
728 /* Note that we don't assign costs to copies that in most cases
729 will go away. */
730 default:
734 gcc_unreachable ();
735 return 0;
738 /* Look up the defining statement for BASE_IN and return a pointer
739 to its candidate in the candidate table, if any; otherwise NULL.
740 Only CAND_ADD and CAND_MULT candidates are returned. */
742 static slsr_cand_t
743 base_cand_from_table (tree base_in)
745 slsr_cand_t *result;
747 gimple def = SSA_NAME_DEF_STMT (base_in);
748 if (!def)
749 return (slsr_cand_t) NULL;
751 result = stmt_cand_map->get (def);
753 if (result && (*result)->kind != CAND_REF)
754 return *result;
756 return (slsr_cand_t) NULL;
759 /* Add an entry to the statement-to-candidate mapping. */
761 static void
762 add_cand_for_stmt (gimple gs, slsr_cand_t c)
764 gcc_assert (!stmt_cand_map->put (gs, c));
767 /* Given PHI which contains a phi statement, determine whether it
768 satisfies all the requirements of a phi candidate. If so, create
769 a candidate. Note that a CAND_PHI never has a basis itself, but
770 is used to help find a basis for subsequent candidates. */
772 static void
773 slsr_process_phi (gphi *phi, bool speed)
775 unsigned i;
776 tree arg0_base = NULL_TREE, base_type;
777 slsr_cand_t c;
778 struct loop *cand_loop = gimple_bb (phi)->loop_father;
779 unsigned savings = 0;
781 /* A CAND_PHI requires each of its arguments to have the same
782 derived base name. (See the module header commentary for a
783 definition of derived base names.) Furthermore, all feeding
784 definitions must be in the same position in the loop hierarchy
785 as PHI. */
787 for (i = 0; i < gimple_phi_num_args (phi); i++)
789 slsr_cand_t arg_cand;
790 tree arg = gimple_phi_arg_def (phi, i);
791 tree derived_base_name = NULL_TREE;
792 gimple arg_stmt = NULL;
793 basic_block arg_bb = NULL;
795 if (TREE_CODE (arg) != SSA_NAME)
796 return;
798 arg_cand = base_cand_from_table (arg);
800 if (arg_cand)
802 while (arg_cand->kind != CAND_ADD && arg_cand->kind != CAND_PHI)
804 if (!arg_cand->next_interp)
805 return;
807 arg_cand = lookup_cand (arg_cand->next_interp);
810 if (!integer_onep (arg_cand->stride))
811 return;
813 derived_base_name = arg_cand->base_expr;
814 arg_stmt = arg_cand->cand_stmt;
815 arg_bb = gimple_bb (arg_stmt);
817 /* Gather potential dead code savings if the phi statement
818 can be removed later on. */
819 if (has_single_use (arg))
821 if (gimple_code (arg_stmt) == GIMPLE_PHI)
822 savings += arg_cand->dead_savings;
823 else
824 savings += stmt_cost (arg_stmt, speed);
827 else
829 derived_base_name = arg;
831 if (SSA_NAME_IS_DEFAULT_DEF (arg))
832 arg_bb = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
833 else
834 gimple_bb (SSA_NAME_DEF_STMT (arg));
837 if (!arg_bb || arg_bb->loop_father != cand_loop)
838 return;
840 if (i == 0)
841 arg0_base = derived_base_name;
842 else if (!operand_equal_p (derived_base_name, arg0_base, 0))
843 return;
846 /* Create the candidate. "alloc_cand_and_find_basis" is named
847 misleadingly for this case, as no basis will be sought for a
848 CAND_PHI. */
849 base_type = TREE_TYPE (arg0_base);
851 c = alloc_cand_and_find_basis (CAND_PHI, phi, arg0_base,
852 0, integer_one_node, base_type, savings);
854 /* Add the candidate to the statement-candidate mapping. */
855 add_cand_for_stmt (phi, c);
858 /* Given PBASE which is a pointer to tree, look up the defining
859 statement for it and check whether the candidate is in the
860 form of:
862 X = B + (1 * S), S is integer constant
863 X = B + (i * S), S is integer one
865 If so, set PBASE to the candidate's base_expr and return double
866 int (i * S).
867 Otherwise, just return double int zero. */
869 static widest_int
870 backtrace_base_for_ref (tree *pbase)
872 tree base_in = *pbase;
873 slsr_cand_t base_cand;
875 STRIP_NOPS (base_in);
877 /* Strip off widening conversion(s) to handle cases where
878 e.g. 'B' is widened from an 'int' in order to calculate
879 a 64-bit address. */
880 if (CONVERT_EXPR_P (base_in)
881 && legal_cast_p_1 (base_in, TREE_OPERAND (base_in, 0)))
882 base_in = get_unwidened (base_in, NULL_TREE);
884 if (TREE_CODE (base_in) != SSA_NAME)
885 return 0;
887 base_cand = base_cand_from_table (base_in);
889 while (base_cand && base_cand->kind != CAND_PHI)
891 if (base_cand->kind == CAND_ADD
892 && base_cand->index == 1
893 && TREE_CODE (base_cand->stride) == INTEGER_CST)
895 /* X = B + (1 * S), S is integer constant. */
896 *pbase = base_cand->base_expr;
897 return wi::to_widest (base_cand->stride);
899 else if (base_cand->kind == CAND_ADD
900 && TREE_CODE (base_cand->stride) == INTEGER_CST
901 && integer_onep (base_cand->stride))
903 /* X = B + (i * S), S is integer one. */
904 *pbase = base_cand->base_expr;
905 return base_cand->index;
908 if (base_cand->next_interp)
909 base_cand = lookup_cand (base_cand->next_interp);
910 else
911 base_cand = NULL;
914 return 0;
917 /* Look for the following pattern:
919 *PBASE: MEM_REF (T1, C1)
921 *POFFSET: MULT_EXPR (T2, C3) [C2 is zero]
923 MULT_EXPR (PLUS_EXPR (T2, C2), C3)
925 MULT_EXPR (MINUS_EXPR (T2, -C2), C3)
927 *PINDEX: C4 * BITS_PER_UNIT
929 If not present, leave the input values unchanged and return FALSE.
930 Otherwise, modify the input values as follows and return TRUE:
932 *PBASE: T1
933 *POFFSET: MULT_EXPR (T2, C3)
934 *PINDEX: C1 + (C2 * C3) + C4
936 When T2 is recorded by a CAND_ADD in the form of (T2' + C5), it
937 will be further restructured to:
939 *PBASE: T1
940 *POFFSET: MULT_EXPR (T2', C3)
941 *PINDEX: C1 + (C2 * C3) + C4 + (C5 * C3) */
943 static bool
944 restructure_reference (tree *pbase, tree *poffset, widest_int *pindex,
945 tree *ptype)
947 tree base = *pbase, offset = *poffset;
948 widest_int index = *pindex;
949 tree mult_op0, t1, t2, type;
950 widest_int c1, c2, c3, c4, c5;
952 if (!base
953 || !offset
954 || TREE_CODE (base) != MEM_REF
955 || TREE_CODE (offset) != MULT_EXPR
956 || TREE_CODE (TREE_OPERAND (offset, 1)) != INTEGER_CST
957 || wi::umod_floor (index, BITS_PER_UNIT) != 0)
958 return false;
960 t1 = TREE_OPERAND (base, 0);
961 c1 = widest_int::from (mem_ref_offset (base), SIGNED);
962 type = TREE_TYPE (TREE_OPERAND (base, 1));
964 mult_op0 = TREE_OPERAND (offset, 0);
965 c3 = wi::to_widest (TREE_OPERAND (offset, 1));
967 if (TREE_CODE (mult_op0) == PLUS_EXPR)
969 if (TREE_CODE (TREE_OPERAND (mult_op0, 1)) == INTEGER_CST)
971 t2 = TREE_OPERAND (mult_op0, 0);
972 c2 = wi::to_widest (TREE_OPERAND (mult_op0, 1));
974 else
975 return false;
977 else if (TREE_CODE (mult_op0) == MINUS_EXPR)
979 if (TREE_CODE (TREE_OPERAND (mult_op0, 1)) == INTEGER_CST)
981 t2 = TREE_OPERAND (mult_op0, 0);
982 c2 = -wi::to_widest (TREE_OPERAND (mult_op0, 1));
984 else
985 return false;
987 else
989 t2 = mult_op0;
990 c2 = 0;
993 c4 = wi::lrshift (index, LOG2_BITS_PER_UNIT);
994 c5 = backtrace_base_for_ref (&t2);
996 *pbase = t1;
997 *poffset = fold_build2 (MULT_EXPR, sizetype, fold_convert (sizetype, t2),
998 wide_int_to_tree (sizetype, c3));
999 *pindex = c1 + c2 * c3 + c4 + c5 * c3;
1000 *ptype = type;
1002 return true;
1005 /* Given GS which contains a data reference, create a CAND_REF entry in
1006 the candidate table and attempt to find a basis. */
1008 static void
1009 slsr_process_ref (gimple gs)
1011 tree ref_expr, base, offset, type;
1012 HOST_WIDE_INT bitsize, bitpos;
1013 machine_mode mode;
1014 int unsignedp, reversep, volatilep;
1015 slsr_cand_t c;
1017 if (gimple_vdef (gs))
1018 ref_expr = gimple_assign_lhs (gs);
1019 else
1020 ref_expr = gimple_assign_rhs1 (gs);
1022 if (!handled_component_p (ref_expr)
1023 || TREE_CODE (ref_expr) == BIT_FIELD_REF
1024 || (TREE_CODE (ref_expr) == COMPONENT_REF
1025 && DECL_BIT_FIELD (TREE_OPERAND (ref_expr, 1))))
1026 return;
1028 base = get_inner_reference (ref_expr, &bitsize, &bitpos, &offset, &mode,
1029 &unsignedp, &reversep, &volatilep, false);
1030 if (reversep)
1031 return;
1032 widest_int index = bitpos;
1034 if (!restructure_reference (&base, &offset, &index, &type))
1035 return;
1037 c = alloc_cand_and_find_basis (CAND_REF, gs, base, index, offset,
1038 type, 0);
1040 /* Add the candidate to the statement-candidate mapping. */
1041 add_cand_for_stmt (gs, c);
1044 /* Create a candidate entry for a statement GS, where GS multiplies
1045 two SSA names BASE_IN and STRIDE_IN. Propagate any known information
1046 about the two SSA names into the new candidate. Return the new
1047 candidate. */
1049 static slsr_cand_t
1050 create_mul_ssa_cand (gimple gs, tree base_in, tree stride_in, bool speed)
1052 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
1053 widest_int index;
1054 unsigned savings = 0;
1055 slsr_cand_t c;
1056 slsr_cand_t base_cand = base_cand_from_table (base_in);
1058 /* Look at all interpretations of the base candidate, if necessary,
1059 to find information to propagate into this candidate. */
1060 while (base_cand && !base && base_cand->kind != CAND_PHI)
1063 if (base_cand->kind == CAND_MULT && integer_onep (base_cand->stride))
1065 /* Y = (B + i') * 1
1066 X = Y * Z
1067 ================
1068 X = (B + i') * Z */
1069 base = base_cand->base_expr;
1070 index = base_cand->index;
1071 stride = stride_in;
1072 ctype = base_cand->cand_type;
1073 if (has_single_use (base_in))
1074 savings = (base_cand->dead_savings
1075 + stmt_cost (base_cand->cand_stmt, speed));
1077 else if (base_cand->kind == CAND_ADD
1078 && TREE_CODE (base_cand->stride) == INTEGER_CST)
1080 /* Y = B + (i' * S), S constant
1081 X = Y * Z
1082 ============================
1083 X = B + ((i' * S) * Z) */
1084 base = base_cand->base_expr;
1085 index = base_cand->index * wi::to_widest (base_cand->stride);
1086 stride = stride_in;
1087 ctype = base_cand->cand_type;
1088 if (has_single_use (base_in))
1089 savings = (base_cand->dead_savings
1090 + stmt_cost (base_cand->cand_stmt, speed));
1093 if (base_cand->next_interp)
1094 base_cand = lookup_cand (base_cand->next_interp);
1095 else
1096 base_cand = NULL;
1099 if (!base)
1101 /* No interpretations had anything useful to propagate, so
1102 produce X = (Y + 0) * Z. */
1103 base = base_in;
1104 index = 0;
1105 stride = stride_in;
1106 ctype = TREE_TYPE (base_in);
1109 c = alloc_cand_and_find_basis (CAND_MULT, gs, base, index, stride,
1110 ctype, savings);
1111 return c;
1114 /* Create a candidate entry for a statement GS, where GS multiplies
1115 SSA name BASE_IN by constant STRIDE_IN. Propagate any known
1116 information about BASE_IN into the new candidate. Return the new
1117 candidate. */
1119 static slsr_cand_t
1120 create_mul_imm_cand (gimple gs, tree base_in, tree stride_in, bool speed)
1122 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
1123 widest_int index, temp;
1124 unsigned savings = 0;
1125 slsr_cand_t c;
1126 slsr_cand_t base_cand = base_cand_from_table (base_in);
1128 /* Look at all interpretations of the base candidate, if necessary,
1129 to find information to propagate into this candidate. */
1130 while (base_cand && !base && base_cand->kind != CAND_PHI)
1132 if (base_cand->kind == CAND_MULT
1133 && TREE_CODE (base_cand->stride) == INTEGER_CST)
1135 /* Y = (B + i') * S, S constant
1136 X = Y * c
1137 ============================
1138 X = (B + i') * (S * c) */
1139 temp = wi::to_widest (base_cand->stride) * wi::to_widest (stride_in);
1140 if (wi::fits_to_tree_p (temp, TREE_TYPE (stride_in)))
1142 base = base_cand->base_expr;
1143 index = base_cand->index;
1144 stride = wide_int_to_tree (TREE_TYPE (stride_in), temp);
1145 ctype = base_cand->cand_type;
1146 if (has_single_use (base_in))
1147 savings = (base_cand->dead_savings
1148 + stmt_cost (base_cand->cand_stmt, speed));
1151 else if (base_cand->kind == CAND_ADD && integer_onep (base_cand->stride))
1153 /* Y = B + (i' * 1)
1154 X = Y * c
1155 ===========================
1156 X = (B + i') * c */
1157 base = base_cand->base_expr;
1158 index = base_cand->index;
1159 stride = stride_in;
1160 ctype = base_cand->cand_type;
1161 if (has_single_use (base_in))
1162 savings = (base_cand->dead_savings
1163 + stmt_cost (base_cand->cand_stmt, speed));
1165 else if (base_cand->kind == CAND_ADD
1166 && base_cand->index == 1
1167 && TREE_CODE (base_cand->stride) == INTEGER_CST)
1169 /* Y = B + (1 * S), S constant
1170 X = Y * c
1171 ===========================
1172 X = (B + S) * c */
1173 base = base_cand->base_expr;
1174 index = wi::to_widest (base_cand->stride);
1175 stride = stride_in;
1176 ctype = base_cand->cand_type;
1177 if (has_single_use (base_in))
1178 savings = (base_cand->dead_savings
1179 + stmt_cost (base_cand->cand_stmt, speed));
1182 if (base_cand->next_interp)
1183 base_cand = lookup_cand (base_cand->next_interp);
1184 else
1185 base_cand = NULL;
1188 if (!base)
1190 /* No interpretations had anything useful to propagate, so
1191 produce X = (Y + 0) * c. */
1192 base = base_in;
1193 index = 0;
1194 stride = stride_in;
1195 ctype = TREE_TYPE (base_in);
1198 c = alloc_cand_and_find_basis (CAND_MULT, gs, base, index, stride,
1199 ctype, savings);
1200 return c;
1203 /* Given GS which is a multiply of scalar integers, make an appropriate
1204 entry in the candidate table. If this is a multiply of two SSA names,
1205 create two CAND_MULT interpretations and attempt to find a basis for
1206 each of them. Otherwise, create a single CAND_MULT and attempt to
1207 find a basis. */
1209 static void
1210 slsr_process_mul (gimple gs, tree rhs1, tree rhs2, bool speed)
1212 slsr_cand_t c, c2;
1214 /* If this is a multiply of an SSA name with itself, it is highly
1215 unlikely that we will get a strength reduction opportunity, so
1216 don't record it as a candidate. This simplifies the logic for
1217 finding a basis, so if this is removed that must be considered. */
1218 if (rhs1 == rhs2)
1219 return;
1221 if (TREE_CODE (rhs2) == SSA_NAME)
1223 /* Record an interpretation of this statement in the candidate table
1224 assuming RHS1 is the base expression and RHS2 is the stride. */
1225 c = create_mul_ssa_cand (gs, rhs1, rhs2, speed);
1227 /* Add the first interpretation to the statement-candidate mapping. */
1228 add_cand_for_stmt (gs, c);
1230 /* Record another interpretation of this statement assuming RHS1
1231 is the stride and RHS2 is the base expression. */
1232 c2 = create_mul_ssa_cand (gs, rhs2, rhs1, speed);
1233 c->next_interp = c2->cand_num;
1235 else
1237 /* Record an interpretation for the multiply-immediate. */
1238 c = create_mul_imm_cand (gs, rhs1, rhs2, speed);
1240 /* Add the interpretation to the statement-candidate mapping. */
1241 add_cand_for_stmt (gs, c);
1245 /* Create a candidate entry for a statement GS, where GS adds two
1246 SSA names BASE_IN and ADDEND_IN if SUBTRACT_P is false, and
1247 subtracts ADDEND_IN from BASE_IN otherwise. Propagate any known
1248 information about the two SSA names into the new candidate.
1249 Return the new candidate. */
1251 static slsr_cand_t
1252 create_add_ssa_cand (gimple gs, tree base_in, tree addend_in,
1253 bool subtract_p, bool speed)
1255 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL;
1256 widest_int index;
1257 unsigned savings = 0;
1258 slsr_cand_t c;
1259 slsr_cand_t base_cand = base_cand_from_table (base_in);
1260 slsr_cand_t addend_cand = base_cand_from_table (addend_in);
1262 /* The most useful transformation is a multiply-immediate feeding
1263 an add or subtract. Look for that first. */
1264 while (addend_cand && !base && addend_cand->kind != CAND_PHI)
1266 if (addend_cand->kind == CAND_MULT
1267 && addend_cand->index == 0
1268 && TREE_CODE (addend_cand->stride) == INTEGER_CST)
1270 /* Z = (B + 0) * S, S constant
1271 X = Y +/- Z
1272 ===========================
1273 X = Y + ((+/-1 * S) * B) */
1274 base = base_in;
1275 index = wi::to_widest (addend_cand->stride);
1276 if (subtract_p)
1277 index = -index;
1278 stride = addend_cand->base_expr;
1279 ctype = TREE_TYPE (base_in);
1280 if (has_single_use (addend_in))
1281 savings = (addend_cand->dead_savings
1282 + stmt_cost (addend_cand->cand_stmt, speed));
1285 if (addend_cand->next_interp)
1286 addend_cand = lookup_cand (addend_cand->next_interp);
1287 else
1288 addend_cand = NULL;
1291 while (base_cand && !base && base_cand->kind != CAND_PHI)
1293 if (base_cand->kind == CAND_ADD
1294 && (base_cand->index == 0
1295 || operand_equal_p (base_cand->stride,
1296 integer_zero_node, 0)))
1298 /* Y = B + (i' * S), i' * S = 0
1299 X = Y +/- Z
1300 ============================
1301 X = B + (+/-1 * Z) */
1302 base = base_cand->base_expr;
1303 index = subtract_p ? -1 : 1;
1304 stride = addend_in;
1305 ctype = base_cand->cand_type;
1306 if (has_single_use (base_in))
1307 savings = (base_cand->dead_savings
1308 + stmt_cost (base_cand->cand_stmt, speed));
1310 else if (subtract_p)
1312 slsr_cand_t subtrahend_cand = base_cand_from_table (addend_in);
1314 while (subtrahend_cand && !base && subtrahend_cand->kind != CAND_PHI)
1316 if (subtrahend_cand->kind == CAND_MULT
1317 && subtrahend_cand->index == 0
1318 && TREE_CODE (subtrahend_cand->stride) == INTEGER_CST)
1320 /* Z = (B + 0) * S, S constant
1321 X = Y - Z
1322 ===========================
1323 Value: X = Y + ((-1 * S) * B) */
1324 base = base_in;
1325 index = wi::to_widest (subtrahend_cand->stride);
1326 index = -index;
1327 stride = subtrahend_cand->base_expr;
1328 ctype = TREE_TYPE (base_in);
1329 if (has_single_use (addend_in))
1330 savings = (subtrahend_cand->dead_savings
1331 + stmt_cost (subtrahend_cand->cand_stmt, speed));
1334 if (subtrahend_cand->next_interp)
1335 subtrahend_cand = lookup_cand (subtrahend_cand->next_interp);
1336 else
1337 subtrahend_cand = NULL;
1341 if (base_cand->next_interp)
1342 base_cand = lookup_cand (base_cand->next_interp);
1343 else
1344 base_cand = NULL;
1347 if (!base)
1349 /* No interpretations had anything useful to propagate, so
1350 produce X = Y + (1 * Z). */
1351 base = base_in;
1352 index = subtract_p ? -1 : 1;
1353 stride = addend_in;
1354 ctype = TREE_TYPE (base_in);
1357 c = alloc_cand_and_find_basis (CAND_ADD, gs, base, index, stride,
1358 ctype, savings);
1359 return c;
1362 /* Create a candidate entry for a statement GS, where GS adds SSA
1363 name BASE_IN to constant INDEX_IN. Propagate any known information
1364 about BASE_IN into the new candidate. Return the new candidate. */
1366 static slsr_cand_t
1367 create_add_imm_cand (gimple gs, tree base_in, const widest_int &index_in,
1368 bool speed)
1370 enum cand_kind kind = CAND_ADD;
1371 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
1372 widest_int index, multiple;
1373 unsigned savings = 0;
1374 slsr_cand_t c;
1375 slsr_cand_t base_cand = base_cand_from_table (base_in);
1377 while (base_cand && !base && base_cand->kind != CAND_PHI)
1379 signop sign = TYPE_SIGN (TREE_TYPE (base_cand->stride));
1381 if (TREE_CODE (base_cand->stride) == INTEGER_CST
1382 && wi::multiple_of_p (index_in, wi::to_widest (base_cand->stride),
1383 sign, &multiple))
1385 /* Y = (B + i') * S, S constant, c = kS for some integer k
1386 X = Y + c
1387 ============================
1388 X = (B + (i'+ k)) * S
1390 Y = B + (i' * S), S constant, c = kS for some integer k
1391 X = Y + c
1392 ============================
1393 X = (B + (i'+ k)) * S */
1394 kind = base_cand->kind;
1395 base = base_cand->base_expr;
1396 index = base_cand->index + multiple;
1397 stride = base_cand->stride;
1398 ctype = base_cand->cand_type;
1399 if (has_single_use (base_in))
1400 savings = (base_cand->dead_savings
1401 + stmt_cost (base_cand->cand_stmt, speed));
1404 if (base_cand->next_interp)
1405 base_cand = lookup_cand (base_cand->next_interp);
1406 else
1407 base_cand = NULL;
1410 if (!base)
1412 /* No interpretations had anything useful to propagate, so
1413 produce X = Y + (c * 1). */
1414 kind = CAND_ADD;
1415 base = base_in;
1416 index = index_in;
1417 stride = integer_one_node;
1418 ctype = TREE_TYPE (base_in);
1421 c = alloc_cand_and_find_basis (kind, gs, base, index, stride,
1422 ctype, savings);
1423 return c;
1426 /* Given GS which is an add or subtract of scalar integers or pointers,
1427 make at least one appropriate entry in the candidate table. */
1429 static void
1430 slsr_process_add (gimple gs, tree rhs1, tree rhs2, bool speed)
1432 bool subtract_p = gimple_assign_rhs_code (gs) == MINUS_EXPR;
1433 slsr_cand_t c = NULL, c2;
1435 if (TREE_CODE (rhs2) == SSA_NAME)
1437 /* First record an interpretation assuming RHS1 is the base expression
1438 and RHS2 is the stride. But it doesn't make sense for the
1439 stride to be a pointer, so don't record a candidate in that case. */
1440 if (!POINTER_TYPE_P (TREE_TYPE (rhs2)))
1442 c = create_add_ssa_cand (gs, rhs1, rhs2, subtract_p, speed);
1444 /* Add the first interpretation to the statement-candidate
1445 mapping. */
1446 add_cand_for_stmt (gs, c);
1449 /* If the two RHS operands are identical, or this is a subtract,
1450 we're done. */
1451 if (operand_equal_p (rhs1, rhs2, 0) || subtract_p)
1452 return;
1454 /* Otherwise, record another interpretation assuming RHS2 is the
1455 base expression and RHS1 is the stride, again provided that the
1456 stride is not a pointer. */
1457 if (!POINTER_TYPE_P (TREE_TYPE (rhs1)))
1459 c2 = create_add_ssa_cand (gs, rhs2, rhs1, false, speed);
1460 if (c)
1461 c->next_interp = c2->cand_num;
1462 else
1463 add_cand_for_stmt (gs, c2);
1466 else
1468 /* Record an interpretation for the add-immediate. */
1469 widest_int index = wi::to_widest (rhs2);
1470 if (subtract_p)
1471 index = -index;
1473 c = create_add_imm_cand (gs, rhs1, index, speed);
1475 /* Add the interpretation to the statement-candidate mapping. */
1476 add_cand_for_stmt (gs, c);
1480 /* Given GS which is a negate of a scalar integer, make an appropriate
1481 entry in the candidate table. A negate is equivalent to a multiply
1482 by -1. */
1484 static void
1485 slsr_process_neg (gimple gs, tree rhs1, bool speed)
1487 /* Record a CAND_MULT interpretation for the multiply by -1. */
1488 slsr_cand_t c = create_mul_imm_cand (gs, rhs1, integer_minus_one_node, speed);
1490 /* Add the interpretation to the statement-candidate mapping. */
1491 add_cand_for_stmt (gs, c);
1494 /* Help function for legal_cast_p, operating on two trees. Checks
1495 whether it's allowable to cast from RHS to LHS. See legal_cast_p
1496 for more details. */
1498 static bool
1499 legal_cast_p_1 (tree lhs, tree rhs)
1501 tree lhs_type, rhs_type;
1502 unsigned lhs_size, rhs_size;
1503 bool lhs_wraps, rhs_wraps;
1505 lhs_type = TREE_TYPE (lhs);
1506 rhs_type = TREE_TYPE (rhs);
1507 lhs_size = TYPE_PRECISION (lhs_type);
1508 rhs_size = TYPE_PRECISION (rhs_type);
1509 lhs_wraps = ANY_INTEGRAL_TYPE_P (lhs_type) && TYPE_OVERFLOW_WRAPS (lhs_type);
1510 rhs_wraps = ANY_INTEGRAL_TYPE_P (rhs_type) && TYPE_OVERFLOW_WRAPS (rhs_type);
1512 if (lhs_size < rhs_size
1513 || (rhs_wraps && !lhs_wraps)
1514 || (rhs_wraps && lhs_wraps && rhs_size != lhs_size))
1515 return false;
1517 return true;
1520 /* Return TRUE if GS is a statement that defines an SSA name from
1521 a conversion and is legal for us to combine with an add and multiply
1522 in the candidate table. For example, suppose we have:
1524 A = B + i;
1525 C = (type) A;
1526 D = C * S;
1528 Without the type-cast, we would create a CAND_MULT for D with base B,
1529 index i, and stride S. We want to record this candidate only if it
1530 is equivalent to apply the type cast following the multiply:
1532 A = B + i;
1533 E = A * S;
1534 D = (type) E;
1536 We will record the type with the candidate for D. This allows us
1537 to use a similar previous candidate as a basis. If we have earlier seen
1539 A' = B + i';
1540 C' = (type) A';
1541 D' = C' * S;
1543 we can replace D with
1545 D = D' + (i - i') * S;
1547 But if moving the type-cast would change semantics, we mustn't do this.
1549 This is legitimate for casts from a non-wrapping integral type to
1550 any integral type of the same or larger size. It is not legitimate
1551 to convert a wrapping type to a non-wrapping type, or to a wrapping
1552 type of a different size. I.e., with a wrapping type, we must
1553 assume that the addition B + i could wrap, in which case performing
1554 the multiply before or after one of the "illegal" type casts will
1555 have different semantics. */
1557 static bool
1558 legal_cast_p (gimple gs, tree rhs)
1560 if (!is_gimple_assign (gs)
1561 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (gs)))
1562 return false;
1564 return legal_cast_p_1 (gimple_assign_lhs (gs), rhs);
1567 /* Given GS which is a cast to a scalar integer type, determine whether
1568 the cast is legal for strength reduction. If so, make at least one
1569 appropriate entry in the candidate table. */
1571 static void
1572 slsr_process_cast (gimple gs, tree rhs1, bool speed)
1574 tree lhs, ctype;
1575 slsr_cand_t base_cand, c, c2;
1576 unsigned savings = 0;
1578 if (!legal_cast_p (gs, rhs1))
1579 return;
1581 lhs = gimple_assign_lhs (gs);
1582 base_cand = base_cand_from_table (rhs1);
1583 ctype = TREE_TYPE (lhs);
1585 if (base_cand && base_cand->kind != CAND_PHI)
1587 while (base_cand)
1589 /* Propagate all data from the base candidate except the type,
1590 which comes from the cast, and the base candidate's cast,
1591 which is no longer applicable. */
1592 if (has_single_use (rhs1))
1593 savings = (base_cand->dead_savings
1594 + stmt_cost (base_cand->cand_stmt, speed));
1596 c = alloc_cand_and_find_basis (base_cand->kind, gs,
1597 base_cand->base_expr,
1598 base_cand->index, base_cand->stride,
1599 ctype, savings);
1600 if (base_cand->next_interp)
1601 base_cand = lookup_cand (base_cand->next_interp);
1602 else
1603 base_cand = NULL;
1606 else
1608 /* If nothing is known about the RHS, create fresh CAND_ADD and
1609 CAND_MULT interpretations:
1611 X = Y + (0 * 1)
1612 X = (Y + 0) * 1
1614 The first of these is somewhat arbitrary, but the choice of
1615 1 for the stride simplifies the logic for propagating casts
1616 into their uses. */
1617 c = alloc_cand_and_find_basis (CAND_ADD, gs, rhs1,
1618 0, integer_one_node, ctype, 0);
1619 c2 = alloc_cand_and_find_basis (CAND_MULT, gs, rhs1,
1620 0, integer_one_node, ctype, 0);
1621 c->next_interp = c2->cand_num;
1624 /* Add the first (or only) interpretation to the statement-candidate
1625 mapping. */
1626 add_cand_for_stmt (gs, c);
1629 /* Given GS which is a copy of a scalar integer type, make at least one
1630 appropriate entry in the candidate table.
1632 This interface is included for completeness, but is unnecessary
1633 if this pass immediately follows a pass that performs copy
1634 propagation, such as DOM. */
1636 static void
1637 slsr_process_copy (gimple gs, tree rhs1, bool speed)
1639 slsr_cand_t base_cand, c, c2;
1640 unsigned savings = 0;
1642 base_cand = base_cand_from_table (rhs1);
1644 if (base_cand && base_cand->kind != CAND_PHI)
1646 while (base_cand)
1648 /* Propagate all data from the base candidate. */
1649 if (has_single_use (rhs1))
1650 savings = (base_cand->dead_savings
1651 + stmt_cost (base_cand->cand_stmt, speed));
1653 c = alloc_cand_and_find_basis (base_cand->kind, gs,
1654 base_cand->base_expr,
1655 base_cand->index, base_cand->stride,
1656 base_cand->cand_type, savings);
1657 if (base_cand->next_interp)
1658 base_cand = lookup_cand (base_cand->next_interp);
1659 else
1660 base_cand = NULL;
1663 else
1665 /* If nothing is known about the RHS, create fresh CAND_ADD and
1666 CAND_MULT interpretations:
1668 X = Y + (0 * 1)
1669 X = (Y + 0) * 1
1671 The first of these is somewhat arbitrary, but the choice of
1672 1 for the stride simplifies the logic for propagating casts
1673 into their uses. */
1674 c = alloc_cand_and_find_basis (CAND_ADD, gs, rhs1,
1675 0, integer_one_node, TREE_TYPE (rhs1), 0);
1676 c2 = alloc_cand_and_find_basis (CAND_MULT, gs, rhs1,
1677 0, integer_one_node, TREE_TYPE (rhs1), 0);
1678 c->next_interp = c2->cand_num;
1681 /* Add the first (or only) interpretation to the statement-candidate
1682 mapping. */
1683 add_cand_for_stmt (gs, c);
1686 class find_candidates_dom_walker : public dom_walker
1688 public:
1689 find_candidates_dom_walker (cdi_direction direction)
1690 : dom_walker (direction) {}
1691 virtual void before_dom_children (basic_block);
1694 /* Find strength-reduction candidates in block BB. */
1696 void
1697 find_candidates_dom_walker::before_dom_children (basic_block bb)
1699 bool speed = optimize_bb_for_speed_p (bb);
1701 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1702 gsi_next (&gsi))
1703 slsr_process_phi (gsi.phi (), speed);
1705 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
1706 gsi_next (&gsi))
1708 gimple gs = gsi_stmt (gsi);
1710 if (gimple_vuse (gs) && gimple_assign_single_p (gs))
1711 slsr_process_ref (gs);
1713 else if (is_gimple_assign (gs)
1714 && SCALAR_INT_MODE_P
1715 (TYPE_MODE (TREE_TYPE (gimple_assign_lhs (gs)))))
1717 tree rhs1 = NULL_TREE, rhs2 = NULL_TREE;
1719 switch (gimple_assign_rhs_code (gs))
1721 case MULT_EXPR:
1722 case PLUS_EXPR:
1723 rhs1 = gimple_assign_rhs1 (gs);
1724 rhs2 = gimple_assign_rhs2 (gs);
1725 /* Should never happen, but currently some buggy situations
1726 in earlier phases put constants in rhs1. */
1727 if (TREE_CODE (rhs1) != SSA_NAME)
1728 continue;
1729 break;
1731 /* Possible future opportunity: rhs1 of a ptr+ can be
1732 an ADDR_EXPR. */
1733 case POINTER_PLUS_EXPR:
1734 case MINUS_EXPR:
1735 rhs2 = gimple_assign_rhs2 (gs);
1736 /* Fall-through. */
1738 CASE_CONVERT:
1739 case MODIFY_EXPR:
1740 case NEGATE_EXPR:
1741 rhs1 = gimple_assign_rhs1 (gs);
1742 if (TREE_CODE (rhs1) != SSA_NAME)
1743 continue;
1744 break;
1746 default:
1750 switch (gimple_assign_rhs_code (gs))
1752 case MULT_EXPR:
1753 slsr_process_mul (gs, rhs1, rhs2, speed);
1754 break;
1756 case PLUS_EXPR:
1757 case POINTER_PLUS_EXPR:
1758 case MINUS_EXPR:
1759 slsr_process_add (gs, rhs1, rhs2, speed);
1760 break;
1762 case NEGATE_EXPR:
1763 slsr_process_neg (gs, rhs1, speed);
1764 break;
1766 CASE_CONVERT:
1767 slsr_process_cast (gs, rhs1, speed);
1768 break;
1770 case MODIFY_EXPR:
1771 slsr_process_copy (gs, rhs1, speed);
1772 break;
1774 default:
1781 /* Dump a candidate for debug. */
1783 static void
1784 dump_candidate (slsr_cand_t c)
1786 fprintf (dump_file, "%3d [%d] ", c->cand_num,
1787 gimple_bb (c->cand_stmt)->index);
1788 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
1789 switch (c->kind)
1791 case CAND_MULT:
1792 fputs (" MULT : (", dump_file);
1793 print_generic_expr (dump_file, c->base_expr, 0);
1794 fputs (" + ", dump_file);
1795 print_decs (c->index, dump_file);
1796 fputs (") * ", dump_file);
1797 print_generic_expr (dump_file, c->stride, 0);
1798 fputs (" : ", dump_file);
1799 break;
1800 case CAND_ADD:
1801 fputs (" ADD : ", dump_file);
1802 print_generic_expr (dump_file, c->base_expr, 0);
1803 fputs (" + (", dump_file);
1804 print_decs (c->index, dump_file);
1805 fputs (" * ", dump_file);
1806 print_generic_expr (dump_file, c->stride, 0);
1807 fputs (") : ", dump_file);
1808 break;
1809 case CAND_REF:
1810 fputs (" REF : ", dump_file);
1811 print_generic_expr (dump_file, c->base_expr, 0);
1812 fputs (" + (", dump_file);
1813 print_generic_expr (dump_file, c->stride, 0);
1814 fputs (") + ", dump_file);
1815 print_decs (c->index, dump_file);
1816 fputs (" : ", dump_file);
1817 break;
1818 case CAND_PHI:
1819 fputs (" PHI : ", dump_file);
1820 print_generic_expr (dump_file, c->base_expr, 0);
1821 fputs (" + (unknown * ", dump_file);
1822 print_generic_expr (dump_file, c->stride, 0);
1823 fputs (") : ", dump_file);
1824 break;
1825 default:
1826 gcc_unreachable ();
1828 print_generic_expr (dump_file, c->cand_type, 0);
1829 fprintf (dump_file, "\n basis: %d dependent: %d sibling: %d\n",
1830 c->basis, c->dependent, c->sibling);
1831 fprintf (dump_file, " next-interp: %d dead-savings: %d\n",
1832 c->next_interp, c->dead_savings);
1833 if (c->def_phi)
1834 fprintf (dump_file, " phi: %d\n", c->def_phi);
1835 fputs ("\n", dump_file);
1838 /* Dump the candidate vector for debug. */
1840 static void
1841 dump_cand_vec (void)
1843 unsigned i;
1844 slsr_cand_t c;
1846 fprintf (dump_file, "\nStrength reduction candidate vector:\n\n");
1848 FOR_EACH_VEC_ELT (cand_vec, i, c)
1849 dump_candidate (c);
1852 /* Callback used to dump the candidate chains hash table. */
1855 ssa_base_cand_dump_callback (cand_chain **slot, void *ignored ATTRIBUTE_UNUSED)
1857 const_cand_chain_t chain = *slot;
1858 cand_chain_t p;
1860 print_generic_expr (dump_file, chain->base_expr, 0);
1861 fprintf (dump_file, " -> %d", chain->cand->cand_num);
1863 for (p = chain->next; p; p = p->next)
1864 fprintf (dump_file, " -> %d", p->cand->cand_num);
1866 fputs ("\n", dump_file);
1867 return 1;
1870 /* Dump the candidate chains. */
1872 static void
1873 dump_cand_chains (void)
1875 fprintf (dump_file, "\nStrength reduction candidate chains:\n\n");
1876 base_cand_map->traverse_noresize <void *, ssa_base_cand_dump_callback>
1877 (NULL);
1878 fputs ("\n", dump_file);
1881 /* Dump the increment vector for debug. */
1883 static void
1884 dump_incr_vec (void)
1886 if (dump_file && (dump_flags & TDF_DETAILS))
1888 unsigned i;
1890 fprintf (dump_file, "\nIncrement vector:\n\n");
1892 for (i = 0; i < incr_vec_len; i++)
1894 fprintf (dump_file, "%3d increment: ", i);
1895 print_decs (incr_vec[i].incr, dump_file);
1896 fprintf (dump_file, "\n count: %d", incr_vec[i].count);
1897 fprintf (dump_file, "\n cost: %d", incr_vec[i].cost);
1898 fputs ("\n initializer: ", dump_file);
1899 print_generic_expr (dump_file, incr_vec[i].initializer, 0);
1900 fputs ("\n\n", dump_file);
1905 /* Replace *EXPR in candidate C with an equivalent strength-reduced
1906 data reference. */
1908 static void
1909 replace_ref (tree *expr, slsr_cand_t c)
1911 tree add_expr, mem_ref, acc_type = TREE_TYPE (*expr);
1912 unsigned HOST_WIDE_INT misalign;
1913 unsigned align;
1915 /* Ensure the memory reference carries the minimum alignment
1916 requirement for the data type. See PR58041. */
1917 get_object_alignment_1 (*expr, &align, &misalign);
1918 if (misalign != 0)
1919 align = (misalign & -misalign);
1920 if (align < TYPE_ALIGN (acc_type))
1921 acc_type = build_aligned_type (acc_type, align);
1923 add_expr = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (c->base_expr),
1924 c->base_expr, c->stride);
1925 mem_ref = fold_build2 (MEM_REF, acc_type, add_expr,
1926 wide_int_to_tree (c->cand_type, c->index));
1928 /* Gimplify the base addressing expression for the new MEM_REF tree. */
1929 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
1930 TREE_OPERAND (mem_ref, 0)
1931 = force_gimple_operand_gsi (&gsi, TREE_OPERAND (mem_ref, 0),
1932 /*simple_p=*/true, NULL,
1933 /*before=*/true, GSI_SAME_STMT);
1934 copy_ref_info (mem_ref, *expr);
1935 *expr = mem_ref;
1936 update_stmt (c->cand_stmt);
1939 /* Replace CAND_REF candidate C, each sibling of candidate C, and each
1940 dependent of candidate C with an equivalent strength-reduced data
1941 reference. */
1943 static void
1944 replace_refs (slsr_cand_t c)
1946 if (dump_file && (dump_flags & TDF_DETAILS))
1948 fputs ("Replacing reference: ", dump_file);
1949 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
1952 if (gimple_vdef (c->cand_stmt))
1954 tree *lhs = gimple_assign_lhs_ptr (c->cand_stmt);
1955 replace_ref (lhs, c);
1957 else
1959 tree *rhs = gimple_assign_rhs1_ptr (c->cand_stmt);
1960 replace_ref (rhs, c);
1963 if (dump_file && (dump_flags & TDF_DETAILS))
1965 fputs ("With: ", dump_file);
1966 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
1967 fputs ("\n", dump_file);
1970 if (c->sibling)
1971 replace_refs (lookup_cand (c->sibling));
1973 if (c->dependent)
1974 replace_refs (lookup_cand (c->dependent));
1977 /* Return TRUE if candidate C is dependent upon a PHI. */
1979 static bool
1980 phi_dependent_cand_p (slsr_cand_t c)
1982 /* A candidate is not necessarily dependent upon a PHI just because
1983 it has a phi definition for its base name. It may have a basis
1984 that relies upon the same phi definition, in which case the PHI
1985 is irrelevant to this candidate. */
1986 return (c->def_phi
1987 && c->basis
1988 && lookup_cand (c->basis)->def_phi != c->def_phi);
1991 /* Calculate the increment required for candidate C relative to
1992 its basis. */
1994 static widest_int
1995 cand_increment (slsr_cand_t c)
1997 slsr_cand_t basis;
1999 /* If the candidate doesn't have a basis, just return its own
2000 index. This is useful in record_increments to help us find
2001 an existing initializer. Also, if the candidate's basis is
2002 hidden by a phi, then its own index will be the increment
2003 from the newly introduced phi basis. */
2004 if (!c->basis || phi_dependent_cand_p (c))
2005 return c->index;
2007 basis = lookup_cand (c->basis);
2008 gcc_assert (operand_equal_p (c->base_expr, basis->base_expr, 0));
2009 return c->index - basis->index;
2012 /* Calculate the increment required for candidate C relative to
2013 its basis. If we aren't going to generate pointer arithmetic
2014 for this candidate, return the absolute value of that increment
2015 instead. */
2017 static inline widest_int
2018 cand_abs_increment (slsr_cand_t c)
2020 widest_int increment = cand_increment (c);
2022 if (!address_arithmetic_p && wi::neg_p (increment))
2023 increment = -increment;
2025 return increment;
2028 /* Return TRUE iff candidate C has already been replaced under
2029 another interpretation. */
2031 static inline bool
2032 cand_already_replaced (slsr_cand_t c)
2034 return (gimple_bb (c->cand_stmt) == 0);
2037 /* Common logic used by replace_unconditional_candidate and
2038 replace_conditional_candidate. */
2040 static void
2041 replace_mult_candidate (slsr_cand_t c, tree basis_name, widest_int bump)
2043 tree target_type = TREE_TYPE (gimple_assign_lhs (c->cand_stmt));
2044 enum tree_code cand_code = gimple_assign_rhs_code (c->cand_stmt);
2046 /* It is highly unlikely, but possible, that the resulting
2047 bump doesn't fit in a HWI. Abandon the replacement
2048 in this case. This does not affect siblings or dependents
2049 of C. Restriction to signed HWI is conservative for unsigned
2050 types but allows for safe negation without twisted logic. */
2051 if (wi::fits_shwi_p (bump)
2052 && bump.to_shwi () != HOST_WIDE_INT_MIN
2053 /* It is not useful to replace casts, copies, or adds of
2054 an SSA name and a constant. */
2055 && cand_code != MODIFY_EXPR
2056 && !CONVERT_EXPR_CODE_P (cand_code)
2057 && cand_code != PLUS_EXPR
2058 && cand_code != POINTER_PLUS_EXPR
2059 && cand_code != MINUS_EXPR)
2061 enum tree_code code = PLUS_EXPR;
2062 tree bump_tree;
2063 gimple stmt_to_print = NULL;
2065 /* If the basis name and the candidate's LHS have incompatible
2066 types, introduce a cast. */
2067 if (!useless_type_conversion_p (target_type, TREE_TYPE (basis_name)))
2068 basis_name = introduce_cast_before_cand (c, target_type, basis_name);
2069 if (wi::neg_p (bump))
2071 code = MINUS_EXPR;
2072 bump = -bump;
2075 bump_tree = wide_int_to_tree (target_type, bump);
2077 if (dump_file && (dump_flags & TDF_DETAILS))
2079 fputs ("Replacing: ", dump_file);
2080 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
2083 if (bump == 0)
2085 tree lhs = gimple_assign_lhs (c->cand_stmt);
2086 gassign *copy_stmt = gimple_build_assign (lhs, basis_name);
2087 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
2088 gimple_set_location (copy_stmt, gimple_location (c->cand_stmt));
2089 gsi_replace (&gsi, copy_stmt, false);
2090 c->cand_stmt = copy_stmt;
2091 if (dump_file && (dump_flags & TDF_DETAILS))
2092 stmt_to_print = copy_stmt;
2094 else
2096 tree rhs1, rhs2;
2097 if (cand_code != NEGATE_EXPR) {
2098 rhs1 = gimple_assign_rhs1 (c->cand_stmt);
2099 rhs2 = gimple_assign_rhs2 (c->cand_stmt);
2101 if (cand_code != NEGATE_EXPR
2102 && ((operand_equal_p (rhs1, basis_name, 0)
2103 && operand_equal_p (rhs2, bump_tree, 0))
2104 || (operand_equal_p (rhs1, bump_tree, 0)
2105 && operand_equal_p (rhs2, basis_name, 0))))
2107 if (dump_file && (dump_flags & TDF_DETAILS))
2109 fputs ("(duplicate, not actually replacing)", dump_file);
2110 stmt_to_print = c->cand_stmt;
2113 else
2115 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
2116 gimple_assign_set_rhs_with_ops (&gsi, code,
2117 basis_name, bump_tree);
2118 update_stmt (gsi_stmt (gsi));
2119 c->cand_stmt = gsi_stmt (gsi);
2120 if (dump_file && (dump_flags & TDF_DETAILS))
2121 stmt_to_print = gsi_stmt (gsi);
2125 if (dump_file && (dump_flags & TDF_DETAILS))
2127 fputs ("With: ", dump_file);
2128 print_gimple_stmt (dump_file, stmt_to_print, 0, 0);
2129 fputs ("\n", dump_file);
2134 /* Replace candidate C with an add or subtract. Note that we only
2135 operate on CAND_MULTs with known strides, so we will never generate
2136 a POINTER_PLUS_EXPR. Each candidate X = (B + i) * S is replaced by
2137 X = Y + ((i - i') * S), as described in the module commentary. The
2138 folded value ((i - i') * S) is referred to here as the "bump." */
2140 static void
2141 replace_unconditional_candidate (slsr_cand_t c)
2143 slsr_cand_t basis;
2145 if (cand_already_replaced (c))
2146 return;
2148 basis = lookup_cand (c->basis);
2149 widest_int bump = cand_increment (c) * wi::to_widest (c->stride);
2151 replace_mult_candidate (c, gimple_assign_lhs (basis->cand_stmt), bump);
2154 /* Return the index in the increment vector of the given INCREMENT,
2155 or -1 if not found. The latter can occur if more than
2156 MAX_INCR_VEC_LEN increments have been found. */
2158 static inline int
2159 incr_vec_index (const widest_int &increment)
2161 unsigned i;
2163 for (i = 0; i < incr_vec_len && increment != incr_vec[i].incr; i++)
2166 if (i < incr_vec_len)
2167 return i;
2168 else
2169 return -1;
2172 /* Create a new statement along edge E to add BASIS_NAME to the product
2173 of INCREMENT and the stride of candidate C. Create and return a new
2174 SSA name from *VAR to be used as the LHS of the new statement.
2175 KNOWN_STRIDE is true iff C's stride is a constant. */
2177 static tree
2178 create_add_on_incoming_edge (slsr_cand_t c, tree basis_name,
2179 widest_int increment, edge e, location_t loc,
2180 bool known_stride)
2182 basic_block insert_bb;
2183 gimple_stmt_iterator gsi;
2184 tree lhs, basis_type;
2185 gassign *new_stmt;
2187 /* If the add candidate along this incoming edge has the same
2188 index as C's hidden basis, the hidden basis represents this
2189 edge correctly. */
2190 if (increment == 0)
2191 return basis_name;
2193 basis_type = TREE_TYPE (basis_name);
2194 lhs = make_temp_ssa_name (basis_type, NULL, "slsr");
2196 if (known_stride)
2198 tree bump_tree;
2199 enum tree_code code = PLUS_EXPR;
2200 widest_int bump = increment * wi::to_widest (c->stride);
2201 if (wi::neg_p (bump))
2203 code = MINUS_EXPR;
2204 bump = -bump;
2207 bump_tree = wide_int_to_tree (basis_type, bump);
2208 new_stmt = gimple_build_assign (lhs, code, basis_name, bump_tree);
2210 else
2212 int i;
2213 bool negate_incr = (!address_arithmetic_p && wi::neg_p (increment));
2214 i = incr_vec_index (negate_incr ? -increment : increment);
2215 gcc_assert (i >= 0);
2217 if (incr_vec[i].initializer)
2219 enum tree_code code = negate_incr ? MINUS_EXPR : PLUS_EXPR;
2220 new_stmt = gimple_build_assign (lhs, code, basis_name,
2221 incr_vec[i].initializer);
2223 else if (increment == 1)
2224 new_stmt = gimple_build_assign (lhs, PLUS_EXPR, basis_name, c->stride);
2225 else if (increment == -1)
2226 new_stmt = gimple_build_assign (lhs, MINUS_EXPR, basis_name,
2227 c->stride);
2228 else
2229 gcc_unreachable ();
2232 insert_bb = single_succ_p (e->src) ? e->src : split_edge (e);
2233 gsi = gsi_last_bb (insert_bb);
2235 if (!gsi_end_p (gsi) && is_ctrl_stmt (gsi_stmt (gsi)))
2236 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
2237 else
2238 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
2240 gimple_set_location (new_stmt, loc);
2242 if (dump_file && (dump_flags & TDF_DETAILS))
2244 fprintf (dump_file, "Inserting in block %d: ", insert_bb->index);
2245 print_gimple_stmt (dump_file, new_stmt, 0, 0);
2248 return lhs;
2251 /* Given a candidate C with BASIS_NAME being the LHS of C's basis which
2252 is hidden by the phi node FROM_PHI, create a new phi node in the same
2253 block as FROM_PHI. The new phi is suitable for use as a basis by C,
2254 with its phi arguments representing conditional adjustments to the
2255 hidden basis along conditional incoming paths. Those adjustments are
2256 made by creating add statements (and sometimes recursively creating
2257 phis) along those incoming paths. LOC is the location to attach to
2258 the introduced statements. KNOWN_STRIDE is true iff C's stride is a
2259 constant. */
2261 static tree
2262 create_phi_basis (slsr_cand_t c, gimple from_phi, tree basis_name,
2263 location_t loc, bool known_stride)
2265 int i;
2266 tree name, phi_arg;
2267 gphi *phi;
2268 vec<tree> phi_args;
2269 slsr_cand_t basis = lookup_cand (c->basis);
2270 int nargs = gimple_phi_num_args (from_phi);
2271 basic_block phi_bb = gimple_bb (from_phi);
2272 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (from_phi));
2273 phi_args.create (nargs);
2275 /* Process each argument of the existing phi that represents
2276 conditionally-executed add candidates. */
2277 for (i = 0; i < nargs; i++)
2279 edge e = (*phi_bb->preds)[i];
2280 tree arg = gimple_phi_arg_def (from_phi, i);
2281 tree feeding_def;
2283 /* If the phi argument is the base name of the CAND_PHI, then
2284 this incoming arc should use the hidden basis. */
2285 if (operand_equal_p (arg, phi_cand->base_expr, 0))
2286 if (basis->index == 0)
2287 feeding_def = gimple_assign_lhs (basis->cand_stmt);
2288 else
2290 widest_int incr = -basis->index;
2291 feeding_def = create_add_on_incoming_edge (c, basis_name, incr,
2292 e, loc, known_stride);
2294 else
2296 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2298 /* If there is another phi along this incoming edge, we must
2299 process it in the same fashion to ensure that all basis
2300 adjustments are made along its incoming edges. */
2301 if (gimple_code (arg_def) == GIMPLE_PHI)
2302 feeding_def = create_phi_basis (c, arg_def, basis_name,
2303 loc, known_stride);
2304 else
2306 slsr_cand_t arg_cand = base_cand_from_table (arg);
2307 widest_int diff = arg_cand->index - basis->index;
2308 feeding_def = create_add_on_incoming_edge (c, basis_name, diff,
2309 e, loc, known_stride);
2313 /* Because of recursion, we need to save the arguments in a vector
2314 so we can create the PHI statement all at once. Otherwise the
2315 storage for the half-created PHI can be reclaimed. */
2316 phi_args.safe_push (feeding_def);
2319 /* Create the new phi basis. */
2320 name = make_temp_ssa_name (TREE_TYPE (basis_name), NULL, "slsr");
2321 phi = create_phi_node (name, phi_bb);
2322 SSA_NAME_DEF_STMT (name) = phi;
2324 FOR_EACH_VEC_ELT (phi_args, i, phi_arg)
2326 edge e = (*phi_bb->preds)[i];
2327 add_phi_arg (phi, phi_arg, e, loc);
2330 update_stmt (phi);
2332 if (dump_file && (dump_flags & TDF_DETAILS))
2334 fputs ("Introducing new phi basis: ", dump_file);
2335 print_gimple_stmt (dump_file, phi, 0, 0);
2338 return name;
2341 /* Given a candidate C whose basis is hidden by at least one intervening
2342 phi, introduce a matching number of new phis to represent its basis
2343 adjusted by conditional increments along possible incoming paths. Then
2344 replace C as though it were an unconditional candidate, using the new
2345 basis. */
2347 static void
2348 replace_conditional_candidate (slsr_cand_t c)
2350 tree basis_name, name;
2351 slsr_cand_t basis;
2352 location_t loc;
2354 /* Look up the LHS SSA name from C's basis. This will be the
2355 RHS1 of the adds we will introduce to create new phi arguments. */
2356 basis = lookup_cand (c->basis);
2357 basis_name = gimple_assign_lhs (basis->cand_stmt);
2359 /* Create a new phi statement which will represent C's true basis
2360 after the transformation is complete. */
2361 loc = gimple_location (c->cand_stmt);
2362 name = create_phi_basis (c, lookup_cand (c->def_phi)->cand_stmt,
2363 basis_name, loc, KNOWN_STRIDE);
2364 /* Replace C with an add of the new basis phi and a constant. */
2365 widest_int bump = c->index * wi::to_widest (c->stride);
2367 replace_mult_candidate (c, name, bump);
2370 /* Compute the expected costs of inserting basis adjustments for
2371 candidate C with phi-definition PHI. The cost of inserting
2372 one adjustment is given by ONE_ADD_COST. If PHI has arguments
2373 which are themselves phi results, recursively calculate costs
2374 for those phis as well. */
2376 static int
2377 phi_add_costs (gimple phi, slsr_cand_t c, int one_add_cost)
2379 unsigned i;
2380 int cost = 0;
2381 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
2383 /* If we work our way back to a phi that isn't dominated by the hidden
2384 basis, this isn't a candidate for replacement. Indicate this by
2385 returning an unreasonably high cost. It's not easy to detect
2386 these situations when determining the basis, so we defer the
2387 decision until now. */
2388 basic_block phi_bb = gimple_bb (phi);
2389 slsr_cand_t basis = lookup_cand (c->basis);
2390 basic_block basis_bb = gimple_bb (basis->cand_stmt);
2392 if (phi_bb == basis_bb || !dominated_by_p (CDI_DOMINATORS, phi_bb, basis_bb))
2393 return COST_INFINITE;
2395 for (i = 0; i < gimple_phi_num_args (phi); i++)
2397 tree arg = gimple_phi_arg_def (phi, i);
2399 if (arg != phi_cand->base_expr)
2401 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2403 if (gimple_code (arg_def) == GIMPLE_PHI)
2404 cost += phi_add_costs (arg_def, c, one_add_cost);
2405 else
2407 slsr_cand_t arg_cand = base_cand_from_table (arg);
2409 if (arg_cand->index != c->index)
2410 cost += one_add_cost;
2415 return cost;
2418 /* For candidate C, each sibling of candidate C, and each dependent of
2419 candidate C, determine whether the candidate is dependent upon a
2420 phi that hides its basis. If not, replace the candidate unconditionally.
2421 Otherwise, determine whether the cost of introducing compensation code
2422 for the candidate is offset by the gains from strength reduction. If
2423 so, replace the candidate and introduce the compensation code. */
2425 static void
2426 replace_uncond_cands_and_profitable_phis (slsr_cand_t c)
2428 if (phi_dependent_cand_p (c))
2430 if (c->kind == CAND_MULT)
2432 /* A candidate dependent upon a phi will replace a multiply by
2433 a constant with an add, and will insert at most one add for
2434 each phi argument. Add these costs with the potential dead-code
2435 savings to determine profitability. */
2436 bool speed = optimize_bb_for_speed_p (gimple_bb (c->cand_stmt));
2437 int mult_savings = stmt_cost (c->cand_stmt, speed);
2438 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
2439 tree phi_result = gimple_phi_result (phi);
2440 int one_add_cost = add_cost (speed,
2441 TYPE_MODE (TREE_TYPE (phi_result)));
2442 int add_costs = one_add_cost + phi_add_costs (phi, c, one_add_cost);
2443 int cost = add_costs - mult_savings - c->dead_savings;
2445 if (dump_file && (dump_flags & TDF_DETAILS))
2447 fprintf (dump_file, " Conditional candidate %d:\n", c->cand_num);
2448 fprintf (dump_file, " add_costs = %d\n", add_costs);
2449 fprintf (dump_file, " mult_savings = %d\n", mult_savings);
2450 fprintf (dump_file, " dead_savings = %d\n", c->dead_savings);
2451 fprintf (dump_file, " cost = %d\n", cost);
2452 if (cost <= COST_NEUTRAL)
2453 fputs (" Replacing...\n", dump_file);
2454 else
2455 fputs (" Not replaced.\n", dump_file);
2458 if (cost <= COST_NEUTRAL)
2459 replace_conditional_candidate (c);
2462 else
2463 replace_unconditional_candidate (c);
2465 if (c->sibling)
2466 replace_uncond_cands_and_profitable_phis (lookup_cand (c->sibling));
2468 if (c->dependent)
2469 replace_uncond_cands_and_profitable_phis (lookup_cand (c->dependent));
2472 /* Count the number of candidates in the tree rooted at C that have
2473 not already been replaced under other interpretations. */
2475 static int
2476 count_candidates (slsr_cand_t c)
2478 unsigned count = cand_already_replaced (c) ? 0 : 1;
2480 if (c->sibling)
2481 count += count_candidates (lookup_cand (c->sibling));
2483 if (c->dependent)
2484 count += count_candidates (lookup_cand (c->dependent));
2486 return count;
2489 /* Increase the count of INCREMENT by one in the increment vector.
2490 INCREMENT is associated with candidate C. If INCREMENT is to be
2491 conditionally executed as part of a conditional candidate replacement,
2492 IS_PHI_ADJUST is true, otherwise false. If an initializer
2493 T_0 = stride * I is provided by a candidate that dominates all
2494 candidates with the same increment, also record T_0 for subsequent use. */
2496 static void
2497 record_increment (slsr_cand_t c, widest_int increment, bool is_phi_adjust)
2499 bool found = false;
2500 unsigned i;
2502 /* Treat increments that differ only in sign as identical so as to
2503 share initializers, unless we are generating pointer arithmetic. */
2504 if (!address_arithmetic_p && wi::neg_p (increment))
2505 increment = -increment;
2507 for (i = 0; i < incr_vec_len; i++)
2509 if (incr_vec[i].incr == increment)
2511 incr_vec[i].count++;
2512 found = true;
2514 /* If we previously recorded an initializer that doesn't
2515 dominate this candidate, it's not going to be useful to
2516 us after all. */
2517 if (incr_vec[i].initializer
2518 && !dominated_by_p (CDI_DOMINATORS,
2519 gimple_bb (c->cand_stmt),
2520 incr_vec[i].init_bb))
2522 incr_vec[i].initializer = NULL_TREE;
2523 incr_vec[i].init_bb = NULL;
2526 break;
2530 if (!found && incr_vec_len < MAX_INCR_VEC_LEN - 1)
2532 /* The first time we see an increment, create the entry for it.
2533 If this is the root candidate which doesn't have a basis, set
2534 the count to zero. We're only processing it so it can possibly
2535 provide an initializer for other candidates. */
2536 incr_vec[incr_vec_len].incr = increment;
2537 incr_vec[incr_vec_len].count = c->basis || is_phi_adjust ? 1 : 0;
2538 incr_vec[incr_vec_len].cost = COST_INFINITE;
2540 /* Optimistically record the first occurrence of this increment
2541 as providing an initializer (if it does); we will revise this
2542 opinion later if it doesn't dominate all other occurrences.
2543 Exception: increments of -1, 0, 1 never need initializers;
2544 and phi adjustments don't ever provide initializers. */
2545 if (c->kind == CAND_ADD
2546 && !is_phi_adjust
2547 && c->index == increment
2548 && (wi::gts_p (increment, 1)
2549 || wi::lts_p (increment, -1))
2550 && (gimple_assign_rhs_code (c->cand_stmt) == PLUS_EXPR
2551 || gimple_assign_rhs_code (c->cand_stmt) == POINTER_PLUS_EXPR))
2553 tree t0 = NULL_TREE;
2554 tree rhs1 = gimple_assign_rhs1 (c->cand_stmt);
2555 tree rhs2 = gimple_assign_rhs2 (c->cand_stmt);
2556 if (operand_equal_p (rhs1, c->base_expr, 0))
2557 t0 = rhs2;
2558 else if (operand_equal_p (rhs2, c->base_expr, 0))
2559 t0 = rhs1;
2560 if (t0
2561 && SSA_NAME_DEF_STMT (t0)
2562 && gimple_bb (SSA_NAME_DEF_STMT (t0)))
2564 incr_vec[incr_vec_len].initializer = t0;
2565 incr_vec[incr_vec_len++].init_bb
2566 = gimple_bb (SSA_NAME_DEF_STMT (t0));
2568 else
2570 incr_vec[incr_vec_len].initializer = NULL_TREE;
2571 incr_vec[incr_vec_len++].init_bb = NULL;
2574 else
2576 incr_vec[incr_vec_len].initializer = NULL_TREE;
2577 incr_vec[incr_vec_len++].init_bb = NULL;
2582 /* Given phi statement PHI that hides a candidate from its BASIS, find
2583 the increments along each incoming arc (recursively handling additional
2584 phis that may be present) and record them. These increments are the
2585 difference in index between the index-adjusting statements and the
2586 index of the basis. */
2588 static void
2589 record_phi_increments (slsr_cand_t basis, gimple phi)
2591 unsigned i;
2592 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
2594 for (i = 0; i < gimple_phi_num_args (phi); i++)
2596 tree arg = gimple_phi_arg_def (phi, i);
2598 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
2600 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2602 if (gimple_code (arg_def) == GIMPLE_PHI)
2603 record_phi_increments (basis, arg_def);
2604 else
2606 slsr_cand_t arg_cand = base_cand_from_table (arg);
2607 widest_int diff = arg_cand->index - basis->index;
2608 record_increment (arg_cand, diff, PHI_ADJUST);
2614 /* Determine how many times each unique increment occurs in the set
2615 of candidates rooted at C's parent, recording the data in the
2616 increment vector. For each unique increment I, if an initializer
2617 T_0 = stride * I is provided by a candidate that dominates all
2618 candidates with the same increment, also record T_0 for subsequent
2619 use. */
2621 static void
2622 record_increments (slsr_cand_t c)
2624 if (!cand_already_replaced (c))
2626 if (!phi_dependent_cand_p (c))
2627 record_increment (c, cand_increment (c), NOT_PHI_ADJUST);
2628 else
2630 /* A candidate with a basis hidden by a phi will have one
2631 increment for its relationship to the index represented by
2632 the phi, and potentially additional increments along each
2633 incoming edge. For the root of the dependency tree (which
2634 has no basis), process just the initial index in case it has
2635 an initializer that can be used by subsequent candidates. */
2636 record_increment (c, c->index, NOT_PHI_ADJUST);
2638 if (c->basis)
2639 record_phi_increments (lookup_cand (c->basis),
2640 lookup_cand (c->def_phi)->cand_stmt);
2644 if (c->sibling)
2645 record_increments (lookup_cand (c->sibling));
2647 if (c->dependent)
2648 record_increments (lookup_cand (c->dependent));
2651 /* Add up and return the costs of introducing add statements that
2652 require the increment INCR on behalf of candidate C and phi
2653 statement PHI. Accumulate into *SAVINGS the potential savings
2654 from removing existing statements that feed PHI and have no other
2655 uses. */
2657 static int
2658 phi_incr_cost (slsr_cand_t c, const widest_int &incr, gimple phi, int *savings)
2660 unsigned i;
2661 int cost = 0;
2662 slsr_cand_t basis = lookup_cand (c->basis);
2663 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
2665 for (i = 0; i < gimple_phi_num_args (phi); i++)
2667 tree arg = gimple_phi_arg_def (phi, i);
2669 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
2671 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2673 if (gimple_code (arg_def) == GIMPLE_PHI)
2675 int feeding_savings = 0;
2676 cost += phi_incr_cost (c, incr, arg_def, &feeding_savings);
2677 if (has_single_use (gimple_phi_result (arg_def)))
2678 *savings += feeding_savings;
2680 else
2682 slsr_cand_t arg_cand = base_cand_from_table (arg);
2683 widest_int diff = arg_cand->index - basis->index;
2685 if (incr == diff)
2687 tree basis_lhs = gimple_assign_lhs (basis->cand_stmt);
2688 tree lhs = gimple_assign_lhs (arg_cand->cand_stmt);
2689 cost += add_cost (true, TYPE_MODE (TREE_TYPE (basis_lhs)));
2690 if (has_single_use (lhs))
2691 *savings += stmt_cost (arg_cand->cand_stmt, true);
2697 return cost;
2700 /* Return the first candidate in the tree rooted at C that has not
2701 already been replaced, favoring siblings over dependents. */
2703 static slsr_cand_t
2704 unreplaced_cand_in_tree (slsr_cand_t c)
2706 if (!cand_already_replaced (c))
2707 return c;
2709 if (c->sibling)
2711 slsr_cand_t sib = unreplaced_cand_in_tree (lookup_cand (c->sibling));
2712 if (sib)
2713 return sib;
2716 if (c->dependent)
2718 slsr_cand_t dep = unreplaced_cand_in_tree (lookup_cand (c->dependent));
2719 if (dep)
2720 return dep;
2723 return NULL;
2726 /* Return TRUE if the candidates in the tree rooted at C should be
2727 optimized for speed, else FALSE. We estimate this based on the block
2728 containing the most dominant candidate in the tree that has not yet
2729 been replaced. */
2731 static bool
2732 optimize_cands_for_speed_p (slsr_cand_t c)
2734 slsr_cand_t c2 = unreplaced_cand_in_tree (c);
2735 gcc_assert (c2);
2736 return optimize_bb_for_speed_p (gimple_bb (c2->cand_stmt));
2739 /* Add COST_IN to the lowest cost of any dependent path starting at
2740 candidate C or any of its siblings, counting only candidates along
2741 such paths with increment INCR. Assume that replacing a candidate
2742 reduces cost by REPL_SAVINGS. Also account for savings from any
2743 statements that would go dead. If COUNT_PHIS is true, include
2744 costs of introducing feeding statements for conditional candidates. */
2746 static int
2747 lowest_cost_path (int cost_in, int repl_savings, slsr_cand_t c,
2748 const widest_int &incr, bool count_phis)
2750 int local_cost, sib_cost, savings = 0;
2751 widest_int cand_incr = cand_abs_increment (c);
2753 if (cand_already_replaced (c))
2754 local_cost = cost_in;
2755 else if (incr == cand_incr)
2756 local_cost = cost_in - repl_savings - c->dead_savings;
2757 else
2758 local_cost = cost_in - c->dead_savings;
2760 if (count_phis
2761 && phi_dependent_cand_p (c)
2762 && !cand_already_replaced (c))
2764 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
2765 local_cost += phi_incr_cost (c, incr, phi, &savings);
2767 if (has_single_use (gimple_phi_result (phi)))
2768 local_cost -= savings;
2771 if (c->dependent)
2772 local_cost = lowest_cost_path (local_cost, repl_savings,
2773 lookup_cand (c->dependent), incr,
2774 count_phis);
2776 if (c->sibling)
2778 sib_cost = lowest_cost_path (cost_in, repl_savings,
2779 lookup_cand (c->sibling), incr,
2780 count_phis);
2781 local_cost = MIN (local_cost, sib_cost);
2784 return local_cost;
2787 /* Compute the total savings that would accrue from all replacements
2788 in the candidate tree rooted at C, counting only candidates with
2789 increment INCR. Assume that replacing a candidate reduces cost
2790 by REPL_SAVINGS. Also account for savings from statements that
2791 would go dead. */
2793 static int
2794 total_savings (int repl_savings, slsr_cand_t c, const widest_int &incr,
2795 bool count_phis)
2797 int savings = 0;
2798 widest_int cand_incr = cand_abs_increment (c);
2800 if (incr == cand_incr && !cand_already_replaced (c))
2801 savings += repl_savings + c->dead_savings;
2803 if (count_phis
2804 && phi_dependent_cand_p (c)
2805 && !cand_already_replaced (c))
2807 int phi_savings = 0;
2808 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
2809 savings -= phi_incr_cost (c, incr, phi, &phi_savings);
2811 if (has_single_use (gimple_phi_result (phi)))
2812 savings += phi_savings;
2815 if (c->dependent)
2816 savings += total_savings (repl_savings, lookup_cand (c->dependent), incr,
2817 count_phis);
2819 if (c->sibling)
2820 savings += total_savings (repl_savings, lookup_cand (c->sibling), incr,
2821 count_phis);
2823 return savings;
2826 /* Use target-specific costs to determine and record which increments
2827 in the current candidate tree are profitable to replace, assuming
2828 MODE and SPEED. FIRST_DEP is the first dependent of the root of
2829 the candidate tree.
2831 One slight limitation here is that we don't account for the possible
2832 introduction of casts in some cases. See replace_one_candidate for
2833 the cases where these are introduced. This should probably be cleaned
2834 up sometime. */
2836 static void
2837 analyze_increments (slsr_cand_t first_dep, machine_mode mode, bool speed)
2839 unsigned i;
2841 for (i = 0; i < incr_vec_len; i++)
2843 HOST_WIDE_INT incr = incr_vec[i].incr.to_shwi ();
2845 /* If somehow this increment is bigger than a HWI, we won't
2846 be optimizing candidates that use it. And if the increment
2847 has a count of zero, nothing will be done with it. */
2848 if (!wi::fits_shwi_p (incr_vec[i].incr) || !incr_vec[i].count)
2849 incr_vec[i].cost = COST_INFINITE;
2851 /* Increments of 0, 1, and -1 are always profitable to replace,
2852 because they always replace a multiply or add with an add or
2853 copy, and may cause one or more existing instructions to go
2854 dead. Exception: -1 can't be assumed to be profitable for
2855 pointer addition. */
2856 else if (incr == 0
2857 || incr == 1
2858 || (incr == -1
2859 && (gimple_assign_rhs_code (first_dep->cand_stmt)
2860 != POINTER_PLUS_EXPR)))
2861 incr_vec[i].cost = COST_NEUTRAL;
2863 /* FORNOW: If we need to add an initializer, give up if a cast from
2864 the candidate's type to its stride's type can lose precision.
2865 This could eventually be handled better by expressly retaining the
2866 result of a cast to a wider type in the stride. Example:
2868 short int _1;
2869 _2 = (int) _1;
2870 _3 = _2 * 10;
2871 _4 = x + _3; ADD: x + (10 * _1) : int
2872 _5 = _2 * 15;
2873 _6 = x + _3; ADD: x + (15 * _1) : int
2875 Right now replacing _6 would cause insertion of an initializer
2876 of the form "short int T = _1 * 5;" followed by a cast to
2877 int, which could overflow incorrectly. Had we recorded _2 or
2878 (int)_1 as the stride, this wouldn't happen. However, doing
2879 this breaks other opportunities, so this will require some
2880 care. */
2881 else if (!incr_vec[i].initializer
2882 && TREE_CODE (first_dep->stride) != INTEGER_CST
2883 && !legal_cast_p_1 (first_dep->stride,
2884 gimple_assign_lhs (first_dep->cand_stmt)))
2886 incr_vec[i].cost = COST_INFINITE;
2888 /* If we need to add an initializer, make sure we don't introduce
2889 a multiply by a pointer type, which can happen in certain cast
2890 scenarios. FIXME: When cleaning up these cast issues, we can
2891 afford to introduce the multiply provided we cast out to an
2892 unsigned int of appropriate size. */
2893 else if (!incr_vec[i].initializer
2894 && TREE_CODE (first_dep->stride) != INTEGER_CST
2895 && POINTER_TYPE_P (TREE_TYPE (first_dep->stride)))
2897 incr_vec[i].cost = COST_INFINITE;
2899 /* For any other increment, if this is a multiply candidate, we
2900 must introduce a temporary T and initialize it with
2901 T_0 = stride * increment. When optimizing for speed, walk the
2902 candidate tree to calculate the best cost reduction along any
2903 path; if it offsets the fixed cost of inserting the initializer,
2904 replacing the increment is profitable. When optimizing for
2905 size, instead calculate the total cost reduction from replacing
2906 all candidates with this increment. */
2907 else if (first_dep->kind == CAND_MULT)
2909 int cost = mult_by_coeff_cost (incr, mode, speed);
2910 int repl_savings = mul_cost (speed, mode) - add_cost (speed, mode);
2911 if (speed)
2912 cost = lowest_cost_path (cost, repl_savings, first_dep,
2913 incr_vec[i].incr, COUNT_PHIS);
2914 else
2915 cost -= total_savings (repl_savings, first_dep, incr_vec[i].incr,
2916 COUNT_PHIS);
2918 incr_vec[i].cost = cost;
2921 /* If this is an add candidate, the initializer may already
2922 exist, so only calculate the cost of the initializer if it
2923 doesn't. We are replacing one add with another here, so the
2924 known replacement savings is zero. We will account for removal
2925 of dead instructions in lowest_cost_path or total_savings. */
2926 else
2928 int cost = 0;
2929 if (!incr_vec[i].initializer)
2930 cost = mult_by_coeff_cost (incr, mode, speed);
2932 if (speed)
2933 cost = lowest_cost_path (cost, 0, first_dep, incr_vec[i].incr,
2934 DONT_COUNT_PHIS);
2935 else
2936 cost -= total_savings (0, first_dep, incr_vec[i].incr,
2937 DONT_COUNT_PHIS);
2939 incr_vec[i].cost = cost;
2944 /* Return the nearest common dominator of BB1 and BB2. If the blocks
2945 are identical, return the earlier of C1 and C2 in *WHERE. Otherwise,
2946 if the NCD matches BB1, return C1 in *WHERE; if the NCD matches BB2,
2947 return C2 in *WHERE; and if the NCD matches neither, return NULL in
2948 *WHERE. Note: It is possible for one of C1 and C2 to be NULL. */
2950 static basic_block
2951 ncd_for_two_cands (basic_block bb1, basic_block bb2,
2952 slsr_cand_t c1, slsr_cand_t c2, slsr_cand_t *where)
2954 basic_block ncd;
2956 if (!bb1)
2958 *where = c2;
2959 return bb2;
2962 if (!bb2)
2964 *where = c1;
2965 return bb1;
2968 ncd = nearest_common_dominator (CDI_DOMINATORS, bb1, bb2);
2970 /* If both candidates are in the same block, the earlier
2971 candidate wins. */
2972 if (bb1 == ncd && bb2 == ncd)
2974 if (!c1 || (c2 && c2->cand_num < c1->cand_num))
2975 *where = c2;
2976 else
2977 *where = c1;
2980 /* Otherwise, if one of them produced a candidate in the
2981 dominator, that one wins. */
2982 else if (bb1 == ncd)
2983 *where = c1;
2985 else if (bb2 == ncd)
2986 *where = c2;
2988 /* If neither matches the dominator, neither wins. */
2989 else
2990 *where = NULL;
2992 return ncd;
2995 /* Consider all candidates that feed PHI. Find the nearest common
2996 dominator of those candidates requiring the given increment INCR.
2997 Further find and return the nearest common dominator of this result
2998 with block NCD. If the returned block contains one or more of the
2999 candidates, return the earliest candidate in the block in *WHERE. */
3001 static basic_block
3002 ncd_with_phi (slsr_cand_t c, const widest_int &incr, gphi *phi,
3003 basic_block ncd, slsr_cand_t *where)
3005 unsigned i;
3006 slsr_cand_t basis = lookup_cand (c->basis);
3007 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
3009 for (i = 0; i < gimple_phi_num_args (phi); i++)
3011 tree arg = gimple_phi_arg_def (phi, i);
3013 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
3015 gimple arg_def = SSA_NAME_DEF_STMT (arg);
3017 if (gimple_code (arg_def) == GIMPLE_PHI)
3018 ncd = ncd_with_phi (c, incr, as_a <gphi *> (arg_def), ncd,
3019 where);
3020 else
3022 slsr_cand_t arg_cand = base_cand_from_table (arg);
3023 widest_int diff = arg_cand->index - basis->index;
3024 basic_block pred = gimple_phi_arg_edge (phi, i)->src;
3026 if ((incr == diff) || (!address_arithmetic_p && incr == -diff))
3027 ncd = ncd_for_two_cands (ncd, pred, *where, NULL, where);
3032 return ncd;
3035 /* Consider the candidate C together with any candidates that feed
3036 C's phi dependence (if any). Find and return the nearest common
3037 dominator of those candidates requiring the given increment INCR.
3038 If the returned block contains one or more of the candidates,
3039 return the earliest candidate in the block in *WHERE. */
3041 static basic_block
3042 ncd_of_cand_and_phis (slsr_cand_t c, const widest_int &incr, slsr_cand_t *where)
3044 basic_block ncd = NULL;
3046 if (cand_abs_increment (c) == incr)
3048 ncd = gimple_bb (c->cand_stmt);
3049 *where = c;
3052 if (phi_dependent_cand_p (c))
3053 ncd = ncd_with_phi (c, incr,
3054 as_a <gphi *> (lookup_cand (c->def_phi)->cand_stmt),
3055 ncd, where);
3057 return ncd;
3060 /* Consider all candidates in the tree rooted at C for which INCR
3061 represents the required increment of C relative to its basis.
3062 Find and return the basic block that most nearly dominates all
3063 such candidates. If the returned block contains one or more of
3064 the candidates, return the earliest candidate in the block in
3065 *WHERE. */
3067 static basic_block
3068 nearest_common_dominator_for_cands (slsr_cand_t c, const widest_int &incr,
3069 slsr_cand_t *where)
3071 basic_block sib_ncd = NULL, dep_ncd = NULL, this_ncd = NULL, ncd;
3072 slsr_cand_t sib_where = NULL, dep_where = NULL, this_where = NULL, new_where;
3074 /* First find the NCD of all siblings and dependents. */
3075 if (c->sibling)
3076 sib_ncd = nearest_common_dominator_for_cands (lookup_cand (c->sibling),
3077 incr, &sib_where);
3078 if (c->dependent)
3079 dep_ncd = nearest_common_dominator_for_cands (lookup_cand (c->dependent),
3080 incr, &dep_where);
3081 if (!sib_ncd && !dep_ncd)
3083 new_where = NULL;
3084 ncd = NULL;
3086 else if (sib_ncd && !dep_ncd)
3088 new_where = sib_where;
3089 ncd = sib_ncd;
3091 else if (dep_ncd && !sib_ncd)
3093 new_where = dep_where;
3094 ncd = dep_ncd;
3096 else
3097 ncd = ncd_for_two_cands (sib_ncd, dep_ncd, sib_where,
3098 dep_where, &new_where);
3100 /* If the candidate's increment doesn't match the one we're interested
3101 in (and nor do any increments for feeding defs of a phi-dependence),
3102 then the result depends only on siblings and dependents. */
3103 this_ncd = ncd_of_cand_and_phis (c, incr, &this_where);
3105 if (!this_ncd || cand_already_replaced (c))
3107 *where = new_where;
3108 return ncd;
3111 /* Otherwise, compare this candidate with the result from all siblings
3112 and dependents. */
3113 ncd = ncd_for_two_cands (ncd, this_ncd, new_where, this_where, where);
3115 return ncd;
3118 /* Return TRUE if the increment indexed by INDEX is profitable to replace. */
3120 static inline bool
3121 profitable_increment_p (unsigned index)
3123 return (incr_vec[index].cost <= COST_NEUTRAL);
3126 /* For each profitable increment in the increment vector not equal to
3127 0 or 1 (or -1, for non-pointer arithmetic), find the nearest common
3128 dominator of all statements in the candidate chain rooted at C
3129 that require that increment, and insert an initializer
3130 T_0 = stride * increment at that location. Record T_0 with the
3131 increment record. */
3133 static void
3134 insert_initializers (slsr_cand_t c)
3136 unsigned i;
3138 for (i = 0; i < incr_vec_len; i++)
3140 basic_block bb;
3141 slsr_cand_t where = NULL;
3142 gassign *init_stmt;
3143 tree stride_type, new_name, incr_tree;
3144 widest_int incr = incr_vec[i].incr;
3146 if (!profitable_increment_p (i)
3147 || incr == 1
3148 || (incr == -1
3149 && gimple_assign_rhs_code (c->cand_stmt) != POINTER_PLUS_EXPR)
3150 || incr == 0)
3151 continue;
3153 /* We may have already identified an existing initializer that
3154 will suffice. */
3155 if (incr_vec[i].initializer)
3157 if (dump_file && (dump_flags & TDF_DETAILS))
3159 fputs ("Using existing initializer: ", dump_file);
3160 print_gimple_stmt (dump_file,
3161 SSA_NAME_DEF_STMT (incr_vec[i].initializer),
3162 0, 0);
3164 continue;
3167 /* Find the block that most closely dominates all candidates
3168 with this increment. If there is at least one candidate in
3169 that block, the earliest one will be returned in WHERE. */
3170 bb = nearest_common_dominator_for_cands (c, incr, &where);
3172 /* Create a new SSA name to hold the initializer's value. */
3173 stride_type = TREE_TYPE (c->stride);
3174 new_name = make_temp_ssa_name (stride_type, NULL, "slsr");
3175 incr_vec[i].initializer = new_name;
3177 /* Create the initializer and insert it in the latest possible
3178 dominating position. */
3179 incr_tree = wide_int_to_tree (stride_type, incr);
3180 init_stmt = gimple_build_assign (new_name, MULT_EXPR,
3181 c->stride, incr_tree);
3182 if (where)
3184 gimple_stmt_iterator gsi = gsi_for_stmt (where->cand_stmt);
3185 gsi_insert_before (&gsi, init_stmt, GSI_SAME_STMT);
3186 gimple_set_location (init_stmt, gimple_location (where->cand_stmt));
3188 else
3190 gimple_stmt_iterator gsi = gsi_last_bb (bb);
3191 gimple basis_stmt = lookup_cand (c->basis)->cand_stmt;
3193 if (!gsi_end_p (gsi) && is_ctrl_stmt (gsi_stmt (gsi)))
3194 gsi_insert_before (&gsi, init_stmt, GSI_SAME_STMT);
3195 else
3196 gsi_insert_after (&gsi, init_stmt, GSI_SAME_STMT);
3198 gimple_set_location (init_stmt, gimple_location (basis_stmt));
3201 if (dump_file && (dump_flags & TDF_DETAILS))
3203 fputs ("Inserting initializer: ", dump_file);
3204 print_gimple_stmt (dump_file, init_stmt, 0, 0);
3209 /* Return TRUE iff all required increments for candidates feeding PHI
3210 are profitable to replace on behalf of candidate C. */
3212 static bool
3213 all_phi_incrs_profitable (slsr_cand_t c, gimple phi)
3215 unsigned i;
3216 slsr_cand_t basis = lookup_cand (c->basis);
3217 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
3219 for (i = 0; i < gimple_phi_num_args (phi); i++)
3221 tree arg = gimple_phi_arg_def (phi, i);
3223 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
3225 gimple arg_def = SSA_NAME_DEF_STMT (arg);
3227 if (gimple_code (arg_def) == GIMPLE_PHI)
3229 if (!all_phi_incrs_profitable (c, arg_def))
3230 return false;
3232 else
3234 int j;
3235 slsr_cand_t arg_cand = base_cand_from_table (arg);
3236 widest_int increment = arg_cand->index - basis->index;
3238 if (!address_arithmetic_p && wi::neg_p (increment))
3239 increment = -increment;
3241 j = incr_vec_index (increment);
3243 if (dump_file && (dump_flags & TDF_DETAILS))
3245 fprintf (dump_file, " Conditional candidate %d, phi: ",
3246 c->cand_num);
3247 print_gimple_stmt (dump_file, phi, 0, 0);
3248 fputs (" increment: ", dump_file);
3249 print_decs (increment, dump_file);
3250 if (j < 0)
3251 fprintf (dump_file,
3252 "\n Not replaced; incr_vec overflow.\n");
3253 else {
3254 fprintf (dump_file, "\n cost: %d\n", incr_vec[j].cost);
3255 if (profitable_increment_p (j))
3256 fputs (" Replacing...\n", dump_file);
3257 else
3258 fputs (" Not replaced.\n", dump_file);
3262 if (j < 0 || !profitable_increment_p (j))
3263 return false;
3268 return true;
3271 /* Create a NOP_EXPR that copies FROM_EXPR into a new SSA name of
3272 type TO_TYPE, and insert it in front of the statement represented
3273 by candidate C. Use *NEW_VAR to create the new SSA name. Return
3274 the new SSA name. */
3276 static tree
3277 introduce_cast_before_cand (slsr_cand_t c, tree to_type, tree from_expr)
3279 tree cast_lhs;
3280 gassign *cast_stmt;
3281 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3283 cast_lhs = make_temp_ssa_name (to_type, NULL, "slsr");
3284 cast_stmt = gimple_build_assign (cast_lhs, NOP_EXPR, from_expr);
3285 gimple_set_location (cast_stmt, gimple_location (c->cand_stmt));
3286 gsi_insert_before (&gsi, cast_stmt, GSI_SAME_STMT);
3288 if (dump_file && (dump_flags & TDF_DETAILS))
3290 fputs (" Inserting: ", dump_file);
3291 print_gimple_stmt (dump_file, cast_stmt, 0, 0);
3294 return cast_lhs;
3297 /* Replace the RHS of the statement represented by candidate C with
3298 NEW_CODE, NEW_RHS1, and NEW_RHS2, provided that to do so doesn't
3299 leave C unchanged or just interchange its operands. The original
3300 operation and operands are in OLD_CODE, OLD_RHS1, and OLD_RHS2.
3301 If the replacement was made and we are doing a details dump,
3302 return the revised statement, else NULL. */
3304 static gimple
3305 replace_rhs_if_not_dup (enum tree_code new_code, tree new_rhs1, tree new_rhs2,
3306 enum tree_code old_code, tree old_rhs1, tree old_rhs2,
3307 slsr_cand_t c)
3309 if (new_code != old_code
3310 || ((!operand_equal_p (new_rhs1, old_rhs1, 0)
3311 || !operand_equal_p (new_rhs2, old_rhs2, 0))
3312 && (!operand_equal_p (new_rhs1, old_rhs2, 0)
3313 || !operand_equal_p (new_rhs2, old_rhs1, 0))))
3315 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3316 gimple_assign_set_rhs_with_ops (&gsi, new_code, new_rhs1, new_rhs2);
3317 update_stmt (gsi_stmt (gsi));
3318 c->cand_stmt = gsi_stmt (gsi);
3320 if (dump_file && (dump_flags & TDF_DETAILS))
3321 return gsi_stmt (gsi);
3324 else if (dump_file && (dump_flags & TDF_DETAILS))
3325 fputs (" (duplicate, not actually replacing)\n", dump_file);
3327 return NULL;
3330 /* Strength-reduce the statement represented by candidate C by replacing
3331 it with an equivalent addition or subtraction. I is the index into
3332 the increment vector identifying C's increment. NEW_VAR is used to
3333 create a new SSA name if a cast needs to be introduced. BASIS_NAME
3334 is the rhs1 to use in creating the add/subtract. */
3336 static void
3337 replace_one_candidate (slsr_cand_t c, unsigned i, tree basis_name)
3339 gimple stmt_to_print = NULL;
3340 tree orig_rhs1, orig_rhs2;
3341 tree rhs2;
3342 enum tree_code orig_code, repl_code;
3343 widest_int cand_incr;
3345 orig_code = gimple_assign_rhs_code (c->cand_stmt);
3346 orig_rhs1 = gimple_assign_rhs1 (c->cand_stmt);
3347 orig_rhs2 = gimple_assign_rhs2 (c->cand_stmt);
3348 cand_incr = cand_increment (c);
3350 if (dump_file && (dump_flags & TDF_DETAILS))
3352 fputs ("Replacing: ", dump_file);
3353 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
3354 stmt_to_print = c->cand_stmt;
3357 if (address_arithmetic_p)
3358 repl_code = POINTER_PLUS_EXPR;
3359 else
3360 repl_code = PLUS_EXPR;
3362 /* If the increment has an initializer T_0, replace the candidate
3363 statement with an add of the basis name and the initializer. */
3364 if (incr_vec[i].initializer)
3366 tree init_type = TREE_TYPE (incr_vec[i].initializer);
3367 tree orig_type = TREE_TYPE (orig_rhs2);
3369 if (types_compatible_p (orig_type, init_type))
3370 rhs2 = incr_vec[i].initializer;
3371 else
3372 rhs2 = introduce_cast_before_cand (c, orig_type,
3373 incr_vec[i].initializer);
3375 if (incr_vec[i].incr != cand_incr)
3377 gcc_assert (repl_code == PLUS_EXPR);
3378 repl_code = MINUS_EXPR;
3381 stmt_to_print = replace_rhs_if_not_dup (repl_code, basis_name, rhs2,
3382 orig_code, orig_rhs1, orig_rhs2,
3386 /* Otherwise, the increment is one of -1, 0, and 1. Replace
3387 with a subtract of the stride from the basis name, a copy
3388 from the basis name, or an add of the stride to the basis
3389 name, respectively. It may be necessary to introduce a
3390 cast (or reuse an existing cast). */
3391 else if (cand_incr == 1)
3393 tree stride_type = TREE_TYPE (c->stride);
3394 tree orig_type = TREE_TYPE (orig_rhs2);
3396 if (types_compatible_p (orig_type, stride_type))
3397 rhs2 = c->stride;
3398 else
3399 rhs2 = introduce_cast_before_cand (c, orig_type, c->stride);
3401 stmt_to_print = replace_rhs_if_not_dup (repl_code, basis_name, rhs2,
3402 orig_code, orig_rhs1, orig_rhs2,
3406 else if (cand_incr == -1)
3408 tree stride_type = TREE_TYPE (c->stride);
3409 tree orig_type = TREE_TYPE (orig_rhs2);
3410 gcc_assert (repl_code != POINTER_PLUS_EXPR);
3412 if (types_compatible_p (orig_type, stride_type))
3413 rhs2 = c->stride;
3414 else
3415 rhs2 = introduce_cast_before_cand (c, orig_type, c->stride);
3417 if (orig_code != MINUS_EXPR
3418 || !operand_equal_p (basis_name, orig_rhs1, 0)
3419 || !operand_equal_p (rhs2, orig_rhs2, 0))
3421 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3422 gimple_assign_set_rhs_with_ops (&gsi, MINUS_EXPR, basis_name, rhs2);
3423 update_stmt (gsi_stmt (gsi));
3424 c->cand_stmt = gsi_stmt (gsi);
3426 if (dump_file && (dump_flags & TDF_DETAILS))
3427 stmt_to_print = gsi_stmt (gsi);
3429 else if (dump_file && (dump_flags & TDF_DETAILS))
3430 fputs (" (duplicate, not actually replacing)\n", dump_file);
3433 else if (cand_incr == 0)
3435 tree lhs = gimple_assign_lhs (c->cand_stmt);
3436 tree lhs_type = TREE_TYPE (lhs);
3437 tree basis_type = TREE_TYPE (basis_name);
3439 if (types_compatible_p (lhs_type, basis_type))
3441 gassign *copy_stmt = gimple_build_assign (lhs, basis_name);
3442 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3443 gimple_set_location (copy_stmt, gimple_location (c->cand_stmt));
3444 gsi_replace (&gsi, copy_stmt, false);
3445 c->cand_stmt = copy_stmt;
3447 if (dump_file && (dump_flags & TDF_DETAILS))
3448 stmt_to_print = copy_stmt;
3450 else
3452 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3453 gassign *cast_stmt = gimple_build_assign (lhs, NOP_EXPR, basis_name);
3454 gimple_set_location (cast_stmt, gimple_location (c->cand_stmt));
3455 gsi_replace (&gsi, cast_stmt, false);
3456 c->cand_stmt = cast_stmt;
3458 if (dump_file && (dump_flags & TDF_DETAILS))
3459 stmt_to_print = cast_stmt;
3462 else
3463 gcc_unreachable ();
3465 if (dump_file && (dump_flags & TDF_DETAILS) && stmt_to_print)
3467 fputs ("With: ", dump_file);
3468 print_gimple_stmt (dump_file, stmt_to_print, 0, 0);
3469 fputs ("\n", dump_file);
3473 /* For each candidate in the tree rooted at C, replace it with
3474 an increment if such has been shown to be profitable. */
3476 static void
3477 replace_profitable_candidates (slsr_cand_t c)
3479 if (!cand_already_replaced (c))
3481 widest_int increment = cand_abs_increment (c);
3482 enum tree_code orig_code = gimple_assign_rhs_code (c->cand_stmt);
3483 int i;
3485 i = incr_vec_index (increment);
3487 /* Only process profitable increments. Nothing useful can be done
3488 to a cast or copy. */
3489 if (i >= 0
3490 && profitable_increment_p (i)
3491 && orig_code != MODIFY_EXPR
3492 && !CONVERT_EXPR_CODE_P (orig_code))
3494 if (phi_dependent_cand_p (c))
3496 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
3498 if (all_phi_incrs_profitable (c, phi))
3500 /* Look up the LHS SSA name from C's basis. This will be
3501 the RHS1 of the adds we will introduce to create new
3502 phi arguments. */
3503 slsr_cand_t basis = lookup_cand (c->basis);
3504 tree basis_name = gimple_assign_lhs (basis->cand_stmt);
3506 /* Create a new phi statement that will represent C's true
3507 basis after the transformation is complete. */
3508 location_t loc = gimple_location (c->cand_stmt);
3509 tree name = create_phi_basis (c, phi, basis_name,
3510 loc, UNKNOWN_STRIDE);
3512 /* Replace C with an add of the new basis phi and the
3513 increment. */
3514 replace_one_candidate (c, i, name);
3517 else
3519 slsr_cand_t basis = lookup_cand (c->basis);
3520 tree basis_name = gimple_assign_lhs (basis->cand_stmt);
3521 replace_one_candidate (c, i, basis_name);
3526 if (c->sibling)
3527 replace_profitable_candidates (lookup_cand (c->sibling));
3529 if (c->dependent)
3530 replace_profitable_candidates (lookup_cand (c->dependent));
3533 /* Analyze costs of related candidates in the candidate vector,
3534 and make beneficial replacements. */
3536 static void
3537 analyze_candidates_and_replace (void)
3539 unsigned i;
3540 slsr_cand_t c;
3542 /* Each candidate that has a null basis and a non-null
3543 dependent is the root of a tree of related statements.
3544 Analyze each tree to determine a subset of those
3545 statements that can be replaced with maximum benefit. */
3546 FOR_EACH_VEC_ELT (cand_vec, i, c)
3548 slsr_cand_t first_dep;
3550 if (c->basis != 0 || c->dependent == 0)
3551 continue;
3553 if (dump_file && (dump_flags & TDF_DETAILS))
3554 fprintf (dump_file, "\nProcessing dependency tree rooted at %d.\n",
3555 c->cand_num);
3557 first_dep = lookup_cand (c->dependent);
3559 /* If this is a chain of CAND_REFs, unconditionally replace
3560 each of them with a strength-reduced data reference. */
3561 if (c->kind == CAND_REF)
3562 replace_refs (c);
3564 /* If the common stride of all related candidates is a known
3565 constant, each candidate without a phi-dependence can be
3566 profitably replaced. Each replaces a multiply by a single
3567 add, with the possibility that a feeding add also goes dead.
3568 A candidate with a phi-dependence is replaced only if the
3569 compensation code it requires is offset by the strength
3570 reduction savings. */
3571 else if (TREE_CODE (c->stride) == INTEGER_CST)
3572 replace_uncond_cands_and_profitable_phis (first_dep);
3574 /* When the stride is an SSA name, it may still be profitable
3575 to replace some or all of the dependent candidates, depending
3576 on whether the introduced increments can be reused, or are
3577 less expensive to calculate than the replaced statements. */
3578 else
3580 machine_mode mode;
3581 bool speed;
3583 /* Determine whether we'll be generating pointer arithmetic
3584 when replacing candidates. */
3585 address_arithmetic_p = (c->kind == CAND_ADD
3586 && POINTER_TYPE_P (c->cand_type));
3588 /* If all candidates have already been replaced under other
3589 interpretations, nothing remains to be done. */
3590 if (!count_candidates (c))
3591 continue;
3593 /* Construct an array of increments for this candidate chain. */
3594 incr_vec = XNEWVEC (incr_info, MAX_INCR_VEC_LEN);
3595 incr_vec_len = 0;
3596 record_increments (c);
3598 /* Determine which increments are profitable to replace. */
3599 mode = TYPE_MODE (TREE_TYPE (gimple_assign_lhs (c->cand_stmt)));
3600 speed = optimize_cands_for_speed_p (c);
3601 analyze_increments (first_dep, mode, speed);
3603 /* Insert initializers of the form T_0 = stride * increment
3604 for use in profitable replacements. */
3605 insert_initializers (first_dep);
3606 dump_incr_vec ();
3608 /* Perform the replacements. */
3609 replace_profitable_candidates (first_dep);
3610 free (incr_vec);
3615 namespace {
3617 const pass_data pass_data_strength_reduction =
3619 GIMPLE_PASS, /* type */
3620 "slsr", /* name */
3621 OPTGROUP_NONE, /* optinfo_flags */
3622 TV_GIMPLE_SLSR, /* tv_id */
3623 ( PROP_cfg | PROP_ssa ), /* properties_required */
3624 0, /* properties_provided */
3625 0, /* properties_destroyed */
3626 0, /* todo_flags_start */
3627 0, /* todo_flags_finish */
3630 class pass_strength_reduction : public gimple_opt_pass
3632 public:
3633 pass_strength_reduction (gcc::context *ctxt)
3634 : gimple_opt_pass (pass_data_strength_reduction, ctxt)
3637 /* opt_pass methods: */
3638 virtual bool gate (function *) { return flag_tree_slsr; }
3639 virtual unsigned int execute (function *);
3641 }; // class pass_strength_reduction
3643 unsigned
3644 pass_strength_reduction::execute (function *fun)
3646 /* Create the obstack where candidates will reside. */
3647 gcc_obstack_init (&cand_obstack);
3649 /* Allocate the candidate vector. */
3650 cand_vec.create (128);
3652 /* Allocate the mapping from statements to candidate indices. */
3653 stmt_cand_map = new hash_map<gimple, slsr_cand_t>;
3655 /* Create the obstack where candidate chains will reside. */
3656 gcc_obstack_init (&chain_obstack);
3658 /* Allocate the mapping from base expressions to candidate chains. */
3659 base_cand_map = new hash_table<cand_chain_hasher> (500);
3661 /* Allocate the mapping from bases to alternative bases. */
3662 alt_base_map = new hash_map<tree, tree>;
3664 /* Initialize the loop optimizer. We need to detect flow across
3665 back edges, and this gives us dominator information as well. */
3666 loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
3668 /* Walk the CFG in predominator order looking for strength reduction
3669 candidates. */
3670 find_candidates_dom_walker (CDI_DOMINATORS)
3671 .walk (fun->cfg->x_entry_block_ptr);
3673 if (dump_file && (dump_flags & TDF_DETAILS))
3675 dump_cand_vec ();
3676 dump_cand_chains ();
3679 delete alt_base_map;
3680 free_affine_expand_cache (&name_expansions);
3682 /* Analyze costs and make appropriate replacements. */
3683 analyze_candidates_and_replace ();
3685 loop_optimizer_finalize ();
3686 delete base_cand_map;
3687 base_cand_map = NULL;
3688 obstack_free (&chain_obstack, NULL);
3689 delete stmt_cand_map;
3690 cand_vec.release ();
3691 obstack_free (&cand_obstack, NULL);
3693 return 0;
3696 } // anon namespace
3698 gimple_opt_pass *
3699 make_pass_strength_reduction (gcc::context *ctxt)
3701 return new pass_strength_reduction (ctxt);