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