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