OSDN Git Service

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