OSDN Git Service

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