2018-02-09 Vladimir Makarov <vmakarov@redhat.com>
[official-gcc.git] / gcc / tree-scalar-evolution.c
blob0ba1aa8359adccf0e451ab55244a6320962092d8
1 /* Scalar evolution detector.
2 Copyright (C) 2003-2018 Free Software Foundation, Inc.
3 Contributed by Sebastian Pop <s.pop@laposte.net>
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/>. */
22 Description:
24 This pass analyzes the evolution of scalar variables in loop
25 structures. The algorithm is based on the SSA representation,
26 and on the loop hierarchy tree. This algorithm is not based on
27 the notion of versions of a variable, as it was the case for the
28 previous implementations of the scalar evolution algorithm, but
29 it assumes that each defined name is unique.
31 The notation used in this file is called "chains of recurrences",
32 and has been proposed by Eugene Zima, Robert Van Engelen, and
33 others for describing induction variables in programs. For example
34 "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
35 when entering in the loop_1 and has a step 2 in this loop, in other
36 words "for (b = 0; b < N; b+=2);". Note that the coefficients of
37 this chain of recurrence (or chrec [shrek]) can contain the name of
38 other variables, in which case they are called parametric chrecs.
39 For example, "b -> {a, +, 2}_1" means that the initial value of "b"
40 is the value of "a". In most of the cases these parametric chrecs
41 are fully instantiated before their use because symbolic names can
42 hide some difficult cases such as self-references described later
43 (see the Fibonacci example).
45 A short sketch of the algorithm is:
47 Given a scalar variable to be analyzed, follow the SSA edge to
48 its definition:
50 - When the definition is a GIMPLE_ASSIGN: if the right hand side
51 (RHS) of the definition cannot be statically analyzed, the answer
52 of the analyzer is: "don't know".
53 Otherwise, for all the variables that are not yet analyzed in the
54 RHS, try to determine their evolution, and finally try to
55 evaluate the operation of the RHS that gives the evolution
56 function of the analyzed variable.
58 - When the definition is a condition-phi-node: determine the
59 evolution function for all the branches of the phi node, and
60 finally merge these evolutions (see chrec_merge).
62 - When the definition is a loop-phi-node: determine its initial
63 condition, that is the SSA edge defined in an outer loop, and
64 keep it symbolic. Then determine the SSA edges that are defined
65 in the body of the loop. Follow the inner edges until ending on
66 another loop-phi-node of the same analyzed loop. If the reached
67 loop-phi-node is not the starting loop-phi-node, then we keep
68 this definition under a symbolic form. If the reached
69 loop-phi-node is the same as the starting one, then we compute a
70 symbolic stride on the return path. The result is then the
71 symbolic chrec {initial_condition, +, symbolic_stride}_loop.
73 Examples:
75 Example 1: Illustration of the basic algorithm.
77 | a = 3
78 | loop_1
79 | b = phi (a, c)
80 | c = b + 1
81 | if (c > 10) exit_loop
82 | endloop
84 Suppose that we want to know the number of iterations of the
85 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
86 ask the scalar evolution analyzer two questions: what's the
87 scalar evolution (scev) of "c", and what's the scev of "10". For
88 "10" the answer is "10" since it is a scalar constant. For the
89 scalar variable "c", it follows the SSA edge to its definition,
90 "c = b + 1", and then asks again what's the scev of "b".
91 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
92 c)", where the initial condition is "a", and the inner loop edge
93 is "c". The initial condition is kept under a symbolic form (it
94 may be the case that the copy constant propagation has done its
95 work and we end with the constant "3" as one of the edges of the
96 loop-phi-node). The update edge is followed to the end of the
97 loop, and until reaching again the starting loop-phi-node: b -> c
98 -> b. At this point we have drawn a path from "b" to "b" from
99 which we compute the stride in the loop: in this example it is
100 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
101 that the scev for "b" is known, it is possible to compute the
102 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
103 determine the number of iterations in the loop_1, we have to
104 instantiate_parameters (loop_1, {a + 1, +, 1}_1), that gives after some
105 more analysis the scev {4, +, 1}_1, or in other words, this is
106 the function "f (x) = x + 4", where x is the iteration count of
107 the loop_1. Now we have to solve the inequality "x + 4 > 10",
108 and take the smallest iteration number for which the loop is
109 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
110 there are 8 iterations. In terms of loop normalization, we have
111 created a variable that is implicitly defined, "x" or just "_1",
112 and all the other analyzed scalars of the loop are defined in
113 function of this variable:
115 a -> 3
116 b -> {3, +, 1}_1
117 c -> {4, +, 1}_1
119 or in terms of a C program:
121 | a = 3
122 | for (x = 0; x <= 7; x++)
124 | b = x + 3
125 | c = x + 4
128 Example 2a: Illustration of the algorithm on nested loops.
130 | loop_1
131 | a = phi (1, b)
132 | c = a + 2
133 | loop_2 10 times
134 | b = phi (c, d)
135 | d = b + 3
136 | endloop
137 | endloop
139 For analyzing the scalar evolution of "a", the algorithm follows
140 the SSA edge into the loop's body: "a -> b". "b" is an inner
141 loop-phi-node, and its analysis as in Example 1, gives:
143 b -> {c, +, 3}_2
144 d -> {c + 3, +, 3}_2
146 Following the SSA edge for the initial condition, we end on "c = a
147 + 2", and then on the starting loop-phi-node "a". From this point,
148 the loop stride is computed: back on "c = a + 2" we get a "+2" in
149 the loop_1, then on the loop-phi-node "b" we compute the overall
150 effect of the inner loop that is "b = c + 30", and we get a "+30"
151 in the loop_1. That means that the overall stride in loop_1 is
152 equal to "+32", and the result is:
154 a -> {1, +, 32}_1
155 c -> {3, +, 32}_1
157 Example 2b: Multivariate chains of recurrences.
159 | loop_1
160 | k = phi (0, k + 1)
161 | loop_2 4 times
162 | j = phi (0, j + 1)
163 | loop_3 4 times
164 | i = phi (0, i + 1)
165 | A[j + k] = ...
166 | endloop
167 | endloop
168 | endloop
170 Analyzing the access function of array A with
171 instantiate_parameters (loop_1, "j + k"), we obtain the
172 instantiation and the analysis of the scalar variables "j" and "k"
173 in loop_1. This leads to the scalar evolution {4, +, 1}_1: the end
174 value of loop_2 for "j" is 4, and the evolution of "k" in loop_1 is
175 {0, +, 1}_1. To obtain the evolution function in loop_3 and
176 instantiate the scalar variables up to loop_1, one has to use:
177 instantiate_scev (block_before_loop (loop_1), loop_3, "j + k").
178 The result of this call is {{0, +, 1}_1, +, 1}_2.
180 Example 3: Higher degree polynomials.
182 | loop_1
183 | a = phi (2, b)
184 | c = phi (5, d)
185 | b = a + 1
186 | d = c + a
187 | endloop
189 a -> {2, +, 1}_1
190 b -> {3, +, 1}_1
191 c -> {5, +, a}_1
192 d -> {5 + a, +, a}_1
194 instantiate_parameters (loop_1, {5, +, a}_1) -> {5, +, 2, +, 1}_1
195 instantiate_parameters (loop_1, {5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
197 Example 4: Lucas, Fibonacci, or mixers in general.
199 | loop_1
200 | a = phi (1, b)
201 | c = phi (3, d)
202 | b = c
203 | d = c + a
204 | endloop
206 a -> (1, c)_1
207 c -> {3, +, a}_1
209 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
210 following semantics: during the first iteration of the loop_1, the
211 variable contains the value 1, and then it contains the value "c".
212 Note that this syntax is close to the syntax of the loop-phi-node:
213 "a -> (1, c)_1" vs. "a = phi (1, c)".
215 The symbolic chrec representation contains all the semantics of the
216 original code. What is more difficult is to use this information.
218 Example 5: Flip-flops, or exchangers.
220 | loop_1
221 | a = phi (1, b)
222 | c = phi (3, d)
223 | b = c
224 | d = a
225 | endloop
227 a -> (1, c)_1
228 c -> (3, a)_1
230 Based on these symbolic chrecs, it is possible to refine this
231 information into the more precise PERIODIC_CHRECs:
233 a -> |1, 3|_1
234 c -> |3, 1|_1
236 This transformation is not yet implemented.
238 Further readings:
240 You can find a more detailed description of the algorithm in:
241 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
242 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
243 this is a preliminary report and some of the details of the
244 algorithm have changed. I'm working on a research report that
245 updates the description of the algorithms to reflect the design
246 choices used in this implementation.
248 A set of slides show a high level overview of the algorithm and run
249 an example through the scalar evolution analyzer:
250 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
252 The slides that I have presented at the GCC Summit'04 are available
253 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
256 #include "config.h"
257 #include "system.h"
258 #include "coretypes.h"
259 #include "backend.h"
260 #include "rtl.h"
261 #include "tree.h"
262 #include "gimple.h"
263 #include "ssa.h"
264 #include "gimple-pretty-print.h"
265 #include "fold-const.h"
266 #include "gimplify.h"
267 #include "gimple-iterator.h"
268 #include "gimplify-me.h"
269 #include "tree-cfg.h"
270 #include "tree-ssa-loop-ivopts.h"
271 #include "tree-ssa-loop-manip.h"
272 #include "tree-ssa-loop-niter.h"
273 #include "tree-ssa-loop.h"
274 #include "tree-ssa.h"
275 #include "cfgloop.h"
276 #include "tree-chrec.h"
277 #include "tree-affine.h"
278 #include "tree-scalar-evolution.h"
279 #include "dumpfile.h"
280 #include "params.h"
281 #include "tree-ssa-propagate.h"
282 #include "gimple-fold.h"
284 static tree analyze_scalar_evolution_1 (struct loop *, tree);
285 static tree analyze_scalar_evolution_for_address_of (struct loop *loop,
286 tree var);
288 /* The cached information about an SSA name with version NAME_VERSION,
289 claiming that below basic block with index INSTANTIATED_BELOW, the
290 value of the SSA name can be expressed as CHREC. */
292 struct GTY((for_user)) scev_info_str {
293 unsigned int name_version;
294 int instantiated_below;
295 tree chrec;
298 /* Counters for the scev database. */
299 static unsigned nb_set_scev = 0;
300 static unsigned nb_get_scev = 0;
302 /* The following trees are unique elements. Thus the comparison of
303 another element to these elements should be done on the pointer to
304 these trees, and not on their value. */
306 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
307 tree chrec_not_analyzed_yet;
309 /* Reserved to the cases where the analyzer has detected an
310 undecidable property at compile time. */
311 tree chrec_dont_know;
313 /* When the analyzer has detected that a property will never
314 happen, then it qualifies it with chrec_known. */
315 tree chrec_known;
317 struct scev_info_hasher : ggc_ptr_hash<scev_info_str>
319 static hashval_t hash (scev_info_str *i);
320 static bool equal (const scev_info_str *a, const scev_info_str *b);
323 static GTY (()) hash_table<scev_info_hasher> *scalar_evolution_info;
326 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
328 static inline struct scev_info_str *
329 new_scev_info_str (basic_block instantiated_below, tree var)
331 struct scev_info_str *res;
333 res = ggc_alloc<scev_info_str> ();
334 res->name_version = SSA_NAME_VERSION (var);
335 res->chrec = chrec_not_analyzed_yet;
336 res->instantiated_below = instantiated_below->index;
338 return res;
341 /* Computes a hash function for database element ELT. */
343 hashval_t
344 scev_info_hasher::hash (scev_info_str *elt)
346 return elt->name_version ^ elt->instantiated_below;
349 /* Compares database elements E1 and E2. */
351 bool
352 scev_info_hasher::equal (const scev_info_str *elt1, const scev_info_str *elt2)
354 return (elt1->name_version == elt2->name_version
355 && elt1->instantiated_below == elt2->instantiated_below);
358 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
359 A first query on VAR returns chrec_not_analyzed_yet. */
361 static tree *
362 find_var_scev_info (basic_block instantiated_below, tree var)
364 struct scev_info_str *res;
365 struct scev_info_str tmp;
367 tmp.name_version = SSA_NAME_VERSION (var);
368 tmp.instantiated_below = instantiated_below->index;
369 scev_info_str **slot = scalar_evolution_info->find_slot (&tmp, INSERT);
371 if (!*slot)
372 *slot = new_scev_info_str (instantiated_below, var);
373 res = *slot;
375 return &res->chrec;
378 /* Return true when CHREC contains symbolic names defined in
379 LOOP_NB. */
381 bool
382 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
384 int i, n;
386 if (chrec == NULL_TREE)
387 return false;
389 if (is_gimple_min_invariant (chrec))
390 return false;
392 if (TREE_CODE (chrec) == SSA_NAME)
394 gimple *def;
395 loop_p def_loop, loop;
397 if (SSA_NAME_IS_DEFAULT_DEF (chrec))
398 return false;
400 def = SSA_NAME_DEF_STMT (chrec);
401 def_loop = loop_containing_stmt (def);
402 loop = get_loop (cfun, loop_nb);
404 if (def_loop == NULL)
405 return false;
407 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
408 return true;
410 return false;
413 n = TREE_OPERAND_LENGTH (chrec);
414 for (i = 0; i < n; i++)
415 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
416 loop_nb))
417 return true;
418 return false;
421 /* Return true when PHI is a loop-phi-node. */
423 static bool
424 loop_phi_node_p (gimple *phi)
426 /* The implementation of this function is based on the following
427 property: "all the loop-phi-nodes of a loop are contained in the
428 loop's header basic block". */
430 return loop_containing_stmt (phi)->header == gimple_bb (phi);
433 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
434 In general, in the case of multivariate evolutions we want to get
435 the evolution in different loops. LOOP specifies the level for
436 which to get the evolution.
438 Example:
440 | for (j = 0; j < 100; j++)
442 | for (k = 0; k < 100; k++)
444 | i = k + j; - Here the value of i is a function of j, k.
446 | ... = i - Here the value of i is a function of j.
448 | ... = i - Here the value of i is a scalar.
450 Example:
452 | i_0 = ...
453 | loop_1 10 times
454 | i_1 = phi (i_0, i_2)
455 | i_2 = i_1 + 2
456 | endloop
458 This loop has the same effect as:
459 LOOP_1 has the same effect as:
461 | i_1 = i_0 + 20
463 The overall effect of the loop, "i_0 + 20" in the previous example,
464 is obtained by passing in the parameters: LOOP = 1,
465 EVOLUTION_FN = {i_0, +, 2}_1.
468 tree
469 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
471 bool val = false;
473 if (evolution_fn == chrec_dont_know)
474 return chrec_dont_know;
476 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
478 struct loop *inner_loop = get_chrec_loop (evolution_fn);
480 if (inner_loop == loop
481 || flow_loop_nested_p (loop, inner_loop))
483 tree nb_iter = number_of_latch_executions (inner_loop);
485 if (nb_iter == chrec_dont_know)
486 return chrec_dont_know;
487 else
489 tree res;
491 /* evolution_fn is the evolution function in LOOP. Get
492 its value in the nb_iter-th iteration. */
493 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
495 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
496 res = instantiate_parameters (loop, res);
498 /* Continue the computation until ending on a parent of LOOP. */
499 return compute_overall_effect_of_inner_loop (loop, res);
502 else
503 return evolution_fn;
506 /* If the evolution function is an invariant, there is nothing to do. */
507 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
508 return evolution_fn;
510 else
511 return chrec_dont_know;
514 /* Associate CHREC to SCALAR. */
516 static void
517 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
519 tree *scalar_info;
521 if (TREE_CODE (scalar) != SSA_NAME)
522 return;
524 scalar_info = find_var_scev_info (instantiated_below, scalar);
526 if (dump_file)
528 if (dump_flags & TDF_SCEV)
530 fprintf (dump_file, "(set_scalar_evolution \n");
531 fprintf (dump_file, " instantiated_below = %d \n",
532 instantiated_below->index);
533 fprintf (dump_file, " (scalar = ");
534 print_generic_expr (dump_file, scalar);
535 fprintf (dump_file, ")\n (scalar_evolution = ");
536 print_generic_expr (dump_file, chrec);
537 fprintf (dump_file, "))\n");
539 if (dump_flags & TDF_STATS)
540 nb_set_scev++;
543 *scalar_info = chrec;
546 /* Retrieve the chrec associated to SCALAR instantiated below
547 INSTANTIATED_BELOW block. */
549 static tree
550 get_scalar_evolution (basic_block instantiated_below, tree scalar)
552 tree res;
554 if (dump_file)
556 if (dump_flags & TDF_SCEV)
558 fprintf (dump_file, "(get_scalar_evolution \n");
559 fprintf (dump_file, " (scalar = ");
560 print_generic_expr (dump_file, scalar);
561 fprintf (dump_file, ")\n");
563 if (dump_flags & TDF_STATS)
564 nb_get_scev++;
567 if (VECTOR_TYPE_P (TREE_TYPE (scalar))
568 || TREE_CODE (TREE_TYPE (scalar)) == COMPLEX_TYPE)
569 /* For chrec_dont_know we keep the symbolic form. */
570 res = scalar;
571 else
572 switch (TREE_CODE (scalar))
574 case SSA_NAME:
575 if (SSA_NAME_IS_DEFAULT_DEF (scalar))
576 res = scalar;
577 else
578 res = *find_var_scev_info (instantiated_below, scalar);
579 break;
581 case REAL_CST:
582 case FIXED_CST:
583 case INTEGER_CST:
584 res = scalar;
585 break;
587 default:
588 res = chrec_not_analyzed_yet;
589 break;
592 if (dump_file && (dump_flags & TDF_SCEV))
594 fprintf (dump_file, " (scalar_evolution = ");
595 print_generic_expr (dump_file, res);
596 fprintf (dump_file, "))\n");
599 return res;
602 /* Helper function for add_to_evolution. Returns the evolution
603 function for an assignment of the form "a = b + c", where "a" and
604 "b" are on the strongly connected component. CHREC_BEFORE is the
605 information that we already have collected up to this point.
606 TO_ADD is the evolution of "c".
608 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
609 evolution the expression TO_ADD, otherwise construct an evolution
610 part for this loop. */
612 static tree
613 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
614 gimple *at_stmt)
616 tree type, left, right;
617 struct loop *loop = get_loop (cfun, loop_nb), *chloop;
619 switch (TREE_CODE (chrec_before))
621 case POLYNOMIAL_CHREC:
622 chloop = get_chrec_loop (chrec_before);
623 if (chloop == loop
624 || flow_loop_nested_p (chloop, loop))
626 unsigned var;
628 type = chrec_type (chrec_before);
630 /* When there is no evolution part in this loop, build it. */
631 if (chloop != loop)
633 var = loop_nb;
634 left = chrec_before;
635 right = SCALAR_FLOAT_TYPE_P (type)
636 ? build_real (type, dconst0)
637 : build_int_cst (type, 0);
639 else
641 var = CHREC_VARIABLE (chrec_before);
642 left = CHREC_LEFT (chrec_before);
643 right = CHREC_RIGHT (chrec_before);
646 to_add = chrec_convert (type, to_add, at_stmt);
647 right = chrec_convert_rhs (type, right, at_stmt);
648 right = chrec_fold_plus (chrec_type (right), right, to_add);
649 return build_polynomial_chrec (var, left, right);
651 else
653 gcc_assert (flow_loop_nested_p (loop, chloop));
655 /* Search the evolution in LOOP_NB. */
656 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
657 to_add, at_stmt);
658 right = CHREC_RIGHT (chrec_before);
659 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
660 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
661 left, right);
664 default:
665 /* These nodes do not depend on a loop. */
666 if (chrec_before == chrec_dont_know)
667 return chrec_dont_know;
669 left = chrec_before;
670 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
671 return build_polynomial_chrec (loop_nb, left, right);
675 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
676 of LOOP_NB.
678 Description (provided for completeness, for those who read code in
679 a plane, and for my poor 62 bytes brain that would have forgotten
680 all this in the next two or three months):
682 The algorithm of translation of programs from the SSA representation
683 into the chrecs syntax is based on a pattern matching. After having
684 reconstructed the overall tree expression for a loop, there are only
685 two cases that can arise:
687 1. a = loop-phi (init, a + expr)
688 2. a = loop-phi (init, expr)
690 where EXPR is either a scalar constant with respect to the analyzed
691 loop (this is a degree 0 polynomial), or an expression containing
692 other loop-phi definitions (these are higher degree polynomials).
694 Examples:
697 | init = ...
698 | loop_1
699 | a = phi (init, a + 5)
700 | endloop
703 | inita = ...
704 | initb = ...
705 | loop_1
706 | a = phi (inita, 2 * b + 3)
707 | b = phi (initb, b + 1)
708 | endloop
710 For the first case, the semantics of the SSA representation is:
712 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
714 that is, there is a loop index "x" that determines the scalar value
715 of the variable during the loop execution. During the first
716 iteration, the value is that of the initial condition INIT, while
717 during the subsequent iterations, it is the sum of the initial
718 condition with the sum of all the values of EXPR from the initial
719 iteration to the before last considered iteration.
721 For the second case, the semantics of the SSA program is:
723 | a (x) = init, if x = 0;
724 | expr (x - 1), otherwise.
726 The second case corresponds to the PEELED_CHREC, whose syntax is
727 close to the syntax of a loop-phi-node:
729 | phi (init, expr) vs. (init, expr)_x
731 The proof of the translation algorithm for the first case is a
732 proof by structural induction based on the degree of EXPR.
734 Degree 0:
735 When EXPR is a constant with respect to the analyzed loop, or in
736 other words when EXPR is a polynomial of degree 0, the evolution of
737 the variable A in the loop is an affine function with an initial
738 condition INIT, and a step EXPR. In order to show this, we start
739 from the semantics of the SSA representation:
741 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
743 and since "expr (j)" is a constant with respect to "j",
745 f (x) = init + x * expr
747 Finally, based on the semantics of the pure sum chrecs, by
748 identification we get the corresponding chrecs syntax:
750 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
751 f (x) -> {init, +, expr}_x
753 Higher degree:
754 Suppose that EXPR is a polynomial of degree N with respect to the
755 analyzed loop_x for which we have already determined that it is
756 written under the chrecs syntax:
758 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
760 We start from the semantics of the SSA program:
762 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
764 | f (x) = init + \sum_{j = 0}^{x - 1}
765 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
767 | f (x) = init + \sum_{j = 0}^{x - 1}
768 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
770 | f (x) = init + \sum_{k = 0}^{n - 1}
771 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
773 | f (x) = init + \sum_{k = 0}^{n - 1}
774 | (b_k * \binom{x}{k + 1})
776 | f (x) = init + b_0 * \binom{x}{1} + ...
777 | + b_{n-1} * \binom{x}{n}
779 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
780 | + b_{n-1} * \binom{x}{n}
783 And finally from the definition of the chrecs syntax, we identify:
784 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
786 This shows the mechanism that stands behind the add_to_evolution
787 function. An important point is that the use of symbolic
788 parameters avoids the need of an analysis schedule.
790 Example:
792 | inita = ...
793 | initb = ...
794 | loop_1
795 | a = phi (inita, a + 2 + b)
796 | b = phi (initb, b + 1)
797 | endloop
799 When analyzing "a", the algorithm keeps "b" symbolically:
801 | a -> {inita, +, 2 + b}_1
803 Then, after instantiation, the analyzer ends on the evolution:
805 | a -> {inita, +, 2 + initb, +, 1}_1
809 static tree
810 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
811 tree to_add, gimple *at_stmt)
813 tree type = chrec_type (to_add);
814 tree res = NULL_TREE;
816 if (to_add == NULL_TREE)
817 return chrec_before;
819 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
820 instantiated at this point. */
821 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
822 /* This should not happen. */
823 return chrec_dont_know;
825 if (dump_file && (dump_flags & TDF_SCEV))
827 fprintf (dump_file, "(add_to_evolution \n");
828 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
829 fprintf (dump_file, " (chrec_before = ");
830 print_generic_expr (dump_file, chrec_before);
831 fprintf (dump_file, ")\n (to_add = ");
832 print_generic_expr (dump_file, to_add);
833 fprintf (dump_file, ")\n");
836 if (code == MINUS_EXPR)
837 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
838 ? build_real (type, dconstm1)
839 : build_int_cst_type (type, -1));
841 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
843 if (dump_file && (dump_flags & TDF_SCEV))
845 fprintf (dump_file, " (res = ");
846 print_generic_expr (dump_file, res);
847 fprintf (dump_file, "))\n");
850 return res;
855 /* This section selects the loops that will be good candidates for the
856 scalar evolution analysis. For the moment, greedily select all the
857 loop nests we could analyze. */
859 /* For a loop with a single exit edge, return the COND_EXPR that
860 guards the exit edge. If the expression is too difficult to
861 analyze, then give up. */
863 gcond *
864 get_loop_exit_condition (const struct loop *loop)
866 gcond *res = NULL;
867 edge exit_edge = single_exit (loop);
869 if (dump_file && (dump_flags & TDF_SCEV))
870 fprintf (dump_file, "(get_loop_exit_condition \n ");
872 if (exit_edge)
874 gimple *stmt;
876 stmt = last_stmt (exit_edge->src);
877 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
878 res = cond_stmt;
881 if (dump_file && (dump_flags & TDF_SCEV))
883 print_gimple_stmt (dump_file, res, 0);
884 fprintf (dump_file, ")\n");
887 return res;
891 /* Depth first search algorithm. */
893 enum t_bool {
894 t_false,
895 t_true,
896 t_dont_know
900 static t_bool follow_ssa_edge (struct loop *loop, gimple *, gphi *,
901 tree *, int);
903 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
904 Return true if the strongly connected component has been found. */
906 static t_bool
907 follow_ssa_edge_binary (struct loop *loop, gimple *at_stmt,
908 tree type, tree rhs0, enum tree_code code, tree rhs1,
909 gphi *halting_phi, tree *evolution_of_loop,
910 int limit)
912 t_bool res = t_false;
913 tree evol;
915 switch (code)
917 case POINTER_PLUS_EXPR:
918 case PLUS_EXPR:
919 if (TREE_CODE (rhs0) == SSA_NAME)
921 if (TREE_CODE (rhs1) == SSA_NAME)
923 /* Match an assignment under the form:
924 "a = b + c". */
926 /* We want only assignments of form "name + name" contribute to
927 LIMIT, as the other cases do not necessarily contribute to
928 the complexity of the expression. */
929 limit++;
931 evol = *evolution_of_loop;
932 evol = add_to_evolution
933 (loop->num,
934 chrec_convert (type, evol, at_stmt),
935 code, rhs1, at_stmt);
936 res = follow_ssa_edge
937 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
938 if (res == t_true)
939 *evolution_of_loop = evol;
940 else if (res == t_false)
942 *evolution_of_loop = add_to_evolution
943 (loop->num,
944 chrec_convert (type, *evolution_of_loop, at_stmt),
945 code, rhs0, at_stmt);
946 res = follow_ssa_edge
947 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
948 evolution_of_loop, limit);
949 if (res == t_true)
951 else if (res == t_dont_know)
952 *evolution_of_loop = chrec_dont_know;
955 else if (res == t_dont_know)
956 *evolution_of_loop = chrec_dont_know;
959 else
961 /* Match an assignment under the form:
962 "a = b + ...". */
963 *evolution_of_loop = add_to_evolution
964 (loop->num, chrec_convert (type, *evolution_of_loop,
965 at_stmt),
966 code, rhs1, at_stmt);
967 res = follow_ssa_edge
968 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
969 evolution_of_loop, limit);
970 if (res == t_true)
972 else if (res == t_dont_know)
973 *evolution_of_loop = chrec_dont_know;
977 else if (TREE_CODE (rhs1) == SSA_NAME)
979 /* Match an assignment under the form:
980 "a = ... + c". */
981 *evolution_of_loop = add_to_evolution
982 (loop->num, chrec_convert (type, *evolution_of_loop,
983 at_stmt),
984 code, rhs0, at_stmt);
985 res = follow_ssa_edge
986 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
987 evolution_of_loop, limit);
988 if (res == t_true)
990 else if (res == t_dont_know)
991 *evolution_of_loop = chrec_dont_know;
994 else
995 /* Otherwise, match an assignment under the form:
996 "a = ... + ...". */
997 /* And there is nothing to do. */
998 res = t_false;
999 break;
1001 case MINUS_EXPR:
1002 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1003 if (TREE_CODE (rhs0) == SSA_NAME)
1005 /* Match an assignment under the form:
1006 "a = b - ...". */
1008 /* We want only assignments of form "name - name" contribute to
1009 LIMIT, as the other cases do not necessarily contribute to
1010 the complexity of the expression. */
1011 if (TREE_CODE (rhs1) == SSA_NAME)
1012 limit++;
1014 *evolution_of_loop = add_to_evolution
1015 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1016 MINUS_EXPR, rhs1, at_stmt);
1017 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1018 evolution_of_loop, limit);
1019 if (res == t_true)
1021 else if (res == t_dont_know)
1022 *evolution_of_loop = chrec_dont_know;
1024 else
1025 /* Otherwise, match an assignment under the form:
1026 "a = ... - ...". */
1027 /* And there is nothing to do. */
1028 res = t_false;
1029 break;
1031 default:
1032 res = t_false;
1035 return res;
1038 /* Follow the ssa edge into the expression EXPR.
1039 Return true if the strongly connected component has been found. */
1041 static t_bool
1042 follow_ssa_edge_expr (struct loop *loop, gimple *at_stmt, tree expr,
1043 gphi *halting_phi, tree *evolution_of_loop,
1044 int limit)
1046 enum tree_code code = TREE_CODE (expr);
1047 tree type = TREE_TYPE (expr), rhs0, rhs1;
1048 t_bool res;
1050 /* The EXPR is one of the following cases:
1051 - an SSA_NAME,
1052 - an INTEGER_CST,
1053 - a PLUS_EXPR,
1054 - a POINTER_PLUS_EXPR,
1055 - a MINUS_EXPR,
1056 - an ASSERT_EXPR,
1057 - other cases are not yet handled. */
1059 switch (code)
1061 CASE_CONVERT:
1062 /* This assignment is under the form "a_1 = (cast) rhs. */
1063 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1064 halting_phi, evolution_of_loop, limit);
1065 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1066 break;
1068 case INTEGER_CST:
1069 /* This assignment is under the form "a_1 = 7". */
1070 res = t_false;
1071 break;
1073 case SSA_NAME:
1074 /* This assignment is under the form: "a_1 = b_2". */
1075 res = follow_ssa_edge
1076 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1077 break;
1079 case POINTER_PLUS_EXPR:
1080 case PLUS_EXPR:
1081 case MINUS_EXPR:
1082 /* This case is under the form "rhs0 +- rhs1". */
1083 rhs0 = TREE_OPERAND (expr, 0);
1084 rhs1 = TREE_OPERAND (expr, 1);
1085 type = TREE_TYPE (rhs0);
1086 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1087 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1088 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1089 halting_phi, evolution_of_loop, limit);
1090 break;
1092 case ADDR_EXPR:
1093 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1094 if (TREE_CODE (TREE_OPERAND (expr, 0)) == MEM_REF)
1096 expr = TREE_OPERAND (expr, 0);
1097 rhs0 = TREE_OPERAND (expr, 0);
1098 rhs1 = TREE_OPERAND (expr, 1);
1099 type = TREE_TYPE (rhs0);
1100 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1101 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1102 res = follow_ssa_edge_binary (loop, at_stmt, type,
1103 rhs0, POINTER_PLUS_EXPR, rhs1,
1104 halting_phi, evolution_of_loop, limit);
1106 else
1107 res = t_false;
1108 break;
1110 case ASSERT_EXPR:
1111 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1112 It must be handled as a copy assignment of the form a_1 = a_2. */
1113 rhs0 = ASSERT_EXPR_VAR (expr);
1114 if (TREE_CODE (rhs0) == SSA_NAME)
1115 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1116 halting_phi, evolution_of_loop, limit);
1117 else
1118 res = t_false;
1119 break;
1121 default:
1122 res = t_false;
1123 break;
1126 return res;
1129 /* Follow the ssa edge into the right hand side of an assignment STMT.
1130 Return true if the strongly connected component has been found. */
1132 static t_bool
1133 follow_ssa_edge_in_rhs (struct loop *loop, gimple *stmt,
1134 gphi *halting_phi, tree *evolution_of_loop,
1135 int limit)
1137 enum tree_code code = gimple_assign_rhs_code (stmt);
1138 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1139 t_bool res;
1141 switch (code)
1143 CASE_CONVERT:
1144 /* This assignment is under the form "a_1 = (cast) rhs. */
1145 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1146 halting_phi, evolution_of_loop, limit);
1147 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1148 break;
1150 case POINTER_PLUS_EXPR:
1151 case PLUS_EXPR:
1152 case MINUS_EXPR:
1153 rhs1 = gimple_assign_rhs1 (stmt);
1154 rhs2 = gimple_assign_rhs2 (stmt);
1155 type = TREE_TYPE (rhs1);
1156 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1157 halting_phi, evolution_of_loop, limit);
1158 break;
1160 default:
1161 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1162 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1163 halting_phi, evolution_of_loop, limit);
1164 else
1165 res = t_false;
1166 break;
1169 return res;
1172 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1174 static bool
1175 backedge_phi_arg_p (gphi *phi, int i)
1177 const_edge e = gimple_phi_arg_edge (phi, i);
1179 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1180 about updating it anywhere, and this should work as well most of the
1181 time. */
1182 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1183 return true;
1185 return false;
1188 /* Helper function for one branch of the condition-phi-node. Return
1189 true if the strongly connected component has been found following
1190 this path. */
1192 static inline t_bool
1193 follow_ssa_edge_in_condition_phi_branch (int i,
1194 struct loop *loop,
1195 gphi *condition_phi,
1196 gphi *halting_phi,
1197 tree *evolution_of_branch,
1198 tree init_cond, int limit)
1200 tree branch = PHI_ARG_DEF (condition_phi, i);
1201 *evolution_of_branch = chrec_dont_know;
1203 /* Do not follow back edges (they must belong to an irreducible loop, which
1204 we really do not want to worry about). */
1205 if (backedge_phi_arg_p (condition_phi, i))
1206 return t_false;
1208 if (TREE_CODE (branch) == SSA_NAME)
1210 *evolution_of_branch = init_cond;
1211 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1212 evolution_of_branch, limit);
1215 /* This case occurs when one of the condition branches sets
1216 the variable to a constant: i.e. a phi-node like
1217 "a_2 = PHI <a_7(5), 2(6)>;".
1219 FIXME: This case have to be refined correctly:
1220 in some cases it is possible to say something better than
1221 chrec_dont_know, for example using a wrap-around notation. */
1222 return t_false;
1225 /* This function merges the branches of a condition-phi-node in a
1226 loop. */
1228 static t_bool
1229 follow_ssa_edge_in_condition_phi (struct loop *loop,
1230 gphi *condition_phi,
1231 gphi *halting_phi,
1232 tree *evolution_of_loop, int limit)
1234 int i, n;
1235 tree init = *evolution_of_loop;
1236 tree evolution_of_branch;
1237 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1238 halting_phi,
1239 &evolution_of_branch,
1240 init, limit);
1241 if (res == t_false || res == t_dont_know)
1242 return res;
1244 *evolution_of_loop = evolution_of_branch;
1246 n = gimple_phi_num_args (condition_phi);
1247 for (i = 1; i < n; i++)
1249 /* Quickly give up when the evolution of one of the branches is
1250 not known. */
1251 if (*evolution_of_loop == chrec_dont_know)
1252 return t_true;
1254 /* Increase the limit by the PHI argument number to avoid exponential
1255 time and memory complexity. */
1256 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1257 halting_phi,
1258 &evolution_of_branch,
1259 init, limit + i);
1260 if (res == t_false || res == t_dont_know)
1261 return res;
1263 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1264 evolution_of_branch);
1267 return t_true;
1270 /* Follow an SSA edge in an inner loop. It computes the overall
1271 effect of the loop, and following the symbolic initial conditions,
1272 it follows the edges in the parent loop. The inner loop is
1273 considered as a single statement. */
1275 static t_bool
1276 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1277 gphi *loop_phi_node,
1278 gphi *halting_phi,
1279 tree *evolution_of_loop, int limit)
1281 struct loop *loop = loop_containing_stmt (loop_phi_node);
1282 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1284 /* Sometimes, the inner loop is too difficult to analyze, and the
1285 result of the analysis is a symbolic parameter. */
1286 if (ev == PHI_RESULT (loop_phi_node))
1288 t_bool res = t_false;
1289 int i, n = gimple_phi_num_args (loop_phi_node);
1291 for (i = 0; i < n; i++)
1293 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1294 basic_block bb;
1296 /* Follow the edges that exit the inner loop. */
1297 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1298 if (!flow_bb_inside_loop_p (loop, bb))
1299 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1300 arg, halting_phi,
1301 evolution_of_loop, limit);
1302 if (res == t_true)
1303 break;
1306 /* If the path crosses this loop-phi, give up. */
1307 if (res == t_true)
1308 *evolution_of_loop = chrec_dont_know;
1310 return res;
1313 /* Otherwise, compute the overall effect of the inner loop. */
1314 ev = compute_overall_effect_of_inner_loop (loop, ev);
1315 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1316 evolution_of_loop, limit);
1319 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1320 path that is analyzed on the return walk. */
1322 static t_bool
1323 follow_ssa_edge (struct loop *loop, gimple *def, gphi *halting_phi,
1324 tree *evolution_of_loop, int limit)
1326 struct loop *def_loop;
1328 if (gimple_nop_p (def))
1329 return t_false;
1331 /* Give up if the path is longer than the MAX that we allow. */
1332 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY))
1333 return t_dont_know;
1335 def_loop = loop_containing_stmt (def);
1337 switch (gimple_code (def))
1339 case GIMPLE_PHI:
1340 if (!loop_phi_node_p (def))
1341 /* DEF is a condition-phi-node. Follow the branches, and
1342 record their evolutions. Finally, merge the collected
1343 information and set the approximation to the main
1344 variable. */
1345 return follow_ssa_edge_in_condition_phi
1346 (loop, as_a <gphi *> (def), halting_phi, evolution_of_loop,
1347 limit);
1349 /* When the analyzed phi is the halting_phi, the
1350 depth-first search is over: we have found a path from
1351 the halting_phi to itself in the loop. */
1352 if (def == halting_phi)
1353 return t_true;
1355 /* Otherwise, the evolution of the HALTING_PHI depends
1356 on the evolution of another loop-phi-node, i.e. the
1357 evolution function is a higher degree polynomial. */
1358 if (def_loop == loop)
1359 return t_false;
1361 /* Inner loop. */
1362 if (flow_loop_nested_p (loop, def_loop))
1363 return follow_ssa_edge_inner_loop_phi
1364 (loop, as_a <gphi *> (def), halting_phi, evolution_of_loop,
1365 limit + 1);
1367 /* Outer loop. */
1368 return t_false;
1370 case GIMPLE_ASSIGN:
1371 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1372 evolution_of_loop, limit);
1374 default:
1375 /* At this level of abstraction, the program is just a set
1376 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1377 other node to be handled. */
1378 return t_false;
1383 /* Simplify PEELED_CHREC represented by (init_cond, arg) in LOOP.
1384 Handle below case and return the corresponding POLYNOMIAL_CHREC:
1386 # i_17 = PHI <i_13(5), 0(3)>
1387 # _20 = PHI <_5(5), start_4(D)(3)>
1389 i_13 = i_17 + 1;
1390 _5 = start_4(D) + i_13;
1392 Though variable _20 appears as a PEELED_CHREC in the form of
1393 (start_4, _5)_LOOP, it's a POLYNOMIAL_CHREC like {start_4, 1}_LOOP.
1395 See PR41488. */
1397 static tree
1398 simplify_peeled_chrec (struct loop *loop, tree arg, tree init_cond)
1400 aff_tree aff1, aff2;
1401 tree ev, left, right, type, step_val;
1402 hash_map<tree, name_expansion *> *peeled_chrec_map = NULL;
1404 ev = instantiate_parameters (loop, analyze_scalar_evolution (loop, arg));
1405 if (ev == NULL_TREE || TREE_CODE (ev) != POLYNOMIAL_CHREC)
1406 return chrec_dont_know;
1408 left = CHREC_LEFT (ev);
1409 right = CHREC_RIGHT (ev);
1410 type = TREE_TYPE (left);
1411 step_val = chrec_fold_plus (type, init_cond, right);
1413 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1414 if "left" equals to "init + right". */
1415 if (operand_equal_p (left, step_val, 0))
1417 if (dump_file && (dump_flags & TDF_SCEV))
1418 fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1420 return build_polynomial_chrec (loop->num, init_cond, right);
1423 /* Try harder to check if they are equal. */
1424 tree_to_aff_combination_expand (left, type, &aff1, &peeled_chrec_map);
1425 tree_to_aff_combination_expand (step_val, type, &aff2, &peeled_chrec_map);
1426 free_affine_expand_cache (&peeled_chrec_map);
1427 aff_combination_scale (&aff2, -1);
1428 aff_combination_add (&aff1, &aff2);
1430 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1431 if "left" equals to "init + right". */
1432 if (aff_combination_zero_p (&aff1))
1434 if (dump_file && (dump_flags & TDF_SCEV))
1435 fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1437 return build_polynomial_chrec (loop->num, init_cond, right);
1439 return chrec_dont_know;
1442 /* Given a LOOP_PHI_NODE, this function determines the evolution
1443 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1445 static tree
1446 analyze_evolution_in_loop (gphi *loop_phi_node,
1447 tree init_cond)
1449 int i, n = gimple_phi_num_args (loop_phi_node);
1450 tree evolution_function = chrec_not_analyzed_yet;
1451 struct loop *loop = loop_containing_stmt (loop_phi_node);
1452 basic_block bb;
1453 static bool simplify_peeled_chrec_p = true;
1455 if (dump_file && (dump_flags & TDF_SCEV))
1457 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1458 fprintf (dump_file, " (loop_phi_node = ");
1459 print_gimple_stmt (dump_file, loop_phi_node, 0);
1460 fprintf (dump_file, ")\n");
1463 for (i = 0; i < n; i++)
1465 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1466 gimple *ssa_chain;
1467 tree ev_fn;
1468 t_bool res;
1470 /* Select the edges that enter the loop body. */
1471 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1472 if (!flow_bb_inside_loop_p (loop, bb))
1473 continue;
1475 if (TREE_CODE (arg) == SSA_NAME)
1477 bool val = false;
1479 ssa_chain = SSA_NAME_DEF_STMT (arg);
1481 /* Pass in the initial condition to the follow edge function. */
1482 ev_fn = init_cond;
1483 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1485 /* If ev_fn has no evolution in the inner loop, and the
1486 init_cond is not equal to ev_fn, then we have an
1487 ambiguity between two possible values, as we cannot know
1488 the number of iterations at this point. */
1489 if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1490 && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1491 && !operand_equal_p (init_cond, ev_fn, 0))
1492 ev_fn = chrec_dont_know;
1494 else
1495 res = t_false;
1497 /* When it is impossible to go back on the same
1498 loop_phi_node by following the ssa edges, the
1499 evolution is represented by a peeled chrec, i.e. the
1500 first iteration, EV_FN has the value INIT_COND, then
1501 all the other iterations it has the value of ARG.
1502 For the moment, PEELED_CHREC nodes are not built. */
1503 if (res != t_true)
1505 ev_fn = chrec_dont_know;
1506 /* Try to recognize POLYNOMIAL_CHREC which appears in
1507 the form of PEELED_CHREC, but guard the process with
1508 a bool variable to keep the analyzer from infinite
1509 recurrence for real PEELED_RECs. */
1510 if (simplify_peeled_chrec_p && TREE_CODE (arg) == SSA_NAME)
1512 simplify_peeled_chrec_p = false;
1513 ev_fn = simplify_peeled_chrec (loop, arg, init_cond);
1514 simplify_peeled_chrec_p = true;
1518 /* When there are multiple back edges of the loop (which in fact never
1519 happens currently, but nevertheless), merge their evolutions. */
1520 evolution_function = chrec_merge (evolution_function, ev_fn);
1522 if (evolution_function == chrec_dont_know)
1523 break;
1526 if (dump_file && (dump_flags & TDF_SCEV))
1528 fprintf (dump_file, " (evolution_function = ");
1529 print_generic_expr (dump_file, evolution_function);
1530 fprintf (dump_file, "))\n");
1533 return evolution_function;
1536 /* Looks to see if VAR is a copy of a constant (via straightforward assignments
1537 or degenerate phi's). If so, returns the constant; else, returns VAR. */
1539 static tree
1540 follow_copies_to_constant (tree var)
1542 tree res = var;
1543 while (TREE_CODE (res) == SSA_NAME)
1545 gimple *def = SSA_NAME_DEF_STMT (res);
1546 if (gphi *phi = dyn_cast <gphi *> (def))
1548 if (tree rhs = degenerate_phi_result (phi))
1549 res = rhs;
1550 else
1551 break;
1553 else if (gimple_assign_single_p (def))
1554 /* Will exit loop if not an SSA_NAME. */
1555 res = gimple_assign_rhs1 (def);
1556 else
1557 break;
1559 if (CONSTANT_CLASS_P (res))
1560 return res;
1561 return var;
1564 /* Given a loop-phi-node, return the initial conditions of the
1565 variable on entry of the loop. When the CCP has propagated
1566 constants into the loop-phi-node, the initial condition is
1567 instantiated, otherwise the initial condition is kept symbolic.
1568 This analyzer does not analyze the evolution outside the current
1569 loop, and leaves this task to the on-demand tree reconstructor. */
1571 static tree
1572 analyze_initial_condition (gphi *loop_phi_node)
1574 int i, n;
1575 tree init_cond = chrec_not_analyzed_yet;
1576 struct loop *loop = loop_containing_stmt (loop_phi_node);
1578 if (dump_file && (dump_flags & TDF_SCEV))
1580 fprintf (dump_file, "(analyze_initial_condition \n");
1581 fprintf (dump_file, " (loop_phi_node = \n");
1582 print_gimple_stmt (dump_file, loop_phi_node, 0);
1583 fprintf (dump_file, ")\n");
1586 n = gimple_phi_num_args (loop_phi_node);
1587 for (i = 0; i < n; i++)
1589 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1590 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1592 /* When the branch is oriented to the loop's body, it does
1593 not contribute to the initial condition. */
1594 if (flow_bb_inside_loop_p (loop, bb))
1595 continue;
1597 if (init_cond == chrec_not_analyzed_yet)
1599 init_cond = branch;
1600 continue;
1603 if (TREE_CODE (branch) == SSA_NAME)
1605 init_cond = chrec_dont_know;
1606 break;
1609 init_cond = chrec_merge (init_cond, branch);
1612 /* Ooops -- a loop without an entry??? */
1613 if (init_cond == chrec_not_analyzed_yet)
1614 init_cond = chrec_dont_know;
1616 /* We may not have fully constant propagated IL. Handle degenerate PHIs here
1617 to not miss important early loop unrollings. */
1618 init_cond = follow_copies_to_constant (init_cond);
1620 if (dump_file && (dump_flags & TDF_SCEV))
1622 fprintf (dump_file, " (init_cond = ");
1623 print_generic_expr (dump_file, init_cond);
1624 fprintf (dump_file, "))\n");
1627 return init_cond;
1630 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1632 static tree
1633 interpret_loop_phi (struct loop *loop, gphi *loop_phi_node)
1635 tree res;
1636 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1637 tree init_cond;
1639 gcc_assert (phi_loop == loop);
1641 /* Otherwise really interpret the loop phi. */
1642 init_cond = analyze_initial_condition (loop_phi_node);
1643 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1645 /* Verify we maintained the correct initial condition throughout
1646 possible conversions in the SSA chain. */
1647 if (res != chrec_dont_know)
1649 tree new_init = res;
1650 if (CONVERT_EXPR_P (res)
1651 && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1652 new_init = fold_convert (TREE_TYPE (res),
1653 CHREC_LEFT (TREE_OPERAND (res, 0)));
1654 else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1655 new_init = CHREC_LEFT (res);
1656 STRIP_USELESS_TYPE_CONVERSION (new_init);
1657 if (TREE_CODE (new_init) == POLYNOMIAL_CHREC
1658 || !operand_equal_p (init_cond, new_init, 0))
1659 return chrec_dont_know;
1662 return res;
1665 /* This function merges the branches of a condition-phi-node,
1666 contained in the outermost loop, and whose arguments are already
1667 analyzed. */
1669 static tree
1670 interpret_condition_phi (struct loop *loop, gphi *condition_phi)
1672 int i, n = gimple_phi_num_args (condition_phi);
1673 tree res = chrec_not_analyzed_yet;
1675 for (i = 0; i < n; i++)
1677 tree branch_chrec;
1679 if (backedge_phi_arg_p (condition_phi, i))
1681 res = chrec_dont_know;
1682 break;
1685 branch_chrec = analyze_scalar_evolution
1686 (loop, PHI_ARG_DEF (condition_phi, i));
1688 res = chrec_merge (res, branch_chrec);
1689 if (res == chrec_dont_know)
1690 break;
1693 return res;
1696 /* Interpret the operation RHS1 OP RHS2. If we didn't
1697 analyze this node before, follow the definitions until ending
1698 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1699 return path, this function propagates evolutions (ala constant copy
1700 propagation). OPND1 is not a GIMPLE expression because we could
1701 analyze the effect of an inner loop: see interpret_loop_phi. */
1703 static tree
1704 interpret_rhs_expr (struct loop *loop, gimple *at_stmt,
1705 tree type, tree rhs1, enum tree_code code, tree rhs2)
1707 tree res, chrec1, chrec2, ctype;
1708 gimple *def;
1710 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1712 if (is_gimple_min_invariant (rhs1))
1713 return chrec_convert (type, rhs1, at_stmt);
1715 if (code == SSA_NAME)
1716 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1717 at_stmt);
1719 if (code == ASSERT_EXPR)
1721 rhs1 = ASSERT_EXPR_VAR (rhs1);
1722 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1723 at_stmt);
1727 switch (code)
1729 case ADDR_EXPR:
1730 if (TREE_CODE (TREE_OPERAND (rhs1, 0)) == MEM_REF
1731 || handled_component_p (TREE_OPERAND (rhs1, 0)))
1733 machine_mode mode;
1734 poly_int64 bitsize, bitpos;
1735 int unsignedp, reversep;
1736 int volatilep = 0;
1737 tree base, offset;
1738 tree chrec3;
1739 tree unitpos;
1741 base = get_inner_reference (TREE_OPERAND (rhs1, 0),
1742 &bitsize, &bitpos, &offset, &mode,
1743 &unsignedp, &reversep, &volatilep);
1745 if (TREE_CODE (base) == MEM_REF)
1747 rhs2 = TREE_OPERAND (base, 1);
1748 rhs1 = TREE_OPERAND (base, 0);
1750 chrec1 = analyze_scalar_evolution (loop, rhs1);
1751 chrec2 = analyze_scalar_evolution (loop, rhs2);
1752 chrec1 = chrec_convert (type, chrec1, at_stmt);
1753 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1754 chrec1 = instantiate_parameters (loop, chrec1);
1755 chrec2 = instantiate_parameters (loop, chrec2);
1756 res = chrec_fold_plus (type, chrec1, chrec2);
1758 else
1760 chrec1 = analyze_scalar_evolution_for_address_of (loop, base);
1761 chrec1 = chrec_convert (type, chrec1, at_stmt);
1762 res = chrec1;
1765 if (offset != NULL_TREE)
1767 chrec2 = analyze_scalar_evolution (loop, offset);
1768 chrec2 = chrec_convert (TREE_TYPE (offset), chrec2, at_stmt);
1769 chrec2 = instantiate_parameters (loop, chrec2);
1770 res = chrec_fold_plus (type, res, chrec2);
1773 if (maybe_ne (bitpos, 0))
1775 unitpos = size_int (exact_div (bitpos, BITS_PER_UNIT));
1776 chrec3 = analyze_scalar_evolution (loop, unitpos);
1777 chrec3 = chrec_convert (TREE_TYPE (unitpos), chrec3, at_stmt);
1778 chrec3 = instantiate_parameters (loop, chrec3);
1779 res = chrec_fold_plus (type, res, chrec3);
1782 else
1783 res = chrec_dont_know;
1784 break;
1786 case POINTER_PLUS_EXPR:
1787 chrec1 = analyze_scalar_evolution (loop, rhs1);
1788 chrec2 = analyze_scalar_evolution (loop, rhs2);
1789 chrec1 = chrec_convert (type, chrec1, at_stmt);
1790 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1791 chrec1 = instantiate_parameters (loop, chrec1);
1792 chrec2 = instantiate_parameters (loop, chrec2);
1793 res = chrec_fold_plus (type, chrec1, chrec2);
1794 break;
1796 case PLUS_EXPR:
1797 chrec1 = analyze_scalar_evolution (loop, rhs1);
1798 chrec2 = analyze_scalar_evolution (loop, rhs2);
1799 ctype = type;
1800 /* When the stmt is conditionally executed re-write the CHREC
1801 into a form that has well-defined behavior on overflow. */
1802 if (at_stmt
1803 && INTEGRAL_TYPE_P (type)
1804 && ! TYPE_OVERFLOW_WRAPS (type)
1805 && ! dominated_by_p (CDI_DOMINATORS, loop->latch,
1806 gimple_bb (at_stmt)))
1807 ctype = unsigned_type_for (type);
1808 chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1809 chrec2 = chrec_convert (ctype, chrec2, at_stmt);
1810 chrec1 = instantiate_parameters (loop, chrec1);
1811 chrec2 = instantiate_parameters (loop, chrec2);
1812 res = chrec_fold_plus (ctype, chrec1, chrec2);
1813 if (type != ctype)
1814 res = chrec_convert (type, res, at_stmt);
1815 break;
1817 case MINUS_EXPR:
1818 chrec1 = analyze_scalar_evolution (loop, rhs1);
1819 chrec2 = analyze_scalar_evolution (loop, rhs2);
1820 ctype = type;
1821 /* When the stmt is conditionally executed re-write the CHREC
1822 into a form that has well-defined behavior on overflow. */
1823 if (at_stmt
1824 && INTEGRAL_TYPE_P (type)
1825 && ! TYPE_OVERFLOW_WRAPS (type)
1826 && ! dominated_by_p (CDI_DOMINATORS,
1827 loop->latch, gimple_bb (at_stmt)))
1828 ctype = unsigned_type_for (type);
1829 chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1830 chrec2 = chrec_convert (ctype, chrec2, at_stmt);
1831 chrec1 = instantiate_parameters (loop, chrec1);
1832 chrec2 = instantiate_parameters (loop, chrec2);
1833 res = chrec_fold_minus (ctype, chrec1, chrec2);
1834 if (type != ctype)
1835 res = chrec_convert (type, res, at_stmt);
1836 break;
1838 case NEGATE_EXPR:
1839 chrec1 = analyze_scalar_evolution (loop, rhs1);
1840 ctype = type;
1841 /* When the stmt is conditionally executed re-write the CHREC
1842 into a form that has well-defined behavior on overflow. */
1843 if (at_stmt
1844 && INTEGRAL_TYPE_P (type)
1845 && ! TYPE_OVERFLOW_WRAPS (type)
1846 && ! dominated_by_p (CDI_DOMINATORS,
1847 loop->latch, gimple_bb (at_stmt)))
1848 ctype = unsigned_type_for (type);
1849 chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1850 /* TYPE may be integer, real or complex, so use fold_convert. */
1851 chrec1 = instantiate_parameters (loop, chrec1);
1852 res = chrec_fold_multiply (ctype, chrec1,
1853 fold_convert (ctype, integer_minus_one_node));
1854 if (type != ctype)
1855 res = chrec_convert (type, res, at_stmt);
1856 break;
1858 case BIT_NOT_EXPR:
1859 /* Handle ~X as -1 - X. */
1860 chrec1 = analyze_scalar_evolution (loop, rhs1);
1861 chrec1 = chrec_convert (type, chrec1, at_stmt);
1862 chrec1 = instantiate_parameters (loop, chrec1);
1863 res = chrec_fold_minus (type,
1864 fold_convert (type, integer_minus_one_node),
1865 chrec1);
1866 break;
1868 case MULT_EXPR:
1869 chrec1 = analyze_scalar_evolution (loop, rhs1);
1870 chrec2 = analyze_scalar_evolution (loop, rhs2);
1871 ctype = type;
1872 /* When the stmt is conditionally executed re-write the CHREC
1873 into a form that has well-defined behavior on overflow. */
1874 if (at_stmt
1875 && INTEGRAL_TYPE_P (type)
1876 && ! TYPE_OVERFLOW_WRAPS (type)
1877 && ! dominated_by_p (CDI_DOMINATORS,
1878 loop->latch, gimple_bb (at_stmt)))
1879 ctype = unsigned_type_for (type);
1880 chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1881 chrec2 = chrec_convert (ctype, chrec2, at_stmt);
1882 chrec1 = instantiate_parameters (loop, chrec1);
1883 chrec2 = instantiate_parameters (loop, chrec2);
1884 res = chrec_fold_multiply (ctype, chrec1, chrec2);
1885 if (type != ctype)
1886 res = chrec_convert (type, res, at_stmt);
1887 break;
1889 case LSHIFT_EXPR:
1891 /* Handle A<<B as A * (1<<B). */
1892 tree uns = unsigned_type_for (type);
1893 chrec1 = analyze_scalar_evolution (loop, rhs1);
1894 chrec2 = analyze_scalar_evolution (loop, rhs2);
1895 chrec1 = chrec_convert (uns, chrec1, at_stmt);
1896 chrec1 = instantiate_parameters (loop, chrec1);
1897 chrec2 = instantiate_parameters (loop, chrec2);
1899 tree one = build_int_cst (uns, 1);
1900 chrec2 = fold_build2 (LSHIFT_EXPR, uns, one, chrec2);
1901 res = chrec_fold_multiply (uns, chrec1, chrec2);
1902 res = chrec_convert (type, res, at_stmt);
1904 break;
1906 CASE_CONVERT:
1907 /* In case we have a truncation of a widened operation that in
1908 the truncated type has undefined overflow behavior analyze
1909 the operation done in an unsigned type of the same precision
1910 as the final truncation. We cannot derive a scalar evolution
1911 for the widened operation but for the truncated result. */
1912 if (TREE_CODE (type) == INTEGER_TYPE
1913 && TREE_CODE (TREE_TYPE (rhs1)) == INTEGER_TYPE
1914 && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (rhs1))
1915 && TYPE_OVERFLOW_UNDEFINED (type)
1916 && TREE_CODE (rhs1) == SSA_NAME
1917 && (def = SSA_NAME_DEF_STMT (rhs1))
1918 && is_gimple_assign (def)
1919 && TREE_CODE_CLASS (gimple_assign_rhs_code (def)) == tcc_binary
1920 && TREE_CODE (gimple_assign_rhs2 (def)) == INTEGER_CST)
1922 tree utype = unsigned_type_for (type);
1923 chrec1 = interpret_rhs_expr (loop, at_stmt, utype,
1924 gimple_assign_rhs1 (def),
1925 gimple_assign_rhs_code (def),
1926 gimple_assign_rhs2 (def));
1928 else
1929 chrec1 = analyze_scalar_evolution (loop, rhs1);
1930 res = chrec_convert (type, chrec1, at_stmt, true, rhs1);
1931 break;
1933 case BIT_AND_EXPR:
1934 /* Given int variable A, handle A&0xffff as (int)(unsigned short)A.
1935 If A is SCEV and its value is in the range of representable set
1936 of type unsigned short, the result expression is a (no-overflow)
1937 SCEV. */
1938 res = chrec_dont_know;
1939 if (tree_fits_uhwi_p (rhs2))
1941 int precision;
1942 unsigned HOST_WIDE_INT val = tree_to_uhwi (rhs2);
1944 val ++;
1945 /* Skip if value of rhs2 wraps in unsigned HOST_WIDE_INT or
1946 it's not the maximum value of a smaller type than rhs1. */
1947 if (val != 0
1948 && (precision = exact_log2 (val)) > 0
1949 && (unsigned) precision < TYPE_PRECISION (TREE_TYPE (rhs1)))
1951 tree utype = build_nonstandard_integer_type (precision, 1);
1953 if (TYPE_PRECISION (utype) < TYPE_PRECISION (TREE_TYPE (rhs1)))
1955 chrec1 = analyze_scalar_evolution (loop, rhs1);
1956 chrec1 = chrec_convert (utype, chrec1, at_stmt);
1957 res = chrec_convert (TREE_TYPE (rhs1), chrec1, at_stmt);
1961 break;
1963 default:
1964 res = chrec_dont_know;
1965 break;
1968 return res;
1971 /* Interpret the expression EXPR. */
1973 static tree
1974 interpret_expr (struct loop *loop, gimple *at_stmt, tree expr)
1976 enum tree_code code;
1977 tree type = TREE_TYPE (expr), op0, op1;
1979 if (automatically_generated_chrec_p (expr))
1980 return expr;
1982 if (TREE_CODE (expr) == POLYNOMIAL_CHREC
1983 || get_gimple_rhs_class (TREE_CODE (expr)) == GIMPLE_TERNARY_RHS)
1984 return chrec_dont_know;
1986 extract_ops_from_tree (expr, &code, &op0, &op1);
1988 return interpret_rhs_expr (loop, at_stmt, type,
1989 op0, code, op1);
1992 /* Interpret the rhs of the assignment STMT. */
1994 static tree
1995 interpret_gimple_assign (struct loop *loop, gimple *stmt)
1997 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1998 enum tree_code code = gimple_assign_rhs_code (stmt);
2000 return interpret_rhs_expr (loop, stmt, type,
2001 gimple_assign_rhs1 (stmt), code,
2002 gimple_assign_rhs2 (stmt));
2007 /* This section contains all the entry points:
2008 - number_of_iterations_in_loop,
2009 - analyze_scalar_evolution,
2010 - instantiate_parameters.
2013 /* Helper recursive function. */
2015 static tree
2016 analyze_scalar_evolution_1 (struct loop *loop, tree var)
2018 gimple *def;
2019 basic_block bb;
2020 struct loop *def_loop;
2021 tree res;
2023 if (TREE_CODE (var) != SSA_NAME)
2024 return interpret_expr (loop, NULL, var);
2026 def = SSA_NAME_DEF_STMT (var);
2027 bb = gimple_bb (def);
2028 def_loop = bb->loop_father;
2030 if (!flow_bb_inside_loop_p (loop, bb))
2032 /* Keep symbolic form, but look through obvious copies for constants. */
2033 res = follow_copies_to_constant (var);
2034 goto set_and_end;
2037 if (loop != def_loop)
2039 res = analyze_scalar_evolution_1 (def_loop, var);
2040 struct loop *loop_to_skip = superloop_at_depth (def_loop,
2041 loop_depth (loop) + 1);
2042 res = compute_overall_effect_of_inner_loop (loop_to_skip, res);
2043 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
2044 res = analyze_scalar_evolution_1 (loop, res);
2045 goto set_and_end;
2048 switch (gimple_code (def))
2050 case GIMPLE_ASSIGN:
2051 res = interpret_gimple_assign (loop, def);
2052 break;
2054 case GIMPLE_PHI:
2055 if (loop_phi_node_p (def))
2056 res = interpret_loop_phi (loop, as_a <gphi *> (def));
2057 else
2058 res = interpret_condition_phi (loop, as_a <gphi *> (def));
2059 break;
2061 default:
2062 res = chrec_dont_know;
2063 break;
2066 set_and_end:
2068 /* Keep the symbolic form. */
2069 if (res == chrec_dont_know)
2070 res = var;
2072 if (loop == def_loop)
2073 set_scalar_evolution (block_before_loop (loop), var, res);
2075 return res;
2078 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
2079 LOOP. LOOP is the loop in which the variable is used.
2081 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
2082 pointer to the statement that uses this variable, in order to
2083 determine the evolution function of the variable, use the following
2084 calls:
2086 loop_p loop = loop_containing_stmt (stmt);
2087 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
2088 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
2091 tree
2092 analyze_scalar_evolution (struct loop *loop, tree var)
2094 tree res;
2096 /* ??? Fix callers. */
2097 if (! loop)
2098 return var;
2100 if (dump_file && (dump_flags & TDF_SCEV))
2102 fprintf (dump_file, "(analyze_scalar_evolution \n");
2103 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
2104 fprintf (dump_file, " (scalar = ");
2105 print_generic_expr (dump_file, var);
2106 fprintf (dump_file, ")\n");
2109 res = get_scalar_evolution (block_before_loop (loop), var);
2110 if (res == chrec_not_analyzed_yet)
2111 res = analyze_scalar_evolution_1 (loop, var);
2113 if (dump_file && (dump_flags & TDF_SCEV))
2114 fprintf (dump_file, ")\n");
2116 return res;
2119 /* Analyzes and returns the scalar evolution of VAR address in LOOP. */
2121 static tree
2122 analyze_scalar_evolution_for_address_of (struct loop *loop, tree var)
2124 return analyze_scalar_evolution (loop, build_fold_addr_expr (var));
2127 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
2128 WRTO_LOOP (which should be a superloop of USE_LOOP)
2130 FOLDED_CASTS is set to true if resolve_mixers used
2131 chrec_convert_aggressive (TODO -- not really, we are way too conservative
2132 at the moment in order to keep things simple).
2134 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
2135 example:
2137 for (i = 0; i < 100; i++) -- loop 1
2139 for (j = 0; j < 100; j++) -- loop 2
2141 k1 = i;
2142 k2 = j;
2144 use2 (k1, k2);
2146 for (t = 0; t < 100; t++) -- loop 3
2147 use3 (k1, k2);
2150 use1 (k1, k2);
2153 Both k1 and k2 are invariants in loop3, thus
2154 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
2155 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
2157 As they are invariant, it does not matter whether we consider their
2158 usage in loop 3 or loop 2, hence
2159 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
2160 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
2161 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
2162 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
2164 Similarly for their evolutions with respect to loop 1. The values of K2
2165 in the use in loop 2 vary independently on loop 1, thus we cannot express
2166 the evolution with respect to loop 1:
2167 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
2168 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
2169 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
2170 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
2172 The value of k2 in the use in loop 1 is known, though:
2173 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
2174 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
2177 static tree
2178 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
2179 tree version, bool *folded_casts)
2181 bool val = false;
2182 tree ev = version, tmp;
2184 /* We cannot just do
2186 tmp = analyze_scalar_evolution (use_loop, version);
2187 ev = resolve_mixers (wrto_loop, tmp, folded_casts);
2189 as resolve_mixers would query the scalar evolution with respect to
2190 wrto_loop. For example, in the situation described in the function
2191 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2192 version = k2. Then
2194 analyze_scalar_evolution (use_loop, version) = k2
2196 and resolve_mixers (loop1, k2, folded_casts) finds that the value of
2197 k2 in loop 1 is 100, which is a wrong result, since we are interested
2198 in the value in loop 3.
2200 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2201 each time checking that there is no evolution in the inner loop. */
2203 if (folded_casts)
2204 *folded_casts = false;
2205 while (1)
2207 tmp = analyze_scalar_evolution (use_loop, ev);
2208 ev = resolve_mixers (use_loop, tmp, folded_casts);
2210 if (use_loop == wrto_loop)
2211 return ev;
2213 /* If the value of the use changes in the inner loop, we cannot express
2214 its value in the outer loop (we might try to return interval chrec,
2215 but we do not have a user for it anyway) */
2216 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2217 || !val)
2218 return chrec_dont_know;
2220 use_loop = loop_outer (use_loop);
2225 /* Hashtable helpers for a temporary hash-table used when
2226 instantiating a CHREC or resolving mixers. For this use
2227 instantiated_below is always the same. */
2229 struct instantiate_cache_type
2231 htab_t map;
2232 vec<scev_info_str> entries;
2234 instantiate_cache_type () : map (NULL), entries (vNULL) {}
2235 ~instantiate_cache_type ();
2236 tree get (unsigned slot) { return entries[slot].chrec; }
2237 void set (unsigned slot, tree chrec) { entries[slot].chrec = chrec; }
2240 instantiate_cache_type::~instantiate_cache_type ()
2242 if (map != NULL)
2244 htab_delete (map);
2245 entries.release ();
2249 /* Cache to avoid infinite recursion when instantiating an SSA name.
2250 Live during the outermost instantiate_scev or resolve_mixers call. */
2251 static instantiate_cache_type *global_cache;
2253 /* Computes a hash function for database element ELT. */
2255 static inline hashval_t
2256 hash_idx_scev_info (const void *elt_)
2258 unsigned idx = ((size_t) elt_) - 2;
2259 return scev_info_hasher::hash (&global_cache->entries[idx]);
2262 /* Compares database elements E1 and E2. */
2264 static inline int
2265 eq_idx_scev_info (const void *e1, const void *e2)
2267 unsigned idx1 = ((size_t) e1) - 2;
2268 return scev_info_hasher::equal (&global_cache->entries[idx1],
2269 (const scev_info_str *) e2);
2272 /* Returns from CACHE the slot number of the cached chrec for NAME. */
2274 static unsigned
2275 get_instantiated_value_entry (instantiate_cache_type &cache,
2276 tree name, edge instantiate_below)
2278 if (!cache.map)
2280 cache.map = htab_create (10, hash_idx_scev_info, eq_idx_scev_info, NULL);
2281 cache.entries.create (10);
2284 scev_info_str e;
2285 e.name_version = SSA_NAME_VERSION (name);
2286 e.instantiated_below = instantiate_below->dest->index;
2287 void **slot = htab_find_slot_with_hash (cache.map, &e,
2288 scev_info_hasher::hash (&e), INSERT);
2289 if (!*slot)
2291 e.chrec = chrec_not_analyzed_yet;
2292 *slot = (void *)(size_t)(cache.entries.length () + 2);
2293 cache.entries.safe_push (e);
2296 return ((size_t)*slot) - 2;
2300 /* Return the closed_loop_phi node for VAR. If there is none, return
2301 NULL_TREE. */
2303 static tree
2304 loop_closed_phi_def (tree var)
2306 struct loop *loop;
2307 edge exit;
2308 gphi *phi;
2309 gphi_iterator psi;
2311 if (var == NULL_TREE
2312 || TREE_CODE (var) != SSA_NAME)
2313 return NULL_TREE;
2315 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2316 exit = single_exit (loop);
2317 if (!exit)
2318 return NULL_TREE;
2320 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2322 phi = psi.phi ();
2323 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2324 return PHI_RESULT (phi);
2327 return NULL_TREE;
2330 static tree instantiate_scev_r (edge, struct loop *, struct loop *,
2331 tree, bool *, int);
2333 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2334 and EVOLUTION_LOOP, that were left under a symbolic form.
2336 CHREC is an SSA_NAME to be instantiated.
2338 CACHE is the cache of already instantiated values.
2340 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2341 conversions that may wrap in signed/pointer type are folded, as long
2342 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2343 then we don't do such fold.
2345 SIZE_EXPR is used for computing the size of the expression to be
2346 instantiated, and to stop if it exceeds some limit. */
2348 static tree
2349 instantiate_scev_name (edge instantiate_below,
2350 struct loop *evolution_loop, struct loop *inner_loop,
2351 tree chrec,
2352 bool *fold_conversions,
2353 int size_expr)
2355 tree res;
2356 struct loop *def_loop;
2357 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2359 /* A parameter, nothing to do. */
2360 if (!def_bb
2361 || !dominated_by_p (CDI_DOMINATORS, def_bb, instantiate_below->dest))
2362 return chrec;
2364 /* We cache the value of instantiated variable to avoid exponential
2365 time complexity due to reevaluations. We also store the convenient
2366 value in the cache in order to prevent infinite recursion -- we do
2367 not want to instantiate the SSA_NAME if it is in a mixer
2368 structure. This is used for avoiding the instantiation of
2369 recursively defined functions, such as:
2371 | a_2 -> {0, +, 1, +, a_2}_1 */
2373 unsigned si = get_instantiated_value_entry (*global_cache,
2374 chrec, instantiate_below);
2375 if (global_cache->get (si) != chrec_not_analyzed_yet)
2376 return global_cache->get (si);
2378 /* On recursion return chrec_dont_know. */
2379 global_cache->set (si, chrec_dont_know);
2381 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2383 if (! dominated_by_p (CDI_DOMINATORS,
2384 def_loop->header, instantiate_below->dest))
2386 gimple *def = SSA_NAME_DEF_STMT (chrec);
2387 if (gassign *ass = dyn_cast <gassign *> (def))
2389 switch (gimple_assign_rhs_class (ass))
2391 case GIMPLE_UNARY_RHS:
2393 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2394 inner_loop, gimple_assign_rhs1 (ass),
2395 fold_conversions, size_expr);
2396 if (op0 == chrec_dont_know)
2397 return chrec_dont_know;
2398 res = fold_build1 (gimple_assign_rhs_code (ass),
2399 TREE_TYPE (chrec), op0);
2400 break;
2402 case GIMPLE_BINARY_RHS:
2404 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2405 inner_loop, gimple_assign_rhs1 (ass),
2406 fold_conversions, size_expr);
2407 if (op0 == chrec_dont_know)
2408 return chrec_dont_know;
2409 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2410 inner_loop, gimple_assign_rhs2 (ass),
2411 fold_conversions, size_expr);
2412 if (op1 == chrec_dont_know)
2413 return chrec_dont_know;
2414 res = fold_build2 (gimple_assign_rhs_code (ass),
2415 TREE_TYPE (chrec), op0, op1);
2416 break;
2418 default:
2419 res = chrec_dont_know;
2422 else
2423 res = chrec_dont_know;
2424 global_cache->set (si, res);
2425 return res;
2428 /* If the analysis yields a parametric chrec, instantiate the
2429 result again. */
2430 res = analyze_scalar_evolution (def_loop, chrec);
2432 /* Don't instantiate default definitions. */
2433 if (TREE_CODE (res) == SSA_NAME
2434 && SSA_NAME_IS_DEFAULT_DEF (res))
2437 /* Don't instantiate loop-closed-ssa phi nodes. */
2438 else if (TREE_CODE (res) == SSA_NAME
2439 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2440 > loop_depth (def_loop))
2442 if (res == chrec)
2443 res = loop_closed_phi_def (chrec);
2444 else
2445 res = chrec;
2447 /* When there is no loop_closed_phi_def, it means that the
2448 variable is not used after the loop: try to still compute the
2449 value of the variable when exiting the loop. */
2450 if (res == NULL_TREE)
2452 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2453 res = analyze_scalar_evolution (loop, chrec);
2454 res = compute_overall_effect_of_inner_loop (loop, res);
2455 res = instantiate_scev_r (instantiate_below, evolution_loop,
2456 inner_loop, res,
2457 fold_conversions, size_expr);
2459 else if (dominated_by_p (CDI_DOMINATORS,
2460 gimple_bb (SSA_NAME_DEF_STMT (res)),
2461 instantiate_below->dest))
2462 res = chrec_dont_know;
2465 else if (res != chrec_dont_know)
2467 if (inner_loop
2468 && def_bb->loop_father != inner_loop
2469 && !flow_loop_nested_p (def_bb->loop_father, inner_loop))
2470 /* ??? We could try to compute the overall effect of the loop here. */
2471 res = chrec_dont_know;
2472 else
2473 res = instantiate_scev_r (instantiate_below, evolution_loop,
2474 inner_loop, res,
2475 fold_conversions, size_expr);
2478 /* Store the correct value to the cache. */
2479 global_cache->set (si, res);
2480 return res;
2483 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2484 and EVOLUTION_LOOP, that were left under a symbolic form.
2486 CHREC is a polynomial chain of recurrence to be instantiated.
2488 CACHE is the cache of already instantiated values.
2490 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2491 conversions that may wrap in signed/pointer type are folded, as long
2492 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2493 then we don't do such fold.
2495 SIZE_EXPR is used for computing the size of the expression to be
2496 instantiated, and to stop if it exceeds some limit. */
2498 static tree
2499 instantiate_scev_poly (edge instantiate_below,
2500 struct loop *evolution_loop, struct loop *,
2501 tree chrec, bool *fold_conversions, int size_expr)
2503 tree op1;
2504 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2505 get_chrec_loop (chrec),
2506 CHREC_LEFT (chrec), fold_conversions,
2507 size_expr);
2508 if (op0 == chrec_dont_know)
2509 return chrec_dont_know;
2511 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2512 get_chrec_loop (chrec),
2513 CHREC_RIGHT (chrec), fold_conversions,
2514 size_expr);
2515 if (op1 == chrec_dont_know)
2516 return chrec_dont_know;
2518 if (CHREC_LEFT (chrec) != op0
2519 || CHREC_RIGHT (chrec) != op1)
2521 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2522 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2525 return chrec;
2528 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2529 and EVOLUTION_LOOP, that were left under a symbolic form.
2531 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2533 CACHE is the cache of already instantiated values.
2535 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2536 conversions that may wrap in signed/pointer type are folded, as long
2537 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2538 then we don't do such fold.
2540 SIZE_EXPR is used for computing the size of the expression to be
2541 instantiated, and to stop if it exceeds some limit. */
2543 static tree
2544 instantiate_scev_binary (edge instantiate_below,
2545 struct loop *evolution_loop, struct loop *inner_loop,
2546 tree chrec, enum tree_code code,
2547 tree type, tree c0, tree c1,
2548 bool *fold_conversions, int size_expr)
2550 tree op1;
2551 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2552 c0, fold_conversions, size_expr);
2553 if (op0 == chrec_dont_know)
2554 return chrec_dont_know;
2556 op1 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2557 c1, fold_conversions, size_expr);
2558 if (op1 == chrec_dont_know)
2559 return chrec_dont_know;
2561 if (c0 != op0
2562 || c1 != op1)
2564 op0 = chrec_convert (type, op0, NULL);
2565 op1 = chrec_convert_rhs (type, op1, NULL);
2567 switch (code)
2569 case POINTER_PLUS_EXPR:
2570 case PLUS_EXPR:
2571 return chrec_fold_plus (type, op0, op1);
2573 case MINUS_EXPR:
2574 return chrec_fold_minus (type, op0, op1);
2576 case MULT_EXPR:
2577 return chrec_fold_multiply (type, op0, op1);
2579 default:
2580 gcc_unreachable ();
2584 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2587 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2588 and EVOLUTION_LOOP, that were left under a symbolic form.
2590 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2591 instantiated.
2593 CACHE is the cache of already instantiated values.
2595 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2596 conversions that may wrap in signed/pointer type are folded, as long
2597 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2598 then we don't do such fold.
2600 SIZE_EXPR is used for computing the size of the expression to be
2601 instantiated, and to stop if it exceeds some limit. */
2603 static tree
2604 instantiate_scev_convert (edge instantiate_below,
2605 struct loop *evolution_loop, struct loop *inner_loop,
2606 tree chrec, tree type, tree op,
2607 bool *fold_conversions, int size_expr)
2609 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2610 inner_loop, op,
2611 fold_conversions, size_expr);
2613 if (op0 == chrec_dont_know)
2614 return chrec_dont_know;
2616 if (fold_conversions)
2618 tree tmp = chrec_convert_aggressive (type, op0, fold_conversions);
2619 if (tmp)
2620 return tmp;
2622 /* If we used chrec_convert_aggressive, we can no longer assume that
2623 signed chrecs do not overflow, as chrec_convert does, so avoid
2624 calling it in that case. */
2625 if (*fold_conversions)
2627 if (chrec && op0 == op)
2628 return chrec;
2630 return fold_convert (type, op0);
2634 return chrec_convert (type, op0, NULL);
2637 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2638 and EVOLUTION_LOOP, that were left under a symbolic form.
2640 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2641 Handle ~X as -1 - X.
2642 Handle -X as -1 * X.
2644 CACHE is the cache of already instantiated values.
2646 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2647 conversions that may wrap in signed/pointer type are folded, as long
2648 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2649 then we don't do such fold.
2651 SIZE_EXPR is used for computing the size of the expression to be
2652 instantiated, and to stop if it exceeds some limit. */
2654 static tree
2655 instantiate_scev_not (edge instantiate_below,
2656 struct loop *evolution_loop, struct loop *inner_loop,
2657 tree chrec,
2658 enum tree_code code, tree type, tree op,
2659 bool *fold_conversions, int size_expr)
2661 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2662 inner_loop, op,
2663 fold_conversions, size_expr);
2665 if (op0 == chrec_dont_know)
2666 return chrec_dont_know;
2668 if (op != op0)
2670 op0 = chrec_convert (type, op0, NULL);
2672 switch (code)
2674 case BIT_NOT_EXPR:
2675 return chrec_fold_minus
2676 (type, fold_convert (type, integer_minus_one_node), op0);
2678 case NEGATE_EXPR:
2679 return chrec_fold_multiply
2680 (type, fold_convert (type, integer_minus_one_node), op0);
2682 default:
2683 gcc_unreachable ();
2687 return chrec ? chrec : fold_build1 (code, type, op0);
2690 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2691 and EVOLUTION_LOOP, that were left under a symbolic form.
2693 CHREC is the scalar evolution to instantiate.
2695 CACHE is the cache of already instantiated values.
2697 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2698 conversions that may wrap in signed/pointer type are folded, as long
2699 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2700 then we don't do such fold.
2702 SIZE_EXPR is used for computing the size of the expression to be
2703 instantiated, and to stop if it exceeds some limit. */
2705 static tree
2706 instantiate_scev_r (edge instantiate_below,
2707 struct loop *evolution_loop, struct loop *inner_loop,
2708 tree chrec,
2709 bool *fold_conversions, int size_expr)
2711 /* Give up if the expression is larger than the MAX that we allow. */
2712 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2713 return chrec_dont_know;
2715 if (chrec == NULL_TREE
2716 || automatically_generated_chrec_p (chrec)
2717 || is_gimple_min_invariant (chrec))
2718 return chrec;
2720 switch (TREE_CODE (chrec))
2722 case SSA_NAME:
2723 return instantiate_scev_name (instantiate_below, evolution_loop,
2724 inner_loop, chrec,
2725 fold_conversions, size_expr);
2727 case POLYNOMIAL_CHREC:
2728 return instantiate_scev_poly (instantiate_below, evolution_loop,
2729 inner_loop, chrec,
2730 fold_conversions, size_expr);
2732 case POINTER_PLUS_EXPR:
2733 case PLUS_EXPR:
2734 case MINUS_EXPR:
2735 case MULT_EXPR:
2736 return instantiate_scev_binary (instantiate_below, evolution_loop,
2737 inner_loop, chrec,
2738 TREE_CODE (chrec), chrec_type (chrec),
2739 TREE_OPERAND (chrec, 0),
2740 TREE_OPERAND (chrec, 1),
2741 fold_conversions, size_expr);
2743 CASE_CONVERT:
2744 return instantiate_scev_convert (instantiate_below, evolution_loop,
2745 inner_loop, chrec,
2746 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2747 fold_conversions, size_expr);
2749 case NEGATE_EXPR:
2750 case BIT_NOT_EXPR:
2751 return instantiate_scev_not (instantiate_below, evolution_loop,
2752 inner_loop, chrec,
2753 TREE_CODE (chrec), TREE_TYPE (chrec),
2754 TREE_OPERAND (chrec, 0),
2755 fold_conversions, size_expr);
2757 case ADDR_EXPR:
2758 if (is_gimple_min_invariant (chrec))
2759 return chrec;
2760 /* Fallthru. */
2761 case SCEV_NOT_KNOWN:
2762 return chrec_dont_know;
2764 case SCEV_KNOWN:
2765 return chrec_known;
2767 default:
2768 if (CONSTANT_CLASS_P (chrec))
2769 return chrec;
2770 return chrec_dont_know;
2774 /* Analyze all the parameters of the chrec that were left under a
2775 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2776 recursive instantiation of parameters: a parameter is a variable
2777 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2778 a function parameter. */
2780 tree
2781 instantiate_scev (edge instantiate_below, struct loop *evolution_loop,
2782 tree chrec)
2784 tree res;
2786 if (dump_file && (dump_flags & TDF_SCEV))
2788 fprintf (dump_file, "(instantiate_scev \n");
2789 fprintf (dump_file, " (instantiate_below = %d -> %d)\n",
2790 instantiate_below->src->index, instantiate_below->dest->index);
2791 if (evolution_loop)
2792 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2793 fprintf (dump_file, " (chrec = ");
2794 print_generic_expr (dump_file, chrec);
2795 fprintf (dump_file, ")\n");
2798 bool destr = false;
2799 if (!global_cache)
2801 global_cache = new instantiate_cache_type;
2802 destr = true;
2805 res = instantiate_scev_r (instantiate_below, evolution_loop,
2806 NULL, chrec, NULL, 0);
2808 if (destr)
2810 delete global_cache;
2811 global_cache = NULL;
2814 if (dump_file && (dump_flags & TDF_SCEV))
2816 fprintf (dump_file, " (res = ");
2817 print_generic_expr (dump_file, res);
2818 fprintf (dump_file, "))\n");
2821 return res;
2824 /* Similar to instantiate_parameters, but does not introduce the
2825 evolutions in outer loops for LOOP invariants in CHREC, and does not
2826 care about causing overflows, as long as they do not affect value
2827 of an expression. */
2829 tree
2830 resolve_mixers (struct loop *loop, tree chrec, bool *folded_casts)
2832 bool destr = false;
2833 bool fold_conversions = false;
2834 if (!global_cache)
2836 global_cache = new instantiate_cache_type;
2837 destr = true;
2840 tree ret = instantiate_scev_r (loop_preheader_edge (loop), loop, NULL,
2841 chrec, &fold_conversions, 0);
2843 if (folded_casts && !*folded_casts)
2844 *folded_casts = fold_conversions;
2846 if (destr)
2848 delete global_cache;
2849 global_cache = NULL;
2852 return ret;
2855 /* Entry point for the analysis of the number of iterations pass.
2856 This function tries to safely approximate the number of iterations
2857 the loop will run. When this property is not decidable at compile
2858 time, the result is chrec_dont_know. Otherwise the result is a
2859 scalar or a symbolic parameter. When the number of iterations may
2860 be equal to zero and the property cannot be determined at compile
2861 time, the result is a COND_EXPR that represents in a symbolic form
2862 the conditions under which the number of iterations is not zero.
2864 Example of analysis: suppose that the loop has an exit condition:
2866 "if (b > 49) goto end_loop;"
2868 and that in a previous analysis we have determined that the
2869 variable 'b' has an evolution function:
2871 "EF = {23, +, 5}_2".
2873 When we evaluate the function at the point 5, i.e. the value of the
2874 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2875 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2876 the loop body has been executed 6 times. */
2878 tree
2879 number_of_latch_executions (struct loop *loop)
2881 edge exit;
2882 struct tree_niter_desc niter_desc;
2883 tree may_be_zero;
2884 tree res;
2886 /* Determine whether the number of iterations in loop has already
2887 been computed. */
2888 res = loop->nb_iterations;
2889 if (res)
2890 return res;
2892 may_be_zero = NULL_TREE;
2894 if (dump_file && (dump_flags & TDF_SCEV))
2895 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2897 res = chrec_dont_know;
2898 exit = single_exit (loop);
2900 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2902 may_be_zero = niter_desc.may_be_zero;
2903 res = niter_desc.niter;
2906 if (res == chrec_dont_know
2907 || !may_be_zero
2908 || integer_zerop (may_be_zero))
2910 else if (integer_nonzerop (may_be_zero))
2911 res = build_int_cst (TREE_TYPE (res), 0);
2913 else if (COMPARISON_CLASS_P (may_be_zero))
2914 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2915 build_int_cst (TREE_TYPE (res), 0), res);
2916 else
2917 res = chrec_dont_know;
2919 if (dump_file && (dump_flags & TDF_SCEV))
2921 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2922 print_generic_expr (dump_file, res);
2923 fprintf (dump_file, "))\n");
2926 loop->nb_iterations = res;
2927 return res;
2931 /* Counters for the stats. */
2933 struct chrec_stats
2935 unsigned nb_chrecs;
2936 unsigned nb_affine;
2937 unsigned nb_affine_multivar;
2938 unsigned nb_higher_poly;
2939 unsigned nb_chrec_dont_know;
2940 unsigned nb_undetermined;
2943 /* Reset the counters. */
2945 static inline void
2946 reset_chrecs_counters (struct chrec_stats *stats)
2948 stats->nb_chrecs = 0;
2949 stats->nb_affine = 0;
2950 stats->nb_affine_multivar = 0;
2951 stats->nb_higher_poly = 0;
2952 stats->nb_chrec_dont_know = 0;
2953 stats->nb_undetermined = 0;
2956 /* Dump the contents of a CHREC_STATS structure. */
2958 static void
2959 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2961 fprintf (file, "\n(\n");
2962 fprintf (file, "-----------------------------------------\n");
2963 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2964 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2965 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2966 stats->nb_higher_poly);
2967 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2968 fprintf (file, "-----------------------------------------\n");
2969 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2970 fprintf (file, "%d\twith undetermined coefficients\n",
2971 stats->nb_undetermined);
2972 fprintf (file, "-----------------------------------------\n");
2973 fprintf (file, "%d\tchrecs in the scev database\n",
2974 (int) scalar_evolution_info->elements ());
2975 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2976 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2977 fprintf (file, "-----------------------------------------\n");
2978 fprintf (file, ")\n\n");
2981 /* Gather statistics about CHREC. */
2983 static void
2984 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2986 if (dump_file && (dump_flags & TDF_STATS))
2988 fprintf (dump_file, "(classify_chrec ");
2989 print_generic_expr (dump_file, chrec);
2990 fprintf (dump_file, "\n");
2993 stats->nb_chrecs++;
2995 if (chrec == NULL_TREE)
2997 stats->nb_undetermined++;
2998 return;
3001 switch (TREE_CODE (chrec))
3003 case POLYNOMIAL_CHREC:
3004 if (evolution_function_is_affine_p (chrec))
3006 if (dump_file && (dump_flags & TDF_STATS))
3007 fprintf (dump_file, " affine_univariate\n");
3008 stats->nb_affine++;
3010 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
3012 if (dump_file && (dump_flags & TDF_STATS))
3013 fprintf (dump_file, " affine_multivariate\n");
3014 stats->nb_affine_multivar++;
3016 else
3018 if (dump_file && (dump_flags & TDF_STATS))
3019 fprintf (dump_file, " higher_degree_polynomial\n");
3020 stats->nb_higher_poly++;
3023 break;
3025 default:
3026 break;
3029 if (chrec_contains_undetermined (chrec))
3031 if (dump_file && (dump_flags & TDF_STATS))
3032 fprintf (dump_file, " undetermined\n");
3033 stats->nb_undetermined++;
3036 if (dump_file && (dump_flags & TDF_STATS))
3037 fprintf (dump_file, ")\n");
3040 /* Classify the chrecs of the whole database. */
3042 void
3043 gather_stats_on_scev_database (void)
3045 struct chrec_stats stats;
3047 if (!dump_file)
3048 return;
3050 reset_chrecs_counters (&stats);
3052 hash_table<scev_info_hasher>::iterator iter;
3053 scev_info_str *elt;
3054 FOR_EACH_HASH_TABLE_ELEMENT (*scalar_evolution_info, elt, scev_info_str *,
3055 iter)
3056 gather_chrec_stats (elt->chrec, &stats);
3058 dump_chrecs_stats (dump_file, &stats);
3063 /* Initializer. */
3065 static void
3066 initialize_scalar_evolutions_analyzer (void)
3068 /* The elements below are unique. */
3069 if (chrec_dont_know == NULL_TREE)
3071 chrec_not_analyzed_yet = NULL_TREE;
3072 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3073 chrec_known = make_node (SCEV_KNOWN);
3074 TREE_TYPE (chrec_dont_know) = void_type_node;
3075 TREE_TYPE (chrec_known) = void_type_node;
3079 /* Initialize the analysis of scalar evolutions for LOOPS. */
3081 void
3082 scev_initialize (void)
3084 struct loop *loop;
3086 gcc_assert (! scev_initialized_p ());
3088 scalar_evolution_info = hash_table<scev_info_hasher>::create_ggc (100);
3090 initialize_scalar_evolutions_analyzer ();
3092 FOR_EACH_LOOP (loop, 0)
3094 loop->nb_iterations = NULL_TREE;
3098 /* Return true if SCEV is initialized. */
3100 bool
3101 scev_initialized_p (void)
3103 return scalar_evolution_info != NULL;
3106 /* Cleans up the information cached by the scalar evolutions analysis
3107 in the hash table. */
3109 void
3110 scev_reset_htab (void)
3112 if (!scalar_evolution_info)
3113 return;
3115 scalar_evolution_info->empty ();
3118 /* Cleans up the information cached by the scalar evolutions analysis
3119 in the hash table and in the loop->nb_iterations. */
3121 void
3122 scev_reset (void)
3124 struct loop *loop;
3126 scev_reset_htab ();
3128 FOR_EACH_LOOP (loop, 0)
3130 loop->nb_iterations = NULL_TREE;
3134 /* Return true if the IV calculation in TYPE can overflow based on the knowledge
3135 of the upper bound on the number of iterations of LOOP, the BASE and STEP
3136 of IV.
3138 We do not use information whether TYPE can overflow so it is safe to
3139 use this test even for derived IVs not computed every iteration or
3140 hypotetical IVs to be inserted into code. */
3142 bool
3143 iv_can_overflow_p (struct loop *loop, tree type, tree base, tree step)
3145 widest_int nit;
3146 wide_int base_min, base_max, step_min, step_max, type_min, type_max;
3147 signop sgn = TYPE_SIGN (type);
3149 if (integer_zerop (step))
3150 return false;
3152 if (TREE_CODE (base) == INTEGER_CST)
3153 base_min = base_max = wi::to_wide (base);
3154 else if (TREE_CODE (base) == SSA_NAME
3155 && INTEGRAL_TYPE_P (TREE_TYPE (base))
3156 && get_range_info (base, &base_min, &base_max) == VR_RANGE)
3158 else
3159 return true;
3161 if (TREE_CODE (step) == INTEGER_CST)
3162 step_min = step_max = wi::to_wide (step);
3163 else if (TREE_CODE (step) == SSA_NAME
3164 && INTEGRAL_TYPE_P (TREE_TYPE (step))
3165 && get_range_info (step, &step_min, &step_max) == VR_RANGE)
3167 else
3168 return true;
3170 if (!get_max_loop_iterations (loop, &nit))
3171 return true;
3173 type_min = wi::min_value (type);
3174 type_max = wi::max_value (type);
3176 /* Just sanity check that we don't see values out of the range of the type.
3177 In this case the arithmetics bellow would overflow. */
3178 gcc_checking_assert (wi::ge_p (base_min, type_min, sgn)
3179 && wi::le_p (base_max, type_max, sgn));
3181 /* Account the possible increment in the last ieration. */
3182 bool overflow = false;
3183 nit = wi::add (nit, 1, SIGNED, &overflow);
3184 if (overflow)
3185 return true;
3187 /* NIT is typeless and can exceed the precision of the type. In this case
3188 overflow is always possible, because we know STEP is non-zero. */
3189 if (wi::min_precision (nit, UNSIGNED) > TYPE_PRECISION (type))
3190 return true;
3191 wide_int nit2 = wide_int::from (nit, TYPE_PRECISION (type), UNSIGNED);
3193 /* If step can be positive, check that nit*step <= type_max-base.
3194 This can be done by unsigned arithmetic and we only need to watch overflow
3195 in the multiplication. The right hand side can always be represented in
3196 the type. */
3197 if (sgn == UNSIGNED || !wi::neg_p (step_max))
3199 bool overflow = false;
3200 if (wi::gtu_p (wi::mul (step_max, nit2, UNSIGNED, &overflow),
3201 type_max - base_max)
3202 || overflow)
3203 return true;
3205 /* If step can be negative, check that nit*(-step) <= base_min-type_min. */
3206 if (sgn == SIGNED && wi::neg_p (step_min))
3208 bool overflow = false, overflow2 = false;
3209 if (wi::gtu_p (wi::mul (wi::neg (step_min, &overflow2),
3210 nit2, UNSIGNED, &overflow),
3211 base_min - type_min)
3212 || overflow || overflow2)
3213 return true;
3216 return false;
3219 /* Given EV with form of "(type) {inner_base, inner_step}_loop", this
3220 function tries to derive condition under which it can be simplified
3221 into "{(type)inner_base, (type)inner_step}_loop". The condition is
3222 the maximum number that inner iv can iterate. */
3224 static tree
3225 derive_simple_iv_with_niters (tree ev, tree *niters)
3227 if (!CONVERT_EXPR_P (ev))
3228 return ev;
3230 tree inner_ev = TREE_OPERAND (ev, 0);
3231 if (TREE_CODE (inner_ev) != POLYNOMIAL_CHREC)
3232 return ev;
3234 tree init = CHREC_LEFT (inner_ev);
3235 tree step = CHREC_RIGHT (inner_ev);
3236 if (TREE_CODE (init) != INTEGER_CST
3237 || TREE_CODE (step) != INTEGER_CST || integer_zerop (step))
3238 return ev;
3240 tree type = TREE_TYPE (ev);
3241 tree inner_type = TREE_TYPE (inner_ev);
3242 if (TYPE_PRECISION (inner_type) >= TYPE_PRECISION (type))
3243 return ev;
3245 /* Type conversion in "(type) {inner_base, inner_step}_loop" can be
3246 folded only if inner iv won't overflow. We compute the maximum
3247 number the inner iv can iterate before overflowing and return the
3248 simplified affine iv. */
3249 tree delta;
3250 init = fold_convert (type, init);
3251 step = fold_convert (type, step);
3252 ev = build_polynomial_chrec (CHREC_VARIABLE (inner_ev), init, step);
3253 if (tree_int_cst_sign_bit (step))
3255 tree bound = lower_bound_in_type (inner_type, inner_type);
3256 delta = fold_build2 (MINUS_EXPR, type, init, fold_convert (type, bound));
3257 step = fold_build1 (NEGATE_EXPR, type, step);
3259 else
3261 tree bound = upper_bound_in_type (inner_type, inner_type);
3262 delta = fold_build2 (MINUS_EXPR, type, fold_convert (type, bound), init);
3264 *niters = fold_build2 (FLOOR_DIV_EXPR, type, delta, step);
3265 return ev;
3268 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3269 respect to WRTO_LOOP and returns its base and step in IV if possible
3270 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3271 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3272 invariant in LOOP. Otherwise we require it to be an integer constant.
3274 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3275 because it is computed in signed arithmetics). Consequently, adding an
3276 induction variable
3278 for (i = IV->base; ; i += IV->step)
3280 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3281 false for the type of the induction variable, or you can prove that i does
3282 not wrap by some other argument. Otherwise, this might introduce undefined
3283 behavior, and
3285 i = iv->base;
3286 for (; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3288 must be used instead.
3290 When IV_NITERS is not NULL, this function also checks case in which OP
3291 is a conversion of an inner simple iv of below form:
3293 (outer_type){inner_base, inner_step}_loop.
3295 If type of inner iv has smaller precision than outer_type, it can't be
3296 folded into {(outer_type)inner_base, (outer_type)inner_step}_loop because
3297 the inner iv could overflow/wrap. In this case, we derive a condition
3298 under which the inner iv won't overflow/wrap and do the simplification.
3299 The derived condition normally is the maximum number the inner iv can
3300 iterate, and will be stored in IV_NITERS. This is useful in loop niter
3301 analysis, to derive break conditions when a loop must terminate, when is
3302 infinite. */
3304 bool
3305 simple_iv_with_niters (struct loop *wrto_loop, struct loop *use_loop,
3306 tree op, affine_iv *iv, tree *iv_niters,
3307 bool allow_nonconstant_step)
3309 enum tree_code code;
3310 tree type, ev, base, e;
3311 wide_int extreme;
3312 bool folded_casts, overflow;
3314 iv->base = NULL_TREE;
3315 iv->step = NULL_TREE;
3316 iv->no_overflow = false;
3318 type = TREE_TYPE (op);
3319 if (!POINTER_TYPE_P (type)
3320 && !INTEGRAL_TYPE_P (type))
3321 return false;
3323 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3324 &folded_casts);
3325 if (chrec_contains_undetermined (ev)
3326 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3327 return false;
3329 if (tree_does_not_contain_chrecs (ev))
3331 iv->base = ev;
3332 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3333 iv->no_overflow = true;
3334 return true;
3337 /* If we can derive valid scalar evolution with assumptions. */
3338 if (iv_niters && TREE_CODE (ev) != POLYNOMIAL_CHREC)
3339 ev = derive_simple_iv_with_niters (ev, iv_niters);
3341 if (TREE_CODE (ev) != POLYNOMIAL_CHREC)
3342 return false;
3344 if (CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3345 return false;
3347 iv->step = CHREC_RIGHT (ev);
3348 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3349 || tree_contains_chrecs (iv->step, NULL))
3350 return false;
3352 iv->base = CHREC_LEFT (ev);
3353 if (tree_contains_chrecs (iv->base, NULL))
3354 return false;
3356 iv->no_overflow = !folded_casts && nowrap_type_p (type);
3358 if (!iv->no_overflow
3359 && !iv_can_overflow_p (wrto_loop, type, iv->base, iv->step))
3360 iv->no_overflow = true;
3362 /* Try to simplify iv base:
3364 (signed T) ((unsigned T)base + step) ;; TREE_TYPE (base) == signed T
3365 == (signed T)(unsigned T)base + step
3366 == base + step
3368 If we can prove operation (base + step) doesn't overflow or underflow.
3369 Specifically, we try to prove below conditions are satisfied:
3371 base <= UPPER_BOUND (type) - step ;;step > 0
3372 base >= LOWER_BOUND (type) - step ;;step < 0
3374 This is done by proving the reverse conditions are false using loop's
3375 initial conditions.
3377 The is necessary to make loop niter, or iv overflow analysis easier
3378 for below example:
3380 int foo (int *a, signed char s, signed char l)
3382 signed char i;
3383 for (i = s; i < l; i++)
3384 a[i] = 0;
3385 return 0;
3388 Note variable I is firstly converted to type unsigned char, incremented,
3389 then converted back to type signed char. */
3391 if (wrto_loop->num != use_loop->num)
3392 return true;
3394 if (!CONVERT_EXPR_P (iv->base) || TREE_CODE (iv->step) != INTEGER_CST)
3395 return true;
3397 type = TREE_TYPE (iv->base);
3398 e = TREE_OPERAND (iv->base, 0);
3399 if (TREE_CODE (e) != PLUS_EXPR
3400 || TREE_CODE (TREE_OPERAND (e, 1)) != INTEGER_CST
3401 || !tree_int_cst_equal (iv->step,
3402 fold_convert (type, TREE_OPERAND (e, 1))))
3403 return true;
3404 e = TREE_OPERAND (e, 0);
3405 if (!CONVERT_EXPR_P (e))
3406 return true;
3407 base = TREE_OPERAND (e, 0);
3408 if (!useless_type_conversion_p (type, TREE_TYPE (base)))
3409 return true;
3411 if (tree_int_cst_sign_bit (iv->step))
3413 code = LT_EXPR;
3414 extreme = wi::min_value (type);
3416 else
3418 code = GT_EXPR;
3419 extreme = wi::max_value (type);
3421 overflow = false;
3422 extreme = wi::sub (extreme, wi::to_wide (iv->step),
3423 TYPE_SIGN (type), &overflow);
3424 if (overflow)
3425 return true;
3426 e = fold_build2 (code, boolean_type_node, base,
3427 wide_int_to_tree (type, extreme));
3428 e = simplify_using_initial_conditions (use_loop, e);
3429 if (!integer_zerop (e))
3430 return true;
3432 if (POINTER_TYPE_P (TREE_TYPE (base)))
3433 code = POINTER_PLUS_EXPR;
3434 else
3435 code = PLUS_EXPR;
3437 iv->base = fold_build2 (code, TREE_TYPE (base), base, iv->step);
3438 return true;
3441 /* Like simple_iv_with_niters, but return TRUE when OP behaves as a simple
3442 affine iv unconditionally. */
3444 bool
3445 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3446 affine_iv *iv, bool allow_nonconstant_step)
3448 return simple_iv_with_niters (wrto_loop, use_loop, op, iv,
3449 NULL, allow_nonconstant_step);
3452 /* Finalize the scalar evolution analysis. */
3454 void
3455 scev_finalize (void)
3457 if (!scalar_evolution_info)
3458 return;
3459 scalar_evolution_info->empty ();
3460 scalar_evolution_info = NULL;
3461 free_numbers_of_iterations_estimates (cfun);
3464 /* Returns true if the expression EXPR is considered to be too expensive
3465 for scev_const_prop. */
3467 bool
3468 expression_expensive_p (tree expr)
3470 enum tree_code code;
3472 if (is_gimple_val (expr))
3473 return false;
3475 code = TREE_CODE (expr);
3476 if (code == TRUNC_DIV_EXPR
3477 || code == CEIL_DIV_EXPR
3478 || code == FLOOR_DIV_EXPR
3479 || code == ROUND_DIV_EXPR
3480 || code == TRUNC_MOD_EXPR
3481 || code == CEIL_MOD_EXPR
3482 || code == FLOOR_MOD_EXPR
3483 || code == ROUND_MOD_EXPR
3484 || code == EXACT_DIV_EXPR)
3486 /* Division by power of two is usually cheap, so we allow it.
3487 Forbid anything else. */
3488 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3489 return true;
3492 switch (TREE_CODE_CLASS (code))
3494 case tcc_binary:
3495 case tcc_comparison:
3496 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3497 return true;
3499 /* Fallthru. */
3500 case tcc_unary:
3501 return expression_expensive_p (TREE_OPERAND (expr, 0));
3503 default:
3504 return true;
3508 /* Do final value replacement for LOOP. */
3510 void
3511 final_value_replacement_loop (struct loop *loop)
3513 /* If we do not know exact number of iterations of the loop, we cannot
3514 replace the final value. */
3515 edge exit = single_exit (loop);
3516 if (!exit)
3517 return;
3519 tree niter = number_of_latch_executions (loop);
3520 if (niter == chrec_dont_know)
3521 return;
3523 /* Ensure that it is possible to insert new statements somewhere. */
3524 if (!single_pred_p (exit->dest))
3525 split_loop_exit_edge (exit);
3527 /* Set stmt insertion pointer. All stmts are inserted before this point. */
3528 gimple_stmt_iterator gsi = gsi_after_labels (exit->dest);
3530 struct loop *ex_loop
3531 = superloop_at_depth (loop,
3532 loop_depth (exit->dest->loop_father) + 1);
3534 gphi_iterator psi;
3535 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3537 gphi *phi = psi.phi ();
3538 tree rslt = PHI_RESULT (phi);
3539 tree def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3540 if (virtual_operand_p (def))
3542 gsi_next (&psi);
3543 continue;
3546 if (!POINTER_TYPE_P (TREE_TYPE (def))
3547 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3549 gsi_next (&psi);
3550 continue;
3553 bool folded_casts;
3554 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def,
3555 &folded_casts);
3556 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3557 if (!tree_does_not_contain_chrecs (def)
3558 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3559 /* Moving the computation from the loop may prolong life range
3560 of some ssa names, which may cause problems if they appear
3561 on abnormal edges. */
3562 || contains_abnormal_ssa_name_p (def)
3563 /* Do not emit expensive expressions. The rationale is that
3564 when someone writes a code like
3566 while (n > 45) n -= 45;
3568 he probably knows that n is not large, and does not want it
3569 to be turned into n %= 45. */
3570 || expression_expensive_p (def))
3572 if (dump_file && (dump_flags & TDF_DETAILS))
3574 fprintf (dump_file, "not replacing:\n ");
3575 print_gimple_stmt (dump_file, phi, 0);
3576 fprintf (dump_file, "\n");
3578 gsi_next (&psi);
3579 continue;
3582 /* Eliminate the PHI node and replace it by a computation outside
3583 the loop. */
3584 if (dump_file)
3586 fprintf (dump_file, "\nfinal value replacement:\n ");
3587 print_gimple_stmt (dump_file, phi, 0);
3588 fprintf (dump_file, " with\n ");
3590 def = unshare_expr (def);
3591 remove_phi_node (&psi, false);
3593 /* If def's type has undefined overflow and there were folded
3594 casts, rewrite all stmts added for def into arithmetics
3595 with defined overflow behavior. */
3596 if (folded_casts && ANY_INTEGRAL_TYPE_P (TREE_TYPE (def))
3597 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (def)))
3599 gimple_seq stmts;
3600 gimple_stmt_iterator gsi2;
3601 def = force_gimple_operand (def, &stmts, true, NULL_TREE);
3602 gsi2 = gsi_start (stmts);
3603 while (!gsi_end_p (gsi2))
3605 gimple *stmt = gsi_stmt (gsi2);
3606 gimple_stmt_iterator gsi3 = gsi2;
3607 gsi_next (&gsi2);
3608 gsi_remove (&gsi3, false);
3609 if (is_gimple_assign (stmt)
3610 && arith_code_with_undefined_signed_overflow
3611 (gimple_assign_rhs_code (stmt)))
3612 gsi_insert_seq_before (&gsi,
3613 rewrite_to_defined_overflow (stmt),
3614 GSI_SAME_STMT);
3615 else
3616 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
3619 else
3620 def = force_gimple_operand_gsi (&gsi, def, false, NULL_TREE,
3621 true, GSI_SAME_STMT);
3623 gassign *ass = gimple_build_assign (rslt, def);
3624 gsi_insert_before (&gsi, ass, GSI_SAME_STMT);
3625 if (dump_file)
3627 print_gimple_stmt (dump_file, ass, 0);
3628 fprintf (dump_file, "\n");
3633 /* Replace ssa names for that scev can prove they are constant by the
3634 appropriate constants. Also perform final value replacement in loops,
3635 in case the replacement expressions are cheap.
3637 We only consider SSA names defined by phi nodes; rest is left to the
3638 ordinary constant propagation pass. */
3640 unsigned int
3641 scev_const_prop (void)
3643 basic_block bb;
3644 tree name, type, ev;
3645 gphi *phi;
3646 struct loop *loop;
3647 bitmap ssa_names_to_remove = NULL;
3648 unsigned i;
3649 gphi_iterator psi;
3651 if (number_of_loops (cfun) <= 1)
3652 return 0;
3654 FOR_EACH_BB_FN (bb, cfun)
3656 loop = bb->loop_father;
3658 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3660 phi = psi.phi ();
3661 name = PHI_RESULT (phi);
3663 if (virtual_operand_p (name))
3664 continue;
3666 type = TREE_TYPE (name);
3668 if (!POINTER_TYPE_P (type)
3669 && !INTEGRAL_TYPE_P (type))
3670 continue;
3672 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name),
3673 NULL);
3674 if (!is_gimple_min_invariant (ev)
3675 || !may_propagate_copy (name, ev))
3676 continue;
3678 /* Replace the uses of the name. */
3679 if (name != ev)
3681 if (dump_file && (dump_flags & TDF_DETAILS))
3683 fprintf (dump_file, "Replacing uses of: ");
3684 print_generic_expr (dump_file, name);
3685 fprintf (dump_file, " with: ");
3686 print_generic_expr (dump_file, ev);
3687 fprintf (dump_file, "\n");
3689 replace_uses_by (name, ev);
3692 if (!ssa_names_to_remove)
3693 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3694 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3698 /* Remove the ssa names that were replaced by constants. We do not
3699 remove them directly in the previous cycle, since this
3700 invalidates scev cache. */
3701 if (ssa_names_to_remove)
3703 bitmap_iterator bi;
3705 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3707 gimple_stmt_iterator psi;
3708 name = ssa_name (i);
3709 phi = as_a <gphi *> (SSA_NAME_DEF_STMT (name));
3711 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3712 psi = gsi_for_stmt (phi);
3713 remove_phi_node (&psi, true);
3716 BITMAP_FREE (ssa_names_to_remove);
3717 scev_reset ();
3720 /* Now the regular final value replacement. */
3721 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
3722 final_value_replacement_loop (loop);
3724 return 0;
3727 #include "gt-tree-scalar-evolution.h"