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