OSDN Git Service

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