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