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. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #define DEBUG_TYPE "scalar-evolution"
62 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/GlobalVariable.h"
66 #include "llvm/GlobalAlias.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/LLVMContext.h"
69 #include "llvm/Operator.h"
70 #include "llvm/Analysis/ConstantFolding.h"
71 #include "llvm/Analysis/Dominators.h"
72 #include "llvm/Analysis/LoopInfo.h"
73 #include "llvm/Analysis/ValueTracking.h"
74 #include "llvm/Assembly/Writer.h"
75 #include "llvm/Target/TargetData.h"
76 #include "llvm/Support/CommandLine.h"
77 #include "llvm/Support/ConstantRange.h"
78 #include "llvm/Support/Debug.h"
79 #include "llvm/Support/ErrorHandling.h"
80 #include "llvm/Support/GetElementPtrTypeIterator.h"
81 #include "llvm/Support/InstIterator.h"
82 #include "llvm/Support/MathExtras.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/ADT/Statistic.h"
85 #include "llvm/ADT/STLExtras.h"
86 #include "llvm/ADT/SmallPtrSet.h"
87 #include <algorithm>
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 "
103                                  "derived loop"),
104                         cl::init(100));
105 
106 static RegisterPass<ScalarEvolution>
107 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
108 char ScalarEvolution::ID = 0;
109 
110 //===----------------------------------------------------------------------===//
111 //                           SCEV class definitions
112 //===----------------------------------------------------------------------===//
113 
114 //===----------------------------------------------------------------------===//
115 // Implementation of the SCEV class.
116 //
117 
118 SCEV::~SCEV() {}
119 
120 void SCEV::dump() const {
121   print(dbgs());
122   dbgs() << '\n';
123 }
124 
125 bool SCEV::isZero() const {
126   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127     return SC->getValue()->isZero();
128   return false;
129 }
130 
131 bool SCEV::isOne() const {
132   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133     return SC->getValue()->isOne();
134   return false;
135 }
136 
137 bool SCEV::isAllOnesValue() const {
138   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139     return SC->getValue()->isAllOnesValue();
140   return false;
141 }
142 
143 SCEVCouldNotCompute::SCEVCouldNotCompute() :
144   SCEV(FoldingSetNodeIDRef(), 0, scCouldNotCompute) {}
145 
146 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
147   llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
148   return false;
149 }
150 
151 const Type *SCEVCouldNotCompute::getType() const {
152   llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
153   return 0;
154 }
155 
156 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
157   llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
158   return false;
159 }
160 
161 bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162   llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
163   return false;
164 }
165 
166 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
167   OS << "***COULDNOTCOMPUTE***";
168 }
169 
170 bool SCEVCouldNotCompute::classof(const SCEV *S) {
171   return S->getSCEVType() == scCouldNotCompute;
172 }
173 
174 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
175   FoldingSetNodeID ID;
176   ID.AddInteger(scConstant);
177   ID.AddPointer(V);
178   void *IP = 0;
179   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
180   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator),
181                                              CurAllocationSequenceNumber++,
182                                              V);
183   UniqueSCEVs.InsertNode(S, IP);
184   return S;
185 }
186 
187 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
188   return getConstant(ConstantInt::get(getContext(), Val));
189 }
190 
191 const SCEV *
192 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
193   const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
194   return getConstant(ConstantInt::get(ITy, V, isSigned));
195 }
196 
197 const Type *SCEVConstant::getType() const { return V->getType(); }
198 
199 void SCEVConstant::print(raw_ostream &OS) const {
200   WriteAsOperand(OS, V, false);
201 }
202 
203 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, unsigned Num,
204                            unsigned SCEVTy, const SCEV *op, const Type *ty)
205   : SCEV(ID, Num, SCEVTy), Op(op), Ty(ty) {}
206 
207 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
208   return Op->dominates(BB, DT);
209 }
210 
211 bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
212   return Op->properlyDominates(BB, DT);
213 }
214 
215 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, unsigned Num,
216                                    const SCEV *op, const Type *ty)
217   : SCEVCastExpr(ID, Num, scTruncate, op, ty) {
218   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
219          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
220          "Cannot truncate non-integer value!");
221 }
222 
223 void SCEVTruncateExpr::print(raw_ostream &OS) const {
224   OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
225 }
226 
227 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, unsigned Num,
228                                        const SCEV *op, const Type *ty)
229   : SCEVCastExpr(ID, Num, scZeroExtend, op, ty) {
230   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
231          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
232          "Cannot zero extend non-integer value!");
233 }
234 
235 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
236   OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
237 }
238 
239 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, unsigned Num,
240                                        const SCEV *op, const Type *ty)
241   : SCEVCastExpr(ID, Num, scSignExtend, op, ty) {
242   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
243          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
244          "Cannot sign extend non-integer value!");
245 }
246 
247 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
248   OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
249 }
250 
251 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
252   const char *OpStr = getOperationStr();
253   OS << "(";
254   for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
255     OS << **I;
256     if (next(I) != E)
257       OS << OpStr;
258   }
259   OS << ")";
260 }
261 
262 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
263   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
264     if (!getOperand(i)->dominates(BB, DT))
265       return false;
266   }
267   return true;
268 }
269 
270 bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
271   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
272     if (!getOperand(i)->properlyDominates(BB, DT))
273       return false;
274   }
275   return true;
276 }
277 
278 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
279   return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
280 }
281 
282 bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
283   return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
284 }
285 
286 void SCEVUDivExpr::print(raw_ostream &OS) const {
287   OS << "(" << *LHS << " /u " << *RHS << ")";
288 }
289 
290 const Type *SCEVUDivExpr::getType() const {
291   // In most cases the types of LHS and RHS will be the same, but in some
292   // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
293   // depend on the type for correctness, but handling types carefully can
294   // avoid extra casts in the SCEVExpander. The LHS is more likely to be
295   // a pointer type than the RHS, so use the RHS' type here.
296   return RHS->getType();
297 }
298 
299 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
300   // Add recurrences are never invariant in the function-body (null loop).
301   if (!QueryLoop)
302     return false;
303 
304   // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
305   if (QueryLoop->contains(L))
306     return false;
307 
308   // This recurrence is variant w.r.t. QueryLoop if any of its operands
309   // are variant.
310   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
311     if (!getOperand(i)->isLoopInvariant(QueryLoop))
312       return false;
313 
314   // Otherwise it's loop-invariant.
315   return true;
316 }
317 
318 bool
319 SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
320   return DT->dominates(L->getHeader(), BB) &&
321          SCEVNAryExpr::dominates(BB, DT);
322 }
323 
324 bool
325 SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
326   // This uses a "dominates" query instead of "properly dominates" query because
327   // the instruction which produces the addrec's value is a PHI, and a PHI
328   // effectively properly dominates its entire containing block.
329   return DT->dominates(L->getHeader(), BB) &&
330          SCEVNAryExpr::properlyDominates(BB, DT);
331 }
332 
333 void SCEVAddRecExpr::print(raw_ostream &OS) const {
334   OS << "{" << *Operands[0];
335   for (unsigned i = 1, e = NumOperands; i != e; ++i)
336     OS << ",+," << *Operands[i];
337   OS << "}<";
338   WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
339   OS << ">";
340 }
341 
342 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
343   // All non-instruction values are loop invariant.  All instructions are loop
344   // invariant if they are not contained in the specified loop.
345   // Instructions are never considered invariant in the function body
346   // (null loop) because they are defined within the "loop".
347   if (Instruction *I = dyn_cast<Instruction>(V))
348     return L && !L->contains(I);
349   return true;
350 }
351 
352 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
353   if (Instruction *I = dyn_cast<Instruction>(getValue()))
354     return DT->dominates(I->getParent(), BB);
355   return true;
356 }
357 
358 bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
359   if (Instruction *I = dyn_cast<Instruction>(getValue()))
360     return DT->properlyDominates(I->getParent(), BB);
361   return true;
362 }
363 
364 const Type *SCEVUnknown::getType() const {
365   return V->getType();
366 }
367 
368 bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
369   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
370     if (VCE->getOpcode() == Instruction::PtrToInt)
371       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
372         if (CE->getOpcode() == Instruction::GetElementPtr &&
373             CE->getOperand(0)->isNullValue() &&
374             CE->getNumOperands() == 2)
375           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
376             if (CI->isOne()) {
377               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
378                                  ->getElementType();
379               return true;
380             }
381 
382   return false;
383 }
384 
385 bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
386   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
387     if (VCE->getOpcode() == Instruction::PtrToInt)
388       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
389         if (CE->getOpcode() == Instruction::GetElementPtr &&
390             CE->getOperand(0)->isNullValue()) {
391           const Type *Ty =
392             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
393           if (const StructType *STy = dyn_cast<StructType>(Ty))
394             if (!STy->isPacked() &&
395                 CE->getNumOperands() == 3 &&
396                 CE->getOperand(1)->isNullValue()) {
397               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
398                 if (CI->isOne() &&
399                     STy->getNumElements() == 2 &&
400                     STy->getElementType(0)->isIntegerTy(1)) {
401                   AllocTy = STy->getElementType(1);
402                   return true;
403                 }
404             }
405         }
406 
407   return false;
408 }
409 
410 bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
411   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
412     if (VCE->getOpcode() == Instruction::PtrToInt)
413       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
414         if (CE->getOpcode() == Instruction::GetElementPtr &&
415             CE->getNumOperands() == 3 &&
416             CE->getOperand(0)->isNullValue() &&
417             CE->getOperand(1)->isNullValue()) {
418           const Type *Ty =
419             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
420           // Ignore vector types here so that ScalarEvolutionExpander doesn't
421           // emit getelementptrs that index into vectors.
422           if (Ty->isStructTy() || Ty->isArrayTy()) {
423             CTy = Ty;
424             FieldNo = CE->getOperand(2);
425             return true;
426           }
427         }
428 
429   return false;
430 }
431 
432 void SCEVUnknown::print(raw_ostream &OS) const {
433   const Type *AllocTy;
434   if (isSizeOf(AllocTy)) {
435     OS << "sizeof(" << *AllocTy << ")";
436     return;
437   }
438   if (isAlignOf(AllocTy)) {
439     OS << "alignof(" << *AllocTy << ")";
440     return;
441   }
442 
443   const Type *CTy;
444   Constant *FieldNo;
445   if (isOffsetOf(CTy, FieldNo)) {
446     OS << "offsetof(" << *CTy << ", ";
447     WriteAsOperand(OS, FieldNo, false);
448     OS << ")";
449     return;
450   }
451 
452   // Otherwise just print it normally.
453   WriteAsOperand(OS, V, false);
454 }
455 
456 //===----------------------------------------------------------------------===//
457 //                               SCEV Utilities
458 //===----------------------------------------------------------------------===//
459 
460 static bool CompareTypes(const Type *A, const Type *B) {
461   if (A->getTypeID() != B->getTypeID())
462     return A->getTypeID() < B->getTypeID();
463   if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
464     const IntegerType *BI = cast<IntegerType>(B);
465     return AI->getBitWidth() < BI->getBitWidth();
466   }
467   if (const PointerType *AI = dyn_cast<PointerType>(A)) {
468     const PointerType *BI = cast<PointerType>(B);
469     return CompareTypes(AI->getElementType(), BI->getElementType());
470   }
471   if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
472     const ArrayType *BI = cast<ArrayType>(B);
473     if (AI->getNumElements() != BI->getNumElements())
474       return AI->getNumElements() < BI->getNumElements();
475     return CompareTypes(AI->getElementType(), BI->getElementType());
476   }
477   if (const VectorType *AI = dyn_cast<VectorType>(A)) {
478     const VectorType *BI = cast<VectorType>(B);
479     if (AI->getNumElements() != BI->getNumElements())
480       return AI->getNumElements() < BI->getNumElements();
481     return CompareTypes(AI->getElementType(), BI->getElementType());
482   }
483   if (const StructType *AI = dyn_cast<StructType>(A)) {
484     const StructType *BI = cast<StructType>(B);
485     if (AI->getNumElements() != BI->getNumElements())
486       return AI->getNumElements() < BI->getNumElements();
487     for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
488       if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
489           CompareTypes(BI->getElementType(i), AI->getElementType(i)))
490         return CompareTypes(AI->getElementType(i), BI->getElementType(i));
491   }
492   return false;
493 }
494 
495 namespace {
496   /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
497   /// than the complexity of the RHS.  This comparator is used to canonicalize
498   /// expressions.
499   class SCEVComplexityCompare {
500     LoopInfo *LI;
501   public:
502     explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
503 
504     bool operator()(const SCEV *LHS, const SCEV *RHS) const {
505       // Fast-path: SCEVs are uniqued so we can do a quick equality check.
506       if (LHS == RHS)
507         return false;
508 
509       // Primarily, sort the SCEVs by their getSCEVType().
510       unsigned LST = LHS->getSCEVType();
511       unsigned RST = RHS->getSCEVType();
512       if (LST != RST)
513         return LST < RST;
514 
515       // Then, pick an arbitrary deterministic sort.
516       return LHS->getAllocationSequenceNumber() <
517              RHS->getAllocationSequenceNumber();
518     }
519   };
520 }
521 
522 /// GroupByComplexity - Given a list of SCEV objects, order them by their
523 /// complexity, and group objects of the same complexity together by value.
524 /// When this routine is finished, we know that any duplicates in the vector are
525 /// consecutive and that complexity is monotonically increasing.
526 ///
527 /// Note that we go take special precautions to ensure that we get deterministic
528 /// results from this routine.  In other words, we don't want the results of
529 /// this to depend on where the addresses of various SCEV objects happened to
530 /// land in memory.
531 ///
532 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
533                               LoopInfo *LI) {
534   if (Ops.size() < 2) return;  // Noop
535 
536   SCEVComplexityCompare Comp(LI);
537 
538   if (Ops.size() == 2) {
539     // This is the common case, which also happens to be trivially simple.
540     // Special case it.
541     if (Comp(Ops[1], Ops[0]))
542       std::swap(Ops[0], Ops[1]);
543     return;
544   }
545 
546   std::stable_sort(Ops.begin(), Ops.end(), Comp);
547 }
548 
549 
550 
551 //===----------------------------------------------------------------------===//
552 //                      Simple SCEV method implementations
553 //===----------------------------------------------------------------------===//
554 
555 /// BinomialCoefficient - Compute BC(It, K).  The result has width W.
556 /// Assume, K > 0.
557 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
558                                        ScalarEvolution &SE,
559                                        const Type* ResultTy) {
560   // Handle the simplest case efficiently.
561   if (K == 1)
562     return SE.getTruncateOrZeroExtend(It, ResultTy);
563 
564   // We are using the following formula for BC(It, K):
565   //
566   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
567   //
568   // Suppose, W is the bitwidth of the return value.  We must be prepared for
569   // overflow.  Hence, we must assure that the result of our computation is
570   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
571   // safe in modular arithmetic.
572   //
573   // However, this code doesn't use exactly that formula; the formula it uses
574   // is something like the following, where T is the number of factors of 2 in
575   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
576   // exponentiation:
577   //
578   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
579   //
580   // This formula is trivially equivalent to the previous formula.  However,
581   // this formula can be implemented much more efficiently.  The trick is that
582   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
583   // arithmetic.  To do exact division in modular arithmetic, all we have
584   // to do is multiply by the inverse.  Therefore, this step can be done at
585   // width W.
586   //
587   // The next issue is how to safely do the division by 2^T.  The way this
588   // is done is by doing the multiplication step at a width of at least W + T
589   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
590   // when we perform the division by 2^T (which is equivalent to a right shift
591   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
592   // truncated out after the division by 2^T.
593   //
594   // In comparison to just directly using the first formula, this technique
595   // is much more efficient; using the first formula requires W * K bits,
596   // but this formula less than W + K bits. Also, the first formula requires
597   // a division step, whereas this formula only requires multiplies and shifts.
598   //
599   // It doesn't matter whether the subtraction step is done in the calculation
600   // width or the input iteration count's width; if the subtraction overflows,
601   // the result must be zero anyway.  We prefer here to do it in the width of
602   // the induction variable because it helps a lot for certain cases; CodeGen
603   // isn't smart enough to ignore the overflow, which leads to much less
604   // efficient code if the width of the subtraction is wider than the native
605   // register width.
606   //
607   // (It's possible to not widen at all by pulling out factors of 2 before
608   // the multiplication; for example, K=2 can be calculated as
609   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
610   // extra arithmetic, so it's not an obvious win, and it gets
611   // much more complicated for K > 3.)
612 
613   // Protection from insane SCEVs; this bound is conservative,
614   // but it probably doesn't matter.
615   if (K > 1000)
616     return SE.getCouldNotCompute();
617 
618   unsigned W = SE.getTypeSizeInBits(ResultTy);
619 
620   // Calculate K! / 2^T and T; we divide out the factors of two before
621   // multiplying for calculating K! / 2^T to avoid overflow.
622   // Other overflow doesn't matter because we only care about the bottom
623   // W bits of the result.
624   APInt OddFactorial(W, 1);
625   unsigned T = 1;
626   for (unsigned i = 3; i <= K; ++i) {
627     APInt Mult(W, i);
628     unsigned TwoFactors = Mult.countTrailingZeros();
629     T += TwoFactors;
630     Mult = Mult.lshr(TwoFactors);
631     OddFactorial *= Mult;
632   }
633 
634   // We need at least W + T bits for the multiplication step
635   unsigned CalculationBits = W + T;
636 
637   // Calculate 2^T, at width T+W.
638   APInt DivFactor = APInt(CalculationBits, 1).shl(T);
639 
640   // Calculate the multiplicative inverse of K! / 2^T;
641   // this multiplication factor will perform the exact division by
642   // K! / 2^T.
643   APInt Mod = APInt::getSignedMinValue(W+1);
644   APInt MultiplyFactor = OddFactorial.zext(W+1);
645   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
646   MultiplyFactor = MultiplyFactor.trunc(W);
647 
648   // Calculate the product, at width T+W
649   const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
650                                                       CalculationBits);
651   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
652   for (unsigned i = 1; i != K; ++i) {
653     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
654     Dividend = SE.getMulExpr(Dividend,
655                              SE.getTruncateOrZeroExtend(S, CalculationTy));
656   }
657 
658   // Divide by 2^T
659   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
660 
661   // Truncate the result, and divide by K! / 2^T.
662 
663   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
664                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
665 }
666 
667 /// evaluateAtIteration - Return the value of this chain of recurrences at
668 /// the specified iteration number.  We can evaluate this recurrence by
669 /// multiplying each element in the chain by the binomial coefficient
670 /// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
671 ///
672 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
673 ///
674 /// where BC(It, k) stands for binomial coefficient.
675 ///
676 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
677                                                 ScalarEvolution &SE) const {
678   const SCEV *Result = getStart();
679   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
680     // The computation is correct in the face of overflow provided that the
681     // multiplication is performed _after_ the evaluation of the binomial
682     // coefficient.
683     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
684     if (isa<SCEVCouldNotCompute>(Coeff))
685       return Coeff;
686 
687     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
688   }
689   return Result;
690 }
691 
692 //===----------------------------------------------------------------------===//
693 //                    SCEV Expression folder implementations
694 //===----------------------------------------------------------------------===//
695 
696 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
697                                              const Type *Ty) {
698   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
699          "This is not a truncating conversion!");
700   assert(isSCEVable(Ty) &&
701          "This is not a conversion to a SCEVable type!");
702   Ty = getEffectiveSCEVType(Ty);
703 
704   FoldingSetNodeID ID;
705   ID.AddInteger(scTruncate);
706   ID.AddPointer(Op);
707   ID.AddPointer(Ty);
708   void *IP = 0;
709   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
710 
711   // Fold if the operand is constant.
712   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
713     return getConstant(
714       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
715 
716   // trunc(trunc(x)) --> trunc(x)
717   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
718     return getTruncateExpr(ST->getOperand(), Ty);
719 
720   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
721   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
722     return getTruncateOrSignExtend(SS->getOperand(), Ty);
723 
724   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
725   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
726     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
727 
728   // If the input value is a chrec scev, truncate the chrec's operands.
729   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
730     SmallVector<const SCEV *, 4> Operands;
731     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
732       Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
733     return getAddRecExpr(Operands, AddRec->getLoop());
734   }
735 
736   // The cast wasn't folded; create an explicit cast node.
737   // Recompute the insert position, as it may have been invalidated.
738   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
739   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
740                                                  CurAllocationSequenceNumber++,
741                                                  Op, Ty);
742   UniqueSCEVs.InsertNode(S, IP);
743   return S;
744 }
745 
746 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
747                                                const Type *Ty) {
748   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
749          "This is not an extending conversion!");
750   assert(isSCEVable(Ty) &&
751          "This is not a conversion to a SCEVable type!");
752   Ty = getEffectiveSCEVType(Ty);
753 
754   // Fold if the operand is constant.
755   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
756     const Type *IntTy = getEffectiveSCEVType(Ty);
757     Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
758     if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
759     return getConstant(cast<ConstantInt>(C));
760   }
761 
762   // zext(zext(x)) --> zext(x)
763   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
764     return getZeroExtendExpr(SZ->getOperand(), Ty);
765 
766   // Before doing any expensive analysis, check to see if we've already
767   // computed a SCEV for this Op and Ty.
768   FoldingSetNodeID ID;
769   ID.AddInteger(scZeroExtend);
770   ID.AddPointer(Op);
771   ID.AddPointer(Ty);
772   void *IP = 0;
773   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
774 
775   // If the input value is a chrec scev, and we can prove that the value
776   // did not overflow the old, smaller, value, we can zero extend all of the
777   // operands (often constants).  This allows analysis of something like
778   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
779   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
780     if (AR->isAffine()) {
781       const SCEV *Start = AR->getStart();
782       const SCEV *Step = AR->getStepRecurrence(*this);
783       unsigned BitWidth = getTypeSizeInBits(AR->getType());
784       const Loop *L = AR->getLoop();
785 
786       // If we have special knowledge that this addrec won't overflow,
787       // we don't need to do any further analysis.
788       if (AR->hasNoUnsignedWrap())
789         return getAddRecExpr(getZeroExtendExpr(Start, Ty),
790                              getZeroExtendExpr(Step, Ty),
791                              L);
792 
793       // Check whether the backedge-taken count is SCEVCouldNotCompute.
794       // Note that this serves two purposes: It filters out loops that are
795       // simply not analyzable, and it covers the case where this code is
796       // being called from within backedge-taken count analysis, such that
797       // attempting to ask for the backedge-taken count would likely result
798       // in infinite recursion. In the later case, the analysis code will
799       // cope with a conservative value, and it will take care to purge
800       // that value once it has finished.
801       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
802       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
803         // Manually compute the final value for AR, checking for
804         // overflow.
805 
806         // Check whether the backedge-taken count can be losslessly casted to
807         // the addrec's type. The count is always unsigned.
808         const SCEV *CastedMaxBECount =
809           getTruncateOrZeroExtend(MaxBECount, Start->getType());
810         const SCEV *RecastedMaxBECount =
811           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
812         if (MaxBECount == RecastedMaxBECount) {
813           const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
814           // Check whether Start+Step*MaxBECount has no unsigned overflow.
815           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
816           const SCEV *Add = getAddExpr(Start, ZMul);
817           const SCEV *OperandExtendedAdd =
818             getAddExpr(getZeroExtendExpr(Start, WideTy),
819                        getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
820                                   getZeroExtendExpr(Step, WideTy)));
821           if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
822             // Return the expression with the addrec on the outside.
823             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
824                                  getZeroExtendExpr(Step, Ty),
825                                  L);
826 
827           // Similar to above, only this time treat the step value as signed.
828           // This covers loops that count down.
829           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
830           Add = getAddExpr(Start, SMul);
831           OperandExtendedAdd =
832             getAddExpr(getZeroExtendExpr(Start, WideTy),
833                        getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
834                                   getSignExtendExpr(Step, WideTy)));
835           if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
836             // Return the expression with the addrec on the outside.
837             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
838                                  getSignExtendExpr(Step, Ty),
839                                  L);
840         }
841 
842         // If the backedge is guarded by a comparison with the pre-inc value
843         // the addrec is safe. Also, if the entry is guarded by a comparison
844         // with the start value and the backedge is guarded by a comparison
845         // with the post-inc value, the addrec is safe.
846         if (isKnownPositive(Step)) {
847           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
848                                       getUnsignedRange(Step).getUnsignedMax());
849           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
850               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
851                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
852                                            AR->getPostIncExpr(*this), N)))
853             // Return the expression with the addrec on the outside.
854             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
855                                  getZeroExtendExpr(Step, Ty),
856                                  L);
857         } else if (isKnownNegative(Step)) {
858           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
859                                       getSignedRange(Step).getSignedMin());
860           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
861               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
862                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
863                                            AR->getPostIncExpr(*this), N)))
864             // Return the expression with the addrec on the outside.
865             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
866                                  getSignExtendExpr(Step, Ty),
867                                  L);
868         }
869       }
870     }
871 
872   // The cast wasn't folded; create an explicit cast node.
873   // Recompute the insert position, as it may have been invalidated.
874   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
875   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
876                                                   CurAllocationSequenceNumber++,
877                                                    Op, Ty);
878   UniqueSCEVs.InsertNode(S, IP);
879   return S;
880 }
881 
882 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
883                                                const Type *Ty) {
884   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
885          "This is not an extending conversion!");
886   assert(isSCEVable(Ty) &&
887          "This is not a conversion to a SCEVable type!");
888   Ty = getEffectiveSCEVType(Ty);
889 
890   // Fold if the operand is constant.
891   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
892     const Type *IntTy = getEffectiveSCEVType(Ty);
893     Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
894     if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
895     return getConstant(cast<ConstantInt>(C));
896   }
897 
898   // sext(sext(x)) --> sext(x)
899   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
900     return getSignExtendExpr(SS->getOperand(), Ty);
901 
902   // Before doing any expensive analysis, check to see if we've already
903   // computed a SCEV for this Op and Ty.
904   FoldingSetNodeID ID;
905   ID.AddInteger(scSignExtend);
906   ID.AddPointer(Op);
907   ID.AddPointer(Ty);
908   void *IP = 0;
909   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
910 
911   // If the input value is a chrec scev, and we can prove that the value
912   // did not overflow the old, smaller, value, we can sign extend all of the
913   // operands (often constants).  This allows analysis of something like
914   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
915   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
916     if (AR->isAffine()) {
917       const SCEV *Start = AR->getStart();
918       const SCEV *Step = AR->getStepRecurrence(*this);
919       unsigned BitWidth = getTypeSizeInBits(AR->getType());
920       const Loop *L = AR->getLoop();
921 
922       // If we have special knowledge that this addrec won't overflow,
923       // we don't need to do any further analysis.
924       if (AR->hasNoSignedWrap())
925         return getAddRecExpr(getSignExtendExpr(Start, Ty),
926                              getSignExtendExpr(Step, Ty),
927                              L);
928 
929       // Check whether the backedge-taken count is SCEVCouldNotCompute.
930       // Note that this serves two purposes: It filters out loops that are
931       // simply not analyzable, and it covers the case where this code is
932       // being called from within backedge-taken count analysis, such that
933       // attempting to ask for the backedge-taken count would likely result
934       // in infinite recursion. In the later case, the analysis code will
935       // cope with a conservative value, and it will take care to purge
936       // that value once it has finished.
937       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
938       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
939         // Manually compute the final value for AR, checking for
940         // overflow.
941 
942         // Check whether the backedge-taken count can be losslessly casted to
943         // the addrec's type. The count is always unsigned.
944         const SCEV *CastedMaxBECount =
945           getTruncateOrZeroExtend(MaxBECount, Start->getType());
946         const SCEV *RecastedMaxBECount =
947           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
948         if (MaxBECount == RecastedMaxBECount) {
949           const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
950           // Check whether Start+Step*MaxBECount has no signed overflow.
951           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
952           const SCEV *Add = getAddExpr(Start, SMul);
953           const SCEV *OperandExtendedAdd =
954             getAddExpr(getSignExtendExpr(Start, WideTy),
955                        getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
956                                   getSignExtendExpr(Step, WideTy)));
957           if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
958             // Return the expression with the addrec on the outside.
959             return getAddRecExpr(getSignExtendExpr(Start, Ty),
960                                  getSignExtendExpr(Step, Ty),
961                                  L);
962 
963           // Similar to above, only this time treat the step value as unsigned.
964           // This covers loops that count up with an unsigned step.
965           const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
966           Add = getAddExpr(Start, UMul);
967           OperandExtendedAdd =
968             getAddExpr(getSignExtendExpr(Start, WideTy),
969                        getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
970                                   getZeroExtendExpr(Step, WideTy)));
971           if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
972             // Return the expression with the addrec on the outside.
973             return getAddRecExpr(getSignExtendExpr(Start, Ty),
974                                  getZeroExtendExpr(Step, Ty),
975                                  L);
976         }
977 
978         // If the backedge is guarded by a comparison with the pre-inc value
979         // the addrec is safe. Also, if the entry is guarded by a comparison
980         // with the start value and the backedge is guarded by a comparison
981         // with the post-inc value, the addrec is safe.
982         if (isKnownPositive(Step)) {
983           const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
984                                       getSignedRange(Step).getSignedMax());
985           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
986               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
987                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
988                                            AR->getPostIncExpr(*this), N)))
989             // Return the expression with the addrec on the outside.
990             return getAddRecExpr(getSignExtendExpr(Start, Ty),
991                                  getSignExtendExpr(Step, Ty),
992                                  L);
993         } else if (isKnownNegative(Step)) {
994           const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
995                                       getSignedRange(Step).getSignedMin());
996           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
997               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
998                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
999                                            AR->getPostIncExpr(*this), N)))
1000             // Return the expression with the addrec on the outside.
1001             return getAddRecExpr(getSignExtendExpr(Start, Ty),
1002                                  getSignExtendExpr(Step, Ty),
1003                                  L);
1004         }
1005       }
1006     }
1007 
1008   // The cast wasn't folded; create an explicit cast node.
1009   // Recompute the insert position, as it may have been invalidated.
1010   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1011   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1012                                                   CurAllocationSequenceNumber++,
1013                                                    Op, Ty);
1014   UniqueSCEVs.InsertNode(S, IP);
1015   return S;
1016 }
1017 
1018 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1019 /// unspecified bits out to the given type.
1020 ///
1021 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1022                                               const Type *Ty) {
1023   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1024          "This is not an extending conversion!");
1025   assert(isSCEVable(Ty) &&
1026          "This is not a conversion to a SCEVable type!");
1027   Ty = getEffectiveSCEVType(Ty);
1028 
1029   // Sign-extend negative constants.
1030   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1031     if (SC->getValue()->getValue().isNegative())
1032       return getSignExtendExpr(Op, Ty);
1033 
1034   // Peel off a truncate cast.
1035   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1036     const SCEV *NewOp = T->getOperand();
1037     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1038       return getAnyExtendExpr(NewOp, Ty);
1039     return getTruncateOrNoop(NewOp, Ty);
1040   }
1041 
1042   // Next try a zext cast. If the cast is folded, use it.
1043   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1044   if (!isa<SCEVZeroExtendExpr>(ZExt))
1045     return ZExt;
1046 
1047   // Next try a sext cast. If the cast is folded, use it.
1048   const SCEV *SExt = getSignExtendExpr(Op, Ty);
1049   if (!isa<SCEVSignExtendExpr>(SExt))
1050     return SExt;
1051 
1052   // Force the cast to be folded into the operands of an addrec.
1053   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1054     SmallVector<const SCEV *, 4> Ops;
1055     for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1056          I != E; ++I)
1057       Ops.push_back(getAnyExtendExpr(*I, Ty));
1058     return getAddRecExpr(Ops, AR->getLoop());
1059   }
1060 
1061   // If the expression is obviously signed, use the sext cast value.
1062   if (isa<SCEVSMaxExpr>(Op))
1063     return SExt;
1064 
1065   // Absent any other information, use the zext cast value.
1066   return ZExt;
1067 }
1068 
1069 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1070 /// a list of operands to be added under the given scale, update the given
1071 /// map. This is a helper function for getAddRecExpr. As an example of
1072 /// what it does, given a sequence of operands that would form an add
1073 /// expression like this:
1074 ///
1075 ///    m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1076 ///
1077 /// where A and B are constants, update the map with these values:
1078 ///
1079 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1080 ///
1081 /// and add 13 + A*B*29 to AccumulatedConstant.
1082 /// This will allow getAddRecExpr to produce this:
1083 ///
1084 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1085 ///
1086 /// This form often exposes folding opportunities that are hidden in
1087 /// the original operand list.
1088 ///
1089 /// Return true iff it appears that any interesting folding opportunities
1090 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1091 /// the common case where no interesting opportunities are present, and
1092 /// is also used as a check to avoid infinite recursion.
1093 ///
1094 static bool
1095 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1096                              SmallVector<const SCEV *, 8> &NewOps,
1097                              APInt &AccumulatedConstant,
1098                              const SCEV *const *Ops, size_t NumOperands,
1099                              const APInt &Scale,
1100                              ScalarEvolution &SE) {
1101   bool Interesting = false;
1102 
1103   // Iterate over the add operands. They are sorted, with constants first.
1104   unsigned i = 0;
1105   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1106     ++i;
1107     // Pull a buried constant out to the outside.
1108     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1109       Interesting = true;
1110     AccumulatedConstant += Scale * C->getValue()->getValue();
1111   }
1112 
1113   // Next comes everything else. We're especially interested in multiplies
1114   // here, but they're in the middle, so just visit the rest with one loop.
1115   for (; i != NumOperands; ++i) {
1116     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1117     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1118       APInt NewScale =
1119         Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1120       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1121         // A multiplication of a constant with another add; recurse.
1122         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1123         Interesting |=
1124           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1125                                        Add->op_begin(), Add->getNumOperands(),
1126                                        NewScale, SE);
1127       } else {
1128         // A multiplication of a constant with some other value. Update
1129         // the map.
1130         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1131         const SCEV *Key = SE.getMulExpr(MulOps);
1132         std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1133           M.insert(std::make_pair(Key, NewScale));
1134         if (Pair.second) {
1135           NewOps.push_back(Pair.first->first);
1136         } else {
1137           Pair.first->second += NewScale;
1138           // The map already had an entry for this value, which may indicate
1139           // a folding opportunity.
1140           Interesting = true;
1141         }
1142       }
1143     } else {
1144       // An ordinary operand. Update the map.
1145       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1146         M.insert(std::make_pair(Ops[i], Scale));
1147       if (Pair.second) {
1148         NewOps.push_back(Pair.first->first);
1149       } else {
1150         Pair.first->second += Scale;
1151         // The map already had an entry for this value, which may indicate
1152         // a folding opportunity.
1153         Interesting = true;
1154       }
1155     }
1156   }
1157 
1158   return Interesting;
1159 }
1160 
1161 namespace {
1162   struct APIntCompare {
1163     bool operator()(const APInt &LHS, const APInt &RHS) const {
1164       return LHS.ult(RHS);
1165     }
1166   };
1167 }
1168 
1169 /// getAddExpr - Get a canonical add expression, or something simpler if
1170 /// possible.
1171 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1172                                         bool HasNUW, bool HasNSW) {
1173   assert(!Ops.empty() && "Cannot get empty add!");
1174   if (Ops.size() == 1) return Ops[0];
1175 #ifndef NDEBUG
1176   const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1177   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1178     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1179            "SCEVAddExpr operand types don't match!");
1180 #endif
1181 
1182   // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1183   if (!HasNUW && HasNSW) {
1184     bool All = true;
1185     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1186       if (!isKnownNonNegative(Ops[i])) {
1187         All = false;
1188         break;
1189       }
1190     if (All) HasNUW = true;
1191   }
1192 
1193   // Sort by complexity, this groups all similar expression types together.
1194   GroupByComplexity(Ops, LI);
1195 
1196   // If there are any constants, fold them together.
1197   unsigned Idx = 0;
1198   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1199     ++Idx;
1200     assert(Idx < Ops.size());
1201     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1202       // We found two constants, fold them together!
1203       Ops[0] = getConstant(LHSC->getValue()->getValue() +
1204                            RHSC->getValue()->getValue());
1205       if (Ops.size() == 2) return Ops[0];
1206       Ops.erase(Ops.begin()+1);  // Erase the folded element
1207       LHSC = cast<SCEVConstant>(Ops[0]);
1208     }
1209 
1210     // If we are left with a constant zero being added, strip it off.
1211     if (LHSC->getValue()->isZero()) {
1212       Ops.erase(Ops.begin());
1213       --Idx;
1214     }
1215 
1216     if (Ops.size() == 1) return Ops[0];
1217   }
1218 
1219   // Okay, check to see if the same value occurs in the operand list twice.  If
1220   // so, merge them together into an multiply expression.  Since we sorted the
1221   // list, these values are required to be adjacent.
1222   const Type *Ty = Ops[0]->getType();
1223   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1224     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
1225       // Found a match, merge the two values into a multiply, and add any
1226       // remaining values to the result.
1227       const SCEV *Two = getConstant(Ty, 2);
1228       const SCEV *Mul = getMulExpr(Ops[i], Two);
1229       if (Ops.size() == 2)
1230         return Mul;
1231       Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1232       Ops.push_back(Mul);
1233       return getAddExpr(Ops, HasNUW, HasNSW);
1234     }
1235 
1236   // Check for truncates. If all the operands are truncated from the same
1237   // type, see if factoring out the truncate would permit the result to be
1238   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1239   // if the contents of the resulting outer trunc fold to something simple.
1240   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1241     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1242     const Type *DstType = Trunc->getType();
1243     const Type *SrcType = Trunc->getOperand()->getType();
1244     SmallVector<const SCEV *, 8> LargeOps;
1245     bool Ok = true;
1246     // Check all the operands to see if they can be represented in the
1247     // source type of the truncate.
1248     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1249       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1250         if (T->getOperand()->getType() != SrcType) {
1251           Ok = false;
1252           break;
1253         }
1254         LargeOps.push_back(T->getOperand());
1255       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1256         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1257       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1258         SmallVector<const SCEV *, 8> LargeMulOps;
1259         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1260           if (const SCEVTruncateExpr *T =
1261                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1262             if (T->getOperand()->getType() != SrcType) {
1263               Ok = false;
1264               break;
1265             }
1266             LargeMulOps.push_back(T->getOperand());
1267           } else if (const SCEVConstant *C =
1268                        dyn_cast<SCEVConstant>(M->getOperand(j))) {
1269             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1270           } else {
1271             Ok = false;
1272             break;
1273           }
1274         }
1275         if (Ok)
1276           LargeOps.push_back(getMulExpr(LargeMulOps));
1277       } else {
1278         Ok = false;
1279         break;
1280       }
1281     }
1282     if (Ok) {
1283       // Evaluate the expression in the larger type.
1284       const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
1285       // If it folds to something simple, use it. Otherwise, don't.
1286       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1287         return getTruncateExpr(Fold, DstType);
1288     }
1289   }
1290 
1291   // Skip past any other cast SCEVs.
1292   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1293     ++Idx;
1294 
1295   // If there are add operands they would be next.
1296   if (Idx < Ops.size()) {
1297     bool DeletedAdd = false;
1298     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1299       // If we have an add, expand the add operands onto the end of the operands
1300       // list.
1301       Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1302       Ops.erase(Ops.begin()+Idx);
1303       DeletedAdd = true;
1304     }
1305 
1306     // If we deleted at least one add, we added operands to the end of the list,
1307     // and they are not necessarily sorted.  Recurse to resort and resimplify
1308     // any operands we just acquired.
1309     if (DeletedAdd)
1310       return getAddExpr(Ops);
1311   }
1312 
1313   // Skip over the add expression until we get to a multiply.
1314   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1315     ++Idx;
1316 
1317   // Check to see if there are any folding opportunities present with
1318   // operands multiplied by constant values.
1319   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1320     uint64_t BitWidth = getTypeSizeInBits(Ty);
1321     DenseMap<const SCEV *, APInt> M;
1322     SmallVector<const SCEV *, 8> NewOps;
1323     APInt AccumulatedConstant(BitWidth, 0);
1324     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1325                                      Ops.data(), Ops.size(),
1326                                      APInt(BitWidth, 1), *this)) {
1327       // Some interesting folding opportunity is present, so its worthwhile to
1328       // re-generate the operands list. Group the operands by constant scale,
1329       // to avoid multiplying by the same constant scale multiple times.
1330       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1331       for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1332            E = NewOps.end(); I != E; ++I)
1333         MulOpLists[M.find(*I)->second].push_back(*I);
1334       // Re-generate the operands list.
1335       Ops.clear();
1336       if (AccumulatedConstant != 0)
1337         Ops.push_back(getConstant(AccumulatedConstant));
1338       for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1339            I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1340         if (I->first != 0)
1341           Ops.push_back(getMulExpr(getConstant(I->first),
1342                                    getAddExpr(I->second)));
1343       if (Ops.empty())
1344         return getConstant(Ty, 0);
1345       if (Ops.size() == 1)
1346         return Ops[0];
1347       return getAddExpr(Ops);
1348     }
1349   }
1350 
1351   // If we are adding something to a multiply expression, make sure the
1352   // something is not already an operand of the multiply.  If so, merge it into
1353   // the multiply.
1354   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1355     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1356     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1357       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1358       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1359         if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1360           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
1361           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1362           if (Mul->getNumOperands() != 2) {
1363             // If the multiply has more than two operands, we must get the
1364             // Y*Z term.
1365             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1366             MulOps.erase(MulOps.begin()+MulOp);
1367             InnerMul = getMulExpr(MulOps);
1368           }
1369           const SCEV *One = getConstant(Ty, 1);
1370           const SCEV *AddOne = getAddExpr(InnerMul, One);
1371           const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1372           if (Ops.size() == 2) return OuterMul;
1373           if (AddOp < Idx) {
1374             Ops.erase(Ops.begin()+AddOp);
1375             Ops.erase(Ops.begin()+Idx-1);
1376           } else {
1377             Ops.erase(Ops.begin()+Idx);
1378             Ops.erase(Ops.begin()+AddOp-1);
1379           }
1380           Ops.push_back(OuterMul);
1381           return getAddExpr(Ops);
1382         }
1383 
1384       // Check this multiply against other multiplies being added together.
1385       for (unsigned OtherMulIdx = Idx+1;
1386            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1387            ++OtherMulIdx) {
1388         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1389         // If MulOp occurs in OtherMul, we can fold the two multiplies
1390         // together.
1391         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1392              OMulOp != e; ++OMulOp)
1393           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1394             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1395             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1396             if (Mul->getNumOperands() != 2) {
1397               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1398                                                   Mul->op_end());
1399               MulOps.erase(MulOps.begin()+MulOp);
1400               InnerMul1 = getMulExpr(MulOps);
1401             }
1402             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1403             if (OtherMul->getNumOperands() != 2) {
1404               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1405                                                   OtherMul->op_end());
1406               MulOps.erase(MulOps.begin()+OMulOp);
1407               InnerMul2 = getMulExpr(MulOps);
1408             }
1409             const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1410             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1411             if (Ops.size() == 2) return OuterMul;
1412             Ops.erase(Ops.begin()+Idx);
1413             Ops.erase(Ops.begin()+OtherMulIdx-1);
1414             Ops.push_back(OuterMul);
1415             return getAddExpr(Ops);
1416           }
1417       }
1418     }
1419   }
1420 
1421   // If there are any add recurrences in the operands list, see if any other
1422   // added values are loop invariant.  If so, we can fold them into the
1423   // recurrence.
1424   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1425     ++Idx;
1426 
1427   // Scan over all recurrences, trying to fold loop invariants into them.
1428   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1429     // Scan all of the other operands to this add and add them to the vector if
1430     // they are loop invariant w.r.t. the recurrence.
1431     SmallVector<const SCEV *, 8> LIOps;
1432     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1433     const Loop *AddRecLoop = AddRec->getLoop();
1434     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1435       if (Ops[i]->isLoopInvariant(AddRecLoop)) {
1436         LIOps.push_back(Ops[i]);
1437         Ops.erase(Ops.begin()+i);
1438         --i; --e;
1439       }
1440 
1441     // If we found some loop invariants, fold them into the recurrence.
1442     if (!LIOps.empty()) {
1443       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
1444       LIOps.push_back(AddRec->getStart());
1445 
1446       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1447                                              AddRec->op_end());
1448       AddRecOps[0] = getAddExpr(LIOps);
1449 
1450       // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
1451       // is not associative so this isn't necessarily safe.
1452       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop);
1453 
1454       // If all of the other operands were loop invariant, we are done.
1455       if (Ops.size() == 1) return NewRec;
1456 
1457       // Otherwise, add the folded AddRec by the non-liv parts.
1458       for (unsigned i = 0;; ++i)
1459         if (Ops[i] == AddRec) {
1460           Ops[i] = NewRec;
1461           break;
1462         }
1463       return getAddExpr(Ops);
1464     }
1465 
1466     // Okay, if there weren't any loop invariants to be folded, check to see if
1467     // there are multiple AddRec's with the same loop induction variable being
1468     // added together.  If so, we can fold them.
1469     for (unsigned OtherIdx = Idx+1;
1470          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1471       if (OtherIdx != Idx) {
1472         const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1473         if (AddRecLoop == OtherAddRec->getLoop()) {
1474           // Other + {A,+,B} + {C,+,D}  -->  Other + {A+C,+,B+D}
1475           SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1476                                               AddRec->op_end());
1477           for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1478             if (i >= NewOps.size()) {
1479               NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1480                             OtherAddRec->op_end());
1481               break;
1482             }
1483             NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1484           }
1485           const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
1486 
1487           if (Ops.size() == 2) return NewAddRec;
1488 
1489           Ops.erase(Ops.begin()+Idx);
1490           Ops.erase(Ops.begin()+OtherIdx-1);
1491           Ops.push_back(NewAddRec);
1492           return getAddExpr(Ops);
1493         }
1494       }
1495 
1496     // Otherwise couldn't fold anything into this recurrence.  Move onto the
1497     // next one.
1498   }
1499 
1500   // Okay, it looks like we really DO need an add expr.  Check to see if we
1501   // already have one, otherwise create a new one.
1502   FoldingSetNodeID ID;
1503   ID.AddInteger(scAddExpr);
1504   ID.AddInteger(Ops.size());
1505   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1506     ID.AddPointer(Ops[i]);
1507   void *IP = 0;
1508   SCEVAddExpr *S =
1509     static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1510   if (!S) {
1511     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1512     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1513     S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1514                                         CurAllocationSequenceNumber++,
1515                                         O, Ops.size());
1516     UniqueSCEVs.InsertNode(S, IP);
1517   }
1518   if (HasNUW) S->setHasNoUnsignedWrap(true);
1519   if (HasNSW) S->setHasNoSignedWrap(true);
1520   return S;
1521 }
1522 
1523 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1524 /// possible.
1525 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1526                                         bool HasNUW, bool HasNSW) {
1527   assert(!Ops.empty() && "Cannot get empty mul!");
1528   if (Ops.size() == 1) return Ops[0];
1529 #ifndef NDEBUG
1530   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1531     assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1532            getEffectiveSCEVType(Ops[0]->getType()) &&
1533            "SCEVMulExpr operand types don't match!");
1534 #endif
1535 
1536   // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1537   if (!HasNUW && HasNSW) {
1538     bool All = true;
1539     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1540       if (!isKnownNonNegative(Ops[i])) {
1541         All = false;
1542         break;
1543       }
1544     if (All) HasNUW = true;
1545   }
1546 
1547   // Sort by complexity, this groups all similar expression types together.
1548   GroupByComplexity(Ops, LI);
1549 
1550   // If there are any constants, fold them together.
1551   unsigned Idx = 0;
1552   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1553 
1554     // C1*(C2+V) -> C1*C2 + C1*V
1555     if (Ops.size() == 2)
1556       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1557         if (Add->getNumOperands() == 2 &&
1558             isa<SCEVConstant>(Add->getOperand(0)))
1559           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1560                             getMulExpr(LHSC, Add->getOperand(1)));
1561 
1562     ++Idx;
1563     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1564       // We found two constants, fold them together!
1565       ConstantInt *Fold = ConstantInt::get(getContext(),
1566                                            LHSC->getValue()->getValue() *
1567                                            RHSC->getValue()->getValue());
1568       Ops[0] = getConstant(Fold);
1569       Ops.erase(Ops.begin()+1);  // Erase the folded element
1570       if (Ops.size() == 1) return Ops[0];
1571       LHSC = cast<SCEVConstant>(Ops[0]);
1572     }
1573 
1574     // If we are left with a constant one being multiplied, strip it off.
1575     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1576       Ops.erase(Ops.begin());
1577       --Idx;
1578     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1579       // If we have a multiply of zero, it will always be zero.
1580       return Ops[0];
1581     } else if (Ops[0]->isAllOnesValue()) {
1582       // If we have a mul by -1 of an add, try distributing the -1 among the
1583       // add operands.
1584       if (Ops.size() == 2)
1585         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1586           SmallVector<const SCEV *, 4> NewOps;
1587           bool AnyFolded = false;
1588           for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1589                I != E; ++I) {
1590             const SCEV *Mul = getMulExpr(Ops[0], *I);
1591             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1592             NewOps.push_back(Mul);
1593           }
1594           if (AnyFolded)
1595             return getAddExpr(NewOps);
1596         }
1597     }
1598 
1599     if (Ops.size() == 1)
1600       return Ops[0];
1601   }
1602 
1603   // Skip over the add expression until we get to a multiply.
1604   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1605     ++Idx;
1606 
1607   // If there are mul operands inline them all into this expression.
1608   if (Idx < Ops.size()) {
1609     bool DeletedMul = false;
1610     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1611       // If we have an mul, expand the mul operands onto the end of the operands
1612       // list.
1613       Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1614       Ops.erase(Ops.begin()+Idx);
1615       DeletedMul = true;
1616     }
1617 
1618     // If we deleted at least one mul, we added operands to the end of the list,
1619     // and they are not necessarily sorted.  Recurse to resort and resimplify
1620     // any operands we just acquired.
1621     if (DeletedMul)
1622       return getMulExpr(Ops);
1623   }
1624 
1625   // If there are any add recurrences in the operands list, see if any other
1626   // added values are loop invariant.  If so, we can fold them into the
1627   // recurrence.
1628   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1629     ++Idx;
1630 
1631   // Scan over all recurrences, trying to fold loop invariants into them.
1632   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1633     // Scan all of the other operands to this mul and add them to the vector if
1634     // they are loop invariant w.r.t. the recurrence.
1635     SmallVector<const SCEV *, 8> LIOps;
1636     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1637     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1638       if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1639         LIOps.push_back(Ops[i]);
1640         Ops.erase(Ops.begin()+i);
1641         --i; --e;
1642       }
1643 
1644     // If we found some loop invariants, fold them into the recurrence.
1645     if (!LIOps.empty()) {
1646       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
1647       SmallVector<const SCEV *, 4> NewOps;
1648       NewOps.reserve(AddRec->getNumOperands());
1649       if (LIOps.size() == 1) {
1650         const SCEV *Scale = LIOps[0];
1651         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1652           NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1653       } else {
1654         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1655           SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
1656           MulOps.push_back(AddRec->getOperand(i));
1657           NewOps.push_back(getMulExpr(MulOps));
1658         }
1659       }
1660 
1661       // It's tempting to propagate the NSW flag here, but nsw multiplication
1662       // is not associative so this isn't necessarily safe.
1663       const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1664                                          HasNUW && AddRec->hasNoUnsignedWrap(),
1665                                          /*HasNSW=*/false);
1666 
1667       // If all of the other operands were loop invariant, we are done.
1668       if (Ops.size() == 1) return NewRec;
1669 
1670       // Otherwise, multiply the folded AddRec by the non-liv parts.
1671       for (unsigned i = 0;; ++i)
1672         if (Ops[i] == AddRec) {
1673           Ops[i] = NewRec;
1674           break;
1675         }
1676       return getMulExpr(Ops);
1677     }
1678 
1679     // Okay, if there weren't any loop invariants to be folded, check to see if
1680     // there are multiple AddRec's with the same loop induction variable being
1681     // multiplied together.  If so, we can fold them.
1682     for (unsigned OtherIdx = Idx+1;
1683          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1684       if (OtherIdx != Idx) {
1685         const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1686         if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1687           // F * G  -->  {A,+,B} * {C,+,D}  -->  {A*C,+,F*D + G*B + B*D}
1688           const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1689           const SCEV *NewStart = getMulExpr(F->getStart(),
1690                                                  G->getStart());
1691           const SCEV *B = F->getStepRecurrence(*this);
1692           const SCEV *D = G->getStepRecurrence(*this);
1693           const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1694                                           getMulExpr(G, B),
1695                                           getMulExpr(B, D));
1696           const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1697                                                F->getLoop());
1698           if (Ops.size() == 2) return NewAddRec;
1699 
1700           Ops.erase(Ops.begin()+Idx);
1701           Ops.erase(Ops.begin()+OtherIdx-1);
1702           Ops.push_back(NewAddRec);
1703           return getMulExpr(Ops);
1704         }
1705       }
1706 
1707     // Otherwise couldn't fold anything into this recurrence.  Move onto the
1708     // next one.
1709   }
1710 
1711   // Okay, it looks like we really DO need an mul expr.  Check to see if we
1712   // already have one, otherwise create a new one.
1713   FoldingSetNodeID ID;
1714   ID.AddInteger(scMulExpr);
1715   ID.AddInteger(Ops.size());
1716   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1717     ID.AddPointer(Ops[i]);
1718   void *IP = 0;
1719   SCEVMulExpr *S =
1720     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1721   if (!S) {
1722     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1723     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1724     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1725                                         CurAllocationSequenceNumber++,
1726                                         O, Ops.size());
1727     UniqueSCEVs.InsertNode(S, IP);
1728   }
1729   if (HasNUW) S->setHasNoUnsignedWrap(true);
1730   if (HasNSW) S->setHasNoSignedWrap(true);
1731   return S;
1732 }
1733 
1734 /// getUDivExpr - Get a canonical unsigned division expression, or something
1735 /// simpler if possible.
1736 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1737                                          const SCEV *RHS) {
1738   assert(getEffectiveSCEVType(LHS->getType()) ==
1739          getEffectiveSCEVType(RHS->getType()) &&
1740          "SCEVUDivExpr operand types don't match!");
1741 
1742   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1743     if (RHSC->getValue()->equalsInt(1))
1744       return LHS;                               // X udiv 1 --> x
1745     // If the denominator is zero, the result of the udiv is undefined. Don't
1746     // try to analyze it, because the resolution chosen here may differ from
1747     // the resolution chosen in other parts of the compiler.
1748     if (!RHSC->getValue()->isZero()) {
1749       // Determine if the division can be folded into the operands of
1750       // its operands.
1751       // TODO: Generalize this to non-constants by using known-bits information.
1752       const Type *Ty = LHS->getType();
1753       unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1754       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1755       // For non-power-of-two values, effectively round the value up to the
1756       // nearest power of two.
1757       if (!RHSC->getValue()->getValue().isPowerOf2())
1758         ++MaxShiftAmt;
1759       const IntegerType *ExtTy =
1760         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1761       // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1762       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1763         if (const SCEVConstant *Step =
1764               dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1765           if (!Step->getValue()->getValue()
1766                 .urem(RHSC->getValue()->getValue()) &&
1767               getZeroExtendExpr(AR, ExtTy) ==
1768               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1769                             getZeroExtendExpr(Step, ExtTy),
1770                             AR->getLoop())) {
1771             SmallVector<const SCEV *, 4> Operands;
1772             for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1773               Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1774             return getAddRecExpr(Operands, AR->getLoop());
1775           }
1776       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1777       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1778         SmallVector<const SCEV *, 4> Operands;
1779         for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1780           Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1781         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1782           // Find an operand that's safely divisible.
1783           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1784             const SCEV *Op = M->getOperand(i);
1785             const SCEV *Div = getUDivExpr(Op, RHSC);
1786             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1787               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1788                                                       M->op_end());
1789               Operands[i] = Div;
1790               return getMulExpr(Operands);
1791             }
1792           }
1793       }
1794       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1795       if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1796         SmallVector<const SCEV *, 4> Operands;
1797         for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1798           Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1799         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1800           Operands.clear();
1801           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1802             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1803             if (isa<SCEVUDivExpr>(Op) ||
1804                 getMulExpr(Op, RHS) != A->getOperand(i))
1805               break;
1806             Operands.push_back(Op);
1807           }
1808           if (Operands.size() == A->getNumOperands())
1809             return getAddExpr(Operands);
1810         }
1811       }
1812 
1813       // Fold if both operands are constant.
1814       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1815         Constant *LHSCV = LHSC->getValue();
1816         Constant *RHSCV = RHSC->getValue();
1817         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1818                                                                    RHSCV)));
1819       }
1820     }
1821   }
1822 
1823   FoldingSetNodeID ID;
1824   ID.AddInteger(scUDivExpr);
1825   ID.AddPointer(LHS);
1826   ID.AddPointer(RHS);
1827   void *IP = 0;
1828   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1829   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1830                                              CurAllocationSequenceNumber++,
1831                                              LHS, RHS);
1832   UniqueSCEVs.InsertNode(S, IP);
1833   return S;
1834 }
1835 
1836 
1837 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1838 /// Simplify the expression as much as possible.
1839 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1840                                            const SCEV *Step, const Loop *L,
1841                                            bool HasNUW, bool HasNSW) {
1842   SmallVector<const SCEV *, 4> Operands;
1843   Operands.push_back(Start);
1844   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1845     if (StepChrec->getLoop() == L) {
1846       Operands.insert(Operands.end(), StepChrec->op_begin(),
1847                       StepChrec->op_end());
1848       return getAddRecExpr(Operands, L);
1849     }
1850 
1851   Operands.push_back(Step);
1852   return getAddRecExpr(Operands, L, HasNUW, HasNSW);
1853 }
1854 
1855 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1856 /// Simplify the expression as much as possible.
1857 const SCEV *
1858 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1859                                const Loop *L,
1860                                bool HasNUW, bool HasNSW) {
1861   if (Operands.size() == 1) return Operands[0];
1862 #ifndef NDEBUG
1863   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1864     assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1865            getEffectiveSCEVType(Operands[0]->getType()) &&
1866            "SCEVAddRecExpr operand types don't match!");
1867 #endif
1868 
1869   if (Operands.back()->isZero()) {
1870     Operands.pop_back();
1871     return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0}  -->  X
1872   }
1873 
1874   // It's tempting to want to call getMaxBackedgeTakenCount count here and
1875   // use that information to infer NUW and NSW flags. However, computing a
1876   // BE count requires calling getAddRecExpr, so we may not yet have a
1877   // meaningful BE count at this point (and if we don't, we'd be stuck
1878   // with a SCEVCouldNotCompute as the cached BE count).
1879 
1880   // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1881   if (!HasNUW && HasNSW) {
1882     bool All = true;
1883     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1884       if (!isKnownNonNegative(Operands[i])) {
1885         All = false;
1886         break;
1887       }
1888     if (All) HasNUW = true;
1889   }
1890 
1891   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1892   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1893     const Loop *NestedLoop = NestedAR->getLoop();
1894     if (L->contains(NestedLoop->getHeader()) ?
1895         (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1896         (!NestedLoop->contains(L->getHeader()) &&
1897          DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
1898       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
1899                                                   NestedAR->op_end());
1900       Operands[0] = NestedAR->getStart();
1901       // AddRecs require their operands be loop-invariant with respect to their
1902       // loops. Don't perform this transformation if it would break this
1903       // requirement.
1904       bool AllInvariant = true;
1905       for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1906         if (!Operands[i]->isLoopInvariant(L)) {
1907           AllInvariant = false;
1908           break;
1909         }
1910       if (AllInvariant) {
1911         NestedOperands[0] = getAddRecExpr(Operands, L);
1912         AllInvariant = true;
1913         for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1914           if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1915             AllInvariant = false;
1916             break;
1917           }
1918         if (AllInvariant)
1919           // Ok, both add recurrences are valid after the transformation.
1920           return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
1921       }
1922       // Reset Operands to its original state.
1923       Operands[0] = NestedAR;
1924     }
1925   }
1926 
1927   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
1928   // already have one, otherwise create a new one.
1929   FoldingSetNodeID ID;
1930   ID.AddInteger(scAddRecExpr);
1931   ID.AddInteger(Operands.size());
1932   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1933     ID.AddPointer(Operands[i]);
1934   ID.AddPointer(L);
1935   void *IP = 0;
1936   SCEVAddRecExpr *S =
1937     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1938   if (!S) {
1939     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
1940     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
1941     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
1942                                            CurAllocationSequenceNumber++,
1943                                            O, Operands.size(), L);
1944     UniqueSCEVs.InsertNode(S, IP);
1945   }
1946   if (HasNUW) S->setHasNoUnsignedWrap(true);
1947   if (HasNSW) S->setHasNoSignedWrap(true);
1948   return S;
1949 }
1950 
1951 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1952                                          const SCEV *RHS) {
1953   SmallVector<const SCEV *, 2> Ops;
1954   Ops.push_back(LHS);
1955   Ops.push_back(RHS);
1956   return getSMaxExpr(Ops);
1957 }
1958 
1959 const SCEV *
1960 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
1961   assert(!Ops.empty() && "Cannot get empty smax!");
1962   if (Ops.size() == 1) return Ops[0];
1963 #ifndef NDEBUG
1964   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1965     assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1966            getEffectiveSCEVType(Ops[0]->getType()) &&
1967            "SCEVSMaxExpr operand types don't match!");
1968 #endif
1969 
1970   // Sort by complexity, this groups all similar expression types together.
1971   GroupByComplexity(Ops, LI);
1972 
1973   // If there are any constants, fold them together.
1974   unsigned Idx = 0;
1975   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1976     ++Idx;
1977     assert(Idx < Ops.size());
1978     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1979       // We found two constants, fold them together!
1980       ConstantInt *Fold = ConstantInt::get(getContext(),
1981                               APIntOps::smax(LHSC->getValue()->getValue(),
1982                                              RHSC->getValue()->getValue()));
1983       Ops[0] = getConstant(Fold);
1984       Ops.erase(Ops.begin()+1);  // Erase the folded element
1985       if (Ops.size() == 1) return Ops[0];
1986       LHSC = cast<SCEVConstant>(Ops[0]);
1987     }
1988 
1989     // If we are left with a constant minimum-int, strip it off.
1990     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1991       Ops.erase(Ops.begin());
1992       --Idx;
1993     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1994       // If we have an smax with a constant maximum-int, it will always be
1995       // maximum-int.
1996       return Ops[0];
1997     }
1998 
1999     if (Ops.size() == 1) return Ops[0];
2000   }
2001 
2002   // Find the first SMax
2003   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2004     ++Idx;
2005 
2006   // Check to see if one of the operands is an SMax. If so, expand its operands
2007   // onto our operand list, and recurse to simplify.
2008   if (Idx < Ops.size()) {
2009     bool DeletedSMax = false;
2010     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2011       Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2012       Ops.erase(Ops.begin()+Idx);
2013       DeletedSMax = true;
2014     }
2015 
2016     if (DeletedSMax)
2017       return getSMaxExpr(Ops);
2018   }
2019 
2020   // Okay, check to see if the same value occurs in the operand list twice.  If
2021   // so, delete one.  Since we sorted the list, these values are required to
2022   // be adjacent.
2023   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2024     //  X smax Y smax Y  -->  X smax Y
2025     //  X smax Y         -->  X, if X is always greater than Y
2026     if (Ops[i] == Ops[i+1] ||
2027         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2028       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2029       --i; --e;
2030     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2031       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2032       --i; --e;
2033     }
2034 
2035   if (Ops.size() == 1) return Ops[0];
2036 
2037   assert(!Ops.empty() && "Reduced smax down to nothing!");
2038 
2039   // Okay, it looks like we really DO need an smax expr.  Check to see if we
2040   // already have one, otherwise create a new one.
2041   FoldingSetNodeID ID;
2042   ID.AddInteger(scSMaxExpr);
2043   ID.AddInteger(Ops.size());
2044   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2045     ID.AddPointer(Ops[i]);
2046   void *IP = 0;
2047   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2048   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2049   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2050   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2051                                              CurAllocationSequenceNumber++,
2052                                              O, Ops.size());
2053   UniqueSCEVs.InsertNode(S, IP);
2054   return S;
2055 }
2056 
2057 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2058                                          const SCEV *RHS) {
2059   SmallVector<const SCEV *, 2> Ops;
2060   Ops.push_back(LHS);
2061   Ops.push_back(RHS);
2062   return getUMaxExpr(Ops);
2063 }
2064 
2065 const SCEV *
2066 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2067   assert(!Ops.empty() && "Cannot get empty umax!");
2068   if (Ops.size() == 1) return Ops[0];
2069 #ifndef NDEBUG
2070   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2071     assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2072            getEffectiveSCEVType(Ops[0]->getType()) &&
2073            "SCEVUMaxExpr operand types don't match!");
2074 #endif
2075 
2076   // Sort by complexity, this groups all similar expression types together.
2077   GroupByComplexity(Ops, LI);
2078 
2079   // If there are any constants, fold them together.
2080   unsigned Idx = 0;
2081   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2082     ++Idx;
2083     assert(Idx < Ops.size());
2084     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2085       // We found two constants, fold them together!
2086       ConstantInt *Fold = ConstantInt::get(getContext(),
2087                               APIntOps::umax(LHSC->getValue()->getValue(),
2088                                              RHSC->getValue()->getValue()));
2089       Ops[0] = getConstant(Fold);
2090       Ops.erase(Ops.begin()+1);  // Erase the folded element
2091       if (Ops.size() == 1) return Ops[0];
2092       LHSC = cast<SCEVConstant>(Ops[0]);
2093     }
2094 
2095     // If we are left with a constant minimum-int, strip it off.
2096     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2097       Ops.erase(Ops.begin());
2098       --Idx;
2099     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2100       // If we have an umax with a constant maximum-int, it will always be
2101       // maximum-int.
2102       return Ops[0];
2103     }
2104 
2105     if (Ops.size() == 1) return Ops[0];
2106   }
2107 
2108   // Find the first UMax
2109   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2110     ++Idx;
2111 
2112   // Check to see if one of the operands is a UMax. If so, expand its operands
2113   // onto our operand list, and recurse to simplify.
2114   if (Idx < Ops.size()) {
2115     bool DeletedUMax = false;
2116     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2117       Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2118       Ops.erase(Ops.begin()+Idx);
2119       DeletedUMax = true;
2120     }
2121 
2122     if (DeletedUMax)
2123       return getUMaxExpr(Ops);
2124   }
2125 
2126   // Okay, check to see if the same value occurs in the operand list twice.  If
2127   // so, delete one.  Since we sorted the list, these values are required to
2128   // be adjacent.
2129   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2130     //  X umax Y umax Y  -->  X umax Y
2131     //  X umax Y         -->  X, if X is always greater than Y
2132     if (Ops[i] == Ops[i+1] ||
2133         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2134       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2135       --i; --e;
2136     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2137       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2138       --i; --e;
2139     }
2140 
2141   if (Ops.size() == 1) return Ops[0];
2142 
2143   assert(!Ops.empty() && "Reduced umax down to nothing!");
2144 
2145   // Okay, it looks like we really DO need a umax expr.  Check to see if we
2146   // already have one, otherwise create a new one.
2147   FoldingSetNodeID ID;
2148   ID.AddInteger(scUMaxExpr);
2149   ID.AddInteger(Ops.size());
2150   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2151     ID.AddPointer(Ops[i]);
2152   void *IP = 0;
2153   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2154   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2155   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2156   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2157                                              CurAllocationSequenceNumber++,
2158                                              O, Ops.size());
2159   UniqueSCEVs.InsertNode(S, IP);
2160   return S;
2161 }
2162 
2163 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2164                                          const SCEV *RHS) {
2165   // ~smax(~x, ~y) == smin(x, y).
2166   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2167 }
2168 
2169 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2170                                          const SCEV *RHS) {
2171   // ~umax(~x, ~y) == umin(x, y)
2172   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2173 }
2174 
2175 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2176   // If we have TargetData, we can bypass creating a target-independent
2177   // constant expression and then folding it back into a ConstantInt.
2178   // This is just a compile-time optimization.
2179   if (TD)
2180     return getConstant(TD->getIntPtrType(getContext()),
2181                        TD->getTypeAllocSize(AllocTy));
2182 
2183   Constant *C = ConstantExpr::getSizeOf(AllocTy);
2184   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2185     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2186       C = Folded;
2187   const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2188   return getTruncateOrZeroExtend(getSCEV(C), Ty);
2189 }
2190 
2191 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2192   Constant *C = ConstantExpr::getAlignOf(AllocTy);
2193   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2194     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2195       C = Folded;
2196   const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2197   return getTruncateOrZeroExtend(getSCEV(C), Ty);
2198 }
2199 
2200 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2201                                              unsigned FieldNo) {
2202   // If we have TargetData, we can bypass creating a target-independent
2203   // constant expression and then folding it back into a ConstantInt.
2204   // This is just a compile-time optimization.
2205   if (TD)
2206     return getConstant(TD->getIntPtrType(getContext()),
2207                        TD->getStructLayout(STy)->getElementOffset(FieldNo));
2208 
2209   Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2210   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2211     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2212       C = Folded;
2213   const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2214   return getTruncateOrZeroExtend(getSCEV(C), Ty);
2215 }
2216 
2217 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2218                                              Constant *FieldNo) {
2219   Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2220   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2221     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2222       C = Folded;
2223   const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2224   return getTruncateOrZeroExtend(getSCEV(C), Ty);
2225 }
2226 
2227 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2228   // Don't attempt to do anything other than create a SCEVUnknown object
2229   // here.  createSCEV only calls getUnknown after checking for all other
2230   // interesting possibilities, and any other code that calls getUnknown
2231   // is doing so in order to hide a value from SCEV canonicalization.
2232 
2233   FoldingSetNodeID ID;
2234   ID.AddInteger(scUnknown);
2235   ID.AddPointer(V);
2236   void *IP = 0;
2237   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2238   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator),
2239                                             CurAllocationSequenceNumber++,
2240                                             V);
2241   UniqueSCEVs.InsertNode(S, IP);
2242   return S;
2243 }
2244 
2245 //===----------------------------------------------------------------------===//
2246 //            Basic SCEV Analysis and PHI Idiom Recognition Code
2247 //
2248 
2249 /// isSCEVable - Test if values of the given type are analyzable within
2250 /// the SCEV framework. This primarily includes integer types, and it
2251 /// can optionally include pointer types if the ScalarEvolution class
2252 /// has access to target-specific information.
2253 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2254   // Integers and pointers are always SCEVable.
2255   return Ty->isIntegerTy() || Ty->isPointerTy();
2256 }
2257 
2258 /// getTypeSizeInBits - Return the size in bits of the specified type,
2259 /// for which isSCEVable must return true.
2260 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2261   assert(isSCEVable(Ty) && "Type is not SCEVable!");
2262 
2263   // If we have a TargetData, use it!
2264   if (TD)
2265     return TD->getTypeSizeInBits(Ty);
2266 
2267   // Integer types have fixed sizes.
2268   if (Ty->isIntegerTy())
2269     return Ty->getPrimitiveSizeInBits();
2270 
2271   // The only other support type is pointer. Without TargetData, conservatively
2272   // assume pointers are 64-bit.
2273   assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2274   return 64;
2275 }
2276 
2277 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2278 /// the given type and which represents how SCEV will treat the given
2279 /// type, for which isSCEVable must return true. For pointer types,
2280 /// this is the pointer-sized integer type.
2281 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2282   assert(isSCEVable(Ty) && "Type is not SCEVable!");
2283 
2284   if (Ty->isIntegerTy())
2285     return Ty;
2286 
2287   // The only other support type is pointer.
2288   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2289   if (TD) return TD->getIntPtrType(getContext());
2290 
2291   // Without TargetData, conservatively assume pointers are 64-bit.
2292   return Type::getInt64Ty(getContext());
2293 }
2294 
2295 const SCEV *ScalarEvolution::getCouldNotCompute() {
2296   return &CouldNotCompute;
2297 }
2298 
2299 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2300 /// expression and create a new one.
2301 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2302   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2303 
2304   std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2305   if (I != Scalars.end()) return I->second;
2306   const SCEV *S = createSCEV(V);
2307   Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2308   return S;
2309 }
2310 
2311 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
2312 /// specified signed integer value and return a SCEV for the constant.
2313 const SCEV *ScalarEvolution::getIntegerSCEV(int64_t Val, const Type *Ty) {
2314   const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2315   return getConstant(ConstantInt::get(ITy, Val));
2316 }
2317 
2318 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2319 ///
2320 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2321   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2322     return getConstant(
2323                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2324 
2325   const Type *Ty = V->getType();
2326   Ty = getEffectiveSCEVType(Ty);
2327   return getMulExpr(V,
2328                   getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2329 }
2330 
2331 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2332 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2333   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2334     return getConstant(
2335                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2336 
2337   const Type *Ty = V->getType();
2338   Ty = getEffectiveSCEVType(Ty);
2339   const SCEV *AllOnes =
2340                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2341   return getMinusSCEV(AllOnes, V);
2342 }
2343 
2344 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2345 ///
2346 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2347                                           const SCEV *RHS) {
2348   // X - Y --> X + -Y
2349   return getAddExpr(LHS, getNegativeSCEV(RHS));
2350 }
2351 
2352 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2353 /// input value to the specified type.  If the type must be extended, it is zero
2354 /// extended.
2355 const SCEV *
2356 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2357                                          const Type *Ty) {
2358   const Type *SrcTy = V->getType();
2359   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2360          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2361          "Cannot truncate or zero extend with non-integer arguments!");
2362   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2363     return V;  // No conversion
2364   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2365     return getTruncateExpr(V, Ty);
2366   return getZeroExtendExpr(V, Ty);
2367 }
2368 
2369 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2370 /// input value to the specified type.  If the type must be extended, it is sign
2371 /// extended.
2372 const SCEV *
2373 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2374                                          const Type *Ty) {
2375   const Type *SrcTy = V->getType();
2376   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2377          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2378          "Cannot truncate or zero extend with non-integer arguments!");
2379   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2380     return V;  // No conversion
2381   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2382     return getTruncateExpr(V, Ty);
2383   return getSignExtendExpr(V, Ty);
2384 }
2385 
2386 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2387 /// input value to the specified type.  If the type must be extended, it is zero
2388 /// extended.  The conversion must not be narrowing.
2389 const SCEV *
2390 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2391   const Type *SrcTy = V->getType();
2392   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2393          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2394          "Cannot noop or zero extend with non-integer arguments!");
2395   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2396          "getNoopOrZeroExtend cannot truncate!");
2397   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2398     return V;  // No conversion
2399   return getZeroExtendExpr(V, Ty);
2400 }
2401 
2402 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2403 /// input value to the specified type.  If the type must be extended, it is sign
2404 /// extended.  The conversion must not be narrowing.
2405 const SCEV *
2406 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2407   const Type *SrcTy = V->getType();
2408   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2409          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2410          "Cannot noop or sign extend with non-integer arguments!");
2411   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2412          "getNoopOrSignExtend cannot truncate!");
2413   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2414     return V;  // No conversion
2415   return getSignExtendExpr(V, Ty);
2416 }
2417 
2418 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2419 /// the input value to the specified type. If the type must be extended,
2420 /// it is extended with unspecified bits. The conversion must not be
2421 /// narrowing.
2422 const SCEV *
2423 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2424   const Type *SrcTy = V->getType();
2425   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2426          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2427          "Cannot noop or any extend with non-integer arguments!");
2428   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2429          "getNoopOrAnyExtend cannot truncate!");
2430   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2431     return V;  // No conversion
2432   return getAnyExtendExpr(V, Ty);
2433 }
2434 
2435 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2436 /// input value to the specified type.  The conversion must not be widening.
2437 const SCEV *
2438 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2439   const Type *SrcTy = V->getType();
2440   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2441          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2442          "Cannot truncate or noop with non-integer arguments!");
2443   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2444          "getTruncateOrNoop cannot extend!");
2445   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2446     return V;  // No conversion
2447   return getTruncateExpr(V, Ty);
2448 }
2449 
2450 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2451 /// the types using zero-extension, and then perform a umax operation
2452 /// with them.
2453 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2454                                                         const SCEV *RHS) {
2455   const SCEV *PromotedLHS = LHS;
2456   const SCEV *PromotedRHS = RHS;
2457 
2458   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2459     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2460   else
2461     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2462 
2463   return getUMaxExpr(PromotedLHS, PromotedRHS);
2464 }
2465 
2466 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2467 /// the types using zero-extension, and then perform a umin operation
2468 /// with them.
2469 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2470                                                         const SCEV *RHS) {
2471   const SCEV *PromotedLHS = LHS;
2472   const SCEV *PromotedRHS = RHS;
2473 
2474   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2475     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2476   else
2477     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2478 
2479   return getUMinExpr(PromotedLHS, PromotedRHS);
2480 }
2481 
2482 /// PushDefUseChildren - Push users of the given Instruction
2483 /// onto the given Worklist.
2484 static void
2485 PushDefUseChildren(Instruction *I,
2486                    SmallVectorImpl<Instruction *> &Worklist) {
2487   // Push the def-use children onto the Worklist stack.
2488   for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2489        UI != UE; ++UI)
2490     Worklist.push_back(cast<Instruction>(UI));
2491 }
2492 
2493 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2494 /// instructions that depend on the given instruction and removes them from
2495 /// the Scalars map if they reference SymName. This is used during PHI
2496 /// resolution.
2497 void
2498 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2499   SmallVector<Instruction *, 16> Worklist;
2500   PushDefUseChildren(PN, Worklist);
2501 
2502   SmallPtrSet<Instruction *, 8> Visited;
2503   Visited.insert(PN);
2504   while (!Worklist.empty()) {
2505     Instruction *I = Worklist.pop_back_val();
2506     if (!Visited.insert(I)) continue;
2507 
2508     std::map<SCEVCallbackVH, const SCEV *>::iterator It =
2509       Scalars.find(static_cast<Value *>(I));
2510     if (It != Scalars.end()) {
2511       // Short-circuit the def-use traversal if the symbolic name
2512       // ceases to appear in expressions.
2513       if (It->second != SymName && !It->second->hasOperand(SymName))
2514         continue;
2515 
2516       // SCEVUnknown for a PHI either means that it has an unrecognized
2517       // structure, it's a PHI that's in the progress of being computed
2518       // by createNodeForPHI, or it's a single-value PHI. In the first case,
2519       // additional loop trip count information isn't going to change anything.
2520       // In the second case, createNodeForPHI will perform the necessary
2521       // updates on its own when it gets to that point. In the third, we do
2522       // want to forget the SCEVUnknown.
2523       if (!isa<PHINode>(I) ||
2524           !isa<SCEVUnknown>(It->second) ||
2525           (I != PN && It->second == SymName)) {
2526         ValuesAtScopes.erase(It->second);
2527         Scalars.erase(It);
2528       }
2529     }
2530 
2531     PushDefUseChildren(I, Worklist);
2532   }
2533 }
2534 
2535 /// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
2536 /// a loop header, making it a potential recurrence, or it doesn't.
2537 ///
2538 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2539   if (const Loop *L = LI->getLoopFor(PN->getParent()))
2540     if (L->getHeader() == PN->getParent()) {
2541       // The loop may have multiple entrances or multiple exits; we can analyze
2542       // this phi as an addrec if it has a unique entry value and a unique
2543       // backedge value.
2544       Value *BEValueV = 0, *StartValueV = 0;
2545       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2546         Value *V = PN->getIncomingValue(i);
2547         if (L->contains(PN->getIncomingBlock(i))) {
2548           if (!BEValueV) {
2549             BEValueV = V;
2550           } else if (BEValueV != V) {
2551             BEValueV = 0;
2552             break;
2553           }
2554         } else if (!StartValueV) {
2555           StartValueV = V;
2556         } else if (StartValueV != V) {
2557           StartValueV = 0;
2558           break;
2559         }
2560       }
2561       if (BEValueV && StartValueV) {
2562         // While we are analyzing this PHI node, handle its value symbolically.
2563         const SCEV *SymbolicName = getUnknown(PN);
2564         assert(Scalars.find(PN) == Scalars.end() &&
2565                "PHI node already processed?");
2566         Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2567 
2568         // Using this symbolic name for the PHI, analyze the value coming around
2569         // the back-edge.
2570         const SCEV *BEValue = getSCEV(BEValueV);
2571 
2572         // NOTE: If BEValue is loop invariant, we know that the PHI node just
2573         // has a special value for the first iteration of the loop.
2574 
2575         // If the value coming around the backedge is an add with the symbolic
2576         // value we just inserted, then we found a simple induction variable!
2577         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2578           // If there is a single occurrence of the symbolic value, replace it
2579           // with a recurrence.
2580           unsigned FoundIndex = Add->getNumOperands();
2581           for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2582             if (Add->getOperand(i) == SymbolicName)
2583               if (FoundIndex == e) {
2584                 FoundIndex = i;
2585                 break;
2586               }
2587 
2588           if (FoundIndex != Add->getNumOperands()) {
2589             // Create an add with everything but the specified operand.
2590             SmallVector<const SCEV *, 8> Ops;
2591             for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2592               if (i != FoundIndex)
2593                 Ops.push_back(Add->getOperand(i));
2594             const SCEV *Accum = getAddExpr(Ops);
2595 
2596             // This is not a valid addrec if the step amount is varying each
2597             // loop iteration, but is not itself an addrec in this loop.
2598             if (Accum->isLoopInvariant(L) ||
2599                 (isa<SCEVAddRecExpr>(Accum) &&
2600                  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2601               bool HasNUW = false;
2602               bool HasNSW = false;
2603 
2604               // If the increment doesn't overflow, then neither the addrec nor
2605               // the post-increment will overflow.
2606               if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2607                 if (OBO->hasNoUnsignedWrap())
2608                   HasNUW = true;
2609                 if (OBO->hasNoSignedWrap())
2610                   HasNSW = true;
2611               }
2612 
2613               const SCEV *StartVal = getSCEV(StartValueV);
2614               const SCEV *PHISCEV =
2615                 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
2616 
2617               // Since the no-wrap flags are on the increment, they apply to the
2618               // post-incremented value as well.
2619               if (Accum->isLoopInvariant(L))
2620                 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2621                                     Accum, L, HasNUW, HasNSW);
2622 
2623               // Okay, for the entire analysis of this edge we assumed the PHI
2624               // to be symbolic.  We now need to go back and purge all of the
2625               // entries for the scalars that use the symbolic expression.
2626               ForgetSymbolicName(PN, SymbolicName);
2627               Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2628               return PHISCEV;
2629             }
2630           }
2631         } else if (const SCEVAddRecExpr *AddRec =
2632                      dyn_cast<SCEVAddRecExpr>(BEValue)) {
2633           // Otherwise, this could be a loop like this:
2634           //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
2635           // In this case, j = {1,+,1}  and BEValue is j.
2636           // Because the other in-value of i (0) fits the evolution of BEValue
2637           // i really is an addrec evolution.
2638           if (AddRec->getLoop() == L && AddRec->isAffine()) {
2639             const SCEV *StartVal = getSCEV(StartValueV);
2640 
2641             // If StartVal = j.start - j.stride, we can use StartVal as the
2642             // initial step of the addrec evolution.
2643             if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2644                                          AddRec->getOperand(1))) {
2645               const SCEV *PHISCEV =
2646                  getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2647 
2648               // Okay, for the entire analysis of this edge we assumed the PHI
2649               // to be symbolic.  We now need to go back and purge all of the
2650               // entries for the scalars that use the symbolic expression.
2651               ForgetSymbolicName(PN, SymbolicName);
2652               Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2653               return PHISCEV;
2654             }
2655           }
2656         }
2657       }
2658     }
2659 
2660   // If the PHI has a single incoming value, follow that value, unless the
2661   // PHI's incoming blocks are in a different loop, in which case doing so
2662   // risks breaking LCSSA form. Instcombine would normally zap these, but
2663   // it doesn't have DominatorTree information, so it may miss cases.
2664   if (Value *V = PN->hasConstantValue(DT)) {
2665     bool AllSameLoop = true;
2666     Loop *PNLoop = LI->getLoopFor(PN->getParent());
2667     for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2668       if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2669         AllSameLoop = false;
2670         break;
2671       }
2672     if (AllSameLoop)
2673       return getSCEV(V);
2674   }
2675 
2676   // If it's not a loop phi, we can't handle it yet.
2677   return getUnknown(PN);
2678 }
2679 
2680 /// createNodeForGEP - Expand GEP instructions into add and multiply
2681 /// operations. This allows them to be analyzed by regular SCEV code.
2682 ///
2683 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2684 
2685   bool InBounds = GEP->isInBounds();
2686   const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2687   Value *Base = GEP->getOperand(0);
2688   // Don't attempt to analyze GEPs over unsized objects.
2689   if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2690     return getUnknown(GEP);
2691   const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
2692   gep_type_iterator GTI = gep_type_begin(GEP);
2693   for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2694                                       E = GEP->op_end();
2695        I != E; ++I) {
2696     Value *Index = *I;
2697     // Compute the (potentially symbolic) offset in bytes for this index.
2698     if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2699       // For a struct, add the member offset.
2700       unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2701       TotalOffset = getAddExpr(TotalOffset,
2702                                getOffsetOfExpr(STy, FieldNo),
2703                                /*HasNUW=*/false, /*HasNSW=*/InBounds);
2704     } else {
2705       // For an array, add the element offset, explicitly scaled.
2706       const SCEV *LocalOffset = getSCEV(Index);
2707       // Getelementptr indices are signed.
2708       LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
2709       // Lower "inbounds" GEPs to NSW arithmetic.
2710       LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
2711                                /*HasNUW=*/false, /*HasNSW=*/InBounds);
2712       TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2713                                /*HasNUW=*/false, /*HasNSW=*/InBounds);
2714     }
2715   }
2716   return getAddExpr(getSCEV(Base), TotalOffset,
2717                     /*HasNUW=*/false, /*HasNSW=*/InBounds);
2718 }
2719 
2720 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2721 /// guaranteed to end in (at every loop iteration).  It is, at the same time,
2722 /// the minimum number of times S is divisible by 2.  For example, given {4,+,8}
2723 /// it returns 2.  If S is guaranteed to be 0, it returns the bitwidth of S.
2724 uint32_t
2725 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2726   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2727     return C->getValue()->getValue().countTrailingZeros();
2728 
2729   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2730     return std::min(GetMinTrailingZeros(T->getOperand()),
2731                     (uint32_t)getTypeSizeInBits(T->getType()));
2732 
2733   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2734     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2735     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2736              getTypeSizeInBits(E->getType()) : OpRes;
2737   }
2738 
2739   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2740     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2741     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2742              getTypeSizeInBits(E->getType()) : OpRes;
2743   }
2744 
2745   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2746     // The result is the min of all operands results.
2747     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2748     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2749       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2750     return MinOpRes;
2751   }
2752 
2753   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2754     // The result is the sum of all operands results.
2755     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2756     uint32_t BitWidth = getTypeSizeInBits(M->getType());
2757     for (unsigned i = 1, e = M->getNumOperands();
2758          SumOpRes != BitWidth && i != e; ++i)
2759       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2760                           BitWidth);
2761     return SumOpRes;
2762   }
2763 
2764   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2765     // The result is the min of all operands results.
2766     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2767     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2768       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2769     return MinOpRes;
2770   }
2771 
2772   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2773     // The result is the min of all operands results.
2774     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2775     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2776       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2777     return MinOpRes;
2778   }
2779 
2780   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2781     // The result is the min of all operands results.
2782     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2783     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2784       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2785     return MinOpRes;
2786   }
2787 
2788   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2789     // For a SCEVUnknown, ask ValueTracking.
2790     unsigned BitWidth = getTypeSizeInBits(U->getType());
2791     APInt Mask = APInt::getAllOnesValue(BitWidth);
2792     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2793     ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2794     return Zeros.countTrailingOnes();
2795   }
2796 
2797   // SCEVUDivExpr
2798   return 0;
2799 }
2800 
2801 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2802 ///
2803 ConstantRange
2804 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2805 
2806   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2807     return ConstantRange(C->getValue()->getValue());
2808 
2809   unsigned BitWidth = getTypeSizeInBits(S->getType());
2810   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2811 
2812   // If the value has known zeros, the maximum unsigned value will have those
2813   // known zeros as well.
2814   uint32_t TZ = GetMinTrailingZeros(S);
2815   if (TZ != 0)
2816     ConservativeResult =
2817       ConstantRange(APInt::getMinValue(BitWidth),
2818                     APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2819 
2820   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2821     ConstantRange X = getUnsignedRange(Add->getOperand(0));
2822     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2823       X = X.add(getUnsignedRange(Add->getOperand(i)));
2824     return ConservativeResult.intersectWith(X);
2825   }
2826 
2827   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2828     ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2829     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2830       X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2831     return ConservativeResult.intersectWith(X);
2832   }
2833 
2834   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2835     ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2836     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2837       X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2838     return ConservativeResult.intersectWith(X);
2839   }
2840 
2841   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2842     ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2843     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2844       X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2845     return ConservativeResult.intersectWith(X);
2846   }
2847 
2848   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2849     ConstantRange X = getUnsignedRange(UDiv->getLHS());
2850     ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2851     return ConservativeResult.intersectWith(X.udiv(Y));
2852   }
2853 
2854   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2855     ConstantRange X = getUnsignedRange(ZExt->getOperand());
2856     return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
2857   }
2858 
2859   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2860     ConstantRange X = getUnsignedRange(SExt->getOperand());
2861     return ConservativeResult.intersectWith(X.signExtend(BitWidth));
2862   }
2863 
2864   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2865     ConstantRange X = getUnsignedRange(Trunc->getOperand());
2866     return ConservativeResult.intersectWith(X.truncate(BitWidth));
2867   }
2868 
2869   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2870     // If there's no unsigned wrap, the value will never be less than its
2871     // initial value.
2872     if (AddRec->hasNoUnsignedWrap())
2873       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2874         if (!C->getValue()->isZero())
2875           ConservativeResult =
2876             ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0));
2877 
2878     // TODO: non-affine addrec
2879     if (AddRec->isAffine()) {
2880       const Type *Ty = AddRec->getType();
2881       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2882       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2883           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
2884         MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2885 
2886         const SCEV *Start = AddRec->getStart();
2887         const SCEV *Step = AddRec->getStepRecurrence(*this);
2888 
2889         ConstantRange StartRange = getUnsignedRange(Start);
2890         ConstantRange StepRange = getSignedRange(Step);
2891         ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
2892         ConstantRange EndRange =
2893           StartRange.add(MaxBECountRange.multiply(StepRange));
2894 
2895         // Check for overflow. This must be done with ConstantRange arithmetic
2896         // because we could be called from within the ScalarEvolution overflow
2897         // checking code.
2898         ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
2899         ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
2900         ConstantRange ExtMaxBECountRange =
2901           MaxBECountRange.zextOrTrunc(BitWidth*2+1);
2902         ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
2903         if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
2904             ExtEndRange)
2905           return ConservativeResult;
2906 
2907         APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2908                                    EndRange.getUnsignedMin());
2909         APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2910                                    EndRange.getUnsignedMax());
2911         if (Min.isMinValue() && Max.isMaxValue())
2912           return ConservativeResult;
2913         return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
2914       }
2915     }
2916 
2917     return ConservativeResult;
2918   }
2919 
2920   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2921     // For a SCEVUnknown, ask ValueTracking.
2922     APInt Mask = APInt::getAllOnesValue(BitWidth);
2923     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2924     ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2925     if (Ones == ~Zeros + 1)
2926       return ConservativeResult;
2927     return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
2928   }
2929 
2930   return ConservativeResult;
2931 }
2932 
2933 /// getSignedRange - Determine the signed range for a particular SCEV.
2934 ///
2935 ConstantRange
2936 ScalarEvolution::getSignedRange(const SCEV *S) {
2937 
2938   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2939     return ConstantRange(C->getValue()->getValue());
2940 
2941   unsigned BitWidth = getTypeSizeInBits(S->getType());
2942   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2943 
2944   // If the value has known zeros, the maximum signed value will have those
2945   // known zeros as well.
2946   uint32_t TZ = GetMinTrailingZeros(S);
2947   if (TZ != 0)
2948     ConservativeResult =
2949       ConstantRange(APInt::getSignedMinValue(BitWidth),
2950                     APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2951 
2952   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2953     ConstantRange X = getSignedRange(Add->getOperand(0));
2954     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2955       X = X.add(getSignedRange(Add->getOperand(i)));
2956     return ConservativeResult.intersectWith(X);
2957   }
2958 
2959   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2960     ConstantRange X = getSignedRange(Mul->getOperand(0));
2961     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2962       X = X.multiply(getSignedRange(Mul->getOperand(i)));
2963     return ConservativeResult.intersectWith(X);
2964   }
2965 
2966   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2967     ConstantRange X = getSignedRange(SMax->getOperand(0));
2968     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2969       X = X.smax(getSignedRange(SMax->getOperand(i)));
2970     return ConservativeResult.intersectWith(X);
2971   }
2972 
2973   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2974     ConstantRange X = getSignedRange(UMax->getOperand(0));
2975     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2976       X = X.umax(getSignedRange(UMax->getOperand(i)));
2977     return ConservativeResult.intersectWith(X);
2978   }
2979 
2980   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2981     ConstantRange X = getSignedRange(UDiv->getLHS());
2982     ConstantRange Y = getSignedRange(UDiv->getRHS());
2983     return ConservativeResult.intersectWith(X.udiv(Y));
2984   }
2985 
2986   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2987     ConstantRange X = getSignedRange(ZExt->getOperand());
2988     return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
2989   }
2990 
2991   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2992     ConstantRange X = getSignedRange(SExt->getOperand());
2993     return ConservativeResult.intersectWith(X.signExtend(BitWidth));
2994   }
2995 
2996   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2997     ConstantRange X = getSignedRange(Trunc->getOperand());
2998     return ConservativeResult.intersectWith(X.truncate(BitWidth));
2999   }
3000 
3001   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3002     // If there's no signed wrap, and all the operands have the same sign or
3003     // zero, the value won't ever change sign.
3004     if (AddRec->hasNoSignedWrap()) {
3005       bool AllNonNeg = true;
3006       bool AllNonPos = true;
3007       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3008         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3009         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3010       }
3011       if (AllNonNeg)
3012         ConservativeResult = ConservativeResult.intersectWith(
3013           ConstantRange(APInt(BitWidth, 0),
3014                         APInt::getSignedMinValue(BitWidth)));
3015       else if (AllNonPos)
3016         ConservativeResult = ConservativeResult.intersectWith(
3017           ConstantRange(APInt::getSignedMinValue(BitWidth),
3018                         APInt(BitWidth, 1)));
3019     }
3020 
3021     // TODO: non-affine addrec
3022     if (AddRec->isAffine()) {
3023       const Type *Ty = AddRec->getType();
3024       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3025       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3026           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3027         MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3028 
3029         const SCEV *Start = AddRec->getStart();
3030         const SCEV *Step = AddRec->getStepRecurrence(*this);
3031 
3032         ConstantRange StartRange = getSignedRange(Start);
3033         ConstantRange StepRange = getSignedRange(Step);
3034         ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3035         ConstantRange EndRange =
3036           StartRange.add(MaxBECountRange.multiply(StepRange));
3037 
3038         // Check for overflow. This must be done with ConstantRange arithmetic
3039         // because we could be called from within the ScalarEvolution overflow
3040         // checking code.
3041         ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3042         ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3043         ConstantRange ExtMaxBECountRange =
3044           MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3045         ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3046         if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3047             ExtEndRange)
3048           return ConservativeResult;
3049 
3050         APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3051                                    EndRange.getSignedMin());
3052         APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3053                                    EndRange.getSignedMax());
3054         if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3055           return ConservativeResult;
3056         return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3057       }
3058     }
3059 
3060     return ConservativeResult;
3061   }
3062 
3063   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3064     // For a SCEVUnknown, ask ValueTracking.
3065     if (!U->getValue()->getType()->isIntegerTy() && !TD)
3066       return ConservativeResult;
3067     unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3068     if (NS == 1)
3069       return ConservativeResult;
3070     return ConservativeResult.intersectWith(
3071       ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3072                     APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
3073   }
3074 
3075   return ConservativeResult;
3076 }
3077 
3078 /// createSCEV - We know that there is no SCEV for the specified value.
3079 /// Analyze the expression.
3080 ///
3081 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3082   if (!isSCEVable(V->getType()))
3083     return getUnknown(V);
3084 
3085   unsigned Opcode = Instruction::UserOp1;
3086   if (Instruction *I = dyn_cast<Instruction>(V)) {
3087     Opcode = I->getOpcode();
3088 
3089     // Don't attempt to analyze instructions in blocks that aren't
3090     // reachable. Such instructions don't matter, and they aren't required
3091     // to obey basic rules for definitions dominating uses which this
3092     // analysis depends on.
3093     if (!DT->isReachableFromEntry(I->getParent()))
3094       return getUnknown(V);
3095   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3096     Opcode = CE->getOpcode();
3097   else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3098     return getConstant(CI);
3099   else if (isa<ConstantPointerNull>(V))
3100     return getConstant(V->getType(), 0);
3101   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3102     return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3103   else
3104     return getUnknown(V);
3105 
3106   Operator *U = cast<Operator>(V);
3107   switch (Opcode) {
3108   case Instruction::Add:
3109     // Don't transfer the NSW and NUW bits from the Add instruction to the
3110     // Add expression, because the Instruction may be guarded by control
3111     // flow and the no-overflow bits may not be valid for the expression in
3112     // any context.
3113     return getAddExpr(getSCEV(U->getOperand(0)),
3114                       getSCEV(U->getOperand(1)));
3115   case Instruction::Mul:
3116     // Don't transfer the NSW and NUW bits from the Mul instruction to the
3117     // Mul expression, as with Add.
3118     return getMulExpr(getSCEV(U->getOperand(0)),
3119                       getSCEV(U->getOperand(1)));
3120   case Instruction::UDiv:
3121     return getUDivExpr(getSCEV(U->getOperand(0)),
3122                        getSCEV(U->getOperand(1)));
3123   case Instruction::Sub:
3124     return getMinusSCEV(getSCEV(U->getOperand(0)),
3125                         getSCEV(U->getOperand(1)));
3126   case Instruction::And:
3127     // For an expression like x&255 that merely masks off the high bits,
3128     // use zext(trunc(x)) as the SCEV expression.
3129     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3130       if (CI->isNullValue())
3131         return getSCEV(U->getOperand(1));
3132       if (CI->isAllOnesValue())
3133         return getSCEV(U->getOperand(0));
3134       const APInt &A = CI->getValue();
3135 
3136       // Instcombine's ShrinkDemandedConstant may strip bits out of
3137       // constants, obscuring what would otherwise be a low-bits mask.
3138       // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3139       // knew about to reconstruct a low-bits mask value.
3140       unsigned LZ = A.countLeadingZeros();
3141       unsigned BitWidth = A.getBitWidth();
3142       APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3143       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3144       ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3145 
3146       APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3147 
3148       if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3149         return
3150           getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3151                                 IntegerType::get(getContext(), BitWidth - LZ)),
3152                             U->getType());
3153     }
3154     break;
3155 
3156   case Instruction::Or:
3157     // If the RHS of the Or is a constant, we may have something like:
3158     // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
3159     // optimizations will transparently handle this case.
3160     //
3161     // In order for this transformation to be safe, the LHS must be of the
3162     // form X*(2^n) and the Or constant must be less than 2^n.
3163     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3164       const SCEV *LHS = getSCEV(U->getOperand(0));
3165       const APInt &CIVal = CI->getValue();
3166       if (GetMinTrailingZeros(LHS) >=
3167           (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3168         // Build a plain add SCEV.
3169         const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3170         // If the LHS of the add was an addrec and it has no-wrap flags,
3171         // transfer the no-wrap flags, since an or won't introduce a wrap.
3172         if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3173           const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3174           if (OldAR->hasNoUnsignedWrap())
3175             const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3176           if (OldAR->hasNoSignedWrap())
3177             const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3178         }
3179         return S;
3180       }
3181     }
3182     break;
3183   case Instruction::Xor:
3184     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3185       // If the RHS of the xor is a signbit, then this is just an add.
3186       // Instcombine turns add of signbit into xor as a strength reduction step.
3187       if (CI->getValue().isSignBit())
3188         return getAddExpr(getSCEV(U->getOperand(0)),
3189                           getSCEV(U->getOperand(1)));
3190 
3191       // If the RHS of xor is -1, then this is a not operation.
3192       if (CI->isAllOnesValue())
3193         return getNotSCEV(getSCEV(U->getOperand(0)));
3194 
3195       // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3196       // This is a variant of the check for xor with -1, and it handles
3197       // the case where instcombine has trimmed non-demanded bits out
3198       // of an xor with -1.
3199       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3200         if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3201           if (BO->getOpcode() == Instruction::And &&
3202               LCI->getValue() == CI->getValue())
3203             if (const SCEVZeroExtendExpr *Z =
3204                   dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3205               const Type *UTy = U->getType();
3206               const SCEV *Z0 = Z->getOperand();
3207               const Type *Z0Ty = Z0->getType();
3208               unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3209 
3210               // If C is a low-bits mask, the zero extend is serving to
3211               // mask off the high bits. Complement the operand and
3212               // re-apply the zext.
3213               if (APIntOps::isMask(Z0TySize, CI->getValue()))
3214                 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3215 
3216               // If C is a single bit, it may be in the sign-bit position
3217               // before the zero-extend. In this case, represent the xor
3218               // using an add, which is equivalent, and re-apply the zext.
3219               APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3220               if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3221                   Trunc.isSignBit())
3222                 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3223                                          UTy);
3224             }
3225     }
3226     break;
3227 
3228   case Instruction::Shl:
3229     // Turn shift left of a constant amount into a multiply.
3230     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3231       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3232 
3233       // If the shift count is not less than the bitwidth, the result of
3234       // the shift is undefined. Don't try to analyze it, because the
3235       // resolution chosen here may differ from the resolution chosen in
3236       // other parts of the compiler.
3237       if (SA->getValue().uge(BitWidth))
3238         break;
3239 
3240       Constant *X = ConstantInt::get(getContext(),
3241         APInt(BitWidth, 1).shl(SA->getZExtValue()));
3242       return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3243     }
3244     break;
3245 
3246   case Instruction::LShr:
3247     // Turn logical shift right of a constant into a unsigned divide.
3248     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3249       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3250 
3251       // If the shift count is not less than the bitwidth, the result of
3252       // the shift is undefined. Don't try to analyze it, because the
3253       // resolution chosen here may differ from the resolution chosen in
3254       // other parts of the compiler.
3255       if (SA->getValue().uge(BitWidth))
3256         break;
3257 
3258       Constant *X = ConstantInt::get(getContext(),
3259         APInt(BitWidth, 1).shl(SA->getZExtValue()));
3260       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3261     }
3262     break;
3263 
3264   case Instruction::AShr:
3265     // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3266     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3267       if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3268         if (L->getOpcode() == Instruction::Shl &&
3269             L->getOperand(1) == U->getOperand(1)) {
3270           uint64_t BitWidth = getTypeSizeInBits(U->getType());
3271 
3272           // If the shift count is not less than the bitwidth, the result of
3273           // the shift is undefined. Don't try to analyze it, because the
3274           // resolution chosen here may differ from the resolution chosen in
3275           // other parts of the compiler.
3276           if (CI->getValue().uge(BitWidth))
3277             break;
3278 
3279           uint64_t Amt = BitWidth - CI->getZExtValue();
3280           if (Amt == BitWidth)
3281             return getSCEV(L->getOperand(0));       // shift by zero --> noop
3282           return
3283             getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3284                                               IntegerType::get(getContext(),
3285                                                                Amt)),
3286                               U->getType());
3287         }
3288     break;
3289 
3290   case Instruction::Trunc:
3291     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3292 
3293   case Instruction::ZExt:
3294     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3295 
3296   case Instruction::SExt:
3297     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3298 
3299   case Instruction::BitCast:
3300     // BitCasts are no-op casts so we just eliminate the cast.
3301     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3302       return getSCEV(U->getOperand(0));
3303     break;
3304 
3305   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3306   // lead to pointer expressions which cannot safely be expanded to GEPs,
3307   // because ScalarEvolution doesn't respect the GEP aliasing rules when
3308   // simplifying integer expressions.
3309 
3310   case Instruction::GetElementPtr:
3311     return createNodeForGEP(cast<GEPOperator>(U));
3312 
3313   case Instruction::PHI:
3314     return createNodeForPHI(cast<PHINode>(U));
3315 
3316   case Instruction::Select:
3317     // This could be a smax or umax that was lowered earlier.
3318     // Try to recover it.
3319     if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3320       Value *LHS = ICI->getOperand(0);
3321       Value *RHS = ICI->getOperand(1);
3322       switch (ICI->getPredicate()) {
3323       case ICmpInst::ICMP_SLT:
3324       case ICmpInst::ICMP_SLE:
3325         std::swap(LHS, RHS);
3326         // fall through
3327       case ICmpInst::ICMP_SGT:
3328       case ICmpInst::ICMP_SGE:
3329         // a >s b ? a+x : b+x  ->  smax(a, b)+x
3330         // a >s b ? b+x : a+x  ->  smin(a, b)+x
3331         if (LHS->getType() == U->getType()) {
3332           const SCEV *LS = getSCEV(LHS);
3333           const SCEV *RS = getSCEV(RHS);
3334           const SCEV *LA = getSCEV(U->getOperand(1));
3335           const SCEV *RA = getSCEV(U->getOperand(2));
3336           const SCEV *LDiff = getMinusSCEV(LA, LS);
3337           const SCEV *RDiff = getMinusSCEV(RA, RS);
3338           if (LDiff == RDiff)
3339             return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3340           LDiff = getMinusSCEV(LA, RS);
3341           RDiff = getMinusSCEV(RA, LS);
3342           if (LDiff == RDiff)
3343             return getAddExpr(getSMinExpr(LS, RS), LDiff);
3344         }
3345         break;
3346       case ICmpInst::ICMP_ULT:
3347       case ICmpInst::ICMP_ULE:
3348         std::swap(LHS, RHS);
3349         // fall through
3350       case ICmpInst::ICMP_UGT:
3351       case ICmpInst::ICMP_UGE:
3352         // a >u b ? a+x : b+x  ->  umax(a, b)+x
3353         // a >u b ? b+x : a+x  ->  umin(a, b)+x
3354         if (LHS->getType() == U->getType()) {
3355           const SCEV *LS = getSCEV(LHS);
3356           const SCEV *RS = getSCEV(RHS);
3357           const SCEV *LA = getSCEV(U->getOperand(1));
3358           const SCEV *RA = getSCEV(U->getOperand(2));
3359           const SCEV *LDiff = getMinusSCEV(LA, LS);
3360           const SCEV *RDiff = getMinusSCEV(RA, RS);
3361           if (LDiff == RDiff)
3362             return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3363           LDiff = getMinusSCEV(LA, RS);
3364           RDiff = getMinusSCEV(RA, LS);
3365           if (LDiff == RDiff)
3366             return getAddExpr(getUMinExpr(LS, RS), LDiff);
3367         }
3368         break;
3369       case ICmpInst::ICMP_NE:
3370         // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
3371         if (LHS->getType() == U->getType() &&
3372             isa<ConstantInt>(RHS) &&
3373             cast<ConstantInt>(RHS)->isZero()) {
3374           const SCEV *One = getConstant(LHS->getType(), 1);
3375           const SCEV *LS = getSCEV(LHS);
3376           const SCEV *LA = getSCEV(U->getOperand(1));
3377           const SCEV *RA = getSCEV(U->getOperand(2));
3378           const SCEV *LDiff = getMinusSCEV(LA, LS);
3379           const SCEV *RDiff = getMinusSCEV(RA, One);
3380           if (LDiff == RDiff)
3381             return getAddExpr(getUMaxExpr(LS, One), LDiff);
3382         }
3383         break;
3384       case ICmpInst::ICMP_EQ:
3385         // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
3386         if (LHS->getType() == U->getType() &&
3387             isa<ConstantInt>(RHS) &&
3388             cast<ConstantInt>(RHS)->isZero()) {
3389           const SCEV *One = getConstant(LHS->getType(), 1);
3390           const SCEV *LS = getSCEV(LHS);
3391           const SCEV *LA = getSCEV(U->getOperand(1));
3392           const SCEV *RA = getSCEV(U->getOperand(2));
3393           const SCEV *LDiff = getMinusSCEV(LA, One);
3394           const SCEV *RDiff = getMinusSCEV(RA, LS);
3395           if (LDiff == RDiff)
3396             return getAddExpr(getUMaxExpr(LS, One), LDiff);
3397         }
3398         break;
3399       default:
3400         break;
3401       }
3402     }
3403 
3404   default: // We cannot analyze this expression.
3405     break;
3406   }
3407 
3408   return getUnknown(V);
3409 }
3410 
3411 
3412 
3413 //===----------------------------------------------------------------------===//
3414 //                   Iteration Count Computation Code
3415 //
3416 
3417 /// getBackedgeTakenCount - If the specified loop has a predictable
3418 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3419 /// object. The backedge-taken count is the number of times the loop header
3420 /// will be branched to from within the loop. This is one less than the
3421 /// trip count of the loop, since it doesn't count the first iteration,
3422 /// when the header is branched to from outside the loop.
3423 ///
3424 /// Note that it is not valid to call this method on a loop without a
3425 /// loop-invariant backedge-taken count (see
3426 /// hasLoopInvariantBackedgeTakenCount).
3427 ///
3428 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3429   return getBackedgeTakenInfo(L).Exact;
3430 }
3431 
3432 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3433 /// return the least SCEV value that is known never to be less than the
3434 /// actual backedge taken count.
3435 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3436   return getBackedgeTakenInfo(L).Max;
3437 }
3438 
3439 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3440 /// onto the given Worklist.
3441 static void
3442 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3443   BasicBlock *Header = L->getHeader();
3444 
3445   // Push all Loop-header PHIs onto the Worklist stack.
3446   for (BasicBlock::iterator I = Header->begin();
3447        PHINode *PN = dyn_cast<PHINode>(I); ++I)
3448     Worklist.push_back(PN);
3449 }
3450 
3451 const ScalarEvolution::BackedgeTakenInfo &
3452 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3453   // Initially insert a CouldNotCompute for this loop. If the insertion
3454   // succeeds, proceed to actually compute a backedge-taken count and
3455   // update the value. The temporary CouldNotCompute value tells SCEV
3456   // code elsewhere that it shouldn't attempt to request a new
3457   // backedge-taken count, which could result in infinite recursion.
3458   std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3459     BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3460   if (Pair.second) {
3461     BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3462     if (BECount.Exact != getCouldNotCompute()) {
3463       assert(BECount.Exact->isLoopInvariant(L) &&
3464              BECount.Max->isLoopInvariant(L) &&
3465              "Computed backedge-taken count isn't loop invariant for loop!");
3466       ++NumTripCountsComputed;
3467 
3468       // Update the value in the map.
3469       Pair.first->second = BECount;
3470     } else {
3471       if (BECount.Max != getCouldNotCompute())
3472         // Update the value in the map.
3473         Pair.first->second = BECount;
3474       if (isa<PHINode>(L->getHeader()->begin()))
3475         // Only count loops that have phi nodes as not being computable.
3476         ++NumTripCountsNotComputed;
3477     }
3478 
3479     // Now that we know more about the trip count for this loop, forget any
3480     // existing SCEV values for PHI nodes in this loop since they are only
3481     // conservative estimates made without the benefit of trip count
3482     // information. This is similar to the code in forgetLoop, except that
3483     // it handles SCEVUnknown PHI nodes specially.
3484     if (BECount.hasAnyInfo()) {
3485       SmallVector<Instruction *, 16> Worklist;
3486       PushLoopPHIs(L, Worklist);
3487 
3488       SmallPtrSet<Instruction *, 8> Visited;
3489       while (!Worklist.empty()) {
3490         Instruction *I = Worklist.pop_back_val();
3491         if (!Visited.insert(I)) continue;
3492 
3493         std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3494           Scalars.find(static_cast<Value *>(I));
3495         if (It != Scalars.end()) {
3496           // SCEVUnknown for a PHI either means that it has an unrecognized
3497           // structure, or it's a PHI that's in the progress of being computed
3498           // by createNodeForPHI.  In the former case, additional loop trip
3499           // count information isn't going to change anything. In the later
3500           // case, createNodeForPHI will perform the necessary updates on its
3501           // own when it gets to that point.
3502           if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3503             ValuesAtScopes.erase(It->second);
3504             Scalars.erase(It);
3505           }
3506           if (PHINode *PN = dyn_cast<PHINode>(I))
3507             ConstantEvolutionLoopExitValue.erase(PN);
3508         }
3509 
3510         PushDefUseChildren(I, Worklist);
3511       }
3512     }
3513   }
3514   return Pair.first->second;
3515 }
3516 
3517 /// forgetLoop - This method should be called by the client when it has
3518 /// changed a loop in a way that may effect ScalarEvolution's ability to
3519 /// compute a trip count, or if the loop is deleted.
3520 void ScalarEvolution::forgetLoop(const Loop *L) {
3521   // Drop any stored trip count value.
3522   BackedgeTakenCounts.erase(L);
3523 
3524   // Drop information about expressions based on loop-header PHIs.
3525   SmallVector<Instruction *, 16> Worklist;
3526   PushLoopPHIs(L, Worklist);
3527 
3528   SmallPtrSet<Instruction *, 8> Visited;
3529   while (!Worklist.empty()) {
3530     Instruction *I = Worklist.pop_back_val();
3531     if (!Visited.insert(I)) continue;
3532 
3533     std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3534       Scalars.find(static_cast<Value *>(I));
3535     if (It != Scalars.end()) {
3536       ValuesAtScopes.erase(It->second);
3537       Scalars.erase(It);
3538       if (PHINode *PN = dyn_cast<PHINode>(I))
3539         ConstantEvolutionLoopExitValue.erase(PN);
3540     }
3541 
3542     PushDefUseChildren(I, Worklist);
3543   }
3544 }
3545 
3546 /// forgetValue - This method should be called by the client when it has
3547 /// changed a value in a way that may effect its value, or which may
3548 /// disconnect it from a def-use chain linking it to a loop.
3549 void ScalarEvolution::forgetValue(Value *V) {
3550   Instruction *I = dyn_cast<Instruction>(V);
3551   if (!I) return;
3552 
3553   // Drop information about expressions based on loop-header PHIs.
3554   SmallVector<Instruction *, 16> Worklist;
3555   Worklist.push_back(I);
3556 
3557   SmallPtrSet<Instruction *, 8> Visited;
3558   while (!Worklist.empty()) {
3559     I = Worklist.pop_back_val();
3560     if (!Visited.insert(I)) continue;
3561 
3562     std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3563       Scalars.find(static_cast<Value *>(I));
3564     if (It != Scalars.end()) {
3565       ValuesAtScopes.erase(It->second);
3566       Scalars.erase(It);
3567       if (PHINode *PN = dyn_cast<PHINode>(I))
3568         ConstantEvolutionLoopExitValue.erase(PN);
3569     }
3570 
3571     PushDefUseChildren(I, Worklist);
3572   }
3573 }
3574 
3575 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3576 /// of the specified loop will execute.
3577 ScalarEvolution::BackedgeTakenInfo
3578 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3579   SmallVector<BasicBlock *, 8> ExitingBlocks;
3580   L->getExitingBlocks(ExitingBlocks);
3581 
3582   // Examine all exits and pick the most conservative values.
3583   const SCEV *BECount = getCouldNotCompute();
3584   const SCEV *MaxBECount = getCouldNotCompute();
3585   bool CouldNotComputeBECount = false;
3586   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3587     BackedgeTakenInfo NewBTI =
3588       ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3589 
3590     if (NewBTI.Exact == getCouldNotCompute()) {
3591       // We couldn't compute an exact value for this exit, so
3592       // we won't be able to compute an exact value for the loop.
3593       CouldNotComputeBECount = true;
3594       BECount = getCouldNotCompute();
3595     } else if (!CouldNotComputeBECount) {
3596       if (BECount == getCouldNotCompute())
3597         BECount = NewBTI.Exact;
3598       else
3599         BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3600     }
3601     if (MaxBECount == getCouldNotCompute())
3602       MaxBECount = NewBTI.Max;
3603     else if (NewBTI.Max != getCouldNotCompute())
3604       MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3605   }
3606 
3607   return BackedgeTakenInfo(BECount, MaxBECount);
3608 }
3609 
3610 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3611 /// of the specified loop will execute if it exits via the specified block.
3612 ScalarEvolution::BackedgeTakenInfo
3613 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3614                                                    BasicBlock *ExitingBlock) {
3615 
3616   // Okay, we've chosen an exiting block.  See what condition causes us to
3617   // exit at this block.
3618   //
3619   // FIXME: we should be able to handle switch instructions (with a single exit)
3620   BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3621   if (ExitBr == 0) return getCouldNotCompute();
3622   assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3623 
3624   // At this point, we know we have a conditional branch that determines whether
3625   // the loop is exited.  However, we don't know if the branch is executed each
3626   // time through the loop.  If not, then the execution count of the branch will
3627   // not be equal to the trip count of the loop.
3628   //
3629   // Currently we check for this by checking to see if the Exit branch goes to
3630   // the loop header.  If so, we know it will always execute the same number of
3631   // times as the loop.  We also handle the case where the exit block *is* the
3632   // loop header.  This is common for un-rotated loops.
3633   //
3634   // If both of those tests fail, walk up the unique predecessor chain to the
3635   // header, stopping if there is an edge that doesn't exit the loop. If the
3636   // header is reached, the execution count of the branch will be equal to the
3637   // trip count of the loop.
3638   //
3639   //  More extensive analysis could be done to handle more cases here.
3640   //
3641   if (ExitBr->getSuccessor(0) != L->getHeader() &&
3642       ExitBr->getSuccessor(1) != L->getHeader() &&
3643       ExitBr->getParent() != L->getHeader()) {
3644     // The simple checks failed, try climbing the unique predecessor chain
3645     // up to the header.
3646     bool Ok = false;
3647     for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3648       BasicBlock *Pred = BB->getUniquePredecessor();
3649       if (!Pred)
3650         return getCouldNotCompute();
3651       TerminatorInst *PredTerm = Pred->getTerminator();
3652       for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3653         BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3654         if (PredSucc == BB)
3655           continue;
3656         // If the predecessor has a successor that isn't BB and isn't
3657         // outside the loop, assume the worst.
3658         if (L->contains(PredSucc))
3659           return getCouldNotCompute();
3660       }
3661       if (Pred == L->getHeader()) {
3662         Ok = true;
3663         break;
3664       }
3665       BB = Pred;
3666     }
3667     if (!Ok)
3668       return getCouldNotCompute();
3669   }
3670 
3671   // Proceed to the next level to examine the exit condition expression.
3672   return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3673                                                ExitBr->getSuccessor(0),
3674                                                ExitBr->getSuccessor(1));
3675 }
3676 
3677 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3678 /// backedge of the specified loop will execute if its exit condition
3679 /// were a conditional branch of ExitCond, TBB, and FBB.
3680 ScalarEvolution::BackedgeTakenInfo
3681 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3682                                                        Value *ExitCond,
3683                                                        BasicBlock *TBB,
3684                                                        BasicBlock *FBB) {
3685   // Check if the controlling expression for this loop is an And or Or.
3686   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3687     if (BO->getOpcode() == Instruction::And) {
3688       // Recurse on the operands of the and.
3689       BackedgeTakenInfo BTI0 =
3690         ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3691       BackedgeTakenInfo BTI1 =
3692         ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3693       const SCEV *BECount = getCouldNotCompute();
3694       const SCEV *MaxBECount = getCouldNotCompute();
3695       if (L->contains(TBB)) {
3696         // Both conditions must be true for the loop to continue executing.
3697         // Choose the less conservative count.
3698         if (BTI0.Exact == getCouldNotCompute() ||
3699             BTI1.Exact == getCouldNotCompute())
3700           BECount = getCouldNotCompute();
3701         else
3702           BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3703         if (BTI0.Max == getCouldNotCompute())
3704           MaxBECount = BTI1.Max;
3705         else if (BTI1.Max == getCouldNotCompute())
3706           MaxBECount = BTI0.Max;
3707         else
3708           MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3709       } else {
3710         // Both conditions must be true for the loop to exit.
3711         assert(L->contains(FBB) && "Loop block has no successor in loop!");
3712         if (BTI0.Exact != getCouldNotCompute() &&
3713             BTI1.Exact != getCouldNotCompute())
3714           BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3715         if (BTI0.Max != getCouldNotCompute() &&
3716             BTI1.Max != getCouldNotCompute())
3717           MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3718       }
3719 
3720       return BackedgeTakenInfo(BECount, MaxBECount);
3721     }
3722     if (BO->getOpcode() == Instruction::Or) {
3723       // Recurse on the operands of the or.
3724       BackedgeTakenInfo BTI0 =
3725         ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3726       BackedgeTakenInfo BTI1 =
3727         ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3728       const SCEV *BECount = getCouldNotCompute();
3729       const SCEV *MaxBECount = getCouldNotCompute();
3730       if (L->contains(FBB)) {
3731         // Both conditions must be false for the loop to continue executing.
3732         // Choose the less conservative count.
3733         if (BTI0.Exact == getCouldNotCompute() ||
3734             BTI1.Exact == getCouldNotCompute())
3735           BECount = getCouldNotCompute();
3736         else
3737           BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3738         if (BTI0.Max == getCouldNotCompute())
3739           MaxBECount = BTI1.Max;
3740         else if (BTI1.Max == getCouldNotCompute())
3741           MaxBECount = BTI0.Max;
3742         else
3743           MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3744       } else {
3745         // Both conditions must be false for the loop to exit.
3746         assert(L->contains(TBB) && "Loop block has no successor in loop!");
3747         if (BTI0.Exact != getCouldNotCompute() &&
3748             BTI1.Exact != getCouldNotCompute())
3749           BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3750         if (BTI0.Max != getCouldNotCompute() &&
3751             BTI1.Max != getCouldNotCompute())
3752           MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3753       }
3754 
3755       return BackedgeTakenInfo(BECount, MaxBECount);
3756     }
3757   }
3758 
3759   // With an icmp, it may be feasible to compute an exact backedge-taken count.
3760   // Proceed to the next level to examine the icmp.
3761   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3762     return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3763 
3764   // Check for a constant condition. These are normally stripped out by
3765   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3766   // preserve the CFG and is temporarily leaving constant conditions
3767   // in place.
3768   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3769     if (L->contains(FBB) == !CI->getZExtValue())
3770       // The backedge is always taken.
3771       return getCouldNotCompute();
3772     else
3773       // The backedge is never taken.
3774       return getConstant(CI->getType(), 0);
3775   }
3776 
3777   // If it's not an integer or pointer comparison then compute it the hard way.
3778   return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3779 }
3780 
3781 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3782 /// backedge of the specified loop will execute if its exit condition
3783 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3784 ScalarEvolution::BackedgeTakenInfo
3785 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3786                                                            ICmpInst *ExitCond,
3787                                                            BasicBlock *TBB,
3788                                                            BasicBlock *FBB) {
3789 
3790   // If the condition was exit on true, convert the condition to exit on false
3791   ICmpInst::Predicate Cond;
3792   if (!L->contains(FBB))
3793     Cond = ExitCond->getPredicate();
3794   else
3795     Cond = ExitCond->getInversePredicate();
3796 
3797   // Handle common loops like: for (X = "string"; *X; ++X)
3798   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3799     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3800       BackedgeTakenInfo ItCnt =
3801         ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3802       if (ItCnt.hasAnyInfo())
3803         return ItCnt;
3804     }
3805 
3806   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3807   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3808 
3809   // Try to evaluate any dependencies out of the loop.
3810   LHS = getSCEVAtScope(LHS, L);
3811   RHS = getSCEVAtScope(RHS, L);
3812 
3813   // At this point, we would like to compute how many iterations of the
3814   // loop the predicate will return true for these inputs.
3815   if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3816     // If there is a loop-invariant, force it into the RHS.
3817     std::swap(LHS, RHS);
3818     Cond = ICmpInst::getSwappedPredicate(Cond);
3819   }
3820 
3821   // Simplify the operands before analyzing them.
3822   (void)SimplifyICmpOperands(Cond, LHS, RHS);
3823 
3824   // If we have a comparison of a chrec against a constant, try to use value
3825   // ranges to answer this query.
3826   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3827     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3828       if (AddRec->getLoop() == L) {
3829         // Form the constant range.
3830         ConstantRange CompRange(
3831             ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3832 
3833         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3834         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3835       }
3836 
3837   switch (Cond) {
3838   case ICmpInst::ICMP_NE: {                     // while (X != Y)
3839     // Convert to: while (X-Y != 0)
3840     BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3841     if (BTI.hasAnyInfo()) return BTI;
3842     break;
3843   }
3844   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
3845     // Convert to: while (X-Y == 0)
3846     BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3847     if (BTI.hasAnyInfo()) return BTI;
3848     break;
3849   }
3850   case ICmpInst::ICMP_SLT: {
3851     BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3852     if (BTI.hasAnyInfo()) return BTI;
3853     break;
3854   }
3855   case ICmpInst::ICMP_SGT: {
3856     BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3857                                              getNotSCEV(RHS), L, true);
3858     if (BTI.hasAnyInfo()) return BTI;
3859     break;
3860   }
3861   case ICmpInst::ICMP_ULT: {
3862     BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3863     if (BTI.hasAnyInfo()) return BTI;
3864     break;
3865   }
3866   case ICmpInst::ICMP_UGT: {
3867     BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3868                                              getNotSCEV(RHS), L, false);
3869     if (BTI.hasAnyInfo()) return BTI;
3870     break;
3871   }
3872   default:
3873 #if 0
3874     dbgs() << "ComputeBackedgeTakenCount ";
3875     if (ExitCond->getOperand(0)->getType()->isUnsigned())
3876       dbgs() << "[unsigned] ";
3877     dbgs() << *LHS << "   "
3878          << Instruction::getOpcodeName(Instruction::ICmp)
3879          << "   " << *RHS << "\n";
3880 #endif
3881     break;
3882   }
3883   return
3884     ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3885 }
3886 
3887 static ConstantInt *
3888 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3889                                 ScalarEvolution &SE) {
3890   const SCEV *InVal = SE.getConstant(C);
3891   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
3892   assert(isa<SCEVConstant>(Val) &&
3893          "Evaluation of SCEV at constant didn't fold correctly?");
3894   return cast<SCEVConstant>(Val)->getValue();
3895 }
3896 
3897 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3898 /// and a GEP expression (missing the pointer index) indexing into it, return
3899 /// the addressed element of the initializer or null if the index expression is
3900 /// invalid.
3901 static Constant *
3902 GetAddressedElementFromGlobal(GlobalVariable *GV,
3903                               const std::vector<ConstantInt*> &Indices) {
3904   Constant *Init = GV->getInitializer();
3905   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3906     uint64_t Idx = Indices[i]->getZExtValue();
3907     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3908       assert(Idx < CS->getNumOperands() && "Bad struct index!");
3909       Init = cast<Constant>(CS->getOperand(Idx));
3910     } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3911       if (Idx >= CA->getNumOperands()) return 0;  // Bogus program
3912       Init = cast<Constant>(CA->getOperand(Idx));
3913     } else if (isa<ConstantAggregateZero>(Init)) {
3914       if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3915         assert(Idx < STy->getNumElements() && "Bad struct index!");
3916         Init = Constant::getNullValue(STy->getElementType(Idx));
3917       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3918         if (Idx >= ATy->getNumElements()) return 0;  // Bogus program
3919         Init = Constant::getNullValue(ATy->getElementType());
3920       } else {
3921         llvm_unreachable("Unknown constant aggregate type!");
3922       }
3923       return 0;
3924     } else {
3925       return 0; // Unknown initializer type
3926     }
3927   }
3928   return Init;
3929 }
3930 
3931 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3932 /// 'icmp op load X, cst', try to see if we can compute the backedge
3933 /// execution count.
3934 ScalarEvolution::BackedgeTakenInfo
3935 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3936                                                 LoadInst *LI,
3937                                                 Constant *RHS,
3938                                                 const Loop *L,
3939                                                 ICmpInst::Predicate predicate) {
3940   if (LI->isVolatile()) return getCouldNotCompute();
3941 
3942   // Check to see if the loaded pointer is a getelementptr of a global.
3943   // TODO: Use SCEV instead of manually grubbing with GEPs.
3944   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
3945   if (!GEP) return getCouldNotCompute();
3946 
3947   // Make sure that it is really a constant global we are gepping, with an
3948   // initializer, and make sure the first IDX is really 0.
3949   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3950   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
3951       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3952       !cast<Constant>(GEP->getOperand(1))->isNullValue())
3953     return getCouldNotCompute();
3954 
3955   // Okay, we allow one non-constant index into the GEP instruction.
3956   Value *VarIdx = 0;
3957   std::vector<ConstantInt*> Indexes;
3958   unsigned VarIdxNum = 0;
3959   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3960     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3961       Indexes.push_back(CI);
3962     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
3963       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
3964       VarIdx = GEP->getOperand(i);
3965       VarIdxNum = i-2;
3966       Indexes.push_back(0);
3967     }
3968 
3969   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3970   // Check to see if X is a loop variant variable value now.
3971   const SCEV *Idx = getSCEV(VarIdx);
3972   Idx = getSCEVAtScope(Idx, L);
3973 
3974   // We can only recognize very limited forms of loop index expressions, in
3975   // particular, only affine AddRec's like {C1,+,C2}.
3976   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
3977   if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3978       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3979       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
3980     return getCouldNotCompute();
3981 
3982   unsigned MaxSteps = MaxBruteForceIterations;
3983   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3984     ConstantInt *ItCst = ConstantInt::get(
3985                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
3986     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
3987 
3988     // Form the GEP offset.
3989     Indexes[VarIdxNum] = Val;
3990 
3991     Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3992     if (Result == 0) break;  // Cannot compute!
3993 
3994     // Evaluate the condition for this iteration.
3995     Result = ConstantExpr::getICmp(predicate, Result, RHS);
3996     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
3997     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3998 #if 0
3999       dbgs() << "\n***\n*** Computed loop count " << *ItCst
4000              << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4001              << "***\n";
4002 #endif
4003       ++NumArrayLenItCounts;
4004       return getConstant(ItCst);   // Found terminating iteration!
4005     }
4006   }
4007   return getCouldNotCompute();
4008 }
4009 
4010 
4011 /// CanConstantFold - Return true if we can constant fold an instruction of the
4012 /// specified type, assuming that all operands were constants.
4013 static bool CanConstantFold(const Instruction *I) {
4014   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4015       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4016     return true;
4017 
4018   if (const CallInst *CI = dyn_cast<CallInst>(I))
4019     if (const Function *F = CI->getCalledFunction())
4020       return canConstantFoldCallTo(F);
4021   return false;
4022 }
4023 
4024 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4025 /// in the loop that V is derived from.  We allow arbitrary operations along the
4026 /// way, but the operands of an operation must either be constants or a value
4027 /// derived from a constant PHI.  If this expression does not fit with these
4028 /// constraints, return null.
4029 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4030   // If this is not an instruction, or if this is an instruction outside of the
4031   // loop, it can't be derived from a loop PHI.
4032   Instruction *I = dyn_cast<Instruction>(V);
4033   if (I == 0 || !L->contains(I)) return 0;
4034 
4035   if (PHINode *PN = dyn_cast<PHINode>(I)) {
4036     if (L->getHeader() == I->getParent())
4037       return PN;
4038     else
4039       // We don't currently keep track of the control flow needed to evaluate
4040       // PHIs, so we cannot handle PHIs inside of loops.
4041       return 0;
4042   }
4043 
4044   // If we won't be able to constant fold this expression even if the operands
4045   // are constants, return early.
4046   if (!CanConstantFold(I)) return 0;
4047 
4048   // Otherwise, we can evaluate this instruction if all of its operands are
4049   // constant or derived from a PHI node themselves.
4050   PHINode *PHI = 0;
4051   for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4052     if (!(isa<Constant>(I->getOperand(Op)) ||
4053           isa<GlobalValue>(I->getOperand(Op)))) {
4054       PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4055       if (P == 0) return 0;  // Not evolving from PHI
4056       if (PHI == 0)
4057         PHI = P;
4058       else if (PHI != P)
4059         return 0;  // Evolving from multiple different PHIs.
4060     }
4061 
4062   // This is a expression evolving from a constant PHI!
4063   return PHI;
4064 }
4065 
4066 /// EvaluateExpression - Given an expression that passes the
4067 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4068 /// in the loop has the value PHIVal.  If we can't fold this expression for some
4069 /// reason, return null.
4070 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4071                                     const TargetData *TD) {
4072   if (isa<PHINode>(V)) return PHIVal;
4073   if (Constant *C = dyn_cast<Constant>(V)) return C;
4074   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
4075   Instruction *I = cast<Instruction>(V);
4076 
4077   std::vector<Constant*> Operands;
4078   Operands.resize(I->getNumOperands());
4079 
4080   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4081     Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4082     if (Operands[i] == 0) return 0;
4083   }
4084 
4085   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4086     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4087                                            Operands[1], TD);
4088   return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4089                                   &Operands[0], Operands.size(), TD);
4090 }
4091 
4092 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4093 /// in the header of its containing loop, we know the loop executes a
4094 /// constant number of times, and the PHI node is just a recurrence
4095 /// involving constants, fold it.
4096 Constant *
4097 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4098                                                    const APInt &BEs,
4099                                                    const Loop *L) {
4100   std::map<PHINode*, Constant*>::iterator I =
4101     ConstantEvolutionLoopExitValue.find(PN);
4102   if (I != ConstantEvolutionLoopExitValue.end())
4103     return I->second;
4104 
4105   if (BEs.ugt(MaxBruteForceIterations))
4106     return ConstantEvolutionLoopExitValue[PN] = 0;  // Not going to evaluate it.
4107 
4108   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4109 
4110   // Since the loop is canonicalized, the PHI node must have two entries.  One
4111   // entry must be a constant (coming in from outside of the loop), and the
4112   // second must be derived from the same PHI.
4113   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4114   Constant *StartCST =
4115     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4116   if (StartCST == 0)
4117     return RetVal = 0;  // Must be a constant.
4118 
4119   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4120   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4121   if (PN2 != PN)
4122     return RetVal = 0;  // Not derived from same PHI.
4123 
4124   // Execute the loop symbolically to determine the exit value.
4125   if (BEs.getActiveBits() >= 32)
4126     return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4127 
4128   unsigned NumIterations = BEs.getZExtValue(); // must be in range
4129   unsigned IterationNum = 0;
4130   for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4131     if (IterationNum == NumIterations)
4132       return RetVal = PHIVal;  // Got exit value!
4133 
4134     // Compute the value of the PHI node for the next iteration.
4135     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4136     if (NextPHI == PHIVal)
4137       return RetVal = NextPHI;  // Stopped evolving!
4138     if (NextPHI == 0)
4139       return 0;        // Couldn't evaluate!
4140     PHIVal = NextPHI;
4141   }
4142 }
4143 
4144 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4145 /// constant number of times (the condition evolves only from constants),
4146 /// try to evaluate a few iterations of the loop until we get the exit
4147 /// condition gets a value of ExitWhen (true or false).  If we cannot
4148 /// evaluate the trip count of the loop, return getCouldNotCompute().
4149 const SCEV *
4150 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4151                                                        Value *Cond,
4152                                                        bool ExitWhen) {
4153   PHINode *PN = getConstantEvolvingPHI(Cond, L);
4154   if (PN == 0) return getCouldNotCompute();
4155 
4156   // Since the loop is canonicalized, the PHI node must have two entries.  One
4157   // entry must be a constant (coming in from outside of the loop), and the
4158   // second must be derived from the same PHI.
4159   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4160   Constant *StartCST =
4161     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4162   if (StartCST == 0) return getCouldNotCompute();  // Must be a constant.
4163 
4164   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4165   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4166   if (PN2 != PN) return getCouldNotCompute();  // Not derived from same PHI.
4167 
4168   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
4169   // the loop symbolically to determine when the condition gets a value of
4170   // "ExitWhen".
4171   unsigned IterationNum = 0;
4172   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
4173   for (Constant *PHIVal = StartCST;
4174        IterationNum != MaxIterations; ++IterationNum) {
4175     ConstantInt *CondVal =
4176       dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4177 
4178     // Couldn't symbolically evaluate.
4179     if (!CondVal) return getCouldNotCompute();
4180 
4181     if (CondVal->getValue() == uint64_t(ExitWhen)) {
4182       ++NumBruteForceTripCountsComputed;
4183       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4184     }
4185 
4186     // Compute the value of the PHI node for the next iteration.
4187     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4188     if (NextPHI == 0 || NextPHI == PHIVal)
4189       return getCouldNotCompute();// Couldn't evaluate or not making progress...
4190     PHIVal = NextPHI;
4191   }
4192 
4193   // Too many iterations were needed to evaluate.
4194   return getCouldNotCompute();
4195 }
4196 
4197 /// getSCEVAtScope - Return a SCEV expression for the specified value
4198 /// at the specified scope in the program.  The L value specifies a loop
4199 /// nest to evaluate the expression at, where null is the top-level or a
4200 /// specified loop is immediately inside of the loop.
4201 ///
4202 /// This method can be used to compute the exit value for a variable defined
4203 /// in a loop by querying what the value will hold in the parent loop.
4204 ///
4205 /// In the case that a relevant loop exit value cannot be computed, the
4206 /// original value V is returned.
4207 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4208   // Check to see if we've folded this expression at this loop before.
4209   std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4210   std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4211     Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4212   if (!Pair.second)
4213     return Pair.first->second ? Pair.first->second : V;
4214 
4215   // Otherwise compute it.
4216   const SCEV *C = computeSCEVAtScope(V, L);
4217   ValuesAtScopes[V][L] = C;
4218   return C;
4219 }
4220 
4221 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4222   if (isa<SCEVConstant>(V)) return V;
4223 
4224   // If this instruction is evolved from a constant-evolving PHI, compute the
4225   // exit value from the loop without using SCEVs.
4226   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4227     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4228       const Loop *LI = (*this->LI)[I->getParent()];
4229       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
4230         if (PHINode *PN = dyn_cast<PHINode>(I))
4231           if (PN->getParent() == LI->getHeader()) {
4232             // Okay, there is no closed form solution for the PHI node.  Check
4233             // to see if the loop that contains it has a known backedge-taken
4234             // count.  If so, we may be able to force computation of the exit
4235             // value.
4236             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4237             if (const SCEVConstant *BTCC =
4238                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4239               // Okay, we know how many times the containing loop executes.  If
4240               // this is a constant evolving PHI node, get the final value at
4241               // the specified iteration number.
4242               Constant *RV = getConstantEvolutionLoopExitValue(PN,
4243                                                    BTCC->getValue()->getValue(),
4244                                                                LI);
4245               if (RV) return getSCEV(RV);
4246             }
4247           }
4248 
4249       // Okay, this is an expression that we cannot symbolically evaluate
4250       // into a SCEV.  Check to see if it's possible to symbolically evaluate
4251       // the arguments into constants, and if so, try to constant propagate the
4252       // result.  This is particularly useful for computing loop exit values.
4253       if (CanConstantFold(I)) {
4254         std::vector<Constant*> Operands;
4255         Operands.reserve(I->getNumOperands());
4256         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4257           Value *Op = I->getOperand(i);
4258           if (Constant *C = dyn_cast<Constant>(Op)) {
4259             Operands.push_back(C);
4260           } else {
4261             // If any of the operands is non-constant and if they are
4262             // non-integer and non-pointer, don't even try to analyze them
4263             // with scev techniques.
4264             if (!isSCEVable(Op->getType()))
4265               return V;
4266 
4267             const SCEV *OpV = getSCEVAtScope(Op, L);
4268             if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
4269               Constant *C = SC->getValue();
4270               if (C->getType() != Op->getType())
4271                 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4272                                                                   Op->getType(),
4273                                                                   false),
4274                                           C, Op->getType());
4275               Operands.push_back(C);
4276             } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
4277               if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4278                 if (C->getType() != Op->getType())
4279                   C =
4280                     ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4281                                                                   Op->getType(),
4282                                                                   false),
4283                                           C, Op->getType());
4284                 Operands.push_back(C);
4285               } else
4286                 return V;
4287             } else {
4288               return V;
4289             }
4290           }
4291         }
4292 
4293         Constant *C = 0;
4294         if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4295           C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4296                                               Operands[0], Operands[1], TD);
4297         else
4298           C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4299                                        &Operands[0], Operands.size(), TD);
4300         if (C)
4301           return getSCEV(C);
4302       }
4303     }
4304 
4305     // This is some other type of SCEVUnknown, just return it.
4306     return V;
4307   }
4308 
4309   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4310     // Avoid performing the look-up in the common case where the specified
4311     // expression has no loop-variant portions.
4312     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4313       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4314       if (OpAtScope != Comm->getOperand(i)) {
4315         // Okay, at least one of these operands is loop variant but might be
4316         // foldable.  Build a new instance of the folded commutative expression.
4317         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4318                                             Comm->op_begin()+i);
4319         NewOps.push_back(OpAtScope);
4320 
4321         for (++i; i != e; ++i) {
4322           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4323           NewOps.push_back(OpAtScope);
4324         }
4325         if (isa<SCEVAddExpr>(Comm))
4326           return getAddExpr(NewOps);
4327         if (isa<SCEVMulExpr>(Comm))
4328           return getMulExpr(NewOps);
4329         if (isa<SCEVSMaxExpr>(Comm))
4330           return getSMaxExpr(NewOps);
4331         if (isa<SCEVUMaxExpr>(Comm))
4332           return getUMaxExpr(NewOps);
4333         llvm_unreachable("Unknown commutative SCEV type!");
4334       }
4335     }
4336     // If we got here, all operands are loop invariant.
4337     return Comm;
4338   }
4339 
4340   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4341     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4342     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4343     if (LHS == Div->getLHS() && RHS == Div->getRHS())
4344       return Div;   // must be loop invariant
4345     return getUDivExpr(LHS, RHS);
4346   }
4347 
4348   // If this is a loop recurrence for a loop that does not contain L, then we
4349   // are dealing with the final value computed by the loop.
4350   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4351     if (!L || !AddRec->getLoop()->contains(L)) {
4352       // To evaluate this recurrence, we need to know how many times the AddRec
4353       // loop iterates.  Compute this now.
4354       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4355       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4356 
4357       // Then, evaluate the AddRec.
4358       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4359     }
4360     return AddRec;
4361   }
4362 
4363   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4364     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4365     if (Op == Cast->getOperand())
4366       return Cast;  // must be loop invariant
4367     return getZeroExtendExpr(Op, Cast->getType());
4368   }
4369 
4370   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4371     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4372     if (Op == Cast->getOperand())
4373       return Cast;  // must be loop invariant
4374     return getSignExtendExpr(Op, Cast->getType());
4375   }
4376 
4377   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4378     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4379     if (Op == Cast->getOperand())
4380       return Cast;  // must be loop invariant
4381     return getTruncateExpr(Op, Cast->getType());
4382   }
4383 
4384   llvm_unreachable("Unknown SCEV type!");
4385   return 0;
4386 }
4387 
4388 /// getSCEVAtScope - This is a convenience function which does
4389 /// getSCEVAtScope(getSCEV(V), L).
4390 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4391   return getSCEVAtScope(getSCEV(V), L);
4392 }
4393 
4394 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4395 /// following equation:
4396 ///
4397 ///     A * X = B (mod N)
4398 ///
4399 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4400 /// A and B isn't important.
4401 ///
4402 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4403 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4404                                                ScalarEvolution &SE) {
4405   uint32_t BW = A.getBitWidth();
4406   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4407   assert(A != 0 && "A must be non-zero.");
4408 
4409   // 1. D = gcd(A, N)
4410   //
4411   // The gcd of A and N may have only one prime factor: 2. The number of
4412   // trailing zeros in A is its multiplicity
4413   uint32_t Mult2 = A.countTrailingZeros();
4414   // D = 2^Mult2
4415 
4416   // 2. Check if B is divisible by D.
4417   //
4418   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4419   // is not less than multiplicity of this prime factor for D.
4420   if (B.countTrailingZeros() < Mult2)
4421     return SE.getCouldNotCompute();
4422 
4423   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4424   // modulo (N / D).
4425   //
4426   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
4427   // bit width during computations.
4428   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
4429   APInt Mod(BW + 1, 0);
4430   Mod.set(BW - Mult2);  // Mod = N / D
4431   APInt I = AD.multiplicativeInverse(Mod);
4432 
4433   // 4. Compute the minimum unsigned root of the equation:
4434   // I * (B / D) mod (N / D)
4435   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4436 
4437   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4438   // bits.
4439   return SE.getConstant(Result.trunc(BW));
4440 }
4441 
4442 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4443 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
4444 /// might be the same) or two SCEVCouldNotCompute objects.
4445 ///
4446 static std::pair<const SCEV *,const SCEV *>
4447 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4448   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4449   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4450   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4451   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4452 
4453   // We currently can only solve this if the coefficients are constants.
4454   if (!LC || !MC || !NC) {
4455     const SCEV *CNC = SE.getCouldNotCompute();
4456     return std::make_pair(CNC, CNC);
4457   }
4458 
4459   uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4460   const APInt &L = LC->getValue()->getValue();
4461   const APInt &M = MC->getValue()->getValue();
4462   const APInt &N = NC->getValue()->getValue();
4463   APInt Two(BitWidth, 2);
4464   APInt Four(BitWidth, 4);
4465 
4466   {
4467     using namespace APIntOps;
4468     const APInt& C = L;
4469     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4470     // The B coefficient is M-N/2
4471     APInt B(M);
4472     B -= sdiv(N,Two);
4473 
4474     // The A coefficient is N/2
4475     APInt A(N.sdiv(Two));
4476 
4477     // Compute the B^2-4ac term.
4478     APInt SqrtTerm(B);
4479     SqrtTerm *= B;
4480     SqrtTerm -= Four * (A * C);
4481 
4482     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4483     // integer value or else APInt::sqrt() will assert.
4484     APInt SqrtVal(SqrtTerm.sqrt());
4485 
4486     // Compute the two solutions for the quadratic formula.
4487     // The divisions must be performed as signed divisions.
4488     APInt NegB(-B);
4489     APInt TwoA( A << 1 );
4490     if (TwoA.isMinValue()) {
4491       const SCEV *CNC = SE.getCouldNotCompute();
4492       return std::make_pair(CNC, CNC);
4493     }
4494 
4495     LLVMContext &Context = SE.getContext();
4496 
4497     ConstantInt *Solution1 =
4498       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4499     ConstantInt *Solution2 =
4500       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4501 
4502     return std::make_pair(SE.getConstant(Solution1),
4503                           SE.getConstant(Solution2));
4504     } // end APIntOps namespace
4505 }
4506 
4507 /// HowFarToZero - Return the number of times a backedge comparing the specified
4508 /// value to zero will execute.  If not computable, return CouldNotCompute.
4509 ScalarEvolution::BackedgeTakenInfo
4510 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4511   // If the value is a constant
4512   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4513     // If the value is already zero, the branch will execute zero times.
4514     if (C->getValue()->isZero()) return C;
4515     return getCouldNotCompute();  // Otherwise it will loop infinitely.
4516   }
4517 
4518   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4519   if (!AddRec || AddRec->getLoop() != L)
4520     return getCouldNotCompute();
4521 
4522   if (AddRec->isAffine()) {
4523     // If this is an affine expression, the execution count of this branch is
4524     // the minimum unsigned root of the following equation:
4525     //
4526     //     Start + Step*N = 0 (mod 2^BW)
4527     //
4528     // equivalent to:
4529     //
4530     //             Step*N = -Start (mod 2^BW)
4531     //
4532     // where BW is the common bit width of Start and Step.
4533 
4534     // Get the initial value for the loop.
4535     const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4536                                        L->getParentLoop());
4537     const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4538                                       L->getParentLoop());
4539 
4540     if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4541       // For now we handle only constant steps.
4542 
4543       // First, handle unitary steps.
4544       if (StepC->getValue()->equalsInt(1))      // 1*N = -Start (mod 2^BW), so:
4545         return getNegativeSCEV(Start);          //   N = -Start (as unsigned)
4546       if (StepC->getValue()->isAllOnesValue())  // -1*N = -Start (mod 2^BW), so:
4547         return Start;                           //    N = Start (as unsigned)
4548 
4549       // Then, try to solve the above equation provided that Start is constant.
4550       if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4551         return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4552                                             -StartC->getValue()->getValue(),
4553                                             *this);
4554     }
4555   } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4556     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4557     // the quadratic equation to solve it.
4558     std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4559                                                                     *this);
4560     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4561     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4562     if (R1) {
4563 #if 0
4564       dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4565              << "  sol#2: " << *R2 << "\n";
4566 #endif
4567       // Pick the smallest positive root value.
4568       if (ConstantInt *CB =
4569           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4570                                    R1->getValue(), R2->getValue()))) {
4571         if (CB->getZExtValue() == false)
4572           std::swap(R1, R2);   // R1 is the minimum root now.
4573 
4574         // We can only use this value if the chrec ends up with an exact zero
4575         // value at this index.  When solving for "X*X != 5", for example, we
4576         // should not accept a root of 2.
4577         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4578         if (Val->isZero())
4579           return R1;  // We found a quadratic root!
4580       }
4581     }
4582   }
4583 
4584   return getCouldNotCompute();
4585 }
4586 
4587 /// HowFarToNonZero - Return the number of times a backedge checking the
4588 /// specified value for nonzero will execute.  If not computable, return
4589 /// CouldNotCompute
4590 ScalarEvolution::BackedgeTakenInfo
4591 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4592   // Loops that look like: while (X == 0) are very strange indeed.  We don't
4593   // handle them yet except for the trivial case.  This could be expanded in the
4594   // future as needed.
4595 
4596   // If the value is a constant, check to see if it is known to be non-zero
4597   // already.  If so, the backedge will execute zero times.
4598   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4599     if (!C->getValue()->isNullValue())
4600       return getConstant(C->getType(), 0);
4601     return getCouldNotCompute();  // Otherwise it will loop infinitely.
4602   }
4603 
4604   // We could implement others, but I really doubt anyone writes loops like
4605   // this, and if they did, they would already be constant folded.
4606   return getCouldNotCompute();
4607 }
4608 
4609 /// getLoopPredecessor - If the given loop's header has exactly one unique
4610 /// predecessor outside the loop, return it. Otherwise return null.
4611 /// This is less strict that the loop "preheader" concept, which requires
4612 /// the predecessor to have only one single successor.
4613 ///
4614 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4615   BasicBlock *Header = L->getHeader();
4616   BasicBlock *Pred = 0;
4617   for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4618        PI != E; ++PI)
4619     if (!L->contains(*PI)) {
4620       if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4621       Pred = *PI;
4622     }
4623   return Pred;
4624 }
4625 
4626 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4627 /// (which may not be an immediate predecessor) which has exactly one
4628 /// successor from which BB is reachable, or null if no such block is
4629 /// found.
4630 ///
4631 std::pair<BasicBlock *, BasicBlock *>
4632 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4633   // If the block has a unique predecessor, then there is no path from the
4634   // predecessor to the block that does not go through the direct edge
4635   // from the predecessor to the block.
4636   if (BasicBlock *Pred = BB->getSinglePredecessor())
4637     return std::make_pair(Pred, BB);
4638 
4639   // A loop's header is defined to be a block that dominates the loop.
4640   // If the header has a unique predecessor outside the loop, it must be
4641   // a block that has exactly one successor that can reach the loop.
4642   if (Loop *L = LI->getLoopFor(BB))
4643     return std::make_pair(getLoopPredecessor(L), L->getHeader());
4644 
4645   return std::pair<BasicBlock *, BasicBlock *>();
4646 }
4647 
4648 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4649 /// testing whether two expressions are equal, however for the purposes of
4650 /// looking for a condition guarding a loop, it can be useful to be a little
4651 /// more general, since a front-end may have replicated the controlling
4652 /// expression.
4653 ///
4654 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4655   // Quick check to see if they are the same SCEV.
4656   if (A == B) return true;
4657 
4658   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4659   // two different instructions with the same value. Check for this case.
4660   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4661     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4662       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4663         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4664           if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
4665             return true;
4666 
4667   // Otherwise assume they may have a different value.
4668   return false;
4669 }
4670 
4671 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4672 /// predicate Pred. Return true iff any changes were made.
4673 ///
4674 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4675                                            const SCEV *&LHS, const SCEV *&RHS) {
4676   bool Changed = false;
4677 
4678   // Canonicalize a constant to the right side.
4679   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4680     // Check for both operands constant.
4681     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4682       if (ConstantExpr::getICmp(Pred,
4683                                 LHSC->getValue(),
4684                                 RHSC->getValue())->isNullValue())
4685         goto trivially_false;
4686       else
4687         goto trivially_true;
4688     }
4689     // Otherwise swap the operands to put the constant on the right.
4690     std::swap(LHS, RHS);
4691     Pred = ICmpInst::getSwappedPredicate(Pred);
4692     Changed = true;
4693   }
4694 
4695   // If we're comparing an addrec with a value which is loop-invariant in the
4696   // addrec's loop, put the addrec on the left. Also make a dominance check,
4697   // as both operands could be addrecs loop-invariant in each other's loop.
4698   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4699     const Loop *L = AR->getLoop();
4700     if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
4701       std::swap(LHS, RHS);
4702       Pred = ICmpInst::getSwappedPredicate(Pred);
4703       Changed = true;
4704     }
4705   }
4706 
4707   // If there's a constant operand, canonicalize comparisons with boundary
4708   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4709   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4710     const APInt &RA = RC->getValue()->getValue();
4711     switch (Pred) {
4712     default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4713     case ICmpInst::ICMP_EQ:
4714     case ICmpInst::ICMP_NE:
4715       break;
4716     case ICmpInst::ICMP_UGE:
4717       if ((RA - 1).isMinValue()) {
4718         Pred = ICmpInst::ICMP_NE;
4719         RHS = getConstant(RA - 1);
4720         Changed = true;
4721         break;
4722       }
4723       if (RA.isMaxValue()) {
4724         Pred = ICmpInst::ICMP_EQ;
4725         Changed = true;
4726         break;
4727       }
4728       if (RA.isMinValue()) goto trivially_true;
4729 
4730       Pred = ICmpInst::ICMP_UGT;
4731       RHS = getConstant(RA - 1);
4732       Changed = true;
4733       break;
4734     case ICmpInst::ICMP_ULE:
4735       if ((RA + 1).isMaxValue()) {
4736         Pred = ICmpInst::ICMP_NE;
4737         RHS = getConstant(RA + 1);
4738         Changed = true;
4739         break;
4740       }
4741       if (RA.isMinValue()) {
4742         Pred = ICmpInst::ICMP_EQ;
4743         Changed = true;
4744         break;
4745       }
4746       if (RA.isMaxValue()) goto trivially_true;
4747 
4748       Pred = ICmpInst::ICMP_ULT;
4749       RHS = getConstant(RA + 1);
4750       Changed = true;
4751       break;
4752     case ICmpInst::ICMP_SGE:
4753       if ((RA - 1).isMinSignedValue()) {
4754         Pred = ICmpInst::ICMP_NE;
4755         RHS = getConstant(RA - 1);
4756         Changed = true;
4757         break;
4758       }
4759       if (RA.isMaxSignedValue()) {
4760         Pred = ICmpInst::ICMP_EQ;
4761         Changed = true;
4762         break;
4763       }
4764       if (RA.isMinSignedValue()) goto trivially_true;
4765 
4766       Pred = ICmpInst::ICMP_SGT;
4767       RHS = getConstant(RA - 1);
4768       Changed = true;
4769       break;
4770     case ICmpInst::ICMP_SLE:
4771       if ((RA + 1).isMaxSignedValue()) {
4772         Pred = ICmpInst::ICMP_NE;
4773         RHS = getConstant(RA + 1);
4774         Changed = true;
4775         break;
4776       }
4777       if (RA.isMinSignedValue()) {
4778         Pred = ICmpInst::ICMP_EQ;
4779         Changed = true;
4780         break;
4781       }
4782       if (RA.isMaxSignedValue()) goto trivially_true;
4783 
4784       Pred = ICmpInst::ICMP_SLT;
4785       RHS = getConstant(RA + 1);
4786       Changed = true;
4787       break;
4788     case ICmpInst::ICMP_UGT:
4789       if (RA.isMinValue()) {
4790         Pred = ICmpInst::ICMP_NE;
4791         Changed = true;
4792         break;
4793       }
4794       if ((RA + 1).isMaxValue()) {
4795         Pred = ICmpInst::ICMP_EQ;
4796         RHS = getConstant(RA + 1);
4797         Changed = true;
4798         break;
4799       }
4800       if (RA.isMaxValue()) goto trivially_false;
4801       break;
4802     case ICmpInst::ICMP_ULT:
4803       if (RA.isMaxValue()) {
4804         Pred = ICmpInst::ICMP_NE;
4805         Changed = true;
4806         break;
4807       }
4808       if ((RA - 1).isMinValue()) {
4809         Pred = ICmpInst::ICMP_EQ;
4810         RHS = getConstant(RA - 1);
4811         Changed = true;
4812         break;
4813       }
4814       if (RA.isMinValue()) goto trivially_false;
4815       break;
4816     case ICmpInst::ICMP_SGT:
4817       if (RA.isMinSignedValue()) {
4818         Pred = ICmpInst::ICMP_NE;
4819         Changed = true;
4820         break;
4821       }
4822       if ((RA + 1).isMaxSignedValue()) {
4823         Pred = ICmpInst::ICMP_EQ;
4824         RHS = getConstant(RA + 1);
4825         Changed = true;
4826         break;
4827       }
4828       if (RA.isMaxSignedValue()) goto trivially_false;
4829       break;
4830     case ICmpInst::ICMP_SLT:
4831       if (RA.isMaxSignedValue()) {
4832         Pred = ICmpInst::ICMP_NE;
4833         Changed = true;
4834         break;
4835       }
4836       if ((RA - 1).isMinSignedValue()) {
4837        Pred = ICmpInst::ICMP_EQ;
4838        RHS = getConstant(RA - 1);
4839         Changed = true;
4840        break;
4841       }
4842       if (RA.isMinSignedValue()) goto trivially_false;
4843       break;
4844     }
4845   }
4846 
4847   // Check for obvious equality.
4848   if (HasSameValue(LHS, RHS)) {
4849     if (ICmpInst::isTrueWhenEqual(Pred))
4850       goto trivially_true;
4851     if (ICmpInst::isFalseWhenEqual(Pred))
4852       goto trivially_false;
4853   }
4854 
4855   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
4856   // adding or subtracting 1 from one of the operands.
4857   switch (Pred) {
4858   case ICmpInst::ICMP_SLE:
4859     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
4860       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
4861                        /*HasNUW=*/false, /*HasNSW=*/true);
4862       Pred = ICmpInst::ICMP_SLT;
4863       Changed = true;
4864     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
4865       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
4866                        /*HasNUW=*/false, /*HasNSW=*/true);
4867       Pred = ICmpInst::ICMP_SLT;
4868       Changed = true;
4869     }
4870     break;
4871   case ICmpInst::ICMP_SGE:
4872     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
4873       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
4874                        /*HasNUW=*/false, /*HasNSW=*/true);
4875       Pred = ICmpInst::ICMP_SGT;
4876       Changed = true;
4877     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
4878       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
4879                        /*HasNUW=*/false, /*HasNSW=*/true);
4880       Pred = ICmpInst::ICMP_SGT;
4881       Changed = true;
4882     }
4883     break;
4884   case ICmpInst::ICMP_ULE:
4885     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
4886       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
4887                        /*HasNUW=*/true, /*HasNSW=*/false);
4888       Pred = ICmpInst::ICMP_ULT;
4889       Changed = true;
4890     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
4891       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
4892                        /*HasNUW=*/true, /*HasNSW=*/false);
4893       Pred = ICmpInst::ICMP_ULT;
4894       Changed = true;
4895     }
4896     break;
4897   case ICmpInst::ICMP_UGE:
4898     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
4899       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
4900                        /*HasNUW=*/true, /*HasNSW=*/false);
4901       Pred = ICmpInst::ICMP_UGT;
4902       Changed = true;
4903     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
4904       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
4905                        /*HasNUW=*/true, /*HasNSW=*/false);
4906       Pred = ICmpInst::ICMP_UGT;
4907       Changed = true;
4908     }
4909     break;
4910   default:
4911     break;
4912   }
4913 
4914   // TODO: More simplifications are possible here.
4915 
4916   return Changed;
4917 
4918 trivially_true:
4919   // Return 0 == 0.
4920   LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
4921   Pred = ICmpInst::ICMP_EQ;
4922   return true;
4923 
4924 trivially_false:
4925   // Return 0 != 0.
4926   LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
4927   Pred = ICmpInst::ICMP_NE;
4928   return true;
4929 }
4930 
4931 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4932   return getSignedRange(S).getSignedMax().isNegative();
4933 }
4934 
4935 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4936   return getSignedRange(S).getSignedMin().isStrictlyPositive();
4937 }
4938 
4939 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4940   return !getSignedRange(S).getSignedMin().isNegative();
4941 }
4942 
4943 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4944   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4945 }
4946 
4947 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4948   return isKnownNegative(S) || isKnownPositive(S);
4949 }
4950 
4951 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4952                                        const SCEV *LHS, const SCEV *RHS) {
4953   // Canonicalize the inputs first.
4954   (void)SimplifyICmpOperands(Pred, LHS, RHS);
4955 
4956   // If LHS or RHS is an addrec, check to see if the condition is true in
4957   // every iteration of the loop.
4958   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
4959     if (isLoopEntryGuardedByCond(
4960           AR->getLoop(), Pred, AR->getStart(), RHS) &&
4961         isLoopBackedgeGuardedByCond(
4962           AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
4963       return true;
4964   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
4965     if (isLoopEntryGuardedByCond(
4966           AR->getLoop(), Pred, LHS, AR->getStart()) &&
4967         isLoopBackedgeGuardedByCond(
4968           AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
4969       return true;
4970 
4971   // Otherwise see what can be done with known constant ranges.
4972   return isKnownPredicateWithRanges(Pred, LHS, RHS);
4973 }
4974 
4975 bool
4976 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
4977                                             const SCEV *LHS, const SCEV *RHS) {
4978   if (HasSameValue(LHS, RHS))
4979     return ICmpInst::isTrueWhenEqual(Pred);
4980 
4981   // This code is split out from isKnownPredicate because it is called from
4982   // within isLoopEntryGuardedByCond.
4983   switch (Pred) {
4984   default:
4985     llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4986     break;
4987   case ICmpInst::ICMP_SGT:
4988     Pred = ICmpInst::ICMP_SLT;
4989     std::swap(LHS, RHS);
4990   case ICmpInst::ICMP_SLT: {
4991     ConstantRange LHSRange = getSignedRange(LHS);
4992     ConstantRange RHSRange = getSignedRange(RHS);
4993     if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4994       return true;
4995     if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4996       return false;
4997     break;
4998   }
4999   case ICmpInst::ICMP_SGE:
5000     Pred = ICmpInst::ICMP_SLE;
5001     std::swap(LHS, RHS);
5002   case ICmpInst::ICMP_SLE: {
5003     ConstantRange LHSRange = getSignedRange(LHS);
5004     ConstantRange RHSRange = getSignedRange(RHS);
5005     if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5006       return true;
5007     if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5008       return false;
5009     break;
5010   }
5011   case ICmpInst::ICMP_UGT:
5012     Pred = ICmpInst::ICMP_ULT;
5013     std::swap(LHS, RHS);
5014   case ICmpInst::ICMP_ULT: {
5015     ConstantRange LHSRange = getUnsignedRange(LHS);
5016     ConstantRange RHSRange = getUnsignedRange(RHS);
5017     if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5018       return true;
5019     if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5020       return false;
5021     break;
5022   }
5023   case ICmpInst::ICMP_UGE:
5024     Pred = ICmpInst::ICMP_ULE;
5025     std::swap(LHS, RHS);
5026   case ICmpInst::ICMP_ULE: {
5027     ConstantRange LHSRange = getUnsignedRange(LHS);
5028     ConstantRange RHSRange = getUnsignedRange(RHS);
5029     if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5030       return true;
5031     if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5032       return false;
5033     break;
5034   }
5035   case ICmpInst::ICMP_NE: {
5036     if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5037       return true;
5038     if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5039       return true;
5040 
5041     const SCEV *Diff = getMinusSCEV(LHS, RHS);
5042     if (isKnownNonZero(Diff))
5043       return true;
5044     break;
5045   }
5046   case ICmpInst::ICMP_EQ:
5047     // The check at the top of the function catches the case where
5048     // the values are known to be equal.
5049     break;
5050   }
5051   return false;
5052 }
5053 
5054 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5055 /// protected by a conditional between LHS and RHS.  This is used to
5056 /// to eliminate casts.
5057 bool
5058 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5059                                              ICmpInst::Predicate Pred,
5060                                              const SCEV *LHS, const SCEV *RHS) {
5061   // Interpret a null as meaning no loop, where there is obviously no guard
5062   // (interprocedural conditions notwithstanding).
5063   if (!L) return true;
5064 
5065   BasicBlock *Latch = L->getLoopLatch();
5066   if (!Latch)
5067     return false;
5068 
5069   BranchInst *LoopContinuePredicate =
5070     dyn_cast<BranchInst>(Latch->getTerminator());
5071   if (!LoopContinuePredicate ||
5072       LoopContinuePredicate->isUnconditional())
5073     return false;
5074 
5075   return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
5076                        LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5077 }
5078 
5079 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5080 /// by a conditional between LHS and RHS.  This is used to help avoid max
5081 /// expressions in loop trip counts, and to eliminate casts.
5082 bool
5083 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5084                                           ICmpInst::Predicate Pred,
5085                                           const SCEV *LHS, const SCEV *RHS) {
5086   // Interpret a null as meaning no loop, where there is obviously no guard
5087   // (interprocedural conditions notwithstanding).
5088   if (!L) return false;
5089 
5090   // Starting at the loop predecessor, climb up the predecessor chain, as long
5091   // as there are predecessors that can be found that have unique successors
5092   // leading to the original header.
5093   for (std::pair<BasicBlock *, BasicBlock *>
5094          Pair(getLoopPredecessor(L), L->getHeader());
5095        Pair.first;
5096        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5097 
5098     BranchInst *LoopEntryPredicate =
5099       dyn_cast<BranchInst>(Pair.first->getTerminator());
5100     if (!LoopEntryPredicate ||
5101         LoopEntryPredicate->isUnconditional())
5102       continue;
5103 
5104     if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
5105                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
5106       return true;
5107   }
5108 
5109   return false;
5110 }
5111 
5112 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5113 /// and RHS is true whenever the given Cond value evaluates to true.
5114 bool ScalarEvolution::isImpliedCond(Value *CondValue,
5115                                     ICmpInst::Predicate Pred,
5116                                     const SCEV *LHS, const SCEV *RHS,
5117                                     bool Inverse) {
5118   // Recursively handle And and Or conditions.
5119   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
5120     if (BO->getOpcode() == Instruction::And) {
5121       if (!Inverse)
5122         return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
5123                isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
5124     } else if (BO->getOpcode() == Instruction::Or) {
5125       if (Inverse)
5126         return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
5127                isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
5128     }
5129   }
5130 
5131   ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
5132   if (!ICI) return false;
5133 
5134   // Bail if the ICmp's operands' types are wider than the needed type
5135   // before attempting to call getSCEV on them. This avoids infinite
5136   // recursion, since the analysis of widening casts can require loop
5137   // exit condition information for overflow checking, which would
5138   // lead back here.
5139   if (getTypeSizeInBits(LHS->getType()) <
5140       getTypeSizeInBits(ICI->getOperand(0)->getType()))
5141     return false;
5142 
5143   // Now that we found a conditional branch that dominates the loop, check to
5144   // see if it is the comparison we are looking for.
5145   ICmpInst::Predicate FoundPred;
5146   if (Inverse)
5147     FoundPred = ICI->getInversePredicate();
5148   else
5149     FoundPred = ICI->getPredicate();
5150 
5151   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5152   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5153 
5154   // Balance the types. The case where FoundLHS' type is wider than
5155   // LHS' type is checked for above.
5156   if (getTypeSizeInBits(LHS->getType()) >
5157       getTypeSizeInBits(FoundLHS->getType())) {
5158     if (CmpInst::isSigned(Pred)) {
5159       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5160       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5161     } else {
5162       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5163       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5164     }
5165   }
5166 
5167   // Canonicalize the query to match the way instcombine will have
5168   // canonicalized the comparison.
5169   if (SimplifyICmpOperands(Pred, LHS, RHS))
5170     if (LHS == RHS)
5171       return CmpInst::isTrueWhenEqual(Pred);
5172   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5173     if (FoundLHS == FoundRHS)
5174       return CmpInst::isFalseWhenEqual(Pred);
5175 
5176   // Check to see if we can make the LHS or RHS match.
5177   if (LHS == FoundRHS || RHS == FoundLHS) {
5178     if (isa<SCEVConstant>(RHS)) {
5179       std::swap(FoundLHS, FoundRHS);
5180       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5181     } else {
5182       std::swap(LHS, RHS);
5183       Pred = ICmpInst::getSwappedPredicate(Pred);
5184     }
5185   }
5186 
5187   // Check whether the found predicate is the same as the desired predicate.
5188   if (FoundPred == Pred)
5189     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5190 
5191   // Check whether swapping the found predicate makes it the same as the
5192   // desired predicate.
5193   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5194     if (isa<SCEVConstant>(RHS))
5195       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5196     else
5197       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5198                                    RHS, LHS, FoundLHS, FoundRHS);
5199   }
5200 
5201   // Check whether the actual condition is beyond sufficient.
5202   if (FoundPred == ICmpInst::ICMP_EQ)
5203     if (ICmpInst::isTrueWhenEqual(Pred))
5204       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5205         return true;
5206   if (Pred == ICmpInst::ICMP_NE)
5207     if (!ICmpInst::isTrueWhenEqual(FoundPred))
5208       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5209         return true;
5210 
5211   // Otherwise assume the worst.
5212   return false;
5213 }
5214 
5215 /// isImpliedCondOperands - Test whether the condition described by Pred,
5216 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5217 /// and FoundRHS is true.
5218 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5219                                             const SCEV *LHS, const SCEV *RHS,
5220                                             const SCEV *FoundLHS,
5221                                             const SCEV *FoundRHS) {
5222   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5223                                      FoundLHS, FoundRHS) ||
5224          // ~x < ~y --> x > y
5225          isImpliedCondOperandsHelper(Pred, LHS, RHS,
5226                                      getNotSCEV(FoundRHS),
5227                                      getNotSCEV(FoundLHS));
5228 }
5229 
5230 /// isImpliedCondOperandsHelper - Test whether the condition described by
5231 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5232 /// FoundLHS, and FoundRHS is true.
5233 bool
5234 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5235                                              const SCEV *LHS, const SCEV *RHS,
5236                                              const SCEV *FoundLHS,
5237                                              const SCEV *FoundRHS) {
5238   switch (Pred) {
5239   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5240   case ICmpInst::ICMP_EQ:
5241   case ICmpInst::ICMP_NE:
5242     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5243       return true;
5244     break;
5245   case ICmpInst::ICMP_SLT:
5246   case ICmpInst::ICMP_SLE:
5247     if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5248         isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5249       return true;
5250     break;
5251   case ICmpInst::ICMP_SGT:
5252   case ICmpInst::ICMP_SGE:
5253     if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5254         isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5255       return true;
5256     break;
5257   case ICmpInst::ICMP_ULT:
5258   case ICmpInst::ICMP_ULE:
5259     if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5260         isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5261       return true;
5262     break;
5263   case ICmpInst::ICMP_UGT:
5264   case ICmpInst::ICMP_UGE:
5265     if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5266         isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5267       return true;
5268     break;
5269   }
5270 
5271   return false;
5272 }
5273 
5274 /// getBECount - Subtract the end and start values and divide by the step,
5275 /// rounding up, to get the number of times the backedge is executed. Return
5276 /// CouldNotCompute if an intermediate computation overflows.
5277 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5278                                         const SCEV *End,
5279                                         const SCEV *Step,
5280                                         bool NoWrap) {
5281   assert(!isKnownNegative(Step) &&
5282          "This code doesn't handle negative strides yet!");
5283 
5284   const Type *Ty = Start->getType();
5285   const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5286   const SCEV *Diff = getMinusSCEV(End, Start);
5287   const SCEV *RoundUp = getAddExpr(Step, NegOne);
5288 
5289   // Add an adjustment to the difference between End and Start so that
5290   // the division will effectively round up.
5291   const SCEV *Add = getAddExpr(Diff, RoundUp);
5292 
5293   if (!NoWrap) {
5294     // Check Add for unsigned overflow.
5295     // TODO: More sophisticated things could be done here.
5296     const Type *WideTy = IntegerType::get(getContext(),
5297                                           getTypeSizeInBits(Ty) + 1);
5298     const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5299     const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5300     const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5301     if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5302       return getCouldNotCompute();
5303   }
5304 
5305   return getUDivExpr(Add, Step);
5306 }
5307 
5308 /// HowManyLessThans - Return the number of times a backedge containing the
5309 /// specified less-than comparison will execute.  If not computable, return
5310 /// CouldNotCompute.
5311 ScalarEvolution::BackedgeTakenInfo
5312 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5313                                   const Loop *L, bool isSigned) {
5314   // Only handle:  "ADDREC < LoopInvariant".
5315   if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
5316 
5317   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5318   if (!AddRec || AddRec->getLoop() != L)
5319     return getCouldNotCompute();
5320 
5321   // Check to see if we have a flag which makes analysis easy.
5322   bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5323                            AddRec->hasNoUnsignedWrap();
5324 
5325   if (AddRec->isAffine()) {
5326     unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5327     const SCEV *Step = AddRec->getStepRecurrence(*this);
5328 
5329     if (Step->isZero())
5330       return getCouldNotCompute();
5331     if (Step->isOne()) {
5332       // With unit stride, the iteration never steps past the limit value.
5333     } else if (isKnownPositive(Step)) {
5334       // Test whether a positive iteration can step past the limit
5335       // value and past the maximum value for its type in a single step.
5336       // Note that it's not sufficient to check NoWrap here, because even
5337       // though the value after a wrap is undefined, it's not undefined
5338       // behavior, so if wrap does occur, the loop could either terminate or
5339       // loop infinitely, but in either case, the loop is guaranteed to
5340       // iterate at least until the iteration where the wrapping occurs.
5341       const SCEV *One = getConstant(Step->getType(), 1);
5342       if (isSigned) {
5343         APInt Max = APInt::getSignedMaxValue(BitWidth);
5344         if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5345               .slt(getSignedRange(RHS).getSignedMax()))
5346           return getCouldNotCompute();
5347       } else {
5348         APInt Max = APInt::getMaxValue(BitWidth);
5349         if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5350               .ult(getUnsignedRange(RHS).getUnsignedMax()))
5351           return getCouldNotCompute();
5352       }
5353     } else
5354       // TODO: Handle negative strides here and below.
5355       return getCouldNotCompute();
5356 
5357     // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5358     // m.  So, we count the number of iterations in which {n,+,s} < m is true.
5359     // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5360     // treat m-n as signed nor unsigned due to overflow possibility.
5361 
5362     // First, we get the value of the LHS in the first iteration: n
5363     const SCEV *Start = AddRec->getOperand(0);
5364 
5365     // Determine the minimum constant start value.
5366     const SCEV *MinStart = getConstant(isSigned ?
5367       getSignedRange(Start).getSignedMin() :
5368       getUnsignedRange(Start).getUnsignedMin());
5369 
5370     // If we know that the condition is true in order to enter the loop,
5371     // then we know that it will run exactly (m-n)/s times. Otherwise, we
5372     // only know that it will execute (max(m,n)-n)/s times. In both cases,
5373     // the division must round up.
5374     const SCEV *End = RHS;
5375     if (!isLoopEntryGuardedByCond(L,
5376                                   isSigned ? ICmpInst::ICMP_SLT :
5377                                              ICmpInst::ICMP_ULT,
5378                                   getMinusSCEV(Start, Step), RHS))
5379       End = isSigned ? getSMaxExpr(RHS, Start)
5380                      : getUMaxExpr(RHS, Start);
5381 
5382     // Determine the maximum constant end value.
5383     const SCEV *MaxEnd = getConstant(isSigned ?
5384       getSignedRange(End).getSignedMax() :
5385       getUnsignedRange(End).getUnsignedMax());
5386 
5387     // If MaxEnd is within a step of the maximum integer value in its type,
5388     // adjust it down to the minimum value which would produce the same effect.
5389     // This allows the subsequent ceiling division of (N+(step-1))/step to
5390     // compute the correct value.
5391     const SCEV *StepMinusOne = getMinusSCEV(Step,
5392                                             getConstant(Step->getType(), 1));
5393     MaxEnd = isSigned ?
5394       getSMinExpr(MaxEnd,
5395                   getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5396                                StepMinusOne)) :
5397       getUMinExpr(MaxEnd,
5398                   getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5399                                StepMinusOne));
5400 
5401     // Finally, we subtract these two values and divide, rounding up, to get
5402     // the number of times the backedge is executed.
5403     const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5404 
5405     // The maximum backedge count is similar, except using the minimum start
5406     // value and the maximum end value.
5407     const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
5408 
5409     return BackedgeTakenInfo(BECount, MaxBECount);
5410   }
5411 
5412   return getCouldNotCompute();
5413 }
5414 
5415 /// getNumIterationsInRange - Return the number of iterations of this loop that
5416 /// produce values in the specified constant range.  Another way of looking at
5417 /// this is that it returns the first iteration number where the value is not in
5418 /// the condition, thus computing the exit count. If the iteration count can't
5419 /// be computed, an instance of SCEVCouldNotCompute is returned.
5420 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5421                                                     ScalarEvolution &SE) const {
5422   if (Range.isFullSet())  // Infinite loop.
5423     return SE.getCouldNotCompute();
5424 
5425   // If the start is a non-zero constant, shift the range to simplify things.
5426   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5427     if (!SC->getValue()->isZero()) {
5428       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5429       Operands[0] = SE.getConstant(SC->getType(), 0);
5430       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
5431       if (const SCEVAddRecExpr *ShiftedAddRec =
5432             dyn_cast<SCEVAddRecExpr>(Shifted))
5433         return ShiftedAddRec->getNumIterationsInRange(
5434                            Range.subtract(SC->getValue()->getValue()), SE);
5435       // This is strange and shouldn't happen.
5436       return SE.getCouldNotCompute();
5437     }
5438 
5439   // The only time we can solve this is when we have all constant indices.
5440   // Otherwise, we cannot determine the overflow conditions.
5441   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5442     if (!isa<SCEVConstant>(getOperand(i)))
5443       return SE.getCouldNotCompute();
5444 
5445 
5446   // Okay at this point we know that all elements of the chrec are constants and
5447   // that the start element is zero.
5448 
5449   // First check to see if the range contains zero.  If not, the first
5450   // iteration exits.
5451   unsigned BitWidth = SE.getTypeSizeInBits(getType());
5452   if (!Range.contains(APInt(BitWidth, 0)))
5453     return SE.getConstant(getType(), 0);
5454 
5455   if (isAffine()) {
5456     // If this is an affine expression then we have this situation:
5457     //   Solve {0,+,A} in Range  ===  Ax in Range
5458 
5459     // We know that zero is in the range.  If A is positive then we know that
5460     // the upper value of the range must be the first possible exit value.
5461     // If A is negative then the lower of the range is the last possible loop
5462     // value.  Also note that we already checked for a full range.
5463     APInt One(BitWidth,1);
5464     APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5465     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5466 
5467     // The exit value should be (End+A)/A.
5468     APInt ExitVal = (End + A).udiv(A);
5469     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5470 
5471     // Evaluate at the exit value.  If we really did fall out of the valid
5472     // range, then we computed our trip count, otherwise wrap around or other
5473     // things must have happened.
5474     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5475     if (Range.contains(Val->getValue()))
5476       return SE.getCouldNotCompute();  // Something strange happened
5477 
5478     // Ensure that the previous value is in the range.  This is a sanity check.
5479     assert(Range.contains(
5480            EvaluateConstantChrecAtConstant(this,
5481            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5482            "Linear scev computation is off in a bad way!");
5483     return SE.getConstant(ExitValue);
5484   } else if (isQuadratic()) {
5485     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5486     // quadratic equation to solve it.  To do this, we must frame our problem in
5487     // terms of figuring out when zero is crossed, instead of when
5488     // Range.getUpper() is crossed.
5489     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5490     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5491     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5492 
5493     // Next, solve the constructed addrec
5494     std::pair<const SCEV *,const SCEV *> Roots =
5495       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5496     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5497     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5498     if (R1) {
5499       // Pick the smallest positive root value.
5500       if (ConstantInt *CB =
5501           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5502                          R1->getValue(), R2->getValue()))) {
5503         if (CB->getZExtValue() == false)
5504           std::swap(R1, R2);   // R1 is the minimum root now.
5505 
5506         // Make sure the root is not off by one.  The returned iteration should
5507         // not be in the range, but the previous one should be.  When solving
5508         // for "X*X < 5", for example, we should not return a root of 2.
5509         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5510                                                              R1->getValue(),
5511                                                              SE);
5512         if (Range.contains(R1Val->getValue())) {
5513           // The next iteration must be out of the range...
5514           ConstantInt *NextVal =
5515                 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5516 
5517           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5518           if (!Range.contains(R1Val->getValue()))
5519             return SE.getConstant(NextVal);
5520           return SE.getCouldNotCompute();  // Something strange happened
5521         }
5522 
5523         // If R1 was not in the range, then it is a good return value.  Make
5524         // sure that R1-1 WAS in the range though, just in case.
5525         ConstantInt *NextVal =
5526                ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5527         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5528         if (Range.contains(R1Val->getValue()))
5529           return R1;
5530         return SE.getCouldNotCompute();  // Something strange happened
5531       }
5532     }
5533   }
5534 
5535   return SE.getCouldNotCompute();
5536 }
5537 
5538 
5539 
5540 //===----------------------------------------------------------------------===//
5541 //                   SCEVCallbackVH Class Implementation
5542 //===----------------------------------------------------------------------===//
5543 
5544 void ScalarEvolution::SCEVCallbackVH::deleted() {
5545   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5546   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5547     SE->ConstantEvolutionLoopExitValue.erase(PN);
5548   SE->Scalars.erase(getValPtr());
5549   // this now dangles!
5550 }
5551 
5552 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
5553   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5554 
5555   // Forget all the expressions associated with users of the old value,
5556   // so that future queries will recompute the expressions using the new
5557   // value.
5558   SmallVector<User *, 16> Worklist;
5559   SmallPtrSet<User *, 8> Visited;
5560   Value *Old = getValPtr();
5561   bool DeleteOld = false;
5562   for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5563        UI != UE; ++UI)
5564     Worklist.push_back(*UI);
5565   while (!Worklist.empty()) {
5566     User *U = Worklist.pop_back_val();
5567     // Deleting the Old value will cause this to dangle. Postpone
5568     // that until everything else is done.
5569     if (U == Old) {
5570       DeleteOld = true;
5571       continue;
5572     }
5573     if (!Visited.insert(U))
5574       continue;
5575     if (PHINode *PN = dyn_cast<PHINode>(U))
5576       SE->ConstantEvolutionLoopExitValue.erase(PN);
5577     SE->Scalars.erase(U);
5578     for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5579          UI != UE; ++UI)
5580       Worklist.push_back(*UI);
5581   }
5582   // Delete the Old value if it (indirectly) references itself.
5583   if (DeleteOld) {
5584     if (PHINode *PN = dyn_cast<PHINode>(Old))
5585       SE->ConstantEvolutionLoopExitValue.erase(PN);
5586     SE->Scalars.erase(Old);
5587     // this now dangles!
5588   }
5589   // this may dangle!
5590 }
5591 
5592 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5593   : CallbackVH(V), SE(se) {}
5594 
5595 //===----------------------------------------------------------------------===//
5596 //                   ScalarEvolution Class Implementation
5597 //===----------------------------------------------------------------------===//
5598 
5599 ScalarEvolution::ScalarEvolution()
5600   : FunctionPass(&ID), CurAllocationSequenceNumber(0) {
5601 }
5602 
5603 bool ScalarEvolution::runOnFunction(Function &F) {
5604   this->F = &F;
5605   LI = &getAnalysis<LoopInfo>();
5606   TD = getAnalysisIfAvailable<TargetData>();
5607   DT = &getAnalysis<DominatorTree>();
5608   return false;
5609 }
5610 
5611 void ScalarEvolution::releaseMemory() {
5612   Scalars.clear();
5613   BackedgeTakenCounts.clear();
5614   ConstantEvolutionLoopExitValue.clear();
5615   ValuesAtScopes.clear();
5616   UniqueSCEVs.clear();
5617   SCEVAllocator.Reset();
5618 }
5619 
5620 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5621   AU.setPreservesAll();
5622   AU.addRequiredTransitive<LoopInfo>();
5623   AU.addRequiredTransitive<DominatorTree>();
5624 }
5625 
5626 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5627   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5628 }
5629 
5630 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5631                           const Loop *L) {
5632   // Print all inner loops first
5633   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5634     PrintLoopInfo(OS, SE, *I);
5635 
5636   OS << "Loop ";
5637   WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5638   OS << ": ";
5639 
5640   SmallVector<BasicBlock *, 8> ExitBlocks;
5641   L->getExitBlocks(ExitBlocks);
5642   if (ExitBlocks.size() != 1)
5643     OS << "<multiple exits> ";
5644 
5645   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5646     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5647   } else {
5648     OS << "Unpredictable backedge-taken count. ";
5649   }
5650 
5651   OS << "\n"
5652         "Loop ";
5653   WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5654   OS << ": ";
5655 
5656   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5657     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5658   } else {
5659     OS << "Unpredictable max backedge-taken count. ";
5660   }
5661 
5662   OS << "\n";
5663 }
5664 
5665 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
5666   // ScalarEvolution's implementation of the print method is to print
5667   // out SCEV values of all instructions that are interesting. Doing
5668   // this potentially causes it to create new SCEV objects though,
5669   // which technically conflicts with the const qualifier. This isn't
5670   // observable from outside the class though, so casting away the
5671   // const isn't dangerous.
5672   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
5673 
5674   OS << "Classifying expressions for: ";
5675   WriteAsOperand(OS, F, /*PrintType=*/false);
5676   OS << "\n";
5677   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5678     if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
5679       OS << *I << '\n';
5680       OS << "  -->  ";
5681       const SCEV *SV = SE.getSCEV(&*I);
5682       SV->print(OS);
5683 
5684       const Loop *L = LI->getLoopFor((*I).getParent());
5685 
5686       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5687       if (AtUse != SV) {
5688         OS << "  -->  ";
5689         AtUse->print(OS);
5690       }
5691 
5692       if (L) {
5693         OS << "\t\t" "Exits: ";
5694         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5695         if (!ExitValue->isLoopInvariant(L)) {
5696           OS << "<<Unknown>>";
5697         } else {
5698           OS << *ExitValue;
5699         }
5700       }
5701 
5702       OS << "\n";
5703     }
5704 
5705   OS << "Determining loop execution counts for: ";
5706   WriteAsOperand(OS, F, /*PrintType=*/false);
5707   OS << "\n";
5708   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5709     PrintLoopInfo(OS, &SE, *I);
5710 }
5711 
5712