OSDN Git Service

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