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