Be more careful when transforming | to +. Patch from Wojciech Matyjewicz.
[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     /// 'setcc 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 /// GetConstantFactor - Determine the largest constant factor that S has.  For
1414 /// example, turn {4,+,8} -> 4.    (S umod result) should always equal zero.
1415 static APInt GetConstantFactor(SCEVHandle S) {
1416   if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
1417     const APInt& V = C->getValue()->getValue();
1418     if (!V.isMinValue())
1419       return V;
1420     else   // Zero is a multiple of everything.
1421       return APInt(C->getBitWidth(), 1).shl(C->getBitWidth()-1);
1422   }
1423
1424   if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) {
1425     return GetConstantFactor(T->getOperand()).trunc(
1426                                cast<IntegerType>(T->getType())->getBitWidth());
1427   }
1428   if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
1429     return GetConstantFactor(E->getOperand()).zext(
1430                                cast<IntegerType>(E->getType())->getBitWidth());
1431   if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S))
1432     return GetConstantFactor(E->getOperand()).sext(
1433                                cast<IntegerType>(E->getType())->getBitWidth());
1434   
1435   if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1436     // The result is the min of all operands.
1437     APInt Res(GetConstantFactor(A->getOperand(0)));
1438     for (unsigned i = 1, e = A->getNumOperands(); 
1439          i != e && Res.ugt(APInt(Res.getBitWidth(),1)); ++i) {
1440       APInt Tmp(GetConstantFactor(A->getOperand(i)));
1441       Res = APIntOps::umin(Res, Tmp);
1442     }
1443     return Res;
1444   }
1445
1446   if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1447     // The result is the product of all the operands.
1448     APInt Res(GetConstantFactor(M->getOperand(0)));
1449     for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i) {
1450       APInt Tmp(GetConstantFactor(M->getOperand(i)));
1451       Res *= Tmp;
1452     }
1453     return Res;
1454   }
1455     
1456   if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1457     // For now, we just handle linear expressions.
1458     if (A->getNumOperands() == 2) {
1459       // We want the GCD between the start and the stride value.
1460       APInt Start(GetConstantFactor(A->getOperand(0)));
1461       if (Start == 1) 
1462         return Start;
1463       APInt Stride(GetConstantFactor(A->getOperand(1)));
1464       return APIntOps::GreatestCommonDivisor(Start, Stride);
1465     }
1466   }
1467   
1468   // SCEVSDivExpr, SCEVUnknown.
1469   return APInt(S->getBitWidth(), 1);
1470 }
1471
1472 /// createSCEV - We know that there is no SCEV for the specified value.
1473 /// Analyze the expression.
1474 ///
1475 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1476   if (Instruction *I = dyn_cast<Instruction>(V)) {
1477     switch (I->getOpcode()) {
1478     case Instruction::Add:
1479       return SE.getAddExpr(getSCEV(I->getOperand(0)),
1480                            getSCEV(I->getOperand(1)));
1481     case Instruction::Mul:
1482       return SE.getMulExpr(getSCEV(I->getOperand(0)),
1483                            getSCEV(I->getOperand(1)));
1484     case Instruction::SDiv:
1485       return SE.getSDivExpr(getSCEV(I->getOperand(0)),
1486                             getSCEV(I->getOperand(1)));
1487     case Instruction::Sub:
1488       return SE.getMinusSCEV(getSCEV(I->getOperand(0)),
1489                              getSCEV(I->getOperand(1)));
1490     case Instruction::Or:
1491       // If the RHS of the Or is a constant, we may have something like:
1492       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
1493       // optimizations will transparently handle this case.
1494       //
1495       // In order for this transformation to be safe, the LHS must be of the
1496       // form X*(2^n) and the Or constant must be less than 2^n.
1497
1498       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1499         SCEVHandle LHS = getSCEV(I->getOperand(0));
1500         APInt CommonFact(GetConstantFactor(LHS));
1501         assert(!CommonFact.isMinValue() &&
1502                "Common factor should at least be 1!");
1503         const APInt &CIVal = CI->getValue();
1504         if (CommonFact.countTrailingZeros() >=
1505             (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1506           return SE.getAddExpr(LHS,
1507                                getSCEV(I->getOperand(1)));
1508       }
1509       break;
1510     case Instruction::Xor:
1511       // If the RHS of the xor is a signbit, then this is just an add.
1512       // Instcombine turns add of signbit into xor as a strength reduction step.
1513       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1514         if (CI->getValue().isSignBit())
1515           return SE.getAddExpr(getSCEV(I->getOperand(0)),
1516                                getSCEV(I->getOperand(1)));
1517       }
1518       break;
1519
1520     case Instruction::Shl:
1521       // Turn shift left of a constant amount into a multiply.
1522       if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1523         uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1524         Constant *X = ConstantInt::get(
1525           APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1526         return SE.getMulExpr(getSCEV(I->getOperand(0)), getSCEV(X));
1527       }
1528       break;
1529
1530     case Instruction::Trunc:
1531       return SE.getTruncateExpr(getSCEV(I->getOperand(0)), I->getType());
1532
1533     case Instruction::ZExt:
1534       return SE.getZeroExtendExpr(getSCEV(I->getOperand(0)), I->getType());
1535
1536     case Instruction::SExt:
1537       return SE.getSignExtendExpr(getSCEV(I->getOperand(0)), I->getType());
1538
1539     case Instruction::BitCast:
1540       // BitCasts are no-op casts so we just eliminate the cast.
1541       if (I->getType()->isInteger() &&
1542           I->getOperand(0)->getType()->isInteger())
1543         return getSCEV(I->getOperand(0));
1544       break;
1545
1546     case Instruction::PHI:
1547       return createNodeForPHI(cast<PHINode>(I));
1548
1549     default: // We cannot analyze this expression.
1550       break;
1551     }
1552   }
1553
1554   return SE.getUnknown(V);
1555 }
1556
1557
1558
1559 //===----------------------------------------------------------------------===//
1560 //                   Iteration Count Computation Code
1561 //
1562
1563 /// getIterationCount - If the specified loop has a predictable iteration
1564 /// count, return it.  Note that it is not valid to call this method on a
1565 /// loop without a loop-invariant iteration count.
1566 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1567   std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1568   if (I == IterationCounts.end()) {
1569     SCEVHandle ItCount = ComputeIterationCount(L);
1570     I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1571     if (ItCount != UnknownValue) {
1572       assert(ItCount->isLoopInvariant(L) &&
1573              "Computed trip count isn't loop invariant for loop!");
1574       ++NumTripCountsComputed;
1575     } else if (isa<PHINode>(L->getHeader()->begin())) {
1576       // Only count loops that have phi nodes as not being computable.
1577       ++NumTripCountsNotComputed;
1578     }
1579   }
1580   return I->second;
1581 }
1582
1583 /// ComputeIterationCount - Compute the number of times the specified loop
1584 /// will iterate.
1585 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1586   // If the loop has a non-one exit block count, we can't analyze it.
1587   SmallVector<BasicBlock*, 8> ExitBlocks;
1588   L->getExitBlocks(ExitBlocks);
1589   if (ExitBlocks.size() != 1) return UnknownValue;
1590
1591   // Okay, there is one exit block.  Try to find the condition that causes the
1592   // loop to be exited.
1593   BasicBlock *ExitBlock = ExitBlocks[0];
1594
1595   BasicBlock *ExitingBlock = 0;
1596   for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1597        PI != E; ++PI)
1598     if (L->contains(*PI)) {
1599       if (ExitingBlock == 0)
1600         ExitingBlock = *PI;
1601       else
1602         return UnknownValue;   // More than one block exiting!
1603     }
1604   assert(ExitingBlock && "No exits from loop, something is broken!");
1605
1606   // Okay, we've computed the exiting block.  See what condition causes us to
1607   // exit.
1608   //
1609   // FIXME: we should be able to handle switch instructions (with a single exit)
1610   BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1611   if (ExitBr == 0) return UnknownValue;
1612   assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1613   
1614   // At this point, we know we have a conditional branch that determines whether
1615   // the loop is exited.  However, we don't know if the branch is executed each
1616   // time through the loop.  If not, then the execution count of the branch will
1617   // not be equal to the trip count of the loop.
1618   //
1619   // Currently we check for this by checking to see if the Exit branch goes to
1620   // the loop header.  If so, we know it will always execute the same number of
1621   // times as the loop.  We also handle the case where the exit block *is* the
1622   // loop header.  This is common for un-rotated loops.  More extensive analysis
1623   // could be done to handle more cases here.
1624   if (ExitBr->getSuccessor(0) != L->getHeader() &&
1625       ExitBr->getSuccessor(1) != L->getHeader() &&
1626       ExitBr->getParent() != L->getHeader())
1627     return UnknownValue;
1628   
1629   ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1630
1631   // If its not an integer comparison then compute it the hard way. 
1632   // Note that ICmpInst deals with pointer comparisons too so we must check
1633   // the type of the operand.
1634   if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1635     return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1636                                           ExitBr->getSuccessor(0) == ExitBlock);
1637
1638   // If the condition was exit on true, convert the condition to exit on false
1639   ICmpInst::Predicate Cond;
1640   if (ExitBr->getSuccessor(1) == ExitBlock)
1641     Cond = ExitCond->getPredicate();
1642   else
1643     Cond = ExitCond->getInversePredicate();
1644
1645   // Handle common loops like: for (X = "string"; *X; ++X)
1646   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1647     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1648       SCEVHandle ItCnt =
1649         ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1650       if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1651     }
1652
1653   SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1654   SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1655
1656   // Try to evaluate any dependencies out of the loop.
1657   SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1658   if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1659   Tmp = getSCEVAtScope(RHS, L);
1660   if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1661
1662   // At this point, we would like to compute how many iterations of the 
1663   // loop the predicate will return true for these inputs.
1664   if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1665     // If there is a constant, force it into the RHS.
1666     std::swap(LHS, RHS);
1667     Cond = ICmpInst::getSwappedPredicate(Cond);
1668   }
1669
1670   // FIXME: think about handling pointer comparisons!  i.e.:
1671   // while (P != P+100) ++P;
1672
1673   // If we have a comparison of a chrec against a constant, try to use value
1674   // ranges to answer this query.
1675   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1676     if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1677       if (AddRec->getLoop() == L) {
1678         // Form the comparison range using the constant of the correct type so
1679         // that the ConstantRange class knows to do a signed or unsigned
1680         // comparison.
1681         ConstantInt *CompVal = RHSC->getValue();
1682         const Type *RealTy = ExitCond->getOperand(0)->getType();
1683         CompVal = dyn_cast<ConstantInt>(
1684           ConstantExpr::getBitCast(CompVal, RealTy));
1685         if (CompVal) {
1686           // Form the constant range.
1687           ConstantRange CompRange(
1688               ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
1689
1690           SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
1691           if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1692         }
1693       }
1694
1695   switch (Cond) {
1696   case ICmpInst::ICMP_NE: {                     // while (X != Y)
1697     // Convert to: while (X-Y != 0)
1698     SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
1699     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1700     break;
1701   }
1702   case ICmpInst::ICMP_EQ: {
1703     // Convert to: while (X-Y == 0)           // while (X == Y)
1704     SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
1705     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1706     break;
1707   }
1708   case ICmpInst::ICMP_SLT: {
1709     SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
1710     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1711     break;
1712   }
1713   case ICmpInst::ICMP_SGT: {
1714     SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1715                                      SE.getNegativeSCEV(RHS), L, true);
1716     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1717     break;
1718   }
1719   case ICmpInst::ICMP_ULT: {
1720     SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1721     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1722     break;
1723   }
1724   case ICmpInst::ICMP_UGT: {
1725     SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1726                                      SE.getNegativeSCEV(RHS), L, false);
1727     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1728     break;
1729   }
1730   default:
1731 #if 0
1732     cerr << "ComputeIterationCount ";
1733     if (ExitCond->getOperand(0)->getType()->isUnsigned())
1734       cerr << "[unsigned] ";
1735     cerr << *LHS << "   "
1736          << Instruction::getOpcodeName(Instruction::ICmp) 
1737          << "   " << *RHS << "\n";
1738 #endif
1739     break;
1740   }
1741   return ComputeIterationCountExhaustively(L, ExitCond,
1742                                        ExitBr->getSuccessor(0) == ExitBlock);
1743 }
1744
1745 static ConstantInt *
1746 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
1747                                 ScalarEvolution &SE) {
1748   SCEVHandle InVal = SE.getConstant(C);
1749   SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
1750   assert(isa<SCEVConstant>(Val) &&
1751          "Evaluation of SCEV at constant didn't fold correctly?");
1752   return cast<SCEVConstant>(Val)->getValue();
1753 }
1754
1755 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1756 /// and a GEP expression (missing the pointer index) indexing into it, return
1757 /// the addressed element of the initializer or null if the index expression is
1758 /// invalid.
1759 static Constant *
1760 GetAddressedElementFromGlobal(GlobalVariable *GV,
1761                               const std::vector<ConstantInt*> &Indices) {
1762   Constant *Init = GV->getInitializer();
1763   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1764     uint64_t Idx = Indices[i]->getZExtValue();
1765     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1766       assert(Idx < CS->getNumOperands() && "Bad struct index!");
1767       Init = cast<Constant>(CS->getOperand(Idx));
1768     } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1769       if (Idx >= CA->getNumOperands()) return 0;  // Bogus program
1770       Init = cast<Constant>(CA->getOperand(Idx));
1771     } else if (isa<ConstantAggregateZero>(Init)) {
1772       if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1773         assert(Idx < STy->getNumElements() && "Bad struct index!");
1774         Init = Constant::getNullValue(STy->getElementType(Idx));
1775       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1776         if (Idx >= ATy->getNumElements()) return 0;  // Bogus program
1777         Init = Constant::getNullValue(ATy->getElementType());
1778       } else {
1779         assert(0 && "Unknown constant aggregate type!");
1780       }
1781       return 0;
1782     } else {
1783       return 0; // Unknown initializer type
1784     }
1785   }
1786   return Init;
1787 }
1788
1789 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1790 /// 'setcc load X, cst', try to se if we can compute the trip count.
1791 SCEVHandle ScalarEvolutionsImpl::
1792 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1793                                          const Loop *L, 
1794                                          ICmpInst::Predicate predicate) {
1795   if (LI->isVolatile()) return UnknownValue;
1796
1797   // Check to see if the loaded pointer is a getelementptr of a global.
1798   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1799   if (!GEP) return UnknownValue;
1800
1801   // Make sure that it is really a constant global we are gepping, with an
1802   // initializer, and make sure the first IDX is really 0.
1803   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1804   if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1805       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1806       !cast<Constant>(GEP->getOperand(1))->isNullValue())
1807     return UnknownValue;
1808
1809   // Okay, we allow one non-constant index into the GEP instruction.
1810   Value *VarIdx = 0;
1811   std::vector<ConstantInt*> Indexes;
1812   unsigned VarIdxNum = 0;
1813   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1814     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1815       Indexes.push_back(CI);
1816     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1817       if (VarIdx) return UnknownValue;  // Multiple non-constant idx's.
1818       VarIdx = GEP->getOperand(i);
1819       VarIdxNum = i-2;
1820       Indexes.push_back(0);
1821     }
1822
1823   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1824   // Check to see if X is a loop variant variable value now.
1825   SCEVHandle Idx = getSCEV(VarIdx);
1826   SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1827   if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1828
1829   // We can only recognize very limited forms of loop index expressions, in
1830   // particular, only affine AddRec's like {C1,+,C2}.
1831   SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1832   if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1833       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1834       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1835     return UnknownValue;
1836
1837   unsigned MaxSteps = MaxBruteForceIterations;
1838   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1839     ConstantInt *ItCst =
1840       ConstantInt::get(IdxExpr->getType(), IterationNum);
1841     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
1842
1843     // Form the GEP offset.
1844     Indexes[VarIdxNum] = Val;
1845
1846     Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1847     if (Result == 0) break;  // Cannot compute!
1848
1849     // Evaluate the condition for this iteration.
1850     Result = ConstantExpr::getICmp(predicate, Result, RHS);
1851     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
1852     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
1853 #if 0
1854       cerr << "\n***\n*** Computed loop count " << *ItCst
1855            << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1856            << "***\n";
1857 #endif
1858       ++NumArrayLenItCounts;
1859       return SE.getConstant(ItCst);   // Found terminating iteration!
1860     }
1861   }
1862   return UnknownValue;
1863 }
1864
1865
1866 /// CanConstantFold - Return true if we can constant fold an instruction of the
1867 /// specified type, assuming that all operands were constants.
1868 static bool CanConstantFold(const Instruction *I) {
1869   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1870       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1871     return true;
1872
1873   if (const CallInst *CI = dyn_cast<CallInst>(I))
1874     if (const Function *F = CI->getCalledFunction())
1875       return canConstantFoldCallTo((Function*)F);  // FIXME: elim cast
1876   return false;
1877 }
1878
1879 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1880 /// in the loop that V is derived from.  We allow arbitrary operations along the
1881 /// way, but the operands of an operation must either be constants or a value
1882 /// derived from a constant PHI.  If this expression does not fit with these
1883 /// constraints, return null.
1884 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1885   // If this is not an instruction, or if this is an instruction outside of the
1886   // loop, it can't be derived from a loop PHI.
1887   Instruction *I = dyn_cast<Instruction>(V);
1888   if (I == 0 || !L->contains(I->getParent())) return 0;
1889
1890   if (PHINode *PN = dyn_cast<PHINode>(I))
1891     if (L->getHeader() == I->getParent())
1892       return PN;
1893     else
1894       // We don't currently keep track of the control flow needed to evaluate
1895       // PHIs, so we cannot handle PHIs inside of loops.
1896       return 0;
1897
1898   // If we won't be able to constant fold this expression even if the operands
1899   // are constants, return early.
1900   if (!CanConstantFold(I)) return 0;
1901
1902   // Otherwise, we can evaluate this instruction if all of its operands are
1903   // constant or derived from a PHI node themselves.
1904   PHINode *PHI = 0;
1905   for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1906     if (!(isa<Constant>(I->getOperand(Op)) ||
1907           isa<GlobalValue>(I->getOperand(Op)))) {
1908       PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1909       if (P == 0) return 0;  // Not evolving from PHI
1910       if (PHI == 0)
1911         PHI = P;
1912       else if (PHI != P)
1913         return 0;  // Evolving from multiple different PHIs.
1914     }
1915
1916   // This is a expression evolving from a constant PHI!
1917   return PHI;
1918 }
1919
1920 /// EvaluateExpression - Given an expression that passes the
1921 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1922 /// in the loop has the value PHIVal.  If we can't fold this expression for some
1923 /// reason, return null.
1924 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1925   if (isa<PHINode>(V)) return PHIVal;
1926   if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1927     return GV;
1928   if (Constant *C = dyn_cast<Constant>(V)) return C;
1929   Instruction *I = cast<Instruction>(V);
1930
1931   std::vector<Constant*> Operands;
1932   Operands.resize(I->getNumOperands());
1933
1934   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1935     Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1936     if (Operands[i] == 0) return 0;
1937   }
1938
1939   return ConstantFoldInstOperands(I, &Operands[0], Operands.size());
1940 }
1941
1942 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1943 /// in the header of its containing loop, we know the loop executes a
1944 /// constant number of times, and the PHI node is just a recurrence
1945 /// involving constants, fold it.
1946 Constant *ScalarEvolutionsImpl::
1947 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
1948   std::map<PHINode*, Constant*>::iterator I =
1949     ConstantEvolutionLoopExitValue.find(PN);
1950   if (I != ConstantEvolutionLoopExitValue.end())
1951     return I->second;
1952
1953   if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
1954     return ConstantEvolutionLoopExitValue[PN] = 0;  // Not going to evaluate it.
1955
1956   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1957
1958   // Since the loop is canonicalized, the PHI node must have two entries.  One
1959   // entry must be a constant (coming in from outside of the loop), and the
1960   // second must be derived from the same PHI.
1961   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1962   Constant *StartCST =
1963     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1964   if (StartCST == 0)
1965     return RetVal = 0;  // Must be a constant.
1966
1967   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1968   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1969   if (PN2 != PN)
1970     return RetVal = 0;  // Not derived from same PHI.
1971
1972   // Execute the loop symbolically to determine the exit value.
1973   if (Its.getActiveBits() >= 32)
1974     return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
1975
1976   unsigned NumIterations = Its.getZExtValue(); // must be in range
1977   unsigned IterationNum = 0;
1978   for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1979     if (IterationNum == NumIterations)
1980       return RetVal = PHIVal;  // Got exit value!
1981
1982     // Compute the value of the PHI node for the next iteration.
1983     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1984     if (NextPHI == PHIVal)
1985       return RetVal = NextPHI;  // Stopped evolving!
1986     if (NextPHI == 0)
1987       return 0;        // Couldn't evaluate!
1988     PHIVal = NextPHI;
1989   }
1990 }
1991
1992 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1993 /// constant number of times (the condition evolves only from constants),
1994 /// try to evaluate a few iterations of the loop until we get the exit
1995 /// condition gets a value of ExitWhen (true or false).  If we cannot
1996 /// evaluate the trip count of the loop, return UnknownValue.
1997 SCEVHandle ScalarEvolutionsImpl::
1998 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1999   PHINode *PN = getConstantEvolvingPHI(Cond, L);
2000   if (PN == 0) return UnknownValue;
2001
2002   // Since the loop is canonicalized, the PHI node must have two entries.  One
2003   // entry must be a constant (coming in from outside of the loop), and the
2004   // second must be derived from the same PHI.
2005   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2006   Constant *StartCST =
2007     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2008   if (StartCST == 0) return UnknownValue;  // Must be a constant.
2009
2010   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2011   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2012   if (PN2 != PN) return UnknownValue;  // Not derived from same PHI.
2013
2014   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
2015   // the loop symbolically to determine when the condition gets a value of
2016   // "ExitWhen".
2017   unsigned IterationNum = 0;
2018   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
2019   for (Constant *PHIVal = StartCST;
2020        IterationNum != MaxIterations; ++IterationNum) {
2021     ConstantInt *CondVal =
2022       dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2023
2024     // Couldn't symbolically evaluate.
2025     if (!CondVal) return UnknownValue;
2026
2027     if (CondVal->getValue() == uint64_t(ExitWhen)) {
2028       ConstantEvolutionLoopExitValue[PN] = PHIVal;
2029       ++NumBruteForceTripCountsComputed;
2030       return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2031     }
2032
2033     // Compute the value of the PHI node for the next iteration.
2034     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2035     if (NextPHI == 0 || NextPHI == PHIVal)
2036       return UnknownValue;  // Couldn't evaluate or not making progress...
2037     PHIVal = NextPHI;
2038   }
2039
2040   // Too many iterations were needed to evaluate.
2041   return UnknownValue;
2042 }
2043
2044 /// getSCEVAtScope - Compute the value of the specified expression within the
2045 /// indicated loop (which may be null to indicate in no loop).  If the
2046 /// expression cannot be evaluated, return UnknownValue.
2047 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2048   // FIXME: this should be turned into a virtual method on SCEV!
2049
2050   if (isa<SCEVConstant>(V)) return V;
2051
2052   // If this instruction is evolves from a constant-evolving PHI, compute the
2053   // exit value from the loop without using SCEVs.
2054   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2055     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2056       const Loop *LI = this->LI[I->getParent()];
2057       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
2058         if (PHINode *PN = dyn_cast<PHINode>(I))
2059           if (PN->getParent() == LI->getHeader()) {
2060             // Okay, there is no closed form solution for the PHI node.  Check
2061             // to see if the loop that contains it has a known iteration count.
2062             // If so, we may be able to force computation of the exit value.
2063             SCEVHandle IterationCount = getIterationCount(LI);
2064             if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2065               // Okay, we know how many times the containing loop executes.  If
2066               // this is a constant evolving PHI node, get the final value at
2067               // the specified iteration number.
2068               Constant *RV = getConstantEvolutionLoopExitValue(PN,
2069                                                     ICC->getValue()->getValue(),
2070                                                                LI);
2071               if (RV) return SE.getUnknown(RV);
2072             }
2073           }
2074
2075       // Okay, this is an expression that we cannot symbolically evaluate
2076       // into a SCEV.  Check to see if it's possible to symbolically evaluate
2077       // the arguments into constants, and if so, try to constant propagate the
2078       // result.  This is particularly useful for computing loop exit values.
2079       if (CanConstantFold(I)) {
2080         std::vector<Constant*> Operands;
2081         Operands.reserve(I->getNumOperands());
2082         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2083           Value *Op = I->getOperand(i);
2084           if (Constant *C = dyn_cast<Constant>(Op)) {
2085             Operands.push_back(C);
2086           } else {
2087             SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2088             if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2089               Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(), 
2090                                                               Op->getType(), 
2091                                                               false));
2092             else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2093               if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2094                 Operands.push_back(ConstantExpr::getIntegerCast(C, 
2095                                                                 Op->getType(), 
2096                                                                 false));
2097               else
2098                 return V;
2099             } else {
2100               return V;
2101             }
2102           }
2103         }
2104         Constant *C =ConstantFoldInstOperands(I, &Operands[0], Operands.size());
2105         return SE.getUnknown(C);
2106       }
2107     }
2108
2109     // This is some other type of SCEVUnknown, just return it.
2110     return V;
2111   }
2112
2113   if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2114     // Avoid performing the look-up in the common case where the specified
2115     // expression has no loop-variant portions.
2116     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2117       SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2118       if (OpAtScope != Comm->getOperand(i)) {
2119         if (OpAtScope == UnknownValue) return UnknownValue;
2120         // Okay, at least one of these operands is loop variant but might be
2121         // foldable.  Build a new instance of the folded commutative expression.
2122         std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2123         NewOps.push_back(OpAtScope);
2124
2125         for (++i; i != e; ++i) {
2126           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2127           if (OpAtScope == UnknownValue) return UnknownValue;
2128           NewOps.push_back(OpAtScope);
2129         }
2130         if (isa<SCEVAddExpr>(Comm))
2131           return SE.getAddExpr(NewOps);
2132         assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
2133         return SE.getMulExpr(NewOps);
2134       }
2135     }
2136     // If we got here, all operands are loop invariant.
2137     return Comm;
2138   }
2139
2140   if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2141     SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2142     if (LHS == UnknownValue) return LHS;
2143     SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2144     if (RHS == UnknownValue) return RHS;
2145     if (LHS == Div->getLHS() && RHS == Div->getRHS())
2146       return Div;   // must be loop invariant
2147     return SE.getSDivExpr(LHS, RHS);
2148   }
2149
2150   // If this is a loop recurrence for a loop that does not contain L, then we
2151   // are dealing with the final value computed by the loop.
2152   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2153     if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2154       // To evaluate this recurrence, we need to know how many times the AddRec
2155       // loop iterates.  Compute this now.
2156       SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2157       if (IterationCount == UnknownValue) return UnknownValue;
2158       IterationCount = getTruncateOrZeroExtend(IterationCount,
2159                                                AddRec->getType(), SE);
2160
2161       // If the value is affine, simplify the expression evaluation to just
2162       // Start + Step*IterationCount.
2163       if (AddRec->isAffine())
2164         return SE.getAddExpr(AddRec->getStart(),
2165                              SE.getMulExpr(IterationCount,
2166                                            AddRec->getOperand(1)));
2167
2168       // Otherwise, evaluate it the hard way.
2169       return AddRec->evaluateAtIteration(IterationCount, SE);
2170     }
2171     return UnknownValue;
2172   }
2173
2174   //assert(0 && "Unknown SCEV type!");
2175   return UnknownValue;
2176 }
2177
2178
2179 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2180 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
2181 /// might be the same) or two SCEVCouldNotCompute objects.
2182 ///
2183 static std::pair<SCEVHandle,SCEVHandle>
2184 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2185   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2186   SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2187   SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2188   SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2189
2190   // We currently can only solve this if the coefficients are constants.
2191   if (!LC || !MC || !NC) {
2192     SCEV *CNC = new SCEVCouldNotCompute();
2193     return std::make_pair(CNC, CNC);
2194   }
2195
2196   uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2197   const APInt &L = LC->getValue()->getValue();
2198   const APInt &M = MC->getValue()->getValue();
2199   const APInt &N = NC->getValue()->getValue();
2200   APInt Two(BitWidth, 2);
2201   APInt Four(BitWidth, 4);
2202
2203   { 
2204     using namespace APIntOps;
2205     const APInt& C = L;
2206     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2207     // The B coefficient is M-N/2
2208     APInt B(M);
2209     B -= sdiv(N,Two);
2210
2211     // The A coefficient is N/2
2212     APInt A(N.sdiv(Two));
2213
2214     // Compute the B^2-4ac term.
2215     APInt SqrtTerm(B);
2216     SqrtTerm *= B;
2217     SqrtTerm -= Four * (A * C);
2218
2219     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2220     // integer value or else APInt::sqrt() will assert.
2221     APInt SqrtVal(SqrtTerm.sqrt());
2222
2223     // Compute the two solutions for the quadratic formula. 
2224     // The divisions must be performed as signed divisions.
2225     APInt NegB(-B);
2226     APInt TwoA( A << 1 );
2227     ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2228     ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2229
2230     return std::make_pair(SE.getConstant(Solution1), 
2231                           SE.getConstant(Solution2));
2232     } // end APIntOps namespace
2233 }
2234
2235 /// HowFarToZero - Return the number of times a backedge comparing the specified
2236 /// value to zero will execute.  If not computable, return UnknownValue
2237 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2238   // If the value is a constant
2239   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2240     // If the value is already zero, the branch will execute zero times.
2241     if (C->getValue()->isZero()) return C;
2242     return UnknownValue;  // Otherwise it will loop infinitely.
2243   }
2244
2245   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2246   if (!AddRec || AddRec->getLoop() != L)
2247     return UnknownValue;
2248
2249   if (AddRec->isAffine()) {
2250     // If this is an affine expression the execution count of this branch is
2251     // equal to:
2252     //
2253     //     (0 - Start/Step)    iff   Start % Step == 0
2254     //
2255     // Get the initial value for the loop.
2256     SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2257     if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2258     SCEVHandle Step = AddRec->getOperand(1);
2259
2260     Step = getSCEVAtScope(Step, L->getParentLoop());
2261
2262     // Figure out if Start % Step == 0.
2263     // FIXME: We should add DivExpr and RemExpr operations to our AST.
2264     if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2265       if (StepC->getValue()->equalsInt(1))      // N % 1 == 0
2266         return SE.getNegativeSCEV(Start);  // 0 - Start/1 == -Start
2267       if (StepC->getValue()->isAllOnesValue())  // N % -1 == 0
2268         return Start;                   // 0 - Start/-1 == Start
2269
2270       // Check to see if Start is divisible by SC with no remainder.
2271       if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2272         ConstantInt *StartCC = StartC->getValue();
2273         Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2274         Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
2275         if (Rem->isNullValue()) {
2276           Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
2277           return SE.getUnknown(Result);
2278         }
2279       }
2280     }
2281   } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2282     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2283     // the quadratic equation to solve it.
2284     std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2285     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2286     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2287     if (R1) {
2288 #if 0
2289       cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2290            << "  sol#2: " << *R2 << "\n";
2291 #endif
2292       // Pick the smallest positive root value.
2293       if (ConstantInt *CB =
2294           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 
2295                                    R1->getValue(), R2->getValue()))) {
2296         if (CB->getZExtValue() == false)
2297           std::swap(R1, R2);   // R1 is the minimum root now.
2298
2299         // We can only use this value if the chrec ends up with an exact zero
2300         // value at this index.  When solving for "X*X != 5", for example, we
2301         // should not accept a root of 2.
2302         SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2303         if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2304           if (EvalVal->getValue()->isZero())
2305             return R1;  // We found a quadratic root!
2306       }
2307     }
2308   }
2309
2310   return UnknownValue;
2311 }
2312
2313 /// HowFarToNonZero - Return the number of times a backedge checking the
2314 /// specified value for nonzero will execute.  If not computable, return
2315 /// UnknownValue
2316 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2317   // Loops that look like: while (X == 0) are very strange indeed.  We don't
2318   // handle them yet except for the trivial case.  This could be expanded in the
2319   // future as needed.
2320
2321   // If the value is a constant, check to see if it is known to be non-zero
2322   // already.  If so, the backedge will execute zero times.
2323   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2324     Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2325     Constant *NonZero = 
2326       ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
2327     if (NonZero == ConstantInt::getTrue())
2328       return getSCEV(Zero);
2329     return UnknownValue;  // Otherwise it will loop infinitely.
2330   }
2331
2332   // We could implement others, but I really doubt anyone writes loops like
2333   // this, and if they did, they would already be constant folded.
2334   return UnknownValue;
2335 }
2336
2337 /// HowManyLessThans - Return the number of times a backedge containing the
2338 /// specified less-than comparison will execute.  If not computable, return
2339 /// UnknownValue.
2340 SCEVHandle ScalarEvolutionsImpl::
2341 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
2342   // Only handle:  "ADDREC < LoopInvariant".
2343   if (!RHS->isLoopInvariant(L)) return UnknownValue;
2344
2345   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2346   if (!AddRec || AddRec->getLoop() != L)
2347     return UnknownValue;
2348
2349   if (AddRec->isAffine()) {
2350     // FORNOW: We only support unit strides.
2351     SCEVHandle Zero = SE.getIntegerSCEV(0, RHS->getType());
2352     SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2353     if (AddRec->getOperand(1) != One)
2354       return UnknownValue;
2355
2356     // The number of iterations for "{n,+,1} < m", is m-n.  However, we don't
2357     // know that m is >= n on input to the loop.  If it is, the condition return
2358     // true zero times.  What we really should return, for full generality, is
2359     // SMAX(0, m-n).  Since we cannot check this, we will instead check for a
2360     // canonical loop form: most do-loops will have a check that dominates the
2361     // loop, that only enters the loop if (n-1)<m.  If we can find this check,
2362     // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2363
2364     // Search for the check.
2365     BasicBlock *Preheader = L->getLoopPreheader();
2366     BasicBlock *PreheaderDest = L->getHeader();
2367     if (Preheader == 0) return UnknownValue;
2368
2369     BranchInst *LoopEntryPredicate =
2370       dyn_cast<BranchInst>(Preheader->getTerminator());
2371     if (!LoopEntryPredicate) return UnknownValue;
2372
2373     // This might be a critical edge broken out.  If the loop preheader ends in
2374     // an unconditional branch to the loop, check to see if the preheader has a
2375     // single predecessor, and if so, look for its terminator.
2376     while (LoopEntryPredicate->isUnconditional()) {
2377       PreheaderDest = Preheader;
2378       Preheader = Preheader->getSinglePredecessor();
2379       if (!Preheader) return UnknownValue;  // Multiple preds.
2380       
2381       LoopEntryPredicate =
2382         dyn_cast<BranchInst>(Preheader->getTerminator());
2383       if (!LoopEntryPredicate) return UnknownValue;
2384     }
2385
2386     // Now that we found a conditional branch that dominates the loop, check to
2387     // see if it is the comparison we are looking for.
2388     if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){
2389       Value *PreCondLHS = ICI->getOperand(0);
2390       Value *PreCondRHS = ICI->getOperand(1);
2391       ICmpInst::Predicate Cond;
2392       if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2393         Cond = ICI->getPredicate();
2394       else
2395         Cond = ICI->getInversePredicate();
2396     
2397       switch (Cond) {
2398       case ICmpInst::ICMP_UGT:
2399         if (isSigned) return UnknownValue;
2400         std::swap(PreCondLHS, PreCondRHS);
2401         Cond = ICmpInst::ICMP_ULT;
2402         break;
2403       case ICmpInst::ICMP_SGT:
2404         if (!isSigned) return UnknownValue;
2405         std::swap(PreCondLHS, PreCondRHS);
2406         Cond = ICmpInst::ICMP_SLT;
2407         break;
2408       case ICmpInst::ICMP_ULT:
2409         if (isSigned) return UnknownValue;
2410         break;
2411       case ICmpInst::ICMP_SLT:
2412         if (!isSigned) return UnknownValue;
2413         break;
2414       default:
2415         return UnknownValue;
2416       }
2417
2418       if (PreCondLHS->getType()->isInteger()) {
2419         if (RHS != getSCEV(PreCondRHS))
2420           return UnknownValue;  // Not a comparison against 'm'.
2421
2422         if (SE.getMinusSCEV(AddRec->getOperand(0), One)
2423                     != getSCEV(PreCondLHS))
2424           return UnknownValue;  // Not a comparison against 'n-1'.
2425       }
2426       else return UnknownValue;
2427
2428       // cerr << "Computed Loop Trip Count as: " 
2429       //      << //  *SE.getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2430       return SE.getMinusSCEV(RHS, AddRec->getOperand(0));
2431     }
2432     else 
2433       return UnknownValue;
2434   }
2435
2436   return UnknownValue;
2437 }
2438
2439 /// getNumIterationsInRange - Return the number of iterations of this loop that
2440 /// produce values in the specified constant range.  Another way of looking at
2441 /// this is that it returns the first iteration number where the value is not in
2442 /// the condition, thus computing the exit count. If the iteration count can't
2443 /// be computed, an instance of SCEVCouldNotCompute is returned.
2444 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2445                                                    ScalarEvolution &SE) const {
2446   if (Range.isFullSet())  // Infinite loop.
2447     return new SCEVCouldNotCompute();
2448
2449   // If the start is a non-zero constant, shift the range to simplify things.
2450   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2451     if (!SC->getValue()->isZero()) {
2452       std::vector<SCEVHandle> Operands(op_begin(), op_end());
2453       Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2454       SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
2455       if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2456         return ShiftedAddRec->getNumIterationsInRange(
2457                            Range.subtract(SC->getValue()->getValue()), SE);
2458       // This is strange and shouldn't happen.
2459       return new SCEVCouldNotCompute();
2460     }
2461
2462   // The only time we can solve this is when we have all constant indices.
2463   // Otherwise, we cannot determine the overflow conditions.
2464   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2465     if (!isa<SCEVConstant>(getOperand(i)))
2466       return new SCEVCouldNotCompute();
2467
2468
2469   // Okay at this point we know that all elements of the chrec are constants and
2470   // that the start element is zero.
2471
2472   // First check to see if the range contains zero.  If not, the first
2473   // iteration exits.
2474   if (!Range.contains(APInt(getBitWidth(),0))) 
2475     return SE.getConstant(ConstantInt::get(getType(),0));
2476
2477   if (isAffine()) {
2478     // If this is an affine expression then we have this situation:
2479     //   Solve {0,+,A} in Range  ===  Ax in Range
2480
2481     // We know that zero is in the range.  If A is positive then we know that
2482     // the upper value of the range must be the first possible exit value.
2483     // If A is negative then the lower of the range is the last possible loop
2484     // value.  Also note that we already checked for a full range.
2485     APInt One(getBitWidth(),1);
2486     APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2487     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2488
2489     // The exit value should be (End+A)/A.
2490     APInt ExitVal = (End + A).udiv(A);
2491     ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2492
2493     // Evaluate at the exit value.  If we really did fall out of the valid
2494     // range, then we computed our trip count, otherwise wrap around or other
2495     // things must have happened.
2496     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
2497     if (Range.contains(Val->getValue()))
2498       return new SCEVCouldNotCompute();  // Something strange happened
2499
2500     // Ensure that the previous value is in the range.  This is a sanity check.
2501     assert(Range.contains(
2502            EvaluateConstantChrecAtConstant(this, 
2503            ConstantInt::get(ExitVal - One), SE)->getValue()) &&
2504            "Linear scev computation is off in a bad way!");
2505     return SE.getConstant(ExitValue);
2506   } else if (isQuadratic()) {
2507     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2508     // quadratic equation to solve it.  To do this, we must frame our problem in
2509     // terms of figuring out when zero is crossed, instead of when
2510     // Range.getUpper() is crossed.
2511     std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2512     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2513     SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
2514
2515     // Next, solve the constructed addrec
2516     std::pair<SCEVHandle,SCEVHandle> Roots =
2517       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
2518     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2519     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2520     if (R1) {
2521       // Pick the smallest positive root value.
2522       if (ConstantInt *CB =
2523           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 
2524                                    R1->getValue(), R2->getValue()))) {
2525         if (CB->getZExtValue() == false)
2526           std::swap(R1, R2);   // R1 is the minimum root now.
2527
2528         // Make sure the root is not off by one.  The returned iteration should
2529         // not be in the range, but the previous one should be.  When solving
2530         // for "X*X < 5", for example, we should not return a root of 2.
2531         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2532                                                              R1->getValue(),
2533                                                              SE);
2534         if (Range.contains(R1Val->getValue())) {
2535           // The next iteration must be out of the range...
2536           ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2537
2538           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2539           if (!Range.contains(R1Val->getValue()))
2540             return SE.getConstant(NextVal);
2541           return new SCEVCouldNotCompute();  // Something strange happened
2542         }
2543
2544         // If R1 was not in the range, then it is a good return value.  Make
2545         // sure that R1-1 WAS in the range though, just in case.
2546         ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
2547         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
2548         if (Range.contains(R1Val->getValue()))
2549           return R1;
2550         return new SCEVCouldNotCompute();  // Something strange happened
2551       }
2552     }
2553   }
2554
2555   // Fallback, if this is a general polynomial, figure out the progression
2556   // through brute force: evaluate until we find an iteration that fails the
2557   // test.  This is likely to be slow, but getting an accurate trip count is
2558   // incredibly important, we will be able to simplify the exit test a lot, and
2559   // we are almost guaranteed to get a trip count in this case.
2560   ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2561   ConstantInt *EndVal  = TestVal;  // Stop when we wrap around.
2562   do {
2563     ++NumBruteForceEvaluations;
2564     SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
2565     if (!isa<SCEVConstant>(Val))  // This shouldn't happen.
2566       return new SCEVCouldNotCompute();
2567
2568     // Check to see if we found the value!
2569     if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
2570       return SE.getConstant(TestVal);
2571
2572     // Increment to test the next index.
2573     TestVal = ConstantInt::get(TestVal->getValue()+1);
2574   } while (TestVal != EndVal);
2575
2576   return new SCEVCouldNotCompute();
2577 }
2578
2579
2580
2581 //===----------------------------------------------------------------------===//
2582 //                   ScalarEvolution Class Implementation
2583 //===----------------------------------------------------------------------===//
2584
2585 bool ScalarEvolution::runOnFunction(Function &F) {
2586   Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
2587   return false;
2588 }
2589
2590 void ScalarEvolution::releaseMemory() {
2591   delete (ScalarEvolutionsImpl*)Impl;
2592   Impl = 0;
2593 }
2594
2595 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2596   AU.setPreservesAll();
2597   AU.addRequiredTransitive<LoopInfo>();
2598 }
2599
2600 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2601   return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2602 }
2603
2604 /// hasSCEV - Return true if the SCEV for this value has already been
2605 /// computed.
2606 bool ScalarEvolution::hasSCEV(Value *V) const {
2607   return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2608 }
2609
2610
2611 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2612 /// the specified value.
2613 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2614   ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2615 }
2616
2617
2618 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2619   return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2620 }
2621
2622 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2623   return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2624 }
2625
2626 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2627   return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2628 }
2629
2630 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2631   return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
2632 }
2633
2634 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2635                           const Loop *L) {
2636   // Print all inner loops first
2637   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2638     PrintLoopInfo(OS, SE, *I);
2639
2640   cerr << "Loop " << L->getHeader()->getName() << ": ";
2641
2642   SmallVector<BasicBlock*, 8> ExitBlocks;
2643   L->getExitBlocks(ExitBlocks);
2644   if (ExitBlocks.size() != 1)
2645     cerr << "<multiple exits> ";
2646
2647   if (SE->hasLoopInvariantIterationCount(L)) {
2648     cerr << *SE->getIterationCount(L) << " iterations! ";
2649   } else {
2650     cerr << "Unpredictable iteration count. ";
2651   }
2652
2653   cerr << "\n";
2654 }
2655
2656 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2657   Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2658   LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2659
2660   OS << "Classifying expressions for: " << F.getName() << "\n";
2661   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2662     if (I->getType()->isInteger()) {
2663       OS << *I;
2664       OS << "  --> ";
2665       SCEVHandle SV = getSCEV(&*I);
2666       SV->print(OS);
2667       OS << "\t\t";
2668
2669       if ((*I).getType()->isInteger()) {
2670         ConstantRange Bounds = SV->getValueRange();
2671         if (!Bounds.isFullSet())
2672           OS << "Bounds: " << Bounds << " ";
2673       }
2674
2675       if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2676         OS << "Exits: ";
2677         SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2678         if (isa<SCEVCouldNotCompute>(ExitValue)) {
2679           OS << "<<Unknown>>";
2680         } else {
2681           OS << *ExitValue;
2682         }
2683       }
2684
2685
2686       OS << "\n";
2687     }
2688
2689   OS << "Determining loop execution counts for: " << F.getName() << "\n";
2690   for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2691     PrintLoopInfo(OS, this, *I);
2692 }