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