OSDN Git Service

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