2013-09-20 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / tree-scalar-evolution.c
blobbda45a6f63bbcbc70ce9240a3067df02a071f465
1 /* Scalar evolution detector.
2 Copyright (C) 2003-2013 Free Software Foundation, Inc.
3 Contributed by Sebastian Pop <s.pop@laposte.net>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
22 Description:
24 This pass analyzes the evolution of scalar variables in loop
25 structures. The algorithm is based on the SSA representation,
26 and on the loop hierarchy tree. This algorithm is not based on
27 the notion of versions of a variable, as it was the case for the
28 previous implementations of the scalar evolution algorithm, but
29 it assumes that each defined name is unique.
31 The notation used in this file is called "chains of recurrences",
32 and has been proposed by Eugene Zima, Robert Van Engelen, and
33 others for describing induction variables in programs. For example
34 "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
35 when entering in the loop_1 and has a step 2 in this loop, in other
36 words "for (b = 0; b < N; b+=2);". Note that the coefficients of
37 this chain of recurrence (or chrec [shrek]) can contain the name of
38 other variables, in which case they are called parametric chrecs.
39 For example, "b -> {a, +, 2}_1" means that the initial value of "b"
40 is the value of "a". In most of the cases these parametric chrecs
41 are fully instantiated before their use because symbolic names can
42 hide some difficult cases such as self-references described later
43 (see the Fibonacci example).
45 A short sketch of the algorithm is:
47 Given a scalar variable to be analyzed, follow the SSA edge to
48 its definition:
50 - When the definition is a GIMPLE_ASSIGN: if the right hand side
51 (RHS) of the definition cannot be statically analyzed, the answer
52 of the analyzer is: "don't know".
53 Otherwise, for all the variables that are not yet analyzed in the
54 RHS, try to determine their evolution, and finally try to
55 evaluate the operation of the RHS that gives the evolution
56 function of the analyzed variable.
58 - When the definition is a condition-phi-node: determine the
59 evolution function for all the branches of the phi node, and
60 finally merge these evolutions (see chrec_merge).
62 - When the definition is a loop-phi-node: determine its initial
63 condition, that is the SSA edge defined in an outer loop, and
64 keep it symbolic. Then determine the SSA edges that are defined
65 in the body of the loop. Follow the inner edges until ending on
66 another loop-phi-node of the same analyzed loop. If the reached
67 loop-phi-node is not the starting loop-phi-node, then we keep
68 this definition under a symbolic form. If the reached
69 loop-phi-node is the same as the starting one, then we compute a
70 symbolic stride on the return path. The result is then the
71 symbolic chrec {initial_condition, +, symbolic_stride}_loop.
73 Examples:
75 Example 1: Illustration of the basic algorithm.
77 | a = 3
78 | loop_1
79 | b = phi (a, c)
80 | c = b + 1
81 | if (c > 10) exit_loop
82 | endloop
84 Suppose that we want to know the number of iterations of the
85 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
86 ask the scalar evolution analyzer two questions: what's the
87 scalar evolution (scev) of "c", and what's the scev of "10". For
88 "10" the answer is "10" since it is a scalar constant. For the
89 scalar variable "c", it follows the SSA edge to its definition,
90 "c = b + 1", and then asks again what's the scev of "b".
91 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
92 c)", where the initial condition is "a", and the inner loop edge
93 is "c". The initial condition is kept under a symbolic form (it
94 may be the case that the copy constant propagation has done its
95 work and we end with the constant "3" as one of the edges of the
96 loop-phi-node). The update edge is followed to the end of the
97 loop, and until reaching again the starting loop-phi-node: b -> c
98 -> b. At this point we have drawn a path from "b" to "b" from
99 which we compute the stride in the loop: in this example it is
100 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
101 that the scev for "b" is known, it is possible to compute the
102 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
103 determine the number of iterations in the loop_1, we have to
104 instantiate_parameters (loop_1, {a + 1, +, 1}_1), that gives after some
105 more analysis the scev {4, +, 1}_1, or in other words, this is
106 the function "f (x) = x + 4", where x is the iteration count of
107 the loop_1. Now we have to solve the inequality "x + 4 > 10",
108 and take the smallest iteration number for which the loop is
109 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
110 there are 8 iterations. In terms of loop normalization, we have
111 created a variable that is implicitly defined, "x" or just "_1",
112 and all the other analyzed scalars of the loop are defined in
113 function of this variable:
115 a -> 3
116 b -> {3, +, 1}_1
117 c -> {4, +, 1}_1
119 or in terms of a C program:
121 | a = 3
122 | for (x = 0; x <= 7; x++)
124 | b = x + 3
125 | c = x + 4
128 Example 2a: Illustration of the algorithm on nested loops.
130 | loop_1
131 | a = phi (1, b)
132 | c = a + 2
133 | loop_2 10 times
134 | b = phi (c, d)
135 | d = b + 3
136 | endloop
137 | endloop
139 For analyzing the scalar evolution of "a", the algorithm follows
140 the SSA edge into the loop's body: "a -> b". "b" is an inner
141 loop-phi-node, and its analysis as in Example 1, gives:
143 b -> {c, +, 3}_2
144 d -> {c + 3, +, 3}_2
146 Following the SSA edge for the initial condition, we end on "c = a
147 + 2", and then on the starting loop-phi-node "a". From this point,
148 the loop stride is computed: back on "c = a + 2" we get a "+2" in
149 the loop_1, then on the loop-phi-node "b" we compute the overall
150 effect of the inner loop that is "b = c + 30", and we get a "+30"
151 in the loop_1. That means that the overall stride in loop_1 is
152 equal to "+32", and the result is:
154 a -> {1, +, 32}_1
155 c -> {3, +, 32}_1
157 Example 2b: Multivariate chains of recurrences.
159 | loop_1
160 | k = phi (0, k + 1)
161 | loop_2 4 times
162 | j = phi (0, j + 1)
163 | loop_3 4 times
164 | i = phi (0, i + 1)
165 | A[j + k] = ...
166 | endloop
167 | endloop
168 | endloop
170 Analyzing the access function of array A with
171 instantiate_parameters (loop_1, "j + k"), we obtain the
172 instantiation and the analysis of the scalar variables "j" and "k"
173 in loop_1. This leads to the scalar evolution {4, +, 1}_1: the end
174 value of loop_2 for "j" is 4, and the evolution of "k" in loop_1 is
175 {0, +, 1}_1. To obtain the evolution function in loop_3 and
176 instantiate the scalar variables up to loop_1, one has to use:
177 instantiate_scev (block_before_loop (loop_1), loop_3, "j + k").
178 The result of this call is {{0, +, 1}_1, +, 1}_2.
180 Example 3: Higher degree polynomials.
182 | loop_1
183 | a = phi (2, b)
184 | c = phi (5, d)
185 | b = a + 1
186 | d = c + a
187 | endloop
189 a -> {2, +, 1}_1
190 b -> {3, +, 1}_1
191 c -> {5, +, a}_1
192 d -> {5 + a, +, a}_1
194 instantiate_parameters (loop_1, {5, +, a}_1) -> {5, +, 2, +, 1}_1
195 instantiate_parameters (loop_1, {5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
197 Example 4: Lucas, Fibonacci, or mixers in general.
199 | loop_1
200 | a = phi (1, b)
201 | c = phi (3, d)
202 | b = c
203 | d = c + a
204 | endloop
206 a -> (1, c)_1
207 c -> {3, +, a}_1
209 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
210 following semantics: during the first iteration of the loop_1, the
211 variable contains the value 1, and then it contains the value "c".
212 Note that this syntax is close to the syntax of the loop-phi-node:
213 "a -> (1, c)_1" vs. "a = phi (1, c)".
215 The symbolic chrec representation contains all the semantics of the
216 original code. What is more difficult is to use this information.
218 Example 5: Flip-flops, or exchangers.
220 | loop_1
221 | a = phi (1, b)
222 | c = phi (3, d)
223 | b = c
224 | d = a
225 | endloop
227 a -> (1, c)_1
228 c -> (3, a)_1
230 Based on these symbolic chrecs, it is possible to refine this
231 information into the more precise PERIODIC_CHRECs:
233 a -> |1, 3|_1
234 c -> |3, 1|_1
236 This transformation is not yet implemented.
238 Further readings:
240 You can find a more detailed description of the algorithm in:
241 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
242 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
243 this is a preliminary report and some of the details of the
244 algorithm have changed. I'm working on a research report that
245 updates the description of the algorithms to reflect the design
246 choices used in this implementation.
248 A set of slides show a high level overview of the algorithm and run
249 an example through the scalar evolution analyzer:
250 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
252 The slides that I have presented at the GCC Summit'04 are available
253 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
256 #include "config.h"
257 #include "system.h"
258 #include "coretypes.h"
259 #include "hash-table.h"
260 #include "gimple-pretty-print.h"
261 #include "tree-ssa.h"
262 #include "cfgloop.h"
263 #include "tree-chrec.h"
264 #include "tree-scalar-evolution.h"
265 #include "dumpfile.h"
266 #include "params.h"
268 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
269 static tree analyze_scalar_evolution_for_address_of (struct loop *loop,
270 tree var);
272 /* The cached information about an SSA name with version NAME_VERSION,
273 claiming that below basic block with index INSTANTIATED_BELOW, the
274 value of the SSA name can be expressed as CHREC. */
276 struct GTY(()) scev_info_str {
277 unsigned int name_version;
278 int instantiated_below;
279 tree chrec;
282 /* Counters for the scev database. */
283 static unsigned nb_set_scev = 0;
284 static unsigned nb_get_scev = 0;
286 /* The following trees are unique elements. Thus the comparison of
287 another element to these elements should be done on the pointer to
288 these trees, and not on their value. */
290 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
291 tree chrec_not_analyzed_yet;
293 /* Reserved to the cases where the analyzer has detected an
294 undecidable property at compile time. */
295 tree chrec_dont_know;
297 /* When the analyzer has detected that a property will never
298 happen, then it qualifies it with chrec_known. */
299 tree chrec_known;
301 static GTY ((param_is (struct scev_info_str))) htab_t scalar_evolution_info;
304 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
306 static inline struct scev_info_str *
307 new_scev_info_str (basic_block instantiated_below, tree var)
309 struct scev_info_str *res;
311 res = ggc_alloc_scev_info_str ();
312 res->name_version = SSA_NAME_VERSION (var);
313 res->chrec = chrec_not_analyzed_yet;
314 res->instantiated_below = instantiated_below->index;
316 return res;
319 /* Computes a hash function for database element ELT. */
321 static inline hashval_t
322 hash_scev_info (const void *elt_)
324 const struct scev_info_str *elt = (const struct scev_info_str *) elt_;
325 return elt->name_version ^ elt->instantiated_below;
328 /* Compares database elements E1 and E2. */
330 static inline int
331 eq_scev_info (const void *e1, const void *e2)
333 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
334 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
336 return (elt1->name_version == elt2->name_version
337 && elt1->instantiated_below == elt2->instantiated_below);
340 /* Deletes database element E. */
342 static void
343 del_scev_info (void *e)
345 ggc_free (e);
349 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
350 A first query on VAR returns chrec_not_analyzed_yet. */
352 static tree *
353 find_var_scev_info (basic_block instantiated_below, tree var)
355 struct scev_info_str *res;
356 struct scev_info_str tmp;
357 PTR *slot;
359 tmp.name_version = SSA_NAME_VERSION (var);
360 tmp.instantiated_below = instantiated_below->index;
361 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
363 if (!*slot)
364 *slot = new_scev_info_str (instantiated_below, var);
365 res = (struct scev_info_str *) *slot;
367 return &res->chrec;
370 /* Return true when CHREC contains symbolic names defined in
371 LOOP_NB. */
373 bool
374 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
376 int i, n;
378 if (chrec == NULL_TREE)
379 return false;
381 if (is_gimple_min_invariant (chrec))
382 return false;
384 if (TREE_CODE (chrec) == SSA_NAME)
386 gimple def;
387 loop_p def_loop, loop;
389 if (SSA_NAME_IS_DEFAULT_DEF (chrec))
390 return false;
392 def = SSA_NAME_DEF_STMT (chrec);
393 def_loop = loop_containing_stmt (def);
394 loop = get_loop (cfun, loop_nb);
396 if (def_loop == NULL)
397 return false;
399 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
400 return true;
402 return false;
405 n = TREE_OPERAND_LENGTH (chrec);
406 for (i = 0; i < n; i++)
407 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
408 loop_nb))
409 return true;
410 return false;
413 /* Return true when PHI is a loop-phi-node. */
415 static bool
416 loop_phi_node_p (gimple phi)
418 /* The implementation of this function is based on the following
419 property: "all the loop-phi-nodes of a loop are contained in the
420 loop's header basic block". */
422 return loop_containing_stmt (phi)->header == gimple_bb (phi);
425 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
426 In general, in the case of multivariate evolutions we want to get
427 the evolution in different loops. LOOP specifies the level for
428 which to get the evolution.
430 Example:
432 | for (j = 0; j < 100; j++)
434 | for (k = 0; k < 100; k++)
436 | i = k + j; - Here the value of i is a function of j, k.
438 | ... = i - Here the value of i is a function of j.
440 | ... = i - Here the value of i is a scalar.
442 Example:
444 | i_0 = ...
445 | loop_1 10 times
446 | i_1 = phi (i_0, i_2)
447 | i_2 = i_1 + 2
448 | endloop
450 This loop has the same effect as:
451 LOOP_1 has the same effect as:
453 | i_1 = i_0 + 20
455 The overall effect of the loop, "i_0 + 20" in the previous example,
456 is obtained by passing in the parameters: LOOP = 1,
457 EVOLUTION_FN = {i_0, +, 2}_1.
460 tree
461 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
463 bool val = false;
465 if (evolution_fn == chrec_dont_know)
466 return chrec_dont_know;
468 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
470 struct loop *inner_loop = get_chrec_loop (evolution_fn);
472 if (inner_loop == loop
473 || flow_loop_nested_p (loop, inner_loop))
475 tree nb_iter = number_of_latch_executions (inner_loop);
477 if (nb_iter == chrec_dont_know)
478 return chrec_dont_know;
479 else
481 tree res;
483 /* evolution_fn is the evolution function in LOOP. Get
484 its value in the nb_iter-th iteration. */
485 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
487 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
488 res = instantiate_parameters (loop, res);
490 /* Continue the computation until ending on a parent of LOOP. */
491 return compute_overall_effect_of_inner_loop (loop, res);
494 else
495 return evolution_fn;
498 /* If the evolution function is an invariant, there is nothing to do. */
499 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
500 return evolution_fn;
502 else
503 return chrec_dont_know;
506 /* Associate CHREC to SCALAR. */
508 static void
509 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
511 tree *scalar_info;
513 if (TREE_CODE (scalar) != SSA_NAME)
514 return;
516 scalar_info = find_var_scev_info (instantiated_below, scalar);
518 if (dump_file)
520 if (dump_flags & TDF_SCEV)
522 fprintf (dump_file, "(set_scalar_evolution \n");
523 fprintf (dump_file, " instantiated_below = %d \n",
524 instantiated_below->index);
525 fprintf (dump_file, " (scalar = ");
526 print_generic_expr (dump_file, scalar, 0);
527 fprintf (dump_file, ")\n (scalar_evolution = ");
528 print_generic_expr (dump_file, chrec, 0);
529 fprintf (dump_file, "))\n");
531 if (dump_flags & TDF_STATS)
532 nb_set_scev++;
535 *scalar_info = chrec;
538 /* Retrieve the chrec associated to SCALAR instantiated below
539 INSTANTIATED_BELOW block. */
541 static tree
542 get_scalar_evolution (basic_block instantiated_below, tree scalar)
544 tree res;
546 if (dump_file)
548 if (dump_flags & TDF_SCEV)
550 fprintf (dump_file, "(get_scalar_evolution \n");
551 fprintf (dump_file, " (scalar = ");
552 print_generic_expr (dump_file, scalar, 0);
553 fprintf (dump_file, ")\n");
555 if (dump_flags & TDF_STATS)
556 nb_get_scev++;
559 switch (TREE_CODE (scalar))
561 case SSA_NAME:
562 res = *find_var_scev_info (instantiated_below, scalar);
563 break;
565 case REAL_CST:
566 case FIXED_CST:
567 case INTEGER_CST:
568 res = scalar;
569 break;
571 default:
572 res = chrec_not_analyzed_yet;
573 break;
576 if (dump_file && (dump_flags & TDF_SCEV))
578 fprintf (dump_file, " (scalar_evolution = ");
579 print_generic_expr (dump_file, res, 0);
580 fprintf (dump_file, "))\n");
583 return res;
586 /* Helper function for add_to_evolution. Returns the evolution
587 function for an assignment of the form "a = b + c", where "a" and
588 "b" are on the strongly connected component. CHREC_BEFORE is the
589 information that we already have collected up to this point.
590 TO_ADD is the evolution of "c".
592 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
593 evolution the expression TO_ADD, otherwise construct an evolution
594 part for this loop. */
596 static tree
597 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
598 gimple at_stmt)
600 tree type, left, right;
601 struct loop *loop = get_loop (cfun, loop_nb), *chloop;
603 switch (TREE_CODE (chrec_before))
605 case POLYNOMIAL_CHREC:
606 chloop = get_chrec_loop (chrec_before);
607 if (chloop == loop
608 || flow_loop_nested_p (chloop, loop))
610 unsigned var;
612 type = chrec_type (chrec_before);
614 /* When there is no evolution part in this loop, build it. */
615 if (chloop != loop)
617 var = loop_nb;
618 left = chrec_before;
619 right = SCALAR_FLOAT_TYPE_P (type)
620 ? build_real (type, dconst0)
621 : build_int_cst (type, 0);
623 else
625 var = CHREC_VARIABLE (chrec_before);
626 left = CHREC_LEFT (chrec_before);
627 right = CHREC_RIGHT (chrec_before);
630 to_add = chrec_convert (type, to_add, at_stmt);
631 right = chrec_convert_rhs (type, right, at_stmt);
632 right = chrec_fold_plus (chrec_type (right), right, to_add);
633 return build_polynomial_chrec (var, left, right);
635 else
637 gcc_assert (flow_loop_nested_p (loop, chloop));
639 /* Search the evolution in LOOP_NB. */
640 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
641 to_add, at_stmt);
642 right = CHREC_RIGHT (chrec_before);
643 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
644 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
645 left, right);
648 default:
649 /* These nodes do not depend on a loop. */
650 if (chrec_before == chrec_dont_know)
651 return chrec_dont_know;
653 left = chrec_before;
654 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
655 return build_polynomial_chrec (loop_nb, left, right);
659 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
660 of LOOP_NB.
662 Description (provided for completeness, for those who read code in
663 a plane, and for my poor 62 bytes brain that would have forgotten
664 all this in the next two or three months):
666 The algorithm of translation of programs from the SSA representation
667 into the chrecs syntax is based on a pattern matching. After having
668 reconstructed the overall tree expression for a loop, there are only
669 two cases that can arise:
671 1. a = loop-phi (init, a + expr)
672 2. a = loop-phi (init, expr)
674 where EXPR is either a scalar constant with respect to the analyzed
675 loop (this is a degree 0 polynomial), or an expression containing
676 other loop-phi definitions (these are higher degree polynomials).
678 Examples:
681 | init = ...
682 | loop_1
683 | a = phi (init, a + 5)
684 | endloop
687 | inita = ...
688 | initb = ...
689 | loop_1
690 | a = phi (inita, 2 * b + 3)
691 | b = phi (initb, b + 1)
692 | endloop
694 For the first case, the semantics of the SSA representation is:
696 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
698 that is, there is a loop index "x" that determines the scalar value
699 of the variable during the loop execution. During the first
700 iteration, the value is that of the initial condition INIT, while
701 during the subsequent iterations, it is the sum of the initial
702 condition with the sum of all the values of EXPR from the initial
703 iteration to the before last considered iteration.
705 For the second case, the semantics of the SSA program is:
707 | a (x) = init, if x = 0;
708 | expr (x - 1), otherwise.
710 The second case corresponds to the PEELED_CHREC, whose syntax is
711 close to the syntax of a loop-phi-node:
713 | phi (init, expr) vs. (init, expr)_x
715 The proof of the translation algorithm for the first case is a
716 proof by structural induction based on the degree of EXPR.
718 Degree 0:
719 When EXPR is a constant with respect to the analyzed loop, or in
720 other words when EXPR is a polynomial of degree 0, the evolution of
721 the variable A in the loop is an affine function with an initial
722 condition INIT, and a step EXPR. In order to show this, we start
723 from the semantics of the SSA representation:
725 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
727 and since "expr (j)" is a constant with respect to "j",
729 f (x) = init + x * expr
731 Finally, based on the semantics of the pure sum chrecs, by
732 identification we get the corresponding chrecs syntax:
734 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
735 f (x) -> {init, +, expr}_x
737 Higher degree:
738 Suppose that EXPR is a polynomial of degree N with respect to the
739 analyzed loop_x for which we have already determined that it is
740 written under the chrecs syntax:
742 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
744 We start from the semantics of the SSA program:
746 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
748 | f (x) = init + \sum_{j = 0}^{x - 1}
749 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
751 | f (x) = init + \sum_{j = 0}^{x - 1}
752 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
754 | f (x) = init + \sum_{k = 0}^{n - 1}
755 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
757 | f (x) = init + \sum_{k = 0}^{n - 1}
758 | (b_k * \binom{x}{k + 1})
760 | f (x) = init + b_0 * \binom{x}{1} + ...
761 | + b_{n-1} * \binom{x}{n}
763 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
764 | + b_{n-1} * \binom{x}{n}
767 And finally from the definition of the chrecs syntax, we identify:
768 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
770 This shows the mechanism that stands behind the add_to_evolution
771 function. An important point is that the use of symbolic
772 parameters avoids the need of an analysis schedule.
774 Example:
776 | inita = ...
777 | initb = ...
778 | loop_1
779 | a = phi (inita, a + 2 + b)
780 | b = phi (initb, b + 1)
781 | endloop
783 When analyzing "a", the algorithm keeps "b" symbolically:
785 | a -> {inita, +, 2 + b}_1
787 Then, after instantiation, the analyzer ends on the evolution:
789 | a -> {inita, +, 2 + initb, +, 1}_1
793 static tree
794 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
795 tree to_add, gimple at_stmt)
797 tree type = chrec_type (to_add);
798 tree res = NULL_TREE;
800 if (to_add == NULL_TREE)
801 return chrec_before;
803 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
804 instantiated at this point. */
805 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
806 /* This should not happen. */
807 return chrec_dont_know;
809 if (dump_file && (dump_flags & TDF_SCEV))
811 fprintf (dump_file, "(add_to_evolution \n");
812 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
813 fprintf (dump_file, " (chrec_before = ");
814 print_generic_expr (dump_file, chrec_before, 0);
815 fprintf (dump_file, ")\n (to_add = ");
816 print_generic_expr (dump_file, to_add, 0);
817 fprintf (dump_file, ")\n");
820 if (code == MINUS_EXPR)
821 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
822 ? build_real (type, dconstm1)
823 : build_int_cst_type (type, -1));
825 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
827 if (dump_file && (dump_flags & TDF_SCEV))
829 fprintf (dump_file, " (res = ");
830 print_generic_expr (dump_file, res, 0);
831 fprintf (dump_file, "))\n");
834 return res;
839 /* This section selects the loops that will be good candidates for the
840 scalar evolution analysis. For the moment, greedily select all the
841 loop nests we could analyze. */
843 /* For a loop with a single exit edge, return the COND_EXPR that
844 guards the exit edge. If the expression is too difficult to
845 analyze, then give up. */
847 gimple
848 get_loop_exit_condition (const struct loop *loop)
850 gimple res = NULL;
851 edge exit_edge = single_exit (loop);
853 if (dump_file && (dump_flags & TDF_SCEV))
854 fprintf (dump_file, "(get_loop_exit_condition \n ");
856 if (exit_edge)
858 gimple stmt;
860 stmt = last_stmt (exit_edge->src);
861 if (gimple_code (stmt) == GIMPLE_COND)
862 res = stmt;
865 if (dump_file && (dump_flags & TDF_SCEV))
867 print_gimple_stmt (dump_file, res, 0, 0);
868 fprintf (dump_file, ")\n");
871 return res;
875 /* Depth first search algorithm. */
877 typedef enum t_bool {
878 t_false,
879 t_true,
880 t_dont_know
881 } t_bool;
884 static t_bool follow_ssa_edge (struct loop *loop, gimple, gimple, tree *, int);
886 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
887 Return true if the strongly connected component has been found. */
889 static t_bool
890 follow_ssa_edge_binary (struct loop *loop, gimple at_stmt,
891 tree type, tree rhs0, enum tree_code code, tree rhs1,
892 gimple halting_phi, tree *evolution_of_loop, int limit)
894 t_bool res = t_false;
895 tree evol;
897 switch (code)
899 case POINTER_PLUS_EXPR:
900 case PLUS_EXPR:
901 if (TREE_CODE (rhs0) == SSA_NAME)
903 if (TREE_CODE (rhs1) == SSA_NAME)
905 /* Match an assignment under the form:
906 "a = b + c". */
908 /* We want only assignments of form "name + name" contribute to
909 LIMIT, as the other cases do not necessarily contribute to
910 the complexity of the expression. */
911 limit++;
913 evol = *evolution_of_loop;
914 res = follow_ssa_edge
915 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
917 if (res == t_true)
918 *evolution_of_loop = add_to_evolution
919 (loop->num,
920 chrec_convert (type, evol, at_stmt),
921 code, rhs1, at_stmt);
923 else if (res == t_false)
925 res = follow_ssa_edge
926 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
927 evolution_of_loop, limit);
929 if (res == t_true)
930 *evolution_of_loop = add_to_evolution
931 (loop->num,
932 chrec_convert (type, *evolution_of_loop, at_stmt),
933 code, rhs0, at_stmt);
935 else if (res == t_dont_know)
936 *evolution_of_loop = chrec_dont_know;
939 else if (res == t_dont_know)
940 *evolution_of_loop = chrec_dont_know;
943 else
945 /* Match an assignment under the form:
946 "a = b + ...". */
947 res = follow_ssa_edge
948 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
949 evolution_of_loop, limit);
950 if (res == t_true)
951 *evolution_of_loop = add_to_evolution
952 (loop->num, chrec_convert (type, *evolution_of_loop,
953 at_stmt),
954 code, rhs1, at_stmt);
956 else if (res == t_dont_know)
957 *evolution_of_loop = chrec_dont_know;
961 else if (TREE_CODE (rhs1) == SSA_NAME)
963 /* Match an assignment under the form:
964 "a = ... + c". */
965 res = follow_ssa_edge
966 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
967 evolution_of_loop, limit);
968 if (res == t_true)
969 *evolution_of_loop = add_to_evolution
970 (loop->num, chrec_convert (type, *evolution_of_loop,
971 at_stmt),
972 code, rhs0, at_stmt);
974 else if (res == t_dont_know)
975 *evolution_of_loop = chrec_dont_know;
978 else
979 /* Otherwise, match an assignment under the form:
980 "a = ... + ...". */
981 /* And there is nothing to do. */
982 res = t_false;
983 break;
985 case MINUS_EXPR:
986 /* This case is under the form "opnd0 = rhs0 - rhs1". */
987 if (TREE_CODE (rhs0) == SSA_NAME)
989 /* Match an assignment under the form:
990 "a = b - ...". */
992 /* We want only assignments of form "name - name" contribute to
993 LIMIT, as the other cases do not necessarily contribute to
994 the complexity of the expression. */
995 if (TREE_CODE (rhs1) == SSA_NAME)
996 limit++;
998 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
999 evolution_of_loop, limit);
1000 if (res == t_true)
1001 *evolution_of_loop = add_to_evolution
1002 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1003 MINUS_EXPR, rhs1, at_stmt);
1005 else if (res == t_dont_know)
1006 *evolution_of_loop = chrec_dont_know;
1008 else
1009 /* Otherwise, match an assignment under the form:
1010 "a = ... - ...". */
1011 /* And there is nothing to do. */
1012 res = t_false;
1013 break;
1015 default:
1016 res = t_false;
1019 return res;
1022 /* Follow the ssa edge into the expression EXPR.
1023 Return true if the strongly connected component has been found. */
1025 static t_bool
1026 follow_ssa_edge_expr (struct loop *loop, gimple at_stmt, tree expr,
1027 gimple halting_phi, tree *evolution_of_loop, int limit)
1029 enum tree_code code = TREE_CODE (expr);
1030 tree type = TREE_TYPE (expr), rhs0, rhs1;
1031 t_bool res;
1033 /* The EXPR is one of the following cases:
1034 - an SSA_NAME,
1035 - an INTEGER_CST,
1036 - a PLUS_EXPR,
1037 - a POINTER_PLUS_EXPR,
1038 - a MINUS_EXPR,
1039 - an ASSERT_EXPR,
1040 - other cases are not yet handled. */
1042 switch (code)
1044 CASE_CONVERT:
1045 /* This assignment is under the form "a_1 = (cast) rhs. */
1046 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1047 halting_phi, evolution_of_loop, limit);
1048 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1049 break;
1051 case INTEGER_CST:
1052 /* This assignment is under the form "a_1 = 7". */
1053 res = t_false;
1054 break;
1056 case SSA_NAME:
1057 /* This assignment is under the form: "a_1 = b_2". */
1058 res = follow_ssa_edge
1059 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1060 break;
1062 case POINTER_PLUS_EXPR:
1063 case PLUS_EXPR:
1064 case MINUS_EXPR:
1065 /* This case is under the form "rhs0 +- rhs1". */
1066 rhs0 = TREE_OPERAND (expr, 0);
1067 rhs1 = TREE_OPERAND (expr, 1);
1068 type = TREE_TYPE (rhs0);
1069 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1070 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1071 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1072 halting_phi, evolution_of_loop, limit);
1073 break;
1075 case ADDR_EXPR:
1076 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1077 if (TREE_CODE (TREE_OPERAND (expr, 0)) == MEM_REF)
1079 expr = TREE_OPERAND (expr, 0);
1080 rhs0 = TREE_OPERAND (expr, 0);
1081 rhs1 = TREE_OPERAND (expr, 1);
1082 type = TREE_TYPE (rhs0);
1083 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1084 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1085 res = follow_ssa_edge_binary (loop, at_stmt, type,
1086 rhs0, POINTER_PLUS_EXPR, rhs1,
1087 halting_phi, evolution_of_loop, limit);
1089 else
1090 res = t_false;
1091 break;
1093 case ASSERT_EXPR:
1094 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1095 It must be handled as a copy assignment of the form a_1 = a_2. */
1096 rhs0 = ASSERT_EXPR_VAR (expr);
1097 if (TREE_CODE (rhs0) == SSA_NAME)
1098 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1099 halting_phi, evolution_of_loop, limit);
1100 else
1101 res = t_false;
1102 break;
1104 default:
1105 res = t_false;
1106 break;
1109 return res;
1112 /* Follow the ssa edge into the right hand side of an assignment STMT.
1113 Return true if the strongly connected component has been found. */
1115 static t_bool
1116 follow_ssa_edge_in_rhs (struct loop *loop, gimple stmt,
1117 gimple halting_phi, tree *evolution_of_loop, int limit)
1119 enum tree_code code = gimple_assign_rhs_code (stmt);
1120 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1121 t_bool res;
1123 switch (code)
1125 CASE_CONVERT:
1126 /* This assignment is under the form "a_1 = (cast) rhs. */
1127 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1128 halting_phi, evolution_of_loop, limit);
1129 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1130 break;
1132 case POINTER_PLUS_EXPR:
1133 case PLUS_EXPR:
1134 case MINUS_EXPR:
1135 rhs1 = gimple_assign_rhs1 (stmt);
1136 rhs2 = gimple_assign_rhs2 (stmt);
1137 type = TREE_TYPE (rhs1);
1138 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1139 halting_phi, evolution_of_loop, limit);
1140 break;
1142 default:
1143 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1144 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1145 halting_phi, evolution_of_loop, limit);
1146 else
1147 res = t_false;
1148 break;
1151 return res;
1154 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1156 static bool
1157 backedge_phi_arg_p (gimple phi, int i)
1159 const_edge e = gimple_phi_arg_edge (phi, i);
1161 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1162 about updating it anywhere, and this should work as well most of the
1163 time. */
1164 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1165 return true;
1167 return false;
1170 /* Helper function for one branch of the condition-phi-node. Return
1171 true if the strongly connected component has been found following
1172 this path. */
1174 static inline t_bool
1175 follow_ssa_edge_in_condition_phi_branch (int i,
1176 struct loop *loop,
1177 gimple condition_phi,
1178 gimple halting_phi,
1179 tree *evolution_of_branch,
1180 tree init_cond, int limit)
1182 tree branch = PHI_ARG_DEF (condition_phi, i);
1183 *evolution_of_branch = chrec_dont_know;
1185 /* Do not follow back edges (they must belong to an irreducible loop, which
1186 we really do not want to worry about). */
1187 if (backedge_phi_arg_p (condition_phi, i))
1188 return t_false;
1190 if (TREE_CODE (branch) == SSA_NAME)
1192 *evolution_of_branch = init_cond;
1193 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1194 evolution_of_branch, limit);
1197 /* This case occurs when one of the condition branches sets
1198 the variable to a constant: i.e. a phi-node like
1199 "a_2 = PHI <a_7(5), 2(6)>;".
1201 FIXME: This case have to be refined correctly:
1202 in some cases it is possible to say something better than
1203 chrec_dont_know, for example using a wrap-around notation. */
1204 return t_false;
1207 /* This function merges the branches of a condition-phi-node in a
1208 loop. */
1210 static t_bool
1211 follow_ssa_edge_in_condition_phi (struct loop *loop,
1212 gimple condition_phi,
1213 gimple halting_phi,
1214 tree *evolution_of_loop, int limit)
1216 int i, n;
1217 tree init = *evolution_of_loop;
1218 tree evolution_of_branch;
1219 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1220 halting_phi,
1221 &evolution_of_branch,
1222 init, limit);
1223 if (res == t_false || res == t_dont_know)
1224 return res;
1226 *evolution_of_loop = evolution_of_branch;
1228 n = gimple_phi_num_args (condition_phi);
1229 for (i = 1; i < n; i++)
1231 /* Quickly give up when the evolution of one of the branches is
1232 not known. */
1233 if (*evolution_of_loop == chrec_dont_know)
1234 return t_true;
1236 /* Increase the limit by the PHI argument number to avoid exponential
1237 time and memory complexity. */
1238 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1239 halting_phi,
1240 &evolution_of_branch,
1241 init, limit + i);
1242 if (res == t_false || res == t_dont_know)
1243 return res;
1245 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1246 evolution_of_branch);
1249 return t_true;
1252 /* Follow an SSA edge in an inner loop. It computes the overall
1253 effect of the loop, and following the symbolic initial conditions,
1254 it follows the edges in the parent loop. The inner loop is
1255 considered as a single statement. */
1257 static t_bool
1258 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1259 gimple loop_phi_node,
1260 gimple halting_phi,
1261 tree *evolution_of_loop, int limit)
1263 struct loop *loop = loop_containing_stmt (loop_phi_node);
1264 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1266 /* Sometimes, the inner loop is too difficult to analyze, and the
1267 result of the analysis is a symbolic parameter. */
1268 if (ev == PHI_RESULT (loop_phi_node))
1270 t_bool res = t_false;
1271 int i, n = gimple_phi_num_args (loop_phi_node);
1273 for (i = 0; i < n; i++)
1275 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1276 basic_block bb;
1278 /* Follow the edges that exit the inner loop. */
1279 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1280 if (!flow_bb_inside_loop_p (loop, bb))
1281 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1282 arg, halting_phi,
1283 evolution_of_loop, limit);
1284 if (res == t_true)
1285 break;
1288 /* If the path crosses this loop-phi, give up. */
1289 if (res == t_true)
1290 *evolution_of_loop = chrec_dont_know;
1292 return res;
1295 /* Otherwise, compute the overall effect of the inner loop. */
1296 ev = compute_overall_effect_of_inner_loop (loop, ev);
1297 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1298 evolution_of_loop, limit);
1301 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1302 path that is analyzed on the return walk. */
1304 static t_bool
1305 follow_ssa_edge (struct loop *loop, gimple def, gimple halting_phi,
1306 tree *evolution_of_loop, int limit)
1308 struct loop *def_loop;
1310 if (gimple_nop_p (def))
1311 return t_false;
1313 /* Give up if the path is longer than the MAX that we allow. */
1314 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY))
1315 return t_dont_know;
1317 def_loop = loop_containing_stmt (def);
1319 switch (gimple_code (def))
1321 case GIMPLE_PHI:
1322 if (!loop_phi_node_p (def))
1323 /* DEF is a condition-phi-node. Follow the branches, and
1324 record their evolutions. Finally, merge the collected
1325 information and set the approximation to the main
1326 variable. */
1327 return follow_ssa_edge_in_condition_phi
1328 (loop, def, halting_phi, evolution_of_loop, limit);
1330 /* When the analyzed phi is the halting_phi, the
1331 depth-first search is over: we have found a path from
1332 the halting_phi to itself in the loop. */
1333 if (def == halting_phi)
1334 return t_true;
1336 /* Otherwise, the evolution of the HALTING_PHI depends
1337 on the evolution of another loop-phi-node, i.e. the
1338 evolution function is a higher degree polynomial. */
1339 if (def_loop == loop)
1340 return t_false;
1342 /* Inner loop. */
1343 if (flow_loop_nested_p (loop, def_loop))
1344 return follow_ssa_edge_inner_loop_phi
1345 (loop, def, halting_phi, evolution_of_loop, limit + 1);
1347 /* Outer loop. */
1348 return t_false;
1350 case GIMPLE_ASSIGN:
1351 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1352 evolution_of_loop, limit);
1354 default:
1355 /* At this level of abstraction, the program is just a set
1356 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1357 other node to be handled. */
1358 return t_false;
1364 /* Given a LOOP_PHI_NODE, this function determines the evolution
1365 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1367 static tree
1368 analyze_evolution_in_loop (gimple loop_phi_node,
1369 tree init_cond)
1371 int i, n = gimple_phi_num_args (loop_phi_node);
1372 tree evolution_function = chrec_not_analyzed_yet;
1373 struct loop *loop = loop_containing_stmt (loop_phi_node);
1374 basic_block bb;
1376 if (dump_file && (dump_flags & TDF_SCEV))
1378 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1379 fprintf (dump_file, " (loop_phi_node = ");
1380 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1381 fprintf (dump_file, ")\n");
1384 for (i = 0; i < n; i++)
1386 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1387 gimple ssa_chain;
1388 tree ev_fn;
1389 t_bool res;
1391 /* Select the edges that enter the loop body. */
1392 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1393 if (!flow_bb_inside_loop_p (loop, bb))
1394 continue;
1396 if (TREE_CODE (arg) == SSA_NAME)
1398 bool val = false;
1400 ssa_chain = SSA_NAME_DEF_STMT (arg);
1402 /* Pass in the initial condition to the follow edge function. */
1403 ev_fn = init_cond;
1404 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1406 /* If ev_fn has no evolution in the inner loop, and the
1407 init_cond is not equal to ev_fn, then we have an
1408 ambiguity between two possible values, as we cannot know
1409 the number of iterations at this point. */
1410 if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1411 && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1412 && !operand_equal_p (init_cond, ev_fn, 0))
1413 ev_fn = chrec_dont_know;
1415 else
1416 res = t_false;
1418 /* When it is impossible to go back on the same
1419 loop_phi_node by following the ssa edges, the
1420 evolution is represented by a peeled chrec, i.e. the
1421 first iteration, EV_FN has the value INIT_COND, then
1422 all the other iterations it has the value of ARG.
1423 For the moment, PEELED_CHREC nodes are not built. */
1424 if (res != t_true)
1425 ev_fn = chrec_dont_know;
1427 /* When there are multiple back edges of the loop (which in fact never
1428 happens currently, but nevertheless), merge their evolutions. */
1429 evolution_function = chrec_merge (evolution_function, ev_fn);
1432 if (dump_file && (dump_flags & TDF_SCEV))
1434 fprintf (dump_file, " (evolution_function = ");
1435 print_generic_expr (dump_file, evolution_function, 0);
1436 fprintf (dump_file, "))\n");
1439 return evolution_function;
1442 /* Given a loop-phi-node, return the initial conditions of the
1443 variable on entry of the loop. When the CCP has propagated
1444 constants into the loop-phi-node, the initial condition is
1445 instantiated, otherwise the initial condition is kept symbolic.
1446 This analyzer does not analyze the evolution outside the current
1447 loop, and leaves this task to the on-demand tree reconstructor. */
1449 static tree
1450 analyze_initial_condition (gimple loop_phi_node)
1452 int i, n;
1453 tree init_cond = chrec_not_analyzed_yet;
1454 struct loop *loop = loop_containing_stmt (loop_phi_node);
1456 if (dump_file && (dump_flags & TDF_SCEV))
1458 fprintf (dump_file, "(analyze_initial_condition \n");
1459 fprintf (dump_file, " (loop_phi_node = \n");
1460 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1461 fprintf (dump_file, ")\n");
1464 n = gimple_phi_num_args (loop_phi_node);
1465 for (i = 0; i < n; i++)
1467 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1468 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1470 /* When the branch is oriented to the loop's body, it does
1471 not contribute to the initial condition. */
1472 if (flow_bb_inside_loop_p (loop, bb))
1473 continue;
1475 if (init_cond == chrec_not_analyzed_yet)
1477 init_cond = branch;
1478 continue;
1481 if (TREE_CODE (branch) == SSA_NAME)
1483 init_cond = chrec_dont_know;
1484 break;
1487 init_cond = chrec_merge (init_cond, branch);
1490 /* Ooops -- a loop without an entry??? */
1491 if (init_cond == chrec_not_analyzed_yet)
1492 init_cond = chrec_dont_know;
1494 /* During early loop unrolling we do not have fully constant propagated IL.
1495 Handle degenerate PHIs here to not miss important unrollings. */
1496 if (TREE_CODE (init_cond) == SSA_NAME)
1498 gimple def = SSA_NAME_DEF_STMT (init_cond);
1499 tree res;
1500 if (gimple_code (def) == GIMPLE_PHI
1501 && (res = degenerate_phi_result (def)) != NULL_TREE
1502 /* Only allow invariants here, otherwise we may break
1503 loop-closed SSA form. */
1504 && is_gimple_min_invariant (res))
1505 init_cond = res;
1508 if (dump_file && (dump_flags & TDF_SCEV))
1510 fprintf (dump_file, " (init_cond = ");
1511 print_generic_expr (dump_file, init_cond, 0);
1512 fprintf (dump_file, "))\n");
1515 return init_cond;
1518 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1520 static tree
1521 interpret_loop_phi (struct loop *loop, gimple loop_phi_node)
1523 tree res;
1524 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1525 tree init_cond;
1527 if (phi_loop != loop)
1529 struct loop *subloop;
1530 tree evolution_fn = analyze_scalar_evolution
1531 (phi_loop, PHI_RESULT (loop_phi_node));
1533 /* Dive one level deeper. */
1534 subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1536 /* Interpret the subloop. */
1537 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1538 return res;
1541 /* Otherwise really interpret the loop phi. */
1542 init_cond = analyze_initial_condition (loop_phi_node);
1543 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1545 /* Verify we maintained the correct initial condition throughout
1546 possible conversions in the SSA chain. */
1547 if (res != chrec_dont_know)
1549 tree new_init = res;
1550 if (CONVERT_EXPR_P (res)
1551 && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1552 new_init = fold_convert (TREE_TYPE (res),
1553 CHREC_LEFT (TREE_OPERAND (res, 0)));
1554 else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1555 new_init = CHREC_LEFT (res);
1556 STRIP_USELESS_TYPE_CONVERSION (new_init);
1557 if (TREE_CODE (new_init) == POLYNOMIAL_CHREC
1558 || !operand_equal_p (init_cond, new_init, 0))
1559 return chrec_dont_know;
1562 return res;
1565 /* This function merges the branches of a condition-phi-node,
1566 contained in the outermost loop, and whose arguments are already
1567 analyzed. */
1569 static tree
1570 interpret_condition_phi (struct loop *loop, gimple condition_phi)
1572 int i, n = gimple_phi_num_args (condition_phi);
1573 tree res = chrec_not_analyzed_yet;
1575 for (i = 0; i < n; i++)
1577 tree branch_chrec;
1579 if (backedge_phi_arg_p (condition_phi, i))
1581 res = chrec_dont_know;
1582 break;
1585 branch_chrec = analyze_scalar_evolution
1586 (loop, PHI_ARG_DEF (condition_phi, i));
1588 res = chrec_merge (res, branch_chrec);
1591 return res;
1594 /* Interpret the operation RHS1 OP RHS2. If we didn't
1595 analyze this node before, follow the definitions until ending
1596 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1597 return path, this function propagates evolutions (ala constant copy
1598 propagation). OPND1 is not a GIMPLE expression because we could
1599 analyze the effect of an inner loop: see interpret_loop_phi. */
1601 static tree
1602 interpret_rhs_expr (struct loop *loop, gimple at_stmt,
1603 tree type, tree rhs1, enum tree_code code, tree rhs2)
1605 tree res, chrec1, chrec2;
1606 gimple def;
1608 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1610 if (is_gimple_min_invariant (rhs1))
1611 return chrec_convert (type, rhs1, at_stmt);
1613 if (code == SSA_NAME)
1614 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1615 at_stmt);
1617 if (code == ASSERT_EXPR)
1619 rhs1 = ASSERT_EXPR_VAR (rhs1);
1620 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1621 at_stmt);
1625 switch (code)
1627 case ADDR_EXPR:
1628 if (TREE_CODE (TREE_OPERAND (rhs1, 0)) == MEM_REF
1629 || handled_component_p (TREE_OPERAND (rhs1, 0)))
1631 enum machine_mode mode;
1632 HOST_WIDE_INT bitsize, bitpos;
1633 int unsignedp;
1634 int volatilep = 0;
1635 tree base, offset;
1636 tree chrec3;
1637 tree unitpos;
1639 base = get_inner_reference (TREE_OPERAND (rhs1, 0),
1640 &bitsize, &bitpos, &offset,
1641 &mode, &unsignedp, &volatilep, false);
1643 if (TREE_CODE (base) == MEM_REF)
1645 rhs2 = TREE_OPERAND (base, 1);
1646 rhs1 = TREE_OPERAND (base, 0);
1648 chrec1 = analyze_scalar_evolution (loop, rhs1);
1649 chrec2 = analyze_scalar_evolution (loop, rhs2);
1650 chrec1 = chrec_convert (type, chrec1, at_stmt);
1651 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1652 chrec1 = instantiate_parameters (loop, chrec1);
1653 chrec2 = instantiate_parameters (loop, chrec2);
1654 res = chrec_fold_plus (type, chrec1, chrec2);
1656 else
1658 chrec1 = analyze_scalar_evolution_for_address_of (loop, base);
1659 chrec1 = chrec_convert (type, chrec1, at_stmt);
1660 res = chrec1;
1663 if (offset != NULL_TREE)
1665 chrec2 = analyze_scalar_evolution (loop, offset);
1666 chrec2 = chrec_convert (TREE_TYPE (offset), chrec2, at_stmt);
1667 chrec2 = instantiate_parameters (loop, chrec2);
1668 res = chrec_fold_plus (type, res, chrec2);
1671 if (bitpos != 0)
1673 gcc_assert ((bitpos % BITS_PER_UNIT) == 0);
1675 unitpos = size_int (bitpos / BITS_PER_UNIT);
1676 chrec3 = analyze_scalar_evolution (loop, unitpos);
1677 chrec3 = chrec_convert (TREE_TYPE (unitpos), chrec3, at_stmt);
1678 chrec3 = instantiate_parameters (loop, chrec3);
1679 res = chrec_fold_plus (type, res, chrec3);
1682 else
1683 res = chrec_dont_know;
1684 break;
1686 case POINTER_PLUS_EXPR:
1687 chrec1 = analyze_scalar_evolution (loop, rhs1);
1688 chrec2 = analyze_scalar_evolution (loop, rhs2);
1689 chrec1 = chrec_convert (type, chrec1, at_stmt);
1690 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1691 chrec1 = instantiate_parameters (loop, chrec1);
1692 chrec2 = instantiate_parameters (loop, chrec2);
1693 res = chrec_fold_plus (type, chrec1, chrec2);
1694 break;
1696 case PLUS_EXPR:
1697 chrec1 = analyze_scalar_evolution (loop, rhs1);
1698 chrec2 = analyze_scalar_evolution (loop, rhs2);
1699 chrec1 = chrec_convert (type, chrec1, at_stmt);
1700 chrec2 = chrec_convert (type, chrec2, at_stmt);
1701 chrec1 = instantiate_parameters (loop, chrec1);
1702 chrec2 = instantiate_parameters (loop, chrec2);
1703 res = chrec_fold_plus (type, chrec1, chrec2);
1704 break;
1706 case MINUS_EXPR:
1707 chrec1 = analyze_scalar_evolution (loop, rhs1);
1708 chrec2 = analyze_scalar_evolution (loop, rhs2);
1709 chrec1 = chrec_convert (type, chrec1, at_stmt);
1710 chrec2 = chrec_convert (type, chrec2, at_stmt);
1711 chrec1 = instantiate_parameters (loop, chrec1);
1712 chrec2 = instantiate_parameters (loop, chrec2);
1713 res = chrec_fold_minus (type, chrec1, chrec2);
1714 break;
1716 case NEGATE_EXPR:
1717 chrec1 = analyze_scalar_evolution (loop, rhs1);
1718 chrec1 = chrec_convert (type, chrec1, at_stmt);
1719 /* TYPE may be integer, real or complex, so use fold_convert. */
1720 chrec1 = instantiate_parameters (loop, chrec1);
1721 res = chrec_fold_multiply (type, chrec1,
1722 fold_convert (type, integer_minus_one_node));
1723 break;
1725 case BIT_NOT_EXPR:
1726 /* Handle ~X as -1 - X. */
1727 chrec1 = analyze_scalar_evolution (loop, rhs1);
1728 chrec1 = chrec_convert (type, chrec1, at_stmt);
1729 chrec1 = instantiate_parameters (loop, chrec1);
1730 res = chrec_fold_minus (type,
1731 fold_convert (type, integer_minus_one_node),
1732 chrec1);
1733 break;
1735 case MULT_EXPR:
1736 chrec1 = analyze_scalar_evolution (loop, rhs1);
1737 chrec2 = analyze_scalar_evolution (loop, rhs2);
1738 chrec1 = chrec_convert (type, chrec1, at_stmt);
1739 chrec2 = chrec_convert (type, chrec2, at_stmt);
1740 chrec1 = instantiate_parameters (loop, chrec1);
1741 chrec2 = instantiate_parameters (loop, chrec2);
1742 res = chrec_fold_multiply (type, chrec1, chrec2);
1743 break;
1745 CASE_CONVERT:
1746 /* In case we have a truncation of a widened operation that in
1747 the truncated type has undefined overflow behavior analyze
1748 the operation done in an unsigned type of the same precision
1749 as the final truncation. We cannot derive a scalar evolution
1750 for the widened operation but for the truncated result. */
1751 if (TREE_CODE (type) == INTEGER_TYPE
1752 && TREE_CODE (TREE_TYPE (rhs1)) == INTEGER_TYPE
1753 && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (rhs1))
1754 && TYPE_OVERFLOW_UNDEFINED (type)
1755 && TREE_CODE (rhs1) == SSA_NAME
1756 && (def = SSA_NAME_DEF_STMT (rhs1))
1757 && is_gimple_assign (def)
1758 && TREE_CODE_CLASS (gimple_assign_rhs_code (def)) == tcc_binary
1759 && TREE_CODE (gimple_assign_rhs2 (def)) == INTEGER_CST)
1761 tree utype = unsigned_type_for (type);
1762 chrec1 = interpret_rhs_expr (loop, at_stmt, utype,
1763 gimple_assign_rhs1 (def),
1764 gimple_assign_rhs_code (def),
1765 gimple_assign_rhs2 (def));
1767 else
1768 chrec1 = analyze_scalar_evolution (loop, rhs1);
1769 res = chrec_convert (type, chrec1, at_stmt);
1770 break;
1772 default:
1773 res = chrec_dont_know;
1774 break;
1777 return res;
1780 /* Interpret the expression EXPR. */
1782 static tree
1783 interpret_expr (struct loop *loop, gimple at_stmt, tree expr)
1785 enum tree_code code;
1786 tree type = TREE_TYPE (expr), op0, op1;
1788 if (automatically_generated_chrec_p (expr))
1789 return expr;
1791 if (TREE_CODE (expr) == POLYNOMIAL_CHREC
1792 || get_gimple_rhs_class (TREE_CODE (expr)) == GIMPLE_TERNARY_RHS)
1793 return chrec_dont_know;
1795 extract_ops_from_tree (expr, &code, &op0, &op1);
1797 return interpret_rhs_expr (loop, at_stmt, type,
1798 op0, code, op1);
1801 /* Interpret the rhs of the assignment STMT. */
1803 static tree
1804 interpret_gimple_assign (struct loop *loop, gimple stmt)
1806 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1807 enum tree_code code = gimple_assign_rhs_code (stmt);
1809 return interpret_rhs_expr (loop, stmt, type,
1810 gimple_assign_rhs1 (stmt), code,
1811 gimple_assign_rhs2 (stmt));
1816 /* This section contains all the entry points:
1817 - number_of_iterations_in_loop,
1818 - analyze_scalar_evolution,
1819 - instantiate_parameters.
1822 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1823 common ancestor of DEF_LOOP and USE_LOOP. */
1825 static tree
1826 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1827 struct loop *def_loop,
1828 tree ev)
1830 bool val;
1831 tree res;
1833 if (def_loop == wrto_loop)
1834 return ev;
1836 def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
1837 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1839 if (no_evolution_in_loop_p (res, wrto_loop->num, &val) && val)
1840 return res;
1842 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1845 /* Helper recursive function. */
1847 static tree
1848 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1850 tree type = TREE_TYPE (var);
1851 gimple def;
1852 basic_block bb;
1853 struct loop *def_loop;
1855 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1856 return chrec_dont_know;
1858 if (TREE_CODE (var) != SSA_NAME)
1859 return interpret_expr (loop, NULL, var);
1861 def = SSA_NAME_DEF_STMT (var);
1862 bb = gimple_bb (def);
1863 def_loop = bb ? bb->loop_father : NULL;
1865 if (bb == NULL
1866 || !flow_bb_inside_loop_p (loop, bb))
1868 /* Keep the symbolic form. */
1869 res = var;
1870 goto set_and_end;
1873 if (res != chrec_not_analyzed_yet)
1875 if (loop != bb->loop_father)
1876 res = compute_scalar_evolution_in_loop
1877 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1879 goto set_and_end;
1882 if (loop != def_loop)
1884 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1885 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1887 goto set_and_end;
1890 switch (gimple_code (def))
1892 case GIMPLE_ASSIGN:
1893 res = interpret_gimple_assign (loop, def);
1894 break;
1896 case GIMPLE_PHI:
1897 if (loop_phi_node_p (def))
1898 res = interpret_loop_phi (loop, def);
1899 else
1900 res = interpret_condition_phi (loop, def);
1901 break;
1903 default:
1904 res = chrec_dont_know;
1905 break;
1908 set_and_end:
1910 /* Keep the symbolic form. */
1911 if (res == chrec_dont_know)
1912 res = var;
1914 if (loop == def_loop)
1915 set_scalar_evolution (block_before_loop (loop), var, res);
1917 return res;
1920 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
1921 LOOP. LOOP is the loop in which the variable is used.
1923 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
1924 pointer to the statement that uses this variable, in order to
1925 determine the evolution function of the variable, use the following
1926 calls:
1928 loop_p loop = loop_containing_stmt (stmt);
1929 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
1930 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
1933 tree
1934 analyze_scalar_evolution (struct loop *loop, tree var)
1936 tree res;
1938 if (dump_file && (dump_flags & TDF_SCEV))
1940 fprintf (dump_file, "(analyze_scalar_evolution \n");
1941 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
1942 fprintf (dump_file, " (scalar = ");
1943 print_generic_expr (dump_file, var, 0);
1944 fprintf (dump_file, ")\n");
1947 res = get_scalar_evolution (block_before_loop (loop), var);
1948 res = analyze_scalar_evolution_1 (loop, var, res);
1950 if (dump_file && (dump_flags & TDF_SCEV))
1951 fprintf (dump_file, ")\n");
1953 return res;
1956 /* Analyzes and returns the scalar evolution of VAR address in LOOP. */
1958 static tree
1959 analyze_scalar_evolution_for_address_of (struct loop *loop, tree var)
1961 return analyze_scalar_evolution (loop, build_fold_addr_expr (var));
1964 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
1965 WRTO_LOOP (which should be a superloop of USE_LOOP)
1967 FOLDED_CASTS is set to true if resolve_mixers used
1968 chrec_convert_aggressive (TODO -- not really, we are way too conservative
1969 at the moment in order to keep things simple).
1971 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
1972 example:
1974 for (i = 0; i < 100; i++) -- loop 1
1976 for (j = 0; j < 100; j++) -- loop 2
1978 k1 = i;
1979 k2 = j;
1981 use2 (k1, k2);
1983 for (t = 0; t < 100; t++) -- loop 3
1984 use3 (k1, k2);
1987 use1 (k1, k2);
1990 Both k1 and k2 are invariants in loop3, thus
1991 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
1992 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
1994 As they are invariant, it does not matter whether we consider their
1995 usage in loop 3 or loop 2, hence
1996 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
1997 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
1998 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
1999 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
2001 Similarly for their evolutions with respect to loop 1. The values of K2
2002 in the use in loop 2 vary independently on loop 1, thus we cannot express
2003 the evolution with respect to loop 1:
2004 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
2005 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
2006 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
2007 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
2009 The value of k2 in the use in loop 1 is known, though:
2010 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
2011 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
2014 static tree
2015 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
2016 tree version, bool *folded_casts)
2018 bool val = false;
2019 tree ev = version, tmp;
2021 /* We cannot just do
2023 tmp = analyze_scalar_evolution (use_loop, version);
2024 ev = resolve_mixers (wrto_loop, tmp);
2026 as resolve_mixers would query the scalar evolution with respect to
2027 wrto_loop. For example, in the situation described in the function
2028 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2029 version = k2. Then
2031 analyze_scalar_evolution (use_loop, version) = k2
2033 and resolve_mixers (loop1, k2) finds that the value of k2 in loop 1
2034 is 100, which is a wrong result, since we are interested in the
2035 value in loop 3.
2037 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2038 each time checking that there is no evolution in the inner loop. */
2040 if (folded_casts)
2041 *folded_casts = false;
2042 while (1)
2044 tmp = analyze_scalar_evolution (use_loop, ev);
2045 ev = resolve_mixers (use_loop, tmp);
2047 if (folded_casts && tmp != ev)
2048 *folded_casts = true;
2050 if (use_loop == wrto_loop)
2051 return ev;
2053 /* If the value of the use changes in the inner loop, we cannot express
2054 its value in the outer loop (we might try to return interval chrec,
2055 but we do not have a user for it anyway) */
2056 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2057 || !val)
2058 return chrec_dont_know;
2060 use_loop = loop_outer (use_loop);
2065 /* Hashtable helpers for a temporary hash-table used when
2066 instantiating a CHREC or resolving mixers. For this use
2067 instantiated_below is always the same. */
2069 struct instantiate_cache_type
2071 htab_t map;
2072 vec<scev_info_str> entries;
2074 instantiate_cache_type () : map (NULL), entries(vNULL) {}
2075 ~instantiate_cache_type ();
2076 tree get (unsigned slot) { return entries[slot].chrec; }
2077 void set (unsigned slot, tree chrec) { entries[slot].chrec = chrec; }
2080 instantiate_cache_type::~instantiate_cache_type ()
2082 if (map != NULL)
2084 htab_delete (map);
2085 entries.release ();
2089 /* Cache to avoid infinite recursion when instantiating an SSA name.
2090 Live during the outermost instantiate_scev or resolve_mixers call. */
2091 static instantiate_cache_type *global_cache;
2093 /* Computes a hash function for database element ELT. */
2095 static inline hashval_t
2096 hash_idx_scev_info (const void *elt_)
2098 unsigned idx = ((size_t) elt_) - 2;
2099 return hash_scev_info (&global_cache->entries[idx]);
2102 /* Compares database elements E1 and E2. */
2104 static inline int
2105 eq_idx_scev_info (const void *e1, const void *e2)
2107 unsigned idx1 = ((size_t) e1) - 2;
2108 return eq_scev_info (&global_cache->entries[idx1], e2);
2111 /* Returns from CACHE the slot number of the cached chrec for NAME. */
2113 static unsigned
2114 get_instantiated_value_entry (instantiate_cache_type &cache,
2115 tree name, basic_block instantiate_below)
2117 if (!cache.map)
2119 cache.map = htab_create (10, hash_idx_scev_info, eq_idx_scev_info, NULL);
2120 cache.entries.create (10);
2123 scev_info_str e;
2124 e.name_version = SSA_NAME_VERSION (name);
2125 e.instantiated_below = instantiate_below->index;
2126 void **slot = htab_find_slot_with_hash (cache.map, &e,
2127 hash_scev_info (&e), INSERT);
2128 if (!*slot)
2130 e.chrec = chrec_not_analyzed_yet;
2131 *slot = (void *)(size_t)(cache.entries.length () + 2);
2132 cache.entries.safe_push (e);
2135 return ((size_t)*slot) - 2;
2139 /* Return the closed_loop_phi node for VAR. If there is none, return
2140 NULL_TREE. */
2142 static tree
2143 loop_closed_phi_def (tree var)
2145 struct loop *loop;
2146 edge exit;
2147 gimple phi;
2148 gimple_stmt_iterator psi;
2150 if (var == NULL_TREE
2151 || TREE_CODE (var) != SSA_NAME)
2152 return NULL_TREE;
2154 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2155 exit = single_exit (loop);
2156 if (!exit)
2157 return NULL_TREE;
2159 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2161 phi = gsi_stmt (psi);
2162 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2163 return PHI_RESULT (phi);
2166 return NULL_TREE;
2169 static tree instantiate_scev_r (basic_block, struct loop *, struct loop *,
2170 tree, bool, int);
2172 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2173 and EVOLUTION_LOOP, that were left under a symbolic form.
2175 CHREC is an SSA_NAME to be instantiated.
2177 CACHE is the cache of already instantiated values.
2179 FOLD_CONVERSIONS should be set to true when the conversions that
2180 may wrap in signed/pointer type are folded, as long as the value of
2181 the chrec is preserved.
2183 SIZE_EXPR is used for computing the size of the expression to be
2184 instantiated, and to stop if it exceeds some limit. */
2186 static tree
2187 instantiate_scev_name (basic_block instantiate_below,
2188 struct loop *evolution_loop, struct loop *inner_loop,
2189 tree chrec,
2190 bool fold_conversions,
2191 int size_expr)
2193 tree res;
2194 struct loop *def_loop;
2195 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2197 /* A parameter (or loop invariant and we do not want to include
2198 evolutions in outer loops), nothing to do. */
2199 if (!def_bb
2200 || loop_depth (def_bb->loop_father) == 0
2201 || dominated_by_p (CDI_DOMINATORS, instantiate_below, def_bb))
2202 return chrec;
2204 /* We cache the value of instantiated variable to avoid exponential
2205 time complexity due to reevaluations. We also store the convenient
2206 value in the cache in order to prevent infinite recursion -- we do
2207 not want to instantiate the SSA_NAME if it is in a mixer
2208 structure. This is used for avoiding the instantiation of
2209 recursively defined functions, such as:
2211 | a_2 -> {0, +, 1, +, a_2}_1 */
2213 unsigned si = get_instantiated_value_entry (*global_cache,
2214 chrec, instantiate_below);
2215 if (global_cache->get (si) != chrec_not_analyzed_yet)
2216 return global_cache->get (si);
2218 /* On recursion return chrec_dont_know. */
2219 global_cache->set (si, chrec_dont_know);
2221 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2223 /* If the analysis yields a parametric chrec, instantiate the
2224 result again. */
2225 res = analyze_scalar_evolution (def_loop, chrec);
2227 /* Don't instantiate default definitions. */
2228 if (TREE_CODE (res) == SSA_NAME
2229 && SSA_NAME_IS_DEFAULT_DEF (res))
2232 /* Don't instantiate loop-closed-ssa phi nodes. */
2233 else if (TREE_CODE (res) == SSA_NAME
2234 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2235 > loop_depth (def_loop))
2237 if (res == chrec)
2238 res = loop_closed_phi_def (chrec);
2239 else
2240 res = chrec;
2242 /* When there is no loop_closed_phi_def, it means that the
2243 variable is not used after the loop: try to still compute the
2244 value of the variable when exiting the loop. */
2245 if (res == NULL_TREE)
2247 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2248 res = analyze_scalar_evolution (loop, chrec);
2249 res = compute_overall_effect_of_inner_loop (loop, res);
2250 res = instantiate_scev_r (instantiate_below, evolution_loop,
2251 inner_loop, res,
2252 fold_conversions, size_expr);
2254 else if (!dominated_by_p (CDI_DOMINATORS, instantiate_below,
2255 gimple_bb (SSA_NAME_DEF_STMT (res))))
2256 res = chrec_dont_know;
2259 else if (res != chrec_dont_know)
2261 if (inner_loop
2262 && def_bb->loop_father != inner_loop
2263 && !flow_loop_nested_p (def_bb->loop_father, inner_loop))
2264 /* ??? We could try to compute the overall effect of the loop here. */
2265 res = chrec_dont_know;
2266 else
2267 res = instantiate_scev_r (instantiate_below, evolution_loop,
2268 inner_loop, res,
2269 fold_conversions, size_expr);
2272 /* Store the correct value to the cache. */
2273 global_cache->set (si, res);
2274 return res;
2277 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2278 and EVOLUTION_LOOP, that were left under a symbolic form.
2280 CHREC is a polynomial chain of recurrence to be instantiated.
2282 CACHE is the cache of already instantiated values.
2284 FOLD_CONVERSIONS should be set to true when the conversions that
2285 may wrap in signed/pointer type are folded, as long as the value of
2286 the chrec is preserved.
2288 SIZE_EXPR is used for computing the size of the expression to be
2289 instantiated, and to stop if it exceeds some limit. */
2291 static tree
2292 instantiate_scev_poly (basic_block instantiate_below,
2293 struct loop *evolution_loop, struct loop *,
2294 tree chrec, bool fold_conversions, int size_expr)
2296 tree op1;
2297 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2298 get_chrec_loop (chrec),
2299 CHREC_LEFT (chrec), fold_conversions,
2300 size_expr);
2301 if (op0 == chrec_dont_know)
2302 return chrec_dont_know;
2304 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2305 get_chrec_loop (chrec),
2306 CHREC_RIGHT (chrec), fold_conversions,
2307 size_expr);
2308 if (op1 == chrec_dont_know)
2309 return chrec_dont_know;
2311 if (CHREC_LEFT (chrec) != op0
2312 || CHREC_RIGHT (chrec) != op1)
2314 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2315 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2318 return chrec;
2321 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2322 and EVOLUTION_LOOP, that were left under a symbolic form.
2324 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2326 CACHE is the cache of already instantiated values.
2328 FOLD_CONVERSIONS should be set to true when the conversions that
2329 may wrap in signed/pointer type are folded, as long as the value of
2330 the chrec is preserved.
2332 SIZE_EXPR is used for computing the size of the expression to be
2333 instantiated, and to stop if it exceeds some limit. */
2335 static tree
2336 instantiate_scev_binary (basic_block instantiate_below,
2337 struct loop *evolution_loop, struct loop *inner_loop,
2338 tree chrec, enum tree_code code,
2339 tree type, tree c0, tree c1,
2340 bool fold_conversions, int size_expr)
2342 tree op1;
2343 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2344 c0, fold_conversions, size_expr);
2345 if (op0 == chrec_dont_know)
2346 return chrec_dont_know;
2348 op1 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2349 c1, fold_conversions, size_expr);
2350 if (op1 == chrec_dont_know)
2351 return chrec_dont_know;
2353 if (c0 != op0
2354 || c1 != op1)
2356 op0 = chrec_convert (type, op0, NULL);
2357 op1 = chrec_convert_rhs (type, op1, NULL);
2359 switch (code)
2361 case POINTER_PLUS_EXPR:
2362 case PLUS_EXPR:
2363 return chrec_fold_plus (type, op0, op1);
2365 case MINUS_EXPR:
2366 return chrec_fold_minus (type, op0, op1);
2368 case MULT_EXPR:
2369 return chrec_fold_multiply (type, op0, op1);
2371 default:
2372 gcc_unreachable ();
2376 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2379 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2380 and EVOLUTION_LOOP, that were left under a symbolic form.
2382 "CHREC" is an array reference to be instantiated.
2384 CACHE is the cache of already instantiated values.
2386 FOLD_CONVERSIONS should be set to true when the conversions that
2387 may wrap in signed/pointer type are folded, as long as the value of
2388 the chrec is preserved.
2390 SIZE_EXPR is used for computing the size of the expression to be
2391 instantiated, and to stop if it exceeds some limit. */
2393 static tree
2394 instantiate_array_ref (basic_block instantiate_below,
2395 struct loop *evolution_loop, struct loop *inner_loop,
2396 tree chrec, bool fold_conversions, int size_expr)
2398 tree res;
2399 tree index = TREE_OPERAND (chrec, 1);
2400 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2401 inner_loop, index,
2402 fold_conversions, size_expr);
2404 if (op1 == chrec_dont_know)
2405 return chrec_dont_know;
2407 if (chrec && op1 == index)
2408 return chrec;
2410 res = unshare_expr (chrec);
2411 TREE_OPERAND (res, 1) = op1;
2412 return res;
2415 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2416 and EVOLUTION_LOOP, that were left under a symbolic form.
2418 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2419 instantiated.
2421 CACHE is the cache of already instantiated values.
2423 FOLD_CONVERSIONS should be set to true when the conversions that
2424 may wrap in signed/pointer type are folded, as long as the value of
2425 the chrec is preserved.
2427 SIZE_EXPR is used for computing the size of the expression to be
2428 instantiated, and to stop if it exceeds some limit. */
2430 static tree
2431 instantiate_scev_convert (basic_block instantiate_below,
2432 struct loop *evolution_loop, struct loop *inner_loop,
2433 tree chrec, tree type, tree op,
2434 bool fold_conversions, int size_expr)
2436 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2437 inner_loop, op,
2438 fold_conversions, size_expr);
2440 if (op0 == chrec_dont_know)
2441 return chrec_dont_know;
2443 if (fold_conversions)
2445 tree tmp = chrec_convert_aggressive (type, op0);
2446 if (tmp)
2447 return tmp;
2450 if (chrec && op0 == op)
2451 return chrec;
2453 /* If we used chrec_convert_aggressive, we can no longer assume that
2454 signed chrecs do not overflow, as chrec_convert does, so avoid
2455 calling it in that case. */
2456 if (fold_conversions)
2457 return fold_convert (type, op0);
2459 return chrec_convert (type, op0, NULL);
2462 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2463 and EVOLUTION_LOOP, that were left under a symbolic form.
2465 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2466 Handle ~X as -1 - X.
2467 Handle -X as -1 * X.
2469 CACHE is the cache of already instantiated values.
2471 FOLD_CONVERSIONS should be set to true when the conversions that
2472 may wrap in signed/pointer type are folded, as long as the value of
2473 the chrec is preserved.
2475 SIZE_EXPR is used for computing the size of the expression to be
2476 instantiated, and to stop if it exceeds some limit. */
2478 static tree
2479 instantiate_scev_not (basic_block instantiate_below,
2480 struct loop *evolution_loop, struct loop *inner_loop,
2481 tree chrec,
2482 enum tree_code code, tree type, tree op,
2483 bool fold_conversions, int size_expr)
2485 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2486 inner_loop, op,
2487 fold_conversions, size_expr);
2489 if (op0 == chrec_dont_know)
2490 return chrec_dont_know;
2492 if (op != op0)
2494 op0 = chrec_convert (type, op0, NULL);
2496 switch (code)
2498 case BIT_NOT_EXPR:
2499 return chrec_fold_minus
2500 (type, fold_convert (type, integer_minus_one_node), op0);
2502 case NEGATE_EXPR:
2503 return chrec_fold_multiply
2504 (type, fold_convert (type, integer_minus_one_node), op0);
2506 default:
2507 gcc_unreachable ();
2511 return chrec ? chrec : fold_build1 (code, type, op0);
2514 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2515 and EVOLUTION_LOOP, that were left under a symbolic form.
2517 CHREC is an expression with 3 operands to be instantiated.
2519 CACHE is the cache of already instantiated values.
2521 FOLD_CONVERSIONS should be set to true when the conversions that
2522 may wrap in signed/pointer type are folded, as long as the value of
2523 the chrec is preserved.
2525 SIZE_EXPR is used for computing the size of the expression to be
2526 instantiated, and to stop if it exceeds some limit. */
2528 static tree
2529 instantiate_scev_3 (basic_block instantiate_below,
2530 struct loop *evolution_loop, struct loop *inner_loop,
2531 tree chrec,
2532 bool fold_conversions, int size_expr)
2534 tree op1, op2;
2535 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2536 inner_loop, TREE_OPERAND (chrec, 0),
2537 fold_conversions, size_expr);
2538 if (op0 == chrec_dont_know)
2539 return chrec_dont_know;
2541 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2542 inner_loop, TREE_OPERAND (chrec, 1),
2543 fold_conversions, size_expr);
2544 if (op1 == chrec_dont_know)
2545 return chrec_dont_know;
2547 op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2548 inner_loop, TREE_OPERAND (chrec, 2),
2549 fold_conversions, size_expr);
2550 if (op2 == chrec_dont_know)
2551 return chrec_dont_know;
2553 if (op0 == TREE_OPERAND (chrec, 0)
2554 && op1 == TREE_OPERAND (chrec, 1)
2555 && op2 == TREE_OPERAND (chrec, 2))
2556 return chrec;
2558 return fold_build3 (TREE_CODE (chrec),
2559 TREE_TYPE (chrec), op0, op1, op2);
2562 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2563 and EVOLUTION_LOOP, that were left under a symbolic form.
2565 CHREC is an expression with 2 operands to be instantiated.
2567 CACHE is the cache of already instantiated values.
2569 FOLD_CONVERSIONS should be set to true when the conversions that
2570 may wrap in signed/pointer type are folded, as long as the value of
2571 the chrec is preserved.
2573 SIZE_EXPR is used for computing the size of the expression to be
2574 instantiated, and to stop if it exceeds some limit. */
2576 static tree
2577 instantiate_scev_2 (basic_block instantiate_below,
2578 struct loop *evolution_loop, struct loop *inner_loop,
2579 tree chrec,
2580 bool fold_conversions, int size_expr)
2582 tree op1;
2583 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2584 inner_loop, TREE_OPERAND (chrec, 0),
2585 fold_conversions, size_expr);
2586 if (op0 == chrec_dont_know)
2587 return chrec_dont_know;
2589 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2590 inner_loop, TREE_OPERAND (chrec, 1),
2591 fold_conversions, size_expr);
2592 if (op1 == chrec_dont_know)
2593 return chrec_dont_know;
2595 if (op0 == TREE_OPERAND (chrec, 0)
2596 && op1 == TREE_OPERAND (chrec, 1))
2597 return chrec;
2599 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2602 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2603 and EVOLUTION_LOOP, that were left under a symbolic form.
2605 CHREC is an expression with 2 operands to be instantiated.
2607 CACHE is the cache of already instantiated values.
2609 FOLD_CONVERSIONS should be set to true when the conversions that
2610 may wrap in signed/pointer type are folded, as long as the value of
2611 the chrec is preserved.
2613 SIZE_EXPR is used for computing the size of the expression to be
2614 instantiated, and to stop if it exceeds some limit. */
2616 static tree
2617 instantiate_scev_1 (basic_block instantiate_below,
2618 struct loop *evolution_loop, struct loop *inner_loop,
2619 tree chrec,
2620 bool fold_conversions, int size_expr)
2622 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2623 inner_loop, TREE_OPERAND (chrec, 0),
2624 fold_conversions, size_expr);
2626 if (op0 == chrec_dont_know)
2627 return chrec_dont_know;
2629 if (op0 == TREE_OPERAND (chrec, 0))
2630 return chrec;
2632 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2635 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2636 and EVOLUTION_LOOP, that were left under a symbolic form.
2638 CHREC is the scalar evolution to instantiate.
2640 CACHE is the cache of already instantiated values.
2642 FOLD_CONVERSIONS should be set to true when the conversions that
2643 may wrap in signed/pointer type are folded, as long as the value of
2644 the chrec is preserved.
2646 SIZE_EXPR is used for computing the size of the expression to be
2647 instantiated, and to stop if it exceeds some limit. */
2649 static tree
2650 instantiate_scev_r (basic_block instantiate_below,
2651 struct loop *evolution_loop, struct loop *inner_loop,
2652 tree chrec,
2653 bool fold_conversions, int size_expr)
2655 /* Give up if the expression is larger than the MAX that we allow. */
2656 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2657 return chrec_dont_know;
2659 if (chrec == NULL_TREE
2660 || automatically_generated_chrec_p (chrec)
2661 || is_gimple_min_invariant (chrec))
2662 return chrec;
2664 switch (TREE_CODE (chrec))
2666 case SSA_NAME:
2667 return instantiate_scev_name (instantiate_below, evolution_loop,
2668 inner_loop, chrec,
2669 fold_conversions, size_expr);
2671 case POLYNOMIAL_CHREC:
2672 return instantiate_scev_poly (instantiate_below, evolution_loop,
2673 inner_loop, chrec,
2674 fold_conversions, size_expr);
2676 case POINTER_PLUS_EXPR:
2677 case PLUS_EXPR:
2678 case MINUS_EXPR:
2679 case MULT_EXPR:
2680 return instantiate_scev_binary (instantiate_below, evolution_loop,
2681 inner_loop, chrec,
2682 TREE_CODE (chrec), chrec_type (chrec),
2683 TREE_OPERAND (chrec, 0),
2684 TREE_OPERAND (chrec, 1),
2685 fold_conversions, size_expr);
2687 CASE_CONVERT:
2688 return instantiate_scev_convert (instantiate_below, evolution_loop,
2689 inner_loop, chrec,
2690 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2691 fold_conversions, size_expr);
2693 case NEGATE_EXPR:
2694 case BIT_NOT_EXPR:
2695 return instantiate_scev_not (instantiate_below, evolution_loop,
2696 inner_loop, chrec,
2697 TREE_CODE (chrec), TREE_TYPE (chrec),
2698 TREE_OPERAND (chrec, 0),
2699 fold_conversions, size_expr);
2701 case ADDR_EXPR:
2702 case SCEV_NOT_KNOWN:
2703 return chrec_dont_know;
2705 case SCEV_KNOWN:
2706 return chrec_known;
2708 case ARRAY_REF:
2709 return instantiate_array_ref (instantiate_below, evolution_loop,
2710 inner_loop, chrec,
2711 fold_conversions, size_expr);
2713 default:
2714 break;
2717 if (VL_EXP_CLASS_P (chrec))
2718 return chrec_dont_know;
2720 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2722 case 3:
2723 return instantiate_scev_3 (instantiate_below, evolution_loop,
2724 inner_loop, chrec,
2725 fold_conversions, size_expr);
2727 case 2:
2728 return instantiate_scev_2 (instantiate_below, evolution_loop,
2729 inner_loop, chrec,
2730 fold_conversions, size_expr);
2732 case 1:
2733 return instantiate_scev_1 (instantiate_below, evolution_loop,
2734 inner_loop, chrec,
2735 fold_conversions, size_expr);
2737 case 0:
2738 return chrec;
2740 default:
2741 break;
2744 /* Too complicated to handle. */
2745 return chrec_dont_know;
2748 /* Analyze all the parameters of the chrec that were left under a
2749 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2750 recursive instantiation of parameters: a parameter is a variable
2751 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2752 a function parameter. */
2754 tree
2755 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2756 tree chrec)
2758 tree res;
2760 if (dump_file && (dump_flags & TDF_SCEV))
2762 fprintf (dump_file, "(instantiate_scev \n");
2763 fprintf (dump_file, " (instantiate_below = %d)\n", instantiate_below->index);
2764 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2765 fprintf (dump_file, " (chrec = ");
2766 print_generic_expr (dump_file, chrec, 0);
2767 fprintf (dump_file, ")\n");
2770 bool destr = false;
2771 if (!global_cache)
2773 global_cache = new instantiate_cache_type;
2774 destr = true;
2777 res = instantiate_scev_r (instantiate_below, evolution_loop,
2778 NULL, chrec, false, 0);
2780 if (destr)
2782 delete global_cache;
2783 global_cache = NULL;
2786 if (dump_file && (dump_flags & TDF_SCEV))
2788 fprintf (dump_file, " (res = ");
2789 print_generic_expr (dump_file, res, 0);
2790 fprintf (dump_file, "))\n");
2793 return res;
2796 /* Similar to instantiate_parameters, but does not introduce the
2797 evolutions in outer loops for LOOP invariants in CHREC, and does not
2798 care about causing overflows, as long as they do not affect value
2799 of an expression. */
2801 tree
2802 resolve_mixers (struct loop *loop, tree chrec)
2804 bool destr = false;
2805 if (!global_cache)
2807 global_cache = new instantiate_cache_type;
2808 destr = true;
2811 tree ret = instantiate_scev_r (block_before_loop (loop), loop, NULL,
2812 chrec, true, 0);
2814 if (destr)
2816 delete global_cache;
2817 global_cache = NULL;
2820 return ret;
2823 /* Entry point for the analysis of the number of iterations pass.
2824 This function tries to safely approximate the number of iterations
2825 the loop will run. When this property is not decidable at compile
2826 time, the result is chrec_dont_know. Otherwise the result is a
2827 scalar or a symbolic parameter. When the number of iterations may
2828 be equal to zero and the property cannot be determined at compile
2829 time, the result is a COND_EXPR that represents in a symbolic form
2830 the conditions under which the number of iterations is not zero.
2832 Example of analysis: suppose that the loop has an exit condition:
2834 "if (b > 49) goto end_loop;"
2836 and that in a previous analysis we have determined that the
2837 variable 'b' has an evolution function:
2839 "EF = {23, +, 5}_2".
2841 When we evaluate the function at the point 5, i.e. the value of the
2842 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2843 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2844 the loop body has been executed 6 times. */
2846 tree
2847 number_of_latch_executions (struct loop *loop)
2849 edge exit;
2850 struct tree_niter_desc niter_desc;
2851 tree may_be_zero;
2852 tree res;
2854 /* Determine whether the number of iterations in loop has already
2855 been computed. */
2856 res = loop->nb_iterations;
2857 if (res)
2858 return res;
2860 may_be_zero = NULL_TREE;
2862 if (dump_file && (dump_flags & TDF_SCEV))
2863 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2865 res = chrec_dont_know;
2866 exit = single_exit (loop);
2868 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2870 may_be_zero = niter_desc.may_be_zero;
2871 res = niter_desc.niter;
2874 if (res == chrec_dont_know
2875 || !may_be_zero
2876 || integer_zerop (may_be_zero))
2878 else if (integer_nonzerop (may_be_zero))
2879 res = build_int_cst (TREE_TYPE (res), 0);
2881 else if (COMPARISON_CLASS_P (may_be_zero))
2882 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2883 build_int_cst (TREE_TYPE (res), 0), res);
2884 else
2885 res = chrec_dont_know;
2887 if (dump_file && (dump_flags & TDF_SCEV))
2889 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2890 print_generic_expr (dump_file, res, 0);
2891 fprintf (dump_file, "))\n");
2894 loop->nb_iterations = res;
2895 return res;
2898 /* Returns the number of executions of the exit condition of LOOP,
2899 i.e., the number by one higher than number_of_latch_executions.
2900 Note that unlike number_of_latch_executions, this number does
2901 not necessarily fit in the unsigned variant of the type of
2902 the control variable -- if the number of iterations is a constant,
2903 we return chrec_dont_know if adding one to number_of_latch_executions
2904 overflows; however, in case the number of iterations is symbolic
2905 expression, the caller is responsible for dealing with this
2906 the possible overflow. */
2908 tree
2909 number_of_exit_cond_executions (struct loop *loop)
2911 tree ret = number_of_latch_executions (loop);
2912 tree type = chrec_type (ret);
2914 if (chrec_contains_undetermined (ret))
2915 return ret;
2917 ret = chrec_fold_plus (type, ret, build_int_cst (type, 1));
2918 if (TREE_CODE (ret) == INTEGER_CST
2919 && TREE_OVERFLOW (ret))
2920 return chrec_dont_know;
2922 return ret;
2927 /* Counters for the stats. */
2929 struct chrec_stats
2931 unsigned nb_chrecs;
2932 unsigned nb_affine;
2933 unsigned nb_affine_multivar;
2934 unsigned nb_higher_poly;
2935 unsigned nb_chrec_dont_know;
2936 unsigned nb_undetermined;
2939 /* Reset the counters. */
2941 static inline void
2942 reset_chrecs_counters (struct chrec_stats *stats)
2944 stats->nb_chrecs = 0;
2945 stats->nb_affine = 0;
2946 stats->nb_affine_multivar = 0;
2947 stats->nb_higher_poly = 0;
2948 stats->nb_chrec_dont_know = 0;
2949 stats->nb_undetermined = 0;
2952 /* Dump the contents of a CHREC_STATS structure. */
2954 static void
2955 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2957 fprintf (file, "\n(\n");
2958 fprintf (file, "-----------------------------------------\n");
2959 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2960 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2961 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2962 stats->nb_higher_poly);
2963 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2964 fprintf (file, "-----------------------------------------\n");
2965 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2966 fprintf (file, "%d\twith undetermined coefficients\n",
2967 stats->nb_undetermined);
2968 fprintf (file, "-----------------------------------------\n");
2969 fprintf (file, "%d\tchrecs in the scev database\n",
2970 (int) htab_elements (scalar_evolution_info));
2971 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2972 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2973 fprintf (file, "-----------------------------------------\n");
2974 fprintf (file, ")\n\n");
2977 /* Gather statistics about CHREC. */
2979 static void
2980 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2982 if (dump_file && (dump_flags & TDF_STATS))
2984 fprintf (dump_file, "(classify_chrec ");
2985 print_generic_expr (dump_file, chrec, 0);
2986 fprintf (dump_file, "\n");
2989 stats->nb_chrecs++;
2991 if (chrec == NULL_TREE)
2993 stats->nb_undetermined++;
2994 return;
2997 switch (TREE_CODE (chrec))
2999 case POLYNOMIAL_CHREC:
3000 if (evolution_function_is_affine_p (chrec))
3002 if (dump_file && (dump_flags & TDF_STATS))
3003 fprintf (dump_file, " affine_univariate\n");
3004 stats->nb_affine++;
3006 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
3008 if (dump_file && (dump_flags & TDF_STATS))
3009 fprintf (dump_file, " affine_multivariate\n");
3010 stats->nb_affine_multivar++;
3012 else
3014 if (dump_file && (dump_flags & TDF_STATS))
3015 fprintf (dump_file, " higher_degree_polynomial\n");
3016 stats->nb_higher_poly++;
3019 break;
3021 default:
3022 break;
3025 if (chrec_contains_undetermined (chrec))
3027 if (dump_file && (dump_flags & TDF_STATS))
3028 fprintf (dump_file, " undetermined\n");
3029 stats->nb_undetermined++;
3032 if (dump_file && (dump_flags & TDF_STATS))
3033 fprintf (dump_file, ")\n");
3036 /* Callback for htab_traverse, gathers information on chrecs in the
3037 hashtable. */
3039 static int
3040 gather_stats_on_scev_database_1 (void **slot, void *stats)
3042 struct scev_info_str *entry = (struct scev_info_str *) *slot;
3044 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
3046 return 1;
3049 /* Classify the chrecs of the whole database. */
3051 void
3052 gather_stats_on_scev_database (void)
3054 struct chrec_stats stats;
3056 if (!dump_file)
3057 return;
3059 reset_chrecs_counters (&stats);
3061 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
3062 &stats);
3064 dump_chrecs_stats (dump_file, &stats);
3069 /* Initializer. */
3071 static void
3072 initialize_scalar_evolutions_analyzer (void)
3074 /* The elements below are unique. */
3075 if (chrec_dont_know == NULL_TREE)
3077 chrec_not_analyzed_yet = NULL_TREE;
3078 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3079 chrec_known = make_node (SCEV_KNOWN);
3080 TREE_TYPE (chrec_dont_know) = void_type_node;
3081 TREE_TYPE (chrec_known) = void_type_node;
3085 /* Initialize the analysis of scalar evolutions for LOOPS. */
3087 void
3088 scev_initialize (void)
3090 loop_iterator li;
3091 struct loop *loop;
3094 scalar_evolution_info = htab_create_ggc (100, hash_scev_info, eq_scev_info,
3095 del_scev_info);
3097 initialize_scalar_evolutions_analyzer ();
3099 FOR_EACH_LOOP (li, loop, 0)
3101 loop->nb_iterations = NULL_TREE;
3105 /* Return true if SCEV is initialized. */
3107 bool
3108 scev_initialized_p (void)
3110 return scalar_evolution_info != NULL;
3113 /* Cleans up the information cached by the scalar evolutions analysis
3114 in the hash table. */
3116 void
3117 scev_reset_htab (void)
3119 if (!scalar_evolution_info)
3120 return;
3122 htab_empty (scalar_evolution_info);
3125 /* Cleans up the information cached by the scalar evolutions analysis
3126 in the hash table and in the loop->nb_iterations. */
3128 void
3129 scev_reset (void)
3131 loop_iterator li;
3132 struct loop *loop;
3134 scev_reset_htab ();
3136 if (!current_loops)
3137 return;
3139 FOR_EACH_LOOP (li, loop, 0)
3141 loop->nb_iterations = NULL_TREE;
3145 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3146 respect to WRTO_LOOP and returns its base and step in IV if possible
3147 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3148 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3149 invariant in LOOP. Otherwise we require it to be an integer constant.
3151 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3152 because it is computed in signed arithmetics). Consequently, adding an
3153 induction variable
3155 for (i = IV->base; ; i += IV->step)
3157 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3158 false for the type of the induction variable, or you can prove that i does
3159 not wrap by some other argument. Otherwise, this might introduce undefined
3160 behavior, and
3162 for (i = iv->base; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3164 must be used instead. */
3166 bool
3167 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3168 affine_iv *iv, bool allow_nonconstant_step)
3170 tree type, ev;
3171 bool folded_casts;
3173 iv->base = NULL_TREE;
3174 iv->step = NULL_TREE;
3175 iv->no_overflow = false;
3177 type = TREE_TYPE (op);
3178 if (!POINTER_TYPE_P (type)
3179 && !INTEGRAL_TYPE_P (type))
3180 return false;
3182 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3183 &folded_casts);
3184 if (chrec_contains_undetermined (ev)
3185 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3186 return false;
3188 if (tree_does_not_contain_chrecs (ev))
3190 iv->base = ev;
3191 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3192 iv->no_overflow = true;
3193 return true;
3196 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
3197 || CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3198 return false;
3200 iv->step = CHREC_RIGHT (ev);
3201 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3202 || tree_contains_chrecs (iv->step, NULL))
3203 return false;
3205 iv->base = CHREC_LEFT (ev);
3206 if (tree_contains_chrecs (iv->base, NULL))
3207 return false;
3209 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
3211 return true;
3214 /* Finalize the scalar evolution analysis. */
3216 void
3217 scev_finalize (void)
3219 if (!scalar_evolution_info)
3220 return;
3221 htab_delete (scalar_evolution_info);
3222 scalar_evolution_info = NULL;
3225 /* Returns true if the expression EXPR is considered to be too expensive
3226 for scev_const_prop. */
3228 bool
3229 expression_expensive_p (tree expr)
3231 enum tree_code code;
3233 if (is_gimple_val (expr))
3234 return false;
3236 code = TREE_CODE (expr);
3237 if (code == TRUNC_DIV_EXPR
3238 || code == CEIL_DIV_EXPR
3239 || code == FLOOR_DIV_EXPR
3240 || code == ROUND_DIV_EXPR
3241 || code == TRUNC_MOD_EXPR
3242 || code == CEIL_MOD_EXPR
3243 || code == FLOOR_MOD_EXPR
3244 || code == ROUND_MOD_EXPR
3245 || code == EXACT_DIV_EXPR)
3247 /* Division by power of two is usually cheap, so we allow it.
3248 Forbid anything else. */
3249 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3250 return true;
3253 switch (TREE_CODE_CLASS (code))
3255 case tcc_binary:
3256 case tcc_comparison:
3257 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3258 return true;
3260 /* Fallthru. */
3261 case tcc_unary:
3262 return expression_expensive_p (TREE_OPERAND (expr, 0));
3264 default:
3265 return true;
3269 /* Replace ssa names for that scev can prove they are constant by the
3270 appropriate constants. Also perform final value replacement in loops,
3271 in case the replacement expressions are cheap.
3273 We only consider SSA names defined by phi nodes; rest is left to the
3274 ordinary constant propagation pass. */
3276 unsigned int
3277 scev_const_prop (void)
3279 basic_block bb;
3280 tree name, type, ev;
3281 gimple phi, ass;
3282 struct loop *loop, *ex_loop;
3283 bitmap ssa_names_to_remove = NULL;
3284 unsigned i;
3285 loop_iterator li;
3286 gimple_stmt_iterator psi;
3288 if (number_of_loops (cfun) <= 1)
3289 return 0;
3291 FOR_EACH_BB (bb)
3293 loop = bb->loop_father;
3295 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3297 phi = gsi_stmt (psi);
3298 name = PHI_RESULT (phi);
3300 if (virtual_operand_p (name))
3301 continue;
3303 type = TREE_TYPE (name);
3305 if (!POINTER_TYPE_P (type)
3306 && !INTEGRAL_TYPE_P (type))
3307 continue;
3309 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
3310 if (!is_gimple_min_invariant (ev)
3311 || !may_propagate_copy (name, ev))
3312 continue;
3314 /* Replace the uses of the name. */
3315 if (name != ev)
3316 replace_uses_by (name, ev);
3318 if (!ssa_names_to_remove)
3319 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3320 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3324 /* Remove the ssa names that were replaced by constants. We do not
3325 remove them directly in the previous cycle, since this
3326 invalidates scev cache. */
3327 if (ssa_names_to_remove)
3329 bitmap_iterator bi;
3331 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3333 gimple_stmt_iterator psi;
3334 name = ssa_name (i);
3335 phi = SSA_NAME_DEF_STMT (name);
3337 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3338 psi = gsi_for_stmt (phi);
3339 remove_phi_node (&psi, true);
3342 BITMAP_FREE (ssa_names_to_remove);
3343 scev_reset ();
3346 /* Now the regular final value replacement. */
3347 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
3349 edge exit;
3350 tree def, rslt, niter;
3351 gimple_stmt_iterator bsi;
3353 /* If we do not know exact number of iterations of the loop, we cannot
3354 replace the final value. */
3355 exit = single_exit (loop);
3356 if (!exit)
3357 continue;
3359 niter = number_of_latch_executions (loop);
3360 if (niter == chrec_dont_know)
3361 continue;
3363 /* Ensure that it is possible to insert new statements somewhere. */
3364 if (!single_pred_p (exit->dest))
3365 split_loop_exit_edge (exit);
3366 bsi = gsi_after_labels (exit->dest);
3368 ex_loop = superloop_at_depth (loop,
3369 loop_depth (exit->dest->loop_father) + 1);
3371 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3373 phi = gsi_stmt (psi);
3374 rslt = PHI_RESULT (phi);
3375 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3376 if (virtual_operand_p (def))
3378 gsi_next (&psi);
3379 continue;
3382 if (!POINTER_TYPE_P (TREE_TYPE (def))
3383 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3385 gsi_next (&psi);
3386 continue;
3389 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def, NULL);
3390 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3391 if (!tree_does_not_contain_chrecs (def)
3392 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3393 /* Moving the computation from the loop may prolong life range
3394 of some ssa names, which may cause problems if they appear
3395 on abnormal edges. */
3396 || contains_abnormal_ssa_name_p (def)
3397 /* Do not emit expensive expressions. The rationale is that
3398 when someone writes a code like
3400 while (n > 45) n -= 45;
3402 he probably knows that n is not large, and does not want it
3403 to be turned into n %= 45. */
3404 || expression_expensive_p (def))
3406 if (dump_file && (dump_flags & TDF_DETAILS))
3408 fprintf (dump_file, "not replacing:\n ");
3409 print_gimple_stmt (dump_file, phi, 0, 0);
3410 fprintf (dump_file, "\n");
3412 gsi_next (&psi);
3413 continue;
3416 /* Eliminate the PHI node and replace it by a computation outside
3417 the loop. */
3418 if (dump_file)
3420 fprintf (dump_file, "\nfinal value replacement:\n ");
3421 print_gimple_stmt (dump_file, phi, 0, 0);
3422 fprintf (dump_file, " with\n ");
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);
3431 if (dump_file)
3433 print_gimple_stmt (dump_file, ass, 0, 0);
3434 fprintf (dump_file, "\n");
3438 return 0;
3441 #include "gt-tree-scalar-evolution.h"