Fix PR312 and IndVarsSimplify/2004-04-05-InvokeCastCrash.llx
[oota-llvm.git] / lib / Analysis / ScalarEvolution.cpp
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle.  These classes are reference counted, managed by the SCEVHandle
18 // class.  We only create one SCEV of a particular shape, so pointer-comparisons
19 // for equality are legal.
20 //
21 // One important aspect of the SCEV objects is that they are never cyclic, even
22 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
24 // recurrence) then we represent it directly as a recurrence node, otherwise we
25 // represent it as a SCEVUnknown node.
26 //
27 // In addition to being able to represent expressions of various types, we also
28 // have folders that are used to build the *canonical* representation for a
29 // particular expression.  These folders are capable of using a variety of
30 // rewrite rules to simplify the expressions.
31 // 
32 // Once the folders are defined, we can implement the more interesting
33 // higher-level code, such as the code that recognizes PHI nodes of various
34 // types, computes the execution count of a loop, etc.
35 //
36 // Orthogonal to the analysis of code above, this file also implements the
37 // ScalarEvolutionRewriter class, which is used to emit code that represents the
38 // various recurrences present in a loop, in canonical forms.
39 //
40 // TODO: We should use these routines and value representations to implement
41 // dependence analysis!
42 //
43 //===----------------------------------------------------------------------===//
44 //
45 // There are several good references for the techniques used in this analysis.
46 //
47 //  Chains of recurrences -- a method to expedite the evaluation
48 //  of closed-form functions
49 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
50 //
51 //  On computational properties of chains of recurrences
52 //  Eugene V. Zima
53 //
54 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
55 //  Robert A. van Engelen
56 //
57 //  Efficient Symbolic Analysis for Optimizing Compilers
58 //  Robert A. van Engelen
59 //
60 //  Using the chains of recurrences algebra for data dependence testing and
61 //  induction variable substitution
62 //  MS Thesis, Johnie Birch
63 //
64 //===----------------------------------------------------------------------===//
65
66 #include "llvm/Analysis/ScalarEvolution.h"
67 #include "llvm/Constants.h"
68 #include "llvm/DerivedTypes.h"
69 #include "llvm/Instructions.h"
70 #include "llvm/Type.h"
71 #include "llvm/Value.h"
72 #include "llvm/Analysis/LoopInfo.h"
73 #include "llvm/Assembly/Writer.h"
74 #include "llvm/Transforms/Scalar.h"
75 #include "llvm/Support/CFG.h"
76 #include "llvm/Support/ConstantRange.h"
77 #include "llvm/Support/InstIterator.h"
78 #include "Support/Statistic.h"
79 using namespace llvm;
80
81 namespace {
82   RegisterAnalysis<ScalarEvolution>
83   R("scalar-evolution", "Scalar Evolution Analysis Printer");
84
85   Statistic<>
86   NumBruteForceEvaluations("scalar-evolution",
87                            "Number of brute force evaluations needed to calculate high-order polynomial exit values");
88   Statistic<>
89   NumTripCountsComputed("scalar-evolution",
90                         "Number of loops with predictable loop counts");
91   Statistic<>
92   NumTripCountsNotComputed("scalar-evolution",
93                            "Number of loops without predictable loop counts");
94 }
95
96 //===----------------------------------------------------------------------===//
97 //                           SCEV class definitions
98 //===----------------------------------------------------------------------===//
99
100 //===----------------------------------------------------------------------===//
101 // Implementation of the SCEV class.
102 //
103 namespace {
104   enum SCEVTypes {
105     // These should be ordered in terms of increasing complexity to make the
106     // folders simpler.
107     scConstant, scTruncate, scZeroExtend, scAddExpr, scMulExpr, scUDivExpr,
108     scAddRecExpr, scUnknown, scCouldNotCompute
109   };
110
111   /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
112   /// than the complexity of the RHS.  If the SCEVs have identical complexity,
113   /// order them by their addresses.  This comparator is used to canonicalize
114   /// expressions.
115   struct SCEVComplexityCompare {
116     bool operator()(SCEV *LHS, SCEV *RHS) {
117       if (LHS->getSCEVType() < RHS->getSCEVType())
118         return true;
119       if (LHS->getSCEVType() == RHS->getSCEVType())
120         return LHS < RHS;
121       return false;
122     }
123   };
124 }
125
126 SCEV::~SCEV() {}
127 void SCEV::dump() const {
128   print(std::cerr);
129 }
130
131 /// getValueRange - Return the tightest constant bounds that this value is
132 /// known to have.  This method is only valid on integer SCEV objects.
133 ConstantRange SCEV::getValueRange() const {
134   const Type *Ty = getType();
135   assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
136   Ty = Ty->getUnsignedVersion();
137   // Default to a full range if no better information is available.
138   return ConstantRange(getType());
139 }
140
141
142 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
143
144 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
145   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 }
147
148 const Type *SCEVCouldNotCompute::getType() const {
149   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 }
151
152 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
153   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
154   return false;
155 }
156
157 Value *SCEVCouldNotCompute::expandCodeFor(ScalarEvolutionRewriter &SER,
158                                           Instruction *InsertPt) {
159   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
160   return 0;
161 }
162
163
164 void SCEVCouldNotCompute::print(std::ostream &OS) const {
165   OS << "***COULDNOTCOMPUTE***";
166 }
167
168 bool SCEVCouldNotCompute::classof(const SCEV *S) {
169   return S->getSCEVType() == scCouldNotCompute;
170 }
171
172
173 //===----------------------------------------------------------------------===//
174 // SCEVConstant - This class represents a constant integer value.
175 //
176 namespace {
177   class SCEVConstant;
178   // SCEVConstants - Only allow the creation of one SCEVConstant for any
179   // particular value.  Don't use a SCEVHandle here, or else the object will
180   // never be deleted!
181   std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
182
183   class SCEVConstant : public SCEV {
184     ConstantInt *V;
185     SCEVConstant(ConstantInt *v) : SCEV(scConstant), V(v) {}
186
187     virtual ~SCEVConstant() {
188       SCEVConstants.erase(V);
189     }
190   public:
191     /// get method - This just gets and returns a new SCEVConstant object.
192     ///
193     static SCEVHandle get(ConstantInt *V) {
194       // Make sure that SCEVConstant instances are all unsigned.
195       if (V->getType()->isSigned()) {
196         const Type *NewTy = V->getType()->getUnsignedVersion();
197         V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
198       }
199
200       SCEVConstant *&R = SCEVConstants[V];
201       if (R == 0) R = new SCEVConstant(V);
202       return R;
203     }
204
205     ConstantInt *getValue() const { return V; }
206
207     /// getValueRange - Return the tightest constant bounds that this value is
208     /// known to have.  This method is only valid on integer SCEV objects.
209     virtual ConstantRange getValueRange() const {
210       return ConstantRange(V);
211     }
212
213     virtual bool isLoopInvariant(const Loop *L) const {
214       return true;
215     }
216
217     virtual bool hasComputableLoopEvolution(const Loop *L) const {
218       return false;  // Not loop variant
219     }
220
221     virtual const Type *getType() const { return V->getType(); }
222
223     Value *expandCodeFor(ScalarEvolutionRewriter &SER,
224                          Instruction *InsertPt) {
225       return getValue();
226     }
227     
228     virtual void print(std::ostream &OS) const {
229       WriteAsOperand(OS, V, false);
230     }
231
232     /// Methods for support type inquiry through isa, cast, and dyn_cast:
233     static inline bool classof(const SCEVConstant *S) { return true; }
234     static inline bool classof(const SCEV *S) {
235       return S->getSCEVType() == scConstant;
236     }
237   };
238 }
239
240
241 //===----------------------------------------------------------------------===//
242 // SCEVTruncateExpr - This class represents a truncation of an integer value to
243 // a smaller integer value.
244 //
245 namespace {
246   class SCEVTruncateExpr;
247   // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
248   // particular input.  Don't use a SCEVHandle here, or else the object will
249   // never be deleted!
250   std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
251
252   class SCEVTruncateExpr : public SCEV {
253     SCEVHandle Op;
254     const Type *Ty;
255     SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
256       : SCEV(scTruncate), Op(op), Ty(ty) {
257       assert(Op->getType()->isInteger() && Ty->isInteger() &&
258              Ty->isUnsigned() &&
259              "Cannot truncate non-integer value!");
260       assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
261              "This is not a truncating conversion!");
262     }
263
264     virtual ~SCEVTruncateExpr() {
265       SCEVTruncates.erase(std::make_pair(Op, Ty));
266     }
267   public:
268     /// get method - This just gets and returns a new SCEVTruncate object
269     ///
270     static SCEVHandle get(const SCEVHandle &Op, const Type *Ty);
271
272     const SCEVHandle &getOperand() const { return Op; }
273     virtual const Type *getType() const { return Ty; }
274     
275     virtual bool isLoopInvariant(const Loop *L) const {
276       return Op->isLoopInvariant(L);
277     }
278
279     virtual bool hasComputableLoopEvolution(const Loop *L) const {
280       return Op->hasComputableLoopEvolution(L);
281     }
282
283     /// getValueRange - Return the tightest constant bounds that this value is
284     /// known to have.  This method is only valid on integer SCEV objects.
285     virtual ConstantRange getValueRange() const {
286       return getOperand()->getValueRange().truncate(getType());
287     }
288
289     Value *expandCodeFor(ScalarEvolutionRewriter &SER,
290                          Instruction *InsertPt);
291     
292     virtual void print(std::ostream &OS) const {
293       OS << "(truncate " << *Op << " to " << *Ty << ")";
294     }
295
296     /// Methods for support type inquiry through isa, cast, and dyn_cast:
297     static inline bool classof(const SCEVTruncateExpr *S) { return true; }
298     static inline bool classof(const SCEV *S) {
299       return S->getSCEVType() == scTruncate;
300     }
301   };
302 }
303
304
305 //===----------------------------------------------------------------------===//
306 // SCEVZeroExtendExpr - This class represents a zero extension of a small
307 // integer value to a larger integer value.
308 //
309 namespace {
310   class SCEVZeroExtendExpr;
311   // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
312   // particular input.  Don't use a SCEVHandle here, or else the object will
313   // never be deleted!
314   std::map<std::pair<SCEV*, const Type*>, SCEVZeroExtendExpr*> SCEVZeroExtends;
315
316   class SCEVZeroExtendExpr : public SCEV {
317     SCEVHandle Op;
318     const Type *Ty;
319     SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
320       : SCEV(scTruncate), Op(Op), Ty(ty) {
321       assert(Op->getType()->isInteger() && Ty->isInteger() &&
322              Ty->isUnsigned() &&
323              "Cannot zero extend non-integer value!");
324       assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
325              "This is not an extending conversion!");
326     }
327
328     virtual ~SCEVZeroExtendExpr() {
329       SCEVZeroExtends.erase(std::make_pair(Op, Ty));
330     }
331   public:
332     /// get method - This just gets and returns a new SCEVZeroExtend object
333     ///
334     static SCEVHandle get(const SCEVHandle &Op, const Type *Ty);
335
336     const SCEVHandle &getOperand() const { return Op; }
337     virtual const Type *getType() const { return Ty; }
338     
339     virtual bool isLoopInvariant(const Loop *L) const {
340       return Op->isLoopInvariant(L);
341     }
342
343     virtual bool hasComputableLoopEvolution(const Loop *L) const {
344       return Op->hasComputableLoopEvolution(L);
345     }
346
347     /// getValueRange - Return the tightest constant bounds that this value is
348     /// known to have.  This method is only valid on integer SCEV objects.
349     virtual ConstantRange getValueRange() const {
350       return getOperand()->getValueRange().zeroExtend(getType());
351     }
352
353     Value *expandCodeFor(ScalarEvolutionRewriter &SER,
354                          Instruction *InsertPt);
355     
356     virtual void print(std::ostream &OS) const {
357       OS << "(zeroextend " << *Op << " to " << *Ty << ")";
358     }
359
360     /// Methods for support type inquiry through isa, cast, and dyn_cast:
361     static inline bool classof(const SCEVZeroExtendExpr *S) { return true; }
362     static inline bool classof(const SCEV *S) {
363       return S->getSCEVType() == scZeroExtend;
364     }
365   };
366 }
367
368
369 //===----------------------------------------------------------------------===//
370 // SCEVCommutativeExpr - This node is the base class for n'ary commutative
371 // operators.
372
373 namespace {
374   class SCEVCommutativeExpr;
375   // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
376   // particular input.  Don't use a SCEVHandle here, or else the object will
377   // never be deleted!
378   std::map<std::pair<unsigned, std::vector<SCEV*> >,
379            SCEVCommutativeExpr*> SCEVCommExprs;
380
381   class SCEVCommutativeExpr : public SCEV {
382     std::vector<SCEVHandle> Operands;
383
384   protected:
385     SCEVCommutativeExpr(enum SCEVTypes T, const std::vector<SCEVHandle> &ops)
386       : SCEV(T) {
387       Operands.reserve(ops.size());
388       Operands.insert(Operands.end(), ops.begin(), ops.end());
389     }
390
391     ~SCEVCommutativeExpr() {
392       SCEVCommExprs.erase(std::make_pair(getSCEVType(),
393                                          std::vector<SCEV*>(Operands.begin(),
394                                                             Operands.end())));
395     }
396
397   public:
398     unsigned getNumOperands() const { return Operands.size(); }
399     const SCEVHandle &getOperand(unsigned i) const {
400       assert(i < Operands.size() && "Operand index out of range!");
401       return Operands[i];
402     }
403
404     const std::vector<SCEVHandle> &getOperands() const { return Operands; }
405     typedef std::vector<SCEVHandle>::const_iterator op_iterator;
406     op_iterator op_begin() const { return Operands.begin(); }
407     op_iterator op_end() const { return Operands.end(); }
408
409
410     virtual bool isLoopInvariant(const Loop *L) const {
411       for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
412         if (!getOperand(i)->isLoopInvariant(L)) return false;
413       return true;
414     }
415
416     virtual bool hasComputableLoopEvolution(const Loop *L) const {
417       for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
418         if (getOperand(i)->hasComputableLoopEvolution(L)) return true;
419       return false;
420     }
421
422     virtual const Type *getType() const { return getOperand(0)->getType(); }
423
424     virtual const char *getOperationStr() const = 0;
425     
426     virtual void print(std::ostream &OS) const {
427       assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
428       const char *OpStr = getOperationStr();
429       OS << "(" << *Operands[0];
430       for (unsigned i = 1, e = Operands.size(); i != e; ++i)
431         OS << OpStr << *Operands[i];
432       OS << ")";
433     }
434
435     /// Methods for support type inquiry through isa, cast, and dyn_cast:
436     static inline bool classof(const SCEVCommutativeExpr *S) { return true; }
437     static inline bool classof(const SCEV *S) {
438       return S->getSCEVType() == scAddExpr ||
439              S->getSCEVType() == scMulExpr;
440     }
441   };
442 }
443
444 //===----------------------------------------------------------------------===//
445 // SCEVAddExpr - This node represents an addition of some number of SCEV's.
446 //
447 namespace {
448   class SCEVAddExpr : public SCEVCommutativeExpr {
449     SCEVAddExpr(const std::vector<SCEVHandle> &ops)
450       : SCEVCommutativeExpr(scAddExpr, ops) {
451     }
452
453   public:
454     static SCEVHandle get(std::vector<SCEVHandle> &Ops);
455
456     static SCEVHandle get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
457       std::vector<SCEVHandle> Ops;
458       Ops.push_back(LHS);
459       Ops.push_back(RHS);
460       return get(Ops);
461     }
462
463     static SCEVHandle get(const SCEVHandle &Op0, const SCEVHandle &Op1,
464                           const SCEVHandle &Op2) {
465       std::vector<SCEVHandle> Ops;
466       Ops.push_back(Op0);
467       Ops.push_back(Op1);
468       Ops.push_back(Op2);
469       return get(Ops);
470     }
471
472     virtual const char *getOperationStr() const { return " + "; }
473
474     Value *expandCodeFor(ScalarEvolutionRewriter &SER,
475                          Instruction *InsertPt);
476
477     /// Methods for support type inquiry through isa, cast, and dyn_cast:
478     static inline bool classof(const SCEVAddExpr *S) { return true; }
479     static inline bool classof(const SCEV *S) {
480       return S->getSCEVType() == scAddExpr;
481     }
482   };
483 }
484
485 //===----------------------------------------------------------------------===//
486 // SCEVMulExpr - This node represents multiplication of some number of SCEV's.
487 //
488 namespace {
489   class SCEVMulExpr : public SCEVCommutativeExpr {
490     SCEVMulExpr(const std::vector<SCEVHandle> &ops)
491       : SCEVCommutativeExpr(scMulExpr, ops) {
492     }
493
494   public:
495     static SCEVHandle get(std::vector<SCEVHandle> &Ops);
496
497     static SCEVHandle get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
498       std::vector<SCEVHandle> Ops;
499       Ops.push_back(LHS);
500       Ops.push_back(RHS);
501       return get(Ops);
502     }
503
504     virtual const char *getOperationStr() const { return " * "; }
505
506     Value *expandCodeFor(ScalarEvolutionRewriter &SER,
507                          Instruction *InsertPt);
508
509     /// Methods for support type inquiry through isa, cast, and dyn_cast:
510     static inline bool classof(const SCEVMulExpr *S) { return true; }
511     static inline bool classof(const SCEV *S) {
512       return S->getSCEVType() == scMulExpr;
513     }
514   };
515 }
516
517
518 //===----------------------------------------------------------------------===//
519 // SCEVUDivExpr - This class represents a binary unsigned division operation.
520 //
521 namespace {
522   class SCEVUDivExpr;
523   // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
524   // input.  Don't use a SCEVHandle here, or else the object will never be
525   // deleted!
526   std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
527
528   class SCEVUDivExpr : public SCEV {
529     SCEVHandle LHS, RHS;
530     SCEVUDivExpr(const SCEVHandle &lhs, const SCEVHandle &rhs)
531       : SCEV(scUDivExpr), LHS(lhs), RHS(rhs) {}
532
533     virtual ~SCEVUDivExpr() {
534       SCEVUDivs.erase(std::make_pair(LHS, RHS));
535     }
536   public:
537     /// get method - This just gets and returns a new SCEVUDiv object.
538     ///
539     static SCEVHandle get(const SCEVHandle &LHS, const SCEVHandle &RHS);
540
541     const SCEVHandle &getLHS() const { return LHS; }
542     const SCEVHandle &getRHS() const { return RHS; }
543
544     virtual bool isLoopInvariant(const Loop *L) const {
545       return LHS->isLoopInvariant(L) && RHS->isLoopInvariant(L);
546     }
547
548     virtual bool hasComputableLoopEvolution(const Loop *L) const {
549       return LHS->hasComputableLoopEvolution(L) &&
550              RHS->hasComputableLoopEvolution(L);
551     }
552
553     virtual const Type *getType() const {
554       const Type *Ty = LHS->getType();
555       if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
556       return Ty;
557     }
558
559     Value *expandCodeFor(ScalarEvolutionRewriter &SER,
560                          Instruction *InsertPt);
561     
562     virtual void print(std::ostream &OS) const {
563       OS << "(" << *LHS << " /u " << *RHS << ")";
564     }
565
566     /// Methods for support type inquiry through isa, cast, and dyn_cast:
567     static inline bool classof(const SCEVUDivExpr *S) { return true; }
568     static inline bool classof(const SCEV *S) {
569       return S->getSCEVType() == scUDivExpr;
570     }
571   };
572 }
573
574
575 //===----------------------------------------------------------------------===//
576
577 // SCEVAddRecExpr - This node represents a polynomial recurrence on the trip
578 // count of the specified loop.
579 //
580 // All operands of an AddRec are required to be loop invariant.
581 //
582 namespace {
583   class SCEVAddRecExpr;
584   // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
585   // particular input.  Don't use a SCEVHandle here, or else the object will
586   // never be deleted!
587   std::map<std::pair<const Loop *, std::vector<SCEV*> >,
588            SCEVAddRecExpr*> SCEVAddRecExprs;
589
590   class SCEVAddRecExpr : public SCEV {
591     std::vector<SCEVHandle> Operands;
592     const Loop *L;
593
594     SCEVAddRecExpr(const std::vector<SCEVHandle> &ops, const Loop *l)
595       : SCEV(scAddRecExpr), Operands(ops), L(l) {
596       for (unsigned i = 0, e = Operands.size(); i != e; ++i)
597         assert(Operands[i]->isLoopInvariant(l) &&
598                "Operands of AddRec must be loop-invariant!");
599     }
600     ~SCEVAddRecExpr() {
601       SCEVAddRecExprs.erase(std::make_pair(L,
602                                            std::vector<SCEV*>(Operands.begin(),
603                                                               Operands.end())));
604     }
605   public:
606     static SCEVHandle get(const SCEVHandle &Start, const SCEVHandle &Step,
607                           const Loop *);
608     static SCEVHandle get(std::vector<SCEVHandle> &Operands,
609                           const Loop *);
610     static SCEVHandle get(const std::vector<SCEVHandle> &Operands,
611                           const Loop *L) {
612       std::vector<SCEVHandle> NewOp(Operands);
613       return get(NewOp, L);
614     }
615
616     typedef std::vector<SCEVHandle>::const_iterator op_iterator;
617     op_iterator op_begin() const { return Operands.begin(); }
618     op_iterator op_end() const { return Operands.end(); }
619
620     unsigned getNumOperands() const { return Operands.size(); }
621     const SCEVHandle &getOperand(unsigned i) const { return Operands[i]; }
622     const SCEVHandle &getStart() const { return Operands[0]; }
623     const Loop *getLoop() const { return L; }
624
625
626     /// getStepRecurrence - This method constructs and returns the recurrence
627     /// indicating how much this expression steps by.  If this is a polynomial
628     /// of degree N, it returns a chrec of degree N-1.
629     SCEVHandle getStepRecurrence() const {
630       if (getNumOperands() == 2) return getOperand(1);
631       return SCEVAddRecExpr::get(std::vector<SCEVHandle>(op_begin()+1,op_end()),
632                                  getLoop());
633     }
634
635     virtual bool hasComputableLoopEvolution(const Loop *QL) const {
636       if (L == QL) return true;
637       /// FIXME: What if the start or step value a recurrence for the specified
638       /// loop?
639       return false;
640     }
641
642
643     virtual bool isLoopInvariant(const Loop *QueryLoop) const {
644       // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
645       // contain L.
646       return !QueryLoop->contains(L->getHeader());
647     }
648
649     virtual const Type *getType() const { return Operands[0]->getType(); }
650
651     Value *expandCodeFor(ScalarEvolutionRewriter &SER,
652                          Instruction *InsertPt);
653
654
655     /// isAffine - Return true if this is an affine AddRec (i.e., it represents
656     /// an expressions A+B*x where A and B are loop invariant values.
657     bool isAffine() const {
658       // We know that the start value is invariant.  This expression is thus
659       // affine iff the step is also invariant.
660       return getNumOperands() == 2;
661     }
662
663     /// isQuadratic - Return true if this is an quadratic AddRec (i.e., it
664     /// represents an expressions A+B*x+C*x^2 where A, B and C are loop
665     /// invariant values.  This corresponds to an addrec of the form {L,+,M,+,N}
666     bool isQuadratic() const {
667       return getNumOperands() == 3;
668     }
669
670     /// evaluateAtIteration - Return the value of this chain of recurrences at
671     /// the specified iteration number.
672     SCEVHandle evaluateAtIteration(SCEVHandle It) const;
673
674     /// getNumIterationsInRange - Return the number of iterations of this loop
675     /// that produce values in the specified constant range.  Another way of
676     /// looking at this is that it returns the first iteration number where the
677     /// value is not in the condition, thus computing the exit count.  If the
678     /// iteration count can't be computed, an instance of SCEVCouldNotCompute is
679     /// returned.
680     SCEVHandle getNumIterationsInRange(ConstantRange Range) const;
681
682
683     virtual void print(std::ostream &OS) const {
684       OS << "{" << *Operands[0];
685       for (unsigned i = 1, e = Operands.size(); i != e; ++i)
686         OS << ",+," << *Operands[i];
687       OS << "}<" << L->getHeader()->getName() + ">";
688     }
689
690     /// Methods for support type inquiry through isa, cast, and dyn_cast:
691     static inline bool classof(const SCEVAddRecExpr *S) { return true; }
692     static inline bool classof(const SCEV *S) {
693       return S->getSCEVType() == scAddRecExpr;
694     }
695   };
696 }
697
698
699 //===----------------------------------------------------------------------===//
700 // SCEVUnknown - This means that we are dealing with an entirely unknown SCEV
701 // value, and only represent it as it's LLVM Value.  This is the "bottom" value
702 // for the analysis.
703 //
704 namespace {
705   class SCEVUnknown;
706   // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any
707   // particular value.  Don't use a SCEVHandle here, or else the object will
708   // never be deleted!
709   std::map<Value*, SCEVUnknown*> SCEVUnknowns;
710
711   class SCEVUnknown : public SCEV {
712     Value *V;
713     SCEVUnknown(Value *v) : SCEV(scUnknown), V(v) {}
714
715   protected:
716     ~SCEVUnknown() { SCEVUnknowns.erase(V); }
717   public:
718     /// get method - For SCEVUnknown, this just gets and returns a new
719     /// SCEVUnknown.
720     static SCEVHandle get(Value *V) {
721       if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
722         return SCEVConstant::get(CI);
723       SCEVUnknown *&Result = SCEVUnknowns[V];
724       if (Result == 0) Result = new SCEVUnknown(V);
725       return Result;
726     }
727
728     Value *getValue() const { return V; }
729
730     Value *expandCodeFor(ScalarEvolutionRewriter &SER,
731                          Instruction *InsertPt) {
732       return V;
733     }
734
735     virtual bool isLoopInvariant(const Loop *L) const {
736       // All non-instruction values are loop invariant.  All instructions are
737       // loop invariant if they are not contained in the specified loop.
738       if (Instruction *I = dyn_cast<Instruction>(V))
739         return !L->contains(I->getParent());
740       return true;
741     }
742
743     virtual bool hasComputableLoopEvolution(const Loop *QL) const {
744       return false; // not computable
745     }
746
747     virtual const Type *getType() const { return V->getType(); }
748
749     virtual void print(std::ostream &OS) const {
750       WriteAsOperand(OS, V, false);
751     }
752
753     /// Methods for support type inquiry through isa, cast, and dyn_cast:
754     static inline bool classof(const SCEVUnknown *S) { return true; }
755     static inline bool classof(const SCEV *S) {
756       return S->getSCEVType() == scUnknown;
757     }
758   };
759 }
760
761 //===----------------------------------------------------------------------===//
762 //                      Simple SCEV method implementations
763 //===----------------------------------------------------------------------===//
764
765 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
766 /// specified signed integer value and return a SCEV for the constant.
767 static SCEVHandle getIntegerSCEV(int Val, const Type *Ty) {
768   Constant *C;
769   if (Val == 0) 
770     C = Constant::getNullValue(Ty);
771   else if (Ty->isFloatingPoint())
772     C = ConstantFP::get(Ty, Val);
773   else if (Ty->isSigned())
774     C = ConstantSInt::get(Ty, Val);
775   else {
776     C = ConstantSInt::get(Ty->getSignedVersion(), Val);
777     C = ConstantExpr::getCast(C, Ty);
778   }
779   return SCEVUnknown::get(C);
780 }
781
782 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
783 /// input value to the specified type.  If the type must be extended, it is zero
784 /// extended.
785 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
786   const Type *SrcTy = V->getType();
787   assert(SrcTy->isInteger() && Ty->isInteger() &&
788          "Cannot truncate or zero extend with non-integer arguments!");
789   if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
790     return V;  // No conversion
791   if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
792     return SCEVTruncateExpr::get(V, Ty);
793   return SCEVZeroExtendExpr::get(V, Ty);
794 }
795
796 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
797 ///
798 static SCEVHandle getNegativeSCEV(const SCEVHandle &V) {
799   if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
800     return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
801   
802   return SCEVMulExpr::get(V, getIntegerSCEV(-1, V->getType()));
803 }
804
805 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
806 ///
807 static SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
808   // X - Y --> X + -Y
809   return SCEVAddExpr::get(LHS, getNegativeSCEV(RHS));
810 }
811
812
813 /// Binomial - Evaluate N!/((N-M)!*M!)  .  Note that N is often large and M is
814 /// often very small, so we try to reduce the number of N! terms we need to
815 /// evaluate by evaluating this as  (N!/(N-M)!)/M!
816 static ConstantInt *Binomial(ConstantInt *N, unsigned M) {
817   uint64_t NVal = N->getRawValue();
818   uint64_t FirstTerm = 1;
819   for (unsigned i = 0; i != M; ++i)
820     FirstTerm *= NVal-i;
821
822   unsigned MFactorial = 1;
823   for (; M; --M)
824     MFactorial *= M;
825
826   Constant *Result = ConstantUInt::get(Type::ULongTy, FirstTerm/MFactorial);
827   Result = ConstantExpr::getCast(Result, N->getType());
828   assert(isa<ConstantInt>(Result) && "Cast of integer not folded??");
829   return cast<ConstantInt>(Result);
830 }
831
832 /// PartialFact - Compute V!/(V-NumSteps)!
833 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
834   // Handle this case efficiently, it is common to have constant iteration
835   // counts while computing loop exit values.
836   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
837     uint64_t Val = SC->getValue()->getRawValue();
838     uint64_t Result = 1;
839     for (; NumSteps; --NumSteps)
840       Result *= Val-(NumSteps-1);
841     Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
842     return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
843   }
844
845   const Type *Ty = V->getType();
846   if (NumSteps == 0)
847     return getIntegerSCEV(1, Ty);
848   
849   SCEVHandle Result = V;
850   for (unsigned i = 1; i != NumSteps; ++i)
851     Result = SCEVMulExpr::get(Result, getMinusSCEV(V, getIntegerSCEV(i, Ty)));
852   return Result;
853 }
854
855
856 /// evaluateAtIteration - Return the value of this chain of recurrences at
857 /// the specified iteration number.  We can evaluate this recurrence by
858 /// multiplying each element in the chain by the binomial coefficient
859 /// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
860 ///
861 ///   A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
862 ///
863 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
864 /// Is the binomial equation safe using modular arithmetic??
865 ///
866 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
867   SCEVHandle Result = getStart();
868   int Divisor = 1;
869   const Type *Ty = It->getType();
870   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
871     SCEVHandle BC = PartialFact(It, i);
872     Divisor *= i;
873     SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
874                                        getIntegerSCEV(Divisor, Ty));
875     Result = SCEVAddExpr::get(Result, Val);
876   }
877   return Result;
878 }
879
880
881 //===----------------------------------------------------------------------===//
882 //                    SCEV Expression folder implementations
883 //===----------------------------------------------------------------------===//
884
885 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
886   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
887     return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
888
889   // If the input value is a chrec scev made out of constants, truncate
890   // all of the constants.
891   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
892     std::vector<SCEVHandle> Operands;
893     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
894       // FIXME: This should allow truncation of other expression types!
895       if (isa<SCEVConstant>(AddRec->getOperand(i)))
896         Operands.push_back(get(AddRec->getOperand(i), Ty));
897       else
898         break;
899     if (Operands.size() == AddRec->getNumOperands())
900       return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
901   }
902
903   SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
904   if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
905   return Result;
906 }
907
908 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
909   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
910     return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
911
912   // FIXME: If the input value is a chrec scev, and we can prove that the value
913   // did not overflow the old, smaller, value, we can zero extend all of the
914   // operands (often constants).  This would allow analysis of something like
915   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
916
917   SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
918   if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
919   return Result;
920 }
921
922 // get - Get a canonical add expression, or something simpler if possible.
923 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
924   assert(!Ops.empty() && "Cannot get empty add!");
925
926   // Sort by complexity, this groups all similar expression types together.
927   std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
928
929   // If there are any constants, fold them together.
930   unsigned Idx = 0;
931   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
932     ++Idx;
933     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
934       // We found two constants, fold them together!
935       Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
936       if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
937         Ops[0] = SCEVConstant::get(CI);
938         Ops.erase(Ops.begin()+1);  // Erase the folded element
939         if (Ops.size() == 1) return Ops[0];
940       } else {
941         // If we couldn't fold the expression, move to the next constant.  Note
942         // that this is impossible to happen in practice because we always
943         // constant fold constant ints to constant ints.
944         ++Idx;
945       }
946     }
947
948     // If we are left with a constant zero being added, strip it off.
949     if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
950       Ops.erase(Ops.begin());
951       --Idx;
952     }
953   }
954
955   if (Ops.size() == 1)
956     return Ops[0];
957   
958   // Okay, check to see if the same value occurs in the operand list twice.  If
959   // so, merge them together into an multiply expression.  Since we sorted the
960   // list, these values are required to be adjacent.
961   const Type *Ty = Ops[0]->getType();
962   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
963     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
964       // Found a match, merge the two values into a multiply, and add any
965       // remaining values to the result.
966       SCEVHandle Two = getIntegerSCEV(2, Ty);
967       SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
968       if (Ops.size() == 2)
969         return Mul;
970       Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
971       Ops.push_back(Mul);
972       return SCEVAddExpr::get(Ops);
973     }
974
975   // Okay, now we know the first non-constant operand.  If there are add
976   // operands they would be next.
977   if (Idx < Ops.size()) {
978     bool DeletedAdd = false;
979     while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
980       // If we have an add, expand the add operands onto the end of the operands
981       // list.
982       Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
983       Ops.erase(Ops.begin()+Idx);
984       DeletedAdd = true;
985     }
986
987     // If we deleted at least one add, we added operands to the end of the list,
988     // and they are not necessarily sorted.  Recurse to resort and resimplify
989     // any operands we just aquired.
990     if (DeletedAdd)
991       return get(Ops);
992   }
993
994   // Skip over the add expression until we get to a multiply.
995   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
996     ++Idx;
997
998   // If we are adding something to a multiply expression, make sure the
999   // something is not already an operand of the multiply.  If so, merge it into
1000   // the multiply.
1001   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1002     SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1003     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1004       SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1005       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1006         if (MulOpSCEV == Ops[AddOp] &&
1007             (Mul->getNumOperands() != 2 || !isa<SCEVConstant>(MulOpSCEV))) {
1008           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
1009           SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1010           if (Mul->getNumOperands() != 2) {
1011             // If the multiply has more than two operands, we must get the
1012             // Y*Z term.
1013             std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1014             MulOps.erase(MulOps.begin()+MulOp);
1015             InnerMul = SCEVMulExpr::get(MulOps);
1016           }
1017           SCEVHandle One = getIntegerSCEV(1, Ty);
1018           SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
1019           SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
1020           if (Ops.size() == 2) return OuterMul;
1021           if (AddOp < Idx) {
1022             Ops.erase(Ops.begin()+AddOp);
1023             Ops.erase(Ops.begin()+Idx-1);
1024           } else {
1025             Ops.erase(Ops.begin()+Idx);
1026             Ops.erase(Ops.begin()+AddOp-1);
1027           }
1028           Ops.push_back(OuterMul);
1029           return SCEVAddExpr::get(Ops);
1030         }
1031       
1032       // Check this multiply against other multiplies being added together.
1033       for (unsigned OtherMulIdx = Idx+1;
1034            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1035            ++OtherMulIdx) {
1036         SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1037         // If MulOp occurs in OtherMul, we can fold the two multiplies
1038         // together.
1039         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1040              OMulOp != e; ++OMulOp)
1041           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1042             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1043             SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1044             if (Mul->getNumOperands() != 2) {
1045               std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1046               MulOps.erase(MulOps.begin()+MulOp);
1047               InnerMul1 = SCEVMulExpr::get(MulOps);
1048             }
1049             SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1050             if (OtherMul->getNumOperands() != 2) {
1051               std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1052                                              OtherMul->op_end());
1053               MulOps.erase(MulOps.begin()+OMulOp);
1054               InnerMul2 = SCEVMulExpr::get(MulOps);
1055             }
1056             SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
1057             SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
1058             if (Ops.size() == 2) return OuterMul;
1059             Ops.erase(Ops.begin()+Idx);
1060             Ops.erase(Ops.begin()+OtherMulIdx-1);
1061             Ops.push_back(OuterMul);
1062             return SCEVAddExpr::get(Ops);
1063           }
1064       }
1065     }
1066   }
1067
1068   // If there are any add recurrences in the operands list, see if any other
1069   // added values are loop invariant.  If so, we can fold them into the
1070   // recurrence.
1071   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1072     ++Idx;
1073
1074   // Scan over all recurrences, trying to fold loop invariants into them.
1075   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1076     // Scan all of the other operands to this add and add them to the vector if
1077     // they are loop invariant w.r.t. the recurrence.
1078     std::vector<SCEVHandle> LIOps;
1079     SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1080     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1081       if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1082         LIOps.push_back(Ops[i]);
1083         Ops.erase(Ops.begin()+i);
1084         --i; --e;
1085       }
1086
1087     // If we found some loop invariants, fold them into the recurrence.
1088     if (!LIOps.empty()) {
1089       //  NLI + LI + { Start,+,Step}  -->  NLI + { LI+Start,+,Step }
1090       LIOps.push_back(AddRec->getStart());
1091
1092       std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
1093       AddRecOps[0] = SCEVAddExpr::get(LIOps);
1094
1095       SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
1096       // If all of the other operands were loop invariant, we are done.
1097       if (Ops.size() == 1) return NewRec;
1098
1099       // Otherwise, add the folded AddRec by the non-liv parts.
1100       for (unsigned i = 0;; ++i)
1101         if (Ops[i] == AddRec) {
1102           Ops[i] = NewRec;
1103           break;
1104         }
1105       return SCEVAddExpr::get(Ops);
1106     }
1107
1108     // Okay, if there weren't any loop invariants to be folded, check to see if
1109     // there are multiple AddRec's with the same loop induction variable being
1110     // added together.  If so, we can fold them.
1111     for (unsigned OtherIdx = Idx+1;
1112          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1113       if (OtherIdx != Idx) {
1114         SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1115         if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1116           // Other + {A,+,B} + {C,+,D}  -->  Other + {A+C,+,B+D}
1117           std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1118           for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1119             if (i >= NewOps.size()) {
1120               NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1121                             OtherAddRec->op_end());
1122               break;
1123             }
1124             NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
1125           }
1126           SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
1127
1128           if (Ops.size() == 2) return NewAddRec;
1129
1130           Ops.erase(Ops.begin()+Idx);
1131           Ops.erase(Ops.begin()+OtherIdx-1);
1132           Ops.push_back(NewAddRec);
1133           return SCEVAddExpr::get(Ops);
1134         }
1135       }
1136
1137     // Otherwise couldn't fold anything into this recurrence.  Move onto the
1138     // next one.
1139   }
1140
1141   // Okay, it looks like we really DO need an add expr.  Check to see if we
1142   // already have one, otherwise create a new one.
1143   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1144   SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
1145                                                               SCEVOps)];
1146   if (Result == 0) Result = new SCEVAddExpr(Ops);
1147   return Result;
1148 }
1149
1150
1151 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
1152   assert(!Ops.empty() && "Cannot get empty mul!");
1153
1154   // Sort by complexity, this groups all similar expression types together.
1155   std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
1156
1157   // If there are any constants, fold them together.
1158   unsigned Idx = 0;
1159   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1160
1161     // C1*(C2+V) -> C1*C2 + C1*V
1162     if (Ops.size() == 2)
1163       if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1164         if (Add->getNumOperands() == 2 &&
1165             isa<SCEVConstant>(Add->getOperand(0)))
1166           return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
1167                                   SCEVMulExpr::get(LHSC, Add->getOperand(1)));
1168
1169
1170     ++Idx;
1171     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1172       // We found two constants, fold them together!
1173       Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
1174       if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
1175         Ops[0] = SCEVConstant::get(CI);
1176         Ops.erase(Ops.begin()+1);  // Erase the folded element
1177         if (Ops.size() == 1) return Ops[0];
1178       } else {
1179         // If we couldn't fold the expression, move to the next constant.  Note
1180         // that this is impossible to happen in practice because we always
1181         // constant fold constant ints to constant ints.
1182         ++Idx;
1183       }
1184     }
1185
1186     // If we are left with a constant one being multiplied, strip it off.
1187     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1188       Ops.erase(Ops.begin());
1189       --Idx;
1190     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
1191       // If we have a multiply of zero, it will always be zero.
1192       return Ops[0];
1193     }
1194   }
1195
1196   // Skip over the add expression until we get to a multiply.
1197   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1198     ++Idx;
1199
1200   if (Ops.size() == 1)
1201     return Ops[0];
1202   
1203   // If there are mul operands inline them all into this expression.
1204   if (Idx < Ops.size()) {
1205     bool DeletedMul = false;
1206     while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1207       // If we have an mul, expand the mul operands onto the end of the operands
1208       // list.
1209       Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1210       Ops.erase(Ops.begin()+Idx);
1211       DeletedMul = true;
1212     }
1213
1214     // If we deleted at least one mul, we added operands to the end of the list,
1215     // and they are not necessarily sorted.  Recurse to resort and resimplify
1216     // any operands we just aquired.
1217     if (DeletedMul)
1218       return get(Ops);
1219   }
1220
1221   // If there are any add recurrences in the operands list, see if any other
1222   // added values are loop invariant.  If so, we can fold them into the
1223   // recurrence.
1224   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1225     ++Idx;
1226
1227   // Scan over all recurrences, trying to fold loop invariants into them.
1228   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1229     // Scan all of the other operands to this mul and add them to the vector if
1230     // they are loop invariant w.r.t. the recurrence.
1231     std::vector<SCEVHandle> LIOps;
1232     SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1233     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1234       if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1235         LIOps.push_back(Ops[i]);
1236         Ops.erase(Ops.begin()+i);
1237         --i; --e;
1238       }
1239
1240     // If we found some loop invariants, fold them into the recurrence.
1241     if (!LIOps.empty()) {
1242       //  NLI * LI * { Start,+,Step}  -->  NLI * { LI*Start,+,LI*Step }
1243       std::vector<SCEVHandle> NewOps;
1244       NewOps.reserve(AddRec->getNumOperands());
1245       if (LIOps.size() == 1) {
1246         SCEV *Scale = LIOps[0];
1247         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1248           NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
1249       } else {
1250         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1251           std::vector<SCEVHandle> MulOps(LIOps);
1252           MulOps.push_back(AddRec->getOperand(i));
1253           NewOps.push_back(SCEVMulExpr::get(MulOps));
1254         }
1255       }
1256
1257       SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
1258
1259       // If all of the other operands were loop invariant, we are done.
1260       if (Ops.size() == 1) return NewRec;
1261
1262       // Otherwise, multiply the folded AddRec by the non-liv parts.
1263       for (unsigned i = 0;; ++i)
1264         if (Ops[i] == AddRec) {
1265           Ops[i] = NewRec;
1266           break;
1267         }
1268       return SCEVMulExpr::get(Ops);
1269     }
1270
1271     // Okay, if there weren't any loop invariants to be folded, check to see if
1272     // there are multiple AddRec's with the same loop induction variable being
1273     // multiplied together.  If so, we can fold them.
1274     for (unsigned OtherIdx = Idx+1;
1275          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1276       if (OtherIdx != Idx) {
1277         SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1278         if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1279           // F * G  -->  {A,+,B} * {C,+,D}  -->  {A*C,+,F*D + G*B + B*D}
1280           SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1281           SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
1282                                                  G->getStart());
1283           SCEVHandle B = F->getStepRecurrence();
1284           SCEVHandle D = G->getStepRecurrence();
1285           SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
1286                                                 SCEVMulExpr::get(G, B),
1287                                                 SCEVMulExpr::get(B, D));
1288           SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
1289                                                      F->getLoop());
1290           if (Ops.size() == 2) return NewAddRec;
1291
1292           Ops.erase(Ops.begin()+Idx);
1293           Ops.erase(Ops.begin()+OtherIdx-1);
1294           Ops.push_back(NewAddRec);
1295           return SCEVMulExpr::get(Ops);
1296         }
1297       }
1298
1299     // Otherwise couldn't fold anything into this recurrence.  Move onto the
1300     // next one.
1301   }
1302
1303   // Okay, it looks like we really DO need an mul expr.  Check to see if we
1304   // already have one, otherwise create a new one.
1305   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1306   SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
1307                                                               SCEVOps)];
1308   if (Result == 0) Result = new SCEVMulExpr(Ops);
1309   return Result;
1310 }
1311
1312 SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1313   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1314     if (RHSC->getValue()->equalsInt(1))
1315       return LHS;                            // X /u 1 --> x
1316     if (RHSC->getValue()->isAllOnesValue())
1317       return getNegativeSCEV(LHS);           // X /u -1  -->  -x
1318
1319     if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1320       Constant *LHSCV = LHSC->getValue();
1321       Constant *RHSCV = RHSC->getValue();
1322       if (LHSCV->getType()->isSigned())
1323         LHSCV = ConstantExpr::getCast(LHSCV,
1324                                       LHSCV->getType()->getUnsignedVersion());
1325       if (RHSCV->getType()->isSigned())
1326         RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
1327       return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
1328     }
1329   }
1330
1331   // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1332
1333   SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
1334   if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1335   return Result;
1336 }
1337
1338
1339 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1340 /// specified loop.  Simplify the expression as much as possible.
1341 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1342                                const SCEVHandle &Step, const Loop *L) {
1343   std::vector<SCEVHandle> Operands;
1344   Operands.push_back(Start);
1345   if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1346     if (StepChrec->getLoop() == L) {
1347       Operands.insert(Operands.end(), StepChrec->op_begin(),
1348                       StepChrec->op_end());
1349       return get(Operands, L);
1350     }
1351
1352   Operands.push_back(Step);
1353   return get(Operands, L);
1354 }
1355
1356 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1357 /// specified loop.  Simplify the expression as much as possible.
1358 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1359                                const Loop *L) {
1360   if (Operands.size() == 1) return Operands[0];
1361
1362   if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1363     if (StepC->getValue()->isNullValue()) {
1364       Operands.pop_back();
1365       return get(Operands, L);             // { X,+,0 }  -->  X
1366     }
1367
1368   SCEVAddRecExpr *&Result =
1369     SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1370                                                          Operands.end()))];
1371   if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1372   return Result;
1373 }
1374
1375
1376 //===----------------------------------------------------------------------===//
1377 //                  Non-trivial closed-form SCEV Expanders
1378 //===----------------------------------------------------------------------===//
1379
1380 Value *SCEVTruncateExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
1381                                        Instruction *InsertPt) {
1382   Value *V = SER.ExpandCodeFor(getOperand(), InsertPt);
1383   return new CastInst(V, getType(), "tmp.", InsertPt);
1384 }
1385
1386 Value *SCEVZeroExtendExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
1387                                          Instruction *InsertPt) {
1388   Value *V = SER.ExpandCodeFor(getOperand(), InsertPt,
1389                                getOperand()->getType()->getUnsignedVersion());
1390   return new CastInst(V, getType(), "tmp.", InsertPt);
1391 }
1392
1393 Value *SCEVAddExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
1394                                   Instruction *InsertPt) {
1395   const Type *Ty = getType();
1396   Value *V = SER.ExpandCodeFor(getOperand(getNumOperands()-1), InsertPt, Ty);
1397
1398   // Emit a bunch of add instructions
1399   for (int i = getNumOperands()-2; i >= 0; --i)
1400     V = BinaryOperator::create(Instruction::Add, V,
1401                                SER.ExpandCodeFor(getOperand(i), InsertPt, Ty),
1402                                "tmp.", InsertPt);
1403   return V;
1404 }
1405
1406 Value *SCEVMulExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
1407                                   Instruction *InsertPt) {
1408   const Type *Ty = getType();
1409   int FirstOp = 0;  // Set if we should emit a subtract.
1410   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getOperand(0)))
1411     if (SC->getValue()->isAllOnesValue())
1412       FirstOp = 1;
1413
1414   int i = getNumOperands()-2;
1415   Value *V = SER.ExpandCodeFor(getOperand(i+1), InsertPt, Ty);
1416
1417   // Emit a bunch of multiply instructions
1418   for (; i >= FirstOp; --i)
1419     V = BinaryOperator::create(Instruction::Mul, V,
1420                                SER.ExpandCodeFor(getOperand(i), InsertPt, Ty),
1421                                "tmp.", InsertPt);
1422   // -1 * ...  --->  0 - ...
1423   if (FirstOp == 1)
1424     V = BinaryOperator::create(Instruction::Sub, Constant::getNullValue(Ty), V,
1425                                "tmp.", InsertPt);
1426   return V;
1427 }
1428
1429 Value *SCEVUDivExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
1430                                    Instruction *InsertPt) {
1431   const Type *Ty = getType();
1432   Value *LHS = SER.ExpandCodeFor(getLHS(), InsertPt, Ty);
1433   Value *RHS = SER.ExpandCodeFor(getRHS(), InsertPt, Ty);
1434   return BinaryOperator::create(Instruction::Div, LHS, RHS, "tmp.", InsertPt);
1435 }
1436
1437 Value *SCEVAddRecExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
1438                                      Instruction *InsertPt) {
1439   const Type *Ty = getType();
1440   // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
1441   assert(Ty->isIntegral() && "Cannot expand fp recurrences yet!");
1442
1443   // {X,+,F} --> X + {0,+,F}
1444   if (!isa<SCEVConstant>(getStart()) ||
1445       !cast<SCEVConstant>(getStart())->getValue()->isNullValue()) {
1446     Value *Start = SER.ExpandCodeFor(getStart(), InsertPt, Ty);
1447     std::vector<SCEVHandle> NewOps(op_begin(), op_end());
1448     NewOps[0] = getIntegerSCEV(0, getType());
1449     Value *Rest = SER.ExpandCodeFor(SCEVAddRecExpr::get(NewOps, getLoop()),
1450                                     InsertPt, getType());
1451
1452     // FIXME: look for an existing add to use.
1453     return BinaryOperator::create(Instruction::Add, Rest, Start, "tmp.",
1454                                   InsertPt);
1455   }
1456
1457   // {0,+,1} --> Insert a canonical induction variable into the loop!
1458   if (getNumOperands() == 2 && getOperand(1) == getIntegerSCEV(1, getType())) {
1459     // Create and insert the PHI node for the induction variable in the
1460     // specified loop.
1461     BasicBlock *Header = getLoop()->getHeader();
1462     PHINode *PN = new PHINode(Ty, "indvar", Header->begin());
1463     PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
1464
1465     // Insert a unit add instruction after the PHI nodes in the header block.
1466     BasicBlock::iterator I = PN;
1467     while (isa<PHINode>(I)) ++I;
1468
1469     Constant *One = Ty->isFloatingPoint() ?(Constant*)ConstantFP::get(Ty, 1.0)
1470       :(Constant*)ConstantInt::get(Ty, 1);
1471     Instruction *Add = BinaryOperator::create(Instruction::Add, PN, One,
1472                                               "indvar.next", I);
1473
1474     pred_iterator PI = pred_begin(Header);
1475     if (*PI == L->getLoopPreheader())
1476       ++PI;
1477     PN->addIncoming(Add, *PI);
1478     return PN;
1479   }
1480
1481   // Get the canonical induction variable I for this loop.
1482   Value *I = SER.GetOrInsertCanonicalInductionVariable(getLoop(), Ty);
1483
1484   if (getNumOperands() == 2) {   // {0,+,F} --> i*F
1485     Value *F = SER.ExpandCodeFor(getOperand(1), InsertPt, Ty);
1486     return BinaryOperator::create(Instruction::Mul, I, F, "tmp.", InsertPt);
1487   }
1488
1489   // If this is a chain of recurrences, turn it into a closed form, using the
1490   // folders, then expandCodeFor the closed form.  This allows the folders to
1491   // simplify the expression without having to build a bunch of special code
1492   // into this folder.
1493   SCEVHandle IH = SCEVUnknown::get(I);   // Get I as a "symbolic" SCEV.
1494
1495   SCEVHandle V = evaluateAtIteration(IH);
1496   //std::cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
1497
1498   return SER.ExpandCodeFor(V, InsertPt, Ty);
1499 }
1500
1501
1502 //===----------------------------------------------------------------------===//
1503 //             ScalarEvolutionsImpl Definition and Implementation
1504 //===----------------------------------------------------------------------===//
1505 //
1506 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1507 /// evolution code.
1508 ///
1509 namespace {
1510   struct ScalarEvolutionsImpl {
1511     /// F - The function we are analyzing.
1512     ///
1513     Function &F;
1514
1515     /// LI - The loop information for the function we are currently analyzing.
1516     ///
1517     LoopInfo &LI;
1518
1519     /// UnknownValue - This SCEV is used to represent unknown trip counts and
1520     /// things.
1521     SCEVHandle UnknownValue;
1522
1523     /// Scalars - This is a cache of the scalars we have analyzed so far.
1524     ///
1525     std::map<Value*, SCEVHandle> Scalars;
1526
1527     /// IterationCounts - Cache the iteration count of the loops for this
1528     /// function as they are computed.
1529     std::map<const Loop*, SCEVHandle> IterationCounts;
1530
1531   public:
1532     ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1533       : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1534
1535     /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1536     /// expression and create a new one.
1537     SCEVHandle getSCEV(Value *V);
1538
1539     /// getSCEVAtScope - Compute the value of the specified expression within
1540     /// the indicated loop (which may be null to indicate in no loop).  If the
1541     /// expression cannot be evaluated, return UnknownValue itself.
1542     SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1543
1544
1545     /// hasLoopInvariantIterationCount - Return true if the specified loop has
1546     /// an analyzable loop-invariant iteration count.
1547     bool hasLoopInvariantIterationCount(const Loop *L);
1548
1549     /// getIterationCount - If the specified loop has a predictable iteration
1550     /// count, return it.  Note that it is not valid to call this method on a
1551     /// loop without a loop-invariant iteration count.
1552     SCEVHandle getIterationCount(const Loop *L);
1553
1554     /// deleteInstructionFromRecords - This method should be called by the
1555     /// client before it removes an instruction from the program, to make sure
1556     /// that no dangling references are left around.
1557     void deleteInstructionFromRecords(Instruction *I);
1558
1559   private:
1560     /// createSCEV - We know that there is no SCEV for the specified value.
1561     /// Analyze the expression.
1562     SCEVHandle createSCEV(Value *V);
1563     SCEVHandle createNodeForCast(CastInst *CI);
1564
1565     /// createNodeForPHI - Provide the special handling we need to analyze PHI
1566     /// SCEVs.
1567     SCEVHandle createNodeForPHI(PHINode *PN);
1568     void UpdatePHIUserScalarEntries(Instruction *I, PHINode *PN,
1569                                     std::set<Instruction*> &UpdatedInsts);
1570
1571     /// ComputeIterationCount - Compute the number of times the specified loop
1572     /// will iterate.
1573     SCEVHandle ComputeIterationCount(const Loop *L);
1574
1575     /// HowFarToZero - Return the number of times a backedge comparing the
1576     /// specified value to zero will execute.  If not computable, return
1577     /// UnknownValue
1578     SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1579
1580     /// HowFarToNonZero - Return the number of times a backedge checking the
1581     /// specified value for nonzero will execute.  If not computable, return
1582     /// UnknownValue
1583     SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1584   };
1585 }
1586
1587 //===----------------------------------------------------------------------===//
1588 //            Basic SCEV Analysis and PHI Idiom Recognition Code
1589 //
1590
1591 /// deleteInstructionFromRecords - This method should be called by the
1592 /// client before it removes an instruction from the program, to make sure
1593 /// that no dangling references are left around.
1594 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1595   Scalars.erase(I);
1596 }
1597
1598
1599 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1600 /// expression and create a new one.
1601 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1602   assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1603
1604   std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1605   if (I != Scalars.end()) return I->second;
1606   SCEVHandle S = createSCEV(V);
1607   Scalars.insert(std::make_pair(V, S));
1608   return S;
1609 }
1610
1611
1612 /// UpdatePHIUserScalarEntries - After PHI node analysis, we have a bunch of
1613 /// entries in the scalar map that refer to the "symbolic" PHI value instead of
1614 /// the recurrence value.  After we resolve the PHI we must loop over all of the
1615 /// using instructions that have scalar map entries and update them.
1616 void ScalarEvolutionsImpl::UpdatePHIUserScalarEntries(Instruction *I,
1617                                                       PHINode *PN,
1618                                         std::set<Instruction*> &UpdatedInsts) {
1619   std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1620   if (SI == Scalars.end()) return;   // This scalar wasn't previous processed.
1621   if (UpdatedInsts.insert(I).second) {
1622     Scalars.erase(SI);                 // Remove the old entry
1623     getSCEV(I);                        // Calculate the new entry
1624     
1625     for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1626          UI != E; ++UI)
1627       UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN, UpdatedInsts);
1628   }
1629 }
1630
1631
1632 /// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
1633 /// a loop header, making it a potential recurrence, or it doesn't.
1634 ///
1635 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1636   if (PN->getNumIncomingValues() == 2)  // The loops have been canonicalized.
1637     if (const Loop *L = LI.getLoopFor(PN->getParent()))
1638       if (L->getHeader() == PN->getParent()) {
1639         // If it lives in the loop header, it has two incoming values, one
1640         // from outside the loop, and one from inside.
1641         unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1642         unsigned BackEdge     = IncomingEdge^1;
1643         
1644         // While we are analyzing this PHI node, handle its value symbolically.
1645         SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1646         assert(Scalars.find(PN) == Scalars.end() &&
1647                "PHI node already processed?");
1648         Scalars.insert(std::make_pair(PN, SymbolicName));
1649
1650         // Using this symbolic name for the PHI, analyze the value coming around
1651         // the back-edge.
1652         SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1653
1654         // NOTE: If BEValue is loop invariant, we know that the PHI node just
1655         // has a special value for the first iteration of the loop.
1656
1657         // If the value coming around the backedge is an add with the symbolic
1658         // value we just inserted, then we found a simple induction variable!
1659         if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1660           // If there is a single occurrence of the symbolic value, replace it
1661           // with a recurrence.
1662           unsigned FoundIndex = Add->getNumOperands();
1663           for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1664             if (Add->getOperand(i) == SymbolicName)
1665               if (FoundIndex == e) {
1666                 FoundIndex = i;
1667                 break;
1668               }
1669
1670           if (FoundIndex != Add->getNumOperands()) {
1671             // Create an add with everything but the specified operand.
1672             std::vector<SCEVHandle> Ops;
1673             for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1674               if (i != FoundIndex)
1675                 Ops.push_back(Add->getOperand(i));
1676             SCEVHandle Accum = SCEVAddExpr::get(Ops);
1677
1678             // This is not a valid addrec if the step amount is varying each
1679             // loop iteration, but is not itself an addrec in this loop.
1680             if (Accum->isLoopInvariant(L) ||
1681                 (isa<SCEVAddRecExpr>(Accum) &&
1682                  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1683               SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1684               SCEVHandle PHISCEV  = SCEVAddRecExpr::get(StartVal, Accum, L);
1685
1686               // Okay, for the entire analysis of this edge we assumed the PHI
1687               // to be symbolic.  We now need to go back and update all of the
1688               // entries for the scalars that use the PHI (except for the PHI
1689               // itself) to use the new analyzed value instead of the "symbolic"
1690               // value.
1691               Scalars.find(PN)->second = PHISCEV;       // Update the PHI value
1692               std::set<Instruction*> UpdatedInsts;
1693               UpdatedInsts.insert(PN);
1694               for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
1695                    UI != E; ++UI)
1696                 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN,
1697                                            UpdatedInsts);
1698               return PHISCEV;
1699             }
1700           }
1701         }
1702
1703         return SymbolicName;
1704       }
1705   
1706   // If it's not a loop phi, we can't handle it yet.
1707   return SCEVUnknown::get(PN);
1708 }
1709
1710 /// createNodeForCast - Handle the various forms of casts that we support.
1711 ///
1712 SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1713   const Type *SrcTy = CI->getOperand(0)->getType();
1714   const Type *DestTy = CI->getType();
1715   
1716   // If this is a noop cast (ie, conversion from int to uint), ignore it.
1717   if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1718     return getSCEV(CI->getOperand(0));
1719   
1720   if (SrcTy->isInteger() && DestTy->isInteger()) {
1721     // Otherwise, if this is a truncating integer cast, we can represent this
1722     // cast.
1723     if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1724       return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1725                                    CI->getType()->getUnsignedVersion());
1726     if (SrcTy->isUnsigned() &&
1727         SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1728       return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1729                                      CI->getType()->getUnsignedVersion());
1730   }
1731
1732   // If this is an sign or zero extending cast and we can prove that the value
1733   // will never overflow, we could do similar transformations.
1734
1735   // Otherwise, we can't handle this cast!
1736   return SCEVUnknown::get(CI);
1737 }
1738
1739
1740 /// createSCEV - We know that there is no SCEV for the specified value.
1741 /// Analyze the expression.
1742 ///
1743 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1744   if (Instruction *I = dyn_cast<Instruction>(V)) {
1745     switch (I->getOpcode()) {
1746     case Instruction::Add:
1747       return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1748                               getSCEV(I->getOperand(1)));
1749     case Instruction::Mul:
1750       return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1751                               getSCEV(I->getOperand(1)));
1752     case Instruction::Div:
1753       if (V->getType()->isInteger() && V->getType()->isUnsigned())
1754         return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1755                                  getSCEV(I->getOperand(1)));
1756       break;
1757
1758     case Instruction::Sub:
1759       return getMinusSCEV(getSCEV(I->getOperand(0)), getSCEV(I->getOperand(1)));
1760
1761     case Instruction::Shl:
1762       // Turn shift left of a constant amount into a multiply.
1763       if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1764         Constant *X = ConstantInt::get(V->getType(), 1);
1765         X = ConstantExpr::getShl(X, SA);
1766         return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1767       }
1768       break;
1769
1770     case Instruction::Shr:
1771       if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1772         if (V->getType()->isUnsigned()) {
1773           Constant *X = ConstantInt::get(V->getType(), 1);
1774           X = ConstantExpr::getShl(X, SA);
1775           return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1776         }
1777       break;
1778
1779     case Instruction::Cast:
1780       return createNodeForCast(cast<CastInst>(I));
1781
1782     case Instruction::PHI:
1783       return createNodeForPHI(cast<PHINode>(I));
1784
1785     default: // We cannot analyze this expression.
1786       break;
1787     }
1788   }
1789
1790   return SCEVUnknown::get(V);
1791 }
1792
1793
1794
1795 //===----------------------------------------------------------------------===//
1796 //                   Iteration Count Computation Code
1797 //
1798
1799 /// getIterationCount - If the specified loop has a predictable iteration
1800 /// count, return it.  Note that it is not valid to call this method on a
1801 /// loop without a loop-invariant iteration count.
1802 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1803   std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1804   if (I == IterationCounts.end()) {
1805     SCEVHandle ItCount = ComputeIterationCount(L);
1806     I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1807     if (ItCount != UnknownValue) {
1808       assert(ItCount->isLoopInvariant(L) &&
1809              "Computed trip count isn't loop invariant for loop!");
1810       ++NumTripCountsComputed;
1811     } else if (isa<PHINode>(L->getHeader()->begin())) {
1812       // Only count loops that have phi nodes as not being computable.
1813       ++NumTripCountsNotComputed;
1814     }
1815   }
1816   return I->second;
1817 }
1818
1819 /// ComputeIterationCount - Compute the number of times the specified loop
1820 /// will iterate.
1821 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1822   // If the loop has a non-one exit block count, we can't analyze it.
1823   if (L->getExitBlocks().size() != 1) return UnknownValue;
1824
1825   // Okay, there is one exit block.  Try to find the condition that causes the
1826   // loop to be exited.
1827   BasicBlock *ExitBlock = L->getExitBlocks()[0];
1828
1829   BasicBlock *ExitingBlock = 0;
1830   for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1831        PI != E; ++PI)
1832     if (L->contains(*PI)) {
1833       if (ExitingBlock == 0)
1834         ExitingBlock = *PI;
1835       else
1836         return UnknownValue;   // More than one block exiting!
1837     }
1838   assert(ExitingBlock && "No exits from loop, something is broken!");
1839
1840   // Okay, we've computed the exiting block.  See what condition causes us to
1841   // exit.
1842   //
1843   // FIXME: we should be able to handle switch instructions (with a single exit)
1844   // FIXME: We should handle cast of int to bool as well
1845   BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1846   if (ExitBr == 0) return UnknownValue;
1847   assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1848   SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
1849   if (ExitCond == 0) return UnknownValue;
1850
1851   SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1852   SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1853
1854   // Try to evaluate any dependencies out of the loop.
1855   SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1856   if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1857   Tmp = getSCEVAtScope(RHS, L);
1858   if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1859
1860   // If the condition was exit on true, convert the condition to exit on false.
1861   Instruction::BinaryOps Cond;
1862   if (ExitBr->getSuccessor(1) == ExitBlock)
1863     Cond = ExitCond->getOpcode();
1864   else
1865     Cond = ExitCond->getInverseCondition();
1866
1867   // At this point, we would like to compute how many iterations of the loop the
1868   // predicate will return true for these inputs.
1869   if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1870     // If there is a constant, force it into the RHS.
1871     std::swap(LHS, RHS);
1872     Cond = SetCondInst::getSwappedCondition(Cond);
1873   }
1874
1875   // FIXME: think about handling pointer comparisons!  i.e.:
1876   // while (P != P+100) ++P;
1877
1878   // If we have a comparison of a chrec against a constant, try to use value
1879   // ranges to answer this query.
1880   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1881     if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1882       if (AddRec->getLoop() == L) {
1883         // Form the comparison range using the constant of the correct type so
1884         // that the ConstantRange class knows to do a signed or unsigned
1885         // comparison.
1886         ConstantInt *CompVal = RHSC->getValue();
1887         const Type *RealTy = ExitCond->getOperand(0)->getType();
1888         CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1889         if (CompVal) {
1890           // Form the constant range.
1891           ConstantRange CompRange(Cond, CompVal);
1892           
1893           // Now that we have it, if it's signed, convert it to an unsigned
1894           // range.
1895           if (CompRange.getLower()->getType()->isSigned()) {
1896             const Type *NewTy = RHSC->getValue()->getType();
1897             Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1898             Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1899             CompRange = ConstantRange(NewL, NewU);
1900           }
1901           
1902           SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1903           if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1904         }
1905       }
1906   
1907   switch (Cond) {
1908   case Instruction::SetNE:                     // while (X != Y)
1909     // Convert to: while (X-Y != 0)
1910     if (LHS->getType()->isInteger())
1911       return HowFarToZero(getMinusSCEV(LHS, RHS), L);
1912     break;
1913   case Instruction::SetEQ:
1914     // Convert to: while (X-Y == 0)           // while (X == Y)
1915     if (LHS->getType()->isInteger())
1916       return HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
1917     break;
1918   default:
1919 #if 0
1920     std::cerr << "ComputeIterationCount ";
1921     if (ExitCond->getOperand(0)->getType()->isUnsigned())
1922       std::cerr << "[unsigned] ";
1923     std::cerr << *LHS << "   "
1924               << Instruction::getOpcodeName(Cond) << "   " << *RHS << "\n";
1925 #endif
1926     break;
1927   }
1928   return UnknownValue;
1929 }
1930
1931 /// getSCEVAtScope - Compute the value of the specified expression within the
1932 /// indicated loop (which may be null to indicate in no loop).  If the
1933 /// expression cannot be evaluated, return UnknownValue.
1934 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1935   // FIXME: this should be turned into a virtual method on SCEV!
1936
1937   if (isa<SCEVConstant>(V) || isa<SCEVUnknown>(V)) return V;
1938   if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1939     // Avoid performing the look-up in the common case where the specified
1940     // expression has no loop-variant portions.
1941     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1942       SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1943       if (OpAtScope != Comm->getOperand(i)) {
1944         if (OpAtScope == UnknownValue) return UnknownValue;
1945         // Okay, at least one of these operands is loop variant but might be
1946         // foldable.  Build a new instance of the folded commutative expression.
1947         std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i-1);
1948         NewOps.push_back(OpAtScope);
1949
1950         for (++i; i != e; ++i) {
1951           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1952           if (OpAtScope == UnknownValue) return UnknownValue;
1953           NewOps.push_back(OpAtScope);
1954         }
1955         if (isa<SCEVAddExpr>(Comm))
1956           return SCEVAddExpr::get(NewOps);
1957         assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1958         return SCEVMulExpr::get(NewOps);
1959       }
1960     }
1961     // If we got here, all operands are loop invariant.
1962     return Comm;
1963   }
1964
1965   if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1966     SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1967     if (LHS == UnknownValue) return LHS;
1968     SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1969     if (RHS == UnknownValue) return RHS;
1970     if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1971       return UDiv;   // must be loop invariant
1972     return SCEVUDivExpr::get(LHS, RHS);
1973   }
1974
1975   // If this is a loop recurrence for a loop that does not contain L, then we
1976   // are dealing with the final value computed by the loop.
1977   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1978     if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1979       // To evaluate this recurrence, we need to know how many times the AddRec
1980       // loop iterates.  Compute this now.
1981       SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1982       if (IterationCount == UnknownValue) return UnknownValue;
1983       IterationCount = getTruncateOrZeroExtend(IterationCount,
1984                                                AddRec->getType());
1985       
1986       // If the value is affine, simplify the expression evaluation to just
1987       // Start + Step*IterationCount.
1988       if (AddRec->isAffine())
1989         return SCEVAddExpr::get(AddRec->getStart(),
1990                                 SCEVMulExpr::get(IterationCount,
1991                                                  AddRec->getOperand(1)));
1992
1993       // Otherwise, evaluate it the hard way.
1994       return AddRec->evaluateAtIteration(IterationCount);
1995     }
1996     return UnknownValue;
1997   }
1998
1999   //assert(0 && "Unknown SCEV type!");
2000   return UnknownValue;
2001 }
2002
2003
2004 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2005 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
2006 /// might be the same) or two SCEVCouldNotCompute objects.
2007 ///
2008 static std::pair<SCEVHandle,SCEVHandle>
2009 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2010   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2011   SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2012   SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2013   SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2014   
2015   // We currently can only solve this if the coefficients are constants.
2016   if (!L || !M || !N) {
2017     SCEV *CNC = new SCEVCouldNotCompute();
2018     return std::make_pair(CNC, CNC);
2019   }
2020
2021   Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
2022   
2023   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2024   Constant *C = L->getValue();
2025   // The B coefficient is M-N/2
2026   Constant *B = ConstantExpr::getSub(M->getValue(),
2027                                      ConstantExpr::getDiv(N->getValue(),
2028                                                           Two));
2029   // The A coefficient is N/2
2030   Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
2031         
2032   // Compute the B^2-4ac term.
2033   Constant *SqrtTerm =
2034     ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2035                          ConstantExpr::getMul(A, C));
2036   SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2037
2038   // Compute floor(sqrt(B^2-4ac))
2039   ConstantUInt *SqrtVal =
2040     cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
2041                                    SqrtTerm->getType()->getUnsignedVersion()));
2042   uint64_t SqrtValV = SqrtVal->getValue();
2043   uint64_t SqrtValV2 = (uint64_t)sqrtl(SqrtValV);
2044   // The square root might not be precise for arbitrary 64-bit integer
2045   // values.  Do some sanity checks to ensure it's correct.
2046   if (SqrtValV2*SqrtValV2 > SqrtValV ||
2047       (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2048     SCEV *CNC = new SCEVCouldNotCompute();
2049     return std::make_pair(CNC, CNC);
2050   }
2051
2052   SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
2053   SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
2054   
2055   Constant *NegB = ConstantExpr::getNeg(B);
2056   Constant *TwoA = ConstantExpr::getMul(A, Two);
2057   
2058   // The divisions must be performed as signed divisions.
2059   const Type *SignedTy = NegB->getType()->getSignedVersion();
2060   NegB = ConstantExpr::getCast(NegB, SignedTy);
2061   TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2062   SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
2063   
2064   Constant *Solution1 =
2065     ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2066   Constant *Solution2 =
2067     ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2068   return std::make_pair(SCEVUnknown::get(Solution1),
2069                         SCEVUnknown::get(Solution2));
2070 }
2071
2072 /// HowFarToZero - Return the number of times a backedge comparing the specified
2073 /// value to zero will execute.  If not computable, return UnknownValue
2074 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2075   // If the value is a constant
2076   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2077     // If the value is already zero, the branch will execute zero times.
2078     if (C->getValue()->isNullValue()) return C;
2079     return UnknownValue;  // Otherwise it will loop infinitely.
2080   }
2081
2082   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2083   if (!AddRec || AddRec->getLoop() != L)
2084     return UnknownValue;
2085
2086   if (AddRec->isAffine()) {
2087     // If this is an affine expression the execution count of this branch is
2088     // equal to:
2089     //
2090     //     (0 - Start/Step)    iff   Start % Step == 0
2091     //
2092     // Get the initial value for the loop.
2093     SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2094     SCEVHandle Step = AddRec->getOperand(1);
2095
2096     Step = getSCEVAtScope(Step, L->getParentLoop());
2097
2098     // Figure out if Start % Step == 0.
2099     // FIXME: We should add DivExpr and RemExpr operations to our AST.
2100     if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2101       if (StepC->getValue()->equalsInt(1))      // N % 1 == 0
2102         return getNegativeSCEV(Start);  // 0 - Start/1 == -Start
2103       if (StepC->getValue()->isAllOnesValue())  // N % -1 == 0
2104         return Start;                   // 0 - Start/-1 == Start
2105
2106       // Check to see if Start is divisible by SC with no remainder.
2107       if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2108         ConstantInt *StartCC = StartC->getValue();
2109         Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2110         Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
2111         if (Rem->isNullValue()) {
2112           Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
2113           return SCEVUnknown::get(Result);
2114         }
2115       }
2116     }
2117   } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2118     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2119     // the quadratic equation to solve it.
2120     std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2121     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2122     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2123     if (R1) {
2124 #if 0
2125       std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2126                 << "  sol#2: " << *R2 << "\n";
2127 #endif
2128       // Pick the smallest positive root value.
2129       assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2130       if (ConstantBool *CB =
2131           dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2132                                                         R2->getValue()))) {
2133         if (CB != ConstantBool::True)
2134           std::swap(R1, R2);   // R1 is the minimum root now.
2135           
2136         // We can only use this value if the chrec ends up with an exact zero
2137         // value at this index.  When solving for "X*X != 5", for example, we
2138         // should not accept a root of 2.
2139         SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2140         if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2141           if (EvalVal->getValue()->isNullValue())
2142             return R1;  // We found a quadratic root!
2143       }
2144     }
2145   }
2146   
2147   return UnknownValue;
2148 }
2149
2150 /// HowFarToNonZero - Return the number of times a backedge checking the
2151 /// specified value for nonzero will execute.  If not computable, return
2152 /// UnknownValue
2153 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2154   // Loops that look like: while (X == 0) are very strange indeed.  We don't
2155   // handle them yet except for the trivial case.  This could be expanded in the
2156   // future as needed.
2157  
2158   // If the value is a constant, check to see if it is known to be non-zero
2159   // already.  If so, the backedge will execute zero times.
2160   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2161     Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2162     Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2163     if (NonZero == ConstantBool::True)
2164       return getSCEV(Zero);
2165     return UnknownValue;  // Otherwise it will loop infinitely.
2166   }
2167   
2168   // We could implement others, but I really doubt anyone writes loops like
2169   // this, and if they did, they would already be constant folded.
2170   return UnknownValue;
2171 }
2172
2173 static ConstantInt *
2174 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
2175   SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
2176   SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
2177   assert(isa<SCEVConstant>(Val) &&
2178          "Evaluation of SCEV at constant didn't fold correctly?");
2179   return cast<SCEVConstant>(Val)->getValue();
2180 }
2181
2182
2183 /// getNumIterationsInRange - Return the number of iterations of this loop that
2184 /// produce values in the specified constant range.  Another way of looking at
2185 /// this is that it returns the first iteration number where the value is not in
2186 /// the condition, thus computing the exit count. If the iteration count can't
2187 /// be computed, an instance of SCEVCouldNotCompute is returned.
2188 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2189   if (Range.isFullSet())  // Infinite loop.
2190     return new SCEVCouldNotCompute();
2191
2192   // If the start is a non-zero constant, shift the range to simplify things.
2193   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2194     if (!SC->getValue()->isNullValue()) {
2195       std::vector<SCEVHandle> Operands(op_begin(), op_end());
2196       Operands[0] = getIntegerSCEV(0, SC->getType());
2197       SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2198       if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2199         return ShiftedAddRec->getNumIterationsInRange(
2200                                               Range.subtract(SC->getValue()));
2201       // This is strange and shouldn't happen.
2202       return new SCEVCouldNotCompute();
2203     }
2204
2205   // The only time we can solve this is when we have all constant indices.
2206   // Otherwise, we cannot determine the overflow conditions.
2207   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2208     if (!isa<SCEVConstant>(getOperand(i)))
2209       return new SCEVCouldNotCompute();
2210
2211
2212   // Okay at this point we know that all elements of the chrec are constants and
2213   // that the start element is zero.
2214
2215   // First check to see if the range contains zero.  If not, the first
2216   // iteration exits.
2217   ConstantInt *Zero = ConstantInt::get(getType(), 0);
2218   if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2219   
2220   if (isAffine()) {
2221     // If this is an affine expression then we have this situation:
2222     //   Solve {0,+,A} in Range  ===  Ax in Range
2223
2224     // Since we know that zero is in the range, we know that the upper value of
2225     // the range must be the first possible exit value.  Also note that we
2226     // already checked for a full range.
2227     ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2228     ConstantInt *A     = cast<SCEVConstant>(getOperand(1))->getValue();
2229     ConstantInt *One   = ConstantInt::get(getType(), 1);
2230
2231     // The exit value should be (Upper+A-1)/A.
2232     Constant *ExitValue = Upper;
2233     if (A != One) {
2234       ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2235       ExitValue = ConstantExpr::getDiv(ExitValue, A);
2236     }
2237     assert(isa<ConstantInt>(ExitValue) &&
2238            "Constant folding of integers not implemented?");
2239
2240     // Evaluate at the exit value.  If we really did fall out of the valid
2241     // range, then we computed our trip count, otherwise wrap around or other
2242     // things must have happened.
2243     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2244     if (Range.contains(Val))
2245       return new SCEVCouldNotCompute();  // Something strange happened
2246
2247     // Ensure that the previous value is in the range.  This is a sanity check.
2248     assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2249                               ConstantExpr::getSub(ExitValue, One))) &&
2250            "Linear scev computation is off in a bad way!");
2251     return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2252   } else if (isQuadratic()) {
2253     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2254     // quadratic equation to solve it.  To do this, we must frame our problem in
2255     // terms of figuring out when zero is crossed, instead of when
2256     // Range.getUpper() is crossed.
2257     std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2258     NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2259     SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2260
2261     // Next, solve the constructed addrec
2262     std::pair<SCEVHandle,SCEVHandle> Roots =
2263       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2264     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2265     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2266     if (R1) {
2267       // Pick the smallest positive root value.
2268       assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2269       if (ConstantBool *CB =
2270           dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2271                                                         R2->getValue()))) {
2272         if (CB != ConstantBool::True)
2273           std::swap(R1, R2);   // R1 is the minimum root now.
2274           
2275         // Make sure the root is not off by one.  The returned iteration should
2276         // not be in the range, but the previous one should be.  When solving
2277         // for "X*X < 5", for example, we should not return a root of 2.
2278         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2279                                                              R1->getValue());
2280         if (Range.contains(R1Val)) {
2281           // The next iteration must be out of the range...
2282           Constant *NextVal =
2283             ConstantExpr::getAdd(R1->getValue(),
2284                                  ConstantInt::get(R1->getType(), 1));
2285           
2286           R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2287           if (!Range.contains(R1Val))
2288             return SCEVUnknown::get(NextVal);
2289           return new SCEVCouldNotCompute();  // Something strange happened
2290         }
2291    
2292         // If R1 was not in the range, then it is a good return value.  Make
2293         // sure that R1-1 WAS in the range though, just in case.
2294         Constant *NextVal =
2295           ConstantExpr::getSub(R1->getValue(),
2296                                ConstantInt::get(R1->getType(), 1));
2297         R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2298         if (Range.contains(R1Val))
2299           return R1;
2300         return new SCEVCouldNotCompute();  // Something strange happened
2301       }
2302     }
2303   }
2304
2305   // Fallback, if this is a general polynomial, figure out the progression
2306   // through brute force: evaluate until we find an iteration that fails the
2307   // test.  This is likely to be slow, but getting an accurate trip count is
2308   // incredibly important, we will be able to simplify the exit test a lot, and
2309   // we are almost guaranteed to get a trip count in this case.
2310   ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2311   ConstantInt *One     = ConstantInt::get(getType(), 1);
2312   ConstantInt *EndVal  = TestVal;  // Stop when we wrap around.
2313   do {
2314     ++NumBruteForceEvaluations;
2315     SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2316     if (!isa<SCEVConstant>(Val))  // This shouldn't happen.
2317       return new SCEVCouldNotCompute();
2318
2319     // Check to see if we found the value!
2320     if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2321       return SCEVConstant::get(TestVal);
2322
2323     // Increment to test the next index.
2324     TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2325   } while (TestVal != EndVal);
2326   
2327   return new SCEVCouldNotCompute();
2328 }
2329
2330
2331
2332 //===----------------------------------------------------------------------===//
2333 //                   ScalarEvolution Class Implementation
2334 //===----------------------------------------------------------------------===//
2335
2336 bool ScalarEvolution::runOnFunction(Function &F) {
2337   Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2338   return false;
2339 }
2340
2341 void ScalarEvolution::releaseMemory() {
2342   delete (ScalarEvolutionsImpl*)Impl;
2343   Impl = 0;
2344 }
2345
2346 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2347   AU.setPreservesAll();
2348   AU.addRequiredID(LoopSimplifyID);
2349   AU.addRequiredTransitive<LoopInfo>();
2350 }
2351
2352 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2353   return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2354 }
2355
2356 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2357   return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2358 }
2359
2360 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2361   return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2362 }
2363
2364 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2365   return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2366 }
2367
2368 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2369   return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2370 }
2371
2372
2373 /// shouldSubstituteIndVar - Return true if we should perform induction variable
2374 /// substitution for this variable.  This is a hack because we don't have a
2375 /// strength reduction pass yet.  When we do we will promote all vars, because
2376 /// we can strength reduce them later as desired.
2377 bool ScalarEvolution::shouldSubstituteIndVar(const SCEV *S) const {
2378   // Don't substitute high degree polynomials.
2379   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S))
2380     if (AddRec->getNumOperands() > 3) return false;
2381   return true;
2382 }
2383
2384
2385 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE, 
2386                           const Loop *L) {
2387   // Print all inner loops first
2388   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2389     PrintLoopInfo(OS, SE, *I);
2390   
2391   std::cerr << "Loop " << L->getHeader()->getName() << ": ";
2392   if (L->getExitBlocks().size() != 1)
2393     std::cerr << "<multiple exits> ";
2394
2395   if (SE->hasLoopInvariantIterationCount(L)) {
2396     std::cerr << *SE->getIterationCount(L) << " iterations! ";
2397   } else {
2398     std::cerr << "Unpredictable iteration count. ";
2399   }
2400
2401   std::cerr << "\n";
2402 }
2403
2404 void ScalarEvolution::print(std::ostream &OS) const {
2405   Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2406   LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2407
2408   OS << "Classifying expressions for: " << F.getName() << "\n";
2409   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2410     if ((*I)->getType()->isInteger()) {
2411       OS << **I;
2412       OS << "  --> ";
2413       SCEVHandle SV = getSCEV(*I);
2414       SV->print(OS);
2415       OS << "\t\t";
2416       
2417       if ((*I)->getType()->isIntegral()) {
2418         ConstantRange Bounds = SV->getValueRange();
2419         if (!Bounds.isFullSet())
2420           OS << "Bounds: " << Bounds << " ";
2421       }
2422
2423       if (const Loop *L = LI.getLoopFor((*I)->getParent())) {
2424         OS << "Exits: ";
2425         SCEVHandle ExitValue = getSCEVAtScope(*I, L->getParentLoop());
2426         if (isa<SCEVCouldNotCompute>(ExitValue)) {
2427           OS << "<<Unknown>>";
2428         } else {
2429           OS << *ExitValue;
2430         }
2431       }
2432
2433
2434       OS << "\n";
2435     }
2436
2437   OS << "Determining loop execution counts for: " << F.getName() << "\n";
2438   for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2439     PrintLoopInfo(OS, this, *I);
2440 }
2441
2442 //===----------------------------------------------------------------------===//
2443 //                ScalarEvolutionRewriter Class Implementation
2444 //===----------------------------------------------------------------------===//
2445
2446 Value *ScalarEvolutionRewriter::
2447 GetOrInsertCanonicalInductionVariable(const Loop *L, const Type *Ty) {
2448   assert((Ty->isInteger() || Ty->isFloatingPoint()) &&
2449          "Can only insert integer or floating point induction variables!");
2450
2451   // Check to see if we already inserted one.
2452   SCEVHandle H = SCEVAddRecExpr::get(getIntegerSCEV(0, Ty),
2453                                      getIntegerSCEV(1, Ty), L);
2454   return ExpandCodeFor(H, 0, Ty);
2455 }
2456
2457 /// ExpandCodeFor - Insert code to directly compute the specified SCEV
2458 /// expression into the program.  The inserted code is inserted into the
2459 /// specified block.
2460 Value *ScalarEvolutionRewriter::ExpandCodeFor(SCEVHandle SH,
2461                                               Instruction *InsertPt,
2462                                               const Type *Ty) {
2463   std::map<SCEVHandle, Value*>::iterator ExistVal =InsertedExpressions.find(SH);
2464   Value *V;
2465   if (ExistVal != InsertedExpressions.end()) {
2466     V = ExistVal->second;
2467   } else {
2468     // Ask the recurrence object to expand the code for itself.
2469     V = SH->expandCodeFor(*this, InsertPt);
2470     // Cache the generated result.
2471     InsertedExpressions.insert(std::make_pair(SH, V));
2472   }
2473
2474   if (Ty == 0 || V->getType() == Ty)
2475     return V;
2476   if (Constant *C = dyn_cast<Constant>(V))
2477     return ConstantExpr::getCast(C, Ty);
2478   else if (Instruction *I = dyn_cast<Instruction>(V)) {
2479     // FIXME: check to see if there is already a cast!
2480     BasicBlock::iterator IP = I; ++IP;
2481     if (InvokeInst *II = dyn_cast<InvokeInst>(I))
2482       IP = II->getNormalDest()->begin();
2483     while (isa<PHINode>(IP)) ++IP;
2484     return new CastInst(V, Ty, V->getName(), IP);
2485   } else {
2486     // FIXME: check to see if there is already a cast!
2487     return new CastInst(V, Ty, V->getName(), InsertPt);
2488   }
2489 }