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