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