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