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