PR tree-optimization/27639
[official-gcc.git] / gcc / tree-scalar-evolution.c
blob52b0ba38b679fa4758b1eb2d0a91bdee2249cb0b
1 /* Scalar evolution detector.
2 Copyright (C) 2003, 2004, 2005 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 2, 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 COPYING. If not, write to the Free
19 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301, USA. */
22 /*
23 Description:
25 This pass analyzes the evolution of scalar variables in loop
26 structures. The algorithm is based on the SSA representation,
27 and on the loop hierarchy tree. This algorithm is not based on
28 the notion of versions of a variable, as it was the case for the
29 previous implementations of the scalar evolution algorithm, but
30 it assumes that each defined name is unique.
32 The notation used in this file is called "chains of recurrences",
33 and has been proposed by Eugene Zima, Robert Van Engelen, and
34 others for describing induction variables in programs. For example
35 "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
36 when entering in the loop_1 and has a step 2 in this loop, in other
37 words "for (b = 0; b < N; b+=2);". Note that the coefficients of
38 this chain of recurrence (or chrec [shrek]) can contain the name of
39 other variables, in which case they are called parametric chrecs.
40 For example, "b -> {a, +, 2}_1" means that the initial value of "b"
41 is the value of "a". In most of the cases these parametric chrecs
42 are fully instantiated before their use because symbolic names can
43 hide some difficult cases such as self-references described later
44 (see the Fibonacci example).
46 A short sketch of the algorithm is:
48 Given a scalar variable to be analyzed, follow the SSA edge to
49 its definition:
51 - When the definition is a MODIFY_EXPR: if the right hand side
52 (RHS) of the definition cannot be statically analyzed, the answer
53 of the analyzer is: "don't know".
54 Otherwise, for all the variables that are not yet analyzed in the
55 RHS, try to determine their evolution, and finally try to
56 evaluate the operation of the RHS that gives the evolution
57 function of the analyzed variable.
59 - When the definition is a condition-phi-node: determine the
60 evolution function for all the branches of the phi node, and
61 finally merge these evolutions (see chrec_merge).
63 - When the definition is a loop-phi-node: determine its initial
64 condition, that is the SSA edge defined in an outer loop, and
65 keep it symbolic. Then determine the SSA edges that are defined
66 in the body of the loop. Follow the inner edges until ending on
67 another loop-phi-node of the same analyzed loop. If the reached
68 loop-phi-node is not the starting loop-phi-node, then we keep
69 this definition under a symbolic form. If the reached
70 loop-phi-node is the same as the starting one, then we compute a
71 symbolic stride on the return path. The result is then the
72 symbolic chrec {initial_condition, +, symbolic_stride}_loop.
74 Examples:
76 Example 1: Illustration of the basic algorithm.
78 | a = 3
79 | loop_1
80 | b = phi (a, c)
81 | c = b + 1
82 | if (c > 10) exit_loop
83 | endloop
85 Suppose that we want to know the number of iterations of the
86 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
87 ask the scalar evolution analyzer two questions: what's the
88 scalar evolution (scev) of "c", and what's the scev of "10". For
89 "10" the answer is "10" since it is a scalar constant. For the
90 scalar variable "c", it follows the SSA edge to its definition,
91 "c = b + 1", and then asks again what's the scev of "b".
92 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
93 c)", where the initial condition is "a", and the inner loop edge
94 is "c". The initial condition is kept under a symbolic form (it
95 may be the case that the copy constant propagation has done its
96 work and we end with the constant "3" as one of the edges of the
97 loop-phi-node). The update edge is followed to the end of the
98 loop, and until reaching again the starting loop-phi-node: b -> c
99 -> b. At this point we have drawn a path from "b" to "b" from
100 which we compute the stride in the loop: in this example it is
101 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
102 that the scev for "b" is known, it is possible to compute the
103 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
104 determine the number of iterations in the loop_1, we have to
105 instantiate_parameters ({a + 1, +, 1}_1), that gives after some
106 more analysis the scev {4, +, 1}_1, or in other words, this is
107 the function "f (x) = x + 4", where x is the iteration count of
108 the loop_1. Now we have to solve the inequality "x + 4 > 10",
109 and take the smallest iteration number for which the loop is
110 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
111 there are 8 iterations. In terms of loop normalization, we have
112 created a variable that is implicitly defined, "x" or just "_1",
113 and all the other analyzed scalars of the loop are defined in
114 function of this variable:
116 a -> 3
117 b -> {3, +, 1}_1
118 c -> {4, +, 1}_1
120 or in terms of a C program:
122 | a = 3
123 | for (x = 0; x <= 7; x++)
125 | b = x + 3
126 | c = x + 4
129 Example 2: Illustration of the algorithm on nested loops.
131 | loop_1
132 | a = phi (1, b)
133 | c = a + 2
134 | loop_2 10 times
135 | b = phi (c, d)
136 | d = b + 3
137 | endloop
138 | endloop
140 For analyzing the scalar evolution of "a", the algorithm follows
141 the SSA edge into the loop's body: "a -> b". "b" is an inner
142 loop-phi-node, and its analysis as in Example 1, gives:
144 b -> {c, +, 3}_2
145 d -> {c + 3, +, 3}_2
147 Following the SSA edge for the initial condition, we end on "c = a
148 + 2", and then on the starting loop-phi-node "a". From this point,
149 the loop stride is computed: back on "c = a + 2" we get a "+2" in
150 the loop_1, then on the loop-phi-node "b" we compute the overall
151 effect of the inner loop that is "b = c + 30", and we get a "+30"
152 in the loop_1. That means that the overall stride in loop_1 is
153 equal to "+32", and the result is:
155 a -> {1, +, 32}_1
156 c -> {3, +, 32}_1
158 Example 3: Higher degree polynomials.
160 | loop_1
161 | a = phi (2, b)
162 | c = phi (5, d)
163 | b = a + 1
164 | d = c + a
165 | endloop
167 a -> {2, +, 1}_1
168 b -> {3, +, 1}_1
169 c -> {5, +, a}_1
170 d -> {5 + a, +, a}_1
172 instantiate_parameters ({5, +, a}_1) -> {5, +, 2, +, 1}_1
173 instantiate_parameters ({5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
175 Example 4: Lucas, Fibonacci, or mixers in general.
177 | loop_1
178 | a = phi (1, b)
179 | c = phi (3, d)
180 | b = c
181 | d = c + a
182 | endloop
184 a -> (1, c)_1
185 c -> {3, +, a}_1
187 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
188 following semantics: during the first iteration of the loop_1, the
189 variable contains the value 1, and then it contains the value "c".
190 Note that this syntax is close to the syntax of the loop-phi-node:
191 "a -> (1, c)_1" vs. "a = phi (1, c)".
193 The symbolic chrec representation contains all the semantics of the
194 original code. What is more difficult is to use this information.
196 Example 5: Flip-flops, or exchangers.
198 | loop_1
199 | a = phi (1, b)
200 | c = phi (3, d)
201 | b = c
202 | d = a
203 | endloop
205 a -> (1, c)_1
206 c -> (3, a)_1
208 Based on these symbolic chrecs, it is possible to refine this
209 information into the more precise PERIODIC_CHRECs:
211 a -> |1, 3|_1
212 c -> |3, 1|_1
214 This transformation is not yet implemented.
216 Further readings:
218 You can find a more detailed description of the algorithm in:
219 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
220 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
221 this is a preliminary report and some of the details of the
222 algorithm have changed. I'm working on a research report that
223 updates the description of the algorithms to reflect the design
224 choices used in this implementation.
226 A set of slides show a high level overview of the algorithm and run
227 an example through the scalar evolution analyzer:
228 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
230 The slides that I have presented at the GCC Summit'04 are available
231 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
234 #include "config.h"
235 #include "system.h"
236 #include "coretypes.h"
237 #include "tm.h"
238 #include "ggc.h"
239 #include "tree.h"
240 #include "real.h"
242 /* These RTL headers are needed for basic-block.h. */
243 #include "rtl.h"
244 #include "basic-block.h"
245 #include "diagnostic.h"
246 #include "tree-flow.h"
247 #include "tree-dump.h"
248 #include "timevar.h"
249 #include "cfgloop.h"
250 #include "tree-chrec.h"
251 #include "tree-scalar-evolution.h"
252 #include "tree-pass.h"
253 #include "flags.h"
254 #include "params.h"
256 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
257 static tree resolve_mixers (struct loop *, tree);
259 /* The cached information about a ssa name VAR, claiming that inside LOOP,
260 the value of VAR can be expressed as CHREC. */
262 struct scev_info_str
264 tree var;
265 tree chrec;
268 /* Counters for the scev database. */
269 static unsigned nb_set_scev = 0;
270 static unsigned nb_get_scev = 0;
272 /* The following trees are unique elements. Thus the comparison of
273 another element to these elements should be done on the pointer to
274 these trees, and not on their value. */
276 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
277 tree chrec_not_analyzed_yet;
279 /* Reserved to the cases where the analyzer has detected an
280 undecidable property at compile time. */
281 tree chrec_dont_know;
283 /* When the analyzer has detected that a property will never
284 happen, then it qualifies it with chrec_known. */
285 tree chrec_known;
287 static bitmap already_instantiated;
289 static htab_t scalar_evolution_info;
292 /* Constructs a new SCEV_INFO_STR structure. */
294 static inline struct scev_info_str *
295 new_scev_info_str (tree var)
297 struct scev_info_str *res;
299 res = XNEW (struct scev_info_str);
300 res->var = var;
301 res->chrec = chrec_not_analyzed_yet;
303 return res;
306 /* Computes a hash function for database element ELT. */
308 static hashval_t
309 hash_scev_info (const void *elt)
311 return SSA_NAME_VERSION (((struct scev_info_str *) elt)->var);
314 /* Compares database elements E1 and E2. */
316 static int
317 eq_scev_info (const void *e1, const void *e2)
319 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
320 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
322 return elt1->var == elt2->var;
325 /* Deletes database element E. */
327 static void
328 del_scev_info (void *e)
330 free (e);
333 /* Get the index corresponding to VAR in the current LOOP. If
334 it's the first time we ask for this VAR, then we return
335 chrec_not_analyzed_yet for this VAR and return its index. */
337 static tree *
338 find_var_scev_info (tree var)
340 struct scev_info_str *res;
341 struct scev_info_str tmp;
342 PTR *slot;
344 tmp.var = var;
345 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
347 if (!*slot)
348 *slot = new_scev_info_str (var);
349 res = (struct scev_info_str *) *slot;
351 return &res->chrec;
354 /* Return true when CHREC contains symbolic names defined in
355 LOOP_NB. */
357 bool
358 chrec_contains_symbols_defined_in_loop (tree chrec, unsigned loop_nb)
360 if (chrec == NULL_TREE)
361 return false;
363 if (TREE_INVARIANT (chrec))
364 return false;
366 if (TREE_CODE (chrec) == VAR_DECL
367 || TREE_CODE (chrec) == PARM_DECL
368 || TREE_CODE (chrec) == FUNCTION_DECL
369 || TREE_CODE (chrec) == LABEL_DECL
370 || TREE_CODE (chrec) == RESULT_DECL
371 || TREE_CODE (chrec) == FIELD_DECL)
372 return true;
374 if (TREE_CODE (chrec) == SSA_NAME)
376 tree def = SSA_NAME_DEF_STMT (chrec);
377 struct loop *def_loop = loop_containing_stmt (def);
378 struct loop *loop = current_loops->parray[loop_nb];
380 if (def_loop == NULL)
381 return false;
383 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
384 return true;
386 return false;
389 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
391 case 3:
392 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, 2),
393 loop_nb))
394 return true;
396 case 2:
397 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, 1),
398 loop_nb))
399 return true;
401 case 1:
402 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, 0),
403 loop_nb))
404 return true;
406 default:
407 return false;
411 /* Return true when PHI is a loop-phi-node. */
413 static bool
414 loop_phi_node_p (tree phi)
416 /* The implementation of this function is based on the following
417 property: "all the loop-phi-nodes of a loop are contained in the
418 loop's header basic block". */
420 return loop_containing_stmt (phi)->header == bb_for_stmt (phi);
423 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
424 In general, in the case of multivariate evolutions we want to get
425 the evolution in different loops. LOOP specifies the level for
426 which to get the evolution.
428 Example:
430 | for (j = 0; j < 100; j++)
432 | for (k = 0; k < 100; k++)
434 | i = k + j; - Here the value of i is a function of j, k.
436 | ... = i - Here the value of i is a function of j.
438 | ... = i - Here the value of i is a scalar.
440 Example:
442 | i_0 = ...
443 | loop_1 10 times
444 | i_1 = phi (i_0, i_2)
445 | i_2 = i_1 + 2
446 | endloop
448 This loop has the same effect as:
449 LOOP_1 has the same effect as:
451 | i_1 = i_0 + 20
453 The overall effect of the loop, "i_0 + 20" in the previous example,
454 is obtained by passing in the parameters: LOOP = 1,
455 EVOLUTION_FN = {i_0, +, 2}_1.
458 static tree
459 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
461 bool val = false;
463 if (evolution_fn == chrec_dont_know)
464 return chrec_dont_know;
466 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
468 if (CHREC_VARIABLE (evolution_fn) >= (unsigned) loop->num)
470 struct loop *inner_loop =
471 current_loops->parray[CHREC_VARIABLE (evolution_fn)];
472 tree nb_iter = number_of_iterations_in_loop (inner_loop);
474 if (nb_iter == chrec_dont_know)
475 return chrec_dont_know;
476 else
478 tree res;
479 tree type = chrec_type (nb_iter);
481 /* Number of iterations is off by one (the ssa name we
482 analyze must be defined before the exit). */
483 nb_iter = chrec_fold_minus (type, nb_iter,
484 build_int_cst (type, 1));
486 /* evolution_fn is the evolution function in LOOP. Get
487 its value in the nb_iter-th iteration. */
488 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
490 /* Continue the computation until ending on a parent of LOOP. */
491 return compute_overall_effect_of_inner_loop (loop, res);
494 else
495 return evolution_fn;
498 /* If the evolution function is an invariant, there is nothing to do. */
499 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
500 return evolution_fn;
502 else
503 return chrec_dont_know;
506 /* Determine whether the CHREC is always positive/negative. If the expression
507 cannot be statically analyzed, return false, otherwise set the answer into
508 VALUE. */
510 bool
511 chrec_is_positive (tree chrec, bool *value)
513 bool value0, value1, value2;
514 tree type, end_value, nb_iter;
516 switch (TREE_CODE (chrec))
518 case POLYNOMIAL_CHREC:
519 if (!chrec_is_positive (CHREC_LEFT (chrec), &value0)
520 || !chrec_is_positive (CHREC_RIGHT (chrec), &value1))
521 return false;
523 /* FIXME -- overflows. */
524 if (value0 == value1)
526 *value = value0;
527 return true;
530 /* Otherwise the chrec is under the form: "{-197, +, 2}_1",
531 and the proof consists in showing that the sign never
532 changes during the execution of the loop, from 0 to
533 loop->nb_iterations. */
534 if (!evolution_function_is_affine_p (chrec))
535 return false;
537 nb_iter = number_of_iterations_in_loop
538 (current_loops->parray[CHREC_VARIABLE (chrec)]);
540 if (chrec_contains_undetermined (nb_iter))
541 return false;
543 type = chrec_type (nb_iter);
544 nb_iter = chrec_fold_minus (type, nb_iter, build_int_cst (type, 1));
546 #if 0
547 /* TODO -- If the test is after the exit, we may decrease the number of
548 iterations by one. */
549 if (after_exit)
550 nb_iter = chrec_fold_minus (type, nb_iter, build_int_cst (type, 1));
551 #endif
553 end_value = chrec_apply (CHREC_VARIABLE (chrec), chrec, nb_iter);
555 if (!chrec_is_positive (end_value, &value2))
556 return false;
558 *value = value0;
559 return value0 == value1;
561 case INTEGER_CST:
562 *value = (tree_int_cst_sgn (chrec) == 1);
563 return true;
565 default:
566 return false;
570 /* Associate CHREC to SCALAR. */
572 static void
573 set_scalar_evolution (tree scalar, tree chrec)
575 tree *scalar_info;
577 if (TREE_CODE (scalar) != SSA_NAME)
578 return;
580 scalar_info = find_var_scev_info (scalar);
582 if (dump_file)
584 if (dump_flags & TDF_DETAILS)
586 fprintf (dump_file, "(set_scalar_evolution \n");
587 fprintf (dump_file, " (scalar = ");
588 print_generic_expr (dump_file, scalar, 0);
589 fprintf (dump_file, ")\n (scalar_evolution = ");
590 print_generic_expr (dump_file, chrec, 0);
591 fprintf (dump_file, "))\n");
593 if (dump_flags & TDF_STATS)
594 nb_set_scev++;
597 *scalar_info = chrec;
600 /* Retrieve the chrec associated to SCALAR in the LOOP. */
602 static tree
603 get_scalar_evolution (tree scalar)
605 tree res;
607 if (dump_file)
609 if (dump_flags & TDF_DETAILS)
611 fprintf (dump_file, "(get_scalar_evolution \n");
612 fprintf (dump_file, " (scalar = ");
613 print_generic_expr (dump_file, scalar, 0);
614 fprintf (dump_file, ")\n");
616 if (dump_flags & TDF_STATS)
617 nb_get_scev++;
620 switch (TREE_CODE (scalar))
622 case SSA_NAME:
623 res = *find_var_scev_info (scalar);
624 break;
626 case REAL_CST:
627 case INTEGER_CST:
628 res = scalar;
629 break;
631 default:
632 res = chrec_not_analyzed_yet;
633 break;
636 if (dump_file && (dump_flags & TDF_DETAILS))
638 fprintf (dump_file, " (scalar_evolution = ");
639 print_generic_expr (dump_file, res, 0);
640 fprintf (dump_file, "))\n");
643 return res;
646 /* Helper function for add_to_evolution. Returns the evolution
647 function for an assignment of the form "a = b + c", where "a" and
648 "b" are on the strongly connected component. CHREC_BEFORE is the
649 information that we already have collected up to this point.
650 TO_ADD is the evolution of "c".
652 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
653 evolution the expression TO_ADD, otherwise construct an evolution
654 part for this loop. */
656 static tree
657 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
658 tree at_stmt)
660 tree type, left, right;
662 switch (TREE_CODE (chrec_before))
664 case POLYNOMIAL_CHREC:
665 if (CHREC_VARIABLE (chrec_before) <= loop_nb)
667 unsigned var;
669 type = chrec_type (chrec_before);
671 /* When there is no evolution part in this loop, build it. */
672 if (CHREC_VARIABLE (chrec_before) < loop_nb)
674 var = loop_nb;
675 left = chrec_before;
676 right = SCALAR_FLOAT_TYPE_P (type)
677 ? build_real (type, dconst0)
678 : build_int_cst (type, 0);
680 else
682 var = CHREC_VARIABLE (chrec_before);
683 left = CHREC_LEFT (chrec_before);
684 right = CHREC_RIGHT (chrec_before);
687 to_add = chrec_convert (type, to_add, at_stmt);
688 right = chrec_convert (type, right, at_stmt);
689 right = chrec_fold_plus (type, right, to_add);
690 return build_polynomial_chrec (var, left, right);
692 else
694 /* Search the evolution in LOOP_NB. */
695 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
696 to_add, at_stmt);
697 right = CHREC_RIGHT (chrec_before);
698 right = chrec_convert (chrec_type (left), right, at_stmt);
699 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
700 left, right);
703 default:
704 /* These nodes do not depend on a loop. */
705 if (chrec_before == chrec_dont_know)
706 return chrec_dont_know;
708 left = chrec_before;
709 right = chrec_convert (chrec_type (left), to_add, at_stmt);
710 return build_polynomial_chrec (loop_nb, left, right);
714 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
715 of LOOP_NB.
717 Description (provided for completeness, for those who read code in
718 a plane, and for my poor 62 bytes brain that would have forgotten
719 all this in the next two or three months):
721 The algorithm of translation of programs from the SSA representation
722 into the chrecs syntax is based on a pattern matching. After having
723 reconstructed the overall tree expression for a loop, there are only
724 two cases that can arise:
726 1. a = loop-phi (init, a + expr)
727 2. a = loop-phi (init, expr)
729 where EXPR is either a scalar constant with respect to the analyzed
730 loop (this is a degree 0 polynomial), or an expression containing
731 other loop-phi definitions (these are higher degree polynomials).
733 Examples:
736 | init = ...
737 | loop_1
738 | a = phi (init, a + 5)
739 | endloop
742 | inita = ...
743 | initb = ...
744 | loop_1
745 | a = phi (inita, 2 * b + 3)
746 | b = phi (initb, b + 1)
747 | endloop
749 For the first case, the semantics of the SSA representation is:
751 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
753 that is, there is a loop index "x" that determines the scalar value
754 of the variable during the loop execution. During the first
755 iteration, the value is that of the initial condition INIT, while
756 during the subsequent iterations, it is the sum of the initial
757 condition with the sum of all the values of EXPR from the initial
758 iteration to the before last considered iteration.
760 For the second case, the semantics of the SSA program is:
762 | a (x) = init, if x = 0;
763 | expr (x - 1), otherwise.
765 The second case corresponds to the PEELED_CHREC, whose syntax is
766 close to the syntax of a loop-phi-node:
768 | phi (init, expr) vs. (init, expr)_x
770 The proof of the translation algorithm for the first case is a
771 proof by structural induction based on the degree of EXPR.
773 Degree 0:
774 When EXPR is a constant with respect to the analyzed loop, or in
775 other words when EXPR is a polynomial of degree 0, the evolution of
776 the variable A in the loop is an affine function with an initial
777 condition INIT, and a step EXPR. In order to show this, we start
778 from the semantics of the SSA representation:
780 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
782 and since "expr (j)" is a constant with respect to "j",
784 f (x) = init + x * expr
786 Finally, based on the semantics of the pure sum chrecs, by
787 identification we get the corresponding chrecs syntax:
789 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
790 f (x) -> {init, +, expr}_x
792 Higher degree:
793 Suppose that EXPR is a polynomial of degree N with respect to the
794 analyzed loop_x for which we have already determined that it is
795 written under the chrecs syntax:
797 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
799 We start from the semantics of the SSA program:
801 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
803 | f (x) = init + \sum_{j = 0}^{x - 1}
804 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
806 | f (x) = init + \sum_{j = 0}^{x - 1}
807 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
809 | f (x) = init + \sum_{k = 0}^{n - 1}
810 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
812 | f (x) = init + \sum_{k = 0}^{n - 1}
813 | (b_k * \binom{x}{k + 1})
815 | f (x) = init + b_0 * \binom{x}{1} + ...
816 | + b_{n-1} * \binom{x}{n}
818 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
819 | + b_{n-1} * \binom{x}{n}
822 And finally from the definition of the chrecs syntax, we identify:
823 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
825 This shows the mechanism that stands behind the add_to_evolution
826 function. An important point is that the use of symbolic
827 parameters avoids the need of an analysis schedule.
829 Example:
831 | inita = ...
832 | initb = ...
833 | loop_1
834 | a = phi (inita, a + 2 + b)
835 | b = phi (initb, b + 1)
836 | endloop
838 When analyzing "a", the algorithm keeps "b" symbolically:
840 | a -> {inita, +, 2 + b}_1
842 Then, after instantiation, the analyzer ends on the evolution:
844 | a -> {inita, +, 2 + initb, +, 1}_1
848 static tree
849 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
850 tree to_add, tree at_stmt)
852 tree type = chrec_type (to_add);
853 tree res = NULL_TREE;
855 if (to_add == NULL_TREE)
856 return chrec_before;
858 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
859 instantiated at this point. */
860 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
861 /* This should not happen. */
862 return chrec_dont_know;
864 if (dump_file && (dump_flags & TDF_DETAILS))
866 fprintf (dump_file, "(add_to_evolution \n");
867 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
868 fprintf (dump_file, " (chrec_before = ");
869 print_generic_expr (dump_file, chrec_before, 0);
870 fprintf (dump_file, ")\n (to_add = ");
871 print_generic_expr (dump_file, to_add, 0);
872 fprintf (dump_file, ")\n");
875 if (code == MINUS_EXPR)
876 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
877 ? build_real (type, dconstm1)
878 : build_int_cst_type (type, -1));
880 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
882 if (dump_file && (dump_flags & TDF_DETAILS))
884 fprintf (dump_file, " (res = ");
885 print_generic_expr (dump_file, res, 0);
886 fprintf (dump_file, "))\n");
889 return res;
892 /* Helper function. */
894 static inline tree
895 set_nb_iterations_in_loop (struct loop *loop,
896 tree res)
898 tree type = chrec_type (res);
900 res = chrec_fold_plus (type, res, build_int_cst (type, 1));
902 /* FIXME HWI: However we want to store one iteration less than the
903 count of the loop in order to be compatible with the other
904 nb_iter computations in loop-iv. This also allows the
905 representation of nb_iters that are equal to MAX_INT. */
906 if (TREE_CODE (res) == INTEGER_CST
907 && (TREE_INT_CST_LOW (res) == 0
908 || TREE_OVERFLOW (res)))
909 res = chrec_dont_know;
911 if (dump_file && (dump_flags & TDF_DETAILS))
913 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
914 print_generic_expr (dump_file, res, 0);
915 fprintf (dump_file, "))\n");
918 loop->nb_iterations = res;
919 return res;
924 /* This section selects the loops that will be good candidates for the
925 scalar evolution analysis. For the moment, greedily select all the
926 loop nests we could analyze. */
928 /* Return true when it is possible to analyze the condition expression
929 EXPR. */
931 static bool
932 analyzable_condition (tree expr)
934 tree condition;
936 if (TREE_CODE (expr) != COND_EXPR)
937 return false;
939 condition = TREE_OPERAND (expr, 0);
941 switch (TREE_CODE (condition))
943 case SSA_NAME:
944 return true;
946 case LT_EXPR:
947 case LE_EXPR:
948 case GT_EXPR:
949 case GE_EXPR:
950 case EQ_EXPR:
951 case NE_EXPR:
952 return true;
954 default:
955 return false;
958 return false;
961 /* For a loop with a single exit edge, return the COND_EXPR that
962 guards the exit edge. If the expression is too difficult to
963 analyze, then give up. */
965 tree
966 get_loop_exit_condition (struct loop *loop)
968 tree res = NULL_TREE;
969 edge exit_edge = loop->single_exit;
972 if (dump_file && (dump_flags & TDF_DETAILS))
973 fprintf (dump_file, "(get_loop_exit_condition \n ");
975 if (exit_edge)
977 tree expr;
979 expr = last_stmt (exit_edge->src);
980 if (analyzable_condition (expr))
981 res = expr;
984 if (dump_file && (dump_flags & TDF_DETAILS))
986 print_generic_expr (dump_file, res, 0);
987 fprintf (dump_file, ")\n");
990 return res;
993 /* Recursively determine and enqueue the exit conditions for a loop. */
995 static void
996 get_exit_conditions_rec (struct loop *loop,
997 VEC(tree,heap) **exit_conditions)
999 if (!loop)
1000 return;
1002 /* Recurse on the inner loops, then on the next (sibling) loops. */
1003 get_exit_conditions_rec (loop->inner, exit_conditions);
1004 get_exit_conditions_rec (loop->next, exit_conditions);
1006 if (loop->single_exit)
1008 tree loop_condition = get_loop_exit_condition (loop);
1010 if (loop_condition)
1011 VEC_safe_push (tree, heap, *exit_conditions, loop_condition);
1015 /* Select the candidate loop nests for the analysis. This function
1016 initializes the EXIT_CONDITIONS array. */
1018 static void
1019 select_loops_exit_conditions (struct loops *loops,
1020 VEC(tree,heap) **exit_conditions)
1022 struct loop *function_body = loops->parray[0];
1024 get_exit_conditions_rec (function_body->inner, exit_conditions);
1028 /* Depth first search algorithm. */
1030 typedef enum t_bool {
1031 t_false,
1032 t_true,
1033 t_dont_know
1034 } t_bool;
1037 static t_bool follow_ssa_edge (struct loop *loop, tree, tree, tree *, int);
1039 /* Follow the ssa edge into the right hand side RHS of an assignment.
1040 Return true if the strongly connected component has been found. */
1042 static t_bool
1043 follow_ssa_edge_in_rhs (struct loop *loop, tree at_stmt, tree rhs,
1044 tree halting_phi, tree *evolution_of_loop, int limit)
1046 t_bool res = t_false;
1047 tree rhs0, rhs1;
1048 tree type_rhs = TREE_TYPE (rhs);
1049 tree evol;
1051 /* The RHS is one of the following cases:
1052 - an SSA_NAME,
1053 - an INTEGER_CST,
1054 - a PLUS_EXPR,
1055 - a MINUS_EXPR,
1056 - an ASSERT_EXPR,
1057 - other cases are not yet handled. */
1058 switch (TREE_CODE (rhs))
1060 case NOP_EXPR:
1061 /* This assignment is under the form "a_1 = (cast) rhs. */
1062 res = follow_ssa_edge_in_rhs (loop, at_stmt, TREE_OPERAND (rhs, 0),
1063 halting_phi, evolution_of_loop, limit);
1064 *evolution_of_loop = chrec_convert (TREE_TYPE (rhs),
1065 *evolution_of_loop, at_stmt);
1066 break;
1068 case INTEGER_CST:
1069 /* This assignment is under the form "a_1 = 7". */
1070 res = t_false;
1071 break;
1073 case SSA_NAME:
1074 /* This assignment is under the form: "a_1 = b_2". */
1075 res = follow_ssa_edge
1076 (loop, SSA_NAME_DEF_STMT (rhs), halting_phi, evolution_of_loop, limit);
1077 break;
1079 case PLUS_EXPR:
1080 /* This case is under the form "rhs0 + rhs1". */
1081 rhs0 = TREE_OPERAND (rhs, 0);
1082 rhs1 = TREE_OPERAND (rhs, 1);
1083 STRIP_TYPE_NOPS (rhs0);
1084 STRIP_TYPE_NOPS (rhs1);
1086 if (TREE_CODE (rhs0) == SSA_NAME)
1088 if (TREE_CODE (rhs1) == SSA_NAME)
1090 /* Match an assignment under the form:
1091 "a = b + c". */
1092 evol = *evolution_of_loop;
1093 res = follow_ssa_edge
1094 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1095 &evol, limit);
1097 if (res == t_true)
1098 *evolution_of_loop = add_to_evolution
1099 (loop->num,
1100 chrec_convert (type_rhs, evol, at_stmt),
1101 PLUS_EXPR, rhs1, at_stmt);
1103 else if (res == t_false)
1105 res = follow_ssa_edge
1106 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1107 evolution_of_loop, limit);
1109 if (res == t_true)
1110 *evolution_of_loop = add_to_evolution
1111 (loop->num,
1112 chrec_convert (type_rhs, *evolution_of_loop, at_stmt),
1113 PLUS_EXPR, rhs0, at_stmt);
1115 else if (res == t_dont_know)
1116 *evolution_of_loop = chrec_dont_know;
1119 else if (res == t_dont_know)
1120 *evolution_of_loop = chrec_dont_know;
1123 else
1125 /* Match an assignment under the form:
1126 "a = b + ...". */
1127 res = follow_ssa_edge
1128 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1129 evolution_of_loop, limit);
1130 if (res == t_true)
1131 *evolution_of_loop = add_to_evolution
1132 (loop->num, chrec_convert (type_rhs, *evolution_of_loop,
1133 at_stmt),
1134 PLUS_EXPR, rhs1, at_stmt);
1136 else if (res == t_dont_know)
1137 *evolution_of_loop = chrec_dont_know;
1141 else if (TREE_CODE (rhs1) == SSA_NAME)
1143 /* Match an assignment under the form:
1144 "a = ... + c". */
1145 res = follow_ssa_edge
1146 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1147 evolution_of_loop, limit);
1148 if (res == t_true)
1149 *evolution_of_loop = add_to_evolution
1150 (loop->num, chrec_convert (type_rhs, *evolution_of_loop,
1151 at_stmt),
1152 PLUS_EXPR, rhs0, at_stmt);
1154 else if (res == t_dont_know)
1155 *evolution_of_loop = chrec_dont_know;
1158 else
1159 /* Otherwise, match an assignment under the form:
1160 "a = ... + ...". */
1161 /* And there is nothing to do. */
1162 res = t_false;
1164 break;
1166 case MINUS_EXPR:
1167 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1168 rhs0 = TREE_OPERAND (rhs, 0);
1169 rhs1 = TREE_OPERAND (rhs, 1);
1170 STRIP_TYPE_NOPS (rhs0);
1171 STRIP_TYPE_NOPS (rhs1);
1173 if (TREE_CODE (rhs0) == SSA_NAME)
1175 /* Match an assignment under the form:
1176 "a = b - ...". */
1177 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1178 evolution_of_loop, limit);
1179 if (res == t_true)
1180 *evolution_of_loop = add_to_evolution
1181 (loop->num, chrec_convert (type_rhs, *evolution_of_loop, at_stmt),
1182 MINUS_EXPR, rhs1, at_stmt);
1184 else if (res == t_dont_know)
1185 *evolution_of_loop = chrec_dont_know;
1187 else
1188 /* Otherwise, match an assignment under the form:
1189 "a = ... - ...". */
1190 /* And there is nothing to do. */
1191 res = t_false;
1193 break;
1195 case ASSERT_EXPR:
1197 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1198 It must be handled as a copy assignment of the form a_1 = a_2. */
1199 tree op0 = ASSERT_EXPR_VAR (rhs);
1200 if (TREE_CODE (op0) == SSA_NAME)
1201 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (op0),
1202 halting_phi, evolution_of_loop, limit);
1203 else
1204 res = t_false;
1205 break;
1209 default:
1210 res = t_false;
1211 break;
1214 return res;
1217 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1219 static bool
1220 backedge_phi_arg_p (tree phi, int i)
1222 edge e = PHI_ARG_EDGE (phi, i);
1224 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1225 about updating it anywhere, and this should work as well most of the
1226 time. */
1227 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1228 return true;
1230 return false;
1233 /* Helper function for one branch of the condition-phi-node. Return
1234 true if the strongly connected component has been found following
1235 this path. */
1237 static inline t_bool
1238 follow_ssa_edge_in_condition_phi_branch (int i,
1239 struct loop *loop,
1240 tree condition_phi,
1241 tree halting_phi,
1242 tree *evolution_of_branch,
1243 tree init_cond, int limit)
1245 tree branch = PHI_ARG_DEF (condition_phi, i);
1246 *evolution_of_branch = chrec_dont_know;
1248 /* Do not follow back edges (they must belong to an irreducible loop, which
1249 we really do not want to worry about). */
1250 if (backedge_phi_arg_p (condition_phi, i))
1251 return t_false;
1253 if (TREE_CODE (branch) == SSA_NAME)
1255 *evolution_of_branch = init_cond;
1256 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1257 evolution_of_branch, limit);
1260 /* This case occurs when one of the condition branches sets
1261 the variable to a constant: i.e. a phi-node like
1262 "a_2 = PHI <a_7(5), 2(6)>;".
1264 FIXME: This case have to be refined correctly:
1265 in some cases it is possible to say something better than
1266 chrec_dont_know, for example using a wrap-around notation. */
1267 return t_false;
1270 /* This function merges the branches of a condition-phi-node in a
1271 loop. */
1273 static t_bool
1274 follow_ssa_edge_in_condition_phi (struct loop *loop,
1275 tree condition_phi,
1276 tree halting_phi,
1277 tree *evolution_of_loop, int limit)
1279 int i;
1280 tree init = *evolution_of_loop;
1281 tree evolution_of_branch;
1282 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1283 halting_phi,
1284 &evolution_of_branch,
1285 init, limit);
1286 if (res == t_false || res == t_dont_know)
1287 return res;
1289 *evolution_of_loop = evolution_of_branch;
1291 for (i = 1; i < PHI_NUM_ARGS (condition_phi); i++)
1293 /* Quickly give up when the evolution of one of the branches is
1294 not known. */
1295 if (*evolution_of_loop == chrec_dont_know)
1296 return t_true;
1298 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1299 halting_phi,
1300 &evolution_of_branch,
1301 init, limit);
1302 if (res == t_false || res == t_dont_know)
1303 return res;
1305 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1306 evolution_of_branch);
1309 return t_true;
1312 /* Follow an SSA edge in an inner loop. It computes the overall
1313 effect of the loop, and following the symbolic initial conditions,
1314 it follows the edges in the parent loop. The inner loop is
1315 considered as a single statement. */
1317 static t_bool
1318 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1319 tree loop_phi_node,
1320 tree halting_phi,
1321 tree *evolution_of_loop, int limit)
1323 struct loop *loop = loop_containing_stmt (loop_phi_node);
1324 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1326 /* Sometimes, the inner loop is too difficult to analyze, and the
1327 result of the analysis is a symbolic parameter. */
1328 if (ev == PHI_RESULT (loop_phi_node))
1330 t_bool res = t_false;
1331 int i;
1333 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1335 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1336 basic_block bb;
1338 /* Follow the edges that exit the inner loop. */
1339 bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1340 if (!flow_bb_inside_loop_p (loop, bb))
1341 res = follow_ssa_edge_in_rhs (outer_loop, loop_phi_node,
1342 arg, halting_phi,
1343 evolution_of_loop, limit);
1344 if (res == t_true)
1345 break;
1348 /* If the path crosses this loop-phi, give up. */
1349 if (res == t_true)
1350 *evolution_of_loop = chrec_dont_know;
1352 return res;
1355 /* Otherwise, compute the overall effect of the inner loop. */
1356 ev = compute_overall_effect_of_inner_loop (loop, ev);
1357 return follow_ssa_edge_in_rhs (outer_loop, loop_phi_node, ev, halting_phi,
1358 evolution_of_loop, limit);
1361 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1362 path that is analyzed on the return walk. */
1364 static t_bool
1365 follow_ssa_edge (struct loop *loop, tree def, tree halting_phi,
1366 tree *evolution_of_loop, int limit)
1368 struct loop *def_loop;
1370 if (TREE_CODE (def) == NOP_EXPR)
1371 return t_false;
1373 /* Give up if the path is longer than the MAX that we allow. */
1374 if (limit++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
1375 return t_dont_know;
1377 def_loop = loop_containing_stmt (def);
1379 switch (TREE_CODE (def))
1381 case PHI_NODE:
1382 if (!loop_phi_node_p (def))
1383 /* DEF is a condition-phi-node. Follow the branches, and
1384 record their evolutions. Finally, merge the collected
1385 information and set the approximation to the main
1386 variable. */
1387 return follow_ssa_edge_in_condition_phi
1388 (loop, def, halting_phi, evolution_of_loop, limit);
1390 /* When the analyzed phi is the halting_phi, the
1391 depth-first search is over: we have found a path from
1392 the halting_phi to itself in the loop. */
1393 if (def == halting_phi)
1394 return t_true;
1396 /* Otherwise, the evolution of the HALTING_PHI depends
1397 on the evolution of another loop-phi-node, i.e. the
1398 evolution function is a higher degree polynomial. */
1399 if (def_loop == loop)
1400 return t_false;
1402 /* Inner loop. */
1403 if (flow_loop_nested_p (loop, def_loop))
1404 return follow_ssa_edge_inner_loop_phi
1405 (loop, def, halting_phi, evolution_of_loop, limit);
1407 /* Outer loop. */
1408 return t_false;
1410 case MODIFY_EXPR:
1411 return follow_ssa_edge_in_rhs (loop, def,
1412 TREE_OPERAND (def, 1),
1413 halting_phi,
1414 evolution_of_loop, limit);
1416 default:
1417 /* At this level of abstraction, the program is just a set
1418 of MODIFY_EXPRs and PHI_NODEs. In principle there is no
1419 other node to be handled. */
1420 return t_false;
1426 /* Given a LOOP_PHI_NODE, this function determines the evolution
1427 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1429 static tree
1430 analyze_evolution_in_loop (tree loop_phi_node,
1431 tree init_cond)
1433 int i;
1434 tree evolution_function = chrec_not_analyzed_yet;
1435 struct loop *loop = loop_containing_stmt (loop_phi_node);
1436 basic_block bb;
1438 if (dump_file && (dump_flags & TDF_DETAILS))
1440 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1441 fprintf (dump_file, " (loop_phi_node = ");
1442 print_generic_expr (dump_file, loop_phi_node, 0);
1443 fprintf (dump_file, ")\n");
1446 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1448 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1449 tree ssa_chain, ev_fn;
1450 t_bool res;
1452 /* Select the edges that enter the loop body. */
1453 bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1454 if (!flow_bb_inside_loop_p (loop, bb))
1455 continue;
1457 if (TREE_CODE (arg) == SSA_NAME)
1459 ssa_chain = SSA_NAME_DEF_STMT (arg);
1461 /* Pass in the initial condition to the follow edge function. */
1462 ev_fn = init_cond;
1463 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1465 else
1466 res = t_false;
1468 /* When it is impossible to go back on the same
1469 loop_phi_node by following the ssa edges, the
1470 evolution is represented by a peeled chrec, i.e. the
1471 first iteration, EV_FN has the value INIT_COND, then
1472 all the other iterations it has the value of ARG.
1473 For the moment, PEELED_CHREC nodes are not built. */
1474 if (res != t_true)
1475 ev_fn = chrec_dont_know;
1477 /* When there are multiple back edges of the loop (which in fact never
1478 happens currently, but nevertheless), merge their evolutions. */
1479 evolution_function = chrec_merge (evolution_function, ev_fn);
1482 if (dump_file && (dump_flags & TDF_DETAILS))
1484 fprintf (dump_file, " (evolution_function = ");
1485 print_generic_expr (dump_file, evolution_function, 0);
1486 fprintf (dump_file, "))\n");
1489 return evolution_function;
1492 /* Given a loop-phi-node, return the initial conditions of the
1493 variable on entry of the loop. When the CCP has propagated
1494 constants into the loop-phi-node, the initial condition is
1495 instantiated, otherwise the initial condition is kept symbolic.
1496 This analyzer does not analyze the evolution outside the current
1497 loop, and leaves this task to the on-demand tree reconstructor. */
1499 static tree
1500 analyze_initial_condition (tree loop_phi_node)
1502 int i;
1503 tree init_cond = chrec_not_analyzed_yet;
1504 struct loop *loop = bb_for_stmt (loop_phi_node)->loop_father;
1506 if (dump_file && (dump_flags & TDF_DETAILS))
1508 fprintf (dump_file, "(analyze_initial_condition \n");
1509 fprintf (dump_file, " (loop_phi_node = \n");
1510 print_generic_expr (dump_file, loop_phi_node, 0);
1511 fprintf (dump_file, ")\n");
1514 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1516 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1517 basic_block bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1519 /* When the branch is oriented to the loop's body, it does
1520 not contribute to the initial condition. */
1521 if (flow_bb_inside_loop_p (loop, bb))
1522 continue;
1524 if (init_cond == chrec_not_analyzed_yet)
1526 init_cond = branch;
1527 continue;
1530 if (TREE_CODE (branch) == SSA_NAME)
1532 init_cond = chrec_dont_know;
1533 break;
1536 init_cond = chrec_merge (init_cond, branch);
1539 /* Ooops -- a loop without an entry??? */
1540 if (init_cond == chrec_not_analyzed_yet)
1541 init_cond = chrec_dont_know;
1543 if (dump_file && (dump_flags & TDF_DETAILS))
1545 fprintf (dump_file, " (init_cond = ");
1546 print_generic_expr (dump_file, init_cond, 0);
1547 fprintf (dump_file, "))\n");
1550 return init_cond;
1553 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1555 static tree
1556 interpret_loop_phi (struct loop *loop, tree loop_phi_node)
1558 tree res;
1559 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1560 tree init_cond;
1562 if (phi_loop != loop)
1564 struct loop *subloop;
1565 tree evolution_fn = analyze_scalar_evolution
1566 (phi_loop, PHI_RESULT (loop_phi_node));
1568 /* Dive one level deeper. */
1569 subloop = superloop_at_depth (phi_loop, loop->depth + 1);
1571 /* Interpret the subloop. */
1572 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1573 return res;
1576 /* Otherwise really interpret the loop phi. */
1577 init_cond = analyze_initial_condition (loop_phi_node);
1578 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1580 return res;
1583 /* This function merges the branches of a condition-phi-node,
1584 contained in the outermost loop, and whose arguments are already
1585 analyzed. */
1587 static tree
1588 interpret_condition_phi (struct loop *loop, tree condition_phi)
1590 int i;
1591 tree res = chrec_not_analyzed_yet;
1593 for (i = 0; i < PHI_NUM_ARGS (condition_phi); i++)
1595 tree branch_chrec;
1597 if (backedge_phi_arg_p (condition_phi, i))
1599 res = chrec_dont_know;
1600 break;
1603 branch_chrec = analyze_scalar_evolution
1604 (loop, PHI_ARG_DEF (condition_phi, i));
1606 res = chrec_merge (res, branch_chrec);
1609 return res;
1612 /* Interpret the right hand side of a modify_expr OPND1. If we didn't
1613 analyze this node before, follow the definitions until ending
1614 either on an analyzed modify_expr, or on a loop-phi-node. On the
1615 return path, this function propagates evolutions (ala constant copy
1616 propagation). OPND1 is not a GIMPLE expression because we could
1617 analyze the effect of an inner loop: see interpret_loop_phi. */
1619 static tree
1620 interpret_rhs_modify_expr (struct loop *loop, tree at_stmt,
1621 tree opnd1, tree type)
1623 tree res, opnd10, opnd11, chrec10, chrec11;
1625 if (is_gimple_min_invariant (opnd1))
1626 return chrec_convert (type, opnd1, at_stmt);
1628 switch (TREE_CODE (opnd1))
1630 case PLUS_EXPR:
1631 opnd10 = TREE_OPERAND (opnd1, 0);
1632 opnd11 = TREE_OPERAND (opnd1, 1);
1633 chrec10 = analyze_scalar_evolution (loop, opnd10);
1634 chrec11 = analyze_scalar_evolution (loop, opnd11);
1635 chrec10 = chrec_convert (type, chrec10, at_stmt);
1636 chrec11 = chrec_convert (type, chrec11, at_stmt);
1637 res = chrec_fold_plus (type, chrec10, chrec11);
1638 break;
1640 case MINUS_EXPR:
1641 opnd10 = TREE_OPERAND (opnd1, 0);
1642 opnd11 = TREE_OPERAND (opnd1, 1);
1643 chrec10 = analyze_scalar_evolution (loop, opnd10);
1644 chrec11 = analyze_scalar_evolution (loop, opnd11);
1645 chrec10 = chrec_convert (type, chrec10, at_stmt);
1646 chrec11 = chrec_convert (type, chrec11, at_stmt);
1647 res = chrec_fold_minus (type, chrec10, chrec11);
1648 break;
1650 case NEGATE_EXPR:
1651 opnd10 = TREE_OPERAND (opnd1, 0);
1652 chrec10 = analyze_scalar_evolution (loop, opnd10);
1653 chrec10 = chrec_convert (type, chrec10, at_stmt);
1654 /* TYPE may be integer, real or complex, so use fold_convert. */
1655 res = chrec_fold_multiply (type, chrec10,
1656 fold_convert (type, integer_minus_one_node));
1657 break;
1659 case MULT_EXPR:
1660 opnd10 = TREE_OPERAND (opnd1, 0);
1661 opnd11 = TREE_OPERAND (opnd1, 1);
1662 chrec10 = analyze_scalar_evolution (loop, opnd10);
1663 chrec11 = analyze_scalar_evolution (loop, opnd11);
1664 chrec10 = chrec_convert (type, chrec10, at_stmt);
1665 chrec11 = chrec_convert (type, chrec11, at_stmt);
1666 res = chrec_fold_multiply (type, chrec10, chrec11);
1667 break;
1669 case SSA_NAME:
1670 res = chrec_convert (type, analyze_scalar_evolution (loop, opnd1),
1671 at_stmt);
1672 break;
1674 case ASSERT_EXPR:
1675 opnd10 = ASSERT_EXPR_VAR (opnd1);
1676 res = chrec_convert (type, analyze_scalar_evolution (loop, opnd10),
1677 at_stmt);
1678 break;
1680 case NOP_EXPR:
1681 case CONVERT_EXPR:
1682 opnd10 = TREE_OPERAND (opnd1, 0);
1683 chrec10 = analyze_scalar_evolution (loop, opnd10);
1684 res = chrec_convert (type, chrec10, at_stmt);
1685 break;
1687 default:
1688 res = chrec_dont_know;
1689 break;
1692 return res;
1697 /* This section contains all the entry points:
1698 - number_of_iterations_in_loop,
1699 - analyze_scalar_evolution,
1700 - instantiate_parameters.
1703 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1704 common ancestor of DEF_LOOP and USE_LOOP. */
1706 static tree
1707 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1708 struct loop *def_loop,
1709 tree ev)
1711 tree res;
1712 if (def_loop == wrto_loop)
1713 return ev;
1715 def_loop = superloop_at_depth (def_loop, wrto_loop->depth + 1);
1716 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1718 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1721 /* Helper recursive function. */
1723 static tree
1724 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1726 tree def, type = TREE_TYPE (var);
1727 basic_block bb;
1728 struct loop *def_loop;
1730 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1731 return chrec_dont_know;
1733 if (TREE_CODE (var) != SSA_NAME)
1734 return interpret_rhs_modify_expr (loop, NULL_TREE, var, type);
1736 def = SSA_NAME_DEF_STMT (var);
1737 bb = bb_for_stmt (def);
1738 def_loop = bb ? bb->loop_father : NULL;
1740 if (bb == NULL
1741 || !flow_bb_inside_loop_p (loop, bb))
1743 /* Keep the symbolic form. */
1744 res = var;
1745 goto set_and_end;
1748 if (res != chrec_not_analyzed_yet)
1750 if (loop != bb->loop_father)
1751 res = compute_scalar_evolution_in_loop
1752 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1754 goto set_and_end;
1757 if (loop != def_loop)
1759 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1760 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1762 goto set_and_end;
1765 switch (TREE_CODE (def))
1767 case MODIFY_EXPR:
1768 res = interpret_rhs_modify_expr (loop, def, TREE_OPERAND (def, 1), type);
1769 break;
1771 case PHI_NODE:
1772 if (loop_phi_node_p (def))
1773 res = interpret_loop_phi (loop, def);
1774 else
1775 res = interpret_condition_phi (loop, def);
1776 break;
1778 default:
1779 res = chrec_dont_know;
1780 break;
1783 set_and_end:
1785 /* Keep the symbolic form. */
1786 if (res == chrec_dont_know)
1787 res = var;
1789 if (loop == def_loop)
1790 set_scalar_evolution (var, res);
1792 return res;
1795 /* Entry point for the scalar evolution analyzer.
1796 Analyzes and returns the scalar evolution of the ssa_name VAR.
1797 LOOP_NB is the identifier number of the loop in which the variable
1798 is used.
1800 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
1801 pointer to the statement that uses this variable, in order to
1802 determine the evolution function of the variable, use the following
1803 calls:
1805 unsigned loop_nb = loop_containing_stmt (stmt)->num;
1806 tree chrec_with_symbols = analyze_scalar_evolution (loop_nb, var);
1807 tree chrec_instantiated = instantiate_parameters
1808 (loop_nb, chrec_with_symbols);
1811 tree
1812 analyze_scalar_evolution (struct loop *loop, tree var)
1814 tree res;
1816 if (dump_file && (dump_flags & TDF_DETAILS))
1818 fprintf (dump_file, "(analyze_scalar_evolution \n");
1819 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
1820 fprintf (dump_file, " (scalar = ");
1821 print_generic_expr (dump_file, var, 0);
1822 fprintf (dump_file, ")\n");
1825 res = analyze_scalar_evolution_1 (loop, var, get_scalar_evolution (var));
1827 if (TREE_CODE (var) == SSA_NAME && res == chrec_dont_know)
1828 res = var;
1830 if (dump_file && (dump_flags & TDF_DETAILS))
1831 fprintf (dump_file, ")\n");
1833 return res;
1836 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
1837 WRTO_LOOP (which should be a superloop of both USE_LOOP and definition
1838 of VERSION).
1840 FOLDED_CASTS is set to true if resolve_mixers used
1841 chrec_convert_aggressive (TODO -- not really, we are way too conservative
1842 at the moment in order to keep things simple). */
1844 static tree
1845 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
1846 tree version, bool *folded_casts)
1848 bool val = false;
1849 tree ev = version, tmp;
1851 if (folded_casts)
1852 *folded_casts = false;
1853 while (1)
1855 tmp = analyze_scalar_evolution (use_loop, ev);
1856 ev = resolve_mixers (use_loop, tmp);
1858 if (folded_casts && tmp != ev)
1859 *folded_casts = true;
1861 if (use_loop == wrto_loop)
1862 return ev;
1864 /* If the value of the use changes in the inner loop, we cannot express
1865 its value in the outer loop (we might try to return interval chrec,
1866 but we do not have a user for it anyway) */
1867 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
1868 || !val)
1869 return chrec_dont_know;
1871 use_loop = use_loop->outer;
1875 /* Returns instantiated value for VERSION in CACHE. */
1877 static tree
1878 get_instantiated_value (htab_t cache, tree version)
1880 struct scev_info_str *info, pattern;
1882 pattern.var = version;
1883 info = (struct scev_info_str *) htab_find (cache, &pattern);
1885 if (info)
1886 return info->chrec;
1887 else
1888 return NULL_TREE;
1891 /* Sets instantiated value for VERSION to VAL in CACHE. */
1893 static void
1894 set_instantiated_value (htab_t cache, tree version, tree val)
1896 struct scev_info_str *info, pattern;
1897 PTR *slot;
1899 pattern.var = version;
1900 slot = htab_find_slot (cache, &pattern, INSERT);
1902 if (!*slot)
1903 *slot = new_scev_info_str (version);
1904 info = (struct scev_info_str *) *slot;
1905 info->chrec = val;
1908 /* Return the closed_loop_phi node for VAR. If there is none, return
1909 NULL_TREE. */
1911 static tree
1912 loop_closed_phi_def (tree var)
1914 struct loop *loop;
1915 edge exit;
1916 tree phi;
1918 if (var == NULL_TREE
1919 || TREE_CODE (var) != SSA_NAME)
1920 return NULL_TREE;
1922 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
1923 exit = loop->single_exit;
1924 if (!exit)
1925 return NULL_TREE;
1927 for (phi = phi_nodes (exit->dest); phi; phi = PHI_CHAIN (phi))
1928 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
1929 return PHI_RESULT (phi);
1931 return NULL_TREE;
1934 /* Analyze all the parameters of the chrec that were left under a symbolic form,
1935 with respect to LOOP. CHREC is the chrec to instantiate. CACHE is the cache
1936 of already instantiated values. FLAGS modify the way chrecs are
1937 instantiated. SIZE_EXPR is used for computing the size of the expression to
1938 be instantiated, and to stop if it exceeds some limit. */
1940 /* Values for FLAGS. */
1941 enum
1943 INSERT_SUPERLOOP_CHRECS = 1, /* Loop invariants are replaced with chrecs
1944 in outer loops. */
1945 FOLD_CONVERSIONS = 2 /* The conversions that may wrap in
1946 signed/pointer type are folded, as long as the
1947 value of the chrec is preserved. */
1950 static tree
1951 instantiate_parameters_1 (struct loop *loop, tree chrec, int flags, htab_t cache,
1952 int size_expr)
1954 tree res, op0, op1, op2;
1955 basic_block def_bb;
1956 struct loop *def_loop;
1957 tree type = chrec_type (chrec);
1959 /* Give up if the expression is larger than the MAX that we allow. */
1960 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
1961 return chrec_dont_know;
1963 if (automatically_generated_chrec_p (chrec)
1964 || is_gimple_min_invariant (chrec))
1965 return chrec;
1967 switch (TREE_CODE (chrec))
1969 case SSA_NAME:
1970 def_bb = bb_for_stmt (SSA_NAME_DEF_STMT (chrec));
1972 /* A parameter (or loop invariant and we do not want to include
1973 evolutions in outer loops), nothing to do. */
1974 if (!def_bb
1975 || (!(flags & INSERT_SUPERLOOP_CHRECS)
1976 && !flow_bb_inside_loop_p (loop, def_bb)))
1977 return chrec;
1979 /* We cache the value of instantiated variable to avoid exponential
1980 time complexity due to reevaluations. We also store the convenient
1981 value in the cache in order to prevent infinite recursion -- we do
1982 not want to instantiate the SSA_NAME if it is in a mixer
1983 structure. This is used for avoiding the instantiation of
1984 recursively defined functions, such as:
1986 | a_2 -> {0, +, 1, +, a_2}_1 */
1988 res = get_instantiated_value (cache, chrec);
1989 if (res)
1990 return res;
1992 /* Store the convenient value for chrec in the structure. If it
1993 is defined outside of the loop, we may just leave it in symbolic
1994 form, otherwise we need to admit that we do not know its behavior
1995 inside the loop. */
1996 res = !flow_bb_inside_loop_p (loop, def_bb) ? chrec : chrec_dont_know;
1997 set_instantiated_value (cache, chrec, res);
1999 /* To make things even more complicated, instantiate_parameters_1
2000 calls analyze_scalar_evolution that may call # of iterations
2001 analysis that may in turn call instantiate_parameters_1 again.
2002 To prevent the infinite recursion, keep also the bitmap of
2003 ssa names that are being instantiated globally. */
2004 if (bitmap_bit_p (already_instantiated, SSA_NAME_VERSION (chrec)))
2005 return res;
2007 def_loop = find_common_loop (loop, def_bb->loop_father);
2009 /* If the analysis yields a parametric chrec, instantiate the
2010 result again. */
2011 bitmap_set_bit (already_instantiated, SSA_NAME_VERSION (chrec));
2012 res = analyze_scalar_evolution (def_loop, chrec);
2014 /* Don't instantiate loop-closed-ssa phi nodes. */
2015 if (TREE_CODE (res) == SSA_NAME
2016 && (loop_containing_stmt (SSA_NAME_DEF_STMT (res)) == NULL
2017 || (loop_containing_stmt (SSA_NAME_DEF_STMT (res))->depth
2018 > def_loop->depth)))
2020 if (res == chrec)
2021 res = loop_closed_phi_def (chrec);
2022 else
2023 res = chrec;
2025 if (res == NULL_TREE)
2026 res = chrec_dont_know;
2029 else if (res != chrec_dont_know)
2030 res = instantiate_parameters_1 (loop, res, flags, cache, size_expr);
2032 bitmap_clear_bit (already_instantiated, SSA_NAME_VERSION (chrec));
2034 /* Store the correct value to the cache. */
2035 set_instantiated_value (cache, chrec, res);
2036 return res;
2038 case POLYNOMIAL_CHREC:
2039 op0 = instantiate_parameters_1 (loop, CHREC_LEFT (chrec),
2040 flags, cache, size_expr);
2041 if (op0 == chrec_dont_know)
2042 return chrec_dont_know;
2044 op1 = instantiate_parameters_1 (loop, CHREC_RIGHT (chrec),
2045 flags, cache, size_expr);
2046 if (op1 == chrec_dont_know)
2047 return chrec_dont_know;
2049 if (CHREC_LEFT (chrec) != op0
2050 || CHREC_RIGHT (chrec) != op1)
2052 op1 = chrec_convert (chrec_type (op0), op1, NULL_TREE);
2053 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2055 return chrec;
2057 case PLUS_EXPR:
2058 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2059 flags, cache, size_expr);
2060 if (op0 == chrec_dont_know)
2061 return chrec_dont_know;
2063 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2064 flags, cache, size_expr);
2065 if (op1 == chrec_dont_know)
2066 return chrec_dont_know;
2068 if (TREE_OPERAND (chrec, 0) != op0
2069 || TREE_OPERAND (chrec, 1) != op1)
2071 op0 = chrec_convert (type, op0, NULL_TREE);
2072 op1 = chrec_convert (type, op1, NULL_TREE);
2073 chrec = chrec_fold_plus (type, op0, op1);
2075 return chrec;
2077 case MINUS_EXPR:
2078 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2079 flags, cache, size_expr);
2080 if (op0 == chrec_dont_know)
2081 return chrec_dont_know;
2083 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2084 flags, cache, size_expr);
2085 if (op1 == chrec_dont_know)
2086 return chrec_dont_know;
2088 if (TREE_OPERAND (chrec, 0) != op0
2089 || TREE_OPERAND (chrec, 1) != op1)
2091 op0 = chrec_convert (type, op0, NULL_TREE);
2092 op1 = chrec_convert (type, op1, NULL_TREE);
2093 chrec = chrec_fold_minus (type, op0, op1);
2095 return chrec;
2097 case MULT_EXPR:
2098 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2099 flags, cache, size_expr);
2100 if (op0 == chrec_dont_know)
2101 return chrec_dont_know;
2103 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2104 flags, cache, size_expr);
2105 if (op1 == chrec_dont_know)
2106 return chrec_dont_know;
2108 if (TREE_OPERAND (chrec, 0) != op0
2109 || TREE_OPERAND (chrec, 1) != op1)
2111 op0 = chrec_convert (type, op0, NULL_TREE);
2112 op1 = chrec_convert (type, op1, NULL_TREE);
2113 chrec = chrec_fold_multiply (type, op0, op1);
2115 return chrec;
2117 case NOP_EXPR:
2118 case CONVERT_EXPR:
2119 case NON_LVALUE_EXPR:
2120 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2121 flags, cache, size_expr);
2122 if (op0 == chrec_dont_know)
2123 return chrec_dont_know;
2125 if (flags & FOLD_CONVERSIONS)
2127 tree tmp = chrec_convert_aggressive (TREE_TYPE (chrec), op0);
2128 if (tmp)
2129 return tmp;
2132 if (op0 == TREE_OPERAND (chrec, 0))
2133 return chrec;
2135 /* If we used chrec_convert_aggressive, we can no longer assume that
2136 signed chrecs do not overflow, as chrec_convert does, so avoid
2137 calling it in that case. */
2138 if (flags & FOLD_CONVERSIONS)
2139 return fold_convert (TREE_TYPE (chrec), op0);
2141 return chrec_convert (TREE_TYPE (chrec), op0, NULL_TREE);
2143 case SCEV_NOT_KNOWN:
2144 return chrec_dont_know;
2146 case SCEV_KNOWN:
2147 return chrec_known;
2149 default:
2150 break;
2153 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2155 case 3:
2156 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2157 flags, cache, size_expr);
2158 if (op0 == chrec_dont_know)
2159 return chrec_dont_know;
2161 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2162 flags, cache, size_expr);
2163 if (op1 == chrec_dont_know)
2164 return chrec_dont_know;
2166 op2 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 2),
2167 flags, cache, size_expr);
2168 if (op2 == chrec_dont_know)
2169 return chrec_dont_know;
2171 if (op0 == TREE_OPERAND (chrec, 0)
2172 && op1 == TREE_OPERAND (chrec, 1)
2173 && op2 == TREE_OPERAND (chrec, 2))
2174 return chrec;
2176 return fold_build3 (TREE_CODE (chrec),
2177 TREE_TYPE (chrec), op0, op1, op2);
2179 case 2:
2180 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2181 flags, cache, size_expr);
2182 if (op0 == chrec_dont_know)
2183 return chrec_dont_know;
2185 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2186 flags, cache, size_expr);
2187 if (op1 == chrec_dont_know)
2188 return chrec_dont_know;
2190 if (op0 == TREE_OPERAND (chrec, 0)
2191 && op1 == TREE_OPERAND (chrec, 1))
2192 return chrec;
2193 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2195 case 1:
2196 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2197 flags, cache, size_expr);
2198 if (op0 == chrec_dont_know)
2199 return chrec_dont_know;
2200 if (op0 == TREE_OPERAND (chrec, 0))
2201 return chrec;
2202 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2204 case 0:
2205 return chrec;
2207 default:
2208 break;
2211 /* Too complicated to handle. */
2212 return chrec_dont_know;
2215 /* Analyze all the parameters of the chrec that were left under a
2216 symbolic form. LOOP is the loop in which symbolic names have to
2217 be analyzed and instantiated. */
2219 tree
2220 instantiate_parameters (struct loop *loop,
2221 tree chrec)
2223 tree res;
2224 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2226 if (dump_file && (dump_flags & TDF_DETAILS))
2228 fprintf (dump_file, "(instantiate_parameters \n");
2229 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
2230 fprintf (dump_file, " (chrec = ");
2231 print_generic_expr (dump_file, chrec, 0);
2232 fprintf (dump_file, ")\n");
2235 res = instantiate_parameters_1 (loop, chrec, INSERT_SUPERLOOP_CHRECS, cache,
2238 if (dump_file && (dump_flags & TDF_DETAILS))
2240 fprintf (dump_file, " (res = ");
2241 print_generic_expr (dump_file, res, 0);
2242 fprintf (dump_file, "))\n");
2245 htab_delete (cache);
2247 return res;
2250 /* Similar to instantiate_parameters, but does not introduce the
2251 evolutions in outer loops for LOOP invariants in CHREC, and does not
2252 care about causing overflows, as long as they do not affect value
2253 of an expression. */
2255 static tree
2256 resolve_mixers (struct loop *loop, tree chrec)
2258 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2259 tree ret = instantiate_parameters_1 (loop, chrec, FOLD_CONVERSIONS, cache, 0);
2260 htab_delete (cache);
2261 return ret;
2264 /* Entry point for the analysis of the number of iterations pass.
2265 This function tries to safely approximate the number of iterations
2266 the loop will run. When this property is not decidable at compile
2267 time, the result is chrec_dont_know. Otherwise the result is
2268 a scalar or a symbolic parameter.
2270 Example of analysis: suppose that the loop has an exit condition:
2272 "if (b > 49) goto end_loop;"
2274 and that in a previous analysis we have determined that the
2275 variable 'b' has an evolution function:
2277 "EF = {23, +, 5}_2".
2279 When we evaluate the function at the point 5, i.e. the value of the
2280 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2281 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2282 the loop body has been executed 6 times. */
2284 tree
2285 number_of_iterations_in_loop (struct loop *loop)
2287 tree res, type;
2288 edge exit;
2289 struct tree_niter_desc niter_desc;
2291 /* Determine whether the number_of_iterations_in_loop has already
2292 been computed. */
2293 res = loop->nb_iterations;
2294 if (res)
2295 return res;
2296 res = chrec_dont_know;
2298 if (dump_file && (dump_flags & TDF_DETAILS))
2299 fprintf (dump_file, "(number_of_iterations_in_loop\n");
2301 exit = loop->single_exit;
2302 if (!exit)
2303 goto end;
2305 if (!number_of_iterations_exit (loop, exit, &niter_desc, false))
2306 goto end;
2308 type = TREE_TYPE (niter_desc.niter);
2309 if (integer_nonzerop (niter_desc.may_be_zero))
2310 res = build_int_cst (type, 0);
2311 else if (integer_zerop (niter_desc.may_be_zero))
2312 res = niter_desc.niter;
2313 else
2314 res = chrec_dont_know;
2316 end:
2317 return set_nb_iterations_in_loop (loop, res);
2320 /* One of the drivers for testing the scalar evolutions analysis.
2321 This function computes the number of iterations for all the loops
2322 from the EXIT_CONDITIONS array. */
2324 static void
2325 number_of_iterations_for_all_loops (VEC(tree,heap) **exit_conditions)
2327 unsigned int i;
2328 unsigned nb_chrec_dont_know_loops = 0;
2329 unsigned nb_static_loops = 0;
2330 tree cond;
2332 for (i = 0; VEC_iterate (tree, *exit_conditions, i, cond); i++)
2334 tree res = number_of_iterations_in_loop (loop_containing_stmt (cond));
2335 if (chrec_contains_undetermined (res))
2336 nb_chrec_dont_know_loops++;
2337 else
2338 nb_static_loops++;
2341 if (dump_file)
2343 fprintf (dump_file, "\n(\n");
2344 fprintf (dump_file, "-----------------------------------------\n");
2345 fprintf (dump_file, "%d\tnb_chrec_dont_know_loops\n", nb_chrec_dont_know_loops);
2346 fprintf (dump_file, "%d\tnb_static_loops\n", nb_static_loops);
2347 fprintf (dump_file, "%d\tnb_total_loops\n", current_loops->num);
2348 fprintf (dump_file, "-----------------------------------------\n");
2349 fprintf (dump_file, ")\n\n");
2351 print_loop_ir (dump_file);
2357 /* Counters for the stats. */
2359 struct chrec_stats
2361 unsigned nb_chrecs;
2362 unsigned nb_affine;
2363 unsigned nb_affine_multivar;
2364 unsigned nb_higher_poly;
2365 unsigned nb_chrec_dont_know;
2366 unsigned nb_undetermined;
2369 /* Reset the counters. */
2371 static inline void
2372 reset_chrecs_counters (struct chrec_stats *stats)
2374 stats->nb_chrecs = 0;
2375 stats->nb_affine = 0;
2376 stats->nb_affine_multivar = 0;
2377 stats->nb_higher_poly = 0;
2378 stats->nb_chrec_dont_know = 0;
2379 stats->nb_undetermined = 0;
2382 /* Dump the contents of a CHREC_STATS structure. */
2384 static void
2385 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2387 fprintf (file, "\n(\n");
2388 fprintf (file, "-----------------------------------------\n");
2389 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2390 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2391 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2392 stats->nb_higher_poly);
2393 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2394 fprintf (file, "-----------------------------------------\n");
2395 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2396 fprintf (file, "%d\twith undetermined coefficients\n",
2397 stats->nb_undetermined);
2398 fprintf (file, "-----------------------------------------\n");
2399 fprintf (file, "%d\tchrecs in the scev database\n",
2400 (int) htab_elements (scalar_evolution_info));
2401 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2402 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2403 fprintf (file, "-----------------------------------------\n");
2404 fprintf (file, ")\n\n");
2407 /* Gather statistics about CHREC. */
2409 static void
2410 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2412 if (dump_file && (dump_flags & TDF_STATS))
2414 fprintf (dump_file, "(classify_chrec ");
2415 print_generic_expr (dump_file, chrec, 0);
2416 fprintf (dump_file, "\n");
2419 stats->nb_chrecs++;
2421 if (chrec == NULL_TREE)
2423 stats->nb_undetermined++;
2424 return;
2427 switch (TREE_CODE (chrec))
2429 case POLYNOMIAL_CHREC:
2430 if (evolution_function_is_affine_p (chrec))
2432 if (dump_file && (dump_flags & TDF_STATS))
2433 fprintf (dump_file, " affine_univariate\n");
2434 stats->nb_affine++;
2436 else if (evolution_function_is_affine_multivariate_p (chrec))
2438 if (dump_file && (dump_flags & TDF_STATS))
2439 fprintf (dump_file, " affine_multivariate\n");
2440 stats->nb_affine_multivar++;
2442 else
2444 if (dump_file && (dump_flags & TDF_STATS))
2445 fprintf (dump_file, " higher_degree_polynomial\n");
2446 stats->nb_higher_poly++;
2449 break;
2451 default:
2452 break;
2455 if (chrec_contains_undetermined (chrec))
2457 if (dump_file && (dump_flags & TDF_STATS))
2458 fprintf (dump_file, " undetermined\n");
2459 stats->nb_undetermined++;
2462 if (dump_file && (dump_flags & TDF_STATS))
2463 fprintf (dump_file, ")\n");
2466 /* One of the drivers for testing the scalar evolutions analysis.
2467 This function analyzes the scalar evolution of all the scalars
2468 defined as loop phi nodes in one of the loops from the
2469 EXIT_CONDITIONS array.
2471 TODO Optimization: A loop is in canonical form if it contains only
2472 a single scalar loop phi node. All the other scalars that have an
2473 evolution in the loop are rewritten in function of this single
2474 index. This allows the parallelization of the loop. */
2476 static void
2477 analyze_scalar_evolution_for_all_loop_phi_nodes (VEC(tree,heap) **exit_conditions)
2479 unsigned int i;
2480 struct chrec_stats stats;
2481 tree cond;
2483 reset_chrecs_counters (&stats);
2485 for (i = 0; VEC_iterate (tree, *exit_conditions, i, cond); i++)
2487 struct loop *loop;
2488 basic_block bb;
2489 tree phi, chrec;
2491 loop = loop_containing_stmt (cond);
2492 bb = loop->header;
2494 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2495 if (is_gimple_reg (PHI_RESULT (phi)))
2497 chrec = instantiate_parameters
2498 (loop,
2499 analyze_scalar_evolution (loop, PHI_RESULT (phi)));
2501 if (dump_file && (dump_flags & TDF_STATS))
2502 gather_chrec_stats (chrec, &stats);
2506 if (dump_file && (dump_flags & TDF_STATS))
2507 dump_chrecs_stats (dump_file, &stats);
2510 /* Callback for htab_traverse, gathers information on chrecs in the
2511 hashtable. */
2513 static int
2514 gather_stats_on_scev_database_1 (void **slot, void *stats)
2516 struct scev_info_str *entry = (struct scev_info_str *) *slot;
2518 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
2520 return 1;
2523 /* Classify the chrecs of the whole database. */
2525 void
2526 gather_stats_on_scev_database (void)
2528 struct chrec_stats stats;
2530 if (!dump_file)
2531 return;
2533 reset_chrecs_counters (&stats);
2535 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
2536 &stats);
2538 dump_chrecs_stats (dump_file, &stats);
2543 /* Initializer. */
2545 static void
2546 initialize_scalar_evolutions_analyzer (void)
2548 /* The elements below are unique. */
2549 if (chrec_dont_know == NULL_TREE)
2551 chrec_not_analyzed_yet = NULL_TREE;
2552 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
2553 chrec_known = make_node (SCEV_KNOWN);
2554 TREE_TYPE (chrec_dont_know) = void_type_node;
2555 TREE_TYPE (chrec_known) = void_type_node;
2559 /* Initialize the analysis of scalar evolutions for LOOPS. */
2561 void
2562 scev_initialize (struct loops *loops)
2564 unsigned i;
2565 current_loops = loops;
2567 scalar_evolution_info = htab_create (100, hash_scev_info,
2568 eq_scev_info, del_scev_info);
2569 already_instantiated = BITMAP_ALLOC (NULL);
2571 initialize_scalar_evolutions_analyzer ();
2573 for (i = 1; i < loops->num; i++)
2574 if (loops->parray[i])
2575 loops->parray[i]->nb_iterations = NULL_TREE;
2578 /* Cleans up the information cached by the scalar evolutions analysis. */
2580 void
2581 scev_reset (void)
2583 unsigned i;
2584 struct loop *loop;
2586 if (!scalar_evolution_info || !current_loops)
2587 return;
2589 htab_empty (scalar_evolution_info);
2590 for (i = 1; i < current_loops->num; i++)
2592 loop = current_loops->parray[i];
2593 if (loop)
2594 loop->nb_iterations = NULL_TREE;
2598 /* Checks whether OP behaves as a simple affine iv of LOOP in STMT and returns
2599 its base and step in IV if possible. If ALLOW_NONCONSTANT_STEP is true, we
2600 want step to be invariant in LOOP. Otherwise we require it to be an
2601 integer constant. IV->no_overflow is set to true if we are sure the iv cannot
2602 overflow (e.g. because it is computed in signed arithmetics). */
2604 bool
2605 simple_iv (struct loop *loop, tree stmt, tree op, affine_iv *iv,
2606 bool allow_nonconstant_step)
2608 basic_block bb = bb_for_stmt (stmt);
2609 tree type, ev;
2610 bool folded_casts;
2612 iv->base = NULL_TREE;
2613 iv->step = NULL_TREE;
2614 iv->no_overflow = false;
2616 type = TREE_TYPE (op);
2617 if (TREE_CODE (type) != INTEGER_TYPE
2618 && TREE_CODE (type) != POINTER_TYPE)
2619 return false;
2621 ev = analyze_scalar_evolution_in_loop (loop, bb->loop_father, op,
2622 &folded_casts);
2623 if (chrec_contains_undetermined (ev))
2624 return false;
2626 if (tree_does_not_contain_chrecs (ev)
2627 && !chrec_contains_symbols_defined_in_loop (ev, loop->num))
2629 iv->base = ev;
2630 iv->no_overflow = true;
2631 return true;
2634 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
2635 || CHREC_VARIABLE (ev) != (unsigned) loop->num)
2636 return false;
2638 iv->step = CHREC_RIGHT (ev);
2639 if (allow_nonconstant_step)
2641 if (tree_contains_chrecs (iv->step, NULL)
2642 || chrec_contains_symbols_defined_in_loop (iv->step, loop->num))
2643 return false;
2645 else if (TREE_CODE (iv->step) != INTEGER_CST)
2646 return false;
2648 iv->base = CHREC_LEFT (ev);
2649 if (tree_contains_chrecs (iv->base, NULL)
2650 || chrec_contains_symbols_defined_in_loop (iv->base, loop->num))
2651 return false;
2653 iv->no_overflow = (!folded_casts
2654 && !flag_wrapv
2655 && !TYPE_UNSIGNED (type));
2656 return true;
2659 /* Runs the analysis of scalar evolutions. */
2661 void
2662 scev_analysis (void)
2664 VEC(tree,heap) *exit_conditions;
2666 exit_conditions = VEC_alloc (tree, heap, 37);
2667 select_loops_exit_conditions (current_loops, &exit_conditions);
2669 if (dump_file && (dump_flags & TDF_STATS))
2670 analyze_scalar_evolution_for_all_loop_phi_nodes (&exit_conditions);
2672 number_of_iterations_for_all_loops (&exit_conditions);
2673 VEC_free (tree, heap, exit_conditions);
2676 /* Finalize the scalar evolution analysis. */
2678 void
2679 scev_finalize (void)
2681 htab_delete (scalar_evolution_info);
2682 BITMAP_FREE (already_instantiated);
2685 /* Returns true if EXPR looks expensive. */
2687 static bool
2688 expression_expensive_p (tree expr)
2690 return force_expr_to_var_cost (expr) >= target_spill_cost;
2693 /* Replace ssa names for that scev can prove they are constant by the
2694 appropriate constants. Also perform final value replacement in loops,
2695 in case the replacement expressions are cheap.
2697 We only consider SSA names defined by phi nodes; rest is left to the
2698 ordinary constant propagation pass. */
2700 unsigned int
2701 scev_const_prop (void)
2703 basic_block bb;
2704 tree name, phi, next_phi, type, ev;
2705 struct loop *loop, *ex_loop;
2706 bitmap ssa_names_to_remove = NULL;
2707 unsigned i;
2709 if (!current_loops)
2710 return 0;
2712 FOR_EACH_BB (bb)
2714 loop = bb->loop_father;
2716 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2718 name = PHI_RESULT (phi);
2720 if (!is_gimple_reg (name))
2721 continue;
2723 type = TREE_TYPE (name);
2725 if (!POINTER_TYPE_P (type)
2726 && !INTEGRAL_TYPE_P (type))
2727 continue;
2729 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
2730 if (!is_gimple_min_invariant (ev)
2731 || !may_propagate_copy (name, ev))
2732 continue;
2734 /* Replace the uses of the name. */
2735 if (name != ev)
2736 replace_uses_by (name, ev);
2738 if (!ssa_names_to_remove)
2739 ssa_names_to_remove = BITMAP_ALLOC (NULL);
2740 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
2744 /* Remove the ssa names that were replaced by constants. We do not remove them
2745 directly in the previous cycle, since this invalidates scev cache. */
2746 if (ssa_names_to_remove)
2748 bitmap_iterator bi;
2749 unsigned i;
2751 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
2753 name = ssa_name (i);
2754 phi = SSA_NAME_DEF_STMT (name);
2756 gcc_assert (TREE_CODE (phi) == PHI_NODE);
2757 remove_phi_node (phi, NULL);
2760 BITMAP_FREE (ssa_names_to_remove);
2761 scev_reset ();
2764 /* Now the regular final value replacement. */
2765 for (i = current_loops->num - 1; i > 0; i--)
2767 edge exit;
2768 tree def, rslt, ass, niter;
2769 block_stmt_iterator bsi;
2771 loop = current_loops->parray[i];
2772 if (!loop)
2773 continue;
2775 /* If we do not know exact number of iterations of the loop, we cannot
2776 replace the final value. */
2777 exit = loop->single_exit;
2778 if (!exit)
2779 continue;
2781 niter = number_of_iterations_in_loop (loop);
2782 if (niter == chrec_dont_know
2783 /* If computing the number of iterations is expensive, it may be
2784 better not to introduce computations involving it. */
2785 || expression_expensive_p (niter))
2786 continue;
2788 /* Ensure that it is possible to insert new statements somewhere. */
2789 if (!single_pred_p (exit->dest))
2790 split_loop_exit_edge (exit);
2791 tree_block_label (exit->dest);
2792 bsi = bsi_after_labels (exit->dest);
2794 ex_loop = superloop_at_depth (loop, exit->dest->loop_father->depth + 1);
2796 for (phi = phi_nodes (exit->dest); phi; phi = next_phi)
2798 next_phi = PHI_CHAIN (phi);
2799 rslt = PHI_RESULT (phi);
2800 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
2801 if (!is_gimple_reg (def))
2802 continue;
2804 if (!POINTER_TYPE_P (TREE_TYPE (def))
2805 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
2806 continue;
2808 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def, NULL);
2809 def = compute_overall_effect_of_inner_loop (ex_loop, def);
2810 if (!tree_does_not_contain_chrecs (def)
2811 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
2812 /* Moving the computation from the loop may prolong life range
2813 of some ssa names, which may cause problems if they appear
2814 on abnormal edges. */
2815 || contains_abnormal_ssa_name_p (def))
2816 continue;
2818 /* Eliminate the phi node and replace it by a computation outside
2819 the loop. */
2820 def = unshare_expr (def);
2821 SET_PHI_RESULT (phi, NULL_TREE);
2822 remove_phi_node (phi, NULL_TREE);
2824 ass = build2 (MODIFY_EXPR, void_type_node, rslt, NULL_TREE);
2825 SSA_NAME_DEF_STMT (rslt) = ass;
2827 block_stmt_iterator dest = bsi;
2828 bsi_insert_before (&dest, ass, BSI_NEW_STMT);
2829 def = force_gimple_operand_bsi (&dest, def, false, NULL_TREE);
2831 TREE_OPERAND (ass, 1) = def;
2832 update_stmt (ass);
2835 return 0;