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