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