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