OSDN Git Service

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