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