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