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