Update various expressions within tree-scalar-evolution.c to be gimple_phi
[official-gcc.git] / gcc / tree-scalar-evolution.c
blob7ffa2419c02a66aa0df108f113b5036b14df12e9
1 /* Scalar evolution detector.
2 Copyright (C) 2003-2014 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 "tree.h"
260 #include "expr.h"
261 #include "gimple-pretty-print.h"
262 #include "basic-block.h"
263 #include "tree-ssa-alias.h"
264 #include "internal-fn.h"
265 #include "gimple-expr.h"
266 #include "is-a.h"
267 #include "gimple.h"
268 #include "gimplify.h"
269 #include "gimple-iterator.h"
270 #include "gimplify-me.h"
271 #include "gimple-ssa.h"
272 #include "tree-cfg.h"
273 #include "tree-phinodes.h"
274 #include "stringpool.h"
275 #include "tree-ssanames.h"
276 #include "tree-ssa-loop-ivopts.h"
277 #include "tree-ssa-loop-manip.h"
278 #include "tree-ssa-loop-niter.h"
279 #include "tree-ssa-loop.h"
280 #include "tree-ssa.h"
281 #include "cfgloop.h"
282 #include "tree-chrec.h"
283 #include "tree-affine.h"
284 #include "tree-scalar-evolution.h"
285 #include "dumpfile.h"
286 #include "params.h"
287 #include "tree-ssa-propagate.h"
288 #include "gimple-fold.h"
289 #include "gimplify-me.h"
291 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
292 static tree analyze_scalar_evolution_for_address_of (struct loop *loop,
293 tree var);
295 /* The cached information about an SSA name with version NAME_VERSION,
296 claiming that below basic block with index INSTANTIATED_BELOW, the
297 value of the SSA name can be expressed as CHREC. */
299 struct GTY(()) scev_info_str {
300 unsigned int name_version;
301 int instantiated_below;
302 tree chrec;
305 /* Counters for the scev database. */
306 static unsigned nb_set_scev = 0;
307 static unsigned nb_get_scev = 0;
309 /* The following trees are unique elements. Thus the comparison of
310 another element to these elements should be done on the pointer to
311 these trees, and not on their value. */
313 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
314 tree chrec_not_analyzed_yet;
316 /* Reserved to the cases where the analyzer has detected an
317 undecidable property at compile time. */
318 tree chrec_dont_know;
320 /* When the analyzer has detected that a property will never
321 happen, then it qualifies it with chrec_known. */
322 tree chrec_known;
324 static GTY ((param_is (struct scev_info_str))) htab_t scalar_evolution_info;
327 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
329 static inline struct scev_info_str *
330 new_scev_info_str (basic_block instantiated_below, tree var)
332 struct scev_info_str *res;
334 res = ggc_alloc<scev_info_str> ();
335 res->name_version = SSA_NAME_VERSION (var);
336 res->chrec = chrec_not_analyzed_yet;
337 res->instantiated_below = instantiated_below->index;
339 return res;
342 /* Computes a hash function for database element ELT. */
344 static inline hashval_t
345 hash_scev_info (const void *elt_)
347 const struct scev_info_str *elt = (const struct scev_info_str *) elt_;
348 return elt->name_version ^ elt->instantiated_below;
351 /* Compares database elements E1 and E2. */
353 static inline int
354 eq_scev_info (const void *e1, const void *e2)
356 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
357 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
359 return (elt1->name_version == elt2->name_version
360 && elt1->instantiated_below == elt2->instantiated_below);
363 /* Deletes database element E. */
365 static void
366 del_scev_info (void *e)
368 ggc_free (e);
372 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
373 A first query on VAR returns chrec_not_analyzed_yet. */
375 static tree *
376 find_var_scev_info (basic_block instantiated_below, tree var)
378 struct scev_info_str *res;
379 struct scev_info_str tmp;
380 PTR *slot;
382 tmp.name_version = SSA_NAME_VERSION (var);
383 tmp.instantiated_below = instantiated_below->index;
384 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
386 if (!*slot)
387 *slot = new_scev_info_str (instantiated_below, var);
388 res = (struct scev_info_str *) *slot;
390 return &res->chrec;
393 /* Return true when CHREC contains symbolic names defined in
394 LOOP_NB. */
396 bool
397 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
399 int i, n;
401 if (chrec == NULL_TREE)
402 return false;
404 if (is_gimple_min_invariant (chrec))
405 return false;
407 if (TREE_CODE (chrec) == SSA_NAME)
409 gimple def;
410 loop_p def_loop, loop;
412 if (SSA_NAME_IS_DEFAULT_DEF (chrec))
413 return false;
415 def = SSA_NAME_DEF_STMT (chrec);
416 def_loop = loop_containing_stmt (def);
417 loop = get_loop (cfun, loop_nb);
419 if (def_loop == NULL)
420 return false;
422 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
423 return true;
425 return false;
428 n = TREE_OPERAND_LENGTH (chrec);
429 for (i = 0; i < n; i++)
430 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
431 loop_nb))
432 return true;
433 return false;
436 /* Return true when PHI is a loop-phi-node. */
438 static bool
439 loop_phi_node_p (gimple phi)
441 /* The implementation of this function is based on the following
442 property: "all the loop-phi-nodes of a loop are contained in the
443 loop's header basic block". */
445 return loop_containing_stmt (phi)->header == gimple_bb (phi);
448 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
449 In general, in the case of multivariate evolutions we want to get
450 the evolution in different loops. LOOP specifies the level for
451 which to get the evolution.
453 Example:
455 | for (j = 0; j < 100; j++)
457 | for (k = 0; k < 100; k++)
459 | i = k + j; - Here the value of i is a function of j, k.
461 | ... = i - Here the value of i is a function of j.
463 | ... = i - Here the value of i is a scalar.
465 Example:
467 | i_0 = ...
468 | loop_1 10 times
469 | i_1 = phi (i_0, i_2)
470 | i_2 = i_1 + 2
471 | endloop
473 This loop has the same effect as:
474 LOOP_1 has the same effect as:
476 | i_1 = i_0 + 20
478 The overall effect of the loop, "i_0 + 20" in the previous example,
479 is obtained by passing in the parameters: LOOP = 1,
480 EVOLUTION_FN = {i_0, +, 2}_1.
483 tree
484 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
486 bool val = false;
488 if (evolution_fn == chrec_dont_know)
489 return chrec_dont_know;
491 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
493 struct loop *inner_loop = get_chrec_loop (evolution_fn);
495 if (inner_loop == loop
496 || flow_loop_nested_p (loop, inner_loop))
498 tree nb_iter = number_of_latch_executions (inner_loop);
500 if (nb_iter == chrec_dont_know)
501 return chrec_dont_know;
502 else
504 tree res;
506 /* evolution_fn is the evolution function in LOOP. Get
507 its value in the nb_iter-th iteration. */
508 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
510 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
511 res = instantiate_parameters (loop, res);
513 /* Continue the computation until ending on a parent of LOOP. */
514 return compute_overall_effect_of_inner_loop (loop, res);
517 else
518 return evolution_fn;
521 /* If the evolution function is an invariant, there is nothing to do. */
522 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
523 return evolution_fn;
525 else
526 return chrec_dont_know;
529 /* Associate CHREC to SCALAR. */
531 static void
532 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
534 tree *scalar_info;
536 if (TREE_CODE (scalar) != SSA_NAME)
537 return;
539 scalar_info = find_var_scev_info (instantiated_below, scalar);
541 if (dump_file)
543 if (dump_flags & TDF_SCEV)
545 fprintf (dump_file, "(set_scalar_evolution \n");
546 fprintf (dump_file, " instantiated_below = %d \n",
547 instantiated_below->index);
548 fprintf (dump_file, " (scalar = ");
549 print_generic_expr (dump_file, scalar, 0);
550 fprintf (dump_file, ")\n (scalar_evolution = ");
551 print_generic_expr (dump_file, chrec, 0);
552 fprintf (dump_file, "))\n");
554 if (dump_flags & TDF_STATS)
555 nb_set_scev++;
558 *scalar_info = chrec;
561 /* Retrieve the chrec associated to SCALAR instantiated below
562 INSTANTIATED_BELOW block. */
564 static tree
565 get_scalar_evolution (basic_block instantiated_below, tree scalar)
567 tree res;
569 if (dump_file)
571 if (dump_flags & TDF_SCEV)
573 fprintf (dump_file, "(get_scalar_evolution \n");
574 fprintf (dump_file, " (scalar = ");
575 print_generic_expr (dump_file, scalar, 0);
576 fprintf (dump_file, ")\n");
578 if (dump_flags & TDF_STATS)
579 nb_get_scev++;
582 switch (TREE_CODE (scalar))
584 case SSA_NAME:
585 res = *find_var_scev_info (instantiated_below, scalar);
586 break;
588 case REAL_CST:
589 case FIXED_CST:
590 case INTEGER_CST:
591 res = scalar;
592 break;
594 default:
595 res = chrec_not_analyzed_yet;
596 break;
599 if (dump_file && (dump_flags & TDF_SCEV))
601 fprintf (dump_file, " (scalar_evolution = ");
602 print_generic_expr (dump_file, res, 0);
603 fprintf (dump_file, "))\n");
606 return res;
609 /* Helper function for add_to_evolution. Returns the evolution
610 function for an assignment of the form "a = b + c", where "a" and
611 "b" are on the strongly connected component. CHREC_BEFORE is the
612 information that we already have collected up to this point.
613 TO_ADD is the evolution of "c".
615 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
616 evolution the expression TO_ADD, otherwise construct an evolution
617 part for this loop. */
619 static tree
620 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
621 gimple at_stmt)
623 tree type, left, right;
624 struct loop *loop = get_loop (cfun, loop_nb), *chloop;
626 switch (TREE_CODE (chrec_before))
628 case POLYNOMIAL_CHREC:
629 chloop = get_chrec_loop (chrec_before);
630 if (chloop == loop
631 || flow_loop_nested_p (chloop, loop))
633 unsigned var;
635 type = chrec_type (chrec_before);
637 /* When there is no evolution part in this loop, build it. */
638 if (chloop != loop)
640 var = loop_nb;
641 left = chrec_before;
642 right = SCALAR_FLOAT_TYPE_P (type)
643 ? build_real (type, dconst0)
644 : build_int_cst (type, 0);
646 else
648 var = CHREC_VARIABLE (chrec_before);
649 left = CHREC_LEFT (chrec_before);
650 right = CHREC_RIGHT (chrec_before);
653 to_add = chrec_convert (type, to_add, at_stmt);
654 right = chrec_convert_rhs (type, right, at_stmt);
655 right = chrec_fold_plus (chrec_type (right), right, to_add);
656 return build_polynomial_chrec (var, left, right);
658 else
660 gcc_assert (flow_loop_nested_p (loop, chloop));
662 /* Search the evolution in LOOP_NB. */
663 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
664 to_add, at_stmt);
665 right = CHREC_RIGHT (chrec_before);
666 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
667 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
668 left, right);
671 default:
672 /* These nodes do not depend on a loop. */
673 if (chrec_before == chrec_dont_know)
674 return chrec_dont_know;
676 left = chrec_before;
677 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
678 return build_polynomial_chrec (loop_nb, left, right);
682 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
683 of LOOP_NB.
685 Description (provided for completeness, for those who read code in
686 a plane, and for my poor 62 bytes brain that would have forgotten
687 all this in the next two or three months):
689 The algorithm of translation of programs from the SSA representation
690 into the chrecs syntax is based on a pattern matching. After having
691 reconstructed the overall tree expression for a loop, there are only
692 two cases that can arise:
694 1. a = loop-phi (init, a + expr)
695 2. a = loop-phi (init, expr)
697 where EXPR is either a scalar constant with respect to the analyzed
698 loop (this is a degree 0 polynomial), or an expression containing
699 other loop-phi definitions (these are higher degree polynomials).
701 Examples:
704 | init = ...
705 | loop_1
706 | a = phi (init, a + 5)
707 | endloop
710 | inita = ...
711 | initb = ...
712 | loop_1
713 | a = phi (inita, 2 * b + 3)
714 | b = phi (initb, b + 1)
715 | endloop
717 For the first case, the semantics of the SSA representation is:
719 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
721 that is, there is a loop index "x" that determines the scalar value
722 of the variable during the loop execution. During the first
723 iteration, the value is that of the initial condition INIT, while
724 during the subsequent iterations, it is the sum of the initial
725 condition with the sum of all the values of EXPR from the initial
726 iteration to the before last considered iteration.
728 For the second case, the semantics of the SSA program is:
730 | a (x) = init, if x = 0;
731 | expr (x - 1), otherwise.
733 The second case corresponds to the PEELED_CHREC, whose syntax is
734 close to the syntax of a loop-phi-node:
736 | phi (init, expr) vs. (init, expr)_x
738 The proof of the translation algorithm for the first case is a
739 proof by structural induction based on the degree of EXPR.
741 Degree 0:
742 When EXPR is a constant with respect to the analyzed loop, or in
743 other words when EXPR is a polynomial of degree 0, the evolution of
744 the variable A in the loop is an affine function with an initial
745 condition INIT, and a step EXPR. In order to show this, we start
746 from the semantics of the SSA representation:
748 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
750 and since "expr (j)" is a constant with respect to "j",
752 f (x) = init + x * expr
754 Finally, based on the semantics of the pure sum chrecs, by
755 identification we get the corresponding chrecs syntax:
757 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
758 f (x) -> {init, +, expr}_x
760 Higher degree:
761 Suppose that EXPR is a polynomial of degree N with respect to the
762 analyzed loop_x for which we have already determined that it is
763 written under the chrecs syntax:
765 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
767 We start from the semantics of the SSA program:
769 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
771 | f (x) = init + \sum_{j = 0}^{x - 1}
772 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
774 | f (x) = init + \sum_{j = 0}^{x - 1}
775 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
777 | f (x) = init + \sum_{k = 0}^{n - 1}
778 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
780 | f (x) = init + \sum_{k = 0}^{n - 1}
781 | (b_k * \binom{x}{k + 1})
783 | f (x) = init + b_0 * \binom{x}{1} + ...
784 | + b_{n-1} * \binom{x}{n}
786 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
787 | + b_{n-1} * \binom{x}{n}
790 And finally from the definition of the chrecs syntax, we identify:
791 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
793 This shows the mechanism that stands behind the add_to_evolution
794 function. An important point is that the use of symbolic
795 parameters avoids the need of an analysis schedule.
797 Example:
799 | inita = ...
800 | initb = ...
801 | loop_1
802 | a = phi (inita, a + 2 + b)
803 | b = phi (initb, b + 1)
804 | endloop
806 When analyzing "a", the algorithm keeps "b" symbolically:
808 | a -> {inita, +, 2 + b}_1
810 Then, after instantiation, the analyzer ends on the evolution:
812 | a -> {inita, +, 2 + initb, +, 1}_1
816 static tree
817 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
818 tree to_add, gimple at_stmt)
820 tree type = chrec_type (to_add);
821 tree res = NULL_TREE;
823 if (to_add == NULL_TREE)
824 return chrec_before;
826 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
827 instantiated at this point. */
828 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
829 /* This should not happen. */
830 return chrec_dont_know;
832 if (dump_file && (dump_flags & TDF_SCEV))
834 fprintf (dump_file, "(add_to_evolution \n");
835 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
836 fprintf (dump_file, " (chrec_before = ");
837 print_generic_expr (dump_file, chrec_before, 0);
838 fprintf (dump_file, ")\n (to_add = ");
839 print_generic_expr (dump_file, to_add, 0);
840 fprintf (dump_file, ")\n");
843 if (code == MINUS_EXPR)
844 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
845 ? build_real (type, dconstm1)
846 : build_int_cst_type (type, -1));
848 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
850 if (dump_file && (dump_flags & TDF_SCEV))
852 fprintf (dump_file, " (res = ");
853 print_generic_expr (dump_file, res, 0);
854 fprintf (dump_file, "))\n");
857 return res;
862 /* This section selects the loops that will be good candidates for the
863 scalar evolution analysis. For the moment, greedily select all the
864 loop nests we could analyze. */
866 /* For a loop with a single exit edge, return the COND_EXPR that
867 guards the exit edge. If the expression is too difficult to
868 analyze, then give up. */
870 gimple
871 get_loop_exit_condition (const struct loop *loop)
873 gimple res = NULL;
874 edge exit_edge = single_exit (loop);
876 if (dump_file && (dump_flags & TDF_SCEV))
877 fprintf (dump_file, "(get_loop_exit_condition \n ");
879 if (exit_edge)
881 gimple stmt;
883 stmt = last_stmt (exit_edge->src);
884 if (gimple_code (stmt) == GIMPLE_COND)
885 res = stmt;
888 if (dump_file && (dump_flags & TDF_SCEV))
890 print_gimple_stmt (dump_file, res, 0, 0);
891 fprintf (dump_file, ")\n");
894 return res;
898 /* Depth first search algorithm. */
900 typedef enum t_bool {
901 t_false,
902 t_true,
903 t_dont_know
904 } t_bool;
907 static t_bool follow_ssa_edge (struct loop *loop, gimple, gimple_phi,
908 tree *, int);
910 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
911 Return true if the strongly connected component has been found. */
913 static t_bool
914 follow_ssa_edge_binary (struct loop *loop, gimple at_stmt,
915 tree type, tree rhs0, enum tree_code code, tree rhs1,
916 gimple_phi halting_phi, tree *evolution_of_loop,
917 int limit)
919 t_bool res = t_false;
920 tree evol;
922 switch (code)
924 case POINTER_PLUS_EXPR:
925 case PLUS_EXPR:
926 if (TREE_CODE (rhs0) == SSA_NAME)
928 if (TREE_CODE (rhs1) == SSA_NAME)
930 /* Match an assignment under the form:
931 "a = b + c". */
933 /* We want only assignments of form "name + name" contribute to
934 LIMIT, as the other cases do not necessarily contribute to
935 the complexity of the expression. */
936 limit++;
938 evol = *evolution_of_loop;
939 res = follow_ssa_edge
940 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
942 if (res == t_true)
943 *evolution_of_loop = add_to_evolution
944 (loop->num,
945 chrec_convert (type, evol, at_stmt),
946 code, rhs1, at_stmt);
948 else if (res == t_false)
950 res = follow_ssa_edge
951 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
952 evolution_of_loop, limit);
954 if (res == t_true)
955 *evolution_of_loop = add_to_evolution
956 (loop->num,
957 chrec_convert (type, *evolution_of_loop, at_stmt),
958 code, rhs0, at_stmt);
960 else if (res == t_dont_know)
961 *evolution_of_loop = chrec_dont_know;
964 else if (res == t_dont_know)
965 *evolution_of_loop = chrec_dont_know;
968 else
970 /* Match an assignment under the form:
971 "a = b + ...". */
972 res = follow_ssa_edge
973 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
974 evolution_of_loop, limit);
975 if (res == t_true)
976 *evolution_of_loop = add_to_evolution
977 (loop->num, chrec_convert (type, *evolution_of_loop,
978 at_stmt),
979 code, rhs1, at_stmt);
981 else if (res == t_dont_know)
982 *evolution_of_loop = chrec_dont_know;
986 else if (TREE_CODE (rhs1) == SSA_NAME)
988 /* Match an assignment under the form:
989 "a = ... + c". */
990 res = follow_ssa_edge
991 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
992 evolution_of_loop, limit);
993 if (res == t_true)
994 *evolution_of_loop = add_to_evolution
995 (loop->num, chrec_convert (type, *evolution_of_loop,
996 at_stmt),
997 code, rhs0, at_stmt);
999 else if (res == t_dont_know)
1000 *evolution_of_loop = chrec_dont_know;
1003 else
1004 /* Otherwise, match an assignment under the form:
1005 "a = ... + ...". */
1006 /* And there is nothing to do. */
1007 res = t_false;
1008 break;
1010 case MINUS_EXPR:
1011 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1012 if (TREE_CODE (rhs0) == SSA_NAME)
1014 /* Match an assignment under the form:
1015 "a = b - ...". */
1017 /* We want only assignments of form "name - name" contribute to
1018 LIMIT, as the other cases do not necessarily contribute to
1019 the complexity of the expression. */
1020 if (TREE_CODE (rhs1) == SSA_NAME)
1021 limit++;
1023 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1024 evolution_of_loop, limit);
1025 if (res == t_true)
1026 *evolution_of_loop = add_to_evolution
1027 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1028 MINUS_EXPR, rhs1, at_stmt);
1030 else if (res == t_dont_know)
1031 *evolution_of_loop = chrec_dont_know;
1033 else
1034 /* Otherwise, match an assignment under the form:
1035 "a = ... - ...". */
1036 /* And there is nothing to do. */
1037 res = t_false;
1038 break;
1040 default:
1041 res = t_false;
1044 return res;
1047 /* Follow the ssa edge into the expression EXPR.
1048 Return true if the strongly connected component has been found. */
1050 static t_bool
1051 follow_ssa_edge_expr (struct loop *loop, gimple at_stmt, tree expr,
1052 gimple_phi halting_phi, tree *evolution_of_loop,
1053 int limit)
1055 enum tree_code code = TREE_CODE (expr);
1056 tree type = TREE_TYPE (expr), rhs0, rhs1;
1057 t_bool res;
1059 /* The EXPR is one of the following cases:
1060 - an SSA_NAME,
1061 - an INTEGER_CST,
1062 - a PLUS_EXPR,
1063 - a POINTER_PLUS_EXPR,
1064 - a MINUS_EXPR,
1065 - an ASSERT_EXPR,
1066 - other cases are not yet handled. */
1068 switch (code)
1070 CASE_CONVERT:
1071 /* This assignment is under the form "a_1 = (cast) rhs. */
1072 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1073 halting_phi, evolution_of_loop, limit);
1074 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1075 break;
1077 case INTEGER_CST:
1078 /* This assignment is under the form "a_1 = 7". */
1079 res = t_false;
1080 break;
1082 case SSA_NAME:
1083 /* This assignment is under the form: "a_1 = b_2". */
1084 res = follow_ssa_edge
1085 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1086 break;
1088 case POINTER_PLUS_EXPR:
1089 case PLUS_EXPR:
1090 case MINUS_EXPR:
1091 /* This case is under the form "rhs0 +- rhs1". */
1092 rhs0 = TREE_OPERAND (expr, 0);
1093 rhs1 = TREE_OPERAND (expr, 1);
1094 type = TREE_TYPE (rhs0);
1095 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1096 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1097 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1098 halting_phi, evolution_of_loop, limit);
1099 break;
1101 case ADDR_EXPR:
1102 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1103 if (TREE_CODE (TREE_OPERAND (expr, 0)) == MEM_REF)
1105 expr = TREE_OPERAND (expr, 0);
1106 rhs0 = TREE_OPERAND (expr, 0);
1107 rhs1 = TREE_OPERAND (expr, 1);
1108 type = TREE_TYPE (rhs0);
1109 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1110 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1111 res = follow_ssa_edge_binary (loop, at_stmt, type,
1112 rhs0, POINTER_PLUS_EXPR, rhs1,
1113 halting_phi, evolution_of_loop, limit);
1115 else
1116 res = t_false;
1117 break;
1119 case ASSERT_EXPR:
1120 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1121 It must be handled as a copy assignment of the form a_1 = a_2. */
1122 rhs0 = ASSERT_EXPR_VAR (expr);
1123 if (TREE_CODE (rhs0) == SSA_NAME)
1124 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1125 halting_phi, evolution_of_loop, limit);
1126 else
1127 res = t_false;
1128 break;
1130 default:
1131 res = t_false;
1132 break;
1135 return res;
1138 /* Follow the ssa edge into the right hand side of an assignment STMT.
1139 Return true if the strongly connected component has been found. */
1141 static t_bool
1142 follow_ssa_edge_in_rhs (struct loop *loop, gimple stmt,
1143 gimple_phi halting_phi, tree *evolution_of_loop,
1144 int limit)
1146 enum tree_code code = gimple_assign_rhs_code (stmt);
1147 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1148 t_bool res;
1150 switch (code)
1152 CASE_CONVERT:
1153 /* This assignment is under the form "a_1 = (cast) rhs. */
1154 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1155 halting_phi, evolution_of_loop, limit);
1156 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1157 break;
1159 case POINTER_PLUS_EXPR:
1160 case PLUS_EXPR:
1161 case MINUS_EXPR:
1162 rhs1 = gimple_assign_rhs1 (stmt);
1163 rhs2 = gimple_assign_rhs2 (stmt);
1164 type = TREE_TYPE (rhs1);
1165 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1166 halting_phi, evolution_of_loop, limit);
1167 break;
1169 default:
1170 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1171 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1172 halting_phi, evolution_of_loop, limit);
1173 else
1174 res = t_false;
1175 break;
1178 return res;
1181 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1183 static bool
1184 backedge_phi_arg_p (gimple_phi phi, int i)
1186 const_edge e = gimple_phi_arg_edge (phi, i);
1188 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1189 about updating it anywhere, and this should work as well most of the
1190 time. */
1191 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1192 return true;
1194 return false;
1197 /* Helper function for one branch of the condition-phi-node. Return
1198 true if the strongly connected component has been found following
1199 this path. */
1201 static inline t_bool
1202 follow_ssa_edge_in_condition_phi_branch (int i,
1203 struct loop *loop,
1204 gimple_phi condition_phi,
1205 gimple_phi halting_phi,
1206 tree *evolution_of_branch,
1207 tree init_cond, int limit)
1209 tree branch = PHI_ARG_DEF (condition_phi, i);
1210 *evolution_of_branch = chrec_dont_know;
1212 /* Do not follow back edges (they must belong to an irreducible loop, which
1213 we really do not want to worry about). */
1214 if (backedge_phi_arg_p (condition_phi, i))
1215 return t_false;
1217 if (TREE_CODE (branch) == SSA_NAME)
1219 *evolution_of_branch = init_cond;
1220 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1221 evolution_of_branch, limit);
1224 /* This case occurs when one of the condition branches sets
1225 the variable to a constant: i.e. a phi-node like
1226 "a_2 = PHI <a_7(5), 2(6)>;".
1228 FIXME: This case have to be refined correctly:
1229 in some cases it is possible to say something better than
1230 chrec_dont_know, for example using a wrap-around notation. */
1231 return t_false;
1234 /* This function merges the branches of a condition-phi-node in a
1235 loop. */
1237 static t_bool
1238 follow_ssa_edge_in_condition_phi (struct loop *loop,
1239 gimple_phi condition_phi,
1240 gimple_phi halting_phi,
1241 tree *evolution_of_loop, int limit)
1243 int i, n;
1244 tree init = *evolution_of_loop;
1245 tree evolution_of_branch;
1246 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1247 halting_phi,
1248 &evolution_of_branch,
1249 init, limit);
1250 if (res == t_false || res == t_dont_know)
1251 return res;
1253 *evolution_of_loop = evolution_of_branch;
1255 n = gimple_phi_num_args (condition_phi);
1256 for (i = 1; i < n; i++)
1258 /* Quickly give up when the evolution of one of the branches is
1259 not known. */
1260 if (*evolution_of_loop == chrec_dont_know)
1261 return t_true;
1263 /* Increase the limit by the PHI argument number to avoid exponential
1264 time and memory complexity. */
1265 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1266 halting_phi,
1267 &evolution_of_branch,
1268 init, limit + i);
1269 if (res == t_false || res == t_dont_know)
1270 return res;
1272 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1273 evolution_of_branch);
1276 return t_true;
1279 /* Follow an SSA edge in an inner loop. It computes the overall
1280 effect of the loop, and following the symbolic initial conditions,
1281 it follows the edges in the parent loop. The inner loop is
1282 considered as a single statement. */
1284 static t_bool
1285 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1286 gimple_phi loop_phi_node,
1287 gimple_phi halting_phi,
1288 tree *evolution_of_loop, int limit)
1290 struct loop *loop = loop_containing_stmt (loop_phi_node);
1291 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1293 /* Sometimes, the inner loop is too difficult to analyze, and the
1294 result of the analysis is a symbolic parameter. */
1295 if (ev == PHI_RESULT (loop_phi_node))
1297 t_bool res = t_false;
1298 int i, n = gimple_phi_num_args (loop_phi_node);
1300 for (i = 0; i < n; i++)
1302 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1303 basic_block bb;
1305 /* Follow the edges that exit the inner loop. */
1306 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1307 if (!flow_bb_inside_loop_p (loop, bb))
1308 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1309 arg, halting_phi,
1310 evolution_of_loop, limit);
1311 if (res == t_true)
1312 break;
1315 /* If the path crosses this loop-phi, give up. */
1316 if (res == t_true)
1317 *evolution_of_loop = chrec_dont_know;
1319 return res;
1322 /* Otherwise, compute the overall effect of the inner loop. */
1323 ev = compute_overall_effect_of_inner_loop (loop, ev);
1324 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1325 evolution_of_loop, limit);
1328 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1329 path that is analyzed on the return walk. */
1331 static t_bool
1332 follow_ssa_edge (struct loop *loop, gimple def, gimple_phi halting_phi,
1333 tree *evolution_of_loop, int limit)
1335 struct loop *def_loop;
1337 if (gimple_nop_p (def))
1338 return t_false;
1340 /* Give up if the path is longer than the MAX that we allow. */
1341 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY))
1342 return t_dont_know;
1344 def_loop = loop_containing_stmt (def);
1346 switch (gimple_code (def))
1348 case GIMPLE_PHI:
1349 if (!loop_phi_node_p (def))
1350 /* DEF is a condition-phi-node. Follow the branches, and
1351 record their evolutions. Finally, merge the collected
1352 information and set the approximation to the main
1353 variable. */
1354 return follow_ssa_edge_in_condition_phi
1355 (loop, as_a <gimple_phi> (def), halting_phi, evolution_of_loop,
1356 limit);
1358 /* When the analyzed phi is the halting_phi, the
1359 depth-first search is over: we have found a path from
1360 the halting_phi to itself in the loop. */
1361 if (def == halting_phi)
1362 return t_true;
1364 /* Otherwise, the evolution of the HALTING_PHI depends
1365 on the evolution of another loop-phi-node, i.e. the
1366 evolution function is a higher degree polynomial. */
1367 if (def_loop == loop)
1368 return t_false;
1370 /* Inner loop. */
1371 if (flow_loop_nested_p (loop, def_loop))
1372 return follow_ssa_edge_inner_loop_phi
1373 (loop, as_a <gimple_phi> (def), halting_phi, evolution_of_loop,
1374 limit + 1);
1376 /* Outer loop. */
1377 return t_false;
1379 case GIMPLE_ASSIGN:
1380 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1381 evolution_of_loop, limit);
1383 default:
1384 /* At this level of abstraction, the program is just a set
1385 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1386 other node to be handled. */
1387 return t_false;
1392 /* Simplify PEELED_CHREC represented by (init_cond, arg) in LOOP.
1393 Handle below case and return the corresponding POLYNOMIAL_CHREC:
1395 # i_17 = PHI <i_13(5), 0(3)>
1396 # _20 = PHI <_5(5), start_4(D)(3)>
1398 i_13 = i_17 + 1;
1399 _5 = start_4(D) + i_13;
1401 Though variable _20 appears as a PEELED_CHREC in the form of
1402 (start_4, _5)_LOOP, it's a POLYNOMIAL_CHREC like {start_4, 1}_LOOP.
1404 See PR41488. */
1406 static tree
1407 simplify_peeled_chrec (struct loop *loop, tree arg, tree init_cond)
1409 aff_tree aff1, aff2;
1410 tree ev, left, right, type, step_val;
1411 hash_map<tree, name_expansion *> *peeled_chrec_map = NULL;
1413 ev = instantiate_parameters (loop, analyze_scalar_evolution (loop, arg));
1414 if (ev == NULL_TREE || TREE_CODE (ev) != POLYNOMIAL_CHREC)
1415 return chrec_dont_know;
1417 left = CHREC_LEFT (ev);
1418 right = CHREC_RIGHT (ev);
1419 type = TREE_TYPE (left);
1420 step_val = chrec_fold_plus (type, init_cond, right);
1422 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1423 if "left" equals to "init + right". */
1424 if (operand_equal_p (left, step_val, 0))
1426 if (dump_file && (dump_flags & TDF_SCEV))
1427 fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1429 return build_polynomial_chrec (loop->num, init_cond, right);
1432 /* Try harder to check if they are equal. */
1433 tree_to_aff_combination_expand (left, type, &aff1, &peeled_chrec_map);
1434 tree_to_aff_combination_expand (step_val, type, &aff2, &peeled_chrec_map);
1435 free_affine_expand_cache (&peeled_chrec_map);
1436 aff_combination_scale (&aff2, -1);
1437 aff_combination_add (&aff1, &aff2);
1439 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1440 if "left" equals to "init + right". */
1441 if (aff_combination_zero_p (&aff1))
1443 if (dump_file && (dump_flags & TDF_SCEV))
1444 fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1446 return build_polynomial_chrec (loop->num, init_cond, right);
1448 return chrec_dont_know;
1451 /* Given a LOOP_PHI_NODE, this function determines the evolution
1452 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1454 static tree
1455 analyze_evolution_in_loop (gimple_phi loop_phi_node,
1456 tree init_cond)
1458 int i, n = gimple_phi_num_args (loop_phi_node);
1459 tree evolution_function = chrec_not_analyzed_yet;
1460 struct loop *loop = loop_containing_stmt (loop_phi_node);
1461 basic_block bb;
1462 static bool simplify_peeled_chrec_p = true;
1464 if (dump_file && (dump_flags & TDF_SCEV))
1466 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1467 fprintf (dump_file, " (loop_phi_node = ");
1468 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1469 fprintf (dump_file, ")\n");
1472 for (i = 0; i < n; i++)
1474 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1475 gimple ssa_chain;
1476 tree ev_fn;
1477 t_bool res;
1479 /* Select the edges that enter the loop body. */
1480 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1481 if (!flow_bb_inside_loop_p (loop, bb))
1482 continue;
1484 if (TREE_CODE (arg) == SSA_NAME)
1486 bool val = false;
1488 ssa_chain = SSA_NAME_DEF_STMT (arg);
1490 /* Pass in the initial condition to the follow edge function. */
1491 ev_fn = init_cond;
1492 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1494 /* If ev_fn has no evolution in the inner loop, and the
1495 init_cond is not equal to ev_fn, then we have an
1496 ambiguity between two possible values, as we cannot know
1497 the number of iterations at this point. */
1498 if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1499 && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1500 && !operand_equal_p (init_cond, ev_fn, 0))
1501 ev_fn = chrec_dont_know;
1503 else
1504 res = t_false;
1506 /* When it is impossible to go back on the same
1507 loop_phi_node by following the ssa edges, the
1508 evolution is represented by a peeled chrec, i.e. the
1509 first iteration, EV_FN has the value INIT_COND, then
1510 all the other iterations it has the value of ARG.
1511 For the moment, PEELED_CHREC nodes are not built. */
1512 if (res != t_true)
1514 ev_fn = chrec_dont_know;
1515 /* Try to recognize POLYNOMIAL_CHREC which appears in
1516 the form of PEELED_CHREC, but guard the process with
1517 a bool variable to keep the analyzer from infinite
1518 recurrence for real PEELED_RECs. */
1519 if (simplify_peeled_chrec_p && TREE_CODE (arg) == SSA_NAME)
1521 simplify_peeled_chrec_p = false;
1522 ev_fn = simplify_peeled_chrec (loop, arg, init_cond);
1523 simplify_peeled_chrec_p = true;
1527 /* When there are multiple back edges of the loop (which in fact never
1528 happens currently, but nevertheless), merge their evolutions. */
1529 evolution_function = chrec_merge (evolution_function, ev_fn);
1532 if (dump_file && (dump_flags & TDF_SCEV))
1534 fprintf (dump_file, " (evolution_function = ");
1535 print_generic_expr (dump_file, evolution_function, 0);
1536 fprintf (dump_file, "))\n");
1539 return evolution_function;
1542 /* Given a loop-phi-node, return the initial conditions of the
1543 variable on entry of the loop. When the CCP has propagated
1544 constants into the loop-phi-node, the initial condition is
1545 instantiated, otherwise the initial condition is kept symbolic.
1546 This analyzer does not analyze the evolution outside the current
1547 loop, and leaves this task to the on-demand tree reconstructor. */
1549 static tree
1550 analyze_initial_condition (gimple_phi loop_phi_node)
1552 int i, n;
1553 tree init_cond = chrec_not_analyzed_yet;
1554 struct loop *loop = loop_containing_stmt (loop_phi_node);
1556 if (dump_file && (dump_flags & TDF_SCEV))
1558 fprintf (dump_file, "(analyze_initial_condition \n");
1559 fprintf (dump_file, " (loop_phi_node = \n");
1560 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1561 fprintf (dump_file, ")\n");
1564 n = gimple_phi_num_args (loop_phi_node);
1565 for (i = 0; i < n; i++)
1567 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1568 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1570 /* When the branch is oriented to the loop's body, it does
1571 not contribute to the initial condition. */
1572 if (flow_bb_inside_loop_p (loop, bb))
1573 continue;
1575 if (init_cond == chrec_not_analyzed_yet)
1577 init_cond = branch;
1578 continue;
1581 if (TREE_CODE (branch) == SSA_NAME)
1583 init_cond = chrec_dont_know;
1584 break;
1587 init_cond = chrec_merge (init_cond, branch);
1590 /* Ooops -- a loop without an entry??? */
1591 if (init_cond == chrec_not_analyzed_yet)
1592 init_cond = chrec_dont_know;
1594 /* During early loop unrolling we do not have fully constant propagated IL.
1595 Handle degenerate PHIs here to not miss important unrollings. */
1596 if (TREE_CODE (init_cond) == SSA_NAME)
1598 gimple def = SSA_NAME_DEF_STMT (init_cond);
1599 tree res;
1600 if (gimple_code (def) == GIMPLE_PHI
1601 && (res = degenerate_phi_result (def)) != NULL_TREE
1602 /* Only allow invariants here, otherwise we may break
1603 loop-closed SSA form. */
1604 && is_gimple_min_invariant (res))
1605 init_cond = res;
1608 if (dump_file && (dump_flags & TDF_SCEV))
1610 fprintf (dump_file, " (init_cond = ");
1611 print_generic_expr (dump_file, init_cond, 0);
1612 fprintf (dump_file, "))\n");
1615 return init_cond;
1618 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1620 static tree
1621 interpret_loop_phi (struct loop *loop, gimple_phi loop_phi_node)
1623 tree res;
1624 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1625 tree init_cond;
1627 if (phi_loop != loop)
1629 struct loop *subloop;
1630 tree evolution_fn = analyze_scalar_evolution
1631 (phi_loop, PHI_RESULT (loop_phi_node));
1633 /* Dive one level deeper. */
1634 subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1636 /* Interpret the subloop. */
1637 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1638 return res;
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, gimple_phi 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);
1691 return res;
1694 /* Interpret the operation RHS1 OP RHS2. If we didn't
1695 analyze this node before, follow the definitions until ending
1696 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1697 return path, this function propagates evolutions (ala constant copy
1698 propagation). OPND1 is not a GIMPLE expression because we could
1699 analyze the effect of an inner loop: see interpret_loop_phi. */
1701 static tree
1702 interpret_rhs_expr (struct loop *loop, gimple at_stmt,
1703 tree type, tree rhs1, enum tree_code code, tree rhs2)
1705 tree res, chrec1, chrec2;
1706 gimple def;
1708 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1710 if (is_gimple_min_invariant (rhs1))
1711 return chrec_convert (type, rhs1, at_stmt);
1713 if (code == SSA_NAME)
1714 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1715 at_stmt);
1717 if (code == ASSERT_EXPR)
1719 rhs1 = ASSERT_EXPR_VAR (rhs1);
1720 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1721 at_stmt);
1725 switch (code)
1727 case ADDR_EXPR:
1728 if (TREE_CODE (TREE_OPERAND (rhs1, 0)) == MEM_REF
1729 || handled_component_p (TREE_OPERAND (rhs1, 0)))
1731 enum machine_mode mode;
1732 HOST_WIDE_INT bitsize, bitpos;
1733 int unsignedp;
1734 int volatilep = 0;
1735 tree base, offset;
1736 tree chrec3;
1737 tree unitpos;
1739 base = get_inner_reference (TREE_OPERAND (rhs1, 0),
1740 &bitsize, &bitpos, &offset,
1741 &mode, &unsignedp, &volatilep, false);
1743 if (TREE_CODE (base) == MEM_REF)
1745 rhs2 = TREE_OPERAND (base, 1);
1746 rhs1 = TREE_OPERAND (base, 0);
1748 chrec1 = analyze_scalar_evolution (loop, rhs1);
1749 chrec2 = analyze_scalar_evolution (loop, rhs2);
1750 chrec1 = chrec_convert (type, chrec1, at_stmt);
1751 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1752 chrec1 = instantiate_parameters (loop, chrec1);
1753 chrec2 = instantiate_parameters (loop, chrec2);
1754 res = chrec_fold_plus (type, chrec1, chrec2);
1756 else
1758 chrec1 = analyze_scalar_evolution_for_address_of (loop, base);
1759 chrec1 = chrec_convert (type, chrec1, at_stmt);
1760 res = chrec1;
1763 if (offset != NULL_TREE)
1765 chrec2 = analyze_scalar_evolution (loop, offset);
1766 chrec2 = chrec_convert (TREE_TYPE (offset), chrec2, at_stmt);
1767 chrec2 = instantiate_parameters (loop, chrec2);
1768 res = chrec_fold_plus (type, res, chrec2);
1771 if (bitpos != 0)
1773 gcc_assert ((bitpos % BITS_PER_UNIT) == 0);
1775 unitpos = size_int (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 chrec1 = chrec_convert (type, chrec1, at_stmt);
1800 chrec2 = chrec_convert (type, chrec2, at_stmt);
1801 chrec1 = instantiate_parameters (loop, chrec1);
1802 chrec2 = instantiate_parameters (loop, chrec2);
1803 res = chrec_fold_plus (type, chrec1, chrec2);
1804 break;
1806 case MINUS_EXPR:
1807 chrec1 = analyze_scalar_evolution (loop, rhs1);
1808 chrec2 = analyze_scalar_evolution (loop, rhs2);
1809 chrec1 = chrec_convert (type, chrec1, at_stmt);
1810 chrec2 = chrec_convert (type, chrec2, at_stmt);
1811 chrec1 = instantiate_parameters (loop, chrec1);
1812 chrec2 = instantiate_parameters (loop, chrec2);
1813 res = chrec_fold_minus (type, chrec1, chrec2);
1814 break;
1816 case NEGATE_EXPR:
1817 chrec1 = analyze_scalar_evolution (loop, rhs1);
1818 chrec1 = chrec_convert (type, chrec1, at_stmt);
1819 /* TYPE may be integer, real or complex, so use fold_convert. */
1820 chrec1 = instantiate_parameters (loop, chrec1);
1821 res = chrec_fold_multiply (type, chrec1,
1822 fold_convert (type, integer_minus_one_node));
1823 break;
1825 case BIT_NOT_EXPR:
1826 /* Handle ~X as -1 - X. */
1827 chrec1 = analyze_scalar_evolution (loop, rhs1);
1828 chrec1 = chrec_convert (type, chrec1, at_stmt);
1829 chrec1 = instantiate_parameters (loop, chrec1);
1830 res = chrec_fold_minus (type,
1831 fold_convert (type, integer_minus_one_node),
1832 chrec1);
1833 break;
1835 case MULT_EXPR:
1836 chrec1 = analyze_scalar_evolution (loop, rhs1);
1837 chrec2 = analyze_scalar_evolution (loop, rhs2);
1838 chrec1 = chrec_convert (type, chrec1, at_stmt);
1839 chrec2 = chrec_convert (type, chrec2, at_stmt);
1840 chrec1 = instantiate_parameters (loop, chrec1);
1841 chrec2 = instantiate_parameters (loop, chrec2);
1842 res = chrec_fold_multiply (type, chrec1, chrec2);
1843 break;
1845 CASE_CONVERT:
1846 /* In case we have a truncation of a widened operation that in
1847 the truncated type has undefined overflow behavior analyze
1848 the operation done in an unsigned type of the same precision
1849 as the final truncation. We cannot derive a scalar evolution
1850 for the widened operation but for the truncated result. */
1851 if (TREE_CODE (type) == INTEGER_TYPE
1852 && TREE_CODE (TREE_TYPE (rhs1)) == INTEGER_TYPE
1853 && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (rhs1))
1854 && TYPE_OVERFLOW_UNDEFINED (type)
1855 && TREE_CODE (rhs1) == SSA_NAME
1856 && (def = SSA_NAME_DEF_STMT (rhs1))
1857 && is_gimple_assign (def)
1858 && TREE_CODE_CLASS (gimple_assign_rhs_code (def)) == tcc_binary
1859 && TREE_CODE (gimple_assign_rhs2 (def)) == INTEGER_CST)
1861 tree utype = unsigned_type_for (type);
1862 chrec1 = interpret_rhs_expr (loop, at_stmt, utype,
1863 gimple_assign_rhs1 (def),
1864 gimple_assign_rhs_code (def),
1865 gimple_assign_rhs2 (def));
1867 else
1868 chrec1 = analyze_scalar_evolution (loop, rhs1);
1869 res = chrec_convert (type, chrec1, at_stmt);
1870 break;
1872 default:
1873 res = chrec_dont_know;
1874 break;
1877 return res;
1880 /* Interpret the expression EXPR. */
1882 static tree
1883 interpret_expr (struct loop *loop, gimple at_stmt, tree expr)
1885 enum tree_code code;
1886 tree type = TREE_TYPE (expr), op0, op1;
1888 if (automatically_generated_chrec_p (expr))
1889 return expr;
1891 if (TREE_CODE (expr) == POLYNOMIAL_CHREC
1892 || get_gimple_rhs_class (TREE_CODE (expr)) == GIMPLE_TERNARY_RHS)
1893 return chrec_dont_know;
1895 extract_ops_from_tree (expr, &code, &op0, &op1);
1897 return interpret_rhs_expr (loop, at_stmt, type,
1898 op0, code, op1);
1901 /* Interpret the rhs of the assignment STMT. */
1903 static tree
1904 interpret_gimple_assign (struct loop *loop, gimple stmt)
1906 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1907 enum tree_code code = gimple_assign_rhs_code (stmt);
1909 return interpret_rhs_expr (loop, stmt, type,
1910 gimple_assign_rhs1 (stmt), code,
1911 gimple_assign_rhs2 (stmt));
1916 /* This section contains all the entry points:
1917 - number_of_iterations_in_loop,
1918 - analyze_scalar_evolution,
1919 - instantiate_parameters.
1922 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1923 common ancestor of DEF_LOOP and USE_LOOP. */
1925 static tree
1926 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1927 struct loop *def_loop,
1928 tree ev)
1930 bool val;
1931 tree res;
1933 if (def_loop == wrto_loop)
1934 return ev;
1936 def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
1937 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1939 if (no_evolution_in_loop_p (res, wrto_loop->num, &val) && val)
1940 return res;
1942 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1945 /* Helper recursive function. */
1947 static tree
1948 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1950 tree type = TREE_TYPE (var);
1951 gimple def;
1952 basic_block bb;
1953 struct loop *def_loop;
1955 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1956 return chrec_dont_know;
1958 if (TREE_CODE (var) != SSA_NAME)
1959 return interpret_expr (loop, NULL, var);
1961 def = SSA_NAME_DEF_STMT (var);
1962 bb = gimple_bb (def);
1963 def_loop = bb ? bb->loop_father : NULL;
1965 if (bb == NULL
1966 || !flow_bb_inside_loop_p (loop, bb))
1968 /* Keep the symbolic form. */
1969 res = var;
1970 goto set_and_end;
1973 if (res != chrec_not_analyzed_yet)
1975 if (loop != bb->loop_father)
1976 res = compute_scalar_evolution_in_loop
1977 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1979 goto set_and_end;
1982 if (loop != def_loop)
1984 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1985 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1987 goto set_and_end;
1990 switch (gimple_code (def))
1992 case GIMPLE_ASSIGN:
1993 res = interpret_gimple_assign (loop, def);
1994 break;
1996 case GIMPLE_PHI:
1997 if (loop_phi_node_p (def))
1998 res = interpret_loop_phi (loop, as_a <gimple_phi> (def));
1999 else
2000 res = interpret_condition_phi (loop, as_a <gimple_phi> (def));
2001 break;
2003 default:
2004 res = chrec_dont_know;
2005 break;
2008 set_and_end:
2010 /* Keep the symbolic form. */
2011 if (res == chrec_dont_know)
2012 res = var;
2014 if (loop == def_loop)
2015 set_scalar_evolution (block_before_loop (loop), var, res);
2017 return res;
2020 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
2021 LOOP. LOOP is the loop in which the variable is used.
2023 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
2024 pointer to the statement that uses this variable, in order to
2025 determine the evolution function of the variable, use the following
2026 calls:
2028 loop_p loop = loop_containing_stmt (stmt);
2029 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
2030 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
2033 tree
2034 analyze_scalar_evolution (struct loop *loop, tree var)
2036 tree res;
2038 if (dump_file && (dump_flags & TDF_SCEV))
2040 fprintf (dump_file, "(analyze_scalar_evolution \n");
2041 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
2042 fprintf (dump_file, " (scalar = ");
2043 print_generic_expr (dump_file, var, 0);
2044 fprintf (dump_file, ")\n");
2047 res = get_scalar_evolution (block_before_loop (loop), var);
2048 res = analyze_scalar_evolution_1 (loop, var, res);
2050 if (dump_file && (dump_flags & TDF_SCEV))
2051 fprintf (dump_file, ")\n");
2053 return res;
2056 /* Analyzes and returns the scalar evolution of VAR address in LOOP. */
2058 static tree
2059 analyze_scalar_evolution_for_address_of (struct loop *loop, tree var)
2061 return analyze_scalar_evolution (loop, build_fold_addr_expr (var));
2064 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
2065 WRTO_LOOP (which should be a superloop of USE_LOOP)
2067 FOLDED_CASTS is set to true if resolve_mixers used
2068 chrec_convert_aggressive (TODO -- not really, we are way too conservative
2069 at the moment in order to keep things simple).
2071 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
2072 example:
2074 for (i = 0; i < 100; i++) -- loop 1
2076 for (j = 0; j < 100; j++) -- loop 2
2078 k1 = i;
2079 k2 = j;
2081 use2 (k1, k2);
2083 for (t = 0; t < 100; t++) -- loop 3
2084 use3 (k1, k2);
2087 use1 (k1, k2);
2090 Both k1 and k2 are invariants in loop3, thus
2091 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
2092 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
2094 As they are invariant, it does not matter whether we consider their
2095 usage in loop 3 or loop 2, hence
2096 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
2097 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
2098 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
2099 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
2101 Similarly for their evolutions with respect to loop 1. The values of K2
2102 in the use in loop 2 vary independently on loop 1, thus we cannot express
2103 the evolution with respect to loop 1:
2104 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
2105 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
2106 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
2107 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
2109 The value of k2 in the use in loop 1 is known, though:
2110 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
2111 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
2114 static tree
2115 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
2116 tree version, bool *folded_casts)
2118 bool val = false;
2119 tree ev = version, tmp;
2121 /* We cannot just do
2123 tmp = analyze_scalar_evolution (use_loop, version);
2124 ev = resolve_mixers (wrto_loop, tmp);
2126 as resolve_mixers would query the scalar evolution with respect to
2127 wrto_loop. For example, in the situation described in the function
2128 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2129 version = k2. Then
2131 analyze_scalar_evolution (use_loop, version) = k2
2133 and resolve_mixers (loop1, k2) finds that the value of k2 in loop 1
2134 is 100, which is a wrong result, since we are interested in the
2135 value in loop 3.
2137 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2138 each time checking that there is no evolution in the inner loop. */
2140 if (folded_casts)
2141 *folded_casts = false;
2142 while (1)
2144 tmp = analyze_scalar_evolution (use_loop, ev);
2145 ev = resolve_mixers (use_loop, tmp);
2147 if (folded_casts && tmp != ev)
2148 *folded_casts = true;
2150 if (use_loop == wrto_loop)
2151 return ev;
2153 /* If the value of the use changes in the inner loop, we cannot express
2154 its value in the outer loop (we might try to return interval chrec,
2155 but we do not have a user for it anyway) */
2156 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2157 || !val)
2158 return chrec_dont_know;
2160 use_loop = loop_outer (use_loop);
2165 /* Hashtable helpers for a temporary hash-table used when
2166 instantiating a CHREC or resolving mixers. For this use
2167 instantiated_below is always the same. */
2169 struct instantiate_cache_type
2171 htab_t map;
2172 vec<scev_info_str> entries;
2174 instantiate_cache_type () : map (NULL), entries (vNULL) {}
2175 ~instantiate_cache_type ();
2176 tree get (unsigned slot) { return entries[slot].chrec; }
2177 void set (unsigned slot, tree chrec) { entries[slot].chrec = chrec; }
2180 instantiate_cache_type::~instantiate_cache_type ()
2182 if (map != NULL)
2184 htab_delete (map);
2185 entries.release ();
2189 /* Cache to avoid infinite recursion when instantiating an SSA name.
2190 Live during the outermost instantiate_scev or resolve_mixers call. */
2191 static instantiate_cache_type *global_cache;
2193 /* Computes a hash function for database element ELT. */
2195 static inline hashval_t
2196 hash_idx_scev_info (const void *elt_)
2198 unsigned idx = ((size_t) elt_) - 2;
2199 return hash_scev_info (&global_cache->entries[idx]);
2202 /* Compares database elements E1 and E2. */
2204 static inline int
2205 eq_idx_scev_info (const void *e1, const void *e2)
2207 unsigned idx1 = ((size_t) e1) - 2;
2208 return eq_scev_info (&global_cache->entries[idx1], e2);
2211 /* Returns from CACHE the slot number of the cached chrec for NAME. */
2213 static unsigned
2214 get_instantiated_value_entry (instantiate_cache_type &cache,
2215 tree name, basic_block instantiate_below)
2217 if (!cache.map)
2219 cache.map = htab_create (10, hash_idx_scev_info, eq_idx_scev_info, NULL);
2220 cache.entries.create (10);
2223 scev_info_str e;
2224 e.name_version = SSA_NAME_VERSION (name);
2225 e.instantiated_below = instantiate_below->index;
2226 void **slot = htab_find_slot_with_hash (cache.map, &e,
2227 hash_scev_info (&e), INSERT);
2228 if (!*slot)
2230 e.chrec = chrec_not_analyzed_yet;
2231 *slot = (void *)(size_t)(cache.entries.length () + 2);
2232 cache.entries.safe_push (e);
2235 return ((size_t)*slot) - 2;
2239 /* Return the closed_loop_phi node for VAR. If there is none, return
2240 NULL_TREE. */
2242 static tree
2243 loop_closed_phi_def (tree var)
2245 struct loop *loop;
2246 edge exit;
2247 gimple_phi phi;
2248 gimple_phi_iterator psi;
2250 if (var == NULL_TREE
2251 || TREE_CODE (var) != SSA_NAME)
2252 return NULL_TREE;
2254 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2255 exit = single_exit (loop);
2256 if (!exit)
2257 return NULL_TREE;
2259 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2261 phi = psi.phi ();
2262 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2263 return PHI_RESULT (phi);
2266 return NULL_TREE;
2269 static tree instantiate_scev_r (basic_block, struct loop *, struct loop *,
2270 tree, bool, int);
2272 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2273 and EVOLUTION_LOOP, that were left under a symbolic form.
2275 CHREC is an SSA_NAME to be instantiated.
2277 CACHE is the cache of already instantiated values.
2279 FOLD_CONVERSIONS should be set to true when the conversions that
2280 may wrap in signed/pointer type are folded, as long as the value of
2281 the chrec is preserved.
2283 SIZE_EXPR is used for computing the size of the expression to be
2284 instantiated, and to stop if it exceeds some limit. */
2286 static tree
2287 instantiate_scev_name (basic_block instantiate_below,
2288 struct loop *evolution_loop, struct loop *inner_loop,
2289 tree chrec,
2290 bool fold_conversions,
2291 int size_expr)
2293 tree res;
2294 struct loop *def_loop;
2295 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2297 /* A parameter (or loop invariant and we do not want to include
2298 evolutions in outer loops), nothing to do. */
2299 if (!def_bb
2300 || loop_depth (def_bb->loop_father) == 0
2301 || dominated_by_p (CDI_DOMINATORS, instantiate_below, def_bb))
2302 return chrec;
2304 /* We cache the value of instantiated variable to avoid exponential
2305 time complexity due to reevaluations. We also store the convenient
2306 value in the cache in order to prevent infinite recursion -- we do
2307 not want to instantiate the SSA_NAME if it is in a mixer
2308 structure. This is used for avoiding the instantiation of
2309 recursively defined functions, such as:
2311 | a_2 -> {0, +, 1, +, a_2}_1 */
2313 unsigned si = get_instantiated_value_entry (*global_cache,
2314 chrec, instantiate_below);
2315 if (global_cache->get (si) != chrec_not_analyzed_yet)
2316 return global_cache->get (si);
2318 /* On recursion return chrec_dont_know. */
2319 global_cache->set (si, chrec_dont_know);
2321 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2323 /* If the analysis yields a parametric chrec, instantiate the
2324 result again. */
2325 res = analyze_scalar_evolution (def_loop, chrec);
2327 /* Don't instantiate default definitions. */
2328 if (TREE_CODE (res) == SSA_NAME
2329 && SSA_NAME_IS_DEFAULT_DEF (res))
2332 /* Don't instantiate loop-closed-ssa phi nodes. */
2333 else if (TREE_CODE (res) == SSA_NAME
2334 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2335 > loop_depth (def_loop))
2337 if (res == chrec)
2338 res = loop_closed_phi_def (chrec);
2339 else
2340 res = chrec;
2342 /* When there is no loop_closed_phi_def, it means that the
2343 variable is not used after the loop: try to still compute the
2344 value of the variable when exiting the loop. */
2345 if (res == NULL_TREE)
2347 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2348 res = analyze_scalar_evolution (loop, chrec);
2349 res = compute_overall_effect_of_inner_loop (loop, res);
2350 res = instantiate_scev_r (instantiate_below, evolution_loop,
2351 inner_loop, res,
2352 fold_conversions, size_expr);
2354 else if (!dominated_by_p (CDI_DOMINATORS, instantiate_below,
2355 gimple_bb (SSA_NAME_DEF_STMT (res))))
2356 res = chrec_dont_know;
2359 else if (res != chrec_dont_know)
2361 if (inner_loop
2362 && def_bb->loop_father != inner_loop
2363 && !flow_loop_nested_p (def_bb->loop_father, inner_loop))
2364 /* ??? We could try to compute the overall effect of the loop here. */
2365 res = chrec_dont_know;
2366 else
2367 res = instantiate_scev_r (instantiate_below, evolution_loop,
2368 inner_loop, res,
2369 fold_conversions, size_expr);
2372 /* Store the correct value to the cache. */
2373 global_cache->set (si, res);
2374 return res;
2377 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2378 and EVOLUTION_LOOP, that were left under a symbolic form.
2380 CHREC is a polynomial chain of recurrence to be instantiated.
2382 CACHE is the cache of already instantiated values.
2384 FOLD_CONVERSIONS should be set to true when the conversions that
2385 may wrap in signed/pointer type are folded, as long as the value of
2386 the chrec is preserved.
2388 SIZE_EXPR is used for computing the size of the expression to be
2389 instantiated, and to stop if it exceeds some limit. */
2391 static tree
2392 instantiate_scev_poly (basic_block instantiate_below,
2393 struct loop *evolution_loop, struct loop *,
2394 tree chrec, bool fold_conversions, int size_expr)
2396 tree op1;
2397 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2398 get_chrec_loop (chrec),
2399 CHREC_LEFT (chrec), fold_conversions,
2400 size_expr);
2401 if (op0 == chrec_dont_know)
2402 return chrec_dont_know;
2404 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2405 get_chrec_loop (chrec),
2406 CHREC_RIGHT (chrec), fold_conversions,
2407 size_expr);
2408 if (op1 == chrec_dont_know)
2409 return chrec_dont_know;
2411 if (CHREC_LEFT (chrec) != op0
2412 || CHREC_RIGHT (chrec) != op1)
2414 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2415 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2418 return chrec;
2421 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2422 and EVOLUTION_LOOP, that were left under a symbolic form.
2424 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2426 CACHE is the cache of already instantiated values.
2428 FOLD_CONVERSIONS should be set to true when the conversions that
2429 may wrap in signed/pointer type are folded, as long as the value of
2430 the chrec is preserved.
2432 SIZE_EXPR is used for computing the size of the expression to be
2433 instantiated, and to stop if it exceeds some limit. */
2435 static tree
2436 instantiate_scev_binary (basic_block instantiate_below,
2437 struct loop *evolution_loop, struct loop *inner_loop,
2438 tree chrec, enum tree_code code,
2439 tree type, tree c0, tree c1,
2440 bool fold_conversions, int size_expr)
2442 tree op1;
2443 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2444 c0, fold_conversions, size_expr);
2445 if (op0 == chrec_dont_know)
2446 return chrec_dont_know;
2448 op1 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2449 c1, fold_conversions, size_expr);
2450 if (op1 == chrec_dont_know)
2451 return chrec_dont_know;
2453 if (c0 != op0
2454 || c1 != op1)
2456 op0 = chrec_convert (type, op0, NULL);
2457 op1 = chrec_convert_rhs (type, op1, NULL);
2459 switch (code)
2461 case POINTER_PLUS_EXPR:
2462 case PLUS_EXPR:
2463 return chrec_fold_plus (type, op0, op1);
2465 case MINUS_EXPR:
2466 return chrec_fold_minus (type, op0, op1);
2468 case MULT_EXPR:
2469 return chrec_fold_multiply (type, op0, op1);
2471 default:
2472 gcc_unreachable ();
2476 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2479 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2480 and EVOLUTION_LOOP, that were left under a symbolic form.
2482 "CHREC" is an array reference to be instantiated.
2484 CACHE is the cache of already instantiated values.
2486 FOLD_CONVERSIONS should be set to true when the conversions that
2487 may wrap in signed/pointer type are folded, as long as the value of
2488 the chrec is preserved.
2490 SIZE_EXPR is used for computing the size of the expression to be
2491 instantiated, and to stop if it exceeds some limit. */
2493 static tree
2494 instantiate_array_ref (basic_block instantiate_below,
2495 struct loop *evolution_loop, struct loop *inner_loop,
2496 tree chrec, bool fold_conversions, int size_expr)
2498 tree res;
2499 tree index = TREE_OPERAND (chrec, 1);
2500 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2501 inner_loop, index,
2502 fold_conversions, size_expr);
2504 if (op1 == chrec_dont_know)
2505 return chrec_dont_know;
2507 if (chrec && op1 == index)
2508 return chrec;
2510 res = unshare_expr (chrec);
2511 TREE_OPERAND (res, 1) = op1;
2512 return res;
2515 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2516 and EVOLUTION_LOOP, that were left under a symbolic form.
2518 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2519 instantiated.
2521 CACHE is the cache of already instantiated values.
2523 FOLD_CONVERSIONS should be set to true when the conversions that
2524 may wrap in signed/pointer type are folded, as long as the value of
2525 the chrec is preserved.
2527 SIZE_EXPR is used for computing the size of the expression to be
2528 instantiated, and to stop if it exceeds some limit. */
2530 static tree
2531 instantiate_scev_convert (basic_block instantiate_below,
2532 struct loop *evolution_loop, struct loop *inner_loop,
2533 tree chrec, tree type, tree op,
2534 bool fold_conversions, int size_expr)
2536 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2537 inner_loop, op,
2538 fold_conversions, size_expr);
2540 if (op0 == chrec_dont_know)
2541 return chrec_dont_know;
2543 if (fold_conversions)
2545 tree tmp = chrec_convert_aggressive (type, op0);
2546 if (tmp)
2547 return tmp;
2550 if (chrec && op0 == op)
2551 return chrec;
2553 /* If we used chrec_convert_aggressive, we can no longer assume that
2554 signed chrecs do not overflow, as chrec_convert does, so avoid
2555 calling it in that case. */
2556 if (fold_conversions)
2557 return fold_convert (type, op0);
2559 return chrec_convert (type, op0, NULL);
2562 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2563 and EVOLUTION_LOOP, that were left under a symbolic form.
2565 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2566 Handle ~X as -1 - X.
2567 Handle -X as -1 * X.
2569 CACHE is the cache of already instantiated values.
2571 FOLD_CONVERSIONS should be set to true when the conversions that
2572 may wrap in signed/pointer type are folded, as long as the value of
2573 the chrec is preserved.
2575 SIZE_EXPR is used for computing the size of the expression to be
2576 instantiated, and to stop if it exceeds some limit. */
2578 static tree
2579 instantiate_scev_not (basic_block instantiate_below,
2580 struct loop *evolution_loop, struct loop *inner_loop,
2581 tree chrec,
2582 enum tree_code code, tree type, tree op,
2583 bool fold_conversions, int size_expr)
2585 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2586 inner_loop, op,
2587 fold_conversions, size_expr);
2589 if (op0 == chrec_dont_know)
2590 return chrec_dont_know;
2592 if (op != op0)
2594 op0 = chrec_convert (type, op0, NULL);
2596 switch (code)
2598 case BIT_NOT_EXPR:
2599 return chrec_fold_minus
2600 (type, fold_convert (type, integer_minus_one_node), op0);
2602 case NEGATE_EXPR:
2603 return chrec_fold_multiply
2604 (type, fold_convert (type, integer_minus_one_node), op0);
2606 default:
2607 gcc_unreachable ();
2611 return chrec ? chrec : fold_build1 (code, type, op0);
2614 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2615 and EVOLUTION_LOOP, that were left under a symbolic form.
2617 CHREC is an expression with 3 operands to be instantiated.
2619 CACHE is the cache of already instantiated values.
2621 FOLD_CONVERSIONS should be set to true when the conversions that
2622 may wrap in signed/pointer type are folded, as long as the value of
2623 the chrec is preserved.
2625 SIZE_EXPR is used for computing the size of the expression to be
2626 instantiated, and to stop if it exceeds some limit. */
2628 static tree
2629 instantiate_scev_3 (basic_block instantiate_below,
2630 struct loop *evolution_loop, struct loop *inner_loop,
2631 tree chrec,
2632 bool fold_conversions, int size_expr)
2634 tree op1, op2;
2635 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2636 inner_loop, TREE_OPERAND (chrec, 0),
2637 fold_conversions, size_expr);
2638 if (op0 == chrec_dont_know)
2639 return chrec_dont_know;
2641 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2642 inner_loop, TREE_OPERAND (chrec, 1),
2643 fold_conversions, size_expr);
2644 if (op1 == chrec_dont_know)
2645 return chrec_dont_know;
2647 op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2648 inner_loop, TREE_OPERAND (chrec, 2),
2649 fold_conversions, size_expr);
2650 if (op2 == chrec_dont_know)
2651 return chrec_dont_know;
2653 if (op0 == TREE_OPERAND (chrec, 0)
2654 && op1 == TREE_OPERAND (chrec, 1)
2655 && op2 == TREE_OPERAND (chrec, 2))
2656 return chrec;
2658 return fold_build3 (TREE_CODE (chrec),
2659 TREE_TYPE (chrec), op0, op1, op2);
2662 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2663 and EVOLUTION_LOOP, that were left under a symbolic form.
2665 CHREC is an expression with 2 operands to be instantiated.
2667 CACHE is the cache of already instantiated values.
2669 FOLD_CONVERSIONS should be set to true when the conversions that
2670 may wrap in signed/pointer type are folded, as long as the value of
2671 the chrec is preserved.
2673 SIZE_EXPR is used for computing the size of the expression to be
2674 instantiated, and to stop if it exceeds some limit. */
2676 static tree
2677 instantiate_scev_2 (basic_block instantiate_below,
2678 struct loop *evolution_loop, struct loop *inner_loop,
2679 tree chrec,
2680 bool fold_conversions, int size_expr)
2682 tree op1;
2683 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2684 inner_loop, TREE_OPERAND (chrec, 0),
2685 fold_conversions, size_expr);
2686 if (op0 == chrec_dont_know)
2687 return chrec_dont_know;
2689 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2690 inner_loop, TREE_OPERAND (chrec, 1),
2691 fold_conversions, size_expr);
2692 if (op1 == chrec_dont_know)
2693 return chrec_dont_know;
2695 if (op0 == TREE_OPERAND (chrec, 0)
2696 && op1 == TREE_OPERAND (chrec, 1))
2697 return chrec;
2699 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2702 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2703 and EVOLUTION_LOOP, that were left under a symbolic form.
2705 CHREC is an expression with 2 operands to be instantiated.
2707 CACHE is the cache of already instantiated values.
2709 FOLD_CONVERSIONS should be set to true when the conversions that
2710 may wrap in signed/pointer type are folded, as long as the value of
2711 the chrec is preserved.
2713 SIZE_EXPR is used for computing the size of the expression to be
2714 instantiated, and to stop if it exceeds some limit. */
2716 static tree
2717 instantiate_scev_1 (basic_block instantiate_below,
2718 struct loop *evolution_loop, struct loop *inner_loop,
2719 tree chrec,
2720 bool fold_conversions, int size_expr)
2722 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2723 inner_loop, TREE_OPERAND (chrec, 0),
2724 fold_conversions, size_expr);
2726 if (op0 == chrec_dont_know)
2727 return chrec_dont_know;
2729 if (op0 == TREE_OPERAND (chrec, 0))
2730 return chrec;
2732 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2735 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2736 and EVOLUTION_LOOP, that were left under a symbolic form.
2738 CHREC is the scalar evolution to instantiate.
2740 CACHE is the cache of already instantiated values.
2742 FOLD_CONVERSIONS should be set to true when the conversions that
2743 may wrap in signed/pointer type are folded, as long as the value of
2744 the chrec is preserved.
2746 SIZE_EXPR is used for computing the size of the expression to be
2747 instantiated, and to stop if it exceeds some limit. */
2749 static tree
2750 instantiate_scev_r (basic_block instantiate_below,
2751 struct loop *evolution_loop, struct loop *inner_loop,
2752 tree chrec,
2753 bool fold_conversions, int size_expr)
2755 /* Give up if the expression is larger than the MAX that we allow. */
2756 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2757 return chrec_dont_know;
2759 if (chrec == NULL_TREE
2760 || automatically_generated_chrec_p (chrec)
2761 || is_gimple_min_invariant (chrec))
2762 return chrec;
2764 switch (TREE_CODE (chrec))
2766 case SSA_NAME:
2767 return instantiate_scev_name (instantiate_below, evolution_loop,
2768 inner_loop, chrec,
2769 fold_conversions, size_expr);
2771 case POLYNOMIAL_CHREC:
2772 return instantiate_scev_poly (instantiate_below, evolution_loop,
2773 inner_loop, chrec,
2774 fold_conversions, size_expr);
2776 case POINTER_PLUS_EXPR:
2777 case PLUS_EXPR:
2778 case MINUS_EXPR:
2779 case MULT_EXPR:
2780 return instantiate_scev_binary (instantiate_below, evolution_loop,
2781 inner_loop, chrec,
2782 TREE_CODE (chrec), chrec_type (chrec),
2783 TREE_OPERAND (chrec, 0),
2784 TREE_OPERAND (chrec, 1),
2785 fold_conversions, size_expr);
2787 CASE_CONVERT:
2788 return instantiate_scev_convert (instantiate_below, evolution_loop,
2789 inner_loop, chrec,
2790 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2791 fold_conversions, size_expr);
2793 case NEGATE_EXPR:
2794 case BIT_NOT_EXPR:
2795 return instantiate_scev_not (instantiate_below, evolution_loop,
2796 inner_loop, chrec,
2797 TREE_CODE (chrec), TREE_TYPE (chrec),
2798 TREE_OPERAND (chrec, 0),
2799 fold_conversions, size_expr);
2801 case ADDR_EXPR:
2802 case SCEV_NOT_KNOWN:
2803 return chrec_dont_know;
2805 case SCEV_KNOWN:
2806 return chrec_known;
2808 case ARRAY_REF:
2809 return instantiate_array_ref (instantiate_below, evolution_loop,
2810 inner_loop, chrec,
2811 fold_conversions, size_expr);
2813 default:
2814 break;
2817 if (VL_EXP_CLASS_P (chrec))
2818 return chrec_dont_know;
2820 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2822 case 3:
2823 return instantiate_scev_3 (instantiate_below, evolution_loop,
2824 inner_loop, chrec,
2825 fold_conversions, size_expr);
2827 case 2:
2828 return instantiate_scev_2 (instantiate_below, evolution_loop,
2829 inner_loop, chrec,
2830 fold_conversions, size_expr);
2832 case 1:
2833 return instantiate_scev_1 (instantiate_below, evolution_loop,
2834 inner_loop, chrec,
2835 fold_conversions, size_expr);
2837 case 0:
2838 return chrec;
2840 default:
2841 break;
2844 /* Too complicated to handle. */
2845 return chrec_dont_know;
2848 /* Analyze all the parameters of the chrec that were left under a
2849 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2850 recursive instantiation of parameters: a parameter is a variable
2851 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2852 a function parameter. */
2854 tree
2855 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2856 tree chrec)
2858 tree res;
2860 if (dump_file && (dump_flags & TDF_SCEV))
2862 fprintf (dump_file, "(instantiate_scev \n");
2863 fprintf (dump_file, " (instantiate_below = %d)\n", instantiate_below->index);
2864 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2865 fprintf (dump_file, " (chrec = ");
2866 print_generic_expr (dump_file, chrec, 0);
2867 fprintf (dump_file, ")\n");
2870 bool destr = false;
2871 if (!global_cache)
2873 global_cache = new instantiate_cache_type;
2874 destr = true;
2877 res = instantiate_scev_r (instantiate_below, evolution_loop,
2878 NULL, chrec, false, 0);
2880 if (destr)
2882 delete global_cache;
2883 global_cache = NULL;
2886 if (dump_file && (dump_flags & TDF_SCEV))
2888 fprintf (dump_file, " (res = ");
2889 print_generic_expr (dump_file, res, 0);
2890 fprintf (dump_file, "))\n");
2893 return res;
2896 /* Similar to instantiate_parameters, but does not introduce the
2897 evolutions in outer loops for LOOP invariants in CHREC, and does not
2898 care about causing overflows, as long as they do not affect value
2899 of an expression. */
2901 tree
2902 resolve_mixers (struct loop *loop, tree chrec)
2904 bool destr = false;
2905 if (!global_cache)
2907 global_cache = new instantiate_cache_type;
2908 destr = true;
2911 tree ret = instantiate_scev_r (block_before_loop (loop), loop, NULL,
2912 chrec, true, 0);
2914 if (destr)
2916 delete global_cache;
2917 global_cache = NULL;
2920 return ret;
2923 /* Entry point for the analysis of the number of iterations pass.
2924 This function tries to safely approximate the number of iterations
2925 the loop will run. When this property is not decidable at compile
2926 time, the result is chrec_dont_know. Otherwise the result is a
2927 scalar or a symbolic parameter. When the number of iterations may
2928 be equal to zero and the property cannot be determined at compile
2929 time, the result is a COND_EXPR that represents in a symbolic form
2930 the conditions under which the number of iterations is not zero.
2932 Example of analysis: suppose that the loop has an exit condition:
2934 "if (b > 49) goto end_loop;"
2936 and that in a previous analysis we have determined that the
2937 variable 'b' has an evolution function:
2939 "EF = {23, +, 5}_2".
2941 When we evaluate the function at the point 5, i.e. the value of the
2942 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2943 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2944 the loop body has been executed 6 times. */
2946 tree
2947 number_of_latch_executions (struct loop *loop)
2949 edge exit;
2950 struct tree_niter_desc niter_desc;
2951 tree may_be_zero;
2952 tree res;
2954 /* Determine whether the number of iterations in loop has already
2955 been computed. */
2956 res = loop->nb_iterations;
2957 if (res)
2958 return res;
2960 may_be_zero = NULL_TREE;
2962 if (dump_file && (dump_flags & TDF_SCEV))
2963 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2965 res = chrec_dont_know;
2966 exit = single_exit (loop);
2968 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2970 may_be_zero = niter_desc.may_be_zero;
2971 res = niter_desc.niter;
2974 if (res == chrec_dont_know
2975 || !may_be_zero
2976 || integer_zerop (may_be_zero))
2978 else if (integer_nonzerop (may_be_zero))
2979 res = build_int_cst (TREE_TYPE (res), 0);
2981 else if (COMPARISON_CLASS_P (may_be_zero))
2982 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2983 build_int_cst (TREE_TYPE (res), 0), res);
2984 else
2985 res = chrec_dont_know;
2987 if (dump_file && (dump_flags & TDF_SCEV))
2989 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2990 print_generic_expr (dump_file, res, 0);
2991 fprintf (dump_file, "))\n");
2994 loop->nb_iterations = res;
2995 return res;
2999 /* Counters for the stats. */
3001 struct chrec_stats
3003 unsigned nb_chrecs;
3004 unsigned nb_affine;
3005 unsigned nb_affine_multivar;
3006 unsigned nb_higher_poly;
3007 unsigned nb_chrec_dont_know;
3008 unsigned nb_undetermined;
3011 /* Reset the counters. */
3013 static inline void
3014 reset_chrecs_counters (struct chrec_stats *stats)
3016 stats->nb_chrecs = 0;
3017 stats->nb_affine = 0;
3018 stats->nb_affine_multivar = 0;
3019 stats->nb_higher_poly = 0;
3020 stats->nb_chrec_dont_know = 0;
3021 stats->nb_undetermined = 0;
3024 /* Dump the contents of a CHREC_STATS structure. */
3026 static void
3027 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
3029 fprintf (file, "\n(\n");
3030 fprintf (file, "-----------------------------------------\n");
3031 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
3032 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
3033 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
3034 stats->nb_higher_poly);
3035 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
3036 fprintf (file, "-----------------------------------------\n");
3037 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
3038 fprintf (file, "%d\twith undetermined coefficients\n",
3039 stats->nb_undetermined);
3040 fprintf (file, "-----------------------------------------\n");
3041 fprintf (file, "%d\tchrecs in the scev database\n",
3042 (int) htab_elements (scalar_evolution_info));
3043 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
3044 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
3045 fprintf (file, "-----------------------------------------\n");
3046 fprintf (file, ")\n\n");
3049 /* Gather statistics about CHREC. */
3051 static void
3052 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
3054 if (dump_file && (dump_flags & TDF_STATS))
3056 fprintf (dump_file, "(classify_chrec ");
3057 print_generic_expr (dump_file, chrec, 0);
3058 fprintf (dump_file, "\n");
3061 stats->nb_chrecs++;
3063 if (chrec == NULL_TREE)
3065 stats->nb_undetermined++;
3066 return;
3069 switch (TREE_CODE (chrec))
3071 case POLYNOMIAL_CHREC:
3072 if (evolution_function_is_affine_p (chrec))
3074 if (dump_file && (dump_flags & TDF_STATS))
3075 fprintf (dump_file, " affine_univariate\n");
3076 stats->nb_affine++;
3078 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
3080 if (dump_file && (dump_flags & TDF_STATS))
3081 fprintf (dump_file, " affine_multivariate\n");
3082 stats->nb_affine_multivar++;
3084 else
3086 if (dump_file && (dump_flags & TDF_STATS))
3087 fprintf (dump_file, " higher_degree_polynomial\n");
3088 stats->nb_higher_poly++;
3091 break;
3093 default:
3094 break;
3097 if (chrec_contains_undetermined (chrec))
3099 if (dump_file && (dump_flags & TDF_STATS))
3100 fprintf (dump_file, " undetermined\n");
3101 stats->nb_undetermined++;
3104 if (dump_file && (dump_flags & TDF_STATS))
3105 fprintf (dump_file, ")\n");
3108 /* Callback for htab_traverse, gathers information on chrecs in the
3109 hashtable. */
3111 static int
3112 gather_stats_on_scev_database_1 (void **slot, void *stats)
3114 struct scev_info_str *entry = (struct scev_info_str *) *slot;
3116 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
3118 return 1;
3121 /* Classify the chrecs of the whole database. */
3123 void
3124 gather_stats_on_scev_database (void)
3126 struct chrec_stats stats;
3128 if (!dump_file)
3129 return;
3131 reset_chrecs_counters (&stats);
3133 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
3134 &stats);
3136 dump_chrecs_stats (dump_file, &stats);
3141 /* Initializer. */
3143 static void
3144 initialize_scalar_evolutions_analyzer (void)
3146 /* The elements below are unique. */
3147 if (chrec_dont_know == NULL_TREE)
3149 chrec_not_analyzed_yet = NULL_TREE;
3150 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3151 chrec_known = make_node (SCEV_KNOWN);
3152 TREE_TYPE (chrec_dont_know) = void_type_node;
3153 TREE_TYPE (chrec_known) = void_type_node;
3157 /* Initialize the analysis of scalar evolutions for LOOPS. */
3159 void
3160 scev_initialize (void)
3162 struct loop *loop;
3164 scalar_evolution_info = htab_create_ggc (100, hash_scev_info, eq_scev_info,
3165 del_scev_info);
3167 initialize_scalar_evolutions_analyzer ();
3169 FOR_EACH_LOOP (loop, 0)
3171 loop->nb_iterations = NULL_TREE;
3175 /* Return true if SCEV is initialized. */
3177 bool
3178 scev_initialized_p (void)
3180 return scalar_evolution_info != NULL;
3183 /* Cleans up the information cached by the scalar evolutions analysis
3184 in the hash table. */
3186 void
3187 scev_reset_htab (void)
3189 if (!scalar_evolution_info)
3190 return;
3192 htab_empty (scalar_evolution_info);
3195 /* Cleans up the information cached by the scalar evolutions analysis
3196 in the hash table and in the loop->nb_iterations. */
3198 void
3199 scev_reset (void)
3201 struct loop *loop;
3203 scev_reset_htab ();
3205 FOR_EACH_LOOP (loop, 0)
3207 loop->nb_iterations = NULL_TREE;
3211 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3212 respect to WRTO_LOOP and returns its base and step in IV if possible
3213 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3214 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3215 invariant in LOOP. Otherwise we require it to be an integer constant.
3217 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3218 because it is computed in signed arithmetics). Consequently, adding an
3219 induction variable
3221 for (i = IV->base; ; i += IV->step)
3223 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3224 false for the type of the induction variable, or you can prove that i does
3225 not wrap by some other argument. Otherwise, this might introduce undefined
3226 behavior, and
3228 for (i = iv->base; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3230 must be used instead. */
3232 bool
3233 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3234 affine_iv *iv, bool allow_nonconstant_step)
3236 tree type, ev;
3237 bool folded_casts;
3239 iv->base = NULL_TREE;
3240 iv->step = NULL_TREE;
3241 iv->no_overflow = false;
3243 type = TREE_TYPE (op);
3244 if (!POINTER_TYPE_P (type)
3245 && !INTEGRAL_TYPE_P (type))
3246 return false;
3248 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3249 &folded_casts);
3250 if (chrec_contains_undetermined (ev)
3251 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3252 return false;
3254 if (tree_does_not_contain_chrecs (ev))
3256 iv->base = ev;
3257 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3258 iv->no_overflow = true;
3259 return true;
3262 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
3263 || CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3264 return false;
3266 iv->step = CHREC_RIGHT (ev);
3267 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3268 || tree_contains_chrecs (iv->step, NULL))
3269 return false;
3271 iv->base = CHREC_LEFT (ev);
3272 if (tree_contains_chrecs (iv->base, NULL))
3273 return false;
3275 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
3277 return true;
3280 /* Finalize the scalar evolution analysis. */
3282 void
3283 scev_finalize (void)
3285 if (!scalar_evolution_info)
3286 return;
3287 htab_delete (scalar_evolution_info);
3288 scalar_evolution_info = NULL;
3291 /* Returns true if the expression EXPR is considered to be too expensive
3292 for scev_const_prop. */
3294 bool
3295 expression_expensive_p (tree expr)
3297 enum tree_code code;
3299 if (is_gimple_val (expr))
3300 return false;
3302 code = TREE_CODE (expr);
3303 if (code == TRUNC_DIV_EXPR
3304 || code == CEIL_DIV_EXPR
3305 || code == FLOOR_DIV_EXPR
3306 || code == ROUND_DIV_EXPR
3307 || code == TRUNC_MOD_EXPR
3308 || code == CEIL_MOD_EXPR
3309 || code == FLOOR_MOD_EXPR
3310 || code == ROUND_MOD_EXPR
3311 || code == EXACT_DIV_EXPR)
3313 /* Division by power of two is usually cheap, so we allow it.
3314 Forbid anything else. */
3315 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3316 return true;
3319 switch (TREE_CODE_CLASS (code))
3321 case tcc_binary:
3322 case tcc_comparison:
3323 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3324 return true;
3326 /* Fallthru. */
3327 case tcc_unary:
3328 return expression_expensive_p (TREE_OPERAND (expr, 0));
3330 default:
3331 return true;
3335 /* Replace ssa names for that scev can prove they are constant by the
3336 appropriate constants. Also perform final value replacement in loops,
3337 in case the replacement expressions are cheap.
3339 We only consider SSA names defined by phi nodes; rest is left to the
3340 ordinary constant propagation pass. */
3342 unsigned int
3343 scev_const_prop (void)
3345 basic_block bb;
3346 tree name, type, ev;
3347 gimple_phi phi;
3348 gimple ass;
3349 struct loop *loop, *ex_loop;
3350 bitmap ssa_names_to_remove = NULL;
3351 unsigned i;
3352 gimple_phi_iterator psi;
3354 if (number_of_loops (cfun) <= 1)
3355 return 0;
3357 FOR_EACH_BB_FN (bb, cfun)
3359 loop = bb->loop_father;
3361 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3363 phi = psi.phi ();
3364 name = PHI_RESULT (phi);
3366 if (virtual_operand_p (name))
3367 continue;
3369 type = TREE_TYPE (name);
3371 if (!POINTER_TYPE_P (type)
3372 && !INTEGRAL_TYPE_P (type))
3373 continue;
3375 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
3376 if (!is_gimple_min_invariant (ev)
3377 || !may_propagate_copy (name, ev))
3378 continue;
3380 /* Replace the uses of the name. */
3381 if (name != ev)
3382 replace_uses_by (name, ev);
3384 if (!ssa_names_to_remove)
3385 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3386 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3390 /* Remove the ssa names that were replaced by constants. We do not
3391 remove them directly in the previous cycle, since this
3392 invalidates scev cache. */
3393 if (ssa_names_to_remove)
3395 bitmap_iterator bi;
3397 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3399 gimple_stmt_iterator psi;
3400 name = ssa_name (i);
3401 phi = as_a <gimple_phi> (SSA_NAME_DEF_STMT (name));
3403 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3404 psi = gsi_for_stmt (phi);
3405 remove_phi_node (&psi, true);
3408 BITMAP_FREE (ssa_names_to_remove);
3409 scev_reset ();
3412 /* Now the regular final value replacement. */
3413 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
3415 edge exit;
3416 tree def, rslt, niter;
3417 gimple_stmt_iterator gsi;
3419 /* If we do not know exact number of iterations of the loop, we cannot
3420 replace the final value. */
3421 exit = single_exit (loop);
3422 if (!exit)
3423 continue;
3425 niter = number_of_latch_executions (loop);
3426 if (niter == chrec_dont_know)
3427 continue;
3429 /* Ensure that it is possible to insert new statements somewhere. */
3430 if (!single_pred_p (exit->dest))
3431 split_loop_exit_edge (exit);
3432 gsi = gsi_after_labels (exit->dest);
3434 ex_loop = superloop_at_depth (loop,
3435 loop_depth (exit->dest->loop_father) + 1);
3437 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3439 phi = psi.phi ();
3440 rslt = PHI_RESULT (phi);
3441 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3442 if (virtual_operand_p (def))
3444 gsi_next (&psi);
3445 continue;
3448 if (!POINTER_TYPE_P (TREE_TYPE (def))
3449 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3451 gsi_next (&psi);
3452 continue;
3455 bool folded_casts;
3456 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def,
3457 &folded_casts);
3458 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3459 if (!tree_does_not_contain_chrecs (def)
3460 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3461 /* Moving the computation from the loop may prolong life range
3462 of some ssa names, which may cause problems if they appear
3463 on abnormal edges. */
3464 || contains_abnormal_ssa_name_p (def)
3465 /* Do not emit expensive expressions. The rationale is that
3466 when someone writes a code like
3468 while (n > 45) n -= 45;
3470 he probably knows that n is not large, and does not want it
3471 to be turned into n %= 45. */
3472 || expression_expensive_p (def))
3474 if (dump_file && (dump_flags & TDF_DETAILS))
3476 fprintf (dump_file, "not replacing:\n ");
3477 print_gimple_stmt (dump_file, phi, 0, 0);
3478 fprintf (dump_file, "\n");
3480 gsi_next (&psi);
3481 continue;
3484 /* Eliminate the PHI node and replace it by a computation outside
3485 the loop. */
3486 if (dump_file)
3488 fprintf (dump_file, "\nfinal value replacement:\n ");
3489 print_gimple_stmt (dump_file, phi, 0, 0);
3490 fprintf (dump_file, " with\n ");
3492 def = unshare_expr (def);
3493 remove_phi_node (&psi, false);
3495 /* If def's type has undefined overflow and there were folded
3496 casts, rewrite all stmts added for def into arithmetics
3497 with defined overflow behavior. */
3498 if (folded_casts && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (def)))
3500 gimple_seq stmts;
3501 gimple_stmt_iterator gsi2;
3502 def = force_gimple_operand (def, &stmts, true, NULL_TREE);
3503 gsi2 = gsi_start (stmts);
3504 while (!gsi_end_p (gsi2))
3506 gimple stmt = gsi_stmt (gsi2);
3507 gimple_stmt_iterator gsi3 = gsi2;
3508 gsi_next (&gsi2);
3509 gsi_remove (&gsi3, false);
3510 if (is_gimple_assign (stmt)
3511 && arith_code_with_undefined_signed_overflow
3512 (gimple_assign_rhs_code (stmt)))
3513 gsi_insert_seq_before (&gsi,
3514 rewrite_to_defined_overflow (stmt),
3515 GSI_SAME_STMT);
3516 else
3517 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
3520 else
3521 def = force_gimple_operand_gsi (&gsi, def, false, NULL_TREE,
3522 true, GSI_SAME_STMT);
3524 ass = gimple_build_assign (rslt, def);
3525 gsi_insert_before (&gsi, ass, GSI_SAME_STMT);
3526 if (dump_file)
3528 print_gimple_stmt (dump_file, ass, 0, 0);
3529 fprintf (dump_file, "\n");
3533 return 0;
3536 #include "gt-tree-scalar-evolution.h"