2004-07-28 Eric Christopher <echristo@redhat.com>
[official-gcc.git] / gcc / tree-scalar-evolution.c
blobd56b672274bf3f3cf008106ea9ac804f9fc0b959
1 /* Scalar evolution detector.
2 Copyright (C) 2003, 2004 Free Software Foundation, Inc.
3 Contributed by Sebastian Pop <s.pop@laposte.net>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING. If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA. */
22 /*
23 Description:
25 This pass analyzes the evolution of scalar variables in loop
26 structures. The algorithm is based on the SSA representation,
27 and on the loop hierarchy tree. This algorithm is not based on
28 the notion of versions of a variable, as it was the case for the
29 previous implementations of the scalar evolution algorithm, but
30 it assumes that each defined name is unique.
32 The notation used in this file is called "chains of recurrences",
33 and has been proposed by Eugene Zima, Robert Van Engelen, and
34 others for describing induction variables in programs. For example
35 "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
36 when entering in the loop_1 and has a step 2 in this loop, in other
37 words "for (b = 0; b < N; b+=2);". Note that the coefficients of
38 this chain of recurrence (or chrec [shrek]) can contain the name of
39 other variables, in which case they are called parametric chrecs.
40 For example, "b -> {a, +, 2}_1" means that the initial value of "b"
41 is the value of "a". In most of the cases these parametric chrecs
42 are fully instantiated before their use because symbolic names can
43 hide some difficult cases such as self-references described later
44 (see the Fibonacci example).
46 A short sketch of the algorithm is:
48 Given a scalar variable to be analyzed, follow the SSA edge to
49 its definition:
51 - When the definition is a MODIFY_EXPR: if the right hand side
52 (RHS) of the definition cannot be statically analyzed, the answer
53 of the analyzer is: "don't know".
54 Otherwise, for all the variables that are not yet analyzed in the
55 RHS, try to determine their evolution, and finally try to
56 evaluate the operation of the RHS that gives the evolution
57 function of the analyzed variable.
59 - When the definition is a condition-phi-node: determine the
60 evolution function for all the branches of the phi node, and
61 finally merge these evolutions (see chrec_merge).
63 - When the definition is a loop-phi-node: determine its initial
64 condition, that is the SSA edge defined in an outer loop, and
65 keep it symbolic. Then determine the SSA edges that are defined
66 in the body of the loop. Follow the inner edges until ending on
67 another loop-phi-node of the same analyzed loop. If the reached
68 loop-phi-node is not the starting loop-phi-node, then we keep
69 this definition under a symbolic form. If the reached
70 loop-phi-node is the same as the starting one, then we compute a
71 symbolic stride on the return path. The result is then the
72 symbolic chrec {initial_condition, +, symbolic_stride}_loop.
74 Examples:
76 Example 1: Illustration of the basic algorithm.
78 | a = 3
79 | loop_1
80 | b = phi (a, c)
81 | c = b + 1
82 | if (c > 10) exit_loop
83 | endloop
85 Suppose that we want to know the number of iterations of the
86 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
87 ask the scalar evolution analyzer two questions: what's the
88 scalar evolution (scev) of "c", and what's the scev of "10". For
89 "10" the answer is "10" since it is a scalar constant. For the
90 scalar variable "c", it follows the SSA edge to its definition,
91 "c = b + 1", and then asks again what's the scev of "b".
92 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
93 c)", where the initial condition is "a", and the inner loop edge
94 is "c". The initial condition is kept under a symbolic form (it
95 may be the case that the copy constant propagation has done its
96 work and we end with the constant "3" as one of the edges of the
97 loop-phi-node). The update edge is followed to the end of the
98 loop, and until reaching again the starting loop-phi-node: b -> c
99 -> b. At this point we have drawn a path from "b" to "b" from
100 which we compute the stride in the loop: in this example it is
101 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
102 that the scev for "b" is known, it is possible to compute the
103 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
104 determine the number of iterations in the loop_1, we have to
105 instantiate_parameters ({a + 1, +, 1}_1), that gives after some
106 more analysis the scev {4, +, 1}_1, or in other words, this is
107 the function "f (x) = x + 4", where x is the iteration count of
108 the loop_1. Now we have to solve the inequality "x + 4 > 10",
109 and take the smallest iteration number for which the loop is
110 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
111 there are 8 iterations. In terms of loop normalization, we have
112 created a variable that is implicitly defined, "x" or just "_1",
113 and all the other analyzed scalars of the loop are defined in
114 function of this variable:
116 a -> 3
117 b -> {3, +, 1}_1
118 c -> {4, +, 1}_1
120 or in terms of a C program:
122 | a = 3
123 | for (x = 0; x <= 7; x++)
125 | b = x + 3
126 | c = x + 4
129 Example 2: Illustration of the algorithm on nested loops.
131 | loop_1
132 | a = phi (1, b)
133 | c = a + 2
134 | loop_2 10 times
135 | b = phi (c, d)
136 | d = b + 3
137 | endloop
138 | endloop
140 For analyzing the scalar evolution of "a", the algorithm follows
141 the SSA edge into the loop's body: "a -> b". "b" is an inner
142 loop-phi-node, and its analysis as in Example 1, gives:
144 b -> {c, +, 3}_2
145 d -> {c + 3, +, 3}_2
147 Following the SSA edge for the initial condition, we end on "c = a
148 + 2", and then on the starting loop-phi-node "a". From this point,
149 the loop stride is computed: back on "c = a + 2" we get a "+2" in
150 the loop_1, then on the loop-phi-node "b" we compute the overall
151 effect of the inner loop that is "b = c + 30", and we get a "+30"
152 in the loop_1. That means that the overall stride in loop_1 is
153 equal to "+32", and the result is:
155 a -> {1, +, 32}_1
156 c -> {3, +, 32}_1
158 Example 3: Higher degree polynomials.
160 | loop_1
161 | a = phi (2, b)
162 | c = phi (5, d)
163 | b = a + 1
164 | d = c + a
165 | endloop
167 a -> {2, +, 1}_1
168 b -> {3, +, 1}_1
169 c -> {5, +, a}_1
170 d -> {5 + a, +, a}_1
172 instantiate_parameters ({5, +, a}_1) -> {5, +, 2, +, 1}_1
173 instantiate_parameters ({5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
175 Example 4: Lucas, Fibonacci, or mixers in general.
177 | loop_1
178 | a = phi (1, b)
179 | c = phi (3, d)
180 | b = c
181 | d = c + a
182 | endloop
184 a -> (1, c)_1
185 c -> {3, +, a}_1
187 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
188 following semantics: during the first iteration of the loop_1, the
189 variable contains the value 1, and then it contains the value "c".
190 Note that this syntax is close to the syntax of the loop-phi-node:
191 "a -> (1, c)_1" vs. "a = phi (1, c)".
193 The symbolic chrec representation contains all the semantics of the
194 original code. What is more difficult is to use this information.
196 Example 5: Flip-flops, or exchangers.
198 | loop_1
199 | a = phi (1, b)
200 | c = phi (3, d)
201 | b = c
202 | d = a
203 | endloop
205 a -> (1, c)_1
206 c -> (3, a)_1
208 Based on these symbolic chrecs, it is possible to refine this
209 information into the more precise PERIODIC_CHRECs:
211 a -> |1, 3|_1
212 c -> |3, 1|_1
214 This transformation is not yet implemented.
216 Further readings:
218 You can find a more detailed description of the algorithm in:
219 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
220 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
221 this is a preliminary report and some of the details of the
222 algorithm have changed. I'm working on a research report that
223 updates the description of the algorithms to reflect the design
224 choices used in this implementation.
226 A set of slides show a high level overview of the algorithm and run
227 an example through the scalar evolution analyzer:
228 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
230 The slides that I have presented at the GCC Summit'04 are available
231 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
234 #include "config.h"
235 #include "system.h"
236 #include "coretypes.h"
237 #include "tm.h"
238 #include "errors.h"
239 #include "ggc.h"
240 #include "tree.h"
242 /* These RTL headers are needed for basic-block.h. */
243 #include "rtl.h"
244 #include "basic-block.h"
245 #include "diagnostic.h"
246 #include "tree-flow.h"
247 #include "tree-dump.h"
248 #include "timevar.h"
249 #include "cfgloop.h"
250 #include "tree-chrec.h"
251 #include "tree-scalar-evolution.h"
252 #include "tree-pass.h"
253 #include "flags.h"
255 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
256 static tree resolve_mixers (struct loop *, tree);
258 /* The cached information about a ssa name VAR, claiming that inside LOOP,
259 the value of VAR can be expressed as CHREC. */
261 struct scev_info_str
263 tree var;
264 tree chrec;
267 /* Counters for the scev database. */
268 static unsigned nb_set_scev = 0;
269 static unsigned nb_get_scev = 0;
271 /* The following trees are unique elements. Thus the comparison of
272 another element to these elements should be done on the pointer to
273 these trees, and not on their value. */
275 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
276 tree chrec_not_analyzed_yet;
278 /* Reserved to the cases where the analyzer has detected an
279 undecidable property at compile time. */
280 tree chrec_dont_know;
282 /* When the analyzer has detected that a property will never
283 happen, then it qualifies it with chrec_known. */
284 tree chrec_known;
286 static bitmap already_instantiated;
288 static htab_t scalar_evolution_info;
291 /* Constructs a new SCEV_INFO_STR structure. */
293 static inline struct scev_info_str *
294 new_scev_info_str (tree var)
296 struct scev_info_str *res;
298 res = xmalloc (sizeof (struct scev_info_str));
299 res->var = var;
300 res->chrec = chrec_not_analyzed_yet;
302 return res;
305 /* Computes a hash function for database element ELT. */
307 static hashval_t
308 hash_scev_info (const void *elt)
310 return SSA_NAME_VERSION (((struct scev_info_str *) elt)->var);
313 /* Compares database elements E1 and E2. */
315 static int
316 eq_scev_info (const void *e1, const void *e2)
318 const struct scev_info_str *elt1 = e1;
319 const struct scev_info_str *elt2 = e2;
321 return elt1->var == elt2->var;
324 /* Deletes database element E. */
326 static void
327 del_scev_info (void *e)
329 free (e);
332 /* Get the index corresponding to VAR in the current LOOP. If
333 it's the first time we ask for this VAR, then we return
334 chrec_not_analysed_yet for this VAR and return its index. */
336 static tree *
337 find_var_scev_info (tree var)
339 struct scev_info_str *res;
340 struct scev_info_str tmp;
341 PTR *slot;
343 tmp.var = var;
344 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
346 if (!*slot)
347 *slot = new_scev_info_str (var);
348 res = *slot;
350 return &res->chrec;
353 /* Tries to express CHREC in wider type TYPE. */
355 tree
356 count_ev_in_wider_type (tree type, tree chrec)
358 tree base, step;
359 struct loop *loop;
361 if (!evolution_function_is_affine_p (chrec))
362 return fold_convert (type, chrec);
364 base = CHREC_LEFT (chrec);
365 step = CHREC_RIGHT (chrec);
366 loop = current_loops->parray[CHREC_VARIABLE (chrec)];
368 /* TODO -- if we knew the statement at that the conversion occurs,
369 we could pass it to can_count_iv_in_wider_type and get a better
370 result. */
371 step = can_count_iv_in_wider_type (loop, type, base, step, NULL_TREE);
372 if (!step)
373 return fold_convert (type, chrec);
374 base = chrec_convert (type, base);
376 return build_polynomial_chrec (CHREC_VARIABLE (chrec),
377 base, step);
380 /* Return true when CHREC contains symbolic names defined in
381 LOOP_NB. */
383 bool
384 chrec_contains_symbols_defined_in_loop (tree chrec, unsigned loop_nb)
386 if (chrec == NULL_TREE)
387 return false;
389 if (TREE_INVARIANT (chrec))
390 return false;
392 if (TREE_CODE (chrec) == VAR_DECL
393 || TREE_CODE (chrec) == PARM_DECL
394 || TREE_CODE (chrec) == FUNCTION_DECL
395 || TREE_CODE (chrec) == LABEL_DECL
396 || TREE_CODE (chrec) == RESULT_DECL
397 || TREE_CODE (chrec) == FIELD_DECL)
398 return true;
400 if (TREE_CODE (chrec) == SSA_NAME)
402 tree def = SSA_NAME_DEF_STMT (chrec);
403 struct loop *def_loop = loop_containing_stmt (def);
404 struct loop *loop = current_loops->parray[loop_nb];
406 if (def_loop == NULL)
407 return false;
409 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
410 return true;
412 return false;
415 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
417 case 3:
418 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, 2),
419 loop_nb))
420 return true;
422 case 2:
423 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, 1),
424 loop_nb))
425 return true;
427 case 1:
428 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, 0),
429 loop_nb))
430 return true;
432 default:
433 return false;
437 /* Return true when PHI is a loop-phi-node. */
439 static bool
440 loop_phi_node_p (tree phi)
442 /* The implementation of this function is based on the following
443 property: "all the loop-phi-nodes of a loop are contained in the
444 loop's header basic block". */
446 return loop_containing_stmt (phi)->header == bb_for_stmt (phi);
449 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
450 In general, in the case of multivariate evolutions we want to get
451 the evolution in different loops. LOOP specifies the level for
452 which to get the evolution.
454 Example:
456 | for (j = 0; j < 100; j++)
458 | for (k = 0; k < 100; k++)
460 | i = k + j; - Here the value of i is a function of j, k.
462 | ... = i - Here the value of i is a function of j.
464 | ... = i - Here the value of i is a scalar.
466 Example:
468 | i_0 = ...
469 | loop_1 10 times
470 | i_1 = phi (i_0, i_2)
471 | i_2 = i_1 + 2
472 | endloop
474 This loop has the same effect as:
475 LOOP_1 has the same effect as:
477 | i_1 = i_0 + 20
479 The overall effect of the loop, "i_0 + 20" in the previous example,
480 is obtained by passing in the parameters: LOOP = 1,
481 EVOLUTION_FN = {i_0, +, 2}_1.
484 static tree
485 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
487 bool val = false;
489 if (evolution_fn == chrec_dont_know)
490 return chrec_dont_know;
492 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
494 if (CHREC_VARIABLE (evolution_fn) >= (unsigned) loop->num)
496 struct loop *inner_loop =
497 current_loops->parray[CHREC_VARIABLE (evolution_fn)];
498 tree nb_iter = number_of_iterations_in_loop (inner_loop);
500 if (nb_iter == chrec_dont_know)
501 return chrec_dont_know;
502 else
504 tree res;
506 /* Number of iterations is off by one (the ssa name we
507 analyze must be defined before the exit). */
508 nb_iter = chrec_fold_minus (chrec_type (nb_iter),
509 nb_iter,
510 fold_convert (chrec_type (nb_iter),
511 integer_one_node));
513 /* evolution_fn is the evolution function in LOOP. Get
514 its value in the nb_iter-th iteration. */
515 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
517 /* Continue the computation until ending on a parent of LOOP. */
518 return compute_overall_effect_of_inner_loop (loop, res);
521 else
522 return evolution_fn;
525 /* If the evolution function is an invariant, there is nothing to do. */
526 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
527 return evolution_fn;
529 else
530 return chrec_dont_know;
533 /* Determine whether the CHREC is always positive/negative. If the expression
534 cannot be statically analyzed, return false, otherwise set the answer into
535 VALUE. */
537 bool
538 chrec_is_positive (tree chrec, bool *value)
540 bool value0, value1;
541 bool value2;
542 tree end_value;
543 tree nb_iter;
545 switch (TREE_CODE (chrec))
547 case POLYNOMIAL_CHREC:
548 if (!chrec_is_positive (CHREC_LEFT (chrec), &value0)
549 || !chrec_is_positive (CHREC_RIGHT (chrec), &value1))
550 return false;
552 /* FIXME -- overflows. */
553 if (value0 == value1)
555 *value = value0;
556 return true;
559 /* Otherwise the chrec is under the form: "{-197, +, 2}_1",
560 and the proof consists in showing that the sign never
561 changes during the execution of the loop, from 0 to
562 loop->nb_iterations. */
563 if (!evolution_function_is_affine_p (chrec))
564 return false;
566 nb_iter = number_of_iterations_in_loop
567 (current_loops->parray[CHREC_VARIABLE (chrec)]);
569 if (chrec_contains_undetermined (nb_iter))
570 return false;
572 nb_iter = chrec_fold_minus
573 (chrec_type (nb_iter), nb_iter,
574 fold_convert (chrec_type (nb_iter), integer_one_node));
576 #if 0
577 /* TODO -- If the test is after the exit, we may decrease the number of
578 iterations by one. */
579 if (after_exit)
580 nb_iter = chrec_fold_minus
581 (chrec_type (nb_iter), nb_iter,
582 fold_convert (chrec_type (nb_iter), integer_one_node));
583 #endif
585 end_value = chrec_apply (CHREC_VARIABLE (chrec), chrec, nb_iter);
587 if (!chrec_is_positive (end_value, &value2))
588 return false;
590 *value = value0;
591 return value0 == value1;
593 case INTEGER_CST:
594 *value = (tree_int_cst_sgn (chrec) == 1);
595 return true;
597 default:
598 return false;
602 /* Associate CHREC to SCALAR. */
604 static void
605 set_scalar_evolution (tree scalar, tree chrec)
607 tree *scalar_info;
609 if (TREE_CODE (scalar) != SSA_NAME)
610 return;
612 scalar_info = find_var_scev_info (scalar);
614 if (dump_file)
616 if (dump_flags & TDF_DETAILS)
618 fprintf (dump_file, "(set_scalar_evolution \n");
619 fprintf (dump_file, " (scalar = ");
620 print_generic_expr (dump_file, scalar, 0);
621 fprintf (dump_file, ")\n (scalar_evolution = ");
622 print_generic_expr (dump_file, chrec, 0);
623 fprintf (dump_file, "))\n");
625 if (dump_flags & TDF_STATS)
626 nb_set_scev++;
629 *scalar_info = chrec;
632 /* Retrieve the chrec associated to SCALAR in the LOOP. */
634 static tree
635 get_scalar_evolution (tree scalar)
637 tree res;
639 if (dump_file)
641 if (dump_flags & TDF_DETAILS)
643 fprintf (dump_file, "(get_scalar_evolution \n");
644 fprintf (dump_file, " (scalar = ");
645 print_generic_expr (dump_file, scalar, 0);
646 fprintf (dump_file, ")\n");
648 if (dump_flags & TDF_STATS)
649 nb_get_scev++;
652 switch (TREE_CODE (scalar))
654 case SSA_NAME:
655 res = *find_var_scev_info (scalar);
656 break;
658 case REAL_CST:
659 case INTEGER_CST:
660 res = scalar;
661 break;
663 default:
664 res = chrec_not_analyzed_yet;
665 break;
668 if (dump_file && (dump_flags & TDF_DETAILS))
670 fprintf (dump_file, " (scalar_evolution = ");
671 print_generic_expr (dump_file, res, 0);
672 fprintf (dump_file, "))\n");
675 return res;
678 /* Helper function for add_to_evolution. Returns the evolution
679 function for an assignment of the form "a = b + c", where "a" and
680 "b" are on the strongly connected component. CHREC_BEFORE is the
681 information that we already have collected up to this point.
682 TO_ADD is the evolution of "c".
684 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
685 evolution the expression TO_ADD, otherwise construct an evolution
686 part for this loop. */
688 static tree
689 add_to_evolution_1 (unsigned loop_nb,
690 tree chrec_before,
691 tree to_add)
693 switch (TREE_CODE (chrec_before))
695 case POLYNOMIAL_CHREC:
696 if (CHREC_VARIABLE (chrec_before) <= loop_nb)
698 unsigned var;
699 tree left, right;
700 tree type = chrec_type (chrec_before);
702 /* When there is no evolution part in this loop, build it. */
703 if (CHREC_VARIABLE (chrec_before) < loop_nb)
705 var = loop_nb;
706 left = chrec_before;
707 right = fold_convert (type, integer_zero_node);
709 else
711 var = CHREC_VARIABLE (chrec_before);
712 left = CHREC_LEFT (chrec_before);
713 right = CHREC_RIGHT (chrec_before);
716 return build_polynomial_chrec
717 (var, left, chrec_fold_plus (type, right, to_add));
719 else
720 /* Search the evolution in LOOP_NB. */
721 return build_polynomial_chrec
722 (CHREC_VARIABLE (chrec_before),
723 add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before), to_add),
724 CHREC_RIGHT (chrec_before));
726 default:
727 /* These nodes do not depend on a loop. */
728 if (chrec_before == chrec_dont_know)
729 return chrec_dont_know;
730 return build_polynomial_chrec (loop_nb, chrec_before, to_add);
734 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
735 of LOOP_NB.
737 Description (provided for completeness, for those who read code in
738 a plane, and for my poor 62 bytes brain that would have forgotten
739 all this in the next two or three months):
741 The algorithm of translation of programs from the SSA representation
742 into the chrecs syntax is based on a pattern matching. After having
743 reconstructed the overall tree expression for a loop, there are only
744 two cases that can arise:
746 1. a = loop-phi (init, a + expr)
747 2. a = loop-phi (init, expr)
749 where EXPR is either a scalar constant with respect to the analyzed
750 loop (this is a degree 0 polynomial), or an expression containing
751 other loop-phi definitions (these are higher degree polynomials).
753 Examples:
756 | init = ...
757 | loop_1
758 | a = phi (init, a + 5)
759 | endloop
762 | inita = ...
763 | initb = ...
764 | loop_1
765 | a = phi (inita, 2 * b + 3)
766 | b = phi (initb, b + 1)
767 | endloop
769 For the first case, the semantics of the SSA representation is:
771 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
773 that is, there is a loop index "x" that determines the scalar value
774 of the variable during the loop execution. During the first
775 iteration, the value is that of the initial condition INIT, while
776 during the subsequent iterations, it is the sum of the initial
777 condition with the sum of all the values of EXPR from the initial
778 iteration to the before last considered iteration.
780 For the second case, the semantics of the SSA program is:
782 | a (x) = init, if x = 0;
783 | expr (x - 1), otherwise.
785 The second case corresponds to the PEELED_CHREC, whose syntax is
786 close to the syntax of a loop-phi-node:
788 | phi (init, expr) vs. (init, expr)_x
790 The proof of the translation algorithm for the first case is a
791 proof by structural induction based on the degree of EXPR.
793 Degree 0:
794 When EXPR is a constant with respect to the analyzed loop, or in
795 other words when EXPR is a polynomial of degree 0, the evolution of
796 the variable A in the loop is an affine function with an initial
797 condition INIT, and a step EXPR. In order to show this, we start
798 from the semantics of the SSA representation:
800 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
802 and since "expr (j)" is a constant with respect to "j",
804 f (x) = init + x * expr
806 Finally, based on the semantics of the pure sum chrecs, by
807 identification we get the corresponding chrecs syntax:
809 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
810 f (x) -> {init, +, expr}_x
812 Higher degree:
813 Suppose that EXPR is a polynomial of degree N with respect to the
814 analyzed loop_x for which we have already determined that it is
815 written under the chrecs syntax:
817 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
819 We start from the semantics of the SSA program:
821 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
823 | f (x) = init + \sum_{j = 0}^{x - 1}
824 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
826 | f (x) = init + \sum_{j = 0}^{x - 1}
827 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
829 | f (x) = init + \sum_{k = 0}^{n - 1}
830 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
832 | f (x) = init + \sum_{k = 0}^{n - 1}
833 | (b_k * \binom{x}{k + 1})
835 | f (x) = init + b_0 * \binom{x}{1} + ...
836 | + b_{n-1} * \binom{x}{n}
838 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
839 | + b_{n-1} * \binom{x}{n}
842 And finally from the definition of the chrecs syntax, we identify:
843 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
845 This shows the mechanism that stands behind the add_to_evolution
846 function. An important point is that the use of symbolic
847 parameters avoids the need of an analysis schedule.
849 Example:
851 | inita = ...
852 | initb = ...
853 | loop_1
854 | a = phi (inita, a + 2 + b)
855 | b = phi (initb, b + 1)
856 | endloop
858 When analyzing "a", the algorithm keeps "b" symbolically:
860 | a -> {inita, +, 2 + b}_1
862 Then, after instantiation, the analyzer ends on the evolution:
864 | a -> {inita, +, 2 + initb, +, 1}_1
868 static tree
869 add_to_evolution (unsigned loop_nb,
870 tree chrec_before,
871 enum tree_code code,
872 tree to_add)
874 tree type = chrec_type (to_add);
875 tree res = NULL_TREE;
877 if (to_add == NULL_TREE)
878 return chrec_before;
880 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
881 instantiated at this point. */
882 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
883 /* This should not happen. */
884 return chrec_dont_know;
886 if (dump_file && (dump_flags & TDF_DETAILS))
888 fprintf (dump_file, "(add_to_evolution \n");
889 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
890 fprintf (dump_file, " (chrec_before = ");
891 print_generic_expr (dump_file, chrec_before, 0);
892 fprintf (dump_file, ")\n (to_add = ");
893 print_generic_expr (dump_file, to_add, 0);
894 fprintf (dump_file, ")\n");
897 if (code == MINUS_EXPR)
898 to_add = chrec_fold_multiply (type, to_add,
899 fold_convert (type, integer_minus_one_node));
901 res = add_to_evolution_1 (loop_nb, chrec_before, to_add);
903 if (dump_file && (dump_flags & TDF_DETAILS))
905 fprintf (dump_file, " (res = ");
906 print_generic_expr (dump_file, res, 0);
907 fprintf (dump_file, "))\n");
910 return res;
913 /* Helper function. */
915 static inline tree
916 set_nb_iterations_in_loop (struct loop *loop,
917 tree res)
919 res = chrec_fold_plus (chrec_type (res), res, integer_one_node);
920 /* FIXME HWI: However we want to store one iteration less than the
921 count of the loop in order to be compatible with the other
922 nb_iter computations in loop-iv. This also allows the
923 representation of nb_iters that are equal to MAX_INT. */
924 if ((TREE_CODE (res) == INTEGER_CST && TREE_INT_CST_LOW (res) == 0)
925 || TREE_OVERFLOW (res))
926 res = chrec_dont_know;
928 if (dump_file && (dump_flags & TDF_DETAILS))
930 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
931 print_generic_expr (dump_file, res, 0);
932 fprintf (dump_file, "))\n");
935 loop->nb_iterations = res;
936 return res;
941 /* This section selects the loops that will be good candidates for the
942 scalar evolution analysis. For the moment, greedily select all the
943 loop nests we could analyze. */
945 /* Return true when it is possible to analyze the condition expression
946 EXPR. */
948 static bool
949 analyzable_condition (tree expr)
951 tree condition;
953 if (TREE_CODE (expr) != COND_EXPR)
954 return false;
956 condition = TREE_OPERAND (expr, 0);
958 switch (TREE_CODE (condition))
960 case SSA_NAME:
961 /* Volatile expressions are not analyzable. */
962 if (TREE_THIS_VOLATILE (SSA_NAME_VAR (condition)))
963 return false;
964 return true;
966 case LT_EXPR:
967 case LE_EXPR:
968 case GT_EXPR:
969 case GE_EXPR:
970 case EQ_EXPR:
971 case NE_EXPR:
973 tree opnd0, opnd1;
975 opnd0 = TREE_OPERAND (condition, 0);
976 opnd1 = TREE_OPERAND (condition, 1);
978 if (TREE_CODE (opnd0) == SSA_NAME
979 && TREE_THIS_VOLATILE (SSA_NAME_VAR (opnd0)))
980 return false;
982 if (TREE_CODE (opnd1) == SSA_NAME
983 && TREE_THIS_VOLATILE (SSA_NAME_VAR (opnd1)))
984 return false;
986 return true;
989 default:
990 return false;
993 return false;
996 /* For a loop with a single exit edge, return the COND_EXPR that
997 guards the exit edge. If the expression is too difficult to
998 analyze, then give up. */
1000 tree
1001 get_loop_exit_condition (struct loop *loop)
1003 tree res = NULL_TREE;
1005 if (dump_file && (dump_flags & TDF_DETAILS))
1006 fprintf (dump_file, "(get_loop_exit_condition \n ");
1008 if (loop->exit_edges)
1010 edge exit_edge;
1011 tree expr;
1013 exit_edge = loop->exit_edges[0];
1014 expr = last_stmt (exit_edge->src);
1016 if (analyzable_condition (expr))
1017 res = expr;
1020 if (dump_file && (dump_flags & TDF_DETAILS))
1022 print_generic_expr (dump_file, res, 0);
1023 fprintf (dump_file, ")\n");
1026 return res;
1029 /* Recursively determine and enqueue the exit conditions for a loop. */
1031 static void
1032 get_exit_conditions_rec (struct loop *loop,
1033 varray_type *exit_conditions)
1035 if (!loop)
1036 return;
1038 /* Recurse on the inner loops, then on the next (sibling) loops. */
1039 get_exit_conditions_rec (loop->inner, exit_conditions);
1040 get_exit_conditions_rec (loop->next, exit_conditions);
1042 flow_loop_scan (loop, LOOP_EXIT_EDGES);
1043 if (loop->num_exits == 1)
1045 tree loop_condition = get_loop_exit_condition (loop);
1047 if (loop_condition)
1048 VARRAY_PUSH_TREE (*exit_conditions, loop_condition);
1052 /* Select the candidate loop nests for the analysis. This function
1053 initializes the EXIT_CONDITIONS array. */
1055 static void
1056 select_loops_exit_conditions (struct loops *loops,
1057 varray_type *exit_conditions)
1059 struct loop *function_body = loops->parray[0];
1061 get_exit_conditions_rec (function_body->inner, exit_conditions);
1065 /* Depth first search algorithm. */
1067 static bool follow_ssa_edge (struct loop *loop, tree, tree, tree *);
1069 /* Follow the ssa edge into the right hand side RHS of an assignment.
1070 Return true if the strongly connected component has been found. */
1072 static bool
1073 follow_ssa_edge_in_rhs (struct loop *loop,
1074 tree rhs,
1075 tree halting_phi,
1076 tree *evolution_of_loop)
1078 bool res = false;
1079 tree rhs0, rhs1;
1080 tree type_rhs = TREE_TYPE (rhs);
1082 /* The RHS is one of the following cases:
1083 - an SSA_NAME,
1084 - an INTEGER_CST,
1085 - a PLUS_EXPR,
1086 - a MINUS_EXPR,
1087 - other cases are not yet handled.
1089 switch (TREE_CODE (rhs))
1091 case NOP_EXPR:
1092 /* This assignment is under the form "a_1 = (cast) rhs. */
1093 res = follow_ssa_edge_in_rhs (loop, TREE_OPERAND (rhs, 0), halting_phi,
1094 evolution_of_loop);
1095 *evolution_of_loop = chrec_convert (TREE_TYPE (rhs), *evolution_of_loop);
1096 break;
1098 case INTEGER_CST:
1099 /* This assignment is under the form "a_1 = 7". */
1100 res = false;
1101 break;
1103 case SSA_NAME:
1104 /* This assignment is under the form: "a_1 = b_2". */
1105 res = follow_ssa_edge
1106 (loop, SSA_NAME_DEF_STMT (rhs), halting_phi, evolution_of_loop);
1107 break;
1109 case PLUS_EXPR:
1110 /* This case is under the form "rhs0 + rhs1". */
1111 rhs0 = TREE_OPERAND (rhs, 0);
1112 rhs1 = TREE_OPERAND (rhs, 1);
1113 STRIP_TYPE_NOPS (rhs0);
1114 STRIP_TYPE_NOPS (rhs1);
1116 if (TREE_CODE (rhs0) == SSA_NAME)
1118 if (TREE_CODE (rhs1) == SSA_NAME)
1120 /* Match an assignment under the form:
1121 "a = b + c". */
1122 res = follow_ssa_edge
1123 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1124 evolution_of_loop);
1126 if (res)
1127 *evolution_of_loop = add_to_evolution
1128 (loop->num,
1129 chrec_convert (type_rhs, *evolution_of_loop),
1130 PLUS_EXPR, rhs1);
1132 else
1134 res = follow_ssa_edge
1135 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1136 evolution_of_loop);
1138 if (res)
1139 *evolution_of_loop = add_to_evolution
1140 (loop->num,
1141 chrec_convert (type_rhs, *evolution_of_loop),
1142 PLUS_EXPR, rhs0);
1146 else
1148 /* Match an assignment under the form:
1149 "a = b + ...". */
1150 res = follow_ssa_edge
1151 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1152 evolution_of_loop);
1153 if (res)
1154 *evolution_of_loop = add_to_evolution
1155 (loop->num, chrec_convert (type_rhs, *evolution_of_loop),
1156 PLUS_EXPR, rhs1);
1160 else if (TREE_CODE (rhs1) == SSA_NAME)
1162 /* Match an assignment under the form:
1163 "a = ... + c". */
1164 res = follow_ssa_edge
1165 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1166 evolution_of_loop);
1167 if (res)
1168 *evolution_of_loop = add_to_evolution
1169 (loop->num, chrec_convert (type_rhs, *evolution_of_loop),
1170 PLUS_EXPR, rhs0);
1173 else
1174 /* Otherwise, match an assignment under the form:
1175 "a = ... + ...". */
1176 /* And there is nothing to do. */
1177 res = false;
1179 break;
1181 case MINUS_EXPR:
1182 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1183 rhs0 = TREE_OPERAND (rhs, 0);
1184 rhs1 = TREE_OPERAND (rhs, 1);
1185 STRIP_TYPE_NOPS (rhs0);
1186 STRIP_TYPE_NOPS (rhs1);
1188 if (TREE_CODE (rhs0) == SSA_NAME)
1190 if (TREE_CODE (rhs1) == SSA_NAME)
1192 /* Match an assignment under the form:
1193 "a = b - c". */
1194 res = follow_ssa_edge
1195 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1196 evolution_of_loop);
1198 if (res)
1199 *evolution_of_loop = add_to_evolution
1200 (loop->num, chrec_convert (type_rhs, *evolution_of_loop),
1201 MINUS_EXPR, rhs1);
1203 else
1205 res = follow_ssa_edge
1206 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1207 evolution_of_loop);
1209 if (res)
1210 *evolution_of_loop = add_to_evolution
1211 (loop->num,
1212 chrec_fold_multiply (type_rhs,
1213 *evolution_of_loop,
1214 fold_convert (type_rhs,
1215 integer_minus_one_node)),
1216 PLUS_EXPR, rhs0);
1220 else
1222 /* Match an assignment under the form:
1223 "a = b - ...". */
1224 res = follow_ssa_edge
1225 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1226 evolution_of_loop);
1227 if (res)
1228 *evolution_of_loop = add_to_evolution
1229 (loop->num, chrec_convert (type_rhs, *evolution_of_loop),
1230 MINUS_EXPR, rhs1);
1234 else if (TREE_CODE (rhs1) == SSA_NAME)
1236 /* Match an assignment under the form:
1237 "a = ... - c". */
1238 res = follow_ssa_edge
1239 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1240 evolution_of_loop);
1241 if (res)
1242 *evolution_of_loop = add_to_evolution
1243 (loop->num,
1244 chrec_fold_multiply (type_rhs,
1245 *evolution_of_loop,
1246 fold_convert (type_rhs, integer_minus_one_node)),
1247 PLUS_EXPR, rhs0);
1250 else
1251 /* Otherwise, match an assignment under the form:
1252 "a = ... - ...". */
1253 /* And there is nothing to do. */
1254 res = false;
1256 break;
1258 case MULT_EXPR:
1259 /* This case is under the form "opnd0 = rhs0 * rhs1". */
1260 rhs0 = TREE_OPERAND (rhs, 0);
1261 rhs1 = TREE_OPERAND (rhs, 1);
1262 STRIP_TYPE_NOPS (rhs0);
1263 STRIP_TYPE_NOPS (rhs1);
1265 if (TREE_CODE (rhs0) == SSA_NAME)
1267 if (TREE_CODE (rhs1) == SSA_NAME)
1269 /* Match an assignment under the form:
1270 "a = b * c". */
1271 res = follow_ssa_edge
1272 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1273 evolution_of_loop);
1275 if (res)
1276 *evolution_of_loop = chrec_dont_know;
1278 else
1280 res = follow_ssa_edge
1281 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1282 evolution_of_loop);
1284 if (res)
1285 *evolution_of_loop = chrec_dont_know;
1289 else
1291 /* Match an assignment under the form:
1292 "a = b * ...". */
1293 res = follow_ssa_edge
1294 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1295 evolution_of_loop);
1296 if (res)
1297 *evolution_of_loop = chrec_dont_know;
1301 else if (TREE_CODE (rhs1) == SSA_NAME)
1303 /* Match an assignment under the form:
1304 "a = ... * c". */
1305 res = follow_ssa_edge
1306 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1307 evolution_of_loop);
1308 if (res)
1309 *evolution_of_loop = chrec_dont_know;
1312 else
1313 /* Otherwise, match an assignment under the form:
1314 "a = ... * ...". */
1315 /* And there is nothing to do. */
1316 res = false;
1318 break;
1320 default:
1321 res = false;
1322 break;
1325 return res;
1328 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1330 static bool
1331 backedge_phi_arg_p (tree phi, int i)
1333 edge e = PHI_ARG_EDGE (phi, i);
1335 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1336 about updating it anywhere, and this should work as well most of the
1337 time. */
1338 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1339 return true;
1341 return false;
1344 /* Helper function for one branch of the condition-phi-node. Return
1345 true if the strongly connected component has been found following
1346 this path. */
1348 static inline bool
1349 follow_ssa_edge_in_condition_phi_branch (int i,
1350 struct loop *loop,
1351 tree condition_phi,
1352 tree halting_phi,
1353 tree *evolution_of_branch,
1354 tree init_cond)
1356 tree branch = PHI_ARG_DEF (condition_phi, i);
1357 *evolution_of_branch = chrec_dont_know;
1359 /* Do not follow back edges (they must belong to an irreducible loop, which
1360 we really do not want to worry about). */
1361 if (backedge_phi_arg_p (condition_phi, i))
1362 return false;
1364 if (TREE_CODE (branch) == SSA_NAME)
1366 *evolution_of_branch = init_cond;
1367 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1368 evolution_of_branch);
1371 /* This case occurs when one of the condition branches sets
1372 the variable to a constant: ie. a phi-node like
1373 "a_2 = PHI <a_7(5), 2(6)>;".
1375 FIXME: This case have to be refined correctly:
1376 in some cases it is possible to say something better than
1377 chrec_dont_know, for example using a wrap-around notation. */
1378 return false;
1381 /* This function merges the branches of a condition-phi-node in a
1382 loop. */
1384 static bool
1385 follow_ssa_edge_in_condition_phi (struct loop *loop,
1386 tree condition_phi,
1387 tree halting_phi,
1388 tree *evolution_of_loop)
1390 int i;
1391 tree init = *evolution_of_loop;
1392 tree evolution_of_branch;
1394 if (!follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1395 halting_phi,
1396 &evolution_of_branch,
1397 init))
1398 return false;
1399 *evolution_of_loop = evolution_of_branch;
1401 for (i = 1; i < PHI_NUM_ARGS (condition_phi); i++)
1403 if (!follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1404 halting_phi,
1405 &evolution_of_branch,
1406 init))
1407 return false;
1409 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1410 evolution_of_branch);
1413 return true;
1416 /* Follow an SSA edge in an inner loop. It computes the overall
1417 effect of the loop, and following the symbolic initial conditions,
1418 it follows the edges in the parent loop. The inner loop is
1419 considered as a single statement. */
1421 static bool
1422 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1423 tree loop_phi_node,
1424 tree halting_phi,
1425 tree *evolution_of_loop)
1427 struct loop *loop = loop_containing_stmt (loop_phi_node);
1428 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1430 /* Sometimes, the inner loop is too difficult to analyze, and the
1431 result of the analysis is a symbolic parameter. */
1432 if (ev == PHI_RESULT (loop_phi_node))
1434 bool res = false;
1435 int i;
1437 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1439 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1440 basic_block bb;
1442 /* Follow the edges that exit the inner loop. */
1443 bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1444 if (!flow_bb_inside_loop_p (loop, bb))
1445 res = res || follow_ssa_edge_in_rhs (outer_loop, arg, halting_phi,
1446 evolution_of_loop);
1449 /* If the path crosses this loop-phi, give up. */
1450 if (res == true)
1451 *evolution_of_loop = chrec_dont_know;
1453 return res;
1456 /* Otherwise, compute the overall effect of the inner loop. */
1457 ev = compute_overall_effect_of_inner_loop (loop, ev);
1458 return follow_ssa_edge_in_rhs (outer_loop, ev, halting_phi,
1459 evolution_of_loop);
1462 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1463 path that is analyzed on the return walk. */
1465 static bool
1466 follow_ssa_edge (struct loop *loop,
1467 tree def,
1468 tree halting_phi,
1469 tree *evolution_of_loop)
1471 struct loop *def_loop;
1473 if (TREE_CODE (def) == NOP_EXPR)
1474 return false;
1476 def_loop = loop_containing_stmt (def);
1478 switch (TREE_CODE (def))
1480 case PHI_NODE:
1481 if (!loop_phi_node_p (def))
1482 /* DEF is a condition-phi-node. Follow the branches, and
1483 record their evolutions. Finally, merge the collected
1484 information and set the approximation to the main
1485 variable. */
1486 return follow_ssa_edge_in_condition_phi
1487 (loop, def, halting_phi, evolution_of_loop);
1489 /* When the analyzed phi is the halting_phi, the
1490 depth-first search is over: we have found a path from
1491 the halting_phi to itself in the loop. */
1492 if (def == halting_phi)
1493 return true;
1495 /* Otherwise, the evolution of the HALTING_PHI depends
1496 on the evolution of another loop-phi-node, ie. the
1497 evolution function is a higher degree polynomial. */
1498 if (def_loop == loop)
1499 return false;
1501 /* Inner loop. */
1502 if (flow_loop_nested_p (loop, def_loop))
1503 return follow_ssa_edge_inner_loop_phi
1504 (loop, def, halting_phi, evolution_of_loop);
1506 /* Outer loop. */
1507 return false;
1509 case MODIFY_EXPR:
1510 return follow_ssa_edge_in_rhs (loop,
1511 TREE_OPERAND (def, 1),
1512 halting_phi,
1513 evolution_of_loop);
1515 default:
1516 /* At this level of abstraction, the program is just a set
1517 of MODIFY_EXPRs and PHI_NODEs. In principle there is no
1518 other node to be handled. */
1519 return false;
1525 /* Given a LOOP_PHI_NODE, this function determines the evolution
1526 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1528 static tree
1529 analyze_evolution_in_loop (tree loop_phi_node,
1530 tree init_cond)
1532 int i;
1533 tree evolution_function = chrec_not_analyzed_yet;
1534 struct loop *loop = loop_containing_stmt (loop_phi_node);
1535 basic_block bb;
1537 if (dump_file && (dump_flags & TDF_DETAILS))
1539 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1540 fprintf (dump_file, " (loop_phi_node = ");
1541 print_generic_expr (dump_file, loop_phi_node, 0);
1542 fprintf (dump_file, ")\n");
1545 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1547 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1548 tree ssa_chain, ev_fn;
1549 bool res;
1551 /* Select the edges that enter the loop body. */
1552 bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1553 if (!flow_bb_inside_loop_p (loop, bb))
1554 continue;
1556 if (TREE_CODE (arg) == SSA_NAME)
1558 ssa_chain = SSA_NAME_DEF_STMT (arg);
1560 /* Pass in the initial condition to the follow edge function. */
1561 ev_fn = init_cond;
1562 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn);
1564 else
1565 res = false;
1567 /* When it is impossible to go back on the same
1568 loop_phi_node by following the ssa edges, the
1569 evolution is represented by a peeled chrec, ie. the
1570 first iteration, EV_FN has the value INIT_COND, then
1571 all the other iterations it has the value of ARG.
1572 For the moment, PEELED_CHREC nodes are not built. */
1573 if (!res)
1574 ev_fn = chrec_dont_know;
1576 /* When there are multiple back edges of the loop (which in fact never
1577 happens currently, but nevertheless), merge their evolutions. */
1578 evolution_function = chrec_merge (evolution_function, ev_fn);
1581 if (dump_file && (dump_flags & TDF_DETAILS))
1583 fprintf (dump_file, " (evolution_function = ");
1584 print_generic_expr (dump_file, evolution_function, 0);
1585 fprintf (dump_file, "))\n");
1588 return evolution_function;
1591 /* Given a loop-phi-node, return the initial conditions of the
1592 variable on entry of the loop. When the CCP has propagated
1593 constants into the loop-phi-node, the initial condition is
1594 instantiated, otherwise the initial condition is kept symbolic.
1595 This analyzer does not analyze the evolution outside the current
1596 loop, and leaves this task to the on-demand tree reconstructor. */
1598 static tree
1599 analyze_initial_condition (tree loop_phi_node)
1601 int i;
1602 tree init_cond = chrec_not_analyzed_yet;
1603 struct loop *loop = bb_for_stmt (loop_phi_node)->loop_father;
1605 if (dump_file && (dump_flags & TDF_DETAILS))
1607 fprintf (dump_file, "(analyze_initial_condition \n");
1608 fprintf (dump_file, " (loop_phi_node = \n");
1609 print_generic_expr (dump_file, loop_phi_node, 0);
1610 fprintf (dump_file, ")\n");
1613 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1615 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1616 basic_block bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1618 /* When the branch is oriented to the loop's body, it does
1619 not contribute to the initial condition. */
1620 if (flow_bb_inside_loop_p (loop, bb))
1621 continue;
1623 if (init_cond == chrec_not_analyzed_yet)
1625 init_cond = branch;
1626 continue;
1629 if (TREE_CODE (branch) == SSA_NAME)
1631 init_cond = chrec_dont_know;
1632 break;
1635 init_cond = chrec_merge (init_cond, branch);
1638 /* Ooops -- a loop without an entry??? */
1639 if (init_cond == chrec_not_analyzed_yet)
1640 init_cond = chrec_dont_know;
1642 if (dump_file && (dump_flags & TDF_DETAILS))
1644 fprintf (dump_file, " (init_cond = ");
1645 print_generic_expr (dump_file, init_cond, 0);
1646 fprintf (dump_file, "))\n");
1649 return init_cond;
1652 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1654 static tree
1655 interpret_loop_phi (struct loop *loop, tree loop_phi_node)
1657 tree res;
1658 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1659 tree init_cond;
1661 if (phi_loop != loop)
1663 struct loop *subloop;
1664 tree evolution_fn = analyze_scalar_evolution
1665 (phi_loop, PHI_RESULT (loop_phi_node));
1667 /* Dive one level deeper. */
1668 subloop = superloop_at_depth (phi_loop, loop->depth + 1);
1670 /* Interpret the subloop. */
1671 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1672 return res;
1675 /* Otherwise really interpret the loop phi. */
1676 init_cond = analyze_initial_condition (loop_phi_node);
1677 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1679 return res;
1682 /* This function merges the branches of a condition-phi-node,
1683 contained in the outermost loop, and whose arguments are already
1684 analyzed. */
1686 static tree
1687 interpret_condition_phi (struct loop *loop, tree condition_phi)
1689 int i;
1690 tree res = chrec_not_analyzed_yet;
1692 for (i = 0; i < PHI_NUM_ARGS (condition_phi); i++)
1694 tree branch_chrec;
1696 if (backedge_phi_arg_p (condition_phi, i))
1698 res = chrec_dont_know;
1699 break;
1702 branch_chrec = analyze_scalar_evolution
1703 (loop, PHI_ARG_DEF (condition_phi, i));
1705 res = chrec_merge (res, branch_chrec);
1708 return res;
1711 /* Interpret the right hand side of a modify_expr OPND1. If we didn't
1712 analyzed this node before, follow the definitions until ending
1713 either on an analyzed modify_expr, or on a loop-phi-node. On the
1714 return path, this function propagates evolutions (ala constant copy
1715 propagation). OPND1 is not a GIMPLE expression because we could
1716 analyze the effect of an inner loop: see interpret_loop_phi. */
1718 static tree
1719 interpret_rhs_modify_expr (struct loop *loop,
1720 tree opnd1, tree type)
1722 tree res, opnd10, opnd11, chrec10, chrec11;
1724 if (is_gimple_min_invariant (opnd1))
1725 return chrec_convert (type, opnd1);
1727 switch (TREE_CODE (opnd1))
1729 case PLUS_EXPR:
1730 opnd10 = TREE_OPERAND (opnd1, 0);
1731 opnd11 = TREE_OPERAND (opnd1, 1);
1732 chrec10 = analyze_scalar_evolution (loop, opnd10);
1733 chrec11 = analyze_scalar_evolution (loop, opnd11);
1734 chrec10 = chrec_convert (type, chrec10);
1735 chrec11 = chrec_convert (type, chrec11);
1736 res = chrec_fold_plus (type, chrec10, chrec11);
1737 break;
1739 case MINUS_EXPR:
1740 opnd10 = TREE_OPERAND (opnd1, 0);
1741 opnd11 = TREE_OPERAND (opnd1, 1);
1742 chrec10 = analyze_scalar_evolution (loop, opnd10);
1743 chrec11 = analyze_scalar_evolution (loop, opnd11);
1744 chrec10 = chrec_convert (type, chrec10);
1745 chrec11 = chrec_convert (type, chrec11);
1746 res = chrec_fold_minus (type, chrec10, chrec11);
1747 break;
1749 case NEGATE_EXPR:
1750 opnd10 = TREE_OPERAND (opnd1, 0);
1751 chrec10 = analyze_scalar_evolution (loop, opnd10);
1752 chrec10 = chrec_convert (type, chrec10);
1753 res = chrec_fold_minus (type, fold_convert (type, integer_zero_node),
1754 chrec10);
1755 break;
1757 case MULT_EXPR:
1758 opnd10 = TREE_OPERAND (opnd1, 0);
1759 opnd11 = TREE_OPERAND (opnd1, 1);
1760 chrec10 = analyze_scalar_evolution (loop, opnd10);
1761 chrec11 = analyze_scalar_evolution (loop, opnd11);
1762 chrec10 = chrec_convert (type, chrec10);
1763 chrec11 = chrec_convert (type, chrec11);
1764 res = chrec_fold_multiply (type, chrec10, chrec11);
1765 break;
1767 case SSA_NAME:
1768 res = chrec_convert (type, analyze_scalar_evolution (loop, opnd1));
1769 break;
1771 case NOP_EXPR:
1772 case CONVERT_EXPR:
1773 opnd10 = TREE_OPERAND (opnd1, 0);
1774 chrec10 = analyze_scalar_evolution (loop, opnd10);
1775 res = chrec_convert (type, chrec10);
1776 break;
1778 default:
1779 res = chrec_dont_know;
1780 break;
1783 return res;
1788 /* This section contains all the entry points:
1789 - number_of_iterations_in_loop,
1790 - analyze_scalar_evolution,
1791 - instantiate_parameters.
1794 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1795 common ancestor of DEF_LOOP and USE_LOOP. */
1797 static tree
1798 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1799 struct loop *def_loop,
1800 tree ev)
1802 tree res;
1803 if (def_loop == wrto_loop)
1804 return ev;
1806 def_loop = superloop_at_depth (def_loop, wrto_loop->depth + 1);
1807 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1809 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1812 /* Helper recursive function. */
1814 static tree
1815 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1817 tree def, type = TREE_TYPE (var);
1818 basic_block bb;
1819 struct loop *def_loop;
1821 if (loop == NULL)
1822 return chrec_dont_know;
1824 if (TREE_CODE (var) != SSA_NAME)
1825 return interpret_rhs_modify_expr (loop, var, type);
1827 def = SSA_NAME_DEF_STMT (var);
1828 bb = bb_for_stmt (def);
1829 def_loop = bb ? bb->loop_father : NULL;
1831 if (bb == NULL
1832 || !flow_bb_inside_loop_p (loop, bb))
1834 /* Keep the symbolic form. */
1835 res = var;
1836 goto set_and_end;
1839 if (res != chrec_not_analyzed_yet)
1841 if (loop != bb->loop_father)
1842 res = compute_scalar_evolution_in_loop
1843 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1845 goto set_and_end;
1848 if (loop != def_loop)
1850 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1851 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1853 goto set_and_end;
1856 switch (TREE_CODE (def))
1858 case MODIFY_EXPR:
1859 res = interpret_rhs_modify_expr (loop, TREE_OPERAND (def, 1), type);
1860 break;
1862 case PHI_NODE:
1863 if (loop_phi_node_p (def))
1864 res = interpret_loop_phi (loop, def);
1865 else
1866 res = interpret_condition_phi (loop, def);
1867 break;
1869 default:
1870 res = chrec_dont_know;
1871 break;
1874 set_and_end:
1876 /* Keep the symbolic form. */
1877 if (res == chrec_dont_know)
1878 res = var;
1880 if (loop == def_loop)
1881 set_scalar_evolution (var, res);
1883 return res;
1886 /* Entry point for the scalar evolution analyzer.
1887 Analyzes and returns the scalar evolution of the ssa_name VAR.
1888 LOOP_NB is the identifier number of the loop in which the variable
1889 is used.
1891 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
1892 pointer to the statement that uses this variable, in order to
1893 determine the evolution function of the variable, use the following
1894 calls:
1896 unsigned loop_nb = loop_containing_stmt (stmt)->num;
1897 tree chrec_with_symbols = analyze_scalar_evolution (loop_nb, var);
1898 tree chrec_instantiated = instantiate_parameters
1899 (loop_nb, chrec_with_symbols);
1902 tree
1903 analyze_scalar_evolution (struct loop *loop, tree var)
1905 tree res;
1907 if (dump_file && (dump_flags & TDF_DETAILS))
1909 fprintf (dump_file, "(analyze_scalar_evolution \n");
1910 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
1911 fprintf (dump_file, " (scalar = ");
1912 print_generic_expr (dump_file, var, 0);
1913 fprintf (dump_file, ")\n");
1916 res = analyze_scalar_evolution_1 (loop, var, get_scalar_evolution (var));
1918 if (TREE_CODE (var) == SSA_NAME && res == chrec_dont_know)
1919 res = var;
1921 if (dump_file && (dump_flags & TDF_DETAILS))
1922 fprintf (dump_file, ")\n");
1924 return res;
1927 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
1928 WRTO_LOOP (which should be a superloop of both USE_LOOP and definition
1929 of VERSION). */
1931 static tree
1932 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
1933 tree version)
1935 bool val = false;
1936 tree ev = version;
1938 while (1)
1940 ev = analyze_scalar_evolution (use_loop, ev);
1941 ev = resolve_mixers (use_loop, ev);
1943 if (use_loop == wrto_loop)
1944 return ev;
1946 /* If the value of the use changes in the inner loop, we cannot express
1947 its value in the outer loop (we might try to return interval chrec,
1948 but we do not have a user for it anyway) */
1949 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
1950 || !val)
1951 return chrec_dont_know;
1953 use_loop = use_loop->outer;
1957 /* Analyze all the parameters of the chrec that were left under a symbolic form,
1958 with respect to LOOP. CHREC is the chrec to instantiate. If
1959 ALLOW_SUPERLOOP_CHRECS is true, replacing loop invariants with
1960 outer loop chrecs is done. */
1962 static tree
1963 instantiate_parameters_1 (struct loop *loop, tree chrec,
1964 bool allow_superloop_chrecs)
1966 tree res, op0, op1, op2;
1967 basic_block def_bb;
1968 struct loop *def_loop;
1970 if (chrec == NULL_TREE
1971 || automatically_generated_chrec_p (chrec))
1972 return chrec;
1974 if (is_gimple_min_invariant (chrec))
1975 return chrec;
1977 switch (TREE_CODE (chrec))
1979 case SSA_NAME:
1980 def_bb = bb_for_stmt (SSA_NAME_DEF_STMT (chrec));
1982 /* A parameter (or loop invariant and we do not want to include
1983 evolutions in outer loops), nothing to do. */
1984 if (!def_bb
1985 || (!allow_superloop_chrecs
1986 && !flow_bb_inside_loop_p (loop, def_bb)))
1987 return chrec;
1989 /* Don't instantiate the SSA_NAME if it is in a mixer
1990 structure. This is used for avoiding the instantiation of
1991 recursively defined functions, such as:
1993 | a_2 -> {0, +, 1, +, a_2}_1 */
1995 if (bitmap_bit_p (already_instantiated, SSA_NAME_VERSION (chrec)))
1997 if (!flow_bb_inside_loop_p (loop, def_bb))
1999 /* We may keep the loop invariant in symbolic form. */
2000 return chrec;
2002 else
2004 /* Something with unknown behavior in LOOP. */
2005 return chrec_dont_know;
2009 def_loop = find_common_loop (loop, def_bb->loop_father);
2011 /* If the analysis yields a parametric chrec, instantiate the
2012 result again. Avoid the cyclic instantiation in mixers. */
2013 bitmap_set_bit (already_instantiated, SSA_NAME_VERSION (chrec));
2014 res = analyze_scalar_evolution (def_loop, chrec);
2015 res = instantiate_parameters_1 (loop, res, allow_superloop_chrecs);
2016 bitmap_clear_bit (already_instantiated, SSA_NAME_VERSION (chrec));
2017 return res;
2019 case POLYNOMIAL_CHREC:
2020 op0 = instantiate_parameters_1 (loop, CHREC_LEFT (chrec),
2021 allow_superloop_chrecs);
2022 op1 = instantiate_parameters_1 (loop, CHREC_RIGHT (chrec),
2023 allow_superloop_chrecs);
2024 return build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2026 case PLUS_EXPR:
2027 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2028 allow_superloop_chrecs);
2029 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2030 allow_superloop_chrecs);
2031 return chrec_fold_plus (TREE_TYPE (chrec), op0, op1);
2033 case MINUS_EXPR:
2034 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2035 allow_superloop_chrecs);
2036 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2037 allow_superloop_chrecs);
2038 return chrec_fold_minus (TREE_TYPE (chrec), op0, op1);
2040 case MULT_EXPR:
2041 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2042 allow_superloop_chrecs);
2043 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2044 allow_superloop_chrecs);
2045 return chrec_fold_multiply (TREE_TYPE (chrec), op0, op1);
2047 case NOP_EXPR:
2048 case CONVERT_EXPR:
2049 case NON_LVALUE_EXPR:
2050 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2051 allow_superloop_chrecs);
2052 if (op0 == chrec_dont_know)
2053 return chrec_dont_know;
2055 return chrec_convert (TREE_TYPE (chrec), op0);
2057 case SCEV_NOT_KNOWN:
2058 return chrec_dont_know;
2060 case SCEV_KNOWN:
2061 return chrec_known;
2063 default:
2064 break;
2067 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2069 case 3:
2070 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2071 allow_superloop_chrecs);
2072 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2073 allow_superloop_chrecs);
2074 op2 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 2),
2075 allow_superloop_chrecs);
2076 if (op0 == chrec_dont_know
2077 || op1 == chrec_dont_know
2078 || op2 == chrec_dont_know)
2079 return chrec_dont_know;
2080 return fold (build (TREE_CODE (chrec),
2081 TREE_TYPE (chrec), op0, op1, op2));
2083 case 2:
2084 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2085 allow_superloop_chrecs);
2086 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2087 allow_superloop_chrecs);
2088 if (op0 == chrec_dont_know
2089 || op1 == chrec_dont_know)
2090 return chrec_dont_know;
2091 return fold (build (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1));
2093 case 1:
2094 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2095 allow_superloop_chrecs);
2096 if (op0 == chrec_dont_know)
2097 return chrec_dont_know;
2098 return fold (build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0));
2100 case 0:
2101 return chrec;
2103 default:
2104 break;
2107 /* Too complicated to handle. */
2108 return chrec_dont_know;
2111 /* Analyze all the parameters of the chrec that were left under a
2112 symbolic form. LOOP is the loop in which symbolic names have to
2113 be analyzed and instantiated. */
2115 tree
2116 instantiate_parameters (struct loop *loop,
2117 tree chrec)
2119 tree res;
2121 if (dump_file && (dump_flags & TDF_DETAILS))
2123 fprintf (dump_file, "(instantiate_parameters \n");
2124 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
2125 fprintf (dump_file, " (chrec = ");
2126 print_generic_expr (dump_file, chrec, 0);
2127 fprintf (dump_file, ")\n");
2130 res = instantiate_parameters_1 (loop, chrec, true);
2132 if (dump_file && (dump_flags & TDF_DETAILS))
2134 fprintf (dump_file, " (res = ");
2135 print_generic_expr (dump_file, res, 0);
2136 fprintf (dump_file, "))\n");
2139 return res;
2142 /* Similar to instantiate_parameters, but does not introduce the
2143 evolutions in outer loops for LOOP invariants in CHREC. */
2145 static tree
2146 resolve_mixers (struct loop *loop, tree chrec)
2148 return instantiate_parameters_1 (loop, chrec, false);
2151 /* Entry point for the analysis of the number of iterations pass.
2152 This function tries to safely approximate the number of iterations
2153 the loop will run. When this property is not decidable at compile
2154 time, the result is chrec_dont_know. Otherwise the result is
2155 a scalar or a symbolic parameter.
2157 Example of analysis: suppose that the loop has an exit condition:
2159 "if (b > 49) goto end_loop;"
2161 and that in a previous analysis we have determined that the
2162 variable 'b' has an evolution function:
2164 "EF = {23, +, 5}_2".
2166 When we evaluate the function at the point 5, i.e. the value of the
2167 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2168 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2169 the loop body has been executed 6 times. */
2171 tree
2172 number_of_iterations_in_loop (struct loop *loop)
2174 tree res, type;
2175 edge exit;
2176 struct tree_niter_desc niter_desc;
2178 /* Determine whether the number_of_iterations_in_loop has already
2179 been computed. */
2180 res = loop->nb_iterations;
2181 if (res)
2182 return res;
2183 res = chrec_dont_know;
2185 if (dump_file && (dump_flags & TDF_DETAILS))
2186 fprintf (dump_file, "(number_of_iterations_in_loop\n");
2188 if (!loop->exit_edges)
2189 goto end;
2190 exit = loop->exit_edges[0];
2192 if (!number_of_iterations_exit (loop, exit, &niter_desc))
2193 goto end;
2195 type = TREE_TYPE (niter_desc.niter);
2196 if (integer_nonzerop (niter_desc.may_be_zero))
2197 res = fold_convert (type, integer_zero_node);
2198 else if (integer_zerop (niter_desc.may_be_zero))
2199 res = niter_desc.niter;
2200 else
2201 res = chrec_dont_know;
2203 end:
2204 return set_nb_iterations_in_loop (loop, res);
2207 /* One of the drivers for testing the scalar evolutions analysis.
2208 This function computes the number of iterations for all the loops
2209 from the EXIT_CONDITIONS array. */
2211 static void
2212 number_of_iterations_for_all_loops (varray_type exit_conditions)
2214 unsigned int i;
2215 unsigned nb_chrec_dont_know_loops = 0;
2216 unsigned nb_static_loops = 0;
2218 for (i = 0; i < VARRAY_ACTIVE_SIZE (exit_conditions); i++)
2220 tree res = number_of_iterations_in_loop
2221 (loop_containing_stmt (VARRAY_TREE (exit_conditions, i)));
2222 if (chrec_contains_undetermined (res))
2223 nb_chrec_dont_know_loops++;
2224 else
2225 nb_static_loops++;
2228 if (dump_file)
2230 fprintf (dump_file, "\n(\n");
2231 fprintf (dump_file, "-----------------------------------------\n");
2232 fprintf (dump_file, "%d\tnb_chrec_dont_know_loops\n", nb_chrec_dont_know_loops);
2233 fprintf (dump_file, "%d\tnb_static_loops\n", nb_static_loops);
2234 fprintf (dump_file, "%d\tnb_total_loops\n", current_loops->num);
2235 fprintf (dump_file, "-----------------------------------------\n");
2236 fprintf (dump_file, ")\n\n");
2238 print_loop_ir (dump_file);
2244 /* Counters for the stats. */
2246 struct chrec_stats
2248 unsigned nb_chrecs;
2249 unsigned nb_affine;
2250 unsigned nb_affine_multivar;
2251 unsigned nb_higher_poly;
2252 unsigned nb_chrec_dont_know;
2253 unsigned nb_undetermined;
2256 /* Reset the counters. */
2258 static inline void
2259 reset_chrecs_counters (struct chrec_stats *stats)
2261 stats->nb_chrecs = 0;
2262 stats->nb_affine = 0;
2263 stats->nb_affine_multivar = 0;
2264 stats->nb_higher_poly = 0;
2265 stats->nb_chrec_dont_know = 0;
2266 stats->nb_undetermined = 0;
2269 /* Dump the contents of a CHREC_STATS structure. */
2271 static void
2272 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2274 fprintf (file, "\n(\n");
2275 fprintf (file, "-----------------------------------------\n");
2276 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2277 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2278 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2279 stats->nb_higher_poly);
2280 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2281 fprintf (file, "-----------------------------------------\n");
2282 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2283 fprintf (file, "%d\twith undetermined coefficients\n",
2284 stats->nb_undetermined);
2285 fprintf (file, "-----------------------------------------\n");
2286 fprintf (file, "%d\tchrecs in the scev database\n",
2287 (int) htab_elements (scalar_evolution_info));
2288 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2289 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2290 fprintf (file, "-----------------------------------------\n");
2291 fprintf (file, ")\n\n");
2294 /* Gather statistics about CHREC. */
2296 static void
2297 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2299 if (dump_file && (dump_flags & TDF_STATS))
2301 fprintf (dump_file, "(classify_chrec ");
2302 print_generic_expr (dump_file, chrec, 0);
2303 fprintf (dump_file, "\n");
2306 stats->nb_chrecs++;
2308 if (chrec == NULL_TREE)
2310 stats->nb_undetermined++;
2311 return;
2314 switch (TREE_CODE (chrec))
2316 case POLYNOMIAL_CHREC:
2317 if (evolution_function_is_affine_p (chrec))
2319 if (dump_file && (dump_flags & TDF_STATS))
2320 fprintf (dump_file, " affine_univariate\n");
2321 stats->nb_affine++;
2323 else if (evolution_function_is_affine_multivariate_p (chrec))
2325 if (dump_file && (dump_flags & TDF_STATS))
2326 fprintf (dump_file, " affine_multivariate\n");
2327 stats->nb_affine_multivar++;
2329 else
2331 if (dump_file && (dump_flags & TDF_STATS))
2332 fprintf (dump_file, " higher_degree_polynomial\n");
2333 stats->nb_higher_poly++;
2336 break;
2338 default:
2339 break;
2342 if (chrec_contains_undetermined (chrec))
2344 if (dump_file && (dump_flags & TDF_STATS))
2345 fprintf (dump_file, " undetermined\n");
2346 stats->nb_undetermined++;
2349 if (dump_file && (dump_flags & TDF_STATS))
2350 fprintf (dump_file, ")\n");
2353 /* One of the drivers for testing the scalar evolutions analysis.
2354 This function analyzes the scalar evolution of all the scalars
2355 defined as loop phi nodes in one of the loops from the
2356 EXIT_CONDITIONS array.
2358 TODO Optimization: A loop is in canonical form if it contains only
2359 a single scalar loop phi node. All the other scalars that have an
2360 evolution in the loop are rewritten in function of this single
2361 index. This allows the parallelization of the loop. */
2363 static void
2364 analyze_scalar_evolution_for_all_loop_phi_nodes (varray_type exit_conditions)
2366 unsigned int i;
2367 struct chrec_stats stats;
2369 reset_chrecs_counters (&stats);
2371 for (i = 0; i < VARRAY_ACTIVE_SIZE (exit_conditions); i++)
2373 struct loop *loop;
2374 basic_block bb;
2375 tree phi, chrec;
2377 loop = loop_containing_stmt (VARRAY_TREE (exit_conditions, i));
2378 bb = loop->header;
2380 for (phi = phi_nodes (bb); phi; phi = TREE_CHAIN (phi))
2381 if (is_gimple_reg (PHI_RESULT (phi)))
2383 chrec = instantiate_parameters
2384 (loop,
2385 analyze_scalar_evolution (loop, PHI_RESULT (phi)));
2387 if (dump_file && (dump_flags & TDF_STATS))
2388 gather_chrec_stats (chrec, &stats);
2392 if (dump_file && (dump_flags & TDF_STATS))
2393 dump_chrecs_stats (dump_file, &stats);
2396 /* Callback for htab_traverse, gathers information on chrecs in the
2397 hashtable. */
2399 static int
2400 gather_stats_on_scev_database_1 (void **slot, void *stats)
2402 struct scev_info_str *entry = *slot;
2404 gather_chrec_stats (entry->chrec, stats);
2406 return 1;
2409 /* Classify the chrecs of the whole database. */
2411 void
2412 gather_stats_on_scev_database (void)
2414 struct chrec_stats stats;
2416 if (!dump_file)
2417 return;
2419 reset_chrecs_counters (&stats);
2421 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
2422 &stats);
2424 dump_chrecs_stats (dump_file, &stats);
2429 /* Initializer. */
2431 static void
2432 initialize_scalar_evolutions_analyzer (void)
2434 /* The elements below are unique. */
2435 if (chrec_dont_know == NULL_TREE)
2437 chrec_not_analyzed_yet = NULL_TREE;
2438 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
2439 chrec_known = make_node (SCEV_KNOWN);
2440 TREE_TYPE (chrec_dont_know) = NULL_TREE;
2441 TREE_TYPE (chrec_known) = NULL_TREE;
2445 /* Initialize the analysis of scalar evolutions for LOOPS. */
2447 void
2448 scev_initialize (struct loops *loops)
2450 unsigned i;
2451 current_loops = loops;
2453 scalar_evolution_info = htab_create (100, hash_scev_info,
2454 eq_scev_info, del_scev_info);
2455 already_instantiated = BITMAP_XMALLOC ();
2457 initialize_scalar_evolutions_analyzer ();
2459 for (i = 1; i < loops->num; i++)
2460 if (loops->parray[i])
2462 flow_loop_scan (loops->parray[i], LOOP_EXIT_EDGES);
2463 loops->parray[i]->nb_iterations = NULL_TREE;
2467 /* Cleans up the information cached by the scalar evolutions analysis. */
2469 void
2470 scev_reset (void)
2472 unsigned i;
2473 struct loop *loop;
2475 if (!scalar_evolution_info || !current_loops)
2476 return;
2478 htab_empty (scalar_evolution_info);
2479 for (i = 1; i < current_loops->num; i++)
2481 loop = current_loops->parray[i];
2482 if (loop)
2483 loop->nb_iterations = NULL_TREE;
2487 /* Checks whether OP behaves as a simple affine iv of LOOP in STMT and returns
2488 its BASE and STEP if possible. */
2490 bool
2491 simple_iv (struct loop *loop, tree stmt, tree op, tree *base, tree *step)
2493 basic_block bb = bb_for_stmt (stmt);
2494 tree type, ev;
2496 *base = NULL_TREE;
2497 *step = NULL_TREE;
2499 type = TREE_TYPE (op);
2500 if (TREE_CODE (type) != INTEGER_TYPE
2501 && TREE_CODE (type) != POINTER_TYPE)
2502 return false;
2504 ev = analyze_scalar_evolution_in_loop (loop, bb->loop_father, op);
2505 if (chrec_contains_undetermined (ev))
2506 return false;
2508 if (tree_does_not_contain_chrecs (ev)
2509 && !chrec_contains_symbols_defined_in_loop (ev, loop->num))
2511 *base = ev;
2512 return true;
2515 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
2516 || CHREC_VARIABLE (ev) != (unsigned) loop->num)
2517 return false;
2519 *step = CHREC_RIGHT (ev);
2520 if (TREE_CODE (*step) != INTEGER_CST)
2521 return false;
2522 *base = CHREC_LEFT (ev);
2523 if (tree_contains_chrecs (*base)
2524 || chrec_contains_symbols_defined_in_loop (*base, loop->num))
2525 return false;
2527 return true;
2530 /* Runs the analysis of scalar evolutions. */
2532 void
2533 scev_analysis (void)
2535 varray_type exit_conditions;
2537 VARRAY_GENERIC_PTR_INIT (exit_conditions, 37, "exit_conditions");
2538 select_loops_exit_conditions (current_loops, &exit_conditions);
2540 if (dump_file && (dump_flags & TDF_STATS))
2541 analyze_scalar_evolution_for_all_loop_phi_nodes (exit_conditions);
2543 number_of_iterations_for_all_loops (exit_conditions);
2544 VARRAY_CLEAR (exit_conditions);
2547 /* Finalize the scalar evolution analysis. */
2549 void
2550 scev_finalize (void)
2552 htab_delete (scalar_evolution_info);
2553 BITMAP_XFREE (already_instantiated);