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