intrinsic.h (gfc_check_selected_real_kind, [...]): Update prototypes.
[gcc.git] / gcc / tree-scalar-evolution.c
1 /* Scalar evolution detector.
2 Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
3 Free Software Foundation, Inc.
4 Contributed by Sebastian Pop <s.pop@laposte.net>
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
21
22 /*
23 Description:
24
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.
31
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).
45
46 A short sketch of the algorithm is:
47
48 Given a scalar variable to be analyzed, follow the SSA edge to
49 its definition:
50
51 - When the definition is a GIMPLE_ASSIGN: if the right hand side
52 (RHS) of the definition cannot be statically analyzed, the answer
53 of the analyzer is: "don't know".
54 Otherwise, for all the variables that are not yet analyzed in the
55 RHS, try to determine their evolution, and finally try to
56 evaluate the operation of the RHS that gives the evolution
57 function of the analyzed variable.
58
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).
62
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.
73
74 Examples:
75
76 Example 1: Illustration of the basic algorithm.
77
78 | a = 3
79 | loop_1
80 | b = phi (a, c)
81 | c = b + 1
82 | if (c > 10) exit_loop
83 | endloop
84
85 Suppose that we want to know the number of iterations of the
86 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
87 ask the scalar evolution analyzer two questions: what's the
88 scalar evolution (scev) of "c", and what's the scev of "10". For
89 "10" the answer is "10" since it is a scalar constant. For the
90 scalar variable "c", it follows the SSA edge to its definition,
91 "c = b + 1", and then asks again what's the scev of "b".
92 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
93 c)", where the initial condition is "a", and the inner loop edge
94 is "c". The initial condition is kept under a symbolic form (it
95 may be the case that the copy constant propagation has done its
96 work and we end with the constant "3" as one of the edges of the
97 loop-phi-node). The update edge is followed to the end of the
98 loop, and until reaching again the starting loop-phi-node: b -> c
99 -> b. At this point we have drawn a path from "b" to "b" from
100 which we compute the stride in the loop: in this example it is
101 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
102 that the scev for "b" is known, it is possible to compute the
103 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
104 determine the number of iterations in the loop_1, we have to
105 instantiate_parameters (loop_1, {a + 1, +, 1}_1), that gives after some
106 more analysis the scev {4, +, 1}_1, or in other words, this is
107 the function "f (x) = x + 4", where x is the iteration count of
108 the loop_1. Now we have to solve the inequality "x + 4 > 10",
109 and take the smallest iteration number for which the loop is
110 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
111 there are 8 iterations. In terms of loop normalization, we have
112 created a variable that is implicitly defined, "x" or just "_1",
113 and all the other analyzed scalars of the loop are defined in
114 function of this variable:
115
116 a -> 3
117 b -> {3, +, 1}_1
118 c -> {4, +, 1}_1
119
120 or in terms of a C program:
121
122 | a = 3
123 | for (x = 0; x <= 7; x++)
124 | {
125 | b = x + 3
126 | c = x + 4
127 | }
128
129 Example 2a: Illustration of the algorithm on nested loops.
130
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
139
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:
143
144 b -> {c, +, 3}_2
145 d -> {c + 3, +, 3}_2
146
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:
154
155 a -> {1, +, 32}_1
156 c -> {3, +, 32}_1
157
158 Example 2b: Multivariate chains of recurrences.
159
160 | loop_1
161 | k = phi (0, k + 1)
162 | loop_2 4 times
163 | j = phi (0, j + 1)
164 | loop_3 4 times
165 | i = phi (0, i + 1)
166 | A[j + k] = ...
167 | endloop
168 | endloop
169 | endloop
170
171 Analyzing the access function of array A with
172 instantiate_parameters (loop_1, "j + k"), we obtain the
173 instantiation and the analysis of the scalar variables "j" and "k"
174 in loop_1. This leads to the scalar evolution {4, +, 1}_1: the end
175 value of loop_2 for "j" is 4, and the evolution of "k" in loop_1 is
176 {0, +, 1}_1. To obtain the evolution function in loop_3 and
177 instantiate the scalar variables up to loop_1, one has to use:
178 instantiate_scev (block_before_loop (loop_1), loop_3, "j + k").
179 The result of this call is {{0, +, 1}_1, +, 1}_2.
180
181 Example 3: Higher degree polynomials.
182
183 | loop_1
184 | a = phi (2, b)
185 | c = phi (5, d)
186 | b = a + 1
187 | d = c + a
188 | endloop
189
190 a -> {2, +, 1}_1
191 b -> {3, +, 1}_1
192 c -> {5, +, a}_1
193 d -> {5 + a, +, a}_1
194
195 instantiate_parameters (loop_1, {5, +, a}_1) -> {5, +, 2, +, 1}_1
196 instantiate_parameters (loop_1, {5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
197
198 Example 4: Lucas, Fibonacci, or mixers in general.
199
200 | loop_1
201 | a = phi (1, b)
202 | c = phi (3, d)
203 | b = c
204 | d = c + a
205 | endloop
206
207 a -> (1, c)_1
208 c -> {3, +, a}_1
209
210 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
211 following semantics: during the first iteration of the loop_1, the
212 variable contains the value 1, and then it contains the value "c".
213 Note that this syntax is close to the syntax of the loop-phi-node:
214 "a -> (1, c)_1" vs. "a = phi (1, c)".
215
216 The symbolic chrec representation contains all the semantics of the
217 original code. What is more difficult is to use this information.
218
219 Example 5: Flip-flops, or exchangers.
220
221 | loop_1
222 | a = phi (1, b)
223 | c = phi (3, d)
224 | b = c
225 | d = a
226 | endloop
227
228 a -> (1, c)_1
229 c -> (3, a)_1
230
231 Based on these symbolic chrecs, it is possible to refine this
232 information into the more precise PERIODIC_CHRECs:
233
234 a -> |1, 3|_1
235 c -> |3, 1|_1
236
237 This transformation is not yet implemented.
238
239 Further readings:
240
241 You can find a more detailed description of the algorithm in:
242 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
243 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
244 this is a preliminary report and some of the details of the
245 algorithm have changed. I'm working on a research report that
246 updates the description of the algorithms to reflect the design
247 choices used in this implementation.
248
249 A set of slides show a high level overview of the algorithm and run
250 an example through the scalar evolution analyzer:
251 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
252
253 The slides that I have presented at the GCC Summit'04 are available
254 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
255 */
256
257 #include "config.h"
258 #include "system.h"
259 #include "coretypes.h"
260 #include "tm.h"
261 #include "ggc.h"
262 #include "tree.h"
263 #include "basic-block.h"
264 #include "tree-pretty-print.h"
265 #include "gimple-pretty-print.h"
266 #include "tree-flow.h"
267 #include "tree-dump.h"
268 #include "timevar.h"
269 #include "cfgloop.h"
270 #include "tree-chrec.h"
271 #include "tree-scalar-evolution.h"
272 #include "tree-pass.h"
273 #include "flags.h"
274 #include "params.h"
275
276 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
277
278 /* The cached information about an SSA name VAR, claiming that below
279 basic block INSTANTIATED_BELOW, the value of VAR can be expressed
280 as CHREC. */
281
282 struct GTY(()) scev_info_str {
283 basic_block instantiated_below;
284 tree var;
285 tree chrec;
286 };
287
288 /* Counters for the scev database. */
289 static unsigned nb_set_scev = 0;
290 static unsigned nb_get_scev = 0;
291
292 /* The following trees are unique elements. Thus the comparison of
293 another element to these elements should be done on the pointer to
294 these trees, and not on their value. */
295
296 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
297 tree chrec_not_analyzed_yet;
298
299 /* Reserved to the cases where the analyzer has detected an
300 undecidable property at compile time. */
301 tree chrec_dont_know;
302
303 /* When the analyzer has detected that a property will never
304 happen, then it qualifies it with chrec_known. */
305 tree chrec_known;
306
307 static GTY ((param_is (struct scev_info_str))) htab_t scalar_evolution_info;
308
309 \f
310 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
311
312 static inline struct scev_info_str *
313 new_scev_info_str (basic_block instantiated_below, tree var)
314 {
315 struct scev_info_str *res;
316
317 res = ggc_alloc_scev_info_str ();
318 res->var = var;
319 res->chrec = chrec_not_analyzed_yet;
320 res->instantiated_below = instantiated_below;
321
322 return res;
323 }
324
325 /* Computes a hash function for database element ELT. */
326
327 static hashval_t
328 hash_scev_info (const void *elt)
329 {
330 return SSA_NAME_VERSION (((const struct scev_info_str *) elt)->var);
331 }
332
333 /* Compares database elements E1 and E2. */
334
335 static int
336 eq_scev_info (const void *e1, const void *e2)
337 {
338 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
339 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
340
341 return (elt1->var == elt2->var
342 && elt1->instantiated_below == elt2->instantiated_below);
343 }
344
345 /* Deletes database element E. */
346
347 static void
348 del_scev_info (void *e)
349 {
350 ggc_free (e);
351 }
352
353 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
354 A first query on VAR returns chrec_not_analyzed_yet. */
355
356 static tree *
357 find_var_scev_info (basic_block instantiated_below, tree var)
358 {
359 struct scev_info_str *res;
360 struct scev_info_str tmp;
361 PTR *slot;
362
363 tmp.var = var;
364 tmp.instantiated_below = instantiated_below;
365 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
366
367 if (!*slot)
368 *slot = new_scev_info_str (instantiated_below, var);
369 res = (struct scev_info_str *) *slot;
370
371 return &res->chrec;
372 }
373
374 /* Return true when CHREC contains symbolic names defined in
375 LOOP_NB. */
376
377 bool
378 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
379 {
380 int i, n;
381
382 if (chrec == NULL_TREE)
383 return false;
384
385 if (is_gimple_min_invariant (chrec))
386 return false;
387
388 if (TREE_CODE (chrec) == VAR_DECL
389 || TREE_CODE (chrec) == PARM_DECL
390 || TREE_CODE (chrec) == FUNCTION_DECL
391 || TREE_CODE (chrec) == LABEL_DECL
392 || TREE_CODE (chrec) == RESULT_DECL
393 || TREE_CODE (chrec) == FIELD_DECL)
394 return true;
395
396 if (TREE_CODE (chrec) == SSA_NAME)
397 {
398 gimple def = SSA_NAME_DEF_STMT (chrec);
399 struct loop *def_loop = loop_containing_stmt (def);
400 struct loop *loop = get_loop (loop_nb);
401
402 if (def_loop == NULL)
403 return false;
404
405 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
406 return true;
407
408 return false;
409 }
410
411 n = TREE_OPERAND_LENGTH (chrec);
412 for (i = 0; i < n; i++)
413 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
414 loop_nb))
415 return true;
416 return false;
417 }
418
419 /* Return true when PHI is a loop-phi-node. */
420
421 static bool
422 loop_phi_node_p (gimple phi)
423 {
424 /* The implementation of this function is based on the following
425 property: "all the loop-phi-nodes of a loop are contained in the
426 loop's header basic block". */
427
428 return loop_containing_stmt (phi)->header == gimple_bb (phi);
429 }
430
431 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
432 In general, in the case of multivariate evolutions we want to get
433 the evolution in different loops. LOOP specifies the level for
434 which to get the evolution.
435
436 Example:
437
438 | for (j = 0; j < 100; j++)
439 | {
440 | for (k = 0; k < 100; k++)
441 | {
442 | i = k + j; - Here the value of i is a function of j, k.
443 | }
444 | ... = i - Here the value of i is a function of j.
445 | }
446 | ... = i - Here the value of i is a scalar.
447
448 Example:
449
450 | i_0 = ...
451 | loop_1 10 times
452 | i_1 = phi (i_0, i_2)
453 | i_2 = i_1 + 2
454 | endloop
455
456 This loop has the same effect as:
457 LOOP_1 has the same effect as:
458
459 | i_1 = i_0 + 20
460
461 The overall effect of the loop, "i_0 + 20" in the previous example,
462 is obtained by passing in the parameters: LOOP = 1,
463 EVOLUTION_FN = {i_0, +, 2}_1.
464 */
465
466 tree
467 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
468 {
469 bool val = false;
470
471 if (evolution_fn == chrec_dont_know)
472 return chrec_dont_know;
473
474 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
475 {
476 struct loop *inner_loop = get_chrec_loop (evolution_fn);
477
478 if (inner_loop == loop
479 || flow_loop_nested_p (loop, inner_loop))
480 {
481 tree nb_iter = number_of_latch_executions (inner_loop);
482
483 if (nb_iter == chrec_dont_know)
484 return chrec_dont_know;
485 else
486 {
487 tree res;
488
489 /* evolution_fn is the evolution function in LOOP. Get
490 its value in the nb_iter-th iteration. */
491 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
492
493 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
494 res = instantiate_parameters (loop, res);
495
496 /* Continue the computation until ending on a parent of LOOP. */
497 return compute_overall_effect_of_inner_loop (loop, res);
498 }
499 }
500 else
501 return evolution_fn;
502 }
503
504 /* If the evolution function is an invariant, there is nothing to do. */
505 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
506 return evolution_fn;
507
508 else
509 return chrec_dont_know;
510 }
511
512 /* Determine whether the CHREC is always positive/negative. If the expression
513 cannot be statically analyzed, return false, otherwise set the answer into
514 VALUE. */
515
516 bool
517 chrec_is_positive (tree chrec, bool *value)
518 {
519 bool value0, value1, value2;
520 tree end_value, nb_iter;
521
522 switch (TREE_CODE (chrec))
523 {
524 case POLYNOMIAL_CHREC:
525 if (!chrec_is_positive (CHREC_LEFT (chrec), &value0)
526 || !chrec_is_positive (CHREC_RIGHT (chrec), &value1))
527 return false;
528
529 /* FIXME -- overflows. */
530 if (value0 == value1)
531 {
532 *value = value0;
533 return true;
534 }
535
536 /* Otherwise the chrec is under the form: "{-197, +, 2}_1",
537 and the proof consists in showing that the sign never
538 changes during the execution of the loop, from 0 to
539 loop->nb_iterations. */
540 if (!evolution_function_is_affine_p (chrec))
541 return false;
542
543 nb_iter = number_of_latch_executions (get_chrec_loop (chrec));
544 if (chrec_contains_undetermined (nb_iter))
545 return false;
546
547 #if 0
548 /* TODO -- If the test is after the exit, we may decrease the number of
549 iterations by one. */
550 if (after_exit)
551 nb_iter = chrec_fold_minus (type, nb_iter, build_int_cst (type, 1));
552 #endif
553
554 end_value = chrec_apply (CHREC_VARIABLE (chrec), chrec, nb_iter);
555
556 if (!chrec_is_positive (end_value, &value2))
557 return false;
558
559 *value = value0;
560 return value0 == value1;
561
562 case INTEGER_CST:
563 *value = (tree_int_cst_sgn (chrec) == 1);
564 return true;
565
566 default:
567 return false;
568 }
569 }
570
571 /* Associate CHREC to SCALAR. */
572
573 static void
574 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
575 {
576 tree *scalar_info;
577
578 if (TREE_CODE (scalar) != SSA_NAME)
579 return;
580
581 scalar_info = find_var_scev_info (instantiated_below, scalar);
582
583 if (dump_file)
584 {
585 if (dump_flags & TDF_DETAILS)
586 {
587 fprintf (dump_file, "(set_scalar_evolution \n");
588 fprintf (dump_file, " instantiated_below = %d \n",
589 instantiated_below->index);
590 fprintf (dump_file, " (scalar = ");
591 print_generic_expr (dump_file, scalar, 0);
592 fprintf (dump_file, ")\n (scalar_evolution = ");
593 print_generic_expr (dump_file, chrec, 0);
594 fprintf (dump_file, "))\n");
595 }
596 if (dump_flags & TDF_STATS)
597 nb_set_scev++;
598 }
599
600 *scalar_info = chrec;
601 }
602
603 /* Retrieve the chrec associated to SCALAR instantiated below
604 INSTANTIATED_BELOW block. */
605
606 static tree
607 get_scalar_evolution (basic_block instantiated_below, tree scalar)
608 {
609 tree res;
610
611 if (dump_file)
612 {
613 if (dump_flags & TDF_DETAILS)
614 {
615 fprintf (dump_file, "(get_scalar_evolution \n");
616 fprintf (dump_file, " (scalar = ");
617 print_generic_expr (dump_file, scalar, 0);
618 fprintf (dump_file, ")\n");
619 }
620 if (dump_flags & TDF_STATS)
621 nb_get_scev++;
622 }
623
624 switch (TREE_CODE (scalar))
625 {
626 case SSA_NAME:
627 res = *find_var_scev_info (instantiated_below, scalar);
628 break;
629
630 case REAL_CST:
631 case FIXED_CST:
632 case INTEGER_CST:
633 res = scalar;
634 break;
635
636 default:
637 res = chrec_not_analyzed_yet;
638 break;
639 }
640
641 if (dump_file && (dump_flags & TDF_DETAILS))
642 {
643 fprintf (dump_file, " (scalar_evolution = ");
644 print_generic_expr (dump_file, res, 0);
645 fprintf (dump_file, "))\n");
646 }
647
648 return res;
649 }
650
651 /* Helper function for add_to_evolution. Returns the evolution
652 function for an assignment of the form "a = b + c", where "a" and
653 "b" are on the strongly connected component. CHREC_BEFORE is the
654 information that we already have collected up to this point.
655 TO_ADD is the evolution of "c".
656
657 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
658 evolution the expression TO_ADD, otherwise construct an evolution
659 part for this loop. */
660
661 static tree
662 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
663 gimple at_stmt)
664 {
665 tree type, left, right;
666 struct loop *loop = get_loop (loop_nb), *chloop;
667
668 switch (TREE_CODE (chrec_before))
669 {
670 case POLYNOMIAL_CHREC:
671 chloop = get_chrec_loop (chrec_before);
672 if (chloop == loop
673 || flow_loop_nested_p (chloop, loop))
674 {
675 unsigned var;
676
677 type = chrec_type (chrec_before);
678
679 /* When there is no evolution part in this loop, build it. */
680 if (chloop != loop)
681 {
682 var = loop_nb;
683 left = chrec_before;
684 right = SCALAR_FLOAT_TYPE_P (type)
685 ? build_real (type, dconst0)
686 : build_int_cst (type, 0);
687 }
688 else
689 {
690 var = CHREC_VARIABLE (chrec_before);
691 left = CHREC_LEFT (chrec_before);
692 right = CHREC_RIGHT (chrec_before);
693 }
694
695 to_add = chrec_convert (type, to_add, at_stmt);
696 right = chrec_convert_rhs (type, right, at_stmt);
697 right = chrec_fold_plus (chrec_type (right), right, to_add);
698 return build_polynomial_chrec (var, left, right);
699 }
700 else
701 {
702 gcc_assert (flow_loop_nested_p (loop, chloop));
703
704 /* Search the evolution in LOOP_NB. */
705 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
706 to_add, at_stmt);
707 right = CHREC_RIGHT (chrec_before);
708 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
709 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
710 left, right);
711 }
712
713 default:
714 /* These nodes do not depend on a loop. */
715 if (chrec_before == chrec_dont_know)
716 return chrec_dont_know;
717
718 left = chrec_before;
719 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
720 return build_polynomial_chrec (loop_nb, left, right);
721 }
722 }
723
724 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
725 of LOOP_NB.
726
727 Description (provided for completeness, for those who read code in
728 a plane, and for my poor 62 bytes brain that would have forgotten
729 all this in the next two or three months):
730
731 The algorithm of translation of programs from the SSA representation
732 into the chrecs syntax is based on a pattern matching. After having
733 reconstructed the overall tree expression for a loop, there are only
734 two cases that can arise:
735
736 1. a = loop-phi (init, a + expr)
737 2. a = loop-phi (init, expr)
738
739 where EXPR is either a scalar constant with respect to the analyzed
740 loop (this is a degree 0 polynomial), or an expression containing
741 other loop-phi definitions (these are higher degree polynomials).
742
743 Examples:
744
745 1.
746 | init = ...
747 | loop_1
748 | a = phi (init, a + 5)
749 | endloop
750
751 2.
752 | inita = ...
753 | initb = ...
754 | loop_1
755 | a = phi (inita, 2 * b + 3)
756 | b = phi (initb, b + 1)
757 | endloop
758
759 For the first case, the semantics of the SSA representation is:
760
761 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
762
763 that is, there is a loop index "x" that determines the scalar value
764 of the variable during the loop execution. During the first
765 iteration, the value is that of the initial condition INIT, while
766 during the subsequent iterations, it is the sum of the initial
767 condition with the sum of all the values of EXPR from the initial
768 iteration to the before last considered iteration.
769
770 For the second case, the semantics of the SSA program is:
771
772 | a (x) = init, if x = 0;
773 | expr (x - 1), otherwise.
774
775 The second case corresponds to the PEELED_CHREC, whose syntax is
776 close to the syntax of a loop-phi-node:
777
778 | phi (init, expr) vs. (init, expr)_x
779
780 The proof of the translation algorithm for the first case is a
781 proof by structural induction based on the degree of EXPR.
782
783 Degree 0:
784 When EXPR is a constant with respect to the analyzed loop, or in
785 other words when EXPR is a polynomial of degree 0, the evolution of
786 the variable A in the loop is an affine function with an initial
787 condition INIT, and a step EXPR. In order to show this, we start
788 from the semantics of the SSA representation:
789
790 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
791
792 and since "expr (j)" is a constant with respect to "j",
793
794 f (x) = init + x * expr
795
796 Finally, based on the semantics of the pure sum chrecs, by
797 identification we get the corresponding chrecs syntax:
798
799 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
800 f (x) -> {init, +, expr}_x
801
802 Higher degree:
803 Suppose that EXPR is a polynomial of degree N with respect to the
804 analyzed loop_x for which we have already determined that it is
805 written under the chrecs syntax:
806
807 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
808
809 We start from the semantics of the SSA program:
810
811 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
812 |
813 | f (x) = init + \sum_{j = 0}^{x - 1}
814 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
815 |
816 | f (x) = init + \sum_{j = 0}^{x - 1}
817 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
818 |
819 | f (x) = init + \sum_{k = 0}^{n - 1}
820 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
821 |
822 | f (x) = init + \sum_{k = 0}^{n - 1}
823 | (b_k * \binom{x}{k + 1})
824 |
825 | f (x) = init + b_0 * \binom{x}{1} + ...
826 | + b_{n-1} * \binom{x}{n}
827 |
828 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
829 | + b_{n-1} * \binom{x}{n}
830 |
831
832 And finally from the definition of the chrecs syntax, we identify:
833 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
834
835 This shows the mechanism that stands behind the add_to_evolution
836 function. An important point is that the use of symbolic
837 parameters avoids the need of an analysis schedule.
838
839 Example:
840
841 | inita = ...
842 | initb = ...
843 | loop_1
844 | a = phi (inita, a + 2 + b)
845 | b = phi (initb, b + 1)
846 | endloop
847
848 When analyzing "a", the algorithm keeps "b" symbolically:
849
850 | a -> {inita, +, 2 + b}_1
851
852 Then, after instantiation, the analyzer ends on the evolution:
853
854 | a -> {inita, +, 2 + initb, +, 1}_1
855
856 */
857
858 static tree
859 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
860 tree to_add, gimple at_stmt)
861 {
862 tree type = chrec_type (to_add);
863 tree res = NULL_TREE;
864
865 if (to_add == NULL_TREE)
866 return chrec_before;
867
868 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
869 instantiated at this point. */
870 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
871 /* This should not happen. */
872 return chrec_dont_know;
873
874 if (dump_file && (dump_flags & TDF_DETAILS))
875 {
876 fprintf (dump_file, "(add_to_evolution \n");
877 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
878 fprintf (dump_file, " (chrec_before = ");
879 print_generic_expr (dump_file, chrec_before, 0);
880 fprintf (dump_file, ")\n (to_add = ");
881 print_generic_expr (dump_file, to_add, 0);
882 fprintf (dump_file, ")\n");
883 }
884
885 if (code == MINUS_EXPR)
886 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
887 ? build_real (type, dconstm1)
888 : build_int_cst_type (type, -1));
889
890 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
891
892 if (dump_file && (dump_flags & TDF_DETAILS))
893 {
894 fprintf (dump_file, " (res = ");
895 print_generic_expr (dump_file, res, 0);
896 fprintf (dump_file, "))\n");
897 }
898
899 return res;
900 }
901
902 \f
903
904 /* This section selects the loops that will be good candidates for the
905 scalar evolution analysis. For the moment, greedily select all the
906 loop nests we could analyze. */
907
908 /* For a loop with a single exit edge, return the COND_EXPR that
909 guards the exit edge. If the expression is too difficult to
910 analyze, then give up. */
911
912 gimple
913 get_loop_exit_condition (const struct loop *loop)
914 {
915 gimple res = NULL;
916 edge exit_edge = single_exit (loop);
917
918 if (dump_file && (dump_flags & TDF_DETAILS))
919 fprintf (dump_file, "(get_loop_exit_condition \n ");
920
921 if (exit_edge)
922 {
923 gimple stmt;
924
925 stmt = last_stmt (exit_edge->src);
926 if (gimple_code (stmt) == GIMPLE_COND)
927 res = stmt;
928 }
929
930 if (dump_file && (dump_flags & TDF_DETAILS))
931 {
932 print_gimple_stmt (dump_file, res, 0, 0);
933 fprintf (dump_file, ")\n");
934 }
935
936 return res;
937 }
938
939 /* Recursively determine and enqueue the exit conditions for a loop. */
940
941 static void
942 get_exit_conditions_rec (struct loop *loop,
943 VEC(gimple,heap) **exit_conditions)
944 {
945 if (!loop)
946 return;
947
948 /* Recurse on the inner loops, then on the next (sibling) loops. */
949 get_exit_conditions_rec (loop->inner, exit_conditions);
950 get_exit_conditions_rec (loop->next, exit_conditions);
951
952 if (single_exit (loop))
953 {
954 gimple loop_condition = get_loop_exit_condition (loop);
955
956 if (loop_condition)
957 VEC_safe_push (gimple, heap, *exit_conditions, loop_condition);
958 }
959 }
960
961 /* Select the candidate loop nests for the analysis. This function
962 initializes the EXIT_CONDITIONS array. */
963
964 static void
965 select_loops_exit_conditions (VEC(gimple,heap) **exit_conditions)
966 {
967 struct loop *function_body = current_loops->tree_root;
968
969 get_exit_conditions_rec (function_body->inner, exit_conditions);
970 }
971
972 \f
973 /* Depth first search algorithm. */
974
975 typedef enum t_bool {
976 t_false,
977 t_true,
978 t_dont_know
979 } t_bool;
980
981
982 static t_bool follow_ssa_edge (struct loop *loop, gimple, gimple, tree *, int);
983
984 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
985 Return true if the strongly connected component has been found. */
986
987 static t_bool
988 follow_ssa_edge_binary (struct loop *loop, gimple at_stmt,
989 tree type, tree rhs0, enum tree_code code, tree rhs1,
990 gimple halting_phi, tree *evolution_of_loop, int limit)
991 {
992 t_bool res = t_false;
993 tree evol;
994
995 switch (code)
996 {
997 case POINTER_PLUS_EXPR:
998 case PLUS_EXPR:
999 if (TREE_CODE (rhs0) == SSA_NAME)
1000 {
1001 if (TREE_CODE (rhs1) == SSA_NAME)
1002 {
1003 /* Match an assignment under the form:
1004 "a = b + c". */
1005
1006 /* We want only assignments of form "name + name" contribute to
1007 LIMIT, as the other cases do not necessarily contribute to
1008 the complexity of the expression. */
1009 limit++;
1010
1011 evol = *evolution_of_loop;
1012 res = follow_ssa_edge
1013 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
1014
1015 if (res == t_true)
1016 *evolution_of_loop = add_to_evolution
1017 (loop->num,
1018 chrec_convert (type, evol, at_stmt),
1019 code, rhs1, at_stmt);
1020
1021 else if (res == t_false)
1022 {
1023 res = follow_ssa_edge
1024 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1025 evolution_of_loop, limit);
1026
1027 if (res == t_true)
1028 *evolution_of_loop = add_to_evolution
1029 (loop->num,
1030 chrec_convert (type, *evolution_of_loop, at_stmt),
1031 code, rhs0, at_stmt);
1032
1033 else if (res == t_dont_know)
1034 *evolution_of_loop = chrec_dont_know;
1035 }
1036
1037 else if (res == t_dont_know)
1038 *evolution_of_loop = chrec_dont_know;
1039 }
1040
1041 else
1042 {
1043 /* Match an assignment under the form:
1044 "a = b + ...". */
1045 res = follow_ssa_edge
1046 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1047 evolution_of_loop, limit);
1048 if (res == t_true)
1049 *evolution_of_loop = add_to_evolution
1050 (loop->num, chrec_convert (type, *evolution_of_loop,
1051 at_stmt),
1052 code, rhs1, at_stmt);
1053
1054 else if (res == t_dont_know)
1055 *evolution_of_loop = chrec_dont_know;
1056 }
1057 }
1058
1059 else if (TREE_CODE (rhs1) == SSA_NAME)
1060 {
1061 /* Match an assignment under the form:
1062 "a = ... + c". */
1063 res = follow_ssa_edge
1064 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1065 evolution_of_loop, limit);
1066 if (res == t_true)
1067 *evolution_of_loop = add_to_evolution
1068 (loop->num, chrec_convert (type, *evolution_of_loop,
1069 at_stmt),
1070 code, rhs0, at_stmt);
1071
1072 else if (res == t_dont_know)
1073 *evolution_of_loop = chrec_dont_know;
1074 }
1075
1076 else
1077 /* Otherwise, match an assignment under the form:
1078 "a = ... + ...". */
1079 /* And there is nothing to do. */
1080 res = t_false;
1081 break;
1082
1083 case MINUS_EXPR:
1084 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1085 if (TREE_CODE (rhs0) == SSA_NAME)
1086 {
1087 /* Match an assignment under the form:
1088 "a = b - ...". */
1089
1090 /* We want only assignments of form "name - name" contribute to
1091 LIMIT, as the other cases do not necessarily contribute to
1092 the complexity of the expression. */
1093 if (TREE_CODE (rhs1) == SSA_NAME)
1094 limit++;
1095
1096 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1097 evolution_of_loop, limit);
1098 if (res == t_true)
1099 *evolution_of_loop = add_to_evolution
1100 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1101 MINUS_EXPR, rhs1, at_stmt);
1102
1103 else if (res == t_dont_know)
1104 *evolution_of_loop = chrec_dont_know;
1105 }
1106 else
1107 /* Otherwise, match an assignment under the form:
1108 "a = ... - ...". */
1109 /* And there is nothing to do. */
1110 res = t_false;
1111 break;
1112
1113 default:
1114 res = t_false;
1115 }
1116
1117 return res;
1118 }
1119
1120 /* Follow the ssa edge into the expression EXPR.
1121 Return true if the strongly connected component has been found. */
1122
1123 static t_bool
1124 follow_ssa_edge_expr (struct loop *loop, gimple at_stmt, tree expr,
1125 gimple halting_phi, tree *evolution_of_loop, int limit)
1126 {
1127 enum tree_code code = TREE_CODE (expr);
1128 tree type = TREE_TYPE (expr), rhs0, rhs1;
1129 t_bool res;
1130
1131 /* The EXPR is one of the following cases:
1132 - an SSA_NAME,
1133 - an INTEGER_CST,
1134 - a PLUS_EXPR,
1135 - a POINTER_PLUS_EXPR,
1136 - a MINUS_EXPR,
1137 - an ASSERT_EXPR,
1138 - other cases are not yet handled. */
1139
1140 switch (code)
1141 {
1142 CASE_CONVERT:
1143 /* This assignment is under the form "a_1 = (cast) rhs. */
1144 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1145 halting_phi, evolution_of_loop, limit);
1146 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1147 break;
1148
1149 case INTEGER_CST:
1150 /* This assignment is under the form "a_1 = 7". */
1151 res = t_false;
1152 break;
1153
1154 case SSA_NAME:
1155 /* This assignment is under the form: "a_1 = b_2". */
1156 res = follow_ssa_edge
1157 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1158 break;
1159
1160 case POINTER_PLUS_EXPR:
1161 case PLUS_EXPR:
1162 case MINUS_EXPR:
1163 /* This case is under the form "rhs0 +- rhs1". */
1164 rhs0 = TREE_OPERAND (expr, 0);
1165 rhs1 = TREE_OPERAND (expr, 1);
1166 type = TREE_TYPE (rhs0);
1167 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1168 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1169 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1170 halting_phi, evolution_of_loop, limit);
1171 break;
1172
1173 case ASSERT_EXPR:
1174 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1175 It must be handled as a copy assignment of the form a_1 = a_2. */
1176 rhs0 = ASSERT_EXPR_VAR (expr);
1177 if (TREE_CODE (rhs0) == SSA_NAME)
1178 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1179 halting_phi, evolution_of_loop, limit);
1180 else
1181 res = t_false;
1182 break;
1183
1184 default:
1185 res = t_false;
1186 break;
1187 }
1188
1189 return res;
1190 }
1191
1192 /* Follow the ssa edge into the right hand side of an assignment STMT.
1193 Return true if the strongly connected component has been found. */
1194
1195 static t_bool
1196 follow_ssa_edge_in_rhs (struct loop *loop, gimple stmt,
1197 gimple halting_phi, tree *evolution_of_loop, int limit)
1198 {
1199 enum tree_code code = gimple_assign_rhs_code (stmt);
1200 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1201 t_bool res;
1202
1203 switch (code)
1204 {
1205 CASE_CONVERT:
1206 /* This assignment is under the form "a_1 = (cast) rhs. */
1207 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1208 halting_phi, evolution_of_loop, limit);
1209 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1210 break;
1211
1212 case POINTER_PLUS_EXPR:
1213 case PLUS_EXPR:
1214 case MINUS_EXPR:
1215 rhs1 = gimple_assign_rhs1 (stmt);
1216 rhs2 = gimple_assign_rhs2 (stmt);
1217 type = TREE_TYPE (rhs1);
1218 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1219 halting_phi, evolution_of_loop, limit);
1220 break;
1221
1222 default:
1223 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1224 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1225 halting_phi, evolution_of_loop, limit);
1226 else
1227 res = t_false;
1228 break;
1229 }
1230
1231 return res;
1232 }
1233
1234 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1235
1236 static bool
1237 backedge_phi_arg_p (gimple phi, int i)
1238 {
1239 const_edge e = gimple_phi_arg_edge (phi, i);
1240
1241 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1242 about updating it anywhere, and this should work as well most of the
1243 time. */
1244 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1245 return true;
1246
1247 return false;
1248 }
1249
1250 /* Helper function for one branch of the condition-phi-node. Return
1251 true if the strongly connected component has been found following
1252 this path. */
1253
1254 static inline t_bool
1255 follow_ssa_edge_in_condition_phi_branch (int i,
1256 struct loop *loop,
1257 gimple condition_phi,
1258 gimple halting_phi,
1259 tree *evolution_of_branch,
1260 tree init_cond, int limit)
1261 {
1262 tree branch = PHI_ARG_DEF (condition_phi, i);
1263 *evolution_of_branch = chrec_dont_know;
1264
1265 /* Do not follow back edges (they must belong to an irreducible loop, which
1266 we really do not want to worry about). */
1267 if (backedge_phi_arg_p (condition_phi, i))
1268 return t_false;
1269
1270 if (TREE_CODE (branch) == SSA_NAME)
1271 {
1272 *evolution_of_branch = init_cond;
1273 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1274 evolution_of_branch, limit);
1275 }
1276
1277 /* This case occurs when one of the condition branches sets
1278 the variable to a constant: i.e. a phi-node like
1279 "a_2 = PHI <a_7(5), 2(6)>;".
1280
1281 FIXME: This case have to be refined correctly:
1282 in some cases it is possible to say something better than
1283 chrec_dont_know, for example using a wrap-around notation. */
1284 return t_false;
1285 }
1286
1287 /* This function merges the branches of a condition-phi-node in a
1288 loop. */
1289
1290 static t_bool
1291 follow_ssa_edge_in_condition_phi (struct loop *loop,
1292 gimple condition_phi,
1293 gimple halting_phi,
1294 tree *evolution_of_loop, int limit)
1295 {
1296 int i, n;
1297 tree init = *evolution_of_loop;
1298 tree evolution_of_branch;
1299 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1300 halting_phi,
1301 &evolution_of_branch,
1302 init, limit);
1303 if (res == t_false || res == t_dont_know)
1304 return res;
1305
1306 *evolution_of_loop = evolution_of_branch;
1307
1308 n = gimple_phi_num_args (condition_phi);
1309 for (i = 1; i < n; i++)
1310 {
1311 /* Quickly give up when the evolution of one of the branches is
1312 not known. */
1313 if (*evolution_of_loop == chrec_dont_know)
1314 return t_true;
1315
1316 /* Increase the limit by the PHI argument number to avoid exponential
1317 time and memory complexity. */
1318 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1319 halting_phi,
1320 &evolution_of_branch,
1321 init, limit + i);
1322 if (res == t_false || res == t_dont_know)
1323 return res;
1324
1325 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1326 evolution_of_branch);
1327 }
1328
1329 return t_true;
1330 }
1331
1332 /* Follow an SSA edge in an inner loop. It computes the overall
1333 effect of the loop, and following the symbolic initial conditions,
1334 it follows the edges in the parent loop. The inner loop is
1335 considered as a single statement. */
1336
1337 static t_bool
1338 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1339 gimple loop_phi_node,
1340 gimple halting_phi,
1341 tree *evolution_of_loop, int limit)
1342 {
1343 struct loop *loop = loop_containing_stmt (loop_phi_node);
1344 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1345
1346 /* Sometimes, the inner loop is too difficult to analyze, and the
1347 result of the analysis is a symbolic parameter. */
1348 if (ev == PHI_RESULT (loop_phi_node))
1349 {
1350 t_bool res = t_false;
1351 int i, n = gimple_phi_num_args (loop_phi_node);
1352
1353 for (i = 0; i < n; i++)
1354 {
1355 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1356 basic_block bb;
1357
1358 /* Follow the edges that exit the inner loop. */
1359 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1360 if (!flow_bb_inside_loop_p (loop, bb))
1361 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1362 arg, halting_phi,
1363 evolution_of_loop, limit);
1364 if (res == t_true)
1365 break;
1366 }
1367
1368 /* If the path crosses this loop-phi, give up. */
1369 if (res == t_true)
1370 *evolution_of_loop = chrec_dont_know;
1371
1372 return res;
1373 }
1374
1375 /* Otherwise, compute the overall effect of the inner loop. */
1376 ev = compute_overall_effect_of_inner_loop (loop, ev);
1377 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1378 evolution_of_loop, limit);
1379 }
1380
1381 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1382 path that is analyzed on the return walk. */
1383
1384 static t_bool
1385 follow_ssa_edge (struct loop *loop, gimple def, gimple halting_phi,
1386 tree *evolution_of_loop, int limit)
1387 {
1388 struct loop *def_loop;
1389
1390 if (gimple_nop_p (def))
1391 return t_false;
1392
1393 /* Give up if the path is longer than the MAX that we allow. */
1394 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
1395 return t_dont_know;
1396
1397 def_loop = loop_containing_stmt (def);
1398
1399 switch (gimple_code (def))
1400 {
1401 case GIMPLE_PHI:
1402 if (!loop_phi_node_p (def))
1403 /* DEF is a condition-phi-node. Follow the branches, and
1404 record their evolutions. Finally, merge the collected
1405 information and set the approximation to the main
1406 variable. */
1407 return follow_ssa_edge_in_condition_phi
1408 (loop, def, halting_phi, evolution_of_loop, limit);
1409
1410 /* When the analyzed phi is the halting_phi, the
1411 depth-first search is over: we have found a path from
1412 the halting_phi to itself in the loop. */
1413 if (def == halting_phi)
1414 return t_true;
1415
1416 /* Otherwise, the evolution of the HALTING_PHI depends
1417 on the evolution of another loop-phi-node, i.e. the
1418 evolution function is a higher degree polynomial. */
1419 if (def_loop == loop)
1420 return t_false;
1421
1422 /* Inner loop. */
1423 if (flow_loop_nested_p (loop, def_loop))
1424 return follow_ssa_edge_inner_loop_phi
1425 (loop, def, halting_phi, evolution_of_loop, limit + 1);
1426
1427 /* Outer loop. */
1428 return t_false;
1429
1430 case GIMPLE_ASSIGN:
1431 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1432 evolution_of_loop, limit);
1433
1434 default:
1435 /* At this level of abstraction, the program is just a set
1436 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1437 other node to be handled. */
1438 return t_false;
1439 }
1440 }
1441
1442 \f
1443
1444 /* Given a LOOP_PHI_NODE, this function determines the evolution
1445 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1446
1447 static tree
1448 analyze_evolution_in_loop (gimple loop_phi_node,
1449 tree init_cond)
1450 {
1451 int i, n = gimple_phi_num_args (loop_phi_node);
1452 tree evolution_function = chrec_not_analyzed_yet;
1453 struct loop *loop = loop_containing_stmt (loop_phi_node);
1454 basic_block bb;
1455
1456 if (dump_file && (dump_flags & TDF_DETAILS))
1457 {
1458 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1459 fprintf (dump_file, " (loop_phi_node = ");
1460 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1461 fprintf (dump_file, ")\n");
1462 }
1463
1464 for (i = 0; i < n; i++)
1465 {
1466 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1467 gimple ssa_chain;
1468 tree ev_fn;
1469 t_bool res;
1470
1471 /* Select the edges that enter the loop body. */
1472 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1473 if (!flow_bb_inside_loop_p (loop, bb))
1474 continue;
1475
1476 if (TREE_CODE (arg) == SSA_NAME)
1477 {
1478 bool val = false;
1479
1480 ssa_chain = SSA_NAME_DEF_STMT (arg);
1481
1482 /* Pass in the initial condition to the follow edge function. */
1483 ev_fn = init_cond;
1484 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1485
1486 /* If ev_fn has no evolution in the inner loop, and the
1487 init_cond is not equal to ev_fn, then we have an
1488 ambiguity between two possible values, as we cannot know
1489 the number of iterations at this point. */
1490 if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1491 && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1492 && !operand_equal_p (init_cond, ev_fn, 0))
1493 ev_fn = chrec_dont_know;
1494 }
1495 else
1496 res = t_false;
1497
1498 /* When it is impossible to go back on the same
1499 loop_phi_node by following the ssa edges, the
1500 evolution is represented by a peeled chrec, i.e. the
1501 first iteration, EV_FN has the value INIT_COND, then
1502 all the other iterations it has the value of ARG.
1503 For the moment, PEELED_CHREC nodes are not built. */
1504 if (res != t_true)
1505 ev_fn = chrec_dont_know;
1506
1507 /* When there are multiple back edges of the loop (which in fact never
1508 happens currently, but nevertheless), merge their evolutions. */
1509 evolution_function = chrec_merge (evolution_function, ev_fn);
1510 }
1511
1512 if (dump_file && (dump_flags & TDF_DETAILS))
1513 {
1514 fprintf (dump_file, " (evolution_function = ");
1515 print_generic_expr (dump_file, evolution_function, 0);
1516 fprintf (dump_file, "))\n");
1517 }
1518
1519 return evolution_function;
1520 }
1521
1522 /* Given a loop-phi-node, return the initial conditions of the
1523 variable on entry of the loop. When the CCP has propagated
1524 constants into the loop-phi-node, the initial condition is
1525 instantiated, otherwise the initial condition is kept symbolic.
1526 This analyzer does not analyze the evolution outside the current
1527 loop, and leaves this task to the on-demand tree reconstructor. */
1528
1529 static tree
1530 analyze_initial_condition (gimple loop_phi_node)
1531 {
1532 int i, n;
1533 tree init_cond = chrec_not_analyzed_yet;
1534 struct loop *loop = loop_containing_stmt (loop_phi_node);
1535
1536 if (dump_file && (dump_flags & TDF_DETAILS))
1537 {
1538 fprintf (dump_file, "(analyze_initial_condition \n");
1539 fprintf (dump_file, " (loop_phi_node = \n");
1540 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1541 fprintf (dump_file, ")\n");
1542 }
1543
1544 n = gimple_phi_num_args (loop_phi_node);
1545 for (i = 0; i < n; i++)
1546 {
1547 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1548 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1549
1550 /* When the branch is oriented to the loop's body, it does
1551 not contribute to the initial condition. */
1552 if (flow_bb_inside_loop_p (loop, bb))
1553 continue;
1554
1555 if (init_cond == chrec_not_analyzed_yet)
1556 {
1557 init_cond = branch;
1558 continue;
1559 }
1560
1561 if (TREE_CODE (branch) == SSA_NAME)
1562 {
1563 init_cond = chrec_dont_know;
1564 break;
1565 }
1566
1567 init_cond = chrec_merge (init_cond, branch);
1568 }
1569
1570 /* Ooops -- a loop without an entry??? */
1571 if (init_cond == chrec_not_analyzed_yet)
1572 init_cond = chrec_dont_know;
1573
1574 /* During early loop unrolling we do not have fully constant propagated IL.
1575 Handle degenerate PHIs here to not miss important unrollings. */
1576 if (TREE_CODE (init_cond) == SSA_NAME)
1577 {
1578 gimple def = SSA_NAME_DEF_STMT (init_cond);
1579 tree res;
1580 if (gimple_code (def) == GIMPLE_PHI
1581 && (res = degenerate_phi_result (def)) != NULL_TREE
1582 /* Only allow invariants here, otherwise we may break
1583 loop-closed SSA form. */
1584 && is_gimple_min_invariant (res))
1585 init_cond = res;
1586 }
1587
1588 if (dump_file && (dump_flags & TDF_DETAILS))
1589 {
1590 fprintf (dump_file, " (init_cond = ");
1591 print_generic_expr (dump_file, init_cond, 0);
1592 fprintf (dump_file, "))\n");
1593 }
1594
1595 return init_cond;
1596 }
1597
1598 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1599
1600 static tree
1601 interpret_loop_phi (struct loop *loop, gimple loop_phi_node)
1602 {
1603 tree res;
1604 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1605 tree init_cond;
1606
1607 if (phi_loop != loop)
1608 {
1609 struct loop *subloop;
1610 tree evolution_fn = analyze_scalar_evolution
1611 (phi_loop, PHI_RESULT (loop_phi_node));
1612
1613 /* Dive one level deeper. */
1614 subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1615
1616 /* Interpret the subloop. */
1617 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1618 return res;
1619 }
1620
1621 /* Otherwise really interpret the loop phi. */
1622 init_cond = analyze_initial_condition (loop_phi_node);
1623 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1624
1625 /* Verify we maintained the correct initial condition throughout
1626 possible conversions in the SSA chain. */
1627 if (res != chrec_dont_know)
1628 {
1629 tree new_init = res;
1630 if (CONVERT_EXPR_P (res)
1631 && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1632 new_init = fold_convert (TREE_TYPE (res),
1633 CHREC_LEFT (TREE_OPERAND (res, 0)));
1634 else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1635 new_init = CHREC_LEFT (res);
1636 STRIP_USELESS_TYPE_CONVERSION (new_init);
1637 gcc_assert (TREE_CODE (new_init) != POLYNOMIAL_CHREC);
1638 if (!operand_equal_p (init_cond, new_init, 0))
1639 return chrec_dont_know;
1640 }
1641
1642 return res;
1643 }
1644
1645 /* This function merges the branches of a condition-phi-node,
1646 contained in the outermost loop, and whose arguments are already
1647 analyzed. */
1648
1649 static tree
1650 interpret_condition_phi (struct loop *loop, gimple condition_phi)
1651 {
1652 int i, n = gimple_phi_num_args (condition_phi);
1653 tree res = chrec_not_analyzed_yet;
1654
1655 for (i = 0; i < n; i++)
1656 {
1657 tree branch_chrec;
1658
1659 if (backedge_phi_arg_p (condition_phi, i))
1660 {
1661 res = chrec_dont_know;
1662 break;
1663 }
1664
1665 branch_chrec = analyze_scalar_evolution
1666 (loop, PHI_ARG_DEF (condition_phi, i));
1667
1668 res = chrec_merge (res, branch_chrec);
1669 }
1670
1671 return res;
1672 }
1673
1674 /* Interpret the operation RHS1 OP RHS2. If we didn't
1675 analyze this node before, follow the definitions until ending
1676 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1677 return path, this function propagates evolutions (ala constant copy
1678 propagation). OPND1 is not a GIMPLE expression because we could
1679 analyze the effect of an inner loop: see interpret_loop_phi. */
1680
1681 static tree
1682 interpret_rhs_expr (struct loop *loop, gimple at_stmt,
1683 tree type, tree rhs1, enum tree_code code, tree rhs2)
1684 {
1685 tree res, chrec1, chrec2;
1686
1687 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1688 {
1689 if (is_gimple_min_invariant (rhs1))
1690 return chrec_convert (type, rhs1, at_stmt);
1691
1692 if (code == SSA_NAME)
1693 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1694 at_stmt);
1695
1696 if (code == ASSERT_EXPR)
1697 {
1698 rhs1 = ASSERT_EXPR_VAR (rhs1);
1699 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1700 at_stmt);
1701 }
1702
1703 return chrec_dont_know;
1704 }
1705
1706 switch (code)
1707 {
1708 case POINTER_PLUS_EXPR:
1709 chrec1 = analyze_scalar_evolution (loop, rhs1);
1710 chrec2 = analyze_scalar_evolution (loop, rhs2);
1711 chrec1 = chrec_convert (type, chrec1, at_stmt);
1712 chrec2 = chrec_convert (sizetype, chrec2, at_stmt);
1713 res = chrec_fold_plus (type, chrec1, chrec2);
1714 break;
1715
1716 case PLUS_EXPR:
1717 chrec1 = analyze_scalar_evolution (loop, rhs1);
1718 chrec2 = analyze_scalar_evolution (loop, rhs2);
1719 chrec1 = chrec_convert (type, chrec1, at_stmt);
1720 chrec2 = chrec_convert (type, chrec2, at_stmt);
1721 res = chrec_fold_plus (type, chrec1, chrec2);
1722 break;
1723
1724 case MINUS_EXPR:
1725 chrec1 = analyze_scalar_evolution (loop, rhs1);
1726 chrec2 = analyze_scalar_evolution (loop, rhs2);
1727 chrec1 = chrec_convert (type, chrec1, at_stmt);
1728 chrec2 = chrec_convert (type, chrec2, at_stmt);
1729 res = chrec_fold_minus (type, chrec1, chrec2);
1730 break;
1731
1732 case NEGATE_EXPR:
1733 chrec1 = analyze_scalar_evolution (loop, rhs1);
1734 chrec1 = chrec_convert (type, chrec1, at_stmt);
1735 /* TYPE may be integer, real or complex, so use fold_convert. */
1736 res = chrec_fold_multiply (type, chrec1,
1737 fold_convert (type, integer_minus_one_node));
1738 break;
1739
1740 case BIT_NOT_EXPR:
1741 /* Handle ~X as -1 - X. */
1742 chrec1 = analyze_scalar_evolution (loop, rhs1);
1743 chrec1 = chrec_convert (type, chrec1, at_stmt);
1744 res = chrec_fold_minus (type,
1745 fold_convert (type, integer_minus_one_node),
1746 chrec1);
1747 break;
1748
1749 case MULT_EXPR:
1750 chrec1 = analyze_scalar_evolution (loop, rhs1);
1751 chrec2 = analyze_scalar_evolution (loop, rhs2);
1752 chrec1 = chrec_convert (type, chrec1, at_stmt);
1753 chrec2 = chrec_convert (type, chrec2, at_stmt);
1754 res = chrec_fold_multiply (type, chrec1, chrec2);
1755 break;
1756
1757 CASE_CONVERT:
1758 chrec1 = analyze_scalar_evolution (loop, rhs1);
1759 res = chrec_convert (type, chrec1, at_stmt);
1760 break;
1761
1762 default:
1763 res = chrec_dont_know;
1764 break;
1765 }
1766
1767 return res;
1768 }
1769
1770 /* Interpret the expression EXPR. */
1771
1772 static tree
1773 interpret_expr (struct loop *loop, gimple at_stmt, tree expr)
1774 {
1775 enum tree_code code;
1776 tree type = TREE_TYPE (expr), op0, op1;
1777
1778 if (automatically_generated_chrec_p (expr))
1779 return expr;
1780
1781 if (TREE_CODE (expr) == POLYNOMIAL_CHREC)
1782 return chrec_dont_know;
1783
1784 extract_ops_from_tree (expr, &code, &op0, &op1);
1785
1786 return interpret_rhs_expr (loop, at_stmt, type,
1787 op0, code, op1);
1788 }
1789
1790 /* Interpret the rhs of the assignment STMT. */
1791
1792 static tree
1793 interpret_gimple_assign (struct loop *loop, gimple stmt)
1794 {
1795 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1796 enum tree_code code = gimple_assign_rhs_code (stmt);
1797
1798 return interpret_rhs_expr (loop, stmt, type,
1799 gimple_assign_rhs1 (stmt), code,
1800 gimple_assign_rhs2 (stmt));
1801 }
1802
1803 \f
1804
1805 /* This section contains all the entry points:
1806 - number_of_iterations_in_loop,
1807 - analyze_scalar_evolution,
1808 - instantiate_parameters.
1809 */
1810
1811 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1812 common ancestor of DEF_LOOP and USE_LOOP. */
1813
1814 static tree
1815 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1816 struct loop *def_loop,
1817 tree ev)
1818 {
1819 tree res;
1820 if (def_loop == wrto_loop)
1821 return ev;
1822
1823 def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
1824 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1825
1826 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1827 }
1828
1829 /* Helper recursive function. */
1830
1831 static tree
1832 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1833 {
1834 tree type = TREE_TYPE (var);
1835 gimple def;
1836 basic_block bb;
1837 struct loop *def_loop;
1838
1839 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1840 return chrec_dont_know;
1841
1842 if (TREE_CODE (var) != SSA_NAME)
1843 return interpret_expr (loop, NULL, var);
1844
1845 def = SSA_NAME_DEF_STMT (var);
1846 bb = gimple_bb (def);
1847 def_loop = bb ? bb->loop_father : NULL;
1848
1849 if (bb == NULL
1850 || !flow_bb_inside_loop_p (loop, bb))
1851 {
1852 /* Keep the symbolic form. */
1853 res = var;
1854 goto set_and_end;
1855 }
1856
1857 if (res != chrec_not_analyzed_yet)
1858 {
1859 if (loop != bb->loop_father)
1860 res = compute_scalar_evolution_in_loop
1861 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1862
1863 goto set_and_end;
1864 }
1865
1866 if (loop != def_loop)
1867 {
1868 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1869 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1870
1871 goto set_and_end;
1872 }
1873
1874 switch (gimple_code (def))
1875 {
1876 case GIMPLE_ASSIGN:
1877 res = interpret_gimple_assign (loop, def);
1878 break;
1879
1880 case GIMPLE_PHI:
1881 if (loop_phi_node_p (def))
1882 res = interpret_loop_phi (loop, def);
1883 else
1884 res = interpret_condition_phi (loop, def);
1885 break;
1886
1887 default:
1888 res = chrec_dont_know;
1889 break;
1890 }
1891
1892 set_and_end:
1893
1894 /* Keep the symbolic form. */
1895 if (res == chrec_dont_know)
1896 res = var;
1897
1898 if (loop == def_loop)
1899 set_scalar_evolution (block_before_loop (loop), var, res);
1900
1901 return res;
1902 }
1903
1904 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
1905 LOOP. LOOP is the loop in which the variable is used.
1906
1907 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
1908 pointer to the statement that uses this variable, in order to
1909 determine the evolution function of the variable, use the following
1910 calls:
1911
1912 loop_p loop = loop_containing_stmt (stmt);
1913 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
1914 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
1915 */
1916
1917 tree
1918 analyze_scalar_evolution (struct loop *loop, tree var)
1919 {
1920 tree res;
1921
1922 if (dump_file && (dump_flags & TDF_DETAILS))
1923 {
1924 fprintf (dump_file, "(analyze_scalar_evolution \n");
1925 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
1926 fprintf (dump_file, " (scalar = ");
1927 print_generic_expr (dump_file, var, 0);
1928 fprintf (dump_file, ")\n");
1929 }
1930
1931 res = get_scalar_evolution (block_before_loop (loop), var);
1932 res = analyze_scalar_evolution_1 (loop, var, res);
1933
1934 if (dump_file && (dump_flags & TDF_DETAILS))
1935 fprintf (dump_file, ")\n");
1936
1937 return res;
1938 }
1939
1940 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
1941 WRTO_LOOP (which should be a superloop of USE_LOOP)
1942
1943 FOLDED_CASTS is set to true if resolve_mixers used
1944 chrec_convert_aggressive (TODO -- not really, we are way too conservative
1945 at the moment in order to keep things simple).
1946
1947 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
1948 example:
1949
1950 for (i = 0; i < 100; i++) -- loop 1
1951 {
1952 for (j = 0; j < 100; j++) -- loop 2
1953 {
1954 k1 = i;
1955 k2 = j;
1956
1957 use2 (k1, k2);
1958
1959 for (t = 0; t < 100; t++) -- loop 3
1960 use3 (k1, k2);
1961
1962 }
1963 use1 (k1, k2);
1964 }
1965
1966 Both k1 and k2 are invariants in loop3, thus
1967 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
1968 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
1969
1970 As they are invariant, it does not matter whether we consider their
1971 usage in loop 3 or loop 2, hence
1972 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
1973 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
1974 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
1975 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
1976
1977 Similarly for their evolutions with respect to loop 1. The values of K2
1978 in the use in loop 2 vary independently on loop 1, thus we cannot express
1979 the evolution with respect to loop 1:
1980 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
1981 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
1982 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
1983 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
1984
1985 The value of k2 in the use in loop 1 is known, though:
1986 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
1987 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
1988 */
1989
1990 static tree
1991 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
1992 tree version, bool *folded_casts)
1993 {
1994 bool val = false;
1995 tree ev = version, tmp;
1996
1997 /* We cannot just do
1998
1999 tmp = analyze_scalar_evolution (use_loop, version);
2000 ev = resolve_mixers (wrto_loop, tmp);
2001
2002 as resolve_mixers would query the scalar evolution with respect to
2003 wrto_loop. For example, in the situation described in the function
2004 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2005 version = k2. Then
2006
2007 analyze_scalar_evolution (use_loop, version) = k2
2008
2009 and resolve_mixers (loop1, k2) finds that the value of k2 in loop 1
2010 is 100, which is a wrong result, since we are interested in the
2011 value in loop 3.
2012
2013 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2014 each time checking that there is no evolution in the inner loop. */
2015
2016 if (folded_casts)
2017 *folded_casts = false;
2018 while (1)
2019 {
2020 tmp = analyze_scalar_evolution (use_loop, ev);
2021 ev = resolve_mixers (use_loop, tmp);
2022
2023 if (folded_casts && tmp != ev)
2024 *folded_casts = true;
2025
2026 if (use_loop == wrto_loop)
2027 return ev;
2028
2029 /* If the value of the use changes in the inner loop, we cannot express
2030 its value in the outer loop (we might try to return interval chrec,
2031 but we do not have a user for it anyway) */
2032 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2033 || !val)
2034 return chrec_dont_know;
2035
2036 use_loop = loop_outer (use_loop);
2037 }
2038 }
2039
2040 /* Returns from CACHE the value for VERSION instantiated below
2041 INSTANTIATED_BELOW block. */
2042
2043 static tree
2044 get_instantiated_value (htab_t cache, basic_block instantiated_below,
2045 tree version)
2046 {
2047 struct scev_info_str *info, pattern;
2048
2049 pattern.var = version;
2050 pattern.instantiated_below = instantiated_below;
2051 info = (struct scev_info_str *) htab_find (cache, &pattern);
2052
2053 if (info)
2054 return info->chrec;
2055 else
2056 return NULL_TREE;
2057 }
2058
2059 /* Sets in CACHE the value of VERSION instantiated below basic block
2060 INSTANTIATED_BELOW to VAL. */
2061
2062 static void
2063 set_instantiated_value (htab_t cache, basic_block instantiated_below,
2064 tree version, tree val)
2065 {
2066 struct scev_info_str *info, pattern;
2067 PTR *slot;
2068
2069 pattern.var = version;
2070 pattern.instantiated_below = instantiated_below;
2071 slot = htab_find_slot (cache, &pattern, INSERT);
2072
2073 if (!*slot)
2074 *slot = new_scev_info_str (instantiated_below, version);
2075 info = (struct scev_info_str *) *slot;
2076 info->chrec = val;
2077 }
2078
2079 /* Return the closed_loop_phi node for VAR. If there is none, return
2080 NULL_TREE. */
2081
2082 static tree
2083 loop_closed_phi_def (tree var)
2084 {
2085 struct loop *loop;
2086 edge exit;
2087 gimple phi;
2088 gimple_stmt_iterator psi;
2089
2090 if (var == NULL_TREE
2091 || TREE_CODE (var) != SSA_NAME)
2092 return NULL_TREE;
2093
2094 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2095 exit = single_exit (loop);
2096 if (!exit)
2097 return NULL_TREE;
2098
2099 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2100 {
2101 phi = gsi_stmt (psi);
2102 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2103 return PHI_RESULT (phi);
2104 }
2105
2106 return NULL_TREE;
2107 }
2108
2109 static tree instantiate_scev_r (basic_block, struct loop *, tree, bool,
2110 htab_t, int);
2111
2112 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2113 and EVOLUTION_LOOP, that were left under a symbolic form.
2114
2115 CHREC is an SSA_NAME to be instantiated.
2116
2117 CACHE is the cache of already instantiated values.
2118
2119 FOLD_CONVERSIONS should be set to true when the conversions that
2120 may wrap in signed/pointer type are folded, as long as the value of
2121 the chrec is preserved.
2122
2123 SIZE_EXPR is used for computing the size of the expression to be
2124 instantiated, and to stop if it exceeds some limit. */
2125
2126 static tree
2127 instantiate_scev_name (basic_block instantiate_below,
2128 struct loop *evolution_loop, tree chrec,
2129 bool fold_conversions, htab_t cache, int size_expr)
2130 {
2131 tree res;
2132 struct loop *def_loop;
2133 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2134
2135 /* A parameter (or loop invariant and we do not want to include
2136 evolutions in outer loops), nothing to do. */
2137 if (!def_bb
2138 || loop_depth (def_bb->loop_father) == 0
2139 || dominated_by_p (CDI_DOMINATORS, instantiate_below, def_bb))
2140 return chrec;
2141
2142 /* We cache the value of instantiated variable to avoid exponential
2143 time complexity due to reevaluations. We also store the convenient
2144 value in the cache in order to prevent infinite recursion -- we do
2145 not want to instantiate the SSA_NAME if it is in a mixer
2146 structure. This is used for avoiding the instantiation of
2147 recursively defined functions, such as:
2148
2149 | a_2 -> {0, +, 1, +, a_2}_1 */
2150
2151 res = get_instantiated_value (cache, instantiate_below, chrec);
2152 if (res)
2153 return res;
2154
2155 res = chrec_dont_know;
2156 set_instantiated_value (cache, instantiate_below, chrec, res);
2157
2158 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2159
2160 /* If the analysis yields a parametric chrec, instantiate the
2161 result again. */
2162 res = analyze_scalar_evolution (def_loop, chrec);
2163
2164 /* Don't instantiate loop-closed-ssa phi nodes. */
2165 if (TREE_CODE (res) == SSA_NAME
2166 && (loop_containing_stmt (SSA_NAME_DEF_STMT (res)) == NULL
2167 || (loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2168 > loop_depth (def_loop))))
2169 {
2170 if (res == chrec)
2171 res = loop_closed_phi_def (chrec);
2172 else
2173 res = chrec;
2174
2175 /* When there is no loop_closed_phi_def, it means that the
2176 variable is not used after the loop: try to still compute the
2177 value of the variable when exiting the loop. */
2178 if (res == NULL_TREE)
2179 {
2180 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2181 res = analyze_scalar_evolution (loop, chrec);
2182 res = compute_overall_effect_of_inner_loop (loop, res);
2183 res = instantiate_scev_r (instantiate_below, evolution_loop, res,
2184 fold_conversions, cache, size_expr);
2185 }
2186 else if (!dominated_by_p (CDI_DOMINATORS, instantiate_below,
2187 gimple_bb (SSA_NAME_DEF_STMT (res))))
2188 res = chrec_dont_know;
2189 }
2190
2191 else if (res != chrec_dont_know)
2192 res = instantiate_scev_r (instantiate_below, evolution_loop, res,
2193 fold_conversions, cache, size_expr);
2194
2195 /* Store the correct value to the cache. */
2196 set_instantiated_value (cache, instantiate_below, chrec, res);
2197 return res;
2198
2199 }
2200
2201 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2202 and EVOLUTION_LOOP, that were left under a symbolic form.
2203
2204 CHREC is a polynomial chain of recurrence to be instantiated.
2205
2206 CACHE is the cache of already instantiated values.
2207
2208 FOLD_CONVERSIONS should be set to true when the conversions that
2209 may wrap in signed/pointer type are folded, as long as the value of
2210 the chrec is preserved.
2211
2212 SIZE_EXPR is used for computing the size of the expression to be
2213 instantiated, and to stop if it exceeds some limit. */
2214
2215 static tree
2216 instantiate_scev_poly (basic_block instantiate_below,
2217 struct loop *evolution_loop, tree chrec,
2218 bool fold_conversions, htab_t cache, int size_expr)
2219 {
2220 tree op1;
2221 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2222 CHREC_LEFT (chrec), fold_conversions, cache,
2223 size_expr);
2224 if (op0 == chrec_dont_know)
2225 return chrec_dont_know;
2226
2227 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2228 CHREC_RIGHT (chrec), fold_conversions, cache,
2229 size_expr);
2230 if (op1 == chrec_dont_know)
2231 return chrec_dont_know;
2232
2233 if (CHREC_LEFT (chrec) != op0
2234 || CHREC_RIGHT (chrec) != op1)
2235 {
2236 unsigned var = CHREC_VARIABLE (chrec);
2237
2238 /* When the instantiated stride or base has an evolution in an
2239 innermost loop, return chrec_dont_know, as this is not a
2240 valid SCEV representation. In the reduced testcase for
2241 PR40281 we would have {0, +, {1, +, 1}_2}_1 that has no
2242 meaning. */
2243 if ((tree_is_chrec (op0) && CHREC_VARIABLE (op0) > var)
2244 || (tree_is_chrec (op1) && CHREC_VARIABLE (op1) > var))
2245 return chrec_dont_know;
2246
2247 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2248 chrec = build_polynomial_chrec (var, op0, op1);
2249 }
2250
2251 return chrec;
2252 }
2253
2254 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2255 and EVOLUTION_LOOP, that were left under a symbolic form.
2256
2257 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2258
2259 CACHE is the cache of already instantiated values.
2260
2261 FOLD_CONVERSIONS should be set to true when the conversions that
2262 may wrap in signed/pointer type are folded, as long as the value of
2263 the chrec is preserved.
2264
2265 SIZE_EXPR is used for computing the size of the expression to be
2266 instantiated, and to stop if it exceeds some limit. */
2267
2268 static tree
2269 instantiate_scev_binary (basic_block instantiate_below,
2270 struct loop *evolution_loop, tree chrec, enum tree_code code,
2271 tree type, tree c0, tree c1,
2272 bool fold_conversions, htab_t cache, int size_expr)
2273 {
2274 tree op1;
2275 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2276 c0, fold_conversions, cache,
2277 size_expr);
2278 if (op0 == chrec_dont_know)
2279 return chrec_dont_know;
2280
2281 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2282 c1, fold_conversions, cache,
2283 size_expr);
2284 if (op1 == chrec_dont_know)
2285 return chrec_dont_know;
2286
2287 if (c0 != op0
2288 || c1 != op1)
2289 {
2290 op0 = chrec_convert (type, op0, NULL);
2291 op1 = chrec_convert_rhs (type, op1, NULL);
2292
2293 switch (code)
2294 {
2295 case POINTER_PLUS_EXPR:
2296 case PLUS_EXPR:
2297 return chrec_fold_plus (type, op0, op1);
2298
2299 case MINUS_EXPR:
2300 return chrec_fold_minus (type, op0, op1);
2301
2302 case MULT_EXPR:
2303 return chrec_fold_multiply (type, op0, op1);
2304
2305 default:
2306 gcc_unreachable ();
2307 }
2308 }
2309
2310 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2311 }
2312
2313 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2314 and EVOLUTION_LOOP, that were left under a symbolic form.
2315
2316 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2317 instantiated.
2318
2319 CACHE is the cache of already instantiated values.
2320
2321 FOLD_CONVERSIONS should be set to true when the conversions that
2322 may wrap in signed/pointer type are folded, as long as the value of
2323 the chrec is preserved.
2324
2325 SIZE_EXPR is used for computing the size of the expression to be
2326 instantiated, and to stop if it exceeds some limit. */
2327
2328 static tree
2329 instantiate_scev_convert (basic_block instantiate_below,
2330 struct loop *evolution_loop, tree chrec,
2331 tree type, tree op,
2332 bool fold_conversions, htab_t cache, int size_expr)
2333 {
2334 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, op,
2335 fold_conversions, cache, size_expr);
2336
2337 if (op0 == chrec_dont_know)
2338 return chrec_dont_know;
2339
2340 if (fold_conversions)
2341 {
2342 tree tmp = chrec_convert_aggressive (type, op0);
2343 if (tmp)
2344 return tmp;
2345 }
2346
2347 if (chrec && op0 == op)
2348 return chrec;
2349
2350 /* If we used chrec_convert_aggressive, we can no longer assume that
2351 signed chrecs do not overflow, as chrec_convert does, so avoid
2352 calling it in that case. */
2353 if (fold_conversions)
2354 return fold_convert (type, op0);
2355
2356 return chrec_convert (type, op0, NULL);
2357 }
2358
2359 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2360 and EVOLUTION_LOOP, that were left under a symbolic form.
2361
2362 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2363 Handle ~X as -1 - X.
2364 Handle -X as -1 * X.
2365
2366 CACHE is the cache of already instantiated values.
2367
2368 FOLD_CONVERSIONS should be set to true when the conversions that
2369 may wrap in signed/pointer type are folded, as long as the value of
2370 the chrec is preserved.
2371
2372 SIZE_EXPR is used for computing the size of the expression to be
2373 instantiated, and to stop if it exceeds some limit. */
2374
2375 static tree
2376 instantiate_scev_not (basic_block instantiate_below,
2377 struct loop *evolution_loop, tree chrec,
2378 enum tree_code code, tree type, tree op,
2379 bool fold_conversions, htab_t cache, int size_expr)
2380 {
2381 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, op,
2382 fold_conversions, cache, size_expr);
2383
2384 if (op0 == chrec_dont_know)
2385 return chrec_dont_know;
2386
2387 if (op != op0)
2388 {
2389 op0 = chrec_convert (type, op0, NULL);
2390
2391 switch (code)
2392 {
2393 case BIT_NOT_EXPR:
2394 return chrec_fold_minus
2395 (type, fold_convert (type, integer_minus_one_node), op0);
2396
2397 case NEGATE_EXPR:
2398 return chrec_fold_multiply
2399 (type, fold_convert (type, integer_minus_one_node), op0);
2400
2401 default:
2402 gcc_unreachable ();
2403 }
2404 }
2405
2406 return chrec ? chrec : fold_build1 (code, type, op0);
2407 }
2408
2409 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2410 and EVOLUTION_LOOP, that were left under a symbolic form.
2411
2412 CHREC is an expression with 3 operands to be instantiated.
2413
2414 CACHE is the cache of already instantiated values.
2415
2416 FOLD_CONVERSIONS should be set to true when the conversions that
2417 may wrap in signed/pointer type are folded, as long as the value of
2418 the chrec is preserved.
2419
2420 SIZE_EXPR is used for computing the size of the expression to be
2421 instantiated, and to stop if it exceeds some limit. */
2422
2423 static tree
2424 instantiate_scev_3 (basic_block instantiate_below,
2425 struct loop *evolution_loop, tree chrec,
2426 bool fold_conversions, htab_t cache, int size_expr)
2427 {
2428 tree op1, op2;
2429 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2430 TREE_OPERAND (chrec, 0),
2431 fold_conversions, cache, size_expr);
2432 if (op0 == chrec_dont_know)
2433 return chrec_dont_know;
2434
2435 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2436 TREE_OPERAND (chrec, 1),
2437 fold_conversions, cache, size_expr);
2438 if (op1 == chrec_dont_know)
2439 return chrec_dont_know;
2440
2441 op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2442 TREE_OPERAND (chrec, 2),
2443 fold_conversions, cache, size_expr);
2444 if (op2 == chrec_dont_know)
2445 return chrec_dont_know;
2446
2447 if (op0 == TREE_OPERAND (chrec, 0)
2448 && op1 == TREE_OPERAND (chrec, 1)
2449 && op2 == TREE_OPERAND (chrec, 2))
2450 return chrec;
2451
2452 return fold_build3 (TREE_CODE (chrec),
2453 TREE_TYPE (chrec), op0, op1, op2);
2454 }
2455
2456 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2457 and EVOLUTION_LOOP, that were left under a symbolic form.
2458
2459 CHREC is an expression with 2 operands to be instantiated.
2460
2461 CACHE is the cache of already instantiated values.
2462
2463 FOLD_CONVERSIONS should be set to true when the conversions that
2464 may wrap in signed/pointer type are folded, as long as the value of
2465 the chrec is preserved.
2466
2467 SIZE_EXPR is used for computing the size of the expression to be
2468 instantiated, and to stop if it exceeds some limit. */
2469
2470 static tree
2471 instantiate_scev_2 (basic_block instantiate_below,
2472 struct loop *evolution_loop, tree chrec,
2473 bool fold_conversions, htab_t cache, int size_expr)
2474 {
2475 tree op1;
2476 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2477 TREE_OPERAND (chrec, 0),
2478 fold_conversions, cache, size_expr);
2479 if (op0 == chrec_dont_know)
2480 return chrec_dont_know;
2481
2482 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2483 TREE_OPERAND (chrec, 1),
2484 fold_conversions, cache, size_expr);
2485 if (op1 == chrec_dont_know)
2486 return chrec_dont_know;
2487
2488 if (op0 == TREE_OPERAND (chrec, 0)
2489 && op1 == TREE_OPERAND (chrec, 1))
2490 return chrec;
2491
2492 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2493 }
2494
2495 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2496 and EVOLUTION_LOOP, that were left under a symbolic form.
2497
2498 CHREC is an expression with 2 operands to be instantiated.
2499
2500 CACHE is the cache of already instantiated values.
2501
2502 FOLD_CONVERSIONS should be set to true when the conversions that
2503 may wrap in signed/pointer type are folded, as long as the value of
2504 the chrec is preserved.
2505
2506 SIZE_EXPR is used for computing the size of the expression to be
2507 instantiated, and to stop if it exceeds some limit. */
2508
2509 static tree
2510 instantiate_scev_1 (basic_block instantiate_below,
2511 struct loop *evolution_loop, tree chrec,
2512 bool fold_conversions, htab_t cache, int size_expr)
2513 {
2514 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2515 TREE_OPERAND (chrec, 0),
2516 fold_conversions, cache, size_expr);
2517
2518 if (op0 == chrec_dont_know)
2519 return chrec_dont_know;
2520
2521 if (op0 == TREE_OPERAND (chrec, 0))
2522 return chrec;
2523
2524 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2525 }
2526
2527 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2528 and EVOLUTION_LOOP, that were left under a symbolic form.
2529
2530 CHREC is the scalar evolution to instantiate.
2531
2532 CACHE is the cache of already instantiated values.
2533
2534 FOLD_CONVERSIONS should be set to true when the conversions that
2535 may wrap in signed/pointer type are folded, as long as the value of
2536 the chrec is preserved.
2537
2538 SIZE_EXPR is used for computing the size of the expression to be
2539 instantiated, and to stop if it exceeds some limit. */
2540
2541 static tree
2542 instantiate_scev_r (basic_block instantiate_below,
2543 struct loop *evolution_loop, tree chrec,
2544 bool fold_conversions, htab_t cache, int size_expr)
2545 {
2546 /* Give up if the expression is larger than the MAX that we allow. */
2547 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2548 return chrec_dont_know;
2549
2550 if (automatically_generated_chrec_p (chrec)
2551 || is_gimple_min_invariant (chrec))
2552 return chrec;
2553
2554 switch (TREE_CODE (chrec))
2555 {
2556 case SSA_NAME:
2557 return instantiate_scev_name (instantiate_below, evolution_loop, chrec,
2558 fold_conversions, cache, size_expr);
2559
2560 case POLYNOMIAL_CHREC:
2561 return instantiate_scev_poly (instantiate_below, evolution_loop, chrec,
2562 fold_conversions, cache, size_expr);
2563
2564 case POINTER_PLUS_EXPR:
2565 case PLUS_EXPR:
2566 case MINUS_EXPR:
2567 case MULT_EXPR:
2568 return instantiate_scev_binary (instantiate_below, evolution_loop, chrec,
2569 TREE_CODE (chrec), chrec_type (chrec),
2570 TREE_OPERAND (chrec, 0),
2571 TREE_OPERAND (chrec, 1),
2572 fold_conversions, cache, size_expr);
2573
2574 CASE_CONVERT:
2575 return instantiate_scev_convert (instantiate_below, evolution_loop, chrec,
2576 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2577 fold_conversions, cache, size_expr);
2578
2579 case NEGATE_EXPR:
2580 case BIT_NOT_EXPR:
2581 return instantiate_scev_not (instantiate_below, evolution_loop, chrec,
2582 TREE_CODE (chrec), TREE_TYPE (chrec),
2583 TREE_OPERAND (chrec, 0),
2584 fold_conversions, cache, size_expr);
2585
2586 case SCEV_NOT_KNOWN:
2587 return chrec_dont_know;
2588
2589 case SCEV_KNOWN:
2590 return chrec_known;
2591
2592 default:
2593 break;
2594 }
2595
2596 if (VL_EXP_CLASS_P (chrec))
2597 return chrec_dont_know;
2598
2599 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2600 {
2601 case 3:
2602 return instantiate_scev_3 (instantiate_below, evolution_loop, chrec,
2603 fold_conversions, cache, size_expr);
2604
2605 case 2:
2606 return instantiate_scev_2 (instantiate_below, evolution_loop, chrec,
2607 fold_conversions, cache, size_expr);
2608
2609 case 1:
2610 return instantiate_scev_1 (instantiate_below, evolution_loop, chrec,
2611 fold_conversions, cache, size_expr);
2612
2613 case 0:
2614 return chrec;
2615
2616 default:
2617 break;
2618 }
2619
2620 /* Too complicated to handle. */
2621 return chrec_dont_know;
2622 }
2623
2624 /* Analyze all the parameters of the chrec that were left under a
2625 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2626 recursive instantiation of parameters: a parameter is a variable
2627 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2628 a function parameter. */
2629
2630 tree
2631 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2632 tree chrec)
2633 {
2634 tree res;
2635 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2636
2637 if (dump_file && (dump_flags & TDF_DETAILS))
2638 {
2639 fprintf (dump_file, "(instantiate_scev \n");
2640 fprintf (dump_file, " (instantiate_below = %d)\n", instantiate_below->index);
2641 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2642 fprintf (dump_file, " (chrec = ");
2643 print_generic_expr (dump_file, chrec, 0);
2644 fprintf (dump_file, ")\n");
2645 }
2646
2647 res = instantiate_scev_r (instantiate_below, evolution_loop, chrec, false,
2648 cache, 0);
2649
2650 if (dump_file && (dump_flags & TDF_DETAILS))
2651 {
2652 fprintf (dump_file, " (res = ");
2653 print_generic_expr (dump_file, res, 0);
2654 fprintf (dump_file, "))\n");
2655 }
2656
2657 htab_delete (cache);
2658
2659 return res;
2660 }
2661
2662 /* Similar to instantiate_parameters, but does not introduce the
2663 evolutions in outer loops for LOOP invariants in CHREC, and does not
2664 care about causing overflows, as long as they do not affect value
2665 of an expression. */
2666
2667 tree
2668 resolve_mixers (struct loop *loop, tree chrec)
2669 {
2670 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2671 tree ret = instantiate_scev_r (block_before_loop (loop), loop, chrec, true,
2672 cache, 0);
2673 htab_delete (cache);
2674 return ret;
2675 }
2676
2677 /* Entry point for the analysis of the number of iterations pass.
2678 This function tries to safely approximate the number of iterations
2679 the loop will run. When this property is not decidable at compile
2680 time, the result is chrec_dont_know. Otherwise the result is a
2681 scalar or a symbolic parameter. When the number of iterations may
2682 be equal to zero and the property cannot be determined at compile
2683 time, the result is a COND_EXPR that represents in a symbolic form
2684 the conditions under which the number of iterations is not zero.
2685
2686 Example of analysis: suppose that the loop has an exit condition:
2687
2688 "if (b > 49) goto end_loop;"
2689
2690 and that in a previous analysis we have determined that the
2691 variable 'b' has an evolution function:
2692
2693 "EF = {23, +, 5}_2".
2694
2695 When we evaluate the function at the point 5, i.e. the value of the
2696 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2697 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2698 the loop body has been executed 6 times. */
2699
2700 tree
2701 number_of_latch_executions (struct loop *loop)
2702 {
2703 edge exit;
2704 struct tree_niter_desc niter_desc;
2705 tree may_be_zero;
2706 tree res;
2707
2708 /* Determine whether the number of iterations in loop has already
2709 been computed. */
2710 res = loop->nb_iterations;
2711 if (res)
2712 return res;
2713
2714 may_be_zero = NULL_TREE;
2715
2716 if (dump_file && (dump_flags & TDF_DETAILS))
2717 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2718
2719 res = chrec_dont_know;
2720 exit = single_exit (loop);
2721
2722 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2723 {
2724 may_be_zero = niter_desc.may_be_zero;
2725 res = niter_desc.niter;
2726 }
2727
2728 if (res == chrec_dont_know
2729 || !may_be_zero
2730 || integer_zerop (may_be_zero))
2731 ;
2732 else if (integer_nonzerop (may_be_zero))
2733 res = build_int_cst (TREE_TYPE (res), 0);
2734
2735 else if (COMPARISON_CLASS_P (may_be_zero))
2736 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2737 build_int_cst (TREE_TYPE (res), 0), res);
2738 else
2739 res = chrec_dont_know;
2740
2741 if (dump_file && (dump_flags & TDF_DETAILS))
2742 {
2743 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2744 print_generic_expr (dump_file, res, 0);
2745 fprintf (dump_file, "))\n");
2746 }
2747
2748 loop->nb_iterations = res;
2749 return res;
2750 }
2751
2752 /* Returns the number of executions of the exit condition of LOOP,
2753 i.e., the number by one higher than number_of_latch_executions.
2754 Note that unlike number_of_latch_executions, this number does
2755 not necessarily fit in the unsigned variant of the type of
2756 the control variable -- if the number of iterations is a constant,
2757 we return chrec_dont_know if adding one to number_of_latch_executions
2758 overflows; however, in case the number of iterations is symbolic
2759 expression, the caller is responsible for dealing with this
2760 the possible overflow. */
2761
2762 tree
2763 number_of_exit_cond_executions (struct loop *loop)
2764 {
2765 tree ret = number_of_latch_executions (loop);
2766 tree type = chrec_type (ret);
2767
2768 if (chrec_contains_undetermined (ret))
2769 return ret;
2770
2771 ret = chrec_fold_plus (type, ret, build_int_cst (type, 1));
2772 if (TREE_CODE (ret) == INTEGER_CST
2773 && TREE_OVERFLOW (ret))
2774 return chrec_dont_know;
2775
2776 return ret;
2777 }
2778
2779 /* One of the drivers for testing the scalar evolutions analysis.
2780 This function computes the number of iterations for all the loops
2781 from the EXIT_CONDITIONS array. */
2782
2783 static void
2784 number_of_iterations_for_all_loops (VEC(gimple,heap) **exit_conditions)
2785 {
2786 unsigned int i;
2787 unsigned nb_chrec_dont_know_loops = 0;
2788 unsigned nb_static_loops = 0;
2789 gimple cond;
2790
2791 for (i = 0; VEC_iterate (gimple, *exit_conditions, i, cond); i++)
2792 {
2793 tree res = number_of_latch_executions (loop_containing_stmt (cond));
2794 if (chrec_contains_undetermined (res))
2795 nb_chrec_dont_know_loops++;
2796 else
2797 nb_static_loops++;
2798 }
2799
2800 if (dump_file)
2801 {
2802 fprintf (dump_file, "\n(\n");
2803 fprintf (dump_file, "-----------------------------------------\n");
2804 fprintf (dump_file, "%d\tnb_chrec_dont_know_loops\n", nb_chrec_dont_know_loops);
2805 fprintf (dump_file, "%d\tnb_static_loops\n", nb_static_loops);
2806 fprintf (dump_file, "%d\tnb_total_loops\n", number_of_loops ());
2807 fprintf (dump_file, "-----------------------------------------\n");
2808 fprintf (dump_file, ")\n\n");
2809
2810 print_loops (dump_file, 3);
2811 }
2812 }
2813
2814 \f
2815
2816 /* Counters for the stats. */
2817
2818 struct chrec_stats
2819 {
2820 unsigned nb_chrecs;
2821 unsigned nb_affine;
2822 unsigned nb_affine_multivar;
2823 unsigned nb_higher_poly;
2824 unsigned nb_chrec_dont_know;
2825 unsigned nb_undetermined;
2826 };
2827
2828 /* Reset the counters. */
2829
2830 static inline void
2831 reset_chrecs_counters (struct chrec_stats *stats)
2832 {
2833 stats->nb_chrecs = 0;
2834 stats->nb_affine = 0;
2835 stats->nb_affine_multivar = 0;
2836 stats->nb_higher_poly = 0;
2837 stats->nb_chrec_dont_know = 0;
2838 stats->nb_undetermined = 0;
2839 }
2840
2841 /* Dump the contents of a CHREC_STATS structure. */
2842
2843 static void
2844 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2845 {
2846 fprintf (file, "\n(\n");
2847 fprintf (file, "-----------------------------------------\n");
2848 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2849 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2850 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2851 stats->nb_higher_poly);
2852 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2853 fprintf (file, "-----------------------------------------\n");
2854 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2855 fprintf (file, "%d\twith undetermined coefficients\n",
2856 stats->nb_undetermined);
2857 fprintf (file, "-----------------------------------------\n");
2858 fprintf (file, "%d\tchrecs in the scev database\n",
2859 (int) htab_elements (scalar_evolution_info));
2860 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2861 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2862 fprintf (file, "-----------------------------------------\n");
2863 fprintf (file, ")\n\n");
2864 }
2865
2866 /* Gather statistics about CHREC. */
2867
2868 static void
2869 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2870 {
2871 if (dump_file && (dump_flags & TDF_STATS))
2872 {
2873 fprintf (dump_file, "(classify_chrec ");
2874 print_generic_expr (dump_file, chrec, 0);
2875 fprintf (dump_file, "\n");
2876 }
2877
2878 stats->nb_chrecs++;
2879
2880 if (chrec == NULL_TREE)
2881 {
2882 stats->nb_undetermined++;
2883 return;
2884 }
2885
2886 switch (TREE_CODE (chrec))
2887 {
2888 case POLYNOMIAL_CHREC:
2889 if (evolution_function_is_affine_p (chrec))
2890 {
2891 if (dump_file && (dump_flags & TDF_STATS))
2892 fprintf (dump_file, " affine_univariate\n");
2893 stats->nb_affine++;
2894 }
2895 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
2896 {
2897 if (dump_file && (dump_flags & TDF_STATS))
2898 fprintf (dump_file, " affine_multivariate\n");
2899 stats->nb_affine_multivar++;
2900 }
2901 else
2902 {
2903 if (dump_file && (dump_flags & TDF_STATS))
2904 fprintf (dump_file, " higher_degree_polynomial\n");
2905 stats->nb_higher_poly++;
2906 }
2907
2908 break;
2909
2910 default:
2911 break;
2912 }
2913
2914 if (chrec_contains_undetermined (chrec))
2915 {
2916 if (dump_file && (dump_flags & TDF_STATS))
2917 fprintf (dump_file, " undetermined\n");
2918 stats->nb_undetermined++;
2919 }
2920
2921 if (dump_file && (dump_flags & TDF_STATS))
2922 fprintf (dump_file, ")\n");
2923 }
2924
2925 /* One of the drivers for testing the scalar evolutions analysis.
2926 This function analyzes the scalar evolution of all the scalars
2927 defined as loop phi nodes in one of the loops from the
2928 EXIT_CONDITIONS array.
2929
2930 TODO Optimization: A loop is in canonical form if it contains only
2931 a single scalar loop phi node. All the other scalars that have an
2932 evolution in the loop are rewritten in function of this single
2933 index. This allows the parallelization of the loop. */
2934
2935 static void
2936 analyze_scalar_evolution_for_all_loop_phi_nodes (VEC(gimple,heap) **exit_conditions)
2937 {
2938 unsigned int i;
2939 struct chrec_stats stats;
2940 gimple cond, phi;
2941 gimple_stmt_iterator psi;
2942
2943 reset_chrecs_counters (&stats);
2944
2945 for (i = 0; VEC_iterate (gimple, *exit_conditions, i, cond); i++)
2946 {
2947 struct loop *loop;
2948 basic_block bb;
2949 tree chrec;
2950
2951 loop = loop_containing_stmt (cond);
2952 bb = loop->header;
2953
2954 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
2955 {
2956 phi = gsi_stmt (psi);
2957 if (is_gimple_reg (PHI_RESULT (phi)))
2958 {
2959 chrec = instantiate_parameters
2960 (loop,
2961 analyze_scalar_evolution (loop, PHI_RESULT (phi)));
2962
2963 if (dump_file && (dump_flags & TDF_STATS))
2964 gather_chrec_stats (chrec, &stats);
2965 }
2966 }
2967 }
2968
2969 if (dump_file && (dump_flags & TDF_STATS))
2970 dump_chrecs_stats (dump_file, &stats);
2971 }
2972
2973 /* Callback for htab_traverse, gathers information on chrecs in the
2974 hashtable. */
2975
2976 static int
2977 gather_stats_on_scev_database_1 (void **slot, void *stats)
2978 {
2979 struct scev_info_str *entry = (struct scev_info_str *) *slot;
2980
2981 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
2982
2983 return 1;
2984 }
2985
2986 /* Classify the chrecs of the whole database. */
2987
2988 void
2989 gather_stats_on_scev_database (void)
2990 {
2991 struct chrec_stats stats;
2992
2993 if (!dump_file)
2994 return;
2995
2996 reset_chrecs_counters (&stats);
2997
2998 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
2999 &stats);
3000
3001 dump_chrecs_stats (dump_file, &stats);
3002 }
3003
3004 \f
3005
3006 /* Initializer. */
3007
3008 static void
3009 initialize_scalar_evolutions_analyzer (void)
3010 {
3011 /* The elements below are unique. */
3012 if (chrec_dont_know == NULL_TREE)
3013 {
3014 chrec_not_analyzed_yet = NULL_TREE;
3015 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3016 chrec_known = make_node (SCEV_KNOWN);
3017 TREE_TYPE (chrec_dont_know) = void_type_node;
3018 TREE_TYPE (chrec_known) = void_type_node;
3019 }
3020 }
3021
3022 /* Initialize the analysis of scalar evolutions for LOOPS. */
3023
3024 void
3025 scev_initialize (void)
3026 {
3027 loop_iterator li;
3028 struct loop *loop;
3029
3030
3031 scalar_evolution_info = htab_create_ggc (100, hash_scev_info, eq_scev_info,
3032 del_scev_info);
3033
3034 initialize_scalar_evolutions_analyzer ();
3035
3036 FOR_EACH_LOOP (li, loop, 0)
3037 {
3038 loop->nb_iterations = NULL_TREE;
3039 }
3040 }
3041
3042 /* Cleans up the information cached by the scalar evolutions analysis
3043 in the hash table. */
3044
3045 void
3046 scev_reset_htab (void)
3047 {
3048 if (!scalar_evolution_info)
3049 return;
3050
3051 htab_empty (scalar_evolution_info);
3052 }
3053
3054 /* Cleans up the information cached by the scalar evolutions analysis
3055 in the hash table and in the loop->nb_iterations. */
3056
3057 void
3058 scev_reset (void)
3059 {
3060 loop_iterator li;
3061 struct loop *loop;
3062
3063 scev_reset_htab ();
3064
3065 if (!current_loops)
3066 return;
3067
3068 FOR_EACH_LOOP (li, loop, 0)
3069 {
3070 loop->nb_iterations = NULL_TREE;
3071 }
3072 }
3073
3074 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3075 respect to WRTO_LOOP and returns its base and step in IV if possible
3076 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3077 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3078 invariant in LOOP. Otherwise we require it to be an integer constant.
3079
3080 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3081 because it is computed in signed arithmetics). Consequently, adding an
3082 induction variable
3083
3084 for (i = IV->base; ; i += IV->step)
3085
3086 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3087 false for the type of the induction variable, or you can prove that i does
3088 not wrap by some other argument. Otherwise, this might introduce undefined
3089 behavior, and
3090
3091 for (i = iv->base; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3092
3093 must be used instead. */
3094
3095 bool
3096 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3097 affine_iv *iv, bool allow_nonconstant_step)
3098 {
3099 tree type, ev;
3100 bool folded_casts;
3101
3102 iv->base = NULL_TREE;
3103 iv->step = NULL_TREE;
3104 iv->no_overflow = false;
3105
3106 type = TREE_TYPE (op);
3107 if (TREE_CODE (type) != INTEGER_TYPE
3108 && TREE_CODE (type) != POINTER_TYPE)
3109 return false;
3110
3111 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3112 &folded_casts);
3113 if (chrec_contains_undetermined (ev)
3114 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3115 return false;
3116
3117 if (tree_does_not_contain_chrecs (ev))
3118 {
3119 iv->base = ev;
3120 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3121 iv->no_overflow = true;
3122 return true;
3123 }
3124
3125 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
3126 || CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3127 return false;
3128
3129 iv->step = CHREC_RIGHT (ev);
3130 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3131 || tree_contains_chrecs (iv->step, NULL))
3132 return false;
3133
3134 iv->base = CHREC_LEFT (ev);
3135 if (tree_contains_chrecs (iv->base, NULL))
3136 return false;
3137
3138 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
3139
3140 return true;
3141 }
3142
3143 /* Runs the analysis of scalar evolutions. */
3144
3145 void
3146 scev_analysis (void)
3147 {
3148 VEC(gimple,heap) *exit_conditions;
3149
3150 exit_conditions = VEC_alloc (gimple, heap, 37);
3151 select_loops_exit_conditions (&exit_conditions);
3152
3153 if (dump_file && (dump_flags & TDF_STATS))
3154 analyze_scalar_evolution_for_all_loop_phi_nodes (&exit_conditions);
3155
3156 number_of_iterations_for_all_loops (&exit_conditions);
3157 VEC_free (gimple, heap, exit_conditions);
3158 }
3159
3160 /* Finalize the scalar evolution analysis. */
3161
3162 void
3163 scev_finalize (void)
3164 {
3165 if (!scalar_evolution_info)
3166 return;
3167 htab_delete (scalar_evolution_info);
3168 scalar_evolution_info = NULL;
3169 }
3170
3171 /* Returns true if the expression EXPR is considered to be too expensive
3172 for scev_const_prop. */
3173
3174 bool
3175 expression_expensive_p (tree expr)
3176 {
3177 enum tree_code code;
3178
3179 if (is_gimple_val (expr))
3180 return false;
3181
3182 code = TREE_CODE (expr);
3183 if (code == TRUNC_DIV_EXPR
3184 || code == CEIL_DIV_EXPR
3185 || code == FLOOR_DIV_EXPR
3186 || code == ROUND_DIV_EXPR
3187 || code == TRUNC_MOD_EXPR
3188 || code == CEIL_MOD_EXPR
3189 || code == FLOOR_MOD_EXPR
3190 || code == ROUND_MOD_EXPR
3191 || code == EXACT_DIV_EXPR)
3192 {
3193 /* Division by power of two is usually cheap, so we allow it.
3194 Forbid anything else. */
3195 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3196 return true;
3197 }
3198
3199 switch (TREE_CODE_CLASS (code))
3200 {
3201 case tcc_binary:
3202 case tcc_comparison:
3203 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3204 return true;
3205
3206 /* Fallthru. */
3207 case tcc_unary:
3208 return expression_expensive_p (TREE_OPERAND (expr, 0));
3209
3210 default:
3211 return true;
3212 }
3213 }
3214
3215 /* Replace ssa names for that scev can prove they are constant by the
3216 appropriate constants. Also perform final value replacement in loops,
3217 in case the replacement expressions are cheap.
3218
3219 We only consider SSA names defined by phi nodes; rest is left to the
3220 ordinary constant propagation pass. */
3221
3222 unsigned int
3223 scev_const_prop (void)
3224 {
3225 basic_block bb;
3226 tree name, type, ev;
3227 gimple phi, ass;
3228 struct loop *loop, *ex_loop;
3229 bitmap ssa_names_to_remove = NULL;
3230 unsigned i;
3231 loop_iterator li;
3232 gimple_stmt_iterator psi;
3233
3234 if (number_of_loops () <= 1)
3235 return 0;
3236
3237 FOR_EACH_BB (bb)
3238 {
3239 loop = bb->loop_father;
3240
3241 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3242 {
3243 phi = gsi_stmt (psi);
3244 name = PHI_RESULT (phi);
3245
3246 if (!is_gimple_reg (name))
3247 continue;
3248
3249 type = TREE_TYPE (name);
3250
3251 if (!POINTER_TYPE_P (type)
3252 && !INTEGRAL_TYPE_P (type))
3253 continue;
3254
3255 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
3256 if (!is_gimple_min_invariant (ev)
3257 || !may_propagate_copy (name, ev))
3258 continue;
3259
3260 /* Replace the uses of the name. */
3261 if (name != ev)
3262 replace_uses_by (name, ev);
3263
3264 if (!ssa_names_to_remove)
3265 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3266 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3267 }
3268 }
3269
3270 /* Remove the ssa names that were replaced by constants. We do not
3271 remove them directly in the previous cycle, since this
3272 invalidates scev cache. */
3273 if (ssa_names_to_remove)
3274 {
3275 bitmap_iterator bi;
3276
3277 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3278 {
3279 gimple_stmt_iterator psi;
3280 name = ssa_name (i);
3281 phi = SSA_NAME_DEF_STMT (name);
3282
3283 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3284 psi = gsi_for_stmt (phi);
3285 remove_phi_node (&psi, true);
3286 }
3287
3288 BITMAP_FREE (ssa_names_to_remove);
3289 scev_reset ();
3290 }
3291
3292 /* Now the regular final value replacement. */
3293 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
3294 {
3295 edge exit;
3296 tree def, rslt, niter;
3297 gimple_stmt_iterator bsi;
3298
3299 /* If we do not know exact number of iterations of the loop, we cannot
3300 replace the final value. */
3301 exit = single_exit (loop);
3302 if (!exit)
3303 continue;
3304
3305 niter = number_of_latch_executions (loop);
3306 if (niter == chrec_dont_know)
3307 continue;
3308
3309 /* Ensure that it is possible to insert new statements somewhere. */
3310 if (!single_pred_p (exit->dest))
3311 split_loop_exit_edge (exit);
3312 bsi = gsi_after_labels (exit->dest);
3313
3314 ex_loop = superloop_at_depth (loop,
3315 loop_depth (exit->dest->loop_father) + 1);
3316
3317 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3318 {
3319 phi = gsi_stmt (psi);
3320 rslt = PHI_RESULT (phi);
3321 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3322 if (!is_gimple_reg (def))
3323 {
3324 gsi_next (&psi);
3325 continue;
3326 }
3327
3328 if (!POINTER_TYPE_P (TREE_TYPE (def))
3329 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3330 {
3331 gsi_next (&psi);
3332 continue;
3333 }
3334
3335 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def, NULL);
3336 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3337 if (!tree_does_not_contain_chrecs (def)
3338 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3339 /* Moving the computation from the loop may prolong life range
3340 of some ssa names, which may cause problems if they appear
3341 on abnormal edges. */
3342 || contains_abnormal_ssa_name_p (def)
3343 /* Do not emit expensive expressions. The rationale is that
3344 when someone writes a code like
3345
3346 while (n > 45) n -= 45;
3347
3348 he probably knows that n is not large, and does not want it
3349 to be turned into n %= 45. */
3350 || expression_expensive_p (def))
3351 {
3352 gsi_next (&psi);
3353 continue;
3354 }
3355
3356 /* Eliminate the PHI node and replace it by a computation outside
3357 the loop. */
3358 def = unshare_expr (def);
3359 remove_phi_node (&psi, false);
3360
3361 def = force_gimple_operand_gsi (&bsi, def, false, NULL_TREE,
3362 true, GSI_SAME_STMT);
3363 ass = gimple_build_assign (rslt, def);
3364 gsi_insert_before (&bsi, ass, GSI_SAME_STMT);
3365 }
3366 }
3367 return 0;
3368 }
3369
3370 #include "gt-tree-scalar-evolution.h"