OSDN Git Service

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