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