frv.h (TRANSFER_FROM_TRAMPOLINE): Canonicalize comments in backslash regions.
[official-gcc.git] / gcc / tree-scalar-evolution.c
blob1b68b36b30b249fb18699228b32582092452b9cf
1 /* Scalar evolution detector.
2 Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
3 Free Software Foundation, Inc.
4 Contributed by Sebastian Pop <s.pop@laposte.net>
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
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 GIMPLE_ASSIGN: 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 (loop_1, {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 2a: 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 2b: Multivariate chains of recurrences.
160 | loop_1
161 | k = phi (0, k + 1)
162 | loop_2 4 times
163 | j = phi (0, j + 1)
164 | loop_3 4 times
165 | i = phi (0, i + 1)
166 | A[j + k] = ...
167 | endloop
168 | endloop
169 | endloop
171 Analyzing the access function of array A with
172 instantiate_parameters (loop_1, "j + k"), we obtain the
173 instantiation and the analysis of the scalar variables "j" and "k"
174 in loop_1. This leads to the scalar evolution {4, +, 1}_1: the end
175 value of loop_2 for "j" is 4, and the evolution of "k" in loop_1 is
176 {0, +, 1}_1. To obtain the evolution function in loop_3 and
177 instantiate the scalar variables up to loop_1, one has to use:
178 instantiate_scev (block_before_loop (loop_1), loop_3, "j + k").
179 The result of this call is {{0, +, 1}_1, +, 1}_2.
181 Example 3: Higher degree polynomials.
183 | loop_1
184 | a = phi (2, b)
185 | c = phi (5, d)
186 | b = a + 1
187 | d = c + a
188 | endloop
190 a -> {2, +, 1}_1
191 b -> {3, +, 1}_1
192 c -> {5, +, a}_1
193 d -> {5 + a, +, a}_1
195 instantiate_parameters (loop_1, {5, +, a}_1) -> {5, +, 2, +, 1}_1
196 instantiate_parameters (loop_1, {5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
198 Example 4: Lucas, Fibonacci, or mixers in general.
200 | loop_1
201 | a = phi (1, b)
202 | c = phi (3, d)
203 | b = c
204 | d = c + a
205 | endloop
207 a -> (1, c)_1
208 c -> {3, +, a}_1
210 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
211 following semantics: during the first iteration of the loop_1, the
212 variable contains the value 1, and then it contains the value "c".
213 Note that this syntax is close to the syntax of the loop-phi-node:
214 "a -> (1, c)_1" vs. "a = phi (1, c)".
216 The symbolic chrec representation contains all the semantics of the
217 original code. What is more difficult is to use this information.
219 Example 5: Flip-flops, or exchangers.
221 | loop_1
222 | a = phi (1, b)
223 | c = phi (3, d)
224 | b = c
225 | d = a
226 | endloop
228 a -> (1, c)_1
229 c -> (3, a)_1
231 Based on these symbolic chrecs, it is possible to refine this
232 information into the more precise PERIODIC_CHRECs:
234 a -> |1, 3|_1
235 c -> |3, 1|_1
237 This transformation is not yet implemented.
239 Further readings:
241 You can find a more detailed description of the algorithm in:
242 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
243 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
244 this is a preliminary report and some of the details of the
245 algorithm have changed. I'm working on a research report that
246 updates the description of the algorithms to reflect the design
247 choices used in this implementation.
249 A set of slides show a high level overview of the algorithm and run
250 an example through the scalar evolution analyzer:
251 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
253 The slides that I have presented at the GCC Summit'04 are available
254 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
257 #include "config.h"
258 #include "system.h"
259 #include "coretypes.h"
260 #include "gimple-pretty-print.h"
261 #include "tree-flow.h"
262 #include "cfgloop.h"
263 #include "tree-chrec.h"
264 #include "tree-scalar-evolution.h"
265 #include "tree-pass.h"
266 #include "params.h"
268 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
270 /* The cached information about an SSA name VAR, claiming that below
271 basic block INSTANTIATED_BELOW, the value of VAR can be expressed
272 as CHREC. */
274 struct GTY(()) scev_info_str {
275 basic_block instantiated_below;
276 tree var;
277 tree chrec;
280 /* Counters for the scev database. */
281 static unsigned nb_set_scev = 0;
282 static unsigned nb_get_scev = 0;
284 /* The following trees are unique elements. Thus the comparison of
285 another element to these elements should be done on the pointer to
286 these trees, and not on their value. */
288 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
289 tree chrec_not_analyzed_yet;
291 /* Reserved to the cases where the analyzer has detected an
292 undecidable property at compile time. */
293 tree chrec_dont_know;
295 /* When the analyzer has detected that a property will never
296 happen, then it qualifies it with chrec_known. */
297 tree chrec_known;
299 static GTY ((param_is (struct scev_info_str))) htab_t scalar_evolution_info;
302 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
304 static inline struct scev_info_str *
305 new_scev_info_str (basic_block instantiated_below, tree var)
307 struct scev_info_str *res;
309 res = ggc_alloc_scev_info_str ();
310 res->var = var;
311 res->chrec = chrec_not_analyzed_yet;
312 res->instantiated_below = instantiated_below;
314 return res;
317 /* Computes a hash function for database element ELT. */
319 static hashval_t
320 hash_scev_info (const void *elt)
322 return SSA_NAME_VERSION (((const struct scev_info_str *) elt)->var);
325 /* Compares database elements E1 and E2. */
327 static int
328 eq_scev_info (const void *e1, const void *e2)
330 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
331 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
333 return (elt1->var == elt2->var
334 && elt1->instantiated_below == elt2->instantiated_below);
337 /* Deletes database element E. */
339 static void
340 del_scev_info (void *e)
342 ggc_free (e);
345 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
346 A first query on VAR returns chrec_not_analyzed_yet. */
348 static tree *
349 find_var_scev_info (basic_block instantiated_below, tree var)
351 struct scev_info_str *res;
352 struct scev_info_str tmp;
353 PTR *slot;
355 tmp.var = var;
356 tmp.instantiated_below = instantiated_below;
357 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
359 if (!*slot)
360 *slot = new_scev_info_str (instantiated_below, var);
361 res = (struct scev_info_str *) *slot;
363 return &res->chrec;
366 /* Return true when CHREC contains symbolic names defined in
367 LOOP_NB. */
369 bool
370 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
372 int i, n;
374 if (chrec == NULL_TREE)
375 return false;
377 if (is_gimple_min_invariant (chrec))
378 return false;
380 if (TREE_CODE (chrec) == SSA_NAME)
382 gimple def;
383 loop_p def_loop, loop;
385 if (SSA_NAME_IS_DEFAULT_DEF (chrec))
386 return false;
388 def = SSA_NAME_DEF_STMT (chrec);
389 def_loop = loop_containing_stmt (def);
390 loop = get_loop (loop_nb);
392 if (def_loop == NULL)
393 return false;
395 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
396 return true;
398 return false;
401 n = TREE_OPERAND_LENGTH (chrec);
402 for (i = 0; i < n; i++)
403 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
404 loop_nb))
405 return true;
406 return false;
409 /* Return true when PHI is a loop-phi-node. */
411 static bool
412 loop_phi_node_p (gimple phi)
414 /* The implementation of this function is based on the following
415 property: "all the loop-phi-nodes of a loop are contained in the
416 loop's header basic block". */
418 return loop_containing_stmt (phi)->header == gimple_bb (phi);
421 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
422 In general, in the case of multivariate evolutions we want to get
423 the evolution in different loops. LOOP specifies the level for
424 which to get the evolution.
426 Example:
428 | for (j = 0; j < 100; j++)
430 | for (k = 0; k < 100; k++)
432 | i = k + j; - Here the value of i is a function of j, k.
434 | ... = i - Here the value of i is a function of j.
436 | ... = i - Here the value of i is a scalar.
438 Example:
440 | i_0 = ...
441 | loop_1 10 times
442 | i_1 = phi (i_0, i_2)
443 | i_2 = i_1 + 2
444 | endloop
446 This loop has the same effect as:
447 LOOP_1 has the same effect as:
449 | i_1 = i_0 + 20
451 The overall effect of the loop, "i_0 + 20" in the previous example,
452 is obtained by passing in the parameters: LOOP = 1,
453 EVOLUTION_FN = {i_0, +, 2}_1.
456 tree
457 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
459 bool val = false;
461 if (evolution_fn == chrec_dont_know)
462 return chrec_dont_know;
464 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
466 struct loop *inner_loop = get_chrec_loop (evolution_fn);
468 if (inner_loop == loop
469 || flow_loop_nested_p (loop, inner_loop))
471 tree nb_iter = number_of_latch_executions (inner_loop);
473 if (nb_iter == chrec_dont_know)
474 return chrec_dont_know;
475 else
477 tree res;
479 /* evolution_fn is the evolution function in LOOP. Get
480 its value in the nb_iter-th iteration. */
481 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
483 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
484 res = instantiate_parameters (loop, res);
486 /* Continue the computation until ending on a parent of LOOP. */
487 return compute_overall_effect_of_inner_loop (loop, res);
490 else
491 return evolution_fn;
494 /* If the evolution function is an invariant, there is nothing to do. */
495 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
496 return evolution_fn;
498 else
499 return chrec_dont_know;
502 /* Determine whether the CHREC is always positive/negative. If the expression
503 cannot be statically analyzed, return false, otherwise set the answer into
504 VALUE. */
506 bool
507 chrec_is_positive (tree chrec, bool *value)
509 bool value0, value1, value2;
510 tree end_value, nb_iter;
512 switch (TREE_CODE (chrec))
514 case POLYNOMIAL_CHREC:
515 if (!chrec_is_positive (CHREC_LEFT (chrec), &value0)
516 || !chrec_is_positive (CHREC_RIGHT (chrec), &value1))
517 return false;
519 /* FIXME -- overflows. */
520 if (value0 == value1)
522 *value = value0;
523 return true;
526 /* Otherwise the chrec is under the form: "{-197, +, 2}_1",
527 and the proof consists in showing that the sign never
528 changes during the execution of the loop, from 0 to
529 loop->nb_iterations. */
530 if (!evolution_function_is_affine_p (chrec))
531 return false;
533 nb_iter = number_of_latch_executions (get_chrec_loop (chrec));
534 if (chrec_contains_undetermined (nb_iter))
535 return false;
537 #if 0
538 /* TODO -- If the test is after the exit, we may decrease the number of
539 iterations by one. */
540 if (after_exit)
541 nb_iter = chrec_fold_minus (type, nb_iter, build_int_cst (type, 1));
542 #endif
544 end_value = chrec_apply (CHREC_VARIABLE (chrec), chrec, nb_iter);
546 if (!chrec_is_positive (end_value, &value2))
547 return false;
549 *value = value0;
550 return value0 == value1;
552 case INTEGER_CST:
553 *value = (tree_int_cst_sgn (chrec) == 1);
554 return true;
556 default:
557 return false;
561 /* Associate CHREC to SCALAR. */
563 static void
564 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
566 tree *scalar_info;
568 if (TREE_CODE (scalar) != SSA_NAME)
569 return;
571 scalar_info = find_var_scev_info (instantiated_below, scalar);
573 if (dump_file)
575 if (dump_flags & TDF_DETAILS)
577 fprintf (dump_file, "(set_scalar_evolution \n");
578 fprintf (dump_file, " instantiated_below = %d \n",
579 instantiated_below->index);
580 fprintf (dump_file, " (scalar = ");
581 print_generic_expr (dump_file, scalar, 0);
582 fprintf (dump_file, ")\n (scalar_evolution = ");
583 print_generic_expr (dump_file, chrec, 0);
584 fprintf (dump_file, "))\n");
586 if (dump_flags & TDF_STATS)
587 nb_set_scev++;
590 *scalar_info = chrec;
593 /* Retrieve the chrec associated to SCALAR instantiated below
594 INSTANTIATED_BELOW block. */
596 static tree
597 get_scalar_evolution (basic_block instantiated_below, tree scalar)
599 tree res;
601 if (dump_file)
603 if (dump_flags & TDF_DETAILS)
605 fprintf (dump_file, "(get_scalar_evolution \n");
606 fprintf (dump_file, " (scalar = ");
607 print_generic_expr (dump_file, scalar, 0);
608 fprintf (dump_file, ")\n");
610 if (dump_flags & TDF_STATS)
611 nb_get_scev++;
614 switch (TREE_CODE (scalar))
616 case SSA_NAME:
617 res = *find_var_scev_info (instantiated_below, scalar);
618 break;
620 case REAL_CST:
621 case FIXED_CST:
622 case INTEGER_CST:
623 res = scalar;
624 break;
626 default:
627 res = chrec_not_analyzed_yet;
628 break;
631 if (dump_file && (dump_flags & TDF_DETAILS))
633 fprintf (dump_file, " (scalar_evolution = ");
634 print_generic_expr (dump_file, res, 0);
635 fprintf (dump_file, "))\n");
638 return res;
641 /* Helper function for add_to_evolution. Returns the evolution
642 function for an assignment of the form "a = b + c", where "a" and
643 "b" are on the strongly connected component. CHREC_BEFORE is the
644 information that we already have collected up to this point.
645 TO_ADD is the evolution of "c".
647 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
648 evolution the expression TO_ADD, otherwise construct an evolution
649 part for this loop. */
651 static tree
652 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
653 gimple at_stmt)
655 tree type, left, right;
656 struct loop *loop = get_loop (loop_nb), *chloop;
658 switch (TREE_CODE (chrec_before))
660 case POLYNOMIAL_CHREC:
661 chloop = get_chrec_loop (chrec_before);
662 if (chloop == loop
663 || flow_loop_nested_p (chloop, loop))
665 unsigned var;
667 type = chrec_type (chrec_before);
669 /* When there is no evolution part in this loop, build it. */
670 if (chloop != loop)
672 var = loop_nb;
673 left = chrec_before;
674 right = SCALAR_FLOAT_TYPE_P (type)
675 ? build_real (type, dconst0)
676 : build_int_cst (type, 0);
678 else
680 var = CHREC_VARIABLE (chrec_before);
681 left = CHREC_LEFT (chrec_before);
682 right = CHREC_RIGHT (chrec_before);
685 to_add = chrec_convert (type, to_add, at_stmt);
686 right = chrec_convert_rhs (type, right, at_stmt);
687 right = chrec_fold_plus (chrec_type (right), right, to_add);
688 return build_polynomial_chrec (var, left, right);
690 else
692 gcc_assert (flow_loop_nested_p (loop, chloop));
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_rhs (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_rhs (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, gimple 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;
894 /* This section selects the loops that will be good candidates for the
895 scalar evolution analysis. For the moment, greedily select all the
896 loop nests we could analyze. */
898 /* For a loop with a single exit edge, return the COND_EXPR that
899 guards the exit edge. If the expression is too difficult to
900 analyze, then give up. */
902 gimple
903 get_loop_exit_condition (const struct loop *loop)
905 gimple res = NULL;
906 edge exit_edge = single_exit (loop);
908 if (dump_file && (dump_flags & TDF_DETAILS))
909 fprintf (dump_file, "(get_loop_exit_condition \n ");
911 if (exit_edge)
913 gimple stmt;
915 stmt = last_stmt (exit_edge->src);
916 if (gimple_code (stmt) == GIMPLE_COND)
917 res = stmt;
920 if (dump_file && (dump_flags & TDF_DETAILS))
922 print_gimple_stmt (dump_file, res, 0, 0);
923 fprintf (dump_file, ")\n");
926 return res;
929 /* Recursively determine and enqueue the exit conditions for a loop. */
931 static void
932 get_exit_conditions_rec (struct loop *loop,
933 VEC(gimple,heap) **exit_conditions)
935 if (!loop)
936 return;
938 /* Recurse on the inner loops, then on the next (sibling) loops. */
939 get_exit_conditions_rec (loop->inner, exit_conditions);
940 get_exit_conditions_rec (loop->next, exit_conditions);
942 if (single_exit (loop))
944 gimple loop_condition = get_loop_exit_condition (loop);
946 if (loop_condition)
947 VEC_safe_push (gimple, heap, *exit_conditions, loop_condition);
951 /* Select the candidate loop nests for the analysis. This function
952 initializes the EXIT_CONDITIONS array. */
954 static void
955 select_loops_exit_conditions (VEC(gimple,heap) **exit_conditions)
957 struct loop *function_body = current_loops->tree_root;
959 get_exit_conditions_rec (function_body->inner, exit_conditions);
963 /* Depth first search algorithm. */
965 typedef enum t_bool {
966 t_false,
967 t_true,
968 t_dont_know
969 } t_bool;
972 static t_bool follow_ssa_edge (struct loop *loop, gimple, gimple, tree *, int);
974 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
975 Return true if the strongly connected component has been found. */
977 static t_bool
978 follow_ssa_edge_binary (struct loop *loop, gimple at_stmt,
979 tree type, tree rhs0, enum tree_code code, tree rhs1,
980 gimple halting_phi, tree *evolution_of_loop, int limit)
982 t_bool res = t_false;
983 tree evol;
985 switch (code)
987 case POINTER_PLUS_EXPR:
988 case PLUS_EXPR:
989 if (TREE_CODE (rhs0) == SSA_NAME)
991 if (TREE_CODE (rhs1) == SSA_NAME)
993 /* Match an assignment under the form:
994 "a = b + c". */
996 /* We want only assignments of form "name + name" contribute to
997 LIMIT, as the other cases do not necessarily contribute to
998 the complexity of the expression. */
999 limit++;
1001 evol = *evolution_of_loop;
1002 res = follow_ssa_edge
1003 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
1005 if (res == t_true)
1006 *evolution_of_loop = add_to_evolution
1007 (loop->num,
1008 chrec_convert (type, evol, at_stmt),
1009 code, rhs1, at_stmt);
1011 else if (res == t_false)
1013 res = follow_ssa_edge
1014 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1015 evolution_of_loop, limit);
1017 if (res == t_true)
1018 *evolution_of_loop = add_to_evolution
1019 (loop->num,
1020 chrec_convert (type, *evolution_of_loop, at_stmt),
1021 code, rhs0, at_stmt);
1023 else if (res == t_dont_know)
1024 *evolution_of_loop = chrec_dont_know;
1027 else if (res == t_dont_know)
1028 *evolution_of_loop = chrec_dont_know;
1031 else
1033 /* Match an assignment under the form:
1034 "a = b + ...". */
1035 res = follow_ssa_edge
1036 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1037 evolution_of_loop, limit);
1038 if (res == t_true)
1039 *evolution_of_loop = add_to_evolution
1040 (loop->num, chrec_convert (type, *evolution_of_loop,
1041 at_stmt),
1042 code, rhs1, at_stmt);
1044 else if (res == t_dont_know)
1045 *evolution_of_loop = chrec_dont_know;
1049 else if (TREE_CODE (rhs1) == SSA_NAME)
1051 /* Match an assignment under the form:
1052 "a = ... + c". */
1053 res = follow_ssa_edge
1054 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1055 evolution_of_loop, limit);
1056 if (res == t_true)
1057 *evolution_of_loop = add_to_evolution
1058 (loop->num, chrec_convert (type, *evolution_of_loop,
1059 at_stmt),
1060 code, rhs0, at_stmt);
1062 else if (res == t_dont_know)
1063 *evolution_of_loop = chrec_dont_know;
1066 else
1067 /* Otherwise, match an assignment under the form:
1068 "a = ... + ...". */
1069 /* And there is nothing to do. */
1070 res = t_false;
1071 break;
1073 case MINUS_EXPR:
1074 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1075 if (TREE_CODE (rhs0) == SSA_NAME)
1077 /* Match an assignment under the form:
1078 "a = b - ...". */
1080 /* We want only assignments of form "name - name" contribute to
1081 LIMIT, as the other cases do not necessarily contribute to
1082 the complexity of the expression. */
1083 if (TREE_CODE (rhs1) == SSA_NAME)
1084 limit++;
1086 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1087 evolution_of_loop, limit);
1088 if (res == t_true)
1089 *evolution_of_loop = add_to_evolution
1090 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1091 MINUS_EXPR, rhs1, at_stmt);
1093 else if (res == t_dont_know)
1094 *evolution_of_loop = chrec_dont_know;
1096 else
1097 /* Otherwise, match an assignment under the form:
1098 "a = ... - ...". */
1099 /* And there is nothing to do. */
1100 res = t_false;
1101 break;
1103 default:
1104 res = t_false;
1107 return res;
1110 /* Follow the ssa edge into the expression EXPR.
1111 Return true if the strongly connected component has been found. */
1113 static t_bool
1114 follow_ssa_edge_expr (struct loop *loop, gimple at_stmt, tree expr,
1115 gimple halting_phi, tree *evolution_of_loop, int limit)
1117 enum tree_code code = TREE_CODE (expr);
1118 tree type = TREE_TYPE (expr), rhs0, rhs1;
1119 t_bool res;
1121 /* The EXPR is one of the following cases:
1122 - an SSA_NAME,
1123 - an INTEGER_CST,
1124 - a PLUS_EXPR,
1125 - a POINTER_PLUS_EXPR,
1126 - a MINUS_EXPR,
1127 - an ASSERT_EXPR,
1128 - other cases are not yet handled. */
1130 switch (code)
1132 CASE_CONVERT:
1133 /* This assignment is under the form "a_1 = (cast) rhs. */
1134 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1135 halting_phi, evolution_of_loop, limit);
1136 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1137 break;
1139 case INTEGER_CST:
1140 /* This assignment is under the form "a_1 = 7". */
1141 res = t_false;
1142 break;
1144 case SSA_NAME:
1145 /* This assignment is under the form: "a_1 = b_2". */
1146 res = follow_ssa_edge
1147 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1148 break;
1150 case POINTER_PLUS_EXPR:
1151 case PLUS_EXPR:
1152 case MINUS_EXPR:
1153 /* This case is under the form "rhs0 +- rhs1". */
1154 rhs0 = TREE_OPERAND (expr, 0);
1155 rhs1 = TREE_OPERAND (expr, 1);
1156 type = TREE_TYPE (rhs0);
1157 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1158 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1159 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1160 halting_phi, evolution_of_loop, limit);
1161 break;
1163 case ADDR_EXPR:
1164 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1165 if (TREE_CODE (TREE_OPERAND (expr, 0)) == MEM_REF)
1167 expr = TREE_OPERAND (expr, 0);
1168 rhs0 = TREE_OPERAND (expr, 0);
1169 rhs1 = TREE_OPERAND (expr, 1);
1170 type = TREE_TYPE (rhs0);
1171 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1172 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1173 res = follow_ssa_edge_binary (loop, at_stmt, type,
1174 rhs0, POINTER_PLUS_EXPR, rhs1,
1175 halting_phi, evolution_of_loop, limit);
1177 else
1178 res = t_false;
1179 break;
1181 case ASSERT_EXPR:
1182 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1183 It must be handled as a copy assignment of the form a_1 = a_2. */
1184 rhs0 = ASSERT_EXPR_VAR (expr);
1185 if (TREE_CODE (rhs0) == SSA_NAME)
1186 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1187 halting_phi, evolution_of_loop, limit);
1188 else
1189 res = t_false;
1190 break;
1192 default:
1193 res = t_false;
1194 break;
1197 return res;
1200 /* Follow the ssa edge into the right hand side of an assignment STMT.
1201 Return true if the strongly connected component has been found. */
1203 static t_bool
1204 follow_ssa_edge_in_rhs (struct loop *loop, gimple stmt,
1205 gimple halting_phi, tree *evolution_of_loop, int limit)
1207 enum tree_code code = gimple_assign_rhs_code (stmt);
1208 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1209 t_bool res;
1211 switch (code)
1213 CASE_CONVERT:
1214 /* This assignment is under the form "a_1 = (cast) rhs. */
1215 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1216 halting_phi, evolution_of_loop, limit);
1217 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1218 break;
1220 case POINTER_PLUS_EXPR:
1221 case PLUS_EXPR:
1222 case MINUS_EXPR:
1223 rhs1 = gimple_assign_rhs1 (stmt);
1224 rhs2 = gimple_assign_rhs2 (stmt);
1225 type = TREE_TYPE (rhs1);
1226 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1227 halting_phi, evolution_of_loop, limit);
1228 break;
1230 default:
1231 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1232 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1233 halting_phi, evolution_of_loop, limit);
1234 else
1235 res = t_false;
1236 break;
1239 return res;
1242 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1244 static bool
1245 backedge_phi_arg_p (gimple phi, int i)
1247 const_edge e = gimple_phi_arg_edge (phi, i);
1249 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1250 about updating it anywhere, and this should work as well most of the
1251 time. */
1252 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1253 return true;
1255 return false;
1258 /* Helper function for one branch of the condition-phi-node. Return
1259 true if the strongly connected component has been found following
1260 this path. */
1262 static inline t_bool
1263 follow_ssa_edge_in_condition_phi_branch (int i,
1264 struct loop *loop,
1265 gimple condition_phi,
1266 gimple halting_phi,
1267 tree *evolution_of_branch,
1268 tree init_cond, int limit)
1270 tree branch = PHI_ARG_DEF (condition_phi, i);
1271 *evolution_of_branch = chrec_dont_know;
1273 /* Do not follow back edges (they must belong to an irreducible loop, which
1274 we really do not want to worry about). */
1275 if (backedge_phi_arg_p (condition_phi, i))
1276 return t_false;
1278 if (TREE_CODE (branch) == SSA_NAME)
1280 *evolution_of_branch = init_cond;
1281 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1282 evolution_of_branch, limit);
1285 /* This case occurs when one of the condition branches sets
1286 the variable to a constant: i.e. a phi-node like
1287 "a_2 = PHI <a_7(5), 2(6)>;".
1289 FIXME: This case have to be refined correctly:
1290 in some cases it is possible to say something better than
1291 chrec_dont_know, for example using a wrap-around notation. */
1292 return t_false;
1295 /* This function merges the branches of a condition-phi-node in a
1296 loop. */
1298 static t_bool
1299 follow_ssa_edge_in_condition_phi (struct loop *loop,
1300 gimple condition_phi,
1301 gimple halting_phi,
1302 tree *evolution_of_loop, int limit)
1304 int i, n;
1305 tree init = *evolution_of_loop;
1306 tree evolution_of_branch;
1307 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1308 halting_phi,
1309 &evolution_of_branch,
1310 init, limit);
1311 if (res == t_false || res == t_dont_know)
1312 return res;
1314 *evolution_of_loop = evolution_of_branch;
1316 n = gimple_phi_num_args (condition_phi);
1317 for (i = 1; i < n; i++)
1319 /* Quickly give up when the evolution of one of the branches is
1320 not known. */
1321 if (*evolution_of_loop == chrec_dont_know)
1322 return t_true;
1324 /* Increase the limit by the PHI argument number to avoid exponential
1325 time and memory complexity. */
1326 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1327 halting_phi,
1328 &evolution_of_branch,
1329 init, limit + i);
1330 if (res == t_false || res == t_dont_know)
1331 return res;
1333 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1334 evolution_of_branch);
1337 return t_true;
1340 /* Follow an SSA edge in an inner loop. It computes the overall
1341 effect of the loop, and following the symbolic initial conditions,
1342 it follows the edges in the parent loop. The inner loop is
1343 considered as a single statement. */
1345 static t_bool
1346 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1347 gimple loop_phi_node,
1348 gimple halting_phi,
1349 tree *evolution_of_loop, int limit)
1351 struct loop *loop = loop_containing_stmt (loop_phi_node);
1352 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1354 /* Sometimes, the inner loop is too difficult to analyze, and the
1355 result of the analysis is a symbolic parameter. */
1356 if (ev == PHI_RESULT (loop_phi_node))
1358 t_bool res = t_false;
1359 int i, n = gimple_phi_num_args (loop_phi_node);
1361 for (i = 0; i < n; i++)
1363 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1364 basic_block bb;
1366 /* Follow the edges that exit the inner loop. */
1367 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1368 if (!flow_bb_inside_loop_p (loop, bb))
1369 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1370 arg, halting_phi,
1371 evolution_of_loop, limit);
1372 if (res == t_true)
1373 break;
1376 /* If the path crosses this loop-phi, give up. */
1377 if (res == t_true)
1378 *evolution_of_loop = chrec_dont_know;
1380 return res;
1383 /* Otherwise, compute the overall effect of the inner loop. */
1384 ev = compute_overall_effect_of_inner_loop (loop, ev);
1385 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1386 evolution_of_loop, limit);
1389 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1390 path that is analyzed on the return walk. */
1392 static t_bool
1393 follow_ssa_edge (struct loop *loop, gimple def, gimple halting_phi,
1394 tree *evolution_of_loop, int limit)
1396 struct loop *def_loop;
1398 if (gimple_nop_p (def))
1399 return t_false;
1401 /* Give up if the path is longer than the MAX that we allow. */
1402 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY))
1403 return t_dont_know;
1405 def_loop = loop_containing_stmt (def);
1407 switch (gimple_code (def))
1409 case GIMPLE_PHI:
1410 if (!loop_phi_node_p (def))
1411 /* DEF is a condition-phi-node. Follow the branches, and
1412 record their evolutions. Finally, merge the collected
1413 information and set the approximation to the main
1414 variable. */
1415 return follow_ssa_edge_in_condition_phi
1416 (loop, def, halting_phi, evolution_of_loop, limit);
1418 /* When the analyzed phi is the halting_phi, the
1419 depth-first search is over: we have found a path from
1420 the halting_phi to itself in the loop. */
1421 if (def == halting_phi)
1422 return t_true;
1424 /* Otherwise, the evolution of the HALTING_PHI depends
1425 on the evolution of another loop-phi-node, i.e. the
1426 evolution function is a higher degree polynomial. */
1427 if (def_loop == loop)
1428 return t_false;
1430 /* Inner loop. */
1431 if (flow_loop_nested_p (loop, def_loop))
1432 return follow_ssa_edge_inner_loop_phi
1433 (loop, def, halting_phi, evolution_of_loop, limit + 1);
1435 /* Outer loop. */
1436 return t_false;
1438 case GIMPLE_ASSIGN:
1439 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1440 evolution_of_loop, limit);
1442 default:
1443 /* At this level of abstraction, the program is just a set
1444 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1445 other node to be handled. */
1446 return t_false;
1452 /* Given a LOOP_PHI_NODE, this function determines the evolution
1453 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1455 static tree
1456 analyze_evolution_in_loop (gimple loop_phi_node,
1457 tree init_cond)
1459 int i, n = gimple_phi_num_args (loop_phi_node);
1460 tree evolution_function = chrec_not_analyzed_yet;
1461 struct loop *loop = loop_containing_stmt (loop_phi_node);
1462 basic_block bb;
1464 if (dump_file && (dump_flags & TDF_DETAILS))
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)
1513 ev_fn = chrec_dont_know;
1515 /* When there are multiple back edges of the loop (which in fact never
1516 happens currently, but nevertheless), merge their evolutions. */
1517 evolution_function = chrec_merge (evolution_function, ev_fn);
1520 if (dump_file && (dump_flags & TDF_DETAILS))
1522 fprintf (dump_file, " (evolution_function = ");
1523 print_generic_expr (dump_file, evolution_function, 0);
1524 fprintf (dump_file, "))\n");
1527 return evolution_function;
1530 /* Given a loop-phi-node, return the initial conditions of the
1531 variable on entry of the loop. When the CCP has propagated
1532 constants into the loop-phi-node, the initial condition is
1533 instantiated, otherwise the initial condition is kept symbolic.
1534 This analyzer does not analyze the evolution outside the current
1535 loop, and leaves this task to the on-demand tree reconstructor. */
1537 static tree
1538 analyze_initial_condition (gimple loop_phi_node)
1540 int i, n;
1541 tree init_cond = chrec_not_analyzed_yet;
1542 struct loop *loop = loop_containing_stmt (loop_phi_node);
1544 if (dump_file && (dump_flags & TDF_DETAILS))
1546 fprintf (dump_file, "(analyze_initial_condition \n");
1547 fprintf (dump_file, " (loop_phi_node = \n");
1548 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1549 fprintf (dump_file, ")\n");
1552 n = gimple_phi_num_args (loop_phi_node);
1553 for (i = 0; i < n; i++)
1555 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1556 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1558 /* When the branch is oriented to the loop's body, it does
1559 not contribute to the initial condition. */
1560 if (flow_bb_inside_loop_p (loop, bb))
1561 continue;
1563 if (init_cond == chrec_not_analyzed_yet)
1565 init_cond = branch;
1566 continue;
1569 if (TREE_CODE (branch) == SSA_NAME)
1571 init_cond = chrec_dont_know;
1572 break;
1575 init_cond = chrec_merge (init_cond, branch);
1578 /* Ooops -- a loop without an entry??? */
1579 if (init_cond == chrec_not_analyzed_yet)
1580 init_cond = chrec_dont_know;
1582 /* During early loop unrolling we do not have fully constant propagated IL.
1583 Handle degenerate PHIs here to not miss important unrollings. */
1584 if (TREE_CODE (init_cond) == SSA_NAME)
1586 gimple def = SSA_NAME_DEF_STMT (init_cond);
1587 tree res;
1588 if (gimple_code (def) == GIMPLE_PHI
1589 && (res = degenerate_phi_result (def)) != NULL_TREE
1590 /* Only allow invariants here, otherwise we may break
1591 loop-closed SSA form. */
1592 && is_gimple_min_invariant (res))
1593 init_cond = res;
1596 if (dump_file && (dump_flags & TDF_DETAILS))
1598 fprintf (dump_file, " (init_cond = ");
1599 print_generic_expr (dump_file, init_cond, 0);
1600 fprintf (dump_file, "))\n");
1603 return init_cond;
1606 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1608 static tree
1609 interpret_loop_phi (struct loop *loop, gimple loop_phi_node)
1611 tree res;
1612 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1613 tree init_cond;
1615 if (phi_loop != loop)
1617 struct loop *subloop;
1618 tree evolution_fn = analyze_scalar_evolution
1619 (phi_loop, PHI_RESULT (loop_phi_node));
1621 /* Dive one level deeper. */
1622 subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1624 /* Interpret the subloop. */
1625 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1626 return res;
1629 /* Otherwise really interpret the loop phi. */
1630 init_cond = analyze_initial_condition (loop_phi_node);
1631 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1633 /* Verify we maintained the correct initial condition throughout
1634 possible conversions in the SSA chain. */
1635 if (res != chrec_dont_know)
1637 tree new_init = res;
1638 if (CONVERT_EXPR_P (res)
1639 && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1640 new_init = fold_convert (TREE_TYPE (res),
1641 CHREC_LEFT (TREE_OPERAND (res, 0)));
1642 else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1643 new_init = CHREC_LEFT (res);
1644 STRIP_USELESS_TYPE_CONVERSION (new_init);
1645 gcc_assert (TREE_CODE (new_init) != POLYNOMIAL_CHREC);
1646 if (!operand_equal_p (init_cond, new_init, 0))
1647 return chrec_dont_know;
1650 return res;
1653 /* This function merges the branches of a condition-phi-node,
1654 contained in the outermost loop, and whose arguments are already
1655 analyzed. */
1657 static tree
1658 interpret_condition_phi (struct loop *loop, gimple condition_phi)
1660 int i, n = gimple_phi_num_args (condition_phi);
1661 tree res = chrec_not_analyzed_yet;
1663 for (i = 0; i < n; i++)
1665 tree branch_chrec;
1667 if (backedge_phi_arg_p (condition_phi, i))
1669 res = chrec_dont_know;
1670 break;
1673 branch_chrec = analyze_scalar_evolution
1674 (loop, PHI_ARG_DEF (condition_phi, i));
1676 res = chrec_merge (res, branch_chrec);
1679 return res;
1682 /* Interpret the operation RHS1 OP RHS2. If we didn't
1683 analyze this node before, follow the definitions until ending
1684 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1685 return path, this function propagates evolutions (ala constant copy
1686 propagation). OPND1 is not a GIMPLE expression because we could
1687 analyze the effect of an inner loop: see interpret_loop_phi. */
1689 static tree
1690 interpret_rhs_expr (struct loop *loop, gimple at_stmt,
1691 tree type, tree rhs1, enum tree_code code, tree rhs2)
1693 tree res, chrec1, chrec2;
1695 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1697 if (is_gimple_min_invariant (rhs1))
1698 return chrec_convert (type, rhs1, at_stmt);
1700 if (code == SSA_NAME)
1701 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1702 at_stmt);
1704 if (code == ASSERT_EXPR)
1706 rhs1 = ASSERT_EXPR_VAR (rhs1);
1707 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1708 at_stmt);
1712 switch (code)
1714 case ADDR_EXPR:
1715 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1716 if (TREE_CODE (TREE_OPERAND (rhs1, 0)) != MEM_REF)
1718 res = chrec_dont_know;
1719 break;
1722 rhs2 = TREE_OPERAND (TREE_OPERAND (rhs1, 0), 1);
1723 rhs1 = TREE_OPERAND (TREE_OPERAND (rhs1, 0), 0);
1724 /* Fall through. */
1726 case POINTER_PLUS_EXPR:
1727 chrec1 = analyze_scalar_evolution (loop, rhs1);
1728 chrec2 = analyze_scalar_evolution (loop, rhs2);
1729 chrec1 = chrec_convert (type, chrec1, at_stmt);
1730 chrec2 = chrec_convert (sizetype, chrec2, at_stmt);
1731 res = chrec_fold_plus (type, chrec1, chrec2);
1732 break;
1734 case PLUS_EXPR:
1735 chrec1 = analyze_scalar_evolution (loop, rhs1);
1736 chrec2 = analyze_scalar_evolution (loop, rhs2);
1737 chrec1 = chrec_convert (type, chrec1, at_stmt);
1738 chrec2 = chrec_convert (type, chrec2, at_stmt);
1739 res = chrec_fold_plus (type, chrec1, chrec2);
1740 break;
1742 case MINUS_EXPR:
1743 chrec1 = analyze_scalar_evolution (loop, rhs1);
1744 chrec2 = analyze_scalar_evolution (loop, rhs2);
1745 chrec1 = chrec_convert (type, chrec1, at_stmt);
1746 chrec2 = chrec_convert (type, chrec2, at_stmt);
1747 res = chrec_fold_minus (type, chrec1, chrec2);
1748 break;
1750 case NEGATE_EXPR:
1751 chrec1 = analyze_scalar_evolution (loop, rhs1);
1752 chrec1 = chrec_convert (type, chrec1, at_stmt);
1753 /* TYPE may be integer, real or complex, so use fold_convert. */
1754 res = chrec_fold_multiply (type, chrec1,
1755 fold_convert (type, integer_minus_one_node));
1756 break;
1758 case BIT_NOT_EXPR:
1759 /* Handle ~X as -1 - X. */
1760 chrec1 = analyze_scalar_evolution (loop, rhs1);
1761 chrec1 = chrec_convert (type, chrec1, at_stmt);
1762 res = chrec_fold_minus (type,
1763 fold_convert (type, integer_minus_one_node),
1764 chrec1);
1765 break;
1767 case MULT_EXPR:
1768 chrec1 = analyze_scalar_evolution (loop, rhs1);
1769 chrec2 = analyze_scalar_evolution (loop, rhs2);
1770 chrec1 = chrec_convert (type, chrec1, at_stmt);
1771 chrec2 = chrec_convert (type, chrec2, at_stmt);
1772 res = chrec_fold_multiply (type, chrec1, chrec2);
1773 break;
1775 CASE_CONVERT:
1776 chrec1 = analyze_scalar_evolution (loop, rhs1);
1777 res = chrec_convert (type, chrec1, at_stmt);
1778 break;
1780 default:
1781 res = chrec_dont_know;
1782 break;
1785 return res;
1788 /* Interpret the expression EXPR. */
1790 static tree
1791 interpret_expr (struct loop *loop, gimple at_stmt, tree expr)
1793 enum tree_code code;
1794 tree type = TREE_TYPE (expr), op0, op1;
1796 if (automatically_generated_chrec_p (expr))
1797 return expr;
1799 if (TREE_CODE (expr) == POLYNOMIAL_CHREC)
1800 return chrec_dont_know;
1802 extract_ops_from_tree (expr, &code, &op0, &op1);
1804 return interpret_rhs_expr (loop, at_stmt, type,
1805 op0, code, op1);
1808 /* Interpret the rhs of the assignment STMT. */
1810 static tree
1811 interpret_gimple_assign (struct loop *loop, gimple stmt)
1813 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1814 enum tree_code code = gimple_assign_rhs_code (stmt);
1816 return interpret_rhs_expr (loop, stmt, type,
1817 gimple_assign_rhs1 (stmt), code,
1818 gimple_assign_rhs2 (stmt));
1823 /* This section contains all the entry points:
1824 - number_of_iterations_in_loop,
1825 - analyze_scalar_evolution,
1826 - instantiate_parameters.
1829 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1830 common ancestor of DEF_LOOP and USE_LOOP. */
1832 static tree
1833 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1834 struct loop *def_loop,
1835 tree ev)
1837 bool val;
1838 tree res;
1840 if (def_loop == wrto_loop)
1841 return ev;
1843 def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
1844 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1846 if (no_evolution_in_loop_p (res, wrto_loop->num, &val) && val)
1847 return res;
1849 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1852 /* Helper recursive function. */
1854 static tree
1855 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1857 tree type = TREE_TYPE (var);
1858 gimple def;
1859 basic_block bb;
1860 struct loop *def_loop;
1862 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1863 return chrec_dont_know;
1865 if (TREE_CODE (var) != SSA_NAME)
1866 return interpret_expr (loop, NULL, var);
1868 def = SSA_NAME_DEF_STMT (var);
1869 bb = gimple_bb (def);
1870 def_loop = bb ? bb->loop_father : NULL;
1872 if (bb == NULL
1873 || !flow_bb_inside_loop_p (loop, bb))
1875 /* Keep the symbolic form. */
1876 res = var;
1877 goto set_and_end;
1880 if (res != chrec_not_analyzed_yet)
1882 if (loop != bb->loop_father)
1883 res = compute_scalar_evolution_in_loop
1884 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1886 goto set_and_end;
1889 if (loop != def_loop)
1891 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1892 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1894 goto set_and_end;
1897 switch (gimple_code (def))
1899 case GIMPLE_ASSIGN:
1900 res = interpret_gimple_assign (loop, def);
1901 break;
1903 case GIMPLE_PHI:
1904 if (loop_phi_node_p (def))
1905 res = interpret_loop_phi (loop, def);
1906 else
1907 res = interpret_condition_phi (loop, def);
1908 break;
1910 default:
1911 res = chrec_dont_know;
1912 break;
1915 set_and_end:
1917 /* Keep the symbolic form. */
1918 if (res == chrec_dont_know)
1919 res = var;
1921 if (loop == def_loop)
1922 set_scalar_evolution (block_before_loop (loop), var, res);
1924 return res;
1927 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
1928 LOOP. LOOP is the loop in which the variable is used.
1930 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
1931 pointer to the statement that uses this variable, in order to
1932 determine the evolution function of the variable, use the following
1933 calls:
1935 loop_p loop = loop_containing_stmt (stmt);
1936 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
1937 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
1940 tree
1941 analyze_scalar_evolution (struct loop *loop, tree var)
1943 tree res;
1945 if (dump_file && (dump_flags & TDF_DETAILS))
1947 fprintf (dump_file, "(analyze_scalar_evolution \n");
1948 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
1949 fprintf (dump_file, " (scalar = ");
1950 print_generic_expr (dump_file, var, 0);
1951 fprintf (dump_file, ")\n");
1954 res = get_scalar_evolution (block_before_loop (loop), var);
1955 res = analyze_scalar_evolution_1 (loop, var, res);
1957 if (dump_file && (dump_flags & TDF_DETAILS))
1958 fprintf (dump_file, ")\n");
1960 return res;
1963 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
1964 WRTO_LOOP (which should be a superloop of USE_LOOP)
1966 FOLDED_CASTS is set to true if resolve_mixers used
1967 chrec_convert_aggressive (TODO -- not really, we are way too conservative
1968 at the moment in order to keep things simple).
1970 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
1971 example:
1973 for (i = 0; i < 100; i++) -- loop 1
1975 for (j = 0; j < 100; j++) -- loop 2
1977 k1 = i;
1978 k2 = j;
1980 use2 (k1, k2);
1982 for (t = 0; t < 100; t++) -- loop 3
1983 use3 (k1, k2);
1986 use1 (k1, k2);
1989 Both k1 and k2 are invariants in loop3, thus
1990 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
1991 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
1993 As they are invariant, it does not matter whether we consider their
1994 usage in loop 3 or loop 2, hence
1995 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
1996 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
1997 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
1998 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
2000 Similarly for their evolutions with respect to loop 1. The values of K2
2001 in the use in loop 2 vary independently on loop 1, thus we cannot express
2002 the evolution with respect to loop 1:
2003 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
2004 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
2005 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
2006 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
2008 The value of k2 in the use in loop 1 is known, though:
2009 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
2010 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
2013 static tree
2014 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
2015 tree version, bool *folded_casts)
2017 bool val = false;
2018 tree ev = version, tmp;
2020 /* We cannot just do
2022 tmp = analyze_scalar_evolution (use_loop, version);
2023 ev = resolve_mixers (wrto_loop, tmp);
2025 as resolve_mixers would query the scalar evolution with respect to
2026 wrto_loop. For example, in the situation described in the function
2027 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2028 version = k2. Then
2030 analyze_scalar_evolution (use_loop, version) = k2
2032 and resolve_mixers (loop1, k2) finds that the value of k2 in loop 1
2033 is 100, which is a wrong result, since we are interested in the
2034 value in loop 3.
2036 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2037 each time checking that there is no evolution in the inner loop. */
2039 if (folded_casts)
2040 *folded_casts = false;
2041 while (1)
2043 tmp = analyze_scalar_evolution (use_loop, ev);
2044 ev = resolve_mixers (use_loop, tmp);
2046 if (folded_casts && tmp != ev)
2047 *folded_casts = true;
2049 if (use_loop == wrto_loop)
2050 return ev;
2052 /* If the value of the use changes in the inner loop, we cannot express
2053 its value in the outer loop (we might try to return interval chrec,
2054 but we do not have a user for it anyway) */
2055 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2056 || !val)
2057 return chrec_dont_know;
2059 use_loop = loop_outer (use_loop);
2063 /* Returns from CACHE the value for VERSION instantiated below
2064 INSTANTIATED_BELOW block. */
2066 static tree
2067 get_instantiated_value (htab_t cache, basic_block instantiated_below,
2068 tree version)
2070 struct scev_info_str *info, pattern;
2072 pattern.var = version;
2073 pattern.instantiated_below = instantiated_below;
2074 info = (struct scev_info_str *) htab_find (cache, &pattern);
2076 if (info)
2077 return info->chrec;
2078 else
2079 return NULL_TREE;
2082 /* Sets in CACHE the value of VERSION instantiated below basic block
2083 INSTANTIATED_BELOW to VAL. */
2085 static void
2086 set_instantiated_value (htab_t cache, basic_block instantiated_below,
2087 tree version, tree val)
2089 struct scev_info_str *info, pattern;
2090 PTR *slot;
2092 pattern.var = version;
2093 pattern.instantiated_below = instantiated_below;
2094 slot = htab_find_slot (cache, &pattern, INSERT);
2096 if (!*slot)
2097 *slot = new_scev_info_str (instantiated_below, version);
2098 info = (struct scev_info_str *) *slot;
2099 info->chrec = val;
2102 /* Return the closed_loop_phi node for VAR. If there is none, return
2103 NULL_TREE. */
2105 static tree
2106 loop_closed_phi_def (tree var)
2108 struct loop *loop;
2109 edge exit;
2110 gimple phi;
2111 gimple_stmt_iterator psi;
2113 if (var == NULL_TREE
2114 || TREE_CODE (var) != SSA_NAME)
2115 return NULL_TREE;
2117 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2118 exit = single_exit (loop);
2119 if (!exit)
2120 return NULL_TREE;
2122 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2124 phi = gsi_stmt (psi);
2125 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2126 return PHI_RESULT (phi);
2129 return NULL_TREE;
2132 static tree instantiate_scev_r (basic_block, struct loop *, tree, bool,
2133 htab_t, int);
2135 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2136 and EVOLUTION_LOOP, that were left under a symbolic form.
2138 CHREC is an SSA_NAME to be instantiated.
2140 CACHE is the cache of already instantiated values.
2142 FOLD_CONVERSIONS should be set to true when the conversions that
2143 may wrap in signed/pointer type are folded, as long as the value of
2144 the chrec is preserved.
2146 SIZE_EXPR is used for computing the size of the expression to be
2147 instantiated, and to stop if it exceeds some limit. */
2149 static tree
2150 instantiate_scev_name (basic_block instantiate_below,
2151 struct loop *evolution_loop, tree chrec,
2152 bool fold_conversions, htab_t cache, int size_expr)
2154 tree res;
2155 struct loop *def_loop;
2156 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2158 /* A parameter (or loop invariant and we do not want to include
2159 evolutions in outer loops), nothing to do. */
2160 if (!def_bb
2161 || loop_depth (def_bb->loop_father) == 0
2162 || dominated_by_p (CDI_DOMINATORS, instantiate_below, def_bb))
2163 return chrec;
2165 /* We cache the value of instantiated variable to avoid exponential
2166 time complexity due to reevaluations. We also store the convenient
2167 value in the cache in order to prevent infinite recursion -- we do
2168 not want to instantiate the SSA_NAME if it is in a mixer
2169 structure. This is used for avoiding the instantiation of
2170 recursively defined functions, such as:
2172 | a_2 -> {0, +, 1, +, a_2}_1 */
2174 res = get_instantiated_value (cache, instantiate_below, chrec);
2175 if (res)
2176 return res;
2178 res = chrec_dont_know;
2179 set_instantiated_value (cache, instantiate_below, chrec, res);
2181 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2183 /* If the analysis yields a parametric chrec, instantiate the
2184 result again. */
2185 res = analyze_scalar_evolution (def_loop, chrec);
2187 /* Don't instantiate default definitions. */
2188 if (TREE_CODE (res) == SSA_NAME
2189 && SSA_NAME_IS_DEFAULT_DEF (res))
2192 /* Don't instantiate loop-closed-ssa phi nodes. */
2193 else if (TREE_CODE (res) == SSA_NAME
2194 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2195 > loop_depth (def_loop))
2197 if (res == chrec)
2198 res = loop_closed_phi_def (chrec);
2199 else
2200 res = chrec;
2202 /* When there is no loop_closed_phi_def, it means that the
2203 variable is not used after the loop: try to still compute the
2204 value of the variable when exiting the loop. */
2205 if (res == NULL_TREE)
2207 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2208 res = analyze_scalar_evolution (loop, chrec);
2209 res = compute_overall_effect_of_inner_loop (loop, res);
2210 res = instantiate_scev_r (instantiate_below, evolution_loop, res,
2211 fold_conversions, cache, size_expr);
2213 else if (!dominated_by_p (CDI_DOMINATORS, instantiate_below,
2214 gimple_bb (SSA_NAME_DEF_STMT (res))))
2215 res = chrec_dont_know;
2218 else if (res != chrec_dont_know)
2219 res = instantiate_scev_r (instantiate_below, evolution_loop, res,
2220 fold_conversions, cache, size_expr);
2222 /* Store the correct value to the cache. */
2223 set_instantiated_value (cache, instantiate_below, chrec, res);
2224 return res;
2227 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2228 and EVOLUTION_LOOP, that were left under a symbolic form.
2230 CHREC is a polynomial chain of recurrence to be instantiated.
2232 CACHE is the cache of already instantiated values.
2234 FOLD_CONVERSIONS should be set to true when the conversions that
2235 may wrap in signed/pointer type are folded, as long as the value of
2236 the chrec is preserved.
2238 SIZE_EXPR is used for computing the size of the expression to be
2239 instantiated, and to stop if it exceeds some limit. */
2241 static tree
2242 instantiate_scev_poly (basic_block instantiate_below,
2243 struct loop *evolution_loop, tree chrec,
2244 bool fold_conversions, htab_t cache, int size_expr)
2246 tree op1;
2247 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2248 CHREC_LEFT (chrec), fold_conversions, cache,
2249 size_expr);
2250 if (op0 == chrec_dont_know)
2251 return chrec_dont_know;
2253 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2254 CHREC_RIGHT (chrec), fold_conversions, cache,
2255 size_expr);
2256 if (op1 == chrec_dont_know)
2257 return chrec_dont_know;
2259 if (CHREC_LEFT (chrec) != op0
2260 || CHREC_RIGHT (chrec) != op1)
2262 unsigned var = CHREC_VARIABLE (chrec);
2264 /* When the instantiated stride or base has an evolution in an
2265 innermost loop, return chrec_dont_know, as this is not a
2266 valid SCEV representation. In the reduced testcase for
2267 PR40281 we would have {0, +, {1, +, 1}_2}_1 that has no
2268 meaning. */
2269 if ((tree_is_chrec (op0) && CHREC_VARIABLE (op0) > var)
2270 || (tree_is_chrec (op1) && CHREC_VARIABLE (op1) > var))
2271 return chrec_dont_know;
2273 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2274 chrec = build_polynomial_chrec (var, op0, op1);
2277 return chrec;
2280 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2281 and EVOLUTION_LOOP, that were left under a symbolic form.
2283 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2285 CACHE is the cache of already instantiated values.
2287 FOLD_CONVERSIONS should be set to true when the conversions that
2288 may wrap in signed/pointer type are folded, as long as the value of
2289 the chrec is preserved.
2291 SIZE_EXPR is used for computing the size of the expression to be
2292 instantiated, and to stop if it exceeds some limit. */
2294 static tree
2295 instantiate_scev_binary (basic_block instantiate_below,
2296 struct loop *evolution_loop, tree chrec, enum tree_code code,
2297 tree type, tree c0, tree c1,
2298 bool fold_conversions, htab_t cache, int size_expr)
2300 tree op1;
2301 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2302 c0, fold_conversions, cache,
2303 size_expr);
2304 if (op0 == chrec_dont_know)
2305 return chrec_dont_know;
2307 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2308 c1, fold_conversions, cache,
2309 size_expr);
2310 if (op1 == chrec_dont_know)
2311 return chrec_dont_know;
2313 if (c0 != op0
2314 || c1 != op1)
2316 op0 = chrec_convert (type, op0, NULL);
2317 op1 = chrec_convert_rhs (type, op1, NULL);
2319 switch (code)
2321 case POINTER_PLUS_EXPR:
2322 case PLUS_EXPR:
2323 return chrec_fold_plus (type, op0, op1);
2325 case MINUS_EXPR:
2326 return chrec_fold_minus (type, op0, op1);
2328 case MULT_EXPR:
2329 return chrec_fold_multiply (type, op0, op1);
2331 default:
2332 gcc_unreachable ();
2336 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2339 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2340 and EVOLUTION_LOOP, that were left under a symbolic form.
2342 "CHREC" is an array reference to be instantiated.
2344 CACHE is the cache of already instantiated values.
2346 FOLD_CONVERSIONS should be set to true when the conversions that
2347 may wrap in signed/pointer type are folded, as long as the value of
2348 the chrec is preserved.
2350 SIZE_EXPR is used for computing the size of the expression to be
2351 instantiated, and to stop if it exceeds some limit. */
2353 static tree
2354 instantiate_array_ref (basic_block instantiate_below,
2355 struct loop *evolution_loop, tree chrec,
2356 bool fold_conversions, htab_t cache, int size_expr)
2358 tree res;
2359 tree index = TREE_OPERAND (chrec, 1);
2360 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop, index,
2361 fold_conversions, cache, size_expr);
2363 if (op1 == chrec_dont_know)
2364 return chrec_dont_know;
2366 if (chrec && op1 == index)
2367 return chrec;
2369 res = unshare_expr (chrec);
2370 TREE_OPERAND (res, 1) = op1;
2371 return res;
2374 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2375 and EVOLUTION_LOOP, that were left under a symbolic form.
2377 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2378 instantiated.
2380 CACHE is the cache of already instantiated values.
2382 FOLD_CONVERSIONS should be set to true when the conversions that
2383 may wrap in signed/pointer type are folded, as long as the value of
2384 the chrec is preserved.
2386 SIZE_EXPR is used for computing the size of the expression to be
2387 instantiated, and to stop if it exceeds some limit. */
2389 static tree
2390 instantiate_scev_convert (basic_block instantiate_below,
2391 struct loop *evolution_loop, tree chrec,
2392 tree type, tree op,
2393 bool fold_conversions, htab_t cache, int size_expr)
2395 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, op,
2396 fold_conversions, cache, size_expr);
2398 if (op0 == chrec_dont_know)
2399 return chrec_dont_know;
2401 if (fold_conversions)
2403 tree tmp = chrec_convert_aggressive (type, op0);
2404 if (tmp)
2405 return tmp;
2408 if (chrec && op0 == op)
2409 return chrec;
2411 /* If we used chrec_convert_aggressive, we can no longer assume that
2412 signed chrecs do not overflow, as chrec_convert does, so avoid
2413 calling it in that case. */
2414 if (fold_conversions)
2415 return fold_convert (type, op0);
2417 return chrec_convert (type, op0, NULL);
2420 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2421 and EVOLUTION_LOOP, that were left under a symbolic form.
2423 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2424 Handle ~X as -1 - X.
2425 Handle -X as -1 * X.
2427 CACHE is the cache of already instantiated values.
2429 FOLD_CONVERSIONS should be set to true when the conversions that
2430 may wrap in signed/pointer type are folded, as long as the value of
2431 the chrec is preserved.
2433 SIZE_EXPR is used for computing the size of the expression to be
2434 instantiated, and to stop if it exceeds some limit. */
2436 static tree
2437 instantiate_scev_not (basic_block instantiate_below,
2438 struct loop *evolution_loop, tree chrec,
2439 enum tree_code code, tree type, tree op,
2440 bool fold_conversions, htab_t cache, int size_expr)
2442 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, op,
2443 fold_conversions, cache, size_expr);
2445 if (op0 == chrec_dont_know)
2446 return chrec_dont_know;
2448 if (op != op0)
2450 op0 = chrec_convert (type, op0, NULL);
2452 switch (code)
2454 case BIT_NOT_EXPR:
2455 return chrec_fold_minus
2456 (type, fold_convert (type, integer_minus_one_node), op0);
2458 case NEGATE_EXPR:
2459 return chrec_fold_multiply
2460 (type, fold_convert (type, integer_minus_one_node), op0);
2462 default:
2463 gcc_unreachable ();
2467 return chrec ? chrec : fold_build1 (code, type, op0);
2470 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2471 and EVOLUTION_LOOP, that were left under a symbolic form.
2473 CHREC is an expression with 3 operands to be instantiated.
2475 CACHE is the cache of already instantiated values.
2477 FOLD_CONVERSIONS should be set to true when the conversions that
2478 may wrap in signed/pointer type are folded, as long as the value of
2479 the chrec is preserved.
2481 SIZE_EXPR is used for computing the size of the expression to be
2482 instantiated, and to stop if it exceeds some limit. */
2484 static tree
2485 instantiate_scev_3 (basic_block instantiate_below,
2486 struct loop *evolution_loop, tree chrec,
2487 bool fold_conversions, htab_t cache, int size_expr)
2489 tree op1, op2;
2490 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2491 TREE_OPERAND (chrec, 0),
2492 fold_conversions, cache, size_expr);
2493 if (op0 == chrec_dont_know)
2494 return chrec_dont_know;
2496 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2497 TREE_OPERAND (chrec, 1),
2498 fold_conversions, cache, size_expr);
2499 if (op1 == chrec_dont_know)
2500 return chrec_dont_know;
2502 op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2503 TREE_OPERAND (chrec, 2),
2504 fold_conversions, cache, size_expr);
2505 if (op2 == chrec_dont_know)
2506 return chrec_dont_know;
2508 if (op0 == TREE_OPERAND (chrec, 0)
2509 && op1 == TREE_OPERAND (chrec, 1)
2510 && op2 == TREE_OPERAND (chrec, 2))
2511 return chrec;
2513 return fold_build3 (TREE_CODE (chrec),
2514 TREE_TYPE (chrec), op0, op1, op2);
2517 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2518 and EVOLUTION_LOOP, that were left under a symbolic form.
2520 CHREC is an expression with 2 operands to be instantiated.
2522 CACHE is the cache of already instantiated values.
2524 FOLD_CONVERSIONS should be set to true when the conversions that
2525 may wrap in signed/pointer type are folded, as long as the value of
2526 the chrec is preserved.
2528 SIZE_EXPR is used for computing the size of the expression to be
2529 instantiated, and to stop if it exceeds some limit. */
2531 static tree
2532 instantiate_scev_2 (basic_block instantiate_below,
2533 struct loop *evolution_loop, tree chrec,
2534 bool fold_conversions, htab_t cache, int size_expr)
2536 tree op1;
2537 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2538 TREE_OPERAND (chrec, 0),
2539 fold_conversions, cache, size_expr);
2540 if (op0 == chrec_dont_know)
2541 return chrec_dont_know;
2543 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2544 TREE_OPERAND (chrec, 1),
2545 fold_conversions, cache, size_expr);
2546 if (op1 == chrec_dont_know)
2547 return chrec_dont_know;
2549 if (op0 == TREE_OPERAND (chrec, 0)
2550 && op1 == TREE_OPERAND (chrec, 1))
2551 return chrec;
2553 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2556 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2557 and EVOLUTION_LOOP, that were left under a symbolic form.
2559 CHREC is an expression with 2 operands to be instantiated.
2561 CACHE is the cache of already instantiated values.
2563 FOLD_CONVERSIONS should be set to true when the conversions that
2564 may wrap in signed/pointer type are folded, as long as the value of
2565 the chrec is preserved.
2567 SIZE_EXPR is used for computing the size of the expression to be
2568 instantiated, and to stop if it exceeds some limit. */
2570 static tree
2571 instantiate_scev_1 (basic_block instantiate_below,
2572 struct loop *evolution_loop, tree chrec,
2573 bool fold_conversions, htab_t cache, int size_expr)
2575 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2576 TREE_OPERAND (chrec, 0),
2577 fold_conversions, cache, size_expr);
2579 if (op0 == chrec_dont_know)
2580 return chrec_dont_know;
2582 if (op0 == TREE_OPERAND (chrec, 0))
2583 return chrec;
2585 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2588 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2589 and EVOLUTION_LOOP, that were left under a symbolic form.
2591 CHREC is the scalar evolution to instantiate.
2593 CACHE is the cache of already instantiated values.
2595 FOLD_CONVERSIONS should be set to true when the conversions that
2596 may wrap in signed/pointer type are folded, as long as the value of
2597 the chrec is preserved.
2599 SIZE_EXPR is used for computing the size of the expression to be
2600 instantiated, and to stop if it exceeds some limit. */
2602 static tree
2603 instantiate_scev_r (basic_block instantiate_below,
2604 struct loop *evolution_loop, tree chrec,
2605 bool fold_conversions, htab_t cache, int size_expr)
2607 /* Give up if the expression is larger than the MAX that we allow. */
2608 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2609 return chrec_dont_know;
2611 if (chrec == NULL_TREE
2612 || automatically_generated_chrec_p (chrec)
2613 || is_gimple_min_invariant (chrec))
2614 return chrec;
2616 switch (TREE_CODE (chrec))
2618 case SSA_NAME:
2619 return instantiate_scev_name (instantiate_below, evolution_loop, chrec,
2620 fold_conversions, cache, size_expr);
2622 case POLYNOMIAL_CHREC:
2623 return instantiate_scev_poly (instantiate_below, evolution_loop, chrec,
2624 fold_conversions, cache, size_expr);
2626 case POINTER_PLUS_EXPR:
2627 case PLUS_EXPR:
2628 case MINUS_EXPR:
2629 case MULT_EXPR:
2630 return instantiate_scev_binary (instantiate_below, evolution_loop, chrec,
2631 TREE_CODE (chrec), chrec_type (chrec),
2632 TREE_OPERAND (chrec, 0),
2633 TREE_OPERAND (chrec, 1),
2634 fold_conversions, cache, size_expr);
2636 CASE_CONVERT:
2637 return instantiate_scev_convert (instantiate_below, evolution_loop, chrec,
2638 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2639 fold_conversions, cache, size_expr);
2641 case NEGATE_EXPR:
2642 case BIT_NOT_EXPR:
2643 return instantiate_scev_not (instantiate_below, evolution_loop, chrec,
2644 TREE_CODE (chrec), TREE_TYPE (chrec),
2645 TREE_OPERAND (chrec, 0),
2646 fold_conversions, cache, size_expr);
2648 case SCEV_NOT_KNOWN:
2649 return chrec_dont_know;
2651 case SCEV_KNOWN:
2652 return chrec_known;
2654 case ARRAY_REF:
2655 return instantiate_array_ref (instantiate_below, evolution_loop, chrec,
2656 fold_conversions, cache, size_expr);
2658 default:
2659 break;
2662 if (VL_EXP_CLASS_P (chrec))
2663 return chrec_dont_know;
2665 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2667 case 3:
2668 return instantiate_scev_3 (instantiate_below, evolution_loop, chrec,
2669 fold_conversions, cache, size_expr);
2671 case 2:
2672 return instantiate_scev_2 (instantiate_below, evolution_loop, chrec,
2673 fold_conversions, cache, size_expr);
2675 case 1:
2676 return instantiate_scev_1 (instantiate_below, evolution_loop, chrec,
2677 fold_conversions, cache, size_expr);
2679 case 0:
2680 return chrec;
2682 default:
2683 break;
2686 /* Too complicated to handle. */
2687 return chrec_dont_know;
2690 /* Analyze all the parameters of the chrec that were left under a
2691 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2692 recursive instantiation of parameters: a parameter is a variable
2693 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2694 a function parameter. */
2696 tree
2697 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2698 tree chrec)
2700 tree res;
2701 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2703 if (dump_file && (dump_flags & TDF_DETAILS))
2705 fprintf (dump_file, "(instantiate_scev \n");
2706 fprintf (dump_file, " (instantiate_below = %d)\n", instantiate_below->index);
2707 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2708 fprintf (dump_file, " (chrec = ");
2709 print_generic_expr (dump_file, chrec, 0);
2710 fprintf (dump_file, ")\n");
2713 res = instantiate_scev_r (instantiate_below, evolution_loop, chrec, false,
2714 cache, 0);
2716 if (dump_file && (dump_flags & TDF_DETAILS))
2718 fprintf (dump_file, " (res = ");
2719 print_generic_expr (dump_file, res, 0);
2720 fprintf (dump_file, "))\n");
2723 htab_delete (cache);
2725 return res;
2728 /* Similar to instantiate_parameters, but does not introduce the
2729 evolutions in outer loops for LOOP invariants in CHREC, and does not
2730 care about causing overflows, as long as they do not affect value
2731 of an expression. */
2733 tree
2734 resolve_mixers (struct loop *loop, tree chrec)
2736 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2737 tree ret = instantiate_scev_r (block_before_loop (loop), loop, chrec, true,
2738 cache, 0);
2739 htab_delete (cache);
2740 return ret;
2743 /* Entry point for the analysis of the number of iterations pass.
2744 This function tries to safely approximate the number of iterations
2745 the loop will run. When this property is not decidable at compile
2746 time, the result is chrec_dont_know. Otherwise the result is a
2747 scalar or a symbolic parameter. When the number of iterations may
2748 be equal to zero and the property cannot be determined at compile
2749 time, the result is a COND_EXPR that represents in a symbolic form
2750 the conditions under which the number of iterations is not zero.
2752 Example of analysis: suppose that the loop has an exit condition:
2754 "if (b > 49) goto end_loop;"
2756 and that in a previous analysis we have determined that the
2757 variable 'b' has an evolution function:
2759 "EF = {23, +, 5}_2".
2761 When we evaluate the function at the point 5, i.e. the value of the
2762 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2763 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2764 the loop body has been executed 6 times. */
2766 tree
2767 number_of_latch_executions (struct loop *loop)
2769 edge exit;
2770 struct tree_niter_desc niter_desc;
2771 tree may_be_zero;
2772 tree res;
2774 /* Determine whether the number of iterations in loop has already
2775 been computed. */
2776 res = loop->nb_iterations;
2777 if (res)
2778 return res;
2780 may_be_zero = NULL_TREE;
2782 if (dump_file && (dump_flags & TDF_DETAILS))
2783 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2785 res = chrec_dont_know;
2786 exit = single_exit (loop);
2788 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2790 may_be_zero = niter_desc.may_be_zero;
2791 res = niter_desc.niter;
2794 if (res == chrec_dont_know
2795 || !may_be_zero
2796 || integer_zerop (may_be_zero))
2798 else if (integer_nonzerop (may_be_zero))
2799 res = build_int_cst (TREE_TYPE (res), 0);
2801 else if (COMPARISON_CLASS_P (may_be_zero))
2802 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2803 build_int_cst (TREE_TYPE (res), 0), res);
2804 else
2805 res = chrec_dont_know;
2807 if (dump_file && (dump_flags & TDF_DETAILS))
2809 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2810 print_generic_expr (dump_file, res, 0);
2811 fprintf (dump_file, "))\n");
2814 loop->nb_iterations = res;
2815 return res;
2818 /* Returns the number of executions of the exit condition of LOOP,
2819 i.e., the number by one higher than number_of_latch_executions.
2820 Note that unlike number_of_latch_executions, this number does
2821 not necessarily fit in the unsigned variant of the type of
2822 the control variable -- if the number of iterations is a constant,
2823 we return chrec_dont_know if adding one to number_of_latch_executions
2824 overflows; however, in case the number of iterations is symbolic
2825 expression, the caller is responsible for dealing with this
2826 the possible overflow. */
2828 tree
2829 number_of_exit_cond_executions (struct loop *loop)
2831 tree ret = number_of_latch_executions (loop);
2832 tree type = chrec_type (ret);
2834 if (chrec_contains_undetermined (ret))
2835 return ret;
2837 ret = chrec_fold_plus (type, ret, build_int_cst (type, 1));
2838 if (TREE_CODE (ret) == INTEGER_CST
2839 && TREE_OVERFLOW (ret))
2840 return chrec_dont_know;
2842 return ret;
2845 /* One of the drivers for testing the scalar evolutions analysis.
2846 This function computes the number of iterations for all the loops
2847 from the EXIT_CONDITIONS array. */
2849 static void
2850 number_of_iterations_for_all_loops (VEC(gimple,heap) **exit_conditions)
2852 unsigned int i;
2853 unsigned nb_chrec_dont_know_loops = 0;
2854 unsigned nb_static_loops = 0;
2855 gimple cond;
2857 FOR_EACH_VEC_ELT (gimple, *exit_conditions, i, cond)
2859 tree res = number_of_latch_executions (loop_containing_stmt (cond));
2860 if (chrec_contains_undetermined (res))
2861 nb_chrec_dont_know_loops++;
2862 else
2863 nb_static_loops++;
2866 if (dump_file)
2868 fprintf (dump_file, "\n(\n");
2869 fprintf (dump_file, "-----------------------------------------\n");
2870 fprintf (dump_file, "%d\tnb_chrec_dont_know_loops\n", nb_chrec_dont_know_loops);
2871 fprintf (dump_file, "%d\tnb_static_loops\n", nb_static_loops);
2872 fprintf (dump_file, "%d\tnb_total_loops\n", number_of_loops ());
2873 fprintf (dump_file, "-----------------------------------------\n");
2874 fprintf (dump_file, ")\n\n");
2876 print_loops (dump_file, 3);
2882 /* Counters for the stats. */
2884 struct chrec_stats
2886 unsigned nb_chrecs;
2887 unsigned nb_affine;
2888 unsigned nb_affine_multivar;
2889 unsigned nb_higher_poly;
2890 unsigned nb_chrec_dont_know;
2891 unsigned nb_undetermined;
2894 /* Reset the counters. */
2896 static inline void
2897 reset_chrecs_counters (struct chrec_stats *stats)
2899 stats->nb_chrecs = 0;
2900 stats->nb_affine = 0;
2901 stats->nb_affine_multivar = 0;
2902 stats->nb_higher_poly = 0;
2903 stats->nb_chrec_dont_know = 0;
2904 stats->nb_undetermined = 0;
2907 /* Dump the contents of a CHREC_STATS structure. */
2909 static void
2910 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2912 fprintf (file, "\n(\n");
2913 fprintf (file, "-----------------------------------------\n");
2914 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2915 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2916 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2917 stats->nb_higher_poly);
2918 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2919 fprintf (file, "-----------------------------------------\n");
2920 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2921 fprintf (file, "%d\twith undetermined coefficients\n",
2922 stats->nb_undetermined);
2923 fprintf (file, "-----------------------------------------\n");
2924 fprintf (file, "%d\tchrecs in the scev database\n",
2925 (int) htab_elements (scalar_evolution_info));
2926 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2927 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2928 fprintf (file, "-----------------------------------------\n");
2929 fprintf (file, ")\n\n");
2932 /* Gather statistics about CHREC. */
2934 static void
2935 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2937 if (dump_file && (dump_flags & TDF_STATS))
2939 fprintf (dump_file, "(classify_chrec ");
2940 print_generic_expr (dump_file, chrec, 0);
2941 fprintf (dump_file, "\n");
2944 stats->nb_chrecs++;
2946 if (chrec == NULL_TREE)
2948 stats->nb_undetermined++;
2949 return;
2952 switch (TREE_CODE (chrec))
2954 case POLYNOMIAL_CHREC:
2955 if (evolution_function_is_affine_p (chrec))
2957 if (dump_file && (dump_flags & TDF_STATS))
2958 fprintf (dump_file, " affine_univariate\n");
2959 stats->nb_affine++;
2961 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
2963 if (dump_file && (dump_flags & TDF_STATS))
2964 fprintf (dump_file, " affine_multivariate\n");
2965 stats->nb_affine_multivar++;
2967 else
2969 if (dump_file && (dump_flags & TDF_STATS))
2970 fprintf (dump_file, " higher_degree_polynomial\n");
2971 stats->nb_higher_poly++;
2974 break;
2976 default:
2977 break;
2980 if (chrec_contains_undetermined (chrec))
2982 if (dump_file && (dump_flags & TDF_STATS))
2983 fprintf (dump_file, " undetermined\n");
2984 stats->nb_undetermined++;
2987 if (dump_file && (dump_flags & TDF_STATS))
2988 fprintf (dump_file, ")\n");
2991 /* One of the drivers for testing the scalar evolutions analysis.
2992 This function analyzes the scalar evolution of all the scalars
2993 defined as loop phi nodes in one of the loops from the
2994 EXIT_CONDITIONS array.
2996 TODO Optimization: A loop is in canonical form if it contains only
2997 a single scalar loop phi node. All the other scalars that have an
2998 evolution in the loop are rewritten in function of this single
2999 index. This allows the parallelization of the loop. */
3001 static void
3002 analyze_scalar_evolution_for_all_loop_phi_nodes (VEC(gimple,heap) **exit_conditions)
3004 unsigned int i;
3005 struct chrec_stats stats;
3006 gimple cond, phi;
3007 gimple_stmt_iterator psi;
3009 reset_chrecs_counters (&stats);
3011 FOR_EACH_VEC_ELT (gimple, *exit_conditions, i, cond)
3013 struct loop *loop;
3014 basic_block bb;
3015 tree chrec;
3017 loop = loop_containing_stmt (cond);
3018 bb = loop->header;
3020 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3022 phi = gsi_stmt (psi);
3023 if (is_gimple_reg (PHI_RESULT (phi)))
3025 chrec = instantiate_parameters
3026 (loop,
3027 analyze_scalar_evolution (loop, PHI_RESULT (phi)));
3029 if (dump_file && (dump_flags & TDF_STATS))
3030 gather_chrec_stats (chrec, &stats);
3035 if (dump_file && (dump_flags & TDF_STATS))
3036 dump_chrecs_stats (dump_file, &stats);
3039 /* Callback for htab_traverse, gathers information on chrecs in the
3040 hashtable. */
3042 static int
3043 gather_stats_on_scev_database_1 (void **slot, void *stats)
3045 struct scev_info_str *entry = (struct scev_info_str *) *slot;
3047 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
3049 return 1;
3052 /* Classify the chrecs of the whole database. */
3054 void
3055 gather_stats_on_scev_database (void)
3057 struct chrec_stats stats;
3059 if (!dump_file)
3060 return;
3062 reset_chrecs_counters (&stats);
3064 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
3065 &stats);
3067 dump_chrecs_stats (dump_file, &stats);
3072 /* Initializer. */
3074 static void
3075 initialize_scalar_evolutions_analyzer (void)
3077 /* The elements below are unique. */
3078 if (chrec_dont_know == NULL_TREE)
3080 chrec_not_analyzed_yet = NULL_TREE;
3081 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3082 chrec_known = make_node (SCEV_KNOWN);
3083 TREE_TYPE (chrec_dont_know) = void_type_node;
3084 TREE_TYPE (chrec_known) = void_type_node;
3088 /* Initialize the analysis of scalar evolutions for LOOPS. */
3090 void
3091 scev_initialize (void)
3093 loop_iterator li;
3094 struct loop *loop;
3097 scalar_evolution_info = htab_create_ggc (100, hash_scev_info, eq_scev_info,
3098 del_scev_info);
3100 initialize_scalar_evolutions_analyzer ();
3102 FOR_EACH_LOOP (li, loop, 0)
3104 loop->nb_iterations = NULL_TREE;
3108 /* Cleans up the information cached by the scalar evolutions analysis
3109 in the hash table. */
3111 void
3112 scev_reset_htab (void)
3114 if (!scalar_evolution_info)
3115 return;
3117 htab_empty (scalar_evolution_info);
3120 /* Cleans up the information cached by the scalar evolutions analysis
3121 in the hash table and in the loop->nb_iterations. */
3123 void
3124 scev_reset (void)
3126 loop_iterator li;
3127 struct loop *loop;
3129 scev_reset_htab ();
3131 if (!current_loops)
3132 return;
3134 FOR_EACH_LOOP (li, loop, 0)
3136 loop->nb_iterations = NULL_TREE;
3140 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3141 respect to WRTO_LOOP and returns its base and step in IV if possible
3142 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3143 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3144 invariant in LOOP. Otherwise we require it to be an integer constant.
3146 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3147 because it is computed in signed arithmetics). Consequently, adding an
3148 induction variable
3150 for (i = IV->base; ; i += IV->step)
3152 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3153 false for the type of the induction variable, or you can prove that i does
3154 not wrap by some other argument. Otherwise, this might introduce undefined
3155 behavior, and
3157 for (i = iv->base; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3159 must be used instead. */
3161 bool
3162 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3163 affine_iv *iv, bool allow_nonconstant_step)
3165 tree type, ev;
3166 bool folded_casts;
3168 iv->base = NULL_TREE;
3169 iv->step = NULL_TREE;
3170 iv->no_overflow = false;
3172 type = TREE_TYPE (op);
3173 if (TREE_CODE (type) != INTEGER_TYPE
3174 && TREE_CODE (type) != POINTER_TYPE)
3175 return false;
3177 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3178 &folded_casts);
3179 if (chrec_contains_undetermined (ev)
3180 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3181 return false;
3183 if (tree_does_not_contain_chrecs (ev))
3185 iv->base = ev;
3186 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3187 iv->no_overflow = true;
3188 return true;
3191 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
3192 || CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3193 return false;
3195 iv->step = CHREC_RIGHT (ev);
3196 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3197 || tree_contains_chrecs (iv->step, NULL))
3198 return false;
3200 iv->base = CHREC_LEFT (ev);
3201 if (tree_contains_chrecs (iv->base, NULL))
3202 return false;
3204 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
3206 return true;
3209 /* Runs the analysis of scalar evolutions. */
3211 void
3212 scev_analysis (void)
3214 VEC(gimple,heap) *exit_conditions;
3216 exit_conditions = VEC_alloc (gimple, heap, 37);
3217 select_loops_exit_conditions (&exit_conditions);
3219 if (dump_file && (dump_flags & TDF_STATS))
3220 analyze_scalar_evolution_for_all_loop_phi_nodes (&exit_conditions);
3222 number_of_iterations_for_all_loops (&exit_conditions);
3223 VEC_free (gimple, heap, exit_conditions);
3226 /* Finalize the scalar evolution analysis. */
3228 void
3229 scev_finalize (void)
3231 if (!scalar_evolution_info)
3232 return;
3233 htab_delete (scalar_evolution_info);
3234 scalar_evolution_info = NULL;
3237 /* Returns true if the expression EXPR is considered to be too expensive
3238 for scev_const_prop. */
3240 bool
3241 expression_expensive_p (tree expr)
3243 enum tree_code code;
3245 if (is_gimple_val (expr))
3246 return false;
3248 code = TREE_CODE (expr);
3249 if (code == TRUNC_DIV_EXPR
3250 || code == CEIL_DIV_EXPR
3251 || code == FLOOR_DIV_EXPR
3252 || code == ROUND_DIV_EXPR
3253 || code == TRUNC_MOD_EXPR
3254 || code == CEIL_MOD_EXPR
3255 || code == FLOOR_MOD_EXPR
3256 || code == ROUND_MOD_EXPR
3257 || code == EXACT_DIV_EXPR)
3259 /* Division by power of two is usually cheap, so we allow it.
3260 Forbid anything else. */
3261 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3262 return true;
3265 switch (TREE_CODE_CLASS (code))
3267 case tcc_binary:
3268 case tcc_comparison:
3269 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3270 return true;
3272 /* Fallthru. */
3273 case tcc_unary:
3274 return expression_expensive_p (TREE_OPERAND (expr, 0));
3276 default:
3277 return true;
3281 /* Replace ssa names for that scev can prove they are constant by the
3282 appropriate constants. Also perform final value replacement in loops,
3283 in case the replacement expressions are cheap.
3285 We only consider SSA names defined by phi nodes; rest is left to the
3286 ordinary constant propagation pass. */
3288 unsigned int
3289 scev_const_prop (void)
3291 basic_block bb;
3292 tree name, type, ev;
3293 gimple phi, ass;
3294 struct loop *loop, *ex_loop;
3295 bitmap ssa_names_to_remove = NULL;
3296 unsigned i;
3297 loop_iterator li;
3298 gimple_stmt_iterator psi;
3300 if (number_of_loops () <= 1)
3301 return 0;
3303 FOR_EACH_BB (bb)
3305 loop = bb->loop_father;
3307 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3309 phi = gsi_stmt (psi);
3310 name = PHI_RESULT (phi);
3312 if (!is_gimple_reg (name))
3313 continue;
3315 type = TREE_TYPE (name);
3317 if (!POINTER_TYPE_P (type)
3318 && !INTEGRAL_TYPE_P (type))
3319 continue;
3321 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
3322 if (!is_gimple_min_invariant (ev)
3323 || !may_propagate_copy (name, ev))
3324 continue;
3326 /* Replace the uses of the name. */
3327 if (name != ev)
3328 replace_uses_by (name, ev);
3330 if (!ssa_names_to_remove)
3331 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3332 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3336 /* Remove the ssa names that were replaced by constants. We do not
3337 remove them directly in the previous cycle, since this
3338 invalidates scev cache. */
3339 if (ssa_names_to_remove)
3341 bitmap_iterator bi;
3343 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3345 gimple_stmt_iterator psi;
3346 name = ssa_name (i);
3347 phi = SSA_NAME_DEF_STMT (name);
3349 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3350 psi = gsi_for_stmt (phi);
3351 remove_phi_node (&psi, true);
3354 BITMAP_FREE (ssa_names_to_remove);
3355 scev_reset ();
3358 /* Now the regular final value replacement. */
3359 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
3361 edge exit;
3362 tree def, rslt, niter;
3363 gimple_stmt_iterator bsi;
3365 /* If we do not know exact number of iterations of the loop, we cannot
3366 replace the final value. */
3367 exit = single_exit (loop);
3368 if (!exit)
3369 continue;
3371 niter = number_of_latch_executions (loop);
3372 if (niter == chrec_dont_know)
3373 continue;
3375 /* Ensure that it is possible to insert new statements somewhere. */
3376 if (!single_pred_p (exit->dest))
3377 split_loop_exit_edge (exit);
3378 bsi = gsi_after_labels (exit->dest);
3380 ex_loop = superloop_at_depth (loop,
3381 loop_depth (exit->dest->loop_father) + 1);
3383 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3385 phi = gsi_stmt (psi);
3386 rslt = PHI_RESULT (phi);
3387 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3388 if (!is_gimple_reg (def))
3390 gsi_next (&psi);
3391 continue;
3394 if (!POINTER_TYPE_P (TREE_TYPE (def))
3395 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3397 gsi_next (&psi);
3398 continue;
3401 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def, NULL);
3402 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3403 if (!tree_does_not_contain_chrecs (def)
3404 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3405 /* Moving the computation from the loop may prolong life range
3406 of some ssa names, which may cause problems if they appear
3407 on abnormal edges. */
3408 || contains_abnormal_ssa_name_p (def)
3409 /* Do not emit expensive expressions. The rationale is that
3410 when someone writes a code like
3412 while (n > 45) n -= 45;
3414 he probably knows that n is not large, and does not want it
3415 to be turned into n %= 45. */
3416 || expression_expensive_p (def))
3418 gsi_next (&psi);
3419 continue;
3422 /* Eliminate the PHI node and replace it by a computation outside
3423 the loop. */
3424 def = unshare_expr (def);
3425 remove_phi_node (&psi, false);
3427 def = force_gimple_operand_gsi (&bsi, def, false, NULL_TREE,
3428 true, GSI_SAME_STMT);
3429 ass = gimple_build_assign (rslt, def);
3430 gsi_insert_before (&bsi, ass, GSI_SAME_STMT);
3433 return 0;
3436 #include "gt-tree-scalar-evolution.h"