Add a new analysis
[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     std::cerr << "ComputeIterationCount ";
1920     if (ExitCond->getOperand(0)->getType()->isUnsigned())
1921       std::cerr << "[unsigned] ";
1922     std::cerr << *LHS << "   "
1923               << Instruction::getOpcodeName(Cond) << "   " << *RHS << "\n";
1924   }
1925   return UnknownValue;
1926 }
1927
1928 /// getSCEVAtScope - Compute the value of the specified expression within the
1929 /// indicated loop (which may be null to indicate in no loop).  If the
1930 /// expression cannot be evaluated, return UnknownValue.
1931 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1932   // FIXME: this should be turned into a virtual method on SCEV!
1933
1934   if (isa<SCEVConstant>(V) || isa<SCEVUnknown>(V)) return V;
1935   if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1936     // Avoid performing the look-up in the common case where the specified
1937     // expression has no loop-variant portions.
1938     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1939       SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1940       if (OpAtScope != Comm->getOperand(i)) {
1941         if (OpAtScope == UnknownValue) return UnknownValue;
1942         // Okay, at least one of these operands is loop variant but might be
1943         // foldable.  Build a new instance of the folded commutative expression.
1944         std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i-1);
1945         NewOps.push_back(OpAtScope);
1946
1947         for (++i; i != e; ++i) {
1948           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1949           if (OpAtScope == UnknownValue) return UnknownValue;
1950           NewOps.push_back(OpAtScope);
1951         }
1952         if (isa<SCEVAddExpr>(Comm))
1953           return SCEVAddExpr::get(NewOps);
1954         assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1955         return SCEVMulExpr::get(NewOps);
1956       }
1957     }
1958     // If we got here, all operands are loop invariant.
1959     return Comm;
1960   }
1961
1962   if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1963     SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1964     if (LHS == UnknownValue) return LHS;
1965     SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1966     if (RHS == UnknownValue) return RHS;
1967     if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1968       return UDiv;   // must be loop invariant
1969     return SCEVUDivExpr::get(LHS, RHS);
1970   }
1971
1972   // If this is a loop recurrence for a loop that does not contain L, then we
1973   // are dealing with the final value computed by the loop.
1974   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1975     if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1976       // To evaluate this recurrence, we need to know how many times the AddRec
1977       // loop iterates.  Compute this now.
1978       SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1979       if (IterationCount == UnknownValue) return UnknownValue;
1980       IterationCount = getTruncateOrZeroExtend(IterationCount,
1981                                                AddRec->getType());
1982       
1983       // If the value is affine, simplify the expression evaluation to just
1984       // Start + Step*IterationCount.
1985       if (AddRec->isAffine())
1986         return SCEVAddExpr::get(AddRec->getStart(),
1987                                 SCEVMulExpr::get(IterationCount,
1988                                                  AddRec->getOperand(1)));
1989
1990       // Otherwise, evaluate it the hard way.
1991       return AddRec->evaluateAtIteration(IterationCount);
1992     }
1993     return UnknownValue;
1994   }
1995
1996   //assert(0 && "Unknown SCEV type!");
1997   return UnknownValue;
1998 }
1999
2000
2001 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2002 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
2003 /// might be the same) or two SCEVCouldNotCompute objects.
2004 ///
2005 static std::pair<SCEVHandle,SCEVHandle>
2006 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2007   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2008   SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2009   SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2010   SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2011   
2012   // We currently can only solve this if the coefficients are constants.
2013   if (!L || !M || !N) {
2014     SCEV *CNC = new SCEVCouldNotCompute();
2015     return std::make_pair(CNC, CNC);
2016   }
2017
2018   Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
2019   
2020   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2021   Constant *C = L->getValue();
2022   // The B coefficient is M-N/2
2023   Constant *B = ConstantExpr::getSub(M->getValue(),
2024                                      ConstantExpr::getDiv(N->getValue(),
2025                                                           Two));
2026   // The A coefficient is N/2
2027   Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
2028         
2029   // Compute the B^2-4ac term.
2030   Constant *SqrtTerm =
2031     ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2032                          ConstantExpr::getMul(A, C));
2033   SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2034
2035   // Compute floor(sqrt(B^2-4ac))
2036   ConstantUInt *SqrtVal =
2037     cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
2038                                    SqrtTerm->getType()->getUnsignedVersion()));
2039   uint64_t SqrtValV = SqrtVal->getValue();
2040   uint64_t SqrtValV2 = (uint64_t)sqrtl(SqrtValV);
2041   // The square root might not be precise for arbitrary 64-bit integer
2042   // values.  Do some sanity checks to ensure it's correct.
2043   if (SqrtValV2*SqrtValV2 > SqrtValV ||
2044       (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2045     SCEV *CNC = new SCEVCouldNotCompute();
2046     return std::make_pair(CNC, CNC);
2047   }
2048
2049   SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
2050   SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
2051   
2052   Constant *NegB = ConstantExpr::getNeg(B);
2053   Constant *TwoA = ConstantExpr::getMul(A, Two);
2054   
2055   // The divisions must be performed as signed divisions.
2056   const Type *SignedTy = NegB->getType()->getSignedVersion();
2057   NegB = ConstantExpr::getCast(NegB, SignedTy);
2058   TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2059   SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
2060   
2061   Constant *Solution1 =
2062     ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2063   Constant *Solution2 =
2064     ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2065   return std::make_pair(SCEVUnknown::get(Solution1),
2066                         SCEVUnknown::get(Solution2));
2067 }
2068
2069 /// HowFarToZero - Return the number of times a backedge comparing the specified
2070 /// value to zero will execute.  If not computable, return UnknownValue
2071 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2072   // If the value is a constant
2073   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2074     // If the value is already zero, the branch will execute zero times.
2075     if (C->getValue()->isNullValue()) return C;
2076     return UnknownValue;  // Otherwise it will loop infinitely.
2077   }
2078
2079   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2080   if (!AddRec || AddRec->getLoop() != L)
2081     return UnknownValue;
2082
2083   if (AddRec->isAffine()) {
2084     // If this is an affine expression the execution count of this branch is
2085     // equal to:
2086     //
2087     //     (0 - Start/Step)    iff   Start % Step == 0
2088     //
2089     // Get the initial value for the loop.
2090     SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2091     SCEVHandle Step = AddRec->getOperand(1);
2092
2093     Step = getSCEVAtScope(Step, L->getParentLoop());
2094
2095     // Figure out if Start % Step == 0.
2096     // FIXME: We should add DivExpr and RemExpr operations to our AST.
2097     if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2098       if (StepC->getValue()->equalsInt(1))      // N % 1 == 0
2099         return getNegativeSCEV(Start);  // 0 - Start/1 == -Start
2100       if (StepC->getValue()->isAllOnesValue())  // N % -1 == 0
2101         return Start;                   // 0 - Start/-1 == Start
2102
2103       // Check to see if Start is divisible by SC with no remainder.
2104       if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2105         ConstantInt *StartCC = StartC->getValue();
2106         Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2107         Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
2108         if (Rem->isNullValue()) {
2109           Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
2110           return SCEVUnknown::get(Result);
2111         }
2112       }
2113     }
2114   } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2115     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2116     // the quadratic equation to solve it.
2117     std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2118     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2119     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2120     if (R1) {
2121       std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2122                 << "  sol#2: " << *R2 << "\n";
2123       // Pick the smallest positive root value.
2124       assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2125       if (ConstantBool *CB =
2126           dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2127                                                         R2->getValue()))) {
2128         if (CB != ConstantBool::True)
2129           std::swap(R1, R2);   // R1 is the minimum root now.
2130           
2131         // We can only use this value if the chrec ends up with an exact zero
2132         // value at this index.  When solving for "X*X != 5", for example, we
2133         // should not accept a root of 2.
2134         SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2135         if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2136           if (EvalVal->getValue()->isNullValue())
2137             return R1;  // We found a quadratic root!
2138       }
2139     }
2140   }
2141   
2142   return UnknownValue;
2143 }
2144
2145 /// HowFarToNonZero - Return the number of times a backedge checking the
2146 /// specified value for nonzero will execute.  If not computable, return
2147 /// UnknownValue
2148 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2149   // Loops that look like: while (X == 0) are very strange indeed.  We don't
2150   // handle them yet except for the trivial case.  This could be expanded in the
2151   // future as needed.
2152  
2153   // If the value is a constant, check to see if it is known to be non-zero
2154   // already.  If so, the backedge will execute zero times.
2155   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2156     Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2157     Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2158     if (NonZero == ConstantBool::True)
2159       return getSCEV(Zero);
2160     return UnknownValue;  // Otherwise it will loop infinitely.
2161   }
2162   
2163   // We could implement others, but I really doubt anyone writes loops like
2164   // this, and if they did, they would already be constant folded.
2165   return UnknownValue;
2166 }
2167
2168 static ConstantInt *
2169 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
2170   SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
2171   SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
2172   assert(isa<SCEVConstant>(Val) &&
2173          "Evaluation of SCEV at constant didn't fold correctly?");
2174   return cast<SCEVConstant>(Val)->getValue();
2175 }
2176
2177
2178 /// getNumIterationsInRange - Return the number of iterations of this loop that
2179 /// produce values in the specified constant range.  Another way of looking at
2180 /// this is that it returns the first iteration number where the value is not in
2181 /// the condition, thus computing the exit count. If the iteration count can't
2182 /// be computed, an instance of SCEVCouldNotCompute is returned.
2183 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2184   if (Range.isFullSet())  // Infinite loop.
2185     return new SCEVCouldNotCompute();
2186
2187   // If the start is a non-zero constant, shift the range to simplify things.
2188   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2189     if (!SC->getValue()->isNullValue()) {
2190       std::vector<SCEVHandle> Operands(op_begin(), op_end());
2191       Operands[0] = getIntegerSCEV(0, SC->getType());
2192       SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2193       if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2194         return ShiftedAddRec->getNumIterationsInRange(
2195                                               Range.subtract(SC->getValue()));
2196       // This is strange and shouldn't happen.
2197       return new SCEVCouldNotCompute();
2198     }
2199
2200   // The only time we can solve this is when we have all constant indices.
2201   // Otherwise, we cannot determine the overflow conditions.
2202   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2203     if (!isa<SCEVConstant>(getOperand(i)))
2204       return new SCEVCouldNotCompute();
2205
2206
2207   // Okay at this point we know that all elements of the chrec are constants and
2208   // that the start element is zero.
2209
2210   // First check to see if the range contains zero.  If not, the first
2211   // iteration exits.
2212   ConstantInt *Zero = ConstantInt::get(getType(), 0);
2213   if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2214   
2215   if (isAffine()) {
2216     // If this is an affine expression then we have this situation:
2217     //   Solve {0,+,A} in Range  ===  Ax in Range
2218
2219     // Since we know that zero is in the range, we know that the upper value of
2220     // the range must be the first possible exit value.  Also note that we
2221     // already checked for a full range.
2222     ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2223     ConstantInt *A     = cast<SCEVConstant>(getOperand(1))->getValue();
2224     ConstantInt *One   = ConstantInt::get(getType(), 1);
2225
2226     // The exit value should be (Upper+A-1)/A.
2227     Constant *ExitValue = Upper;
2228     if (A != One) {
2229       ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2230       ExitValue = ConstantExpr::getDiv(ExitValue, A);
2231     }
2232     assert(isa<ConstantInt>(ExitValue) &&
2233            "Constant folding of integers not implemented?");
2234
2235     // Evaluate at the exit value.  If we really did fall out of the valid
2236     // range, then we computed our trip count, otherwise wrap around or other
2237     // things must have happened.
2238     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2239     if (Range.contains(Val))
2240       return new SCEVCouldNotCompute();  // Something strange happened
2241
2242     // Ensure that the previous value is in the range.  This is a sanity check.
2243     assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2244                               ConstantExpr::getSub(ExitValue, One))) &&
2245            "Linear scev computation is off in a bad way!");
2246     return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2247   } else if (isQuadratic()) {
2248     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2249     // quadratic equation to solve it.  To do this, we must frame our problem in
2250     // terms of figuring out when zero is crossed, instead of when
2251     // Range.getUpper() is crossed.
2252     std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2253     NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2254     SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2255
2256     // Next, solve the constructed addrec
2257     std::pair<SCEVHandle,SCEVHandle> Roots =
2258       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2259     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2260     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2261     if (R1) {
2262       // Pick the smallest positive root value.
2263       assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2264       if (ConstantBool *CB =
2265           dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2266                                                         R2->getValue()))) {
2267         if (CB != ConstantBool::True)
2268           std::swap(R1, R2);   // R1 is the minimum root now.
2269           
2270         // Make sure the root is not off by one.  The returned iteration should
2271         // not be in the range, but the previous one should be.  When solving
2272         // for "X*X < 5", for example, we should not return a root of 2.
2273         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2274                                                              R1->getValue());
2275         if (Range.contains(R1Val)) {
2276           // The next iteration must be out of the range...
2277           Constant *NextVal =
2278             ConstantExpr::getAdd(R1->getValue(),
2279                                  ConstantInt::get(R1->getType(), 1));
2280           
2281           R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2282           if (!Range.contains(R1Val))
2283             return SCEVUnknown::get(NextVal);
2284           return new SCEVCouldNotCompute();  // Something strange happened
2285         }
2286    
2287         // If R1 was not in the range, then it is a good return value.  Make
2288         // sure that R1-1 WAS in the range though, just in case.
2289         Constant *NextVal =
2290           ConstantExpr::getSub(R1->getValue(),
2291                                ConstantInt::get(R1->getType(), 1));
2292         R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2293         if (Range.contains(R1Val))
2294           return R1;
2295         return new SCEVCouldNotCompute();  // Something strange happened
2296       }
2297     }
2298   }
2299
2300   // Fallback, if this is a general polynomial, figure out the progression
2301   // through brute force: evaluate until we find an iteration that fails the
2302   // test.  This is likely to be slow, but getting an accurate trip count is
2303   // incredibly important, we will be able to simplify the exit test a lot, and
2304   // we are almost guaranteed to get a trip count in this case.
2305   ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2306   ConstantInt *One     = ConstantInt::get(getType(), 1);
2307   ConstantInt *EndVal  = TestVal;  // Stop when we wrap around.
2308   do {
2309     ++NumBruteForceEvaluations;
2310     SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2311     if (!isa<SCEVConstant>(Val))  // This shouldn't happen.
2312       return new SCEVCouldNotCompute();
2313
2314     // Check to see if we found the value!
2315     if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2316       return SCEVConstant::get(TestVal);
2317
2318     // Increment to test the next index.
2319     TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2320   } while (TestVal != EndVal);
2321   
2322   return new SCEVCouldNotCompute();
2323 }
2324
2325
2326
2327 //===----------------------------------------------------------------------===//
2328 //                   ScalarEvolution Class Implementation
2329 //===----------------------------------------------------------------------===//
2330
2331 bool ScalarEvolution::runOnFunction(Function &F) {
2332   Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2333   return false;
2334 }
2335
2336 void ScalarEvolution::releaseMemory() {
2337   delete (ScalarEvolutionsImpl*)Impl;
2338   Impl = 0;
2339 }
2340
2341 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2342   AU.setPreservesAll();
2343   AU.addRequiredID(LoopSimplifyID);
2344   AU.addRequiredTransitive<LoopInfo>();
2345 }
2346
2347 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2348   return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2349 }
2350
2351 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2352   return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2353 }
2354
2355 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2356   return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2357 }
2358
2359 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2360   return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2361 }
2362
2363 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2364   return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2365 }
2366
2367
2368 /// shouldSubstituteIndVar - Return true if we should perform induction variable
2369 /// substitution for this variable.  This is a hack because we don't have a
2370 /// strength reduction pass yet.  When we do we will promote all vars, because
2371 /// we can strength reduce them later as desired.
2372 bool ScalarEvolution::shouldSubstituteIndVar(const SCEV *S) const {
2373   // Don't substitute high degree polynomials.
2374   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S))
2375     if (AddRec->getNumOperands() > 3) return false;
2376   return true;
2377 }
2378
2379
2380 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE, 
2381                           const Loop *L) {
2382   // Print all inner loops first
2383   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2384     PrintLoopInfo(OS, SE, *I);
2385   
2386   std::cerr << "Loop " << L->getHeader()->getName() << ": ";
2387   if (L->getExitBlocks().size() != 1)
2388     std::cerr << "<multiple exits> ";
2389
2390   if (SE->hasLoopInvariantIterationCount(L)) {
2391     std::cerr << *SE->getIterationCount(L) << " iterations! ";
2392   } else {
2393     std::cerr << "Unpredictable iteration count. ";
2394   }
2395
2396   std::cerr << "\n";
2397 }
2398
2399 void ScalarEvolution::print(std::ostream &OS) const {
2400   Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2401   LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2402
2403   OS << "Classifying expressions for: " << F.getName() << "\n";
2404   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2405     if ((*I)->getType()->isInteger()) {
2406       OS << **I;
2407       OS << "  --> ";
2408       SCEVHandle SV = getSCEV(*I);
2409       SV->print(OS);
2410       OS << "\t\t";
2411       
2412       if ((*I)->getType()->isIntegral()) {
2413         ConstantRange Bounds = SV->getValueRange();
2414         if (!Bounds.isFullSet())
2415           OS << "Bounds: " << Bounds << " ";
2416       }
2417
2418       if (const Loop *L = LI.getLoopFor((*I)->getParent())) {
2419         OS << "Exits: ";
2420         SCEVHandle ExitValue = getSCEVAtScope(*I, L->getParentLoop());
2421         if (isa<SCEVCouldNotCompute>(ExitValue)) {
2422           OS << "<<Unknown>>";
2423         } else {
2424           OS << *ExitValue;
2425         }
2426       }
2427
2428
2429       OS << "\n";
2430     }
2431
2432   OS << "Determining loop execution counts for: " << F.getName() << "\n";
2433   for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2434     PrintLoopInfo(OS, this, *I);
2435 }
2436
2437 //===----------------------------------------------------------------------===//
2438 //                ScalarEvolutionRewriter Class Implementation
2439 //===----------------------------------------------------------------------===//
2440
2441 Value *ScalarEvolutionRewriter::
2442 GetOrInsertCanonicalInductionVariable(const Loop *L, const Type *Ty) {
2443   assert((Ty->isInteger() || Ty->isFloatingPoint()) &&
2444          "Can only insert integer or floating point induction variables!");
2445
2446   // Check to see if we already inserted one.
2447   SCEVHandle H = SCEVAddRecExpr::get(getIntegerSCEV(0, Ty),
2448                                      getIntegerSCEV(1, Ty), L);
2449   return ExpandCodeFor(H, 0, Ty);
2450 }
2451
2452 /// ExpandCodeFor - Insert code to directly compute the specified SCEV
2453 /// expression into the program.  The inserted code is inserted into the
2454 /// specified block.
2455 Value *ScalarEvolutionRewriter::ExpandCodeFor(SCEVHandle SH,
2456                                               Instruction *InsertPt,
2457                                               const Type *Ty) {
2458   std::map<SCEVHandle, Value*>::iterator ExistVal =InsertedExpressions.find(SH);
2459   Value *V;
2460   if (ExistVal != InsertedExpressions.end()) {
2461     V = ExistVal->second;
2462   } else {
2463     // Ask the recurrence object to expand the code for itself.
2464     V = SH->expandCodeFor(*this, InsertPt);
2465     // Cache the generated result.
2466     InsertedExpressions.insert(std::make_pair(SH, V));
2467   }
2468
2469   if (Ty == 0 || V->getType() == Ty)
2470     return V;
2471   if (Constant *C = dyn_cast<Constant>(V))
2472     return ConstantExpr::getCast(C, Ty);
2473   else if (Instruction *I = dyn_cast<Instruction>(V)) {
2474     // FIXME: check to see if there is already a cast!
2475     BasicBlock::iterator IP = I; ++IP;
2476     while (isa<PHINode>(IP)) ++IP;
2477     return new CastInst(V, Ty, V->getName(), IP);
2478   } else {
2479     // FIXME: check to see if there is already a cast!
2480     return new CastInst(V, Ty, V->getName(), InsertPt);
2481   }
2482 }