2013-05-03 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / gimple-ssa-strength-reduction.c
blob9f4902d424fcb92716d865bfb6861dd273678afb
1 /* Straight-line strength reduction.
2 Copyright (C) 2012-2013 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 will be implemented in four stages, gradually
28 adding more complex candidates:
30 1) Explicit multiplies, known constant multipliers, no
31 conditional increments. (complete)
32 2) Explicit multiplies, unknown constant multipliers,
33 no conditional increments. (complete)
34 3) Implicit multiplies in addressing expressions. (complete)
35 4) Explicit multiplies, conditional increments. (pending)
37 It would also be possible to apply strength reduction to divisions
38 and modulos, but such opportunities are relatively uncommon.
40 Strength reduction is also currently restricted to integer operations.
41 If desired, it could be extended to floating-point operations under
42 control of something like -funsafe-math-optimizations. */
44 #include "config.h"
45 #include "system.h"
46 #include "coretypes.h"
47 #include "tree.h"
48 #include "gimple.h"
49 #include "basic-block.h"
50 #include "tree-pass.h"
51 #include "cfgloop.h"
52 #include "gimple-pretty-print.h"
53 #include "tree-flow.h"
54 #include "domwalk.h"
55 #include "pointer-set.h"
56 #include "expmed.h"
57 #include "params.h"
58 #include "hash-table.h"
60 /* Information about a strength reduction candidate. Each statement
61 in the candidate table represents an expression of one of the
62 following forms (the special case of CAND_REF will be described
63 later):
65 (CAND_MULT) S1: X = (B + i) * S
66 (CAND_ADD) S1: X = B + (i * S)
68 Here X and B are SSA names, i is an integer constant, and S is
69 either an SSA name or a constant. We call B the "base," i the
70 "index", and S the "stride."
72 Any statement S0 that dominates S1 and is of the form:
74 (CAND_MULT) S0: Y = (B + i') * S
75 (CAND_ADD) S0: Y = B + (i' * S)
77 is called a "basis" for S1. In both cases, S1 may be replaced by
79 S1': X = Y + (i - i') * S,
81 where (i - i') * S is folded to the extent possible.
83 All gimple statements are visited in dominator order, and each
84 statement that may contribute to one of the forms of S1 above is
85 given at least one entry in the candidate table. Such statements
86 include addition, pointer addition, subtraction, multiplication,
87 negation, copies, and nontrivial type casts. If a statement may
88 represent more than one expression of the forms of S1 above,
89 multiple "interpretations" are stored in the table and chained
90 together. Examples:
92 * An add of two SSA names may treat either operand as the base.
93 * A multiply of two SSA names, likewise.
94 * A copy or cast may be thought of as either a CAND_MULT with
95 i = 0 and S = 1, or as a CAND_ADD with i = 0 or S = 0.
97 Candidate records are allocated from an obstack. They are addressed
98 both from a hash table keyed on S1, and from a vector of candidate
99 pointers arranged in predominator order.
101 Opportunity note
102 ----------------
103 Currently we don't recognize:
105 S0: Y = (S * i') - B
106 S1: X = (S * i) - B
108 as a strength reduction opportunity, even though this S1 would
109 also be replaceable by the S1' above. This can be added if it
110 comes up in practice.
112 Strength reduction in addressing
113 --------------------------------
114 There is another kind of candidate known as CAND_REF. A CAND_REF
115 describes a statement containing a memory reference having
116 complex addressing that might benefit from strength reduction.
117 Specifically, we are interested in references for which
118 get_inner_reference returns a base address, offset, and bitpos as
119 follows:
121 base: MEM_REF (T1, C1)
122 offset: MULT_EXPR (PLUS_EXPR (T2, C2), C3)
123 bitpos: C4 * BITS_PER_UNIT
125 Here T1 and T2 are arbitrary trees, and C1, C2, C3, C4 are
126 arbitrary integer constants. Note that C2 may be zero, in which
127 case the offset will be MULT_EXPR (T2, C3).
129 When this pattern is recognized, the original memory reference
130 can be replaced with:
132 MEM_REF (POINTER_PLUS_EXPR (T1, MULT_EXPR (T2, C3)),
133 C1 + (C2 * C3) + C4)
135 which distributes the multiply to allow constant folding. When
136 two or more addressing expressions can be represented by MEM_REFs
137 of this form, differing only in the constants C1, C2, and C4,
138 making this substitution produces more efficient addressing during
139 the RTL phases. When there are not at least two expressions with
140 the same values of T1, T2, and C3, there is nothing to be gained
141 by the replacement.
143 Strength reduction of CAND_REFs uses the same infrastructure as
144 that used by CAND_MULTs and CAND_ADDs. We record T1 in the base (B)
145 field, MULT_EXPR (T2, C3) in the stride (S) field, and
146 C1 + (C2 * C3) + C4 in the index (i) field. A basis for a CAND_REF
147 is thus another CAND_REF with the same B and S values. When at
148 least two CAND_REFs are chained together using the basis relation,
149 each of them is replaced as above, resulting in improved code
150 generation for addressing. */
153 /* Index into the candidate vector, offset by 1. VECs are zero-based,
154 while cand_idx's are one-based, with zero indicating null. */
155 typedef unsigned cand_idx;
157 /* The kind of candidate. */
158 enum cand_kind
160 CAND_MULT,
161 CAND_ADD,
162 CAND_REF
165 struct slsr_cand_d
167 /* The candidate statement S1. */
168 gimple cand_stmt;
170 /* The base expression B: often an SSA name, but not always. */
171 tree base_expr;
173 /* The stride S. */
174 tree stride;
176 /* The index constant i. */
177 double_int index;
179 /* The type of the candidate. This is normally the type of base_expr,
180 but casts may have occurred when combining feeding instructions.
181 A candidate can only be a basis for candidates of the same final type.
182 (For CAND_REFs, this is the type to be used for operand 1 of the
183 replacement MEM_REF.) */
184 tree cand_type;
186 /* The kind of candidate (CAND_MULT, etc.). */
187 enum cand_kind kind;
189 /* Index of this candidate in the candidate vector. */
190 cand_idx cand_num;
192 /* Index of the next candidate record for the same statement.
193 A statement may be useful in more than one way (e.g., due to
194 commutativity). So we can have multiple "interpretations"
195 of a statement. */
196 cand_idx next_interp;
198 /* Index of the basis statement S0, if any, in the candidate vector. */
199 cand_idx basis;
201 /* First candidate for which this candidate is a basis, if one exists. */
202 cand_idx dependent;
204 /* Next candidate having the same basis as this one. */
205 cand_idx sibling;
207 /* If this is a conditional candidate, the defining PHI statement
208 for the base SSA name B. For future use; always NULL for now. */
209 gimple def_phi;
211 /* Savings that can be expected from eliminating dead code if this
212 candidate is replaced. */
213 int dead_savings;
216 typedef struct slsr_cand_d slsr_cand, *slsr_cand_t;
217 typedef const struct slsr_cand_d *const_slsr_cand_t;
219 /* Pointers to candidates are chained together as part of a mapping
220 from base expressions to the candidates that use them. */
222 struct cand_chain_d
224 /* Base expression for the chain of candidates: often, but not
225 always, an SSA name. */
226 tree base_expr;
228 /* Pointer to a candidate. */
229 slsr_cand_t cand;
231 /* Chain pointer. */
232 struct cand_chain_d *next;
236 typedef struct cand_chain_d cand_chain, *cand_chain_t;
237 typedef const struct cand_chain_d *const_cand_chain_t;
239 /* Information about a unique "increment" associated with candidates
240 having an SSA name for a stride. An increment is the difference
241 between the index of the candidate and the index of its basis,
242 i.e., (i - i') as discussed in the module commentary.
244 When we are not going to generate address arithmetic we treat
245 increments that differ only in sign as the same, allowing sharing
246 of the cost of initializers. The absolute value of the increment
247 is stored in the incr_info. */
249 struct incr_info_d
251 /* The increment that relates a candidate to its basis. */
252 double_int incr;
254 /* How many times the increment occurs in the candidate tree. */
255 unsigned count;
257 /* Cost of replacing candidates using this increment. Negative and
258 zero costs indicate replacement should be performed. */
259 int cost;
261 /* If this increment is profitable but is not -1, 0, or 1, it requires
262 an initializer T_0 = stride * incr to be found or introduced in the
263 nearest common dominator of all candidates. This field holds T_0
264 for subsequent use. */
265 tree initializer;
267 /* If the initializer was found to already exist, this is the block
268 where it was found. */
269 basic_block init_bb;
272 typedef struct incr_info_d incr_info, *incr_info_t;
274 /* Candidates are maintained in a vector. If candidate X dominates
275 candidate Y, then X appears before Y in the vector; but the
276 converse does not necessarily hold. */
277 static vec<slsr_cand_t> cand_vec;
279 enum cost_consts
281 COST_NEUTRAL = 0,
282 COST_INFINITE = 1000
285 /* Pointer map embodying a mapping from statements to candidates. */
286 static struct pointer_map_t *stmt_cand_map;
288 /* Obstack for candidates. */
289 static struct obstack cand_obstack;
291 /* Obstack for candidate chains. */
292 static struct obstack chain_obstack;
294 /* An array INCR_VEC of incr_infos is used during analysis of related
295 candidates having an SSA name for a stride. INCR_VEC_LEN describes
296 its current length. */
297 static incr_info_t incr_vec;
298 static unsigned incr_vec_len;
300 /* For a chain of candidates with unknown stride, indicates whether or not
301 we must generate pointer arithmetic when replacing statements. */
302 static bool address_arithmetic_p;
304 /* Produce a pointer to the IDX'th candidate in the candidate vector. */
306 static slsr_cand_t
307 lookup_cand (cand_idx idx)
309 return cand_vec[idx - 1];
312 /* Helper for hashing a candidate chain header. */
314 struct cand_chain_hasher : typed_noop_remove <cand_chain>
316 typedef cand_chain value_type;
317 typedef cand_chain compare_type;
318 static inline hashval_t hash (const value_type *);
319 static inline bool equal (const value_type *, const compare_type *);
322 inline hashval_t
323 cand_chain_hasher::hash (const value_type *p)
325 tree base_expr = p->base_expr;
326 return iterative_hash_expr (base_expr, 0);
329 inline bool
330 cand_chain_hasher::equal (const value_type *chain1, const compare_type *chain2)
332 return operand_equal_p (chain1->base_expr, chain2->base_expr, 0);
335 /* Hash table embodying a mapping from base exprs to chains of candidates. */
336 static hash_table <cand_chain_hasher> base_cand_map;
338 /* Use the base expr from candidate C to look for possible candidates
339 that can serve as a basis for C. Each potential basis must also
340 appear in a block that dominates the candidate statement and have
341 the same stride and type. If more than one possible basis exists,
342 the one with highest index in the vector is chosen; this will be
343 the most immediately dominating basis. */
345 static int
346 find_basis_for_candidate (slsr_cand_t c)
348 cand_chain mapping_key;
349 cand_chain_t chain;
350 slsr_cand_t basis = NULL;
352 // Limit potential of N^2 behavior for long candidate chains.
353 int iters = 0;
354 int max_iters = PARAM_VALUE (PARAM_MAX_SLSR_CANDIDATE_SCAN);
356 mapping_key.base_expr = c->base_expr;
357 chain = base_cand_map.find (&mapping_key);
359 for (; chain && iters < max_iters; chain = chain->next, ++iters)
361 slsr_cand_t one_basis = chain->cand;
363 if (one_basis->kind != c->kind
364 || one_basis->cand_stmt == c->cand_stmt
365 || !operand_equal_p (one_basis->stride, c->stride, 0)
366 || !types_compatible_p (one_basis->cand_type, c->cand_type)
367 || !dominated_by_p (CDI_DOMINATORS,
368 gimple_bb (c->cand_stmt),
369 gimple_bb (one_basis->cand_stmt)))
370 continue;
372 if (!basis || basis->cand_num < one_basis->cand_num)
373 basis = one_basis;
376 if (basis)
378 c->sibling = basis->dependent;
379 basis->dependent = c->cand_num;
380 return basis->cand_num;
383 return 0;
386 /* Record a mapping from the base expression of C to C itself, indicating that
387 C may potentially serve as a basis using that base expression. */
389 static void
390 record_potential_basis (slsr_cand_t c)
392 cand_chain_t node;
393 cand_chain **slot;
395 node = (cand_chain_t) obstack_alloc (&chain_obstack, sizeof (cand_chain));
396 node->base_expr = c->base_expr;
397 node->cand = c;
398 node->next = NULL;
399 slot = base_cand_map.find_slot (node, INSERT);
401 if (*slot)
403 cand_chain_t head = (cand_chain_t) (*slot);
404 node->next = head->next;
405 head->next = node;
407 else
408 *slot = node;
411 /* Allocate storage for a new candidate and initialize its fields.
412 Attempt to find a basis for the candidate. */
414 static slsr_cand_t
415 alloc_cand_and_find_basis (enum cand_kind kind, gimple gs, tree base,
416 double_int index, tree stride, tree ctype,
417 unsigned savings)
419 slsr_cand_t c = (slsr_cand_t) obstack_alloc (&cand_obstack,
420 sizeof (slsr_cand));
421 c->cand_stmt = gs;
422 c->base_expr = base;
423 c->stride = stride;
424 c->index = index;
425 c->cand_type = ctype;
426 c->kind = kind;
427 c->cand_num = cand_vec.length () + 1;
428 c->next_interp = 0;
429 c->dependent = 0;
430 c->sibling = 0;
431 c->def_phi = NULL;
432 c->dead_savings = savings;
434 cand_vec.safe_push (c);
435 c->basis = find_basis_for_candidate (c);
436 record_potential_basis (c);
438 return c;
441 /* Determine the target cost of statement GS when compiling according
442 to SPEED. */
444 static int
445 stmt_cost (gimple gs, bool speed)
447 tree lhs, rhs1, rhs2;
448 enum machine_mode lhs_mode;
450 gcc_assert (is_gimple_assign (gs));
451 lhs = gimple_assign_lhs (gs);
452 rhs1 = gimple_assign_rhs1 (gs);
453 lhs_mode = TYPE_MODE (TREE_TYPE (lhs));
455 switch (gimple_assign_rhs_code (gs))
457 case MULT_EXPR:
458 rhs2 = gimple_assign_rhs2 (gs);
460 if (host_integerp (rhs2, 0))
461 return mult_by_coeff_cost (TREE_INT_CST_LOW (rhs2), lhs_mode, speed);
463 gcc_assert (TREE_CODE (rhs1) != INTEGER_CST);
464 return mul_cost (speed, lhs_mode);
466 case PLUS_EXPR:
467 case POINTER_PLUS_EXPR:
468 case MINUS_EXPR:
469 return add_cost (speed, lhs_mode);
471 case NEGATE_EXPR:
472 return neg_cost (speed, lhs_mode);
474 case NOP_EXPR:
475 return convert_cost (lhs_mode, TYPE_MODE (TREE_TYPE (rhs1)), speed);
477 /* Note that we don't assign costs to copies that in most cases
478 will go away. */
479 default:
483 gcc_unreachable ();
484 return 0;
487 /* Look up the defining statement for BASE_IN and return a pointer
488 to its candidate in the candidate table, if any; otherwise NULL.
489 Only CAND_ADD and CAND_MULT candidates are returned. */
491 static slsr_cand_t
492 base_cand_from_table (tree base_in)
494 slsr_cand_t *result;
496 gimple def = SSA_NAME_DEF_STMT (base_in);
497 if (!def)
498 return (slsr_cand_t) NULL;
500 result = (slsr_cand_t *) pointer_map_contains (stmt_cand_map, def);
502 if (result && (*result)->kind != CAND_REF)
503 return *result;
505 return (slsr_cand_t) NULL;
508 /* Add an entry to the statement-to-candidate mapping. */
510 static void
511 add_cand_for_stmt (gimple gs, slsr_cand_t c)
513 void **slot = pointer_map_insert (stmt_cand_map, gs);
514 gcc_assert (!*slot);
515 *slot = c;
518 /* Look for the following pattern:
520 *PBASE: MEM_REF (T1, C1)
522 *POFFSET: MULT_EXPR (T2, C3) [C2 is zero]
524 MULT_EXPR (PLUS_EXPR (T2, C2), C3)
526 MULT_EXPR (MINUS_EXPR (T2, -C2), C3)
528 *PINDEX: C4 * BITS_PER_UNIT
530 If not present, leave the input values unchanged and return FALSE.
531 Otherwise, modify the input values as follows and return TRUE:
533 *PBASE: T1
534 *POFFSET: MULT_EXPR (T2, C3)
535 *PINDEX: C1 + (C2 * C3) + C4 */
537 static bool
538 restructure_reference (tree *pbase, tree *poffset, double_int *pindex,
539 tree *ptype)
541 tree base = *pbase, offset = *poffset;
542 double_int index = *pindex;
543 double_int bpu = double_int::from_uhwi (BITS_PER_UNIT);
544 tree mult_op0, mult_op1, t1, t2, type;
545 double_int c1, c2, c3, c4;
547 if (!base
548 || !offset
549 || TREE_CODE (base) != MEM_REF
550 || TREE_CODE (offset) != MULT_EXPR
551 || TREE_CODE (TREE_OPERAND (offset, 1)) != INTEGER_CST
552 || !index.umod (bpu, FLOOR_MOD_EXPR).is_zero ())
553 return false;
555 t1 = TREE_OPERAND (base, 0);
556 c1 = mem_ref_offset (base);
557 type = TREE_TYPE (TREE_OPERAND (base, 1));
559 mult_op0 = TREE_OPERAND (offset, 0);
560 mult_op1 = TREE_OPERAND (offset, 1);
562 c3 = tree_to_double_int (mult_op1);
564 if (TREE_CODE (mult_op0) == PLUS_EXPR)
566 if (TREE_CODE (TREE_OPERAND (mult_op0, 1)) == INTEGER_CST)
568 t2 = TREE_OPERAND (mult_op0, 0);
569 c2 = tree_to_double_int (TREE_OPERAND (mult_op0, 1));
571 else
572 return false;
574 else if (TREE_CODE (mult_op0) == MINUS_EXPR)
576 if (TREE_CODE (TREE_OPERAND (mult_op0, 1)) == INTEGER_CST)
578 t2 = TREE_OPERAND (mult_op0, 0);
579 c2 = -tree_to_double_int (TREE_OPERAND (mult_op0, 1));
581 else
582 return false;
584 else
586 t2 = mult_op0;
587 c2 = double_int_zero;
590 c4 = index.udiv (bpu, FLOOR_DIV_EXPR);
592 *pbase = t1;
593 *poffset = fold_build2 (MULT_EXPR, sizetype, t2,
594 double_int_to_tree (sizetype, c3));
595 *pindex = c1 + c2 * c3 + c4;
596 *ptype = type;
598 return true;
601 /* Given GS which contains a data reference, create a CAND_REF entry in
602 the candidate table and attempt to find a basis. */
604 static void
605 slsr_process_ref (gimple gs)
607 tree ref_expr, base, offset, type;
608 HOST_WIDE_INT bitsize, bitpos;
609 enum machine_mode mode;
610 int unsignedp, volatilep;
611 double_int index;
612 slsr_cand_t c;
614 if (gimple_vdef (gs))
615 ref_expr = gimple_assign_lhs (gs);
616 else
617 ref_expr = gimple_assign_rhs1 (gs);
619 if (!handled_component_p (ref_expr)
620 || TREE_CODE (ref_expr) == BIT_FIELD_REF
621 || (TREE_CODE (ref_expr) == COMPONENT_REF
622 && DECL_BIT_FIELD (TREE_OPERAND (ref_expr, 1))))
623 return;
625 base = get_inner_reference (ref_expr, &bitsize, &bitpos, &offset, &mode,
626 &unsignedp, &volatilep, false);
627 index = double_int::from_uhwi (bitpos);
629 if (!restructure_reference (&base, &offset, &index, &type))
630 return;
632 c = alloc_cand_and_find_basis (CAND_REF, gs, base, index, offset,
633 type, 0);
635 /* Add the candidate to the statement-candidate mapping. */
636 add_cand_for_stmt (gs, c);
639 /* Create a candidate entry for a statement GS, where GS multiplies
640 two SSA names BASE_IN and STRIDE_IN. Propagate any known information
641 about the two SSA names into the new candidate. Return the new
642 candidate. */
644 static slsr_cand_t
645 create_mul_ssa_cand (gimple gs, tree base_in, tree stride_in, bool speed)
647 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
648 double_int index;
649 unsigned savings = 0;
650 slsr_cand_t c;
651 slsr_cand_t base_cand = base_cand_from_table (base_in);
653 /* Look at all interpretations of the base candidate, if necessary,
654 to find information to propagate into this candidate. */
655 while (base_cand && !base)
658 if (base_cand->kind == CAND_MULT
659 && operand_equal_p (base_cand->stride, integer_one_node, 0))
661 /* Y = (B + i') * 1
662 X = Y * Z
663 ================
664 X = (B + i') * Z */
665 base = base_cand->base_expr;
666 index = base_cand->index;
667 stride = stride_in;
668 ctype = base_cand->cand_type;
669 if (has_single_use (base_in))
670 savings = (base_cand->dead_savings
671 + stmt_cost (base_cand->cand_stmt, speed));
673 else if (base_cand->kind == CAND_ADD
674 && TREE_CODE (base_cand->stride) == INTEGER_CST)
676 /* Y = B + (i' * S), S constant
677 X = Y * Z
678 ============================
679 X = B + ((i' * S) * Z) */
680 base = base_cand->base_expr;
681 index = base_cand->index * tree_to_double_int (base_cand->stride);
682 stride = stride_in;
683 ctype = base_cand->cand_type;
684 if (has_single_use (base_in))
685 savings = (base_cand->dead_savings
686 + stmt_cost (base_cand->cand_stmt, speed));
689 if (base_cand->next_interp)
690 base_cand = lookup_cand (base_cand->next_interp);
691 else
692 base_cand = NULL;
695 if (!base)
697 /* No interpretations had anything useful to propagate, so
698 produce X = (Y + 0) * Z. */
699 base = base_in;
700 index = double_int_zero;
701 stride = stride_in;
702 ctype = TREE_TYPE (base_in);
705 c = alloc_cand_and_find_basis (CAND_MULT, gs, base, index, stride,
706 ctype, savings);
707 return c;
710 /* Create a candidate entry for a statement GS, where GS multiplies
711 SSA name BASE_IN by constant STRIDE_IN. Propagate any known
712 information about BASE_IN into the new candidate. Return the new
713 candidate. */
715 static slsr_cand_t
716 create_mul_imm_cand (gimple gs, tree base_in, tree stride_in, bool speed)
718 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
719 double_int index, temp;
720 unsigned savings = 0;
721 slsr_cand_t c;
722 slsr_cand_t base_cand = base_cand_from_table (base_in);
724 /* Look at all interpretations of the base candidate, if necessary,
725 to find information to propagate into this candidate. */
726 while (base_cand && !base)
728 if (base_cand->kind == CAND_MULT
729 && TREE_CODE (base_cand->stride) == INTEGER_CST)
731 /* Y = (B + i') * S, S constant
732 X = Y * c
733 ============================
734 X = (B + i') * (S * c) */
735 base = base_cand->base_expr;
736 index = base_cand->index;
737 temp = tree_to_double_int (base_cand->stride)
738 * tree_to_double_int (stride_in);
739 stride = double_int_to_tree (TREE_TYPE (stride_in), temp);
740 ctype = base_cand->cand_type;
741 if (has_single_use (base_in))
742 savings = (base_cand->dead_savings
743 + stmt_cost (base_cand->cand_stmt, speed));
745 else if (base_cand->kind == CAND_ADD
746 && operand_equal_p (base_cand->stride, integer_one_node, 0))
748 /* Y = B + (i' * 1)
749 X = Y * c
750 ===========================
751 X = (B + i') * c */
752 base = base_cand->base_expr;
753 index = base_cand->index;
754 stride = stride_in;
755 ctype = base_cand->cand_type;
756 if (has_single_use (base_in))
757 savings = (base_cand->dead_savings
758 + stmt_cost (base_cand->cand_stmt, speed));
760 else if (base_cand->kind == CAND_ADD
761 && base_cand->index.is_one ()
762 && TREE_CODE (base_cand->stride) == INTEGER_CST)
764 /* Y = B + (1 * S), S constant
765 X = Y * c
766 ===========================
767 X = (B + S) * c */
768 base = base_cand->base_expr;
769 index = tree_to_double_int (base_cand->stride);
770 stride = stride_in;
771 ctype = base_cand->cand_type;
772 if (has_single_use (base_in))
773 savings = (base_cand->dead_savings
774 + stmt_cost (base_cand->cand_stmt, speed));
777 if (base_cand->next_interp)
778 base_cand = lookup_cand (base_cand->next_interp);
779 else
780 base_cand = NULL;
783 if (!base)
785 /* No interpretations had anything useful to propagate, so
786 produce X = (Y + 0) * c. */
787 base = base_in;
788 index = double_int_zero;
789 stride = stride_in;
790 ctype = TREE_TYPE (base_in);
793 c = alloc_cand_and_find_basis (CAND_MULT, gs, base, index, stride,
794 ctype, savings);
795 return c;
798 /* Given GS which is a multiply of scalar integers, make an appropriate
799 entry in the candidate table. If this is a multiply of two SSA names,
800 create two CAND_MULT interpretations and attempt to find a basis for
801 each of them. Otherwise, create a single CAND_MULT and attempt to
802 find a basis. */
804 static void
805 slsr_process_mul (gimple gs, tree rhs1, tree rhs2, bool speed)
807 slsr_cand_t c, c2;
809 /* If this is a multiply of an SSA name with itself, it is highly
810 unlikely that we will get a strength reduction opportunity, so
811 don't record it as a candidate. This simplifies the logic for
812 finding a basis, so if this is removed that must be considered. */
813 if (rhs1 == rhs2)
814 return;
816 if (TREE_CODE (rhs2) == SSA_NAME)
818 /* Record an interpretation of this statement in the candidate table
819 assuming RHS1 is the base expression and RHS2 is the stride. */
820 c = create_mul_ssa_cand (gs, rhs1, rhs2, speed);
822 /* Add the first interpretation to the statement-candidate mapping. */
823 add_cand_for_stmt (gs, c);
825 /* Record another interpretation of this statement assuming RHS1
826 is the stride and RHS2 is the base expression. */
827 c2 = create_mul_ssa_cand (gs, rhs2, rhs1, speed);
828 c->next_interp = c2->cand_num;
830 else
832 /* Record an interpretation for the multiply-immediate. */
833 c = create_mul_imm_cand (gs, rhs1, rhs2, speed);
835 /* Add the interpretation to the statement-candidate mapping. */
836 add_cand_for_stmt (gs, c);
840 /* Create a candidate entry for a statement GS, where GS adds two
841 SSA names BASE_IN and ADDEND_IN if SUBTRACT_P is false, and
842 subtracts ADDEND_IN from BASE_IN otherwise. Propagate any known
843 information about the two SSA names into the new candidate.
844 Return the new candidate. */
846 static slsr_cand_t
847 create_add_ssa_cand (gimple gs, tree base_in, tree addend_in,
848 bool subtract_p, bool speed)
850 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL;
851 double_int index;
852 unsigned savings = 0;
853 slsr_cand_t c;
854 slsr_cand_t base_cand = base_cand_from_table (base_in);
855 slsr_cand_t addend_cand = base_cand_from_table (addend_in);
857 /* The most useful transformation is a multiply-immediate feeding
858 an add or subtract. Look for that first. */
859 while (addend_cand && !base)
861 if (addend_cand->kind == CAND_MULT
862 && addend_cand->index.is_zero ()
863 && TREE_CODE (addend_cand->stride) == INTEGER_CST)
865 /* Z = (B + 0) * S, S constant
866 X = Y +/- Z
867 ===========================
868 X = Y + ((+/-1 * S) * B) */
869 base = base_in;
870 index = tree_to_double_int (addend_cand->stride);
871 if (subtract_p)
872 index = -index;
873 stride = addend_cand->base_expr;
874 ctype = TREE_TYPE (base_in);
875 if (has_single_use (addend_in))
876 savings = (addend_cand->dead_savings
877 + stmt_cost (addend_cand->cand_stmt, speed));
880 if (addend_cand->next_interp)
881 addend_cand = lookup_cand (addend_cand->next_interp);
882 else
883 addend_cand = NULL;
886 while (base_cand && !base)
888 if (base_cand->kind == CAND_ADD
889 && (base_cand->index.is_zero ()
890 || operand_equal_p (base_cand->stride,
891 integer_zero_node, 0)))
893 /* Y = B + (i' * S), i' * S = 0
894 X = Y +/- Z
895 ============================
896 X = B + (+/-1 * Z) */
897 base = base_cand->base_expr;
898 index = subtract_p ? double_int_minus_one : double_int_one;
899 stride = addend_in;
900 ctype = base_cand->cand_type;
901 if (has_single_use (base_in))
902 savings = (base_cand->dead_savings
903 + stmt_cost (base_cand->cand_stmt, speed));
905 else if (subtract_p)
907 slsr_cand_t subtrahend_cand = base_cand_from_table (addend_in);
909 while (subtrahend_cand && !base)
911 if (subtrahend_cand->kind == CAND_MULT
912 && subtrahend_cand->index.is_zero ()
913 && TREE_CODE (subtrahend_cand->stride) == INTEGER_CST)
915 /* Z = (B + 0) * S, S constant
916 X = Y - Z
917 ===========================
918 Value: X = Y + ((-1 * S) * B) */
919 base = base_in;
920 index = tree_to_double_int (subtrahend_cand->stride);
921 index = -index;
922 stride = subtrahend_cand->base_expr;
923 ctype = TREE_TYPE (base_in);
924 if (has_single_use (addend_in))
925 savings = (subtrahend_cand->dead_savings
926 + stmt_cost (subtrahend_cand->cand_stmt, speed));
929 if (subtrahend_cand->next_interp)
930 subtrahend_cand = lookup_cand (subtrahend_cand->next_interp);
931 else
932 subtrahend_cand = NULL;
936 if (base_cand->next_interp)
937 base_cand = lookup_cand (base_cand->next_interp);
938 else
939 base_cand = NULL;
942 if (!base)
944 /* No interpretations had anything useful to propagate, so
945 produce X = Y + (1 * Z). */
946 base = base_in;
947 index = subtract_p ? double_int_minus_one : double_int_one;
948 stride = addend_in;
949 ctype = TREE_TYPE (base_in);
952 c = alloc_cand_and_find_basis (CAND_ADD, gs, base, index, stride,
953 ctype, savings);
954 return c;
957 /* Create a candidate entry for a statement GS, where GS adds SSA
958 name BASE_IN to constant INDEX_IN. Propagate any known information
959 about BASE_IN into the new candidate. Return the new candidate. */
961 static slsr_cand_t
962 create_add_imm_cand (gimple gs, tree base_in, double_int index_in, bool speed)
964 enum cand_kind kind = CAND_ADD;
965 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
966 double_int index, multiple;
967 unsigned savings = 0;
968 slsr_cand_t c;
969 slsr_cand_t base_cand = base_cand_from_table (base_in);
971 while (base_cand && !base)
973 bool unsigned_p = TYPE_UNSIGNED (TREE_TYPE (base_cand->stride));
975 if (TREE_CODE (base_cand->stride) == INTEGER_CST
976 && index_in.multiple_of (tree_to_double_int (base_cand->stride),
977 unsigned_p, &multiple))
979 /* Y = (B + i') * S, S constant, c = kS for some integer k
980 X = Y + c
981 ============================
982 X = (B + (i'+ k)) * S
984 Y = B + (i' * S), S constant, c = kS for some integer k
985 X = Y + c
986 ============================
987 X = (B + (i'+ k)) * S */
988 kind = base_cand->kind;
989 base = base_cand->base_expr;
990 index = base_cand->index + multiple;
991 stride = base_cand->stride;
992 ctype = base_cand->cand_type;
993 if (has_single_use (base_in))
994 savings = (base_cand->dead_savings
995 + stmt_cost (base_cand->cand_stmt, speed));
998 if (base_cand->next_interp)
999 base_cand = lookup_cand (base_cand->next_interp);
1000 else
1001 base_cand = NULL;
1004 if (!base)
1006 /* No interpretations had anything useful to propagate, so
1007 produce X = Y + (c * 1). */
1008 kind = CAND_ADD;
1009 base = base_in;
1010 index = index_in;
1011 stride = integer_one_node;
1012 ctype = TREE_TYPE (base_in);
1015 c = alloc_cand_and_find_basis (kind, gs, base, index, stride,
1016 ctype, savings);
1017 return c;
1020 /* Given GS which is an add or subtract of scalar integers or pointers,
1021 make at least one appropriate entry in the candidate table. */
1023 static void
1024 slsr_process_add (gimple gs, tree rhs1, tree rhs2, bool speed)
1026 bool subtract_p = gimple_assign_rhs_code (gs) == MINUS_EXPR;
1027 slsr_cand_t c = NULL, c2;
1029 if (TREE_CODE (rhs2) == SSA_NAME)
1031 /* First record an interpretation assuming RHS1 is the base expression
1032 and RHS2 is the stride. But it doesn't make sense for the
1033 stride to be a pointer, so don't record a candidate in that case. */
1034 if (!POINTER_TYPE_P (TREE_TYPE (rhs2)))
1036 c = create_add_ssa_cand (gs, rhs1, rhs2, subtract_p, speed);
1038 /* Add the first interpretation to the statement-candidate
1039 mapping. */
1040 add_cand_for_stmt (gs, c);
1043 /* If the two RHS operands are identical, or this is a subtract,
1044 we're done. */
1045 if (operand_equal_p (rhs1, rhs2, 0) || subtract_p)
1046 return;
1048 /* Otherwise, record another interpretation assuming RHS2 is the
1049 base expression and RHS1 is the stride, again provided that the
1050 stride is not a pointer. */
1051 if (!POINTER_TYPE_P (TREE_TYPE (rhs1)))
1053 c2 = create_add_ssa_cand (gs, rhs2, rhs1, false, speed);
1054 if (c)
1055 c->next_interp = c2->cand_num;
1056 else
1057 add_cand_for_stmt (gs, c2);
1060 else
1062 double_int index;
1064 /* Record an interpretation for the add-immediate. */
1065 index = tree_to_double_int (rhs2);
1066 if (subtract_p)
1067 index = -index;
1069 c = create_add_imm_cand (gs, rhs1, index, speed);
1071 /* Add the interpretation to the statement-candidate mapping. */
1072 add_cand_for_stmt (gs, c);
1076 /* Given GS which is a negate of a scalar integer, make an appropriate
1077 entry in the candidate table. A negate is equivalent to a multiply
1078 by -1. */
1080 static void
1081 slsr_process_neg (gimple gs, tree rhs1, bool speed)
1083 /* Record a CAND_MULT interpretation for the multiply by -1. */
1084 slsr_cand_t c = create_mul_imm_cand (gs, rhs1, integer_minus_one_node, speed);
1086 /* Add the interpretation to the statement-candidate mapping. */
1087 add_cand_for_stmt (gs, c);
1090 /* Help function for legal_cast_p, operating on two trees. Checks
1091 whether it's allowable to cast from RHS to LHS. See legal_cast_p
1092 for more details. */
1094 static bool
1095 legal_cast_p_1 (tree lhs, tree rhs)
1097 tree lhs_type, rhs_type;
1098 unsigned lhs_size, rhs_size;
1099 bool lhs_wraps, rhs_wraps;
1101 lhs_type = TREE_TYPE (lhs);
1102 rhs_type = TREE_TYPE (rhs);
1103 lhs_size = TYPE_PRECISION (lhs_type);
1104 rhs_size = TYPE_PRECISION (rhs_type);
1105 lhs_wraps = TYPE_OVERFLOW_WRAPS (lhs_type);
1106 rhs_wraps = TYPE_OVERFLOW_WRAPS (rhs_type);
1108 if (lhs_size < rhs_size
1109 || (rhs_wraps && !lhs_wraps)
1110 || (rhs_wraps && lhs_wraps && rhs_size != lhs_size))
1111 return false;
1113 return true;
1116 /* Return TRUE if GS is a statement that defines an SSA name from
1117 a conversion and is legal for us to combine with an add and multiply
1118 in the candidate table. For example, suppose we have:
1120 A = B + i;
1121 C = (type) A;
1122 D = C * S;
1124 Without the type-cast, we would create a CAND_MULT for D with base B,
1125 index i, and stride S. We want to record this candidate only if it
1126 is equivalent to apply the type cast following the multiply:
1128 A = B + i;
1129 E = A * S;
1130 D = (type) E;
1132 We will record the type with the candidate for D. This allows us
1133 to use a similar previous candidate as a basis. If we have earlier seen
1135 A' = B + i';
1136 C' = (type) A';
1137 D' = C' * S;
1139 we can replace D with
1141 D = D' + (i - i') * S;
1143 But if moving the type-cast would change semantics, we mustn't do this.
1145 This is legitimate for casts from a non-wrapping integral type to
1146 any integral type of the same or larger size. It is not legitimate
1147 to convert a wrapping type to a non-wrapping type, or to a wrapping
1148 type of a different size. I.e., with a wrapping type, we must
1149 assume that the addition B + i could wrap, in which case performing
1150 the multiply before or after one of the "illegal" type casts will
1151 have different semantics. */
1153 static bool
1154 legal_cast_p (gimple gs, tree rhs)
1156 if (!is_gimple_assign (gs)
1157 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (gs)))
1158 return false;
1160 return legal_cast_p_1 (gimple_assign_lhs (gs), rhs);
1163 /* Given GS which is a cast to a scalar integer type, determine whether
1164 the cast is legal for strength reduction. If so, make at least one
1165 appropriate entry in the candidate table. */
1167 static void
1168 slsr_process_cast (gimple gs, tree rhs1, bool speed)
1170 tree lhs, ctype;
1171 slsr_cand_t base_cand, c, c2;
1172 unsigned savings = 0;
1174 if (!legal_cast_p (gs, rhs1))
1175 return;
1177 lhs = gimple_assign_lhs (gs);
1178 base_cand = base_cand_from_table (rhs1);
1179 ctype = TREE_TYPE (lhs);
1181 if (base_cand)
1183 while (base_cand)
1185 /* Propagate all data from the base candidate except the type,
1186 which comes from the cast, and the base candidate's cast,
1187 which is no longer applicable. */
1188 if (has_single_use (rhs1))
1189 savings = (base_cand->dead_savings
1190 + stmt_cost (base_cand->cand_stmt, speed));
1192 c = alloc_cand_and_find_basis (base_cand->kind, gs,
1193 base_cand->base_expr,
1194 base_cand->index, base_cand->stride,
1195 ctype, savings);
1196 if (base_cand->next_interp)
1197 base_cand = lookup_cand (base_cand->next_interp);
1198 else
1199 base_cand = NULL;
1202 else
1204 /* If nothing is known about the RHS, create fresh CAND_ADD and
1205 CAND_MULT interpretations:
1207 X = Y + (0 * 1)
1208 X = (Y + 0) * 1
1210 The first of these is somewhat arbitrary, but the choice of
1211 1 for the stride simplifies the logic for propagating casts
1212 into their uses. */
1213 c = alloc_cand_and_find_basis (CAND_ADD, gs, rhs1, double_int_zero,
1214 integer_one_node, ctype, 0);
1215 c2 = alloc_cand_and_find_basis (CAND_MULT, gs, rhs1, double_int_zero,
1216 integer_one_node, ctype, 0);
1217 c->next_interp = c2->cand_num;
1220 /* Add the first (or only) interpretation to the statement-candidate
1221 mapping. */
1222 add_cand_for_stmt (gs, c);
1225 /* Given GS which is a copy of a scalar integer type, make at least one
1226 appropriate entry in the candidate table.
1228 This interface is included for completeness, but is unnecessary
1229 if this pass immediately follows a pass that performs copy
1230 propagation, such as DOM. */
1232 static void
1233 slsr_process_copy (gimple gs, tree rhs1, bool speed)
1235 slsr_cand_t base_cand, c, c2;
1236 unsigned savings = 0;
1238 base_cand = base_cand_from_table (rhs1);
1240 if (base_cand)
1242 while (base_cand)
1244 /* Propagate all data from the base candidate. */
1245 if (has_single_use (rhs1))
1246 savings = (base_cand->dead_savings
1247 + stmt_cost (base_cand->cand_stmt, speed));
1249 c = alloc_cand_and_find_basis (base_cand->kind, gs,
1250 base_cand->base_expr,
1251 base_cand->index, base_cand->stride,
1252 base_cand->cand_type, savings);
1253 if (base_cand->next_interp)
1254 base_cand = lookup_cand (base_cand->next_interp);
1255 else
1256 base_cand = NULL;
1259 else
1261 /* If nothing is known about the RHS, create fresh CAND_ADD and
1262 CAND_MULT interpretations:
1264 X = Y + (0 * 1)
1265 X = (Y + 0) * 1
1267 The first of these is somewhat arbitrary, but the choice of
1268 1 for the stride simplifies the logic for propagating casts
1269 into their uses. */
1270 c = alloc_cand_and_find_basis (CAND_ADD, gs, rhs1, double_int_zero,
1271 integer_one_node, TREE_TYPE (rhs1), 0);
1272 c2 = alloc_cand_and_find_basis (CAND_MULT, gs, rhs1, double_int_zero,
1273 integer_one_node, TREE_TYPE (rhs1), 0);
1274 c->next_interp = c2->cand_num;
1277 /* Add the first (or only) interpretation to the statement-candidate
1278 mapping. */
1279 add_cand_for_stmt (gs, c);
1282 /* Find strength-reduction candidates in block BB. */
1284 static void
1285 find_candidates_in_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1286 basic_block bb)
1288 bool speed = optimize_bb_for_speed_p (bb);
1289 gimple_stmt_iterator gsi;
1291 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1293 gimple gs = gsi_stmt (gsi);
1295 if (gimple_vuse (gs) && gimple_assign_single_p (gs))
1296 slsr_process_ref (gs);
1298 else if (is_gimple_assign (gs)
1299 && SCALAR_INT_MODE_P
1300 (TYPE_MODE (TREE_TYPE (gimple_assign_lhs (gs)))))
1302 tree rhs1 = NULL_TREE, rhs2 = NULL_TREE;
1304 switch (gimple_assign_rhs_code (gs))
1306 case MULT_EXPR:
1307 case PLUS_EXPR:
1308 rhs1 = gimple_assign_rhs1 (gs);
1309 rhs2 = gimple_assign_rhs2 (gs);
1310 /* Should never happen, but currently some buggy situations
1311 in earlier phases put constants in rhs1. */
1312 if (TREE_CODE (rhs1) != SSA_NAME)
1313 continue;
1314 break;
1316 /* Possible future opportunity: rhs1 of a ptr+ can be
1317 an ADDR_EXPR. */
1318 case POINTER_PLUS_EXPR:
1319 case MINUS_EXPR:
1320 rhs2 = gimple_assign_rhs2 (gs);
1321 /* Fall-through. */
1323 case NOP_EXPR:
1324 case MODIFY_EXPR:
1325 case NEGATE_EXPR:
1326 rhs1 = gimple_assign_rhs1 (gs);
1327 if (TREE_CODE (rhs1) != SSA_NAME)
1328 continue;
1329 break;
1331 default:
1335 switch (gimple_assign_rhs_code (gs))
1337 case MULT_EXPR:
1338 slsr_process_mul (gs, rhs1, rhs2, speed);
1339 break;
1341 case PLUS_EXPR:
1342 case POINTER_PLUS_EXPR:
1343 case MINUS_EXPR:
1344 slsr_process_add (gs, rhs1, rhs2, speed);
1345 break;
1347 case NEGATE_EXPR:
1348 slsr_process_neg (gs, rhs1, speed);
1349 break;
1351 case NOP_EXPR:
1352 slsr_process_cast (gs, rhs1, speed);
1353 break;
1355 case MODIFY_EXPR:
1356 slsr_process_copy (gs, rhs1, speed);
1357 break;
1359 default:
1366 /* Dump a candidate for debug. */
1368 static void
1369 dump_candidate (slsr_cand_t c)
1371 fprintf (dump_file, "%3d [%d] ", c->cand_num,
1372 gimple_bb (c->cand_stmt)->index);
1373 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
1374 switch (c->kind)
1376 case CAND_MULT:
1377 fputs (" MULT : (", dump_file);
1378 print_generic_expr (dump_file, c->base_expr, 0);
1379 fputs (" + ", dump_file);
1380 dump_double_int (dump_file, c->index, false);
1381 fputs (") * ", dump_file);
1382 print_generic_expr (dump_file, c->stride, 0);
1383 fputs (" : ", dump_file);
1384 break;
1385 case CAND_ADD:
1386 fputs (" ADD : ", dump_file);
1387 print_generic_expr (dump_file, c->base_expr, 0);
1388 fputs (" + (", dump_file);
1389 dump_double_int (dump_file, c->index, false);
1390 fputs (" * ", dump_file);
1391 print_generic_expr (dump_file, c->stride, 0);
1392 fputs (") : ", dump_file);
1393 break;
1394 case CAND_REF:
1395 fputs (" REF : ", dump_file);
1396 print_generic_expr (dump_file, c->base_expr, 0);
1397 fputs (" + (", dump_file);
1398 print_generic_expr (dump_file, c->stride, 0);
1399 fputs (") + ", dump_file);
1400 dump_double_int (dump_file, c->index, false);
1401 fputs (" : ", dump_file);
1402 break;
1403 default:
1404 gcc_unreachable ();
1406 print_generic_expr (dump_file, c->cand_type, 0);
1407 fprintf (dump_file, "\n basis: %d dependent: %d sibling: %d\n",
1408 c->basis, c->dependent, c->sibling);
1409 fprintf (dump_file, " next-interp: %d dead-savings: %d\n",
1410 c->next_interp, c->dead_savings);
1411 if (c->def_phi)
1413 fputs (" phi: ", dump_file);
1414 print_gimple_stmt (dump_file, c->def_phi, 0, 0);
1416 fputs ("\n", dump_file);
1419 /* Dump the candidate vector for debug. */
1421 static void
1422 dump_cand_vec (void)
1424 unsigned i;
1425 slsr_cand_t c;
1427 fprintf (dump_file, "\nStrength reduction candidate vector:\n\n");
1429 FOR_EACH_VEC_ELT (cand_vec, i, c)
1430 dump_candidate (c);
1433 /* Callback used to dump the candidate chains hash table. */
1436 ssa_base_cand_dump_callback (cand_chain **slot, void *ignored ATTRIBUTE_UNUSED)
1438 const_cand_chain_t chain = *slot;
1439 cand_chain_t p;
1441 print_generic_expr (dump_file, chain->base_expr, 0);
1442 fprintf (dump_file, " -> %d", chain->cand->cand_num);
1444 for (p = chain->next; p; p = p->next)
1445 fprintf (dump_file, " -> %d", p->cand->cand_num);
1447 fputs ("\n", dump_file);
1448 return 1;
1451 /* Dump the candidate chains. */
1453 static void
1454 dump_cand_chains (void)
1456 fprintf (dump_file, "\nStrength reduction candidate chains:\n\n");
1457 base_cand_map.traverse_noresize <void *, ssa_base_cand_dump_callback> (NULL);
1458 fputs ("\n", dump_file);
1461 /* Dump the increment vector for debug. */
1463 static void
1464 dump_incr_vec (void)
1466 if (dump_file && (dump_flags & TDF_DETAILS))
1468 unsigned i;
1470 fprintf (dump_file, "\nIncrement vector:\n\n");
1472 for (i = 0; i < incr_vec_len; i++)
1474 fprintf (dump_file, "%3d increment: ", i);
1475 dump_double_int (dump_file, incr_vec[i].incr, false);
1476 fprintf (dump_file, "\n count: %d", incr_vec[i].count);
1477 fprintf (dump_file, "\n cost: %d", incr_vec[i].cost);
1478 fputs ("\n initializer: ", dump_file);
1479 print_generic_expr (dump_file, incr_vec[i].initializer, 0);
1480 fputs ("\n\n", dump_file);
1485 /* Recursive helper for unconditional_cands_with_known_stride_p.
1486 Returns TRUE iff C, its siblings, and its dependents are all
1487 unconditional candidates. */
1489 static bool
1490 unconditional_cands (slsr_cand_t c)
1492 if (c->def_phi)
1493 return false;
1495 if (c->sibling && !unconditional_cands (lookup_cand (c->sibling)))
1496 return false;
1498 if (c->dependent && !unconditional_cands (lookup_cand (c->dependent)))
1499 return false;
1501 return true;
1504 /* Determine whether or not the tree of candidates rooted at
1505 ROOT consists entirely of unconditional increments with
1506 an INTEGER_CST stride. */
1508 static bool
1509 unconditional_cands_with_known_stride_p (slsr_cand_t root)
1511 /* The stride is identical for all related candidates, so
1512 check it once. */
1513 if (TREE_CODE (root->stride) != INTEGER_CST)
1514 return false;
1516 return unconditional_cands (lookup_cand (root->dependent));
1519 /* Replace *EXPR in candidate C with an equivalent strength-reduced
1520 data reference. */
1522 static void
1523 replace_ref (tree *expr, slsr_cand_t c)
1525 tree add_expr = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (c->base_expr),
1526 c->base_expr, c->stride);
1527 tree mem_ref = fold_build2 (MEM_REF, TREE_TYPE (*expr), add_expr,
1528 double_int_to_tree (c->cand_type, c->index));
1530 /* Gimplify the base addressing expression for the new MEM_REF tree. */
1531 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
1532 TREE_OPERAND (mem_ref, 0)
1533 = force_gimple_operand_gsi (&gsi, TREE_OPERAND (mem_ref, 0),
1534 /*simple_p=*/true, NULL,
1535 /*before=*/true, GSI_SAME_STMT);
1536 copy_ref_info (mem_ref, *expr);
1537 *expr = mem_ref;
1538 update_stmt (c->cand_stmt);
1541 /* Replace CAND_REF candidate C, each sibling of candidate C, and each
1542 dependent of candidate C with an equivalent strength-reduced data
1543 reference. */
1545 static void
1546 replace_refs (slsr_cand_t c)
1548 if (gimple_vdef (c->cand_stmt))
1550 tree *lhs = gimple_assign_lhs_ptr (c->cand_stmt);
1551 replace_ref (lhs, c);
1553 else
1555 tree *rhs = gimple_assign_rhs1_ptr (c->cand_stmt);
1556 replace_ref (rhs, c);
1559 if (c->sibling)
1560 replace_refs (lookup_cand (c->sibling));
1562 if (c->dependent)
1563 replace_refs (lookup_cand (c->dependent));
1566 /* Calculate the increment required for candidate C relative to
1567 its basis. */
1569 static double_int
1570 cand_increment (slsr_cand_t c)
1572 slsr_cand_t basis;
1574 /* If the candidate doesn't have a basis, just return its own
1575 index. This is useful in record_increments to help us find
1576 an existing initializer. */
1577 if (!c->basis)
1578 return c->index;
1580 basis = lookup_cand (c->basis);
1581 gcc_assert (operand_equal_p (c->base_expr, basis->base_expr, 0));
1582 return c->index - basis->index;
1585 /* Calculate the increment required for candidate C relative to
1586 its basis. If we aren't going to generate pointer arithmetic
1587 for this candidate, return the absolute value of that increment
1588 instead. */
1590 static inline double_int
1591 cand_abs_increment (slsr_cand_t c)
1593 double_int increment = cand_increment (c);
1595 if (!address_arithmetic_p && increment.is_negative ())
1596 increment = -increment;
1598 return increment;
1601 /* If *VAR is NULL or is not of a compatible type with TYPE, create a
1602 new temporary reg of type TYPE and store it in *VAR. */
1604 static inline void
1605 lazy_create_slsr_reg (tree *var, tree type)
1607 if (!*var || !types_compatible_p (TREE_TYPE (*var), type))
1608 *var = create_tmp_reg (type, "slsr");
1611 /* Return TRUE iff candidate C has already been replaced under
1612 another interpretation. */
1614 static inline bool
1615 cand_already_replaced (slsr_cand_t c)
1617 return (gimple_bb (c->cand_stmt) == 0);
1620 /* Helper routine for replace_dependents, doing the work for a
1621 single candidate C. */
1623 static void
1624 replace_dependent (slsr_cand_t c, enum tree_code cand_code)
1626 double_int stride = tree_to_double_int (c->stride);
1627 double_int bump = cand_increment (c) * stride;
1628 gimple stmt_to_print = NULL;
1629 slsr_cand_t basis;
1630 tree basis_name, incr_type, bump_tree;
1631 enum tree_code code;
1633 /* It is highly unlikely, but possible, that the resulting
1634 bump doesn't fit in a HWI. Abandon the replacement
1635 in this case. Restriction to signed HWI is conservative
1636 for unsigned types but allows for safe negation without
1637 twisted logic. */
1638 if (!bump.fits_shwi ())
1639 return;
1641 basis = lookup_cand (c->basis);
1642 basis_name = gimple_assign_lhs (basis->cand_stmt);
1643 if (cand_code == POINTER_PLUS_EXPR)
1645 incr_type = sizetype;
1646 code = cand_code;
1648 else
1650 incr_type = TREE_TYPE (gimple_assign_rhs1 (c->cand_stmt));
1651 code = PLUS_EXPR;
1654 if (bump.is_negative ()
1655 && cand_code != POINTER_PLUS_EXPR)
1657 code = MINUS_EXPR;
1658 bump = -bump;
1661 bump_tree = double_int_to_tree (incr_type, bump);
1663 if (dump_file && (dump_flags & TDF_DETAILS))
1665 fputs ("Replacing: ", dump_file);
1666 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
1669 if (bump.is_zero ())
1671 tree lhs = gimple_assign_lhs (c->cand_stmt);
1672 gimple copy_stmt = gimple_build_assign (lhs, basis_name);
1673 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
1674 gimple_set_location (copy_stmt, gimple_location (c->cand_stmt));
1675 gsi_replace (&gsi, copy_stmt, false);
1676 if (dump_file && (dump_flags & TDF_DETAILS))
1677 stmt_to_print = copy_stmt;
1679 else
1681 tree rhs1 = gimple_assign_rhs1 (c->cand_stmt);
1682 tree rhs2 = gimple_assign_rhs2 (c->cand_stmt);
1683 if (cand_code != NEGATE_EXPR
1684 && ((operand_equal_p (rhs1, basis_name, 0)
1685 && operand_equal_p (rhs2, bump_tree, 0))
1686 || (operand_equal_p (rhs1, bump_tree, 0)
1687 && operand_equal_p (rhs2, basis_name, 0))))
1689 if (dump_file && (dump_flags & TDF_DETAILS))
1691 fputs ("(duplicate, not actually replacing)", dump_file);
1692 stmt_to_print = c->cand_stmt;
1695 else
1697 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
1698 gimple_assign_set_rhs_with_ops (&gsi, code, basis_name, bump_tree);
1699 update_stmt (gsi_stmt (gsi));
1700 if (dump_file && (dump_flags & TDF_DETAILS))
1701 stmt_to_print = gsi_stmt (gsi);
1705 if (dump_file && (dump_flags & TDF_DETAILS))
1707 fputs ("With: ", dump_file);
1708 print_gimple_stmt (dump_file, stmt_to_print, 0, 0);
1709 fputs ("\n", dump_file);
1713 /* Replace candidate C, each sibling of candidate C, and each
1714 dependent of candidate C with an add or subtract. Note that we
1715 only operate on CAND_MULTs with known strides, so we will never
1716 generate a POINTER_PLUS_EXPR. Each candidate X = (B + i) * S is
1717 replaced by X = Y + ((i - i') * S), as described in the module
1718 commentary. The folded value ((i - i') * S) is referred to here
1719 as the "bump." */
1721 static void
1722 replace_dependents (slsr_cand_t c)
1724 enum tree_code cand_code = gimple_assign_rhs_code (c->cand_stmt);
1726 /* It is not useful to replace casts, copies, or adds of an SSA name
1727 and a constant. Also skip candidates that have already been
1728 replaced under another interpretation. */
1729 if (cand_code != MODIFY_EXPR
1730 && cand_code != NOP_EXPR
1731 && c->kind == CAND_MULT
1732 && !cand_already_replaced (c))
1733 replace_dependent (c, cand_code);
1735 if (c->sibling)
1736 replace_dependents (lookup_cand (c->sibling));
1738 if (c->dependent)
1739 replace_dependents (lookup_cand (c->dependent));
1742 /* Return the index in the increment vector of the given INCREMENT. */
1744 static inline unsigned
1745 incr_vec_index (double_int increment)
1747 unsigned i;
1749 for (i = 0; i < incr_vec_len && increment != incr_vec[i].incr; i++)
1752 gcc_assert (i < incr_vec_len);
1753 return i;
1756 /* Count the number of candidates in the tree rooted at C that have
1757 not already been replaced under other interpretations. */
1759 static unsigned
1760 count_candidates (slsr_cand_t c)
1762 unsigned count = cand_already_replaced (c) ? 0 : 1;
1764 if (c->sibling)
1765 count += count_candidates (lookup_cand (c->sibling));
1767 if (c->dependent)
1768 count += count_candidates (lookup_cand (c->dependent));
1770 return count;
1773 /* Increase the count of INCREMENT by one in the increment vector.
1774 INCREMENT is associated with candidate C. If an initializer
1775 T_0 = stride * I is provided by a candidate that dominates all
1776 candidates with the same increment, also record T_0 for subsequent use. */
1778 static void
1779 record_increment (slsr_cand_t c, double_int increment)
1781 bool found = false;
1782 unsigned i;
1784 /* Treat increments that differ only in sign as identical so as to
1785 share initializers, unless we are generating pointer arithmetic. */
1786 if (!address_arithmetic_p && increment.is_negative ())
1787 increment = -increment;
1789 for (i = 0; i < incr_vec_len; i++)
1791 if (incr_vec[i].incr == increment)
1793 incr_vec[i].count++;
1794 found = true;
1796 /* If we previously recorded an initializer that doesn't
1797 dominate this candidate, it's not going to be useful to
1798 us after all. */
1799 if (incr_vec[i].initializer
1800 && !dominated_by_p (CDI_DOMINATORS,
1801 gimple_bb (c->cand_stmt),
1802 incr_vec[i].init_bb))
1804 incr_vec[i].initializer = NULL_TREE;
1805 incr_vec[i].init_bb = NULL;
1808 break;
1812 if (!found)
1814 /* The first time we see an increment, create the entry for it.
1815 If this is the root candidate which doesn't have a basis, set
1816 the count to zero. We're only processing it so it can possibly
1817 provide an initializer for other candidates. */
1818 incr_vec[incr_vec_len].incr = increment;
1819 incr_vec[incr_vec_len].count = c->basis ? 1 : 0;
1820 incr_vec[incr_vec_len].cost = COST_INFINITE;
1822 /* Optimistically record the first occurrence of this increment
1823 as providing an initializer (if it does); we will revise this
1824 opinion later if it doesn't dominate all other occurrences.
1825 Exception: increments of -1, 0, 1 never need initializers. */
1826 if (c->kind == CAND_ADD
1827 && c->index == increment
1828 && (increment.sgt (double_int_one)
1829 || increment.slt (double_int_minus_one))
1830 && (gimple_assign_rhs_code (c->cand_stmt) == PLUS_EXPR
1831 || gimple_assign_rhs_code (c->cand_stmt) == POINTER_PLUS_EXPR))
1833 tree t0 = NULL_TREE;
1834 tree rhs1 = gimple_assign_rhs1 (c->cand_stmt);
1835 tree rhs2 = gimple_assign_rhs2 (c->cand_stmt);
1836 if (operand_equal_p (rhs1, c->base_expr, 0))
1837 t0 = rhs2;
1838 else if (operand_equal_p (rhs2, c->base_expr, 0))
1839 t0 = rhs1;
1840 if (t0
1841 && SSA_NAME_DEF_STMT (t0)
1842 && gimple_bb (SSA_NAME_DEF_STMT (t0)))
1844 incr_vec[incr_vec_len].initializer = t0;
1845 incr_vec[incr_vec_len++].init_bb
1846 = gimple_bb (SSA_NAME_DEF_STMT (t0));
1848 else
1850 incr_vec[incr_vec_len].initializer = NULL_TREE;
1851 incr_vec[incr_vec_len++].init_bb = NULL;
1854 else
1856 incr_vec[incr_vec_len].initializer = NULL_TREE;
1857 incr_vec[incr_vec_len++].init_bb = NULL;
1862 /* Determine how many times each unique increment occurs in the set
1863 of candidates rooted at C's parent, recording the data in the
1864 increment vector. For each unique increment I, if an initializer
1865 T_0 = stride * I is provided by a candidate that dominates all
1866 candidates with the same increment, also record T_0 for subsequent
1867 use. */
1869 static void
1870 record_increments (slsr_cand_t c)
1872 if (!cand_already_replaced (c))
1873 record_increment (c, cand_increment (c));
1875 if (c->sibling)
1876 record_increments (lookup_cand (c->sibling));
1878 if (c->dependent)
1879 record_increments (lookup_cand (c->dependent));
1882 /* Return the first candidate in the tree rooted at C that has not
1883 already been replaced, favoring siblings over dependents. */
1885 static slsr_cand_t
1886 unreplaced_cand_in_tree (slsr_cand_t c)
1888 if (!cand_already_replaced (c))
1889 return c;
1891 if (c->sibling)
1893 slsr_cand_t sib = unreplaced_cand_in_tree (lookup_cand (c->sibling));
1894 if (sib)
1895 return sib;
1898 if (c->dependent)
1900 slsr_cand_t dep = unreplaced_cand_in_tree (lookup_cand (c->dependent));
1901 if (dep)
1902 return dep;
1905 return NULL;
1908 /* Return TRUE if the candidates in the tree rooted at C should be
1909 optimized for speed, else FALSE. We estimate this based on the block
1910 containing the most dominant candidate in the tree that has not yet
1911 been replaced. */
1913 static bool
1914 optimize_cands_for_speed_p (slsr_cand_t c)
1916 slsr_cand_t c2 = unreplaced_cand_in_tree (c);
1917 gcc_assert (c2);
1918 return optimize_bb_for_speed_p (gimple_bb (c2->cand_stmt));
1921 /* Add COST_IN to the lowest cost of any dependent path starting at
1922 candidate C or any of its siblings, counting only candidates along
1923 such paths with increment INCR. Assume that replacing a candidate
1924 reduces cost by REPL_SAVINGS. Also account for savings from any
1925 statements that would go dead. */
1927 static int
1928 lowest_cost_path (int cost_in, int repl_savings, slsr_cand_t c, double_int incr)
1930 int local_cost, sib_cost;
1931 double_int cand_incr = cand_abs_increment (c);
1933 if (cand_already_replaced (c))
1934 local_cost = cost_in;
1935 else if (incr == cand_incr)
1936 local_cost = cost_in - repl_savings - c->dead_savings;
1937 else
1938 local_cost = cost_in - c->dead_savings;
1940 if (c->dependent)
1941 local_cost = lowest_cost_path (local_cost, repl_savings,
1942 lookup_cand (c->dependent), incr);
1944 if (c->sibling)
1946 sib_cost = lowest_cost_path (cost_in, repl_savings,
1947 lookup_cand (c->sibling), incr);
1948 local_cost = MIN (local_cost, sib_cost);
1951 return local_cost;
1954 /* Compute the total savings that would accrue from all replacements
1955 in the candidate tree rooted at C, counting only candidates with
1956 increment INCR. Assume that replacing a candidate reduces cost
1957 by REPL_SAVINGS. Also account for savings from statements that
1958 would go dead. */
1960 static int
1961 total_savings (int repl_savings, slsr_cand_t c, double_int incr)
1963 int savings = 0;
1964 double_int cand_incr = cand_abs_increment (c);
1966 if (incr == cand_incr && !cand_already_replaced (c))
1967 savings += repl_savings + c->dead_savings;
1969 if (c->dependent)
1970 savings += total_savings (repl_savings, lookup_cand (c->dependent), incr);
1972 if (c->sibling)
1973 savings += total_savings (repl_savings, lookup_cand (c->sibling), incr);
1975 return savings;
1978 /* Use target-specific costs to determine and record which increments
1979 in the current candidate tree are profitable to replace, assuming
1980 MODE and SPEED. FIRST_DEP is the first dependent of the root of
1981 the candidate tree.
1983 One slight limitation here is that we don't account for the possible
1984 introduction of casts in some cases. See replace_one_candidate for
1985 the cases where these are introduced. This should probably be cleaned
1986 up sometime. */
1988 static void
1989 analyze_increments (slsr_cand_t first_dep, enum machine_mode mode, bool speed)
1991 unsigned i;
1993 for (i = 0; i < incr_vec_len; i++)
1995 HOST_WIDE_INT incr = incr_vec[i].incr.to_shwi ();
1997 /* If somehow this increment is bigger than a HWI, we won't
1998 be optimizing candidates that use it. And if the increment
1999 has a count of zero, nothing will be done with it. */
2000 if (!incr_vec[i].incr.fits_shwi () || !incr_vec[i].count)
2001 incr_vec[i].cost = COST_INFINITE;
2003 /* Increments of 0, 1, and -1 are always profitable to replace,
2004 because they always replace a multiply or add with an add or
2005 copy, and may cause one or more existing instructions to go
2006 dead. Exception: -1 can't be assumed to be profitable for
2007 pointer addition. */
2008 else if (incr == 0
2009 || incr == 1
2010 || (incr == -1
2011 && (gimple_assign_rhs_code (first_dep->cand_stmt)
2012 != POINTER_PLUS_EXPR)))
2013 incr_vec[i].cost = COST_NEUTRAL;
2015 /* FORNOW: If we need to add an initializer, give up if a cast from
2016 the candidate's type to its stride's type can lose precision.
2017 This could eventually be handled better by expressly retaining the
2018 result of a cast to a wider type in the stride. Example:
2020 short int _1;
2021 _2 = (int) _1;
2022 _3 = _2 * 10;
2023 _4 = x + _3; ADD: x + (10 * _1) : int
2024 _5 = _2 * 15;
2025 _6 = x + _3; ADD: x + (15 * _1) : int
2027 Right now replacing _6 would cause insertion of an initializer
2028 of the form "short int T = _1 * 5;" followed by a cast to
2029 int, which could overflow incorrectly. Had we recorded _2 or
2030 (int)_1 as the stride, this wouldn't happen. However, doing
2031 this breaks other opportunities, so this will require some
2032 care. */
2033 else if (!incr_vec[i].initializer
2034 && TREE_CODE (first_dep->stride) != INTEGER_CST
2035 && !legal_cast_p_1 (first_dep->stride,
2036 gimple_assign_lhs (first_dep->cand_stmt)))
2038 incr_vec[i].cost = COST_INFINITE;
2040 /* If we need to add an initializer, make sure we don't introduce
2041 a multiply by a pointer type, which can happen in certain cast
2042 scenarios. FIXME: When cleaning up these cast issues, we can
2043 afford to introduce the multiply provided we cast out to an
2044 unsigned int of appropriate size. */
2045 else if (!incr_vec[i].initializer
2046 && TREE_CODE (first_dep->stride) != INTEGER_CST
2047 && POINTER_TYPE_P (TREE_TYPE (first_dep->stride)))
2049 incr_vec[i].cost = COST_INFINITE;
2051 /* For any other increment, if this is a multiply candidate, we
2052 must introduce a temporary T and initialize it with
2053 T_0 = stride * increment. When optimizing for speed, walk the
2054 candidate tree to calculate the best cost reduction along any
2055 path; if it offsets the fixed cost of inserting the initializer,
2056 replacing the increment is profitable. When optimizing for
2057 size, instead calculate the total cost reduction from replacing
2058 all candidates with this increment. */
2059 else if (first_dep->kind == CAND_MULT)
2061 int cost = mult_by_coeff_cost (incr, mode, speed);
2062 int repl_savings = mul_cost (speed, mode) - add_cost (speed, mode);
2063 if (speed)
2064 cost = lowest_cost_path (cost, repl_savings, first_dep,
2065 incr_vec[i].incr);
2066 else
2067 cost -= total_savings (repl_savings, first_dep, incr_vec[i].incr);
2069 incr_vec[i].cost = cost;
2072 /* If this is an add candidate, the initializer may already
2073 exist, so only calculate the cost of the initializer if it
2074 doesn't. We are replacing one add with another here, so the
2075 known replacement savings is zero. We will account for removal
2076 of dead instructions in lowest_cost_path or total_savings. */
2077 else
2079 int cost = 0;
2080 if (!incr_vec[i].initializer)
2081 cost = mult_by_coeff_cost (incr, mode, speed);
2083 if (speed)
2084 cost = lowest_cost_path (cost, 0, first_dep, incr_vec[i].incr);
2085 else
2086 cost -= total_savings (0, first_dep, incr_vec[i].incr);
2088 incr_vec[i].cost = cost;
2093 /* Return the nearest common dominator of BB1 and BB2. If the blocks
2094 are identical, return the earlier of C1 and C2 in *WHERE. Otherwise,
2095 if the NCD matches BB1, return C1 in *WHERE; if the NCD matches BB2,
2096 return C2 in *WHERE; and if the NCD matches neither, return NULL in
2097 *WHERE. Note: It is possible for one of C1 and C2 to be NULL. */
2099 static basic_block
2100 ncd_for_two_cands (basic_block bb1, basic_block bb2,
2101 slsr_cand_t c1, slsr_cand_t c2, slsr_cand_t *where)
2103 basic_block ncd;
2105 if (!bb1)
2107 *where = c2;
2108 return bb2;
2111 if (!bb2)
2113 *where = c1;
2114 return bb1;
2117 ncd = nearest_common_dominator (CDI_DOMINATORS, bb1, bb2);
2119 /* If both candidates are in the same block, the earlier
2120 candidate wins. */
2121 if (bb1 == ncd && bb2 == ncd)
2123 if (!c1 || (c2 && c2->cand_num < c1->cand_num))
2124 *where = c2;
2125 else
2126 *where = c1;
2129 /* Otherwise, if one of them produced a candidate in the
2130 dominator, that one wins. */
2131 else if (bb1 == ncd)
2132 *where = c1;
2134 else if (bb2 == ncd)
2135 *where = c2;
2137 /* If neither matches the dominator, neither wins. */
2138 else
2139 *where = NULL;
2141 return ncd;
2144 /* Consider all candidates in the tree rooted at C for which INCR
2145 represents the required increment of C relative to its basis.
2146 Find and return the basic block that most nearly dominates all
2147 such candidates. If the returned block contains one or more of
2148 the candidates, return the earliest candidate in the block in
2149 *WHERE. */
2151 static basic_block
2152 nearest_common_dominator_for_cands (slsr_cand_t c, double_int incr,
2153 slsr_cand_t *where)
2155 basic_block sib_ncd = NULL, dep_ncd = NULL, this_ncd = NULL, ncd;
2156 slsr_cand_t sib_where = NULL, dep_where = NULL, this_where = NULL, new_where;
2157 double_int cand_incr;
2159 /* First find the NCD of all siblings and dependents. */
2160 if (c->sibling)
2161 sib_ncd = nearest_common_dominator_for_cands (lookup_cand (c->sibling),
2162 incr, &sib_where);
2163 if (c->dependent)
2164 dep_ncd = nearest_common_dominator_for_cands (lookup_cand (c->dependent),
2165 incr, &dep_where);
2166 if (!sib_ncd && !dep_ncd)
2168 new_where = NULL;
2169 ncd = NULL;
2171 else if (sib_ncd && !dep_ncd)
2173 new_where = sib_where;
2174 ncd = sib_ncd;
2176 else if (dep_ncd && !sib_ncd)
2178 new_where = dep_where;
2179 ncd = dep_ncd;
2181 else
2182 ncd = ncd_for_two_cands (sib_ncd, dep_ncd, sib_where,
2183 dep_where, &new_where);
2185 /* If the candidate's increment doesn't match the one we're interested
2186 in, then the result depends only on siblings and dependents. */
2187 cand_incr = cand_abs_increment (c);
2189 if (cand_incr != incr || cand_already_replaced (c))
2191 *where = new_where;
2192 return ncd;
2195 /* Otherwise, compare this candidate with the result from all siblings
2196 and dependents. */
2197 this_where = c;
2198 this_ncd = gimple_bb (c->cand_stmt);
2199 ncd = ncd_for_two_cands (ncd, this_ncd, new_where, this_where, where);
2201 return ncd;
2204 /* Return TRUE if the increment indexed by INDEX is profitable to replace. */
2206 static inline bool
2207 profitable_increment_p (unsigned index)
2209 return (incr_vec[index].cost <= COST_NEUTRAL);
2212 /* For each profitable increment in the increment vector not equal to
2213 0 or 1 (or -1, for non-pointer arithmetic), find the nearest common
2214 dominator of all statements in the candidate chain rooted at C
2215 that require that increment, and insert an initializer
2216 T_0 = stride * increment at that location. Record T_0 with the
2217 increment record. */
2219 static void
2220 insert_initializers (slsr_cand_t c)
2222 unsigned i;
2223 tree new_var = NULL_TREE;
2225 for (i = 0; i < incr_vec_len; i++)
2227 basic_block bb;
2228 slsr_cand_t where = NULL;
2229 gimple init_stmt;
2230 tree stride_type, new_name, incr_tree;
2231 double_int incr = incr_vec[i].incr;
2233 if (!profitable_increment_p (i)
2234 || incr.is_one ()
2235 || (incr.is_minus_one ()
2236 && gimple_assign_rhs_code (c->cand_stmt) != POINTER_PLUS_EXPR)
2237 || incr.is_zero ())
2238 continue;
2240 /* We may have already identified an existing initializer that
2241 will suffice. */
2242 if (incr_vec[i].initializer)
2244 if (dump_file && (dump_flags & TDF_DETAILS))
2246 fputs ("Using existing initializer: ", dump_file);
2247 print_gimple_stmt (dump_file,
2248 SSA_NAME_DEF_STMT (incr_vec[i].initializer),
2249 0, 0);
2251 continue;
2254 /* Find the block that most closely dominates all candidates
2255 with this increment. If there is at least one candidate in
2256 that block, the earliest one will be returned in WHERE. */
2257 bb = nearest_common_dominator_for_cands (c, incr, &where);
2259 /* Create a new SSA name to hold the initializer's value. */
2260 stride_type = TREE_TYPE (c->stride);
2261 lazy_create_slsr_reg (&new_var, stride_type);
2262 new_name = make_ssa_name (new_var, NULL);
2263 incr_vec[i].initializer = new_name;
2265 /* Create the initializer and insert it in the latest possible
2266 dominating position. */
2267 incr_tree = double_int_to_tree (stride_type, incr);
2268 init_stmt = gimple_build_assign_with_ops (MULT_EXPR, new_name,
2269 c->stride, incr_tree);
2270 if (where)
2272 gimple_stmt_iterator gsi = gsi_for_stmt (where->cand_stmt);
2273 gsi_insert_before (&gsi, init_stmt, GSI_SAME_STMT);
2274 gimple_set_location (init_stmt, gimple_location (where->cand_stmt));
2276 else
2278 gimple_stmt_iterator gsi = gsi_last_bb (bb);
2279 gimple basis_stmt = lookup_cand (c->basis)->cand_stmt;
2281 if (!gsi_end_p (gsi) && is_ctrl_stmt (gsi_stmt (gsi)))
2282 gsi_insert_before (&gsi, init_stmt, GSI_SAME_STMT);
2283 else
2284 gsi_insert_after (&gsi, init_stmt, GSI_SAME_STMT);
2286 gimple_set_location (init_stmt, gimple_location (basis_stmt));
2289 if (dump_file && (dump_flags & TDF_DETAILS))
2291 fputs ("Inserting initializer: ", dump_file);
2292 print_gimple_stmt (dump_file, init_stmt, 0, 0);
2297 /* Create a NOP_EXPR that copies FROM_EXPR into a new SSA name of
2298 type TO_TYPE, and insert it in front of the statement represented
2299 by candidate C. Use *NEW_VAR to create the new SSA name. Return
2300 the new SSA name. */
2302 static tree
2303 introduce_cast_before_cand (slsr_cand_t c, tree to_type,
2304 tree from_expr, tree *new_var)
2306 tree cast_lhs;
2307 gimple cast_stmt;
2308 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
2310 lazy_create_slsr_reg (new_var, to_type);
2311 cast_lhs = make_ssa_name (*new_var, NULL);
2312 cast_stmt = gimple_build_assign_with_ops (NOP_EXPR, cast_lhs,
2313 from_expr, NULL_TREE);
2314 gimple_set_location (cast_stmt, gimple_location (c->cand_stmt));
2315 gsi_insert_before (&gsi, cast_stmt, GSI_SAME_STMT);
2317 if (dump_file && (dump_flags & TDF_DETAILS))
2319 fputs (" Inserting: ", dump_file);
2320 print_gimple_stmt (dump_file, cast_stmt, 0, 0);
2323 return cast_lhs;
2326 /* Replace the RHS of the statement represented by candidate C with
2327 NEW_CODE, NEW_RHS1, and NEW_RHS2, provided that to do so doesn't
2328 leave C unchanged or just interchange its operands. The original
2329 operation and operands are in OLD_CODE, OLD_RHS1, and OLD_RHS2.
2330 If the replacement was made and we are doing a details dump,
2331 return the revised statement, else NULL. */
2333 static gimple
2334 replace_rhs_if_not_dup (enum tree_code new_code, tree new_rhs1, tree new_rhs2,
2335 enum tree_code old_code, tree old_rhs1, tree old_rhs2,
2336 slsr_cand_t c)
2338 if (new_code != old_code
2339 || ((!operand_equal_p (new_rhs1, old_rhs1, 0)
2340 || !operand_equal_p (new_rhs2, old_rhs2, 0))
2341 && (!operand_equal_p (new_rhs1, old_rhs2, 0)
2342 || !operand_equal_p (new_rhs2, old_rhs1, 0))))
2344 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
2345 gimple_assign_set_rhs_with_ops (&gsi, new_code, new_rhs1, new_rhs2);
2346 update_stmt (gsi_stmt (gsi));
2348 if (dump_file && (dump_flags & TDF_DETAILS))
2349 return gsi_stmt (gsi);
2352 else if (dump_file && (dump_flags & TDF_DETAILS))
2353 fputs (" (duplicate, not actually replacing)\n", dump_file);
2355 return NULL;
2358 /* Strength-reduce the statement represented by candidate C by replacing
2359 it with an equivalent addition or subtraction. I is the index into
2360 the increment vector identifying C's increment. NEW_VAR is used to
2361 create a new SSA name if a cast needs to be introduced. BASIS_NAME
2362 is the rhs1 to use in creating the add/subtract. */
2364 static void
2365 replace_one_candidate (slsr_cand_t c, unsigned i, tree *new_var,
2366 tree basis_name)
2368 gimple stmt_to_print = NULL;
2369 tree orig_rhs1, orig_rhs2;
2370 tree rhs2;
2371 enum tree_code orig_code, repl_code;
2372 double_int cand_incr;
2374 orig_code = gimple_assign_rhs_code (c->cand_stmt);
2375 orig_rhs1 = gimple_assign_rhs1 (c->cand_stmt);
2376 orig_rhs2 = gimple_assign_rhs2 (c->cand_stmt);
2377 cand_incr = cand_increment (c);
2379 if (dump_file && (dump_flags & TDF_DETAILS))
2381 fputs ("Replacing: ", dump_file);
2382 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
2383 stmt_to_print = c->cand_stmt;
2386 if (address_arithmetic_p)
2387 repl_code = POINTER_PLUS_EXPR;
2388 else
2389 repl_code = PLUS_EXPR;
2391 /* If the increment has an initializer T_0, replace the candidate
2392 statement with an add of the basis name and the initializer. */
2393 if (incr_vec[i].initializer)
2395 tree init_type = TREE_TYPE (incr_vec[i].initializer);
2396 tree orig_type = TREE_TYPE (orig_rhs2);
2398 if (types_compatible_p (orig_type, init_type))
2399 rhs2 = incr_vec[i].initializer;
2400 else
2401 rhs2 = introduce_cast_before_cand (c, orig_type,
2402 incr_vec[i].initializer,
2403 new_var);
2405 if (incr_vec[i].incr != cand_incr)
2407 gcc_assert (repl_code == PLUS_EXPR);
2408 repl_code = MINUS_EXPR;
2411 stmt_to_print = replace_rhs_if_not_dup (repl_code, basis_name, rhs2,
2412 orig_code, orig_rhs1, orig_rhs2,
2416 /* Otherwise, the increment is one of -1, 0, and 1. Replace
2417 with a subtract of the stride from the basis name, a copy
2418 from the basis name, or an add of the stride to the basis
2419 name, respectively. It may be necessary to introduce a
2420 cast (or reuse an existing cast). */
2421 else if (cand_incr.is_one ())
2423 tree stride_type = TREE_TYPE (c->stride);
2424 tree orig_type = TREE_TYPE (orig_rhs2);
2426 if (types_compatible_p (orig_type, stride_type))
2427 rhs2 = c->stride;
2428 else
2429 rhs2 = introduce_cast_before_cand (c, orig_type, c->stride, new_var);
2431 stmt_to_print = replace_rhs_if_not_dup (repl_code, basis_name, rhs2,
2432 orig_code, orig_rhs1, orig_rhs2,
2436 else if (cand_incr.is_minus_one ())
2438 tree stride_type = TREE_TYPE (c->stride);
2439 tree orig_type = TREE_TYPE (orig_rhs2);
2440 gcc_assert (repl_code != POINTER_PLUS_EXPR);
2442 if (types_compatible_p (orig_type, stride_type))
2443 rhs2 = c->stride;
2444 else
2445 rhs2 = introduce_cast_before_cand (c, orig_type, c->stride, new_var);
2447 if (orig_code != MINUS_EXPR
2448 || !operand_equal_p (basis_name, orig_rhs1, 0)
2449 || !operand_equal_p (rhs2, orig_rhs2, 0))
2451 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
2452 gimple_assign_set_rhs_with_ops (&gsi, MINUS_EXPR, basis_name, rhs2);
2453 update_stmt (gsi_stmt (gsi));
2455 if (dump_file && (dump_flags & TDF_DETAILS))
2456 stmt_to_print = gsi_stmt (gsi);
2458 else if (dump_file && (dump_flags & TDF_DETAILS))
2459 fputs (" (duplicate, not actually replacing)\n", dump_file);
2462 else if (cand_incr.is_zero ())
2464 tree lhs = gimple_assign_lhs (c->cand_stmt);
2465 tree lhs_type = TREE_TYPE (lhs);
2466 tree basis_type = TREE_TYPE (basis_name);
2468 if (types_compatible_p (lhs_type, basis_type))
2470 gimple copy_stmt = gimple_build_assign (lhs, basis_name);
2471 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
2472 gimple_set_location (copy_stmt, gimple_location (c->cand_stmt));
2473 gsi_replace (&gsi, copy_stmt, false);
2475 if (dump_file && (dump_flags & TDF_DETAILS))
2476 stmt_to_print = copy_stmt;
2478 else
2480 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
2481 gimple cast_stmt = gimple_build_assign_with_ops (NOP_EXPR, lhs,
2482 basis_name,
2483 NULL_TREE);
2484 gimple_set_location (cast_stmt, gimple_location (c->cand_stmt));
2485 gsi_replace (&gsi, cast_stmt, false);
2487 if (dump_file && (dump_flags & TDF_DETAILS))
2488 stmt_to_print = cast_stmt;
2491 else
2492 gcc_unreachable ();
2494 if (dump_file && (dump_flags & TDF_DETAILS) && stmt_to_print)
2496 fputs ("With: ", dump_file);
2497 print_gimple_stmt (dump_file, stmt_to_print, 0, 0);
2498 fputs ("\n", dump_file);
2502 /* For each candidate in the tree rooted at C, replace it with
2503 an increment if such has been shown to be profitable. */
2505 static void
2506 replace_profitable_candidates (slsr_cand_t c)
2508 if (!cand_already_replaced (c))
2510 double_int increment = cand_abs_increment (c);
2511 tree new_var = NULL;
2512 enum tree_code orig_code = gimple_assign_rhs_code (c->cand_stmt);
2513 unsigned i;
2515 i = incr_vec_index (increment);
2517 /* Only process profitable increments. Nothing useful can be done
2518 to a cast or copy. */
2519 if (profitable_increment_p (i)
2520 && orig_code != MODIFY_EXPR
2521 && orig_code != NOP_EXPR)
2523 slsr_cand_t basis = lookup_cand (c->basis);
2524 tree basis_name = gimple_assign_lhs (basis->cand_stmt);
2525 replace_one_candidate (c, i, &new_var, basis_name);
2529 if (c->sibling)
2530 replace_profitable_candidates (lookup_cand (c->sibling));
2532 if (c->dependent)
2533 replace_profitable_candidates (lookup_cand (c->dependent));
2536 /* Analyze costs of related candidates in the candidate vector,
2537 and make beneficial replacements. */
2539 static void
2540 analyze_candidates_and_replace (void)
2542 unsigned i;
2543 slsr_cand_t c;
2545 /* Each candidate that has a null basis and a non-null
2546 dependent is the root of a tree of related statements.
2547 Analyze each tree to determine a subset of those
2548 statements that can be replaced with maximum benefit. */
2549 FOR_EACH_VEC_ELT (cand_vec, i, c)
2551 slsr_cand_t first_dep;
2553 if (c->basis != 0 || c->dependent == 0)
2554 continue;
2556 if (dump_file && (dump_flags & TDF_DETAILS))
2557 fprintf (dump_file, "\nProcessing dependency tree rooted at %d.\n",
2558 c->cand_num);
2560 first_dep = lookup_cand (c->dependent);
2562 /* If this is a chain of CAND_REFs, unconditionally replace
2563 each of them with a strength-reduced data reference. */
2564 if (c->kind == CAND_REF)
2565 replace_refs (c);
2567 /* If the common stride of all related candidates is a
2568 known constant, and none of these has a phi-dependence,
2569 then all replacements are considered profitable.
2570 Each replaces a multiply by a single add, with the
2571 possibility that a feeding add also goes dead as a
2572 result. */
2573 else if (unconditional_cands_with_known_stride_p (c))
2574 replace_dependents (first_dep);
2576 /* When the stride is an SSA name, it may still be profitable
2577 to replace some or all of the dependent candidates, depending
2578 on whether the introduced increments can be reused, or are
2579 less expensive to calculate than the replaced statements. */
2580 else
2582 unsigned length;
2583 enum machine_mode mode;
2584 bool speed;
2586 /* Determine whether we'll be generating pointer arithmetic
2587 when replacing candidates. */
2588 address_arithmetic_p = (c->kind == CAND_ADD
2589 && POINTER_TYPE_P (c->cand_type));
2591 /* If all candidates have already been replaced under other
2592 interpretations, nothing remains to be done. */
2593 length = count_candidates (c);
2594 if (!length)
2595 continue;
2597 /* Construct an array of increments for this candidate chain. */
2598 incr_vec = XNEWVEC (incr_info, length);
2599 incr_vec_len = 0;
2600 record_increments (c);
2602 /* Determine which increments are profitable to replace. */
2603 mode = TYPE_MODE (TREE_TYPE (gimple_assign_lhs (c->cand_stmt)));
2604 speed = optimize_cands_for_speed_p (c);
2605 analyze_increments (first_dep, mode, speed);
2607 /* Insert initializers of the form T_0 = stride * increment
2608 for use in profitable replacements. */
2609 insert_initializers (first_dep);
2610 dump_incr_vec ();
2612 /* Perform the replacements. */
2613 replace_profitable_candidates (first_dep);
2614 free (incr_vec);
2617 /* TODO: When conditional increments occur so that a
2618 candidate is dependent upon a phi-basis, the cost of
2619 introducing a temporary must be accounted for. */
2623 static unsigned
2624 execute_strength_reduction (void)
2626 struct dom_walk_data walk_data;
2628 /* Create the obstack where candidates will reside. */
2629 gcc_obstack_init (&cand_obstack);
2631 /* Allocate the candidate vector. */
2632 cand_vec.create (128);
2634 /* Allocate the mapping from statements to candidate indices. */
2635 stmt_cand_map = pointer_map_create ();
2637 /* Create the obstack where candidate chains will reside. */
2638 gcc_obstack_init (&chain_obstack);
2640 /* Allocate the mapping from base expressions to candidate chains. */
2641 base_cand_map.create (500);
2643 /* Initialize the loop optimizer. We need to detect flow across
2644 back edges, and this gives us dominator information as well. */
2645 loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
2647 /* Set up callbacks for the generic dominator tree walker. */
2648 walk_data.dom_direction = CDI_DOMINATORS;
2649 walk_data.initialize_block_local_data = NULL;
2650 walk_data.before_dom_children = find_candidates_in_block;
2651 walk_data.after_dom_children = NULL;
2652 walk_data.global_data = NULL;
2653 walk_data.block_local_data_size = 0;
2654 init_walk_dominator_tree (&walk_data);
2656 /* Walk the CFG in predominator order looking for strength reduction
2657 candidates. */
2658 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
2660 if (dump_file && (dump_flags & TDF_DETAILS))
2662 dump_cand_vec ();
2663 dump_cand_chains ();
2666 /* Analyze costs and make appropriate replacements. */
2667 analyze_candidates_and_replace ();
2669 /* Free resources. */
2670 fini_walk_dominator_tree (&walk_data);
2671 loop_optimizer_finalize ();
2672 base_cand_map.dispose ();
2673 obstack_free (&chain_obstack, NULL);
2674 pointer_map_destroy (stmt_cand_map);
2675 cand_vec.release ();
2676 obstack_free (&cand_obstack, NULL);
2678 return 0;
2681 static bool
2682 gate_strength_reduction (void)
2684 return flag_tree_slsr;
2687 struct gimple_opt_pass pass_strength_reduction =
2690 GIMPLE_PASS,
2691 "slsr", /* name */
2692 OPTGROUP_NONE, /* optinfo_flags */
2693 gate_strength_reduction, /* gate */
2694 execute_strength_reduction, /* execute */
2695 NULL, /* sub */
2696 NULL, /* next */
2697 0, /* static_pass_number */
2698 TV_GIMPLE_SLSR, /* tv_id */
2699 PROP_cfg | PROP_ssa, /* properties_required */
2700 0, /* properties_provided */
2701 0, /* properties_destroyed */
2702 0, /* todo_flags_start */
2703 TODO_verify_ssa /* todo_flags_finish */