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