5300dbe49f3d2a1f50142efb40b109fe6cc6b0ab
[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 SCEVHandle
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/Analysis/ConstantFolding.h"
69 #include "llvm/Analysis/Dominators.h"
70 #include "llvm/Analysis/LoopInfo.h"
71 #include "llvm/Assembly/Writer.h"
72 #include "llvm/Target/TargetData.h"
73 #include "llvm/Transforms/Scalar.h"
74 #include "llvm/Support/CFG.h"
75 #include "llvm/Support/CommandLine.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/ConstantRange.h"
78 #include "llvm/Support/GetElementPtrTypeIterator.h"
79 #include "llvm/Support/InstIterator.h"
80 #include "llvm/Support/ManagedStatic.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 <ostream>
86 #include <algorithm>
87 #include <cmath>
88 using namespace llvm;
89
90 STATISTIC(NumArrayLenItCounts,
91           "Number of trip counts computed with array length");
92 STATISTIC(NumTripCountsComputed,
93           "Number of loops with predictable loop counts");
94 STATISTIC(NumTripCountsNotComputed,
95           "Number of loops without predictable loop counts");
96 STATISTIC(NumBruteForceTripCountsComputed,
97           "Number of loops with trip counts computed by force");
98
99 static cl::opt<unsigned>
100 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101                         cl::desc("Maximum number of iterations SCEV will "
102                                  "symbolically execute a constant 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 SCEV::~SCEV() {}
117 void SCEV::dump() const {
118   print(errs());
119   errs() << '\n';
120 }
121
122 void SCEV::print(std::ostream &o) const {
123   raw_os_ostream OS(o);
124   print(OS);
125 }
126
127 bool SCEV::isZero() const {
128   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129     return SC->getValue()->isZero();
130   return false;
131 }
132
133
134 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
135
136 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
137   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
138   return false;
139 }
140
141 const Type *SCEVCouldNotCompute::getType() const {
142   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
143   return 0;
144 }
145
146 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
147   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
148   return false;
149 }
150
151 SCEVHandle SCEVCouldNotCompute::
152 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
153                                   const SCEVHandle &Conc,
154                                   ScalarEvolution &SE) const {
155   return this;
156 }
157
158 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
159   OS << "***COULDNOTCOMPUTE***";
160 }
161
162 bool SCEVCouldNotCompute::classof(const SCEV *S) {
163   return S->getSCEVType() == scCouldNotCompute;
164 }
165
166
167 // SCEVConstants - Only allow the creation of one SCEVConstant for any
168 // particular value.  Don't use a SCEVHandle here, or else the object will
169 // never be deleted!
170 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
171
172
173 SCEVConstant::~SCEVConstant() {
174   SCEVConstants->erase(V);
175 }
176
177 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
178   SCEVConstant *&R = (*SCEVConstants)[V];
179   if (R == 0) R = new SCEVConstant(V);
180   return R;
181 }
182
183 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
184   return getConstant(ConstantInt::get(Val));
185 }
186
187 const Type *SCEVConstant::getType() const { return V->getType(); }
188
189 void SCEVConstant::print(raw_ostream &OS) const {
190   WriteAsOperand(OS, V, false);
191 }
192
193 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
194 // particular input.  Don't use a SCEVHandle here, or else the object will
195 // never be deleted!
196 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, 
197                      SCEVTruncateExpr*> > SCEVTruncates;
198
199 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
200   : SCEV(scTruncate), Op(op), Ty(ty) {
201   assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
202          (Ty->isInteger() || isa<PointerType>(Ty)) &&
203          "Cannot truncate non-integer value!");
204 }
205
206 SCEVTruncateExpr::~SCEVTruncateExpr() {
207   SCEVTruncates->erase(std::make_pair(Op, Ty));
208 }
209
210 bool SCEVTruncateExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
211   return Op->dominates(BB, DT);
212 }
213
214 void SCEVTruncateExpr::print(raw_ostream &OS) const {
215   OS << "(truncate " << *Op << " to " << *Ty << ")";
216 }
217
218 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
219 // particular input.  Don't use a SCEVHandle here, or else the object will never
220 // be deleted!
221 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
222                      SCEVZeroExtendExpr*> > SCEVZeroExtends;
223
224 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
225   : SCEV(scZeroExtend), Op(op), Ty(ty) {
226   assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
227          (Ty->isInteger() || isa<PointerType>(Ty)) &&
228          "Cannot zero extend non-integer value!");
229 }
230
231 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
232   SCEVZeroExtends->erase(std::make_pair(Op, Ty));
233 }
234
235 bool SCEVZeroExtendExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
236   return Op->dominates(BB, DT);
237 }
238
239 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
240   OS << "(zeroextend " << *Op << " to " << *Ty << ")";
241 }
242
243 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
244 // particular input.  Don't use a SCEVHandle here, or else the object will never
245 // be deleted!
246 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
247                      SCEVSignExtendExpr*> > SCEVSignExtends;
248
249 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
250   : SCEV(scSignExtend), Op(op), Ty(ty) {
251   assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
252          (Ty->isInteger() || isa<PointerType>(Ty)) &&
253          "Cannot sign extend non-integer value!");
254 }
255
256 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
257   SCEVSignExtends->erase(std::make_pair(Op, Ty));
258 }
259
260 bool SCEVSignExtendExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
261   return Op->dominates(BB, DT);
262 }
263
264 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
265   OS << "(signextend " << *Op << " to " << *Ty << ")";
266 }
267
268 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
269 // particular input.  Don't use a SCEVHandle here, or else the object will never
270 // be deleted!
271 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
272                      SCEVCommutativeExpr*> > SCEVCommExprs;
273
274 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
275   SCEVCommExprs->erase(std::make_pair(getSCEVType(),
276                                       std::vector<SCEV*>(Operands.begin(),
277                                                          Operands.end())));
278 }
279
280 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
281   assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
282   const char *OpStr = getOperationStr();
283   OS << "(" << *Operands[0];
284   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
285     OS << OpStr << *Operands[i];
286   OS << ")";
287 }
288
289 SCEVHandle SCEVCommutativeExpr::
290 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
291                                   const SCEVHandle &Conc,
292                                   ScalarEvolution &SE) const {
293   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
294     SCEVHandle H =
295       getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
296     if (H != getOperand(i)) {
297       std::vector<SCEVHandle> NewOps;
298       NewOps.reserve(getNumOperands());
299       for (unsigned j = 0; j != i; ++j)
300         NewOps.push_back(getOperand(j));
301       NewOps.push_back(H);
302       for (++i; i != e; ++i)
303         NewOps.push_back(getOperand(i)->
304                          replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
305
306       if (isa<SCEVAddExpr>(this))
307         return SE.getAddExpr(NewOps);
308       else if (isa<SCEVMulExpr>(this))
309         return SE.getMulExpr(NewOps);
310       else if (isa<SCEVSMaxExpr>(this))
311         return SE.getSMaxExpr(NewOps);
312       else if (isa<SCEVUMaxExpr>(this))
313         return SE.getUMaxExpr(NewOps);
314       else
315         assert(0 && "Unknown commutative expr!");
316     }
317   }
318   return this;
319 }
320
321 bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
322   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
323     if (!getOperand(i)->dominates(BB, DT))
324       return false;
325   }
326   return true;
327 }
328
329
330 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
331 // input.  Don't use a SCEVHandle here, or else the object will never be
332 // deleted!
333 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>, 
334                      SCEVUDivExpr*> > SCEVUDivs;
335
336 SCEVUDivExpr::~SCEVUDivExpr() {
337   SCEVUDivs->erase(std::make_pair(LHS, RHS));
338 }
339
340 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
341   return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
342 }
343
344 void SCEVUDivExpr::print(raw_ostream &OS) const {
345   OS << "(" << *LHS << " /u " << *RHS << ")";
346 }
347
348 const Type *SCEVUDivExpr::getType() const {
349   return LHS->getType();
350 }
351
352 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
353 // particular input.  Don't use a SCEVHandle here, or else the object will never
354 // be deleted!
355 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
356                      SCEVAddRecExpr*> > SCEVAddRecExprs;
357
358 SCEVAddRecExpr::~SCEVAddRecExpr() {
359   SCEVAddRecExprs->erase(std::make_pair(L,
360                                         std::vector<SCEV*>(Operands.begin(),
361                                                            Operands.end())));
362 }
363
364 bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
365   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
366     if (!getOperand(i)->dominates(BB, DT))
367       return false;
368   }
369   return true;
370 }
371
372
373 SCEVHandle SCEVAddRecExpr::
374 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
375                                   const SCEVHandle &Conc,
376                                   ScalarEvolution &SE) const {
377   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
378     SCEVHandle H =
379       getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
380     if (H != getOperand(i)) {
381       std::vector<SCEVHandle> NewOps;
382       NewOps.reserve(getNumOperands());
383       for (unsigned j = 0; j != i; ++j)
384         NewOps.push_back(getOperand(j));
385       NewOps.push_back(H);
386       for (++i; i != e; ++i)
387         NewOps.push_back(getOperand(i)->
388                          replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
389
390       return SE.getAddRecExpr(NewOps, L);
391     }
392   }
393   return this;
394 }
395
396
397 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
398   // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
399   // contain L and if the start is invariant.
400   return !QueryLoop->contains(L->getHeader()) &&
401          getOperand(0)->isLoopInvariant(QueryLoop);
402 }
403
404
405 void SCEVAddRecExpr::print(raw_ostream &OS) const {
406   OS << "{" << *Operands[0];
407   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
408     OS << ",+," << *Operands[i];
409   OS << "}<" << L->getHeader()->getName() + ">";
410 }
411
412 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
413 // value.  Don't use a SCEVHandle here, or else the object will never be
414 // deleted!
415 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
416
417 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
418
419 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
420   // All non-instruction values are loop invariant.  All instructions are loop
421   // invariant if they are not contained in the specified loop.
422   if (Instruction *I = dyn_cast<Instruction>(V))
423     return !L->contains(I->getParent());
424   return true;
425 }
426
427 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
428   if (Instruction *I = dyn_cast<Instruction>(getValue()))
429     return DT->dominates(I->getParent(), BB);
430   return true;
431 }
432
433 const Type *SCEVUnknown::getType() const {
434   return V->getType();
435 }
436
437 void SCEVUnknown::print(raw_ostream &OS) const {
438   if (isa<PointerType>(V->getType()))
439     OS << "(ptrtoint " << *V->getType() << " ";
440   WriteAsOperand(OS, V, false);
441   if (isa<PointerType>(V->getType()))
442     OS << " to iPTR)";
443 }
444
445 //===----------------------------------------------------------------------===//
446 //                               SCEV Utilities
447 //===----------------------------------------------------------------------===//
448
449 namespace {
450   /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
451   /// than the complexity of the RHS.  This comparator is used to canonicalize
452   /// expressions.
453   struct VISIBILITY_HIDDEN SCEVComplexityCompare {
454     bool operator()(const SCEV *LHS, const SCEV *RHS) const {
455       return LHS->getSCEVType() < RHS->getSCEVType();
456     }
457   };
458 }
459
460 /// GroupByComplexity - Given a list of SCEV objects, order them by their
461 /// complexity, and group objects of the same complexity together by value.
462 /// When this routine is finished, we know that any duplicates in the vector are
463 /// consecutive and that complexity is monotonically increasing.
464 ///
465 /// Note that we go take special precautions to ensure that we get determinstic
466 /// results from this routine.  In other words, we don't want the results of
467 /// this to depend on where the addresses of various SCEV objects happened to
468 /// land in memory.
469 ///
470 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
471   if (Ops.size() < 2) return;  // Noop
472   if (Ops.size() == 2) {
473     // This is the common case, which also happens to be trivially simple.
474     // Special case it.
475     if (SCEVComplexityCompare()(Ops[1], Ops[0]))
476       std::swap(Ops[0], Ops[1]);
477     return;
478   }
479
480   // Do the rough sort by complexity.
481   std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
482
483   // Now that we are sorted by complexity, group elements of the same
484   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
485   // be extremely short in practice.  Note that we take this approach because we
486   // do not want to depend on the addresses of the objects we are grouping.
487   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
488     SCEV *S = Ops[i];
489     unsigned Complexity = S->getSCEVType();
490
491     // If there are any objects of the same complexity and same value as this
492     // one, group them.
493     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
494       if (Ops[j] == S) { // Found a duplicate.
495         // Move it to immediately after i'th element.
496         std::swap(Ops[i+1], Ops[j]);
497         ++i;   // no need to rescan it.
498         if (i == e-2) return;  // Done!
499       }
500     }
501   }
502 }
503
504
505
506 //===----------------------------------------------------------------------===//
507 //                      Simple SCEV method implementations
508 //===----------------------------------------------------------------------===//
509
510 /// BinomialCoefficient - Compute BC(It, K).  The result has width W.
511 // Assume, K > 0.
512 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
513                                       ScalarEvolution &SE,
514                                       const Type* ResultTy) {
515   // Handle the simplest case efficiently.
516   if (K == 1)
517     return SE.getTruncateOrZeroExtend(It, ResultTy);
518
519   // We are using the following formula for BC(It, K):
520   //
521   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
522   //
523   // Suppose, W is the bitwidth of the return value.  We must be prepared for
524   // overflow.  Hence, we must assure that the result of our computation is
525   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
526   // safe in modular arithmetic.
527   //
528   // However, this code doesn't use exactly that formula; the formula it uses
529   // is something like the following, where T is the number of factors of 2 in 
530   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
531   // exponentiation:
532   //
533   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
534   //
535   // This formula is trivially equivalent to the previous formula.  However,
536   // this formula can be implemented much more efficiently.  The trick is that
537   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
538   // arithmetic.  To do exact division in modular arithmetic, all we have
539   // to do is multiply by the inverse.  Therefore, this step can be done at
540   // width W.
541   // 
542   // The next issue is how to safely do the division by 2^T.  The way this
543   // is done is by doing the multiplication step at a width of at least W + T
544   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
545   // when we perform the division by 2^T (which is equivalent to a right shift
546   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
547   // truncated out after the division by 2^T.
548   //
549   // In comparison to just directly using the first formula, this technique
550   // is much more efficient; using the first formula requires W * K bits,
551   // but this formula less than W + K bits. Also, the first formula requires
552   // a division step, whereas this formula only requires multiplies and shifts.
553   //
554   // It doesn't matter whether the subtraction step is done in the calculation
555   // width or the input iteration count's width; if the subtraction overflows,
556   // the result must be zero anyway.  We prefer here to do it in the width of
557   // the induction variable because it helps a lot for certain cases; CodeGen
558   // isn't smart enough to ignore the overflow, which leads to much less
559   // efficient code if the width of the subtraction is wider than the native
560   // register width.
561   //
562   // (It's possible to not widen at all by pulling out factors of 2 before
563   // the multiplication; for example, K=2 can be calculated as
564   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
565   // extra arithmetic, so it's not an obvious win, and it gets
566   // much more complicated for K > 3.)
567
568   // Protection from insane SCEVs; this bound is conservative,
569   // but it probably doesn't matter.
570   if (K > 1000)
571     return SE.getCouldNotCompute();
572
573   unsigned W = SE.getTypeSizeInBits(ResultTy);
574
575   // Calculate K! / 2^T and T; we divide out the factors of two before
576   // multiplying for calculating K! / 2^T to avoid overflow.
577   // Other overflow doesn't matter because we only care about the bottom
578   // W bits of the result.
579   APInt OddFactorial(W, 1);
580   unsigned T = 1;
581   for (unsigned i = 3; i <= K; ++i) {
582     APInt Mult(W, i);
583     unsigned TwoFactors = Mult.countTrailingZeros();
584     T += TwoFactors;
585     Mult = Mult.lshr(TwoFactors);
586     OddFactorial *= Mult;
587   }
588
589   // We need at least W + T bits for the multiplication step
590   unsigned CalculationBits = W + T;
591
592   // Calcuate 2^T, at width T+W.
593   APInt DivFactor = APInt(CalculationBits, 1).shl(T);
594
595   // Calculate the multiplicative inverse of K! / 2^T;
596   // this multiplication factor will perform the exact division by
597   // K! / 2^T.
598   APInt Mod = APInt::getSignedMinValue(W+1);
599   APInt MultiplyFactor = OddFactorial.zext(W+1);
600   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
601   MultiplyFactor = MultiplyFactor.trunc(W);
602
603   // Calculate the product, at width T+W
604   const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
605   SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
606   for (unsigned i = 1; i != K; ++i) {
607     SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
608     Dividend = SE.getMulExpr(Dividend,
609                              SE.getTruncateOrZeroExtend(S, CalculationTy));
610   }
611
612   // Divide by 2^T
613   SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
614
615   // Truncate the result, and divide by K! / 2^T.
616
617   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
618                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
619 }
620
621 /// evaluateAtIteration - Return the value of this chain of recurrences at
622 /// the specified iteration number.  We can evaluate this recurrence by
623 /// multiplying each element in the chain by the binomial coefficient
624 /// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
625 ///
626 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
627 ///
628 /// where BC(It, k) stands for binomial coefficient.
629 ///
630 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
631                                                ScalarEvolution &SE) const {
632   SCEVHandle Result = getStart();
633   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
634     // The computation is correct in the face of overflow provided that the
635     // multiplication is performed _after_ the evaluation of the binomial
636     // coefficient.
637     SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
638     if (isa<SCEVCouldNotCompute>(Coeff))
639       return Coeff;
640
641     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
642   }
643   return Result;
644 }
645
646 //===----------------------------------------------------------------------===//
647 //                    SCEV Expression folder implementations
648 //===----------------------------------------------------------------------===//
649
650 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
651   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
652          "This is not a truncating conversion!");
653
654   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
655     return getUnknown(
656         ConstantExpr::getTrunc(SC->getValue(), Ty));
657
658   // If the input value is a chrec scev made out of constants, truncate
659   // all of the constants.
660   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
661     std::vector<SCEVHandle> Operands;
662     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
663       // FIXME: This should allow truncation of other expression types!
664       if (isa<SCEVConstant>(AddRec->getOperand(i)))
665         Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
666       else
667         break;
668     if (Operands.size() == AddRec->getNumOperands())
669       return getAddRecExpr(Operands, AddRec->getLoop());
670   }
671
672   SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
673   if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
674   return Result;
675 }
676
677 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
678                                               const Type *Ty) {
679   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
680          "This is not an extending conversion!");
681
682   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
683     const Type *IntTy = getEffectiveSCEVType(Ty);
684     Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
685     if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
686     return getUnknown(C);
687   }
688
689   // FIXME: If the input value is a chrec scev, and we can prove that the value
690   // did not overflow the old, smaller, value, we can zero extend all of the
691   // operands (often constants).  This would allow analysis of something like
692   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
693
694   SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
695   if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
696   return Result;
697 }
698
699 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
700   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
701          "This is not an extending conversion!");
702
703   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
704     const Type *IntTy = getEffectiveSCEVType(Ty);
705     Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
706     if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
707     return getUnknown(C);
708   }
709
710   // FIXME: If the input value is a chrec scev, and we can prove that the value
711   // did not overflow the old, smaller, value, we can sign extend all of the
712   // operands (often constants).  This would allow analysis of something like
713   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
714
715   SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
716   if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
717   return Result;
718 }
719
720 // get - Get a canonical add expression, or something simpler if possible.
721 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
722   assert(!Ops.empty() && "Cannot get empty add!");
723   if (Ops.size() == 1) return Ops[0];
724
725   // Sort by complexity, this groups all similar expression types together.
726   GroupByComplexity(Ops);
727
728   // If there are any constants, fold them together.
729   unsigned Idx = 0;
730   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
731     ++Idx;
732     assert(Idx < Ops.size());
733     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
734       // We found two constants, fold them together!
735       ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() + 
736                                            RHSC->getValue()->getValue());
737       Ops[0] = getConstant(Fold);
738       Ops.erase(Ops.begin()+1);  // Erase the folded element
739       if (Ops.size() == 1) return Ops[0];
740       LHSC = cast<SCEVConstant>(Ops[0]);
741     }
742
743     // If we are left with a constant zero being added, strip it off.
744     if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
745       Ops.erase(Ops.begin());
746       --Idx;
747     }
748   }
749
750   if (Ops.size() == 1) return Ops[0];
751
752   // Okay, check to see if the same value occurs in the operand list twice.  If
753   // so, merge them together into an multiply expression.  Since we sorted the
754   // list, these values are required to be adjacent.
755   const Type *Ty = Ops[0]->getType();
756   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
757     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
758       // Found a match, merge the two values into a multiply, and add any
759       // remaining values to the result.
760       SCEVHandle Two = getIntegerSCEV(2, Ty);
761       SCEVHandle Mul = getMulExpr(Ops[i], Two);
762       if (Ops.size() == 2)
763         return Mul;
764       Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
765       Ops.push_back(Mul);
766       return getAddExpr(Ops);
767     }
768
769   // Now we know the first non-constant operand.  Skip past any cast SCEVs.
770   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
771     ++Idx;
772
773   // If there are add operands they would be next.
774   if (Idx < Ops.size()) {
775     bool DeletedAdd = false;
776     while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
777       // If we have an add, expand the add operands onto the end of the operands
778       // list.
779       Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
780       Ops.erase(Ops.begin()+Idx);
781       DeletedAdd = true;
782     }
783
784     // If we deleted at least one add, we added operands to the end of the list,
785     // and they are not necessarily sorted.  Recurse to resort and resimplify
786     // any operands we just aquired.
787     if (DeletedAdd)
788       return getAddExpr(Ops);
789   }
790
791   // Skip over the add expression until we get to a multiply.
792   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
793     ++Idx;
794
795   // If we are adding something to a multiply expression, make sure the
796   // something is not already an operand of the multiply.  If so, merge it into
797   // the multiply.
798   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
799     SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
800     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
801       SCEV *MulOpSCEV = Mul->getOperand(MulOp);
802       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
803         if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
804           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
805           SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
806           if (Mul->getNumOperands() != 2) {
807             // If the multiply has more than two operands, we must get the
808             // Y*Z term.
809             std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
810             MulOps.erase(MulOps.begin()+MulOp);
811             InnerMul = getMulExpr(MulOps);
812           }
813           SCEVHandle One = getIntegerSCEV(1, Ty);
814           SCEVHandle AddOne = getAddExpr(InnerMul, One);
815           SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
816           if (Ops.size() == 2) return OuterMul;
817           if (AddOp < Idx) {
818             Ops.erase(Ops.begin()+AddOp);
819             Ops.erase(Ops.begin()+Idx-1);
820           } else {
821             Ops.erase(Ops.begin()+Idx);
822             Ops.erase(Ops.begin()+AddOp-1);
823           }
824           Ops.push_back(OuterMul);
825           return getAddExpr(Ops);
826         }
827
828       // Check this multiply against other multiplies being added together.
829       for (unsigned OtherMulIdx = Idx+1;
830            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
831            ++OtherMulIdx) {
832         SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
833         // If MulOp occurs in OtherMul, we can fold the two multiplies
834         // together.
835         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
836              OMulOp != e; ++OMulOp)
837           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
838             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
839             SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
840             if (Mul->getNumOperands() != 2) {
841               std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
842               MulOps.erase(MulOps.begin()+MulOp);
843               InnerMul1 = getMulExpr(MulOps);
844             }
845             SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
846             if (OtherMul->getNumOperands() != 2) {
847               std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
848                                              OtherMul->op_end());
849               MulOps.erase(MulOps.begin()+OMulOp);
850               InnerMul2 = getMulExpr(MulOps);
851             }
852             SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
853             SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
854             if (Ops.size() == 2) return OuterMul;
855             Ops.erase(Ops.begin()+Idx);
856             Ops.erase(Ops.begin()+OtherMulIdx-1);
857             Ops.push_back(OuterMul);
858             return getAddExpr(Ops);
859           }
860       }
861     }
862   }
863
864   // If there are any add recurrences in the operands list, see if any other
865   // added values are loop invariant.  If so, we can fold them into the
866   // recurrence.
867   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
868     ++Idx;
869
870   // Scan over all recurrences, trying to fold loop invariants into them.
871   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
872     // Scan all of the other operands to this add and add them to the vector if
873     // they are loop invariant w.r.t. the recurrence.
874     std::vector<SCEVHandle> LIOps;
875     SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
876     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
877       if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
878         LIOps.push_back(Ops[i]);
879         Ops.erase(Ops.begin()+i);
880         --i; --e;
881       }
882
883     // If we found some loop invariants, fold them into the recurrence.
884     if (!LIOps.empty()) {
885       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
886       LIOps.push_back(AddRec->getStart());
887
888       std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
889       AddRecOps[0] = getAddExpr(LIOps);
890
891       SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
892       // If all of the other operands were loop invariant, we are done.
893       if (Ops.size() == 1) return NewRec;
894
895       // Otherwise, add the folded AddRec by the non-liv parts.
896       for (unsigned i = 0;; ++i)
897         if (Ops[i] == AddRec) {
898           Ops[i] = NewRec;
899           break;
900         }
901       return getAddExpr(Ops);
902     }
903
904     // Okay, if there weren't any loop invariants to be folded, check to see if
905     // there are multiple AddRec's with the same loop induction variable being
906     // added together.  If so, we can fold them.
907     for (unsigned OtherIdx = Idx+1;
908          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
909       if (OtherIdx != Idx) {
910         SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
911         if (AddRec->getLoop() == OtherAddRec->getLoop()) {
912           // Other + {A,+,B} + {C,+,D}  -->  Other + {A+C,+,B+D}
913           std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
914           for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
915             if (i >= NewOps.size()) {
916               NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
917                             OtherAddRec->op_end());
918               break;
919             }
920             NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
921           }
922           SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
923
924           if (Ops.size() == 2) return NewAddRec;
925
926           Ops.erase(Ops.begin()+Idx);
927           Ops.erase(Ops.begin()+OtherIdx-1);
928           Ops.push_back(NewAddRec);
929           return getAddExpr(Ops);
930         }
931       }
932
933     // Otherwise couldn't fold anything into this recurrence.  Move onto the
934     // next one.
935   }
936
937   // Okay, it looks like we really DO need an add expr.  Check to see if we
938   // already have one, otherwise create a new one.
939   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
940   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
941                                                                  SCEVOps)];
942   if (Result == 0) Result = new SCEVAddExpr(Ops);
943   return Result;
944 }
945
946
947 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
948   assert(!Ops.empty() && "Cannot get empty mul!");
949
950   // Sort by complexity, this groups all similar expression types together.
951   GroupByComplexity(Ops);
952
953   // If there are any constants, fold them together.
954   unsigned Idx = 0;
955   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
956
957     // C1*(C2+V) -> C1*C2 + C1*V
958     if (Ops.size() == 2)
959       if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
960         if (Add->getNumOperands() == 2 &&
961             isa<SCEVConstant>(Add->getOperand(0)))
962           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
963                             getMulExpr(LHSC, Add->getOperand(1)));
964
965
966     ++Idx;
967     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
968       // We found two constants, fold them together!
969       ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() * 
970                                            RHSC->getValue()->getValue());
971       Ops[0] = getConstant(Fold);
972       Ops.erase(Ops.begin()+1);  // Erase the folded element
973       if (Ops.size() == 1) return Ops[0];
974       LHSC = cast<SCEVConstant>(Ops[0]);
975     }
976
977     // If we are left with a constant one being multiplied, strip it off.
978     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
979       Ops.erase(Ops.begin());
980       --Idx;
981     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
982       // If we have a multiply of zero, it will always be zero.
983       return Ops[0];
984     }
985   }
986
987   // Skip over the add expression until we get to a multiply.
988   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
989     ++Idx;
990
991   if (Ops.size() == 1)
992     return Ops[0];
993
994   // If there are mul operands inline them all into this expression.
995   if (Idx < Ops.size()) {
996     bool DeletedMul = false;
997     while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
998       // If we have an mul, expand the mul operands onto the end of the operands
999       // list.
1000       Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1001       Ops.erase(Ops.begin()+Idx);
1002       DeletedMul = true;
1003     }
1004
1005     // If we deleted at least one mul, we added operands to the end of the list,
1006     // and they are not necessarily sorted.  Recurse to resort and resimplify
1007     // any operands we just aquired.
1008     if (DeletedMul)
1009       return getMulExpr(Ops);
1010   }
1011
1012   // If there are any add recurrences in the operands list, see if any other
1013   // added values are loop invariant.  If so, we can fold them into the
1014   // recurrence.
1015   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1016     ++Idx;
1017
1018   // Scan over all recurrences, trying to fold loop invariants into them.
1019   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1020     // Scan all of the other operands to this mul and add them to the vector if
1021     // they are loop invariant w.r.t. the recurrence.
1022     std::vector<SCEVHandle> LIOps;
1023     SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1024     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1025       if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1026         LIOps.push_back(Ops[i]);
1027         Ops.erase(Ops.begin()+i);
1028         --i; --e;
1029       }
1030
1031     // If we found some loop invariants, fold them into the recurrence.
1032     if (!LIOps.empty()) {
1033       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
1034       std::vector<SCEVHandle> NewOps;
1035       NewOps.reserve(AddRec->getNumOperands());
1036       if (LIOps.size() == 1) {
1037         SCEV *Scale = LIOps[0];
1038         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1039           NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1040       } else {
1041         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1042           std::vector<SCEVHandle> MulOps(LIOps);
1043           MulOps.push_back(AddRec->getOperand(i));
1044           NewOps.push_back(getMulExpr(MulOps));
1045         }
1046       }
1047
1048       SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1049
1050       // If all of the other operands were loop invariant, we are done.
1051       if (Ops.size() == 1) return NewRec;
1052
1053       // Otherwise, multiply the folded AddRec by the non-liv parts.
1054       for (unsigned i = 0;; ++i)
1055         if (Ops[i] == AddRec) {
1056           Ops[i] = NewRec;
1057           break;
1058         }
1059       return getMulExpr(Ops);
1060     }
1061
1062     // Okay, if there weren't any loop invariants to be folded, check to see if
1063     // there are multiple AddRec's with the same loop induction variable being
1064     // multiplied together.  If so, we can fold them.
1065     for (unsigned OtherIdx = Idx+1;
1066          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1067       if (OtherIdx != Idx) {
1068         SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1069         if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1070           // F * G  -->  {A,+,B} * {C,+,D}  -->  {A*C,+,F*D + G*B + B*D}
1071           SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1072           SCEVHandle NewStart = getMulExpr(F->getStart(),
1073                                                  G->getStart());
1074           SCEVHandle B = F->getStepRecurrence(*this);
1075           SCEVHandle D = G->getStepRecurrence(*this);
1076           SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1077                                           getMulExpr(G, B),
1078                                           getMulExpr(B, D));
1079           SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1080                                                F->getLoop());
1081           if (Ops.size() == 2) return NewAddRec;
1082
1083           Ops.erase(Ops.begin()+Idx);
1084           Ops.erase(Ops.begin()+OtherIdx-1);
1085           Ops.push_back(NewAddRec);
1086           return getMulExpr(Ops);
1087         }
1088       }
1089
1090     // Otherwise couldn't fold anything into this recurrence.  Move onto the
1091     // next one.
1092   }
1093
1094   // Okay, it looks like we really DO need an mul expr.  Check to see if we
1095   // already have one, otherwise create a new one.
1096   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1097   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1098                                                                  SCEVOps)];
1099   if (Result == 0)
1100     Result = new SCEVMulExpr(Ops);
1101   return Result;
1102 }
1103
1104 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1105   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1106     if (RHSC->getValue()->equalsInt(1))
1107       return LHS;                            // X udiv 1 --> x
1108
1109     if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1110       Constant *LHSCV = LHSC->getValue();
1111       Constant *RHSCV = RHSC->getValue();
1112       return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1113     }
1114   }
1115
1116   // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1117
1118   SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1119   if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1120   return Result;
1121 }
1122
1123
1124 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1125 /// specified loop.  Simplify the expression as much as possible.
1126 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1127                                const SCEVHandle &Step, const Loop *L) {
1128   std::vector<SCEVHandle> Operands;
1129   Operands.push_back(Start);
1130   if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1131     if (StepChrec->getLoop() == L) {
1132       Operands.insert(Operands.end(), StepChrec->op_begin(),
1133                       StepChrec->op_end());
1134       return getAddRecExpr(Operands, L);
1135     }
1136
1137   Operands.push_back(Step);
1138   return getAddRecExpr(Operands, L);
1139 }
1140
1141 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1142 /// specified loop.  Simplify the expression as much as possible.
1143 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1144                                const Loop *L) {
1145   if (Operands.size() == 1) return Operands[0];
1146
1147   if (Operands.back()->isZero()) {
1148     Operands.pop_back();
1149     return getAddRecExpr(Operands, L);             // {X,+,0}  -->  X
1150   }
1151
1152   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1153   if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1154     const Loop* NestedLoop = NestedAR->getLoop();
1155     if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1156       std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1157                                              NestedAR->op_end());
1158       SCEVHandle NestedARHandle(NestedAR);
1159       Operands[0] = NestedAR->getStart();
1160       NestedOperands[0] = getAddRecExpr(Operands, L);
1161       return getAddRecExpr(NestedOperands, NestedLoop);
1162     }
1163   }
1164
1165   SCEVAddRecExpr *&Result =
1166     (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1167                                                             Operands.end()))];
1168   if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1169   return Result;
1170 }
1171
1172 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1173                                         const SCEVHandle &RHS) {
1174   std::vector<SCEVHandle> Ops;
1175   Ops.push_back(LHS);
1176   Ops.push_back(RHS);
1177   return getSMaxExpr(Ops);
1178 }
1179
1180 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1181   assert(!Ops.empty() && "Cannot get empty smax!");
1182   if (Ops.size() == 1) return Ops[0];
1183
1184   // Sort by complexity, this groups all similar expression types together.
1185   GroupByComplexity(Ops);
1186
1187   // If there are any constants, fold them together.
1188   unsigned Idx = 0;
1189   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1190     ++Idx;
1191     assert(Idx < Ops.size());
1192     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1193       // We found two constants, fold them together!
1194       ConstantInt *Fold = ConstantInt::get(
1195                               APIntOps::smax(LHSC->getValue()->getValue(),
1196                                              RHSC->getValue()->getValue()));
1197       Ops[0] = getConstant(Fold);
1198       Ops.erase(Ops.begin()+1);  // Erase the folded element
1199       if (Ops.size() == 1) return Ops[0];
1200       LHSC = cast<SCEVConstant>(Ops[0]);
1201     }
1202
1203     // If we are left with a constant -inf, strip it off.
1204     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1205       Ops.erase(Ops.begin());
1206       --Idx;
1207     }
1208   }
1209
1210   if (Ops.size() == 1) return Ops[0];
1211
1212   // Find the first SMax
1213   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1214     ++Idx;
1215
1216   // Check to see if one of the operands is an SMax. If so, expand its operands
1217   // onto our operand list, and recurse to simplify.
1218   if (Idx < Ops.size()) {
1219     bool DeletedSMax = false;
1220     while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1221       Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1222       Ops.erase(Ops.begin()+Idx);
1223       DeletedSMax = true;
1224     }
1225
1226     if (DeletedSMax)
1227       return getSMaxExpr(Ops);
1228   }
1229
1230   // Okay, check to see if the same value occurs in the operand list twice.  If
1231   // so, delete one.  Since we sorted the list, these values are required to
1232   // be adjacent.
1233   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1234     if (Ops[i] == Ops[i+1]) {      //  X smax Y smax Y  -->  X smax Y
1235       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1236       --i; --e;
1237     }
1238
1239   if (Ops.size() == 1) return Ops[0];
1240
1241   assert(!Ops.empty() && "Reduced smax down to nothing!");
1242
1243   // Okay, it looks like we really DO need an smax expr.  Check to see if we
1244   // already have one, otherwise create a new one.
1245   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1246   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1247                                                                  SCEVOps)];
1248   if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1249   return Result;
1250 }
1251
1252 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1253                                         const SCEVHandle &RHS) {
1254   std::vector<SCEVHandle> Ops;
1255   Ops.push_back(LHS);
1256   Ops.push_back(RHS);
1257   return getUMaxExpr(Ops);
1258 }
1259
1260 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1261   assert(!Ops.empty() && "Cannot get empty umax!");
1262   if (Ops.size() == 1) return Ops[0];
1263
1264   // Sort by complexity, this groups all similar expression types together.
1265   GroupByComplexity(Ops);
1266
1267   // If there are any constants, fold them together.
1268   unsigned Idx = 0;
1269   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1270     ++Idx;
1271     assert(Idx < Ops.size());
1272     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1273       // We found two constants, fold them together!
1274       ConstantInt *Fold = ConstantInt::get(
1275                               APIntOps::umax(LHSC->getValue()->getValue(),
1276                                              RHSC->getValue()->getValue()));
1277       Ops[0] = getConstant(Fold);
1278       Ops.erase(Ops.begin()+1);  // Erase the folded element
1279       if (Ops.size() == 1) return Ops[0];
1280       LHSC = cast<SCEVConstant>(Ops[0]);
1281     }
1282
1283     // If we are left with a constant zero, strip it off.
1284     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1285       Ops.erase(Ops.begin());
1286       --Idx;
1287     }
1288   }
1289
1290   if (Ops.size() == 1) return Ops[0];
1291
1292   // Find the first UMax
1293   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1294     ++Idx;
1295
1296   // Check to see if one of the operands is a UMax. If so, expand its operands
1297   // onto our operand list, and recurse to simplify.
1298   if (Idx < Ops.size()) {
1299     bool DeletedUMax = false;
1300     while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1301       Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1302       Ops.erase(Ops.begin()+Idx);
1303       DeletedUMax = true;
1304     }
1305
1306     if (DeletedUMax)
1307       return getUMaxExpr(Ops);
1308   }
1309
1310   // Okay, check to see if the same value occurs in the operand list twice.  If
1311   // so, delete one.  Since we sorted the list, these values are required to
1312   // be adjacent.
1313   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1314     if (Ops[i] == Ops[i+1]) {      //  X umax Y umax Y  -->  X umax Y
1315       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1316       --i; --e;
1317     }
1318
1319   if (Ops.size() == 1) return Ops[0];
1320
1321   assert(!Ops.empty() && "Reduced umax down to nothing!");
1322
1323   // Okay, it looks like we really DO need a umax expr.  Check to see if we
1324   // already have one, otherwise create a new one.
1325   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1326   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1327                                                                  SCEVOps)];
1328   if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1329   return Result;
1330 }
1331
1332 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1333   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1334     return getConstant(CI);
1335   if (isa<ConstantPointerNull>(V))
1336     return getIntegerSCEV(0, V->getType());
1337   SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1338   if (Result == 0) Result = new SCEVUnknown(V);
1339   return Result;
1340 }
1341
1342 //===----------------------------------------------------------------------===//
1343 //             ScalarEvolutionsImpl Definition and Implementation
1344 //===----------------------------------------------------------------------===//
1345 //
1346 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1347 /// evolution code.
1348 ///
1349 namespace {
1350   struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1351     /// SE - A reference to the public ScalarEvolution object.
1352     ScalarEvolution &SE;
1353
1354     /// F - The function we are analyzing.
1355     ///
1356     Function &F;
1357
1358     /// LI - The loop information for the function we are currently analyzing.
1359     ///
1360     LoopInfo &LI;
1361
1362     /// TD - The target data information for the target we are targetting.
1363     ///
1364     TargetData *TD;
1365
1366     /// UnknownValue - This SCEV is used to represent unknown trip counts and
1367     /// things.
1368     SCEVHandle UnknownValue;
1369
1370     /// Scalars - This is a cache of the scalars we have analyzed so far.
1371     ///
1372     std::map<Value*, SCEVHandle> Scalars;
1373
1374     /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
1375     /// this function as they are computed.
1376     std::map<const Loop*, SCEVHandle> BackedgeTakenCounts;
1377
1378     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1379     /// the PHI instructions that we attempt to compute constant evolutions for.
1380     /// This allows us to avoid potentially expensive recomputation of these
1381     /// properties.  An instruction maps to null if we are unable to compute its
1382     /// exit value.
1383     std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1384
1385   public:
1386     ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li,
1387                          TargetData *td)
1388       : SE(se), F(f), LI(li), TD(td), UnknownValue(new SCEVCouldNotCompute()) {}
1389
1390     /// isSCEVable - Test if values of the given type are analyzable within
1391     /// the SCEV framework. This primarily includes integer types, and it
1392     /// can optionally include pointer types if the ScalarEvolution class
1393     /// has access to target-specific information.
1394     bool isSCEVable(const Type *Ty) const;
1395
1396     /// getTypeSizeInBits - Return the size in bits of the specified type,
1397     /// for which isSCEVable must return true.
1398     uint64_t getTypeSizeInBits(const Type *Ty) const;
1399
1400     /// getEffectiveSCEVType - Return a type with the same bitwidth as
1401     /// the given type and which represents how SCEV will treat the given
1402     /// type, for which isSCEVable must return true. For pointer types,
1403     /// this is the pointer-sized integer type.
1404     const Type *getEffectiveSCEVType(const Type *Ty) const;
1405
1406     SCEVHandle getCouldNotCompute();
1407
1408     /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1409     /// specified signed integer value and return a SCEV for the constant.
1410     SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
1411
1412     /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1413     ///
1414     SCEVHandle getNegativeSCEV(const SCEVHandle &V);
1415
1416     /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1417     ///
1418     SCEVHandle getNotSCEV(const SCEVHandle &V);
1419
1420     /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1421     ///
1422     SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS);
1423
1424     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
1425     /// of the input value to the specified type.  If the type must be extended,
1426     /// it is zero extended.
1427     SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
1428
1429     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
1430     /// of the input value to the specified type.  If the type must be extended,
1431     /// it is sign extended.
1432     SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
1433
1434     /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1435     /// expression and create a new one.
1436     SCEVHandle getSCEV(Value *V);
1437
1438     /// hasSCEV - Return true if the SCEV for this value has already been
1439     /// computed.
1440     bool hasSCEV(Value *V) const {
1441       return Scalars.count(V);
1442     }
1443
1444     /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1445     /// the specified value.
1446     void setSCEV(Value *V, const SCEVHandle &H) {
1447       bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1448       assert(isNew && "This entry already existed!");
1449       isNew = false;
1450     }
1451
1452
1453     /// getSCEVAtScope - Compute the value of the specified expression within
1454     /// the indicated loop (which may be null to indicate in no loop).  If the
1455     /// expression cannot be evaluated, return UnknownValue itself.
1456     SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1457
1458
1459     /// isLoopGuardedByCond - Test whether entry to the loop is protected by
1460     /// a conditional between LHS and RHS.
1461     bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1462                              SCEV *LHS, SCEV *RHS);
1463
1464     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
1465     /// has an analyzable loop-invariant backedge-taken count.
1466     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
1467
1468     /// forgetLoopBackedgeTakenCount - This method should be called by the
1469     /// client when it has changed a loop in a way that may effect
1470     /// ScalarEvolution's ability to compute a trip count, or if the loop
1471     /// is deleted.
1472     void forgetLoopBackedgeTakenCount(const Loop *L);
1473
1474     /// getBackedgeTakenCount - If the specified loop has a predictable
1475     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
1476     /// object. The backedge-taken count is the number of times the loop header
1477     /// will be branched to from within the loop. This is one less than the
1478     /// trip count of the loop, since it doesn't count the first iteration,
1479     /// when the header is branched to from outside the loop.
1480     ///
1481     /// Note that it is not valid to call this method on a loop without a
1482     /// loop-invariant backedge-taken count (see
1483     /// hasLoopInvariantBackedgeTakenCount).
1484     ///
1485     SCEVHandle getBackedgeTakenCount(const Loop *L);
1486
1487     /// deleteValueFromRecords - This method should be called by the
1488     /// client before it removes a value from the program, to make sure
1489     /// that no dangling references are left around.
1490     void deleteValueFromRecords(Value *V);
1491
1492   private:
1493     /// createSCEV - We know that there is no SCEV for the specified value.
1494     /// Analyze the expression.
1495     SCEVHandle createSCEV(Value *V);
1496
1497     /// createNodeForPHI - Provide the special handling we need to analyze PHI
1498     /// SCEVs.
1499     SCEVHandle createNodeForPHI(PHINode *PN);
1500
1501     /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1502     /// for the specified instruction and replaces any references to the
1503     /// symbolic value SymName with the specified value.  This is used during
1504     /// PHI resolution.
1505     void ReplaceSymbolicValueWithConcrete(Instruction *I,
1506                                           const SCEVHandle &SymName,
1507                                           const SCEVHandle &NewVal);
1508
1509     /// ComputeBackedgeTakenCount - Compute the number of times the specified
1510     /// loop will iterate.
1511     SCEVHandle ComputeBackedgeTakenCount(const Loop *L);
1512
1513     /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
1514     /// of 'icmp op load X, cst', try to see if we can compute the trip count.
1515     SCEVHandle
1516       ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
1517                                                    Constant *RHS,
1518                                                    const Loop *L,
1519                                                    ICmpInst::Predicate p);
1520
1521     /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
1522     /// a constant number of times (the condition evolves only from constants),
1523     /// try to evaluate a few iterations of the loop until we get the exit
1524     /// condition gets a value of ExitWhen (true or false).  If we cannot
1525     /// evaluate the trip count of the loop, return UnknownValue.
1526     SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
1527                                                      bool ExitWhen);
1528
1529     /// HowFarToZero - Return the number of times a backedge comparing the
1530     /// specified value to zero will execute.  If not computable, return
1531     /// UnknownValue.
1532     SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1533
1534     /// HowFarToNonZero - Return the number of times a backedge checking the
1535     /// specified value for nonzero will execute.  If not computable, return
1536     /// UnknownValue.
1537     SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1538
1539     /// HowManyLessThans - Return the number of times a backedge containing the
1540     /// specified less-than comparison will execute.  If not computable, return
1541     /// UnknownValue. isSigned specifies whether the less-than is signed.
1542     SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1543                                 bool isSigned);
1544
1545     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1546     /// (which may not be an immediate predecessor) which has exactly one
1547     /// successor from which BB is reachable, or null if no such block is
1548     /// found.
1549     BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1550
1551     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1552     /// in the header of its containing loop, we know the loop executes a
1553     /// constant number of times, and the PHI node is just a recurrence
1554     /// involving constants, fold it.
1555     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
1556                                                 const Loop *L);
1557   };
1558 }
1559
1560 //===----------------------------------------------------------------------===//
1561 //            Basic SCEV Analysis and PHI Idiom Recognition Code
1562 //
1563
1564 /// deleteValueFromRecords - This method should be called by the
1565 /// client before it removes an instruction from the program, to make sure
1566 /// that no dangling references are left around.
1567 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1568   SmallVector<Value *, 16> Worklist;
1569
1570   if (Scalars.erase(V)) {
1571     if (PHINode *PN = dyn_cast<PHINode>(V))
1572       ConstantEvolutionLoopExitValue.erase(PN);
1573     Worklist.push_back(V);
1574   }
1575
1576   while (!Worklist.empty()) {
1577     Value *VV = Worklist.back();
1578     Worklist.pop_back();
1579
1580     for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1581          UI != UE; ++UI) {
1582       Instruction *Inst = cast<Instruction>(*UI);
1583       if (Scalars.erase(Inst)) {
1584         if (PHINode *PN = dyn_cast<PHINode>(VV))
1585           ConstantEvolutionLoopExitValue.erase(PN);
1586         Worklist.push_back(Inst);
1587       }
1588     }
1589   }
1590 }
1591
1592 /// isSCEVable - Test if values of the given type are analyzable within
1593 /// the SCEV framework. This primarily includes integer types, and it
1594 /// can optionally include pointer types if the ScalarEvolution class
1595 /// has access to target-specific information.
1596 bool ScalarEvolutionsImpl::isSCEVable(const Type *Ty) const {
1597   // Integers are always SCEVable.
1598   if (Ty->isInteger())
1599     return true;
1600
1601   // Pointers are SCEVable if TargetData information is available
1602   // to provide pointer size information.
1603   if (isa<PointerType>(Ty))
1604     return TD != NULL;
1605
1606   // Otherwise it's not SCEVable.
1607   return false;
1608 }
1609
1610 /// getTypeSizeInBits - Return the size in bits of the specified type,
1611 /// for which isSCEVable must return true.
1612 uint64_t ScalarEvolutionsImpl::getTypeSizeInBits(const Type *Ty) const {
1613   assert(isSCEVable(Ty) && "Type is not SCEVable!");
1614
1615   // If we have a TargetData, use it!
1616   if (TD)
1617     return TD->getTypeSizeInBits(Ty);
1618
1619   // Otherwise, we support only integer types.
1620   assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1621   return Ty->getPrimitiveSizeInBits();
1622 }
1623
1624 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1625 /// the given type and which represents how SCEV will treat the given
1626 /// type, for which isSCEVable must return true. For pointer types,
1627 /// this is the pointer-sized integer type.
1628 const Type *ScalarEvolutionsImpl::getEffectiveSCEVType(const Type *Ty) const {
1629   assert(isSCEVable(Ty) && "Type is not SCEVable!");
1630
1631   if (Ty->isInteger())
1632     return Ty;
1633
1634   assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1635   return TD->getIntPtrType();
1636 }
1637
1638 SCEVHandle ScalarEvolutionsImpl::getCouldNotCompute() {
1639   return UnknownValue;
1640 }
1641
1642 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1643 /// expression and create a new one.
1644 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1645   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
1646
1647   std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1648   if (I != Scalars.end()) return I->second;
1649   SCEVHandle S = createSCEV(V);
1650   Scalars.insert(std::make_pair(V, S));
1651   return S;
1652 }
1653
1654 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1655 /// specified signed integer value and return a SCEV for the constant.
1656 SCEVHandle ScalarEvolutionsImpl::getIntegerSCEV(int Val, const Type *Ty) {
1657   Ty = SE.getEffectiveSCEVType(Ty);
1658   Constant *C;
1659   if (Val == 0)
1660     C = Constant::getNullValue(Ty);
1661   else if (Ty->isFloatingPoint())
1662     C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1663                                 APFloat::IEEEdouble, Val));
1664   else
1665     C = ConstantInt::get(Ty, Val);
1666   return SE.getUnknown(C);
1667 }
1668
1669 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1670 ///
1671 SCEVHandle ScalarEvolutionsImpl::getNegativeSCEV(const SCEVHandle &V) {
1672   if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1673     return SE.getUnknown(ConstantExpr::getNeg(VC->getValue()));
1674
1675   const Type *Ty = V->getType();
1676   Ty = SE.getEffectiveSCEVType(Ty);
1677   return SE.getMulExpr(V, SE.getConstant(ConstantInt::getAllOnesValue(Ty)));
1678 }
1679
1680 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1681 SCEVHandle ScalarEvolutionsImpl::getNotSCEV(const SCEVHandle &V) {
1682   if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1683     return SE.getUnknown(ConstantExpr::getNot(VC->getValue()));
1684
1685   const Type *Ty = V->getType();
1686   Ty = SE.getEffectiveSCEVType(Ty);
1687   SCEVHandle AllOnes = SE.getConstant(ConstantInt::getAllOnesValue(Ty));
1688   return getMinusSCEV(AllOnes, V);
1689 }
1690
1691 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1692 ///
1693 SCEVHandle ScalarEvolutionsImpl::getMinusSCEV(const SCEVHandle &LHS,
1694                                               const SCEVHandle &RHS) {
1695   // X - Y --> X + -Y
1696   return SE.getAddExpr(LHS, SE.getNegativeSCEV(RHS));
1697 }
1698
1699 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1700 /// input value to the specified type.  If the type must be extended, it is zero
1701 /// extended.
1702 SCEVHandle
1703 ScalarEvolutionsImpl::getTruncateOrZeroExtend(const SCEVHandle &V,
1704                                               const Type *Ty) {
1705   const Type *SrcTy = V->getType();
1706   assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1707          (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1708          "Cannot truncate or zero extend with non-integer arguments!");
1709   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1710     return V;  // No conversion
1711   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1712     return SE.getTruncateExpr(V, Ty);
1713   return SE.getZeroExtendExpr(V, Ty);
1714 }
1715
1716 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1717 /// input value to the specified type.  If the type must be extended, it is sign
1718 /// extended.
1719 SCEVHandle
1720 ScalarEvolutionsImpl::getTruncateOrSignExtend(const SCEVHandle &V,
1721                                               const Type *Ty) {
1722   const Type *SrcTy = V->getType();
1723   assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1724          (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1725          "Cannot truncate or zero extend with non-integer arguments!");
1726   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1727     return V;  // No conversion
1728   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1729     return SE.getTruncateExpr(V, Ty);
1730   return SE.getSignExtendExpr(V, Ty);
1731 }
1732
1733 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1734 /// the specified instruction and replaces any references to the symbolic value
1735 /// SymName with the specified value.  This is used during PHI resolution.
1736 void ScalarEvolutionsImpl::
1737 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1738                                  const SCEVHandle &NewVal) {
1739   std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1740   if (SI == Scalars.end()) return;
1741
1742   SCEVHandle NV =
1743     SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
1744   if (NV == SI->second) return;  // No change.
1745
1746   SI->second = NV;       // Update the scalars map!
1747
1748   // Any instruction values that use this instruction might also need to be
1749   // updated!
1750   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1751        UI != E; ++UI)
1752     ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1753 }
1754
1755 /// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
1756 /// a loop header, making it a potential recurrence, or it doesn't.
1757 ///
1758 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1759   if (PN->getNumIncomingValues() == 2)  // The loops have been canonicalized.
1760     if (const Loop *L = LI.getLoopFor(PN->getParent()))
1761       if (L->getHeader() == PN->getParent()) {
1762         // If it lives in the loop header, it has two incoming values, one
1763         // from outside the loop, and one from inside.
1764         unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1765         unsigned BackEdge     = IncomingEdge^1;
1766
1767         // While we are analyzing this PHI node, handle its value symbolically.
1768         SCEVHandle SymbolicName = SE.getUnknown(PN);
1769         assert(Scalars.find(PN) == Scalars.end() &&
1770                "PHI node already processed?");
1771         Scalars.insert(std::make_pair(PN, SymbolicName));
1772
1773         // Using this symbolic name for the PHI, analyze the value coming around
1774         // the back-edge.
1775         SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1776
1777         // NOTE: If BEValue is loop invariant, we know that the PHI node just
1778         // has a special value for the first iteration of the loop.
1779
1780         // If the value coming around the backedge is an add with the symbolic
1781         // value we just inserted, then we found a simple induction variable!
1782         if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1783           // If there is a single occurrence of the symbolic value, replace it
1784           // with a recurrence.
1785           unsigned FoundIndex = Add->getNumOperands();
1786           for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1787             if (Add->getOperand(i) == SymbolicName)
1788               if (FoundIndex == e) {
1789                 FoundIndex = i;
1790                 break;
1791               }
1792
1793           if (FoundIndex != Add->getNumOperands()) {
1794             // Create an add with everything but the specified operand.
1795             std::vector<SCEVHandle> Ops;
1796             for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1797               if (i != FoundIndex)
1798                 Ops.push_back(Add->getOperand(i));
1799             SCEVHandle Accum = SE.getAddExpr(Ops);
1800
1801             // This is not a valid addrec if the step amount is varying each
1802             // loop iteration, but is not itself an addrec in this loop.
1803             if (Accum->isLoopInvariant(L) ||
1804                 (isa<SCEVAddRecExpr>(Accum) &&
1805                  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1806               SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1807               SCEVHandle PHISCEV  = SE.getAddRecExpr(StartVal, Accum, L);
1808
1809               // Okay, for the entire analysis of this edge we assumed the PHI
1810               // to be symbolic.  We now need to go back and update all of the
1811               // entries for the scalars that use the PHI (except for the PHI
1812               // itself) to use the new analyzed value instead of the "symbolic"
1813               // value.
1814               ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1815               return PHISCEV;
1816             }
1817           }
1818         } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1819           // Otherwise, this could be a loop like this:
1820           //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
1821           // In this case, j = {1,+,1}  and BEValue is j.
1822           // Because the other in-value of i (0) fits the evolution of BEValue
1823           // i really is an addrec evolution.
1824           if (AddRec->getLoop() == L && AddRec->isAffine()) {
1825             SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1826
1827             // If StartVal = j.start - j.stride, we can use StartVal as the
1828             // initial step of the addrec evolution.
1829             if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1830                                             AddRec->getOperand(1))) {
1831               SCEVHandle PHISCEV = 
1832                  SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1833
1834               // Okay, for the entire analysis of this edge we assumed the PHI
1835               // to be symbolic.  We now need to go back and update all of the
1836               // entries for the scalars that use the PHI (except for the PHI
1837               // itself) to use the new analyzed value instead of the "symbolic"
1838               // value.
1839               ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1840               return PHISCEV;
1841             }
1842           }
1843         }
1844
1845         return SymbolicName;
1846       }
1847
1848   // If it's not a loop phi, we can't handle it yet.
1849   return SE.getUnknown(PN);
1850 }
1851
1852 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1853 /// guaranteed to end in (at every loop iteration).  It is, at the same time,
1854 /// the minimum number of times S is divisible by 2.  For example, given {4,+,8}
1855 /// it returns 2.  If S is guaranteed to be 0, it returns the bitwidth of S.
1856 static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
1857   if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1858     return C->getValue()->getValue().countTrailingZeros();
1859
1860   if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1861     return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1862                     (uint32_t)SE.getTypeSizeInBits(T->getType()));
1863
1864   if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1865     uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1866     return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1867              SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1868   }
1869
1870   if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1871     uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1872     return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1873              SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1874   }
1875
1876   if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1877     // The result is the min of all operands results.
1878     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1879     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1880       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1881     return MinOpRes;
1882   }
1883
1884   if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1885     // The result is the sum of all operands results.
1886     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1887     uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
1888     for (unsigned i = 1, e = M->getNumOperands();
1889          SumOpRes != BitWidth && i != e; ++i)
1890       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
1891                           BitWidth);
1892     return SumOpRes;
1893   }
1894
1895   if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1896     // The result is the min of all operands results.
1897     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1898     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1899       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1900     return MinOpRes;
1901   }
1902
1903   if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1904     // The result is the min of all operands results.
1905     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1906     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1907       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1908     return MinOpRes;
1909   }
1910
1911   if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1912     // The result is the min of all operands results.
1913     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1914     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1915       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1916     return MinOpRes;
1917   }
1918
1919   // SCEVUDivExpr, SCEVUnknown
1920   return 0;
1921 }
1922
1923 /// createSCEV - We know that there is no SCEV for the specified value.
1924 /// Analyze the expression.
1925 ///
1926 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1927   if (!isSCEVable(V->getType()))
1928     return SE.getUnknown(V);
1929
1930   unsigned Opcode = Instruction::UserOp1;
1931   if (Instruction *I = dyn_cast<Instruction>(V))
1932     Opcode = I->getOpcode();
1933   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1934     Opcode = CE->getOpcode();
1935   else
1936     return SE.getUnknown(V);
1937
1938   User *U = cast<User>(V);
1939   switch (Opcode) {
1940   case Instruction::Add:
1941     return SE.getAddExpr(getSCEV(U->getOperand(0)),
1942                          getSCEV(U->getOperand(1)));
1943   case Instruction::Mul:
1944     return SE.getMulExpr(getSCEV(U->getOperand(0)),
1945                          getSCEV(U->getOperand(1)));
1946   case Instruction::UDiv:
1947     return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1948                           getSCEV(U->getOperand(1)));
1949   case Instruction::Sub:
1950     return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1951                            getSCEV(U->getOperand(1)));
1952   case Instruction::Or:
1953     // If the RHS of the Or is a constant, we may have something like:
1954     // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
1955     // optimizations will transparently handle this case.
1956     //
1957     // In order for this transformation to be safe, the LHS must be of the
1958     // form X*(2^n) and the Or constant must be less than 2^n.
1959     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1960       SCEVHandle LHS = getSCEV(U->getOperand(0));
1961       const APInt &CIVal = CI->getValue();
1962       if (GetMinTrailingZeros(LHS, SE) >=
1963           (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1964         return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
1965     }
1966     break;
1967   case Instruction::Xor:
1968     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1969       // If the RHS of the xor is a signbit, then this is just an add.
1970       // Instcombine turns add of signbit into xor as a strength reduction step.
1971       if (CI->getValue().isSignBit())
1972         return SE.getAddExpr(getSCEV(U->getOperand(0)),
1973                              getSCEV(U->getOperand(1)));
1974
1975       // If the RHS of xor is -1, then this is a not operation.
1976       else if (CI->isAllOnesValue())
1977         return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1978     }
1979     break;
1980
1981   case Instruction::Shl:
1982     // Turn shift left of a constant amount into a multiply.
1983     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1984       uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1985       Constant *X = ConstantInt::get(
1986         APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1987       return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1988     }
1989     break;
1990
1991   case Instruction::LShr:
1992     // Turn logical shift right of a constant into a unsigned divide.
1993     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1994       uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1995       Constant *X = ConstantInt::get(
1996         APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1997       return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1998     }
1999     break;
2000
2001   case Instruction::Trunc:
2002     return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2003
2004   case Instruction::ZExt:
2005     return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2006
2007   case Instruction::SExt:
2008     return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2009
2010   case Instruction::BitCast:
2011     // BitCasts are no-op casts so we just eliminate the cast.
2012     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
2013       return getSCEV(U->getOperand(0));
2014     break;
2015
2016   case Instruction::IntToPtr:
2017     if (!TD) break; // Without TD we can't analyze pointers.
2018     return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2019                                    TD->getIntPtrType());
2020
2021   case Instruction::PtrToInt:
2022     if (!TD) break; // Without TD we can't analyze pointers.
2023     return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2024                                    U->getType());
2025
2026   case Instruction::GetElementPtr: {
2027     if (!TD) break; // Without TD we can't analyze pointers.
2028     const Type *IntPtrTy = TD->getIntPtrType();
2029     Value *Base = U->getOperand(0);
2030     SCEVHandle TotalOffset = SE.getIntegerSCEV(0, IntPtrTy);
2031     gep_type_iterator GTI = gep_type_begin(U);
2032     for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
2033                                         E = U->op_end();
2034          I != E; ++I) {
2035       Value *Index = *I;
2036       // Compute the (potentially symbolic) offset in bytes for this index.
2037       if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2038         // For a struct, add the member offset.
2039         const StructLayout &SL = *TD->getStructLayout(STy);
2040         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2041         uint64_t Offset = SL.getElementOffset(FieldNo);
2042         TotalOffset = SE.getAddExpr(TotalOffset,
2043                                     SE.getIntegerSCEV(Offset, IntPtrTy));
2044       } else {
2045         // For an array, add the element offset, explicitly scaled.
2046         SCEVHandle LocalOffset = getSCEV(Index);
2047         if (!isa<PointerType>(LocalOffset->getType()))
2048           // Getelementptr indicies are signed.
2049           LocalOffset = getTruncateOrSignExtend(LocalOffset,
2050                                                 IntPtrTy);
2051         LocalOffset =
2052           SE.getMulExpr(LocalOffset,
2053                         SE.getIntegerSCEV(TD->getTypePaddedSize(*GTI),
2054                                           IntPtrTy));
2055         TotalOffset = SE.getAddExpr(TotalOffset, LocalOffset);
2056       }
2057     }
2058     return SE.getAddExpr(getSCEV(Base), TotalOffset);
2059   }
2060
2061   case Instruction::PHI:
2062     return createNodeForPHI(cast<PHINode>(U));
2063
2064   case Instruction::Select:
2065     // This could be a smax or umax that was lowered earlier.
2066     // Try to recover it.
2067     if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2068       Value *LHS = ICI->getOperand(0);
2069       Value *RHS = ICI->getOperand(1);
2070       switch (ICI->getPredicate()) {
2071       case ICmpInst::ICMP_SLT:
2072       case ICmpInst::ICMP_SLE:
2073         std::swap(LHS, RHS);
2074         // fall through
2075       case ICmpInst::ICMP_SGT:
2076       case ICmpInst::ICMP_SGE:
2077         if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2078           return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2079         else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2080           // ~smax(~x, ~y) == smin(x, y).
2081           return SE.getNotSCEV(SE.getSMaxExpr(
2082                                    SE.getNotSCEV(getSCEV(LHS)),
2083                                    SE.getNotSCEV(getSCEV(RHS))));
2084         break;
2085       case ICmpInst::ICMP_ULT:
2086       case ICmpInst::ICMP_ULE:
2087         std::swap(LHS, RHS);
2088         // fall through
2089       case ICmpInst::ICMP_UGT:
2090       case ICmpInst::ICMP_UGE:
2091         if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2092           return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2093         else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2094           // ~umax(~x, ~y) == umin(x, y)
2095           return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
2096                                               SE.getNotSCEV(getSCEV(RHS))));
2097         break;
2098       default:
2099         break;
2100       }
2101     }
2102
2103   default: // We cannot analyze this expression.
2104     break;
2105   }
2106
2107   return SE.getUnknown(V);
2108 }
2109
2110
2111
2112 //===----------------------------------------------------------------------===//
2113 //                   Iteration Count Computation Code
2114 //
2115
2116 /// getBackedgeTakenCount - If the specified loop has a predictable
2117 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2118 /// object. The backedge-taken count is the number of times the loop header
2119 /// will be branched to from within the loop. This is one less than the
2120 /// trip count of the loop, since it doesn't count the first iteration,
2121 /// when the header is branched to from outside the loop.
2122 ///
2123 /// Note that it is not valid to call this method on a loop without a
2124 /// loop-invariant backedge-taken count (see
2125 /// hasLoopInvariantBackedgeTakenCount).
2126 ///
2127 SCEVHandle ScalarEvolutionsImpl::getBackedgeTakenCount(const Loop *L) {
2128   std::map<const Loop*, SCEVHandle>::iterator I = BackedgeTakenCounts.find(L);
2129   if (I == BackedgeTakenCounts.end()) {
2130     SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
2131     I = BackedgeTakenCounts.insert(std::make_pair(L, ItCount)).first;
2132     if (ItCount != UnknownValue) {
2133       assert(ItCount->isLoopInvariant(L) &&
2134              "Computed trip count isn't loop invariant for loop!");
2135       ++NumTripCountsComputed;
2136     } else if (isa<PHINode>(L->getHeader()->begin())) {
2137       // Only count loops that have phi nodes as not being computable.
2138       ++NumTripCountsNotComputed;
2139     }
2140   }
2141   return I->second;
2142 }
2143
2144 /// forgetLoopBackedgeTakenCount - This method should be called by the
2145 /// client when it has changed a loop in a way that may effect
2146 /// ScalarEvolution's ability to compute a trip count, or if the loop
2147 /// is deleted.
2148 void ScalarEvolutionsImpl::forgetLoopBackedgeTakenCount(const Loop *L) {
2149   BackedgeTakenCounts.erase(L);
2150 }
2151
2152 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
2153 /// of the specified loop will execute.
2154 SCEVHandle ScalarEvolutionsImpl::ComputeBackedgeTakenCount(const Loop *L) {
2155   // If the loop has a non-one exit block count, we can't analyze it.
2156   SmallVector<BasicBlock*, 8> ExitBlocks;
2157   L->getExitBlocks(ExitBlocks);
2158   if (ExitBlocks.size() != 1) return UnknownValue;
2159
2160   // Okay, there is one exit block.  Try to find the condition that causes the
2161   // loop to be exited.
2162   BasicBlock *ExitBlock = ExitBlocks[0];
2163
2164   BasicBlock *ExitingBlock = 0;
2165   for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2166        PI != E; ++PI)
2167     if (L->contains(*PI)) {
2168       if (ExitingBlock == 0)
2169         ExitingBlock = *PI;
2170       else
2171         return UnknownValue;   // More than one block exiting!
2172     }
2173   assert(ExitingBlock && "No exits from loop, something is broken!");
2174
2175   // Okay, we've computed the exiting block.  See what condition causes us to
2176   // exit.
2177   //
2178   // FIXME: we should be able to handle switch instructions (with a single exit)
2179   BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2180   if (ExitBr == 0) return UnknownValue;
2181   assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2182   
2183   // At this point, we know we have a conditional branch that determines whether
2184   // the loop is exited.  However, we don't know if the branch is executed each
2185   // time through the loop.  If not, then the execution count of the branch will
2186   // not be equal to the trip count of the loop.
2187   //
2188   // Currently we check for this by checking to see if the Exit branch goes to
2189   // the loop header.  If so, we know it will always execute the same number of
2190   // times as the loop.  We also handle the case where the exit block *is* the
2191   // loop header.  This is common for un-rotated loops.  More extensive analysis
2192   // could be done to handle more cases here.
2193   if (ExitBr->getSuccessor(0) != L->getHeader() &&
2194       ExitBr->getSuccessor(1) != L->getHeader() &&
2195       ExitBr->getParent() != L->getHeader())
2196     return UnknownValue;
2197   
2198   ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2199
2200   // If it's not an integer comparison then compute it the hard way. 
2201   // Note that ICmpInst deals with pointer comparisons too so we must check
2202   // the type of the operand.
2203   if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2204     return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
2205                                           ExitBr->getSuccessor(0) == ExitBlock);
2206
2207   // If the condition was exit on true, convert the condition to exit on false
2208   ICmpInst::Predicate Cond;
2209   if (ExitBr->getSuccessor(1) == ExitBlock)
2210     Cond = ExitCond->getPredicate();
2211   else
2212     Cond = ExitCond->getInversePredicate();
2213
2214   // Handle common loops like: for (X = "string"; *X; ++X)
2215   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2216     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2217       SCEVHandle ItCnt =
2218         ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
2219       if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2220     }
2221
2222   SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2223   SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2224
2225   // Try to evaluate any dependencies out of the loop.
2226   SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2227   if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2228   Tmp = getSCEVAtScope(RHS, L);
2229   if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2230
2231   // At this point, we would like to compute how many iterations of the 
2232   // loop the predicate will return true for these inputs.
2233   if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2234     // If there is a loop-invariant, force it into the RHS.
2235     std::swap(LHS, RHS);
2236     Cond = ICmpInst::getSwappedPredicate(Cond);
2237   }
2238
2239   // FIXME: think about handling pointer comparisons!  i.e.:
2240   // while (P != P+100) ++P;
2241
2242   // If we have a comparison of a chrec against a constant, try to use value
2243   // ranges to answer this query.
2244   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2245     if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2246       if (AddRec->getLoop() == L) {
2247         // Form the comparison range using the constant of the correct type so
2248         // that the ConstantRange class knows to do a signed or unsigned
2249         // comparison.
2250         ConstantInt *CompVal = RHSC->getValue();
2251         const Type *RealTy = ExitCond->getOperand(0)->getType();
2252         CompVal = dyn_cast<ConstantInt>(
2253           ConstantExpr::getBitCast(CompVal, RealTy));
2254         if (CompVal) {
2255           // Form the constant range.
2256           ConstantRange CompRange(
2257               ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2258
2259           SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
2260           if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2261         }
2262       }
2263
2264   switch (Cond) {
2265   case ICmpInst::ICMP_NE: {                     // while (X != Y)
2266     // Convert to: while (X-Y != 0)
2267     SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
2268     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2269     break;
2270   }
2271   case ICmpInst::ICMP_EQ: {
2272     // Convert to: while (X-Y == 0)           // while (X == Y)
2273     SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
2274     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2275     break;
2276   }
2277   case ICmpInst::ICMP_SLT: {
2278     SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
2279     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2280     break;
2281   }
2282   case ICmpInst::ICMP_SGT: {
2283     SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2284                                      SE.getNotSCEV(RHS), L, true);
2285     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2286     break;
2287   }
2288   case ICmpInst::ICMP_ULT: {
2289     SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
2290     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2291     break;
2292   }
2293   case ICmpInst::ICMP_UGT: {
2294     SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2295                                      SE.getNotSCEV(RHS), L, false);
2296     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2297     break;
2298   }
2299   default:
2300 #if 0
2301     errs() << "ComputeBackedgeTakenCount ";
2302     if (ExitCond->getOperand(0)->getType()->isUnsigned())
2303       errs() << "[unsigned] ";
2304     errs() << *LHS << "   "
2305          << Instruction::getOpcodeName(Instruction::ICmp) 
2306          << "   " << *RHS << "\n";
2307 #endif
2308     break;
2309   }
2310   return
2311     ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2312                                           ExitBr->getSuccessor(0) == ExitBlock);
2313 }
2314
2315 static ConstantInt *
2316 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2317                                 ScalarEvolution &SE) {
2318   SCEVHandle InVal = SE.getConstant(C);
2319   SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2320   assert(isa<SCEVConstant>(Val) &&
2321          "Evaluation of SCEV at constant didn't fold correctly?");
2322   return cast<SCEVConstant>(Val)->getValue();
2323 }
2324
2325 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
2326 /// and a GEP expression (missing the pointer index) indexing into it, return
2327 /// the addressed element of the initializer or null if the index expression is
2328 /// invalid.
2329 static Constant *
2330 GetAddressedElementFromGlobal(GlobalVariable *GV,
2331                               const std::vector<ConstantInt*> &Indices) {
2332   Constant *Init = GV->getInitializer();
2333   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2334     uint64_t Idx = Indices[i]->getZExtValue();
2335     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2336       assert(Idx < CS->getNumOperands() && "Bad struct index!");
2337       Init = cast<Constant>(CS->getOperand(Idx));
2338     } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2339       if (Idx >= CA->getNumOperands()) return 0;  // Bogus program
2340       Init = cast<Constant>(CA->getOperand(Idx));
2341     } else if (isa<ConstantAggregateZero>(Init)) {
2342       if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2343         assert(Idx < STy->getNumElements() && "Bad struct index!");
2344         Init = Constant::getNullValue(STy->getElementType(Idx));
2345       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2346         if (Idx >= ATy->getNumElements()) return 0;  // Bogus program
2347         Init = Constant::getNullValue(ATy->getElementType());
2348       } else {
2349         assert(0 && "Unknown constant aggregate type!");
2350       }
2351       return 0;
2352     } else {
2353       return 0; // Unknown initializer type
2354     }
2355   }
2356   return Init;
2357 }
2358
2359 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2360 /// 'icmp op load X, cst', try to see if we can compute the backedge
2361 /// execution count.
2362 SCEVHandle ScalarEvolutionsImpl::
2363 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2364                                              const Loop *L,
2365                                              ICmpInst::Predicate predicate) {
2366   if (LI->isVolatile()) return UnknownValue;
2367
2368   // Check to see if the loaded pointer is a getelementptr of a global.
2369   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2370   if (!GEP) return UnknownValue;
2371
2372   // Make sure that it is really a constant global we are gepping, with an
2373   // initializer, and make sure the first IDX is really 0.
2374   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2375   if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2376       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2377       !cast<Constant>(GEP->getOperand(1))->isNullValue())
2378     return UnknownValue;
2379
2380   // Okay, we allow one non-constant index into the GEP instruction.
2381   Value *VarIdx = 0;
2382   std::vector<ConstantInt*> Indexes;
2383   unsigned VarIdxNum = 0;
2384   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2385     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2386       Indexes.push_back(CI);
2387     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2388       if (VarIdx) return UnknownValue;  // Multiple non-constant idx's.
2389       VarIdx = GEP->getOperand(i);
2390       VarIdxNum = i-2;
2391       Indexes.push_back(0);
2392     }
2393
2394   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2395   // Check to see if X is a loop variant variable value now.
2396   SCEVHandle Idx = getSCEV(VarIdx);
2397   SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2398   if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2399
2400   // We can only recognize very limited forms of loop index expressions, in
2401   // particular, only affine AddRec's like {C1,+,C2}.
2402   SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2403   if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2404       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2405       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2406     return UnknownValue;
2407
2408   unsigned MaxSteps = MaxBruteForceIterations;
2409   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2410     ConstantInt *ItCst =
2411       ConstantInt::get(IdxExpr->getType(), IterationNum);
2412     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
2413
2414     // Form the GEP offset.
2415     Indexes[VarIdxNum] = Val;
2416
2417     Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2418     if (Result == 0) break;  // Cannot compute!
2419
2420     // Evaluate the condition for this iteration.
2421     Result = ConstantExpr::getICmp(predicate, Result, RHS);
2422     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
2423     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2424 #if 0
2425       errs() << "\n***\n*** Computed loop count " << *ItCst
2426              << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2427              << "***\n";
2428 #endif
2429       ++NumArrayLenItCounts;
2430       return SE.getConstant(ItCst);   // Found terminating iteration!
2431     }
2432   }
2433   return UnknownValue;
2434 }
2435
2436
2437 /// CanConstantFold - Return true if we can constant fold an instruction of the
2438 /// specified type, assuming that all operands were constants.
2439 static bool CanConstantFold(const Instruction *I) {
2440   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2441       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2442     return true;
2443
2444   if (const CallInst *CI = dyn_cast<CallInst>(I))
2445     if (const Function *F = CI->getCalledFunction())
2446       return canConstantFoldCallTo(F);
2447   return false;
2448 }
2449
2450 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2451 /// in the loop that V is derived from.  We allow arbitrary operations along the
2452 /// way, but the operands of an operation must either be constants or a value
2453 /// derived from a constant PHI.  If this expression does not fit with these
2454 /// constraints, return null.
2455 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2456   // If this is not an instruction, or if this is an instruction outside of the
2457   // loop, it can't be derived from a loop PHI.
2458   Instruction *I = dyn_cast<Instruction>(V);
2459   if (I == 0 || !L->contains(I->getParent())) return 0;
2460
2461   if (PHINode *PN = dyn_cast<PHINode>(I)) {
2462     if (L->getHeader() == I->getParent())
2463       return PN;
2464     else
2465       // We don't currently keep track of the control flow needed to evaluate
2466       // PHIs, so we cannot handle PHIs inside of loops.
2467       return 0;
2468   }
2469
2470   // If we won't be able to constant fold this expression even if the operands
2471   // are constants, return early.
2472   if (!CanConstantFold(I)) return 0;
2473
2474   // Otherwise, we can evaluate this instruction if all of its operands are
2475   // constant or derived from a PHI node themselves.
2476   PHINode *PHI = 0;
2477   for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2478     if (!(isa<Constant>(I->getOperand(Op)) ||
2479           isa<GlobalValue>(I->getOperand(Op)))) {
2480       PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2481       if (P == 0) return 0;  // Not evolving from PHI
2482       if (PHI == 0)
2483         PHI = P;
2484       else if (PHI != P)
2485         return 0;  // Evolving from multiple different PHIs.
2486     }
2487
2488   // This is a expression evolving from a constant PHI!
2489   return PHI;
2490 }
2491
2492 /// EvaluateExpression - Given an expression that passes the
2493 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2494 /// in the loop has the value PHIVal.  If we can't fold this expression for some
2495 /// reason, return null.
2496 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2497   if (isa<PHINode>(V)) return PHIVal;
2498   if (Constant *C = dyn_cast<Constant>(V)) return C;
2499   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
2500   Instruction *I = cast<Instruction>(V);
2501
2502   std::vector<Constant*> Operands;
2503   Operands.resize(I->getNumOperands());
2504
2505   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2506     Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2507     if (Operands[i] == 0) return 0;
2508   }
2509
2510   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2511     return ConstantFoldCompareInstOperands(CI->getPredicate(),
2512                                            &Operands[0], Operands.size());
2513   else
2514     return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2515                                     &Operands[0], Operands.size());
2516 }
2517
2518 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2519 /// in the header of its containing loop, we know the loop executes a
2520 /// constant number of times, and the PHI node is just a recurrence
2521 /// involving constants, fold it.
2522 Constant *ScalarEvolutionsImpl::
2523 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
2524   std::map<PHINode*, Constant*>::iterator I =
2525     ConstantEvolutionLoopExitValue.find(PN);
2526   if (I != ConstantEvolutionLoopExitValue.end())
2527     return I->second;
2528
2529   if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
2530     return ConstantEvolutionLoopExitValue[PN] = 0;  // Not going to evaluate it.
2531
2532   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2533
2534   // Since the loop is canonicalized, the PHI node must have two entries.  One
2535   // entry must be a constant (coming in from outside of the loop), and the
2536   // second must be derived from the same PHI.
2537   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2538   Constant *StartCST =
2539     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2540   if (StartCST == 0)
2541     return RetVal = 0;  // Must be a constant.
2542
2543   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2544   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2545   if (PN2 != PN)
2546     return RetVal = 0;  // Not derived from same PHI.
2547
2548   // Execute the loop symbolically to determine the exit value.
2549   if (BEs.getActiveBits() >= 32)
2550     return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2551
2552   unsigned NumIterations = BEs.getZExtValue(); // must be in range
2553   unsigned IterationNum = 0;
2554   for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2555     if (IterationNum == NumIterations)
2556       return RetVal = PHIVal;  // Got exit value!
2557
2558     // Compute the value of the PHI node for the next iteration.
2559     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2560     if (NextPHI == PHIVal)
2561       return RetVal = NextPHI;  // Stopped evolving!
2562     if (NextPHI == 0)
2563       return 0;        // Couldn't evaluate!
2564     PHIVal = NextPHI;
2565   }
2566 }
2567
2568 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
2569 /// constant number of times (the condition evolves only from constants),
2570 /// try to evaluate a few iterations of the loop until we get the exit
2571 /// condition gets a value of ExitWhen (true or false).  If we cannot
2572 /// evaluate the trip count of the loop, return UnknownValue.
2573 SCEVHandle ScalarEvolutionsImpl::
2574 ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2575   PHINode *PN = getConstantEvolvingPHI(Cond, L);
2576   if (PN == 0) return UnknownValue;
2577
2578   // Since the loop is canonicalized, the PHI node must have two entries.  One
2579   // entry must be a constant (coming in from outside of the loop), and the
2580   // second must be derived from the same PHI.
2581   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2582   Constant *StartCST =
2583     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2584   if (StartCST == 0) return UnknownValue;  // Must be a constant.
2585
2586   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2587   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2588   if (PN2 != PN) return UnknownValue;  // Not derived from same PHI.
2589
2590   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
2591   // the loop symbolically to determine when the condition gets a value of
2592   // "ExitWhen".
2593   unsigned IterationNum = 0;
2594   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
2595   for (Constant *PHIVal = StartCST;
2596        IterationNum != MaxIterations; ++IterationNum) {
2597     ConstantInt *CondVal =
2598       dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2599
2600     // Couldn't symbolically evaluate.
2601     if (!CondVal) return UnknownValue;
2602
2603     if (CondVal->getValue() == uint64_t(ExitWhen)) {
2604       ConstantEvolutionLoopExitValue[PN] = PHIVal;
2605       ++NumBruteForceTripCountsComputed;
2606       return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2607     }
2608
2609     // Compute the value of the PHI node for the next iteration.
2610     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2611     if (NextPHI == 0 || NextPHI == PHIVal)
2612       return UnknownValue;  // Couldn't evaluate or not making progress...
2613     PHIVal = NextPHI;
2614   }
2615
2616   // Too many iterations were needed to evaluate.
2617   return UnknownValue;
2618 }
2619
2620 /// getSCEVAtScope - Compute the value of the specified expression within the
2621 /// indicated loop (which may be null to indicate in no loop).  If the
2622 /// expression cannot be evaluated, return UnknownValue.
2623 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2624   // FIXME: this should be turned into a virtual method on SCEV!
2625
2626   if (isa<SCEVConstant>(V)) return V;
2627
2628   // If this instruction is evolved from a constant-evolving PHI, compute the
2629   // exit value from the loop without using SCEVs.
2630   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2631     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2632       const Loop *LI = this->LI[I->getParent()];
2633       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
2634         if (PHINode *PN = dyn_cast<PHINode>(I))
2635           if (PN->getParent() == LI->getHeader()) {
2636             // Okay, there is no closed form solution for the PHI node.  Check
2637             // to see if the loop that contains it has a known backedge-taken
2638             // count.  If so, we may be able to force computation of the exit
2639             // value.
2640             SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2641             if (SCEVConstant *BTCC =
2642                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
2643               // Okay, we know how many times the containing loop executes.  If
2644               // this is a constant evolving PHI node, get the final value at
2645               // the specified iteration number.
2646               Constant *RV = getConstantEvolutionLoopExitValue(PN,
2647                                                    BTCC->getValue()->getValue(),
2648                                                                LI);
2649               if (RV) return SE.getUnknown(RV);
2650             }
2651           }
2652
2653       // Okay, this is an expression that we cannot symbolically evaluate
2654       // into a SCEV.  Check to see if it's possible to symbolically evaluate
2655       // the arguments into constants, and if so, try to constant propagate the
2656       // result.  This is particularly useful for computing loop exit values.
2657       if (CanConstantFold(I)) {
2658         std::vector<Constant*> Operands;
2659         Operands.reserve(I->getNumOperands());
2660         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2661           Value *Op = I->getOperand(i);
2662           if (Constant *C = dyn_cast<Constant>(Op)) {
2663             Operands.push_back(C);
2664           } else {
2665             // If any of the operands is non-constant and if they are
2666             // non-integer and non-pointer, don't even try to analyze them
2667             // with scev techniques.
2668             if (!isa<IntegerType>(Op->getType()) &&
2669                 !isa<PointerType>(Op->getType()))
2670               return V;
2671
2672             SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2673             if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2674               Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(), 
2675                                                               Op->getType(), 
2676                                                               false));
2677             else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2678               if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2679                 Operands.push_back(ConstantExpr::getIntegerCast(C, 
2680                                                                 Op->getType(), 
2681                                                                 false));
2682               else
2683                 return V;
2684             } else {
2685               return V;
2686             }
2687           }
2688         }
2689         
2690         Constant *C;
2691         if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2692           C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2693                                               &Operands[0], Operands.size());
2694         else
2695           C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2696                                        &Operands[0], Operands.size());
2697         return SE.getUnknown(C);
2698       }
2699     }
2700
2701     // This is some other type of SCEVUnknown, just return it.
2702     return V;
2703   }
2704
2705   if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2706     // Avoid performing the look-up in the common case where the specified
2707     // expression has no loop-variant portions.
2708     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2709       SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2710       if (OpAtScope != Comm->getOperand(i)) {
2711         if (OpAtScope == UnknownValue) return UnknownValue;
2712         // Okay, at least one of these operands is loop variant but might be
2713         // foldable.  Build a new instance of the folded commutative expression.
2714         std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2715         NewOps.push_back(OpAtScope);
2716
2717         for (++i; i != e; ++i) {
2718           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2719           if (OpAtScope == UnknownValue) return UnknownValue;
2720           NewOps.push_back(OpAtScope);
2721         }
2722         if (isa<SCEVAddExpr>(Comm))
2723           return SE.getAddExpr(NewOps);
2724         if (isa<SCEVMulExpr>(Comm))
2725           return SE.getMulExpr(NewOps);
2726         if (isa<SCEVSMaxExpr>(Comm))
2727           return SE.getSMaxExpr(NewOps);
2728         if (isa<SCEVUMaxExpr>(Comm))
2729           return SE.getUMaxExpr(NewOps);
2730         assert(0 && "Unknown commutative SCEV type!");
2731       }
2732     }
2733     // If we got here, all operands are loop invariant.
2734     return Comm;
2735   }
2736
2737   if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2738     SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2739     if (LHS == UnknownValue) return LHS;
2740     SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2741     if (RHS == UnknownValue) return RHS;
2742     if (LHS == Div->getLHS() && RHS == Div->getRHS())
2743       return Div;   // must be loop invariant
2744     return SE.getUDivExpr(LHS, RHS);
2745   }
2746
2747   // If this is a loop recurrence for a loop that does not contain L, then we
2748   // are dealing with the final value computed by the loop.
2749   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2750     if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2751       // To evaluate this recurrence, we need to know how many times the AddRec
2752       // loop iterates.  Compute this now.
2753       SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2754       if (BackedgeTakenCount == UnknownValue) return UnknownValue;
2755
2756       // Then, evaluate the AddRec.
2757       return AddRec->evaluateAtIteration(BackedgeTakenCount, SE);
2758     }
2759     return UnknownValue;
2760   }
2761
2762   //assert(0 && "Unknown SCEV type!");
2763   return UnknownValue;
2764 }
2765
2766 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2767 /// following equation:
2768 ///
2769 ///     A * X = B (mod N)
2770 ///
2771 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2772 /// A and B isn't important.
2773 ///
2774 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2775 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2776                                                ScalarEvolution &SE) {
2777   uint32_t BW = A.getBitWidth();
2778   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2779   assert(A != 0 && "A must be non-zero.");
2780
2781   // 1. D = gcd(A, N)
2782   //
2783   // The gcd of A and N may have only one prime factor: 2. The number of
2784   // trailing zeros in A is its multiplicity
2785   uint32_t Mult2 = A.countTrailingZeros();
2786   // D = 2^Mult2
2787
2788   // 2. Check if B is divisible by D.
2789   //
2790   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2791   // is not less than multiplicity of this prime factor for D.
2792   if (B.countTrailingZeros() < Mult2)
2793     return SE.getCouldNotCompute();
2794
2795   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2796   // modulo (N / D).
2797   //
2798   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
2799   // bit width during computations.
2800   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
2801   APInt Mod(BW + 1, 0);
2802   Mod.set(BW - Mult2);  // Mod = N / D
2803   APInt I = AD.multiplicativeInverse(Mod);
2804
2805   // 4. Compute the minimum unsigned root of the equation:
2806   // I * (B / D) mod (N / D)
2807   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2808
2809   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2810   // bits.
2811   return SE.getConstant(Result.trunc(BW));
2812 }
2813
2814 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2815 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
2816 /// might be the same) or two SCEVCouldNotCompute objects.
2817 ///
2818 static std::pair<SCEVHandle,SCEVHandle>
2819 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2820   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2821   SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2822   SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2823   SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2824
2825   // We currently can only solve this if the coefficients are constants.
2826   if (!LC || !MC || !NC) {
2827     SCEV *CNC = SE.getCouldNotCompute();
2828     return std::make_pair(CNC, CNC);
2829   }
2830
2831   uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2832   const APInt &L = LC->getValue()->getValue();
2833   const APInt &M = MC->getValue()->getValue();
2834   const APInt &N = NC->getValue()->getValue();
2835   APInt Two(BitWidth, 2);
2836   APInt Four(BitWidth, 4);
2837
2838   { 
2839     using namespace APIntOps;
2840     const APInt& C = L;
2841     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2842     // The B coefficient is M-N/2
2843     APInt B(M);
2844     B -= sdiv(N,Two);
2845
2846     // The A coefficient is N/2
2847     APInt A(N.sdiv(Two));
2848
2849     // Compute the B^2-4ac term.
2850     APInt SqrtTerm(B);
2851     SqrtTerm *= B;
2852     SqrtTerm -= Four * (A * C);
2853
2854     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2855     // integer value or else APInt::sqrt() will assert.
2856     APInt SqrtVal(SqrtTerm.sqrt());
2857
2858     // Compute the two solutions for the quadratic formula. 
2859     // The divisions must be performed as signed divisions.
2860     APInt NegB(-B);
2861     APInt TwoA( A << 1 );
2862     if (TwoA.isMinValue()) {
2863       SCEV *CNC = SE.getCouldNotCompute();
2864       return std::make_pair(CNC, CNC);
2865     }
2866
2867     ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2868     ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2869
2870     return std::make_pair(SE.getConstant(Solution1), 
2871                           SE.getConstant(Solution2));
2872     } // end APIntOps namespace
2873 }
2874
2875 /// HowFarToZero - Return the number of times a backedge comparing the specified
2876 /// value to zero will execute.  If not computable, return UnknownValue
2877 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2878   // If the value is a constant
2879   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2880     // If the value is already zero, the branch will execute zero times.
2881     if (C->getValue()->isZero()) return C;
2882     return UnknownValue;  // Otherwise it will loop infinitely.
2883   }
2884
2885   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2886   if (!AddRec || AddRec->getLoop() != L)
2887     return UnknownValue;
2888
2889   if (AddRec->isAffine()) {
2890     // If this is an affine expression, the execution count of this branch is
2891     // the minimum unsigned root of the following equation:
2892     //
2893     //     Start + Step*N = 0 (mod 2^BW)
2894     //
2895     // equivalent to:
2896     //
2897     //             Step*N = -Start (mod 2^BW)
2898     //
2899     // where BW is the common bit width of Start and Step.
2900
2901     // Get the initial value for the loop.
2902     SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2903     if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2904
2905     SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
2906
2907     if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2908       // For now we handle only constant steps.
2909
2910       // First, handle unitary steps.
2911       if (StepC->getValue()->equalsInt(1))      // 1*N = -Start (mod 2^BW), so:
2912         return SE.getNegativeSCEV(Start);       //   N = -Start (as unsigned)
2913       if (StepC->getValue()->isAllOnesValue())  // -1*N = -Start (mod 2^BW), so:
2914         return Start;                           //    N = Start (as unsigned)
2915
2916       // Then, try to solve the above equation provided that Start is constant.
2917       if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2918         return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2919                                             -StartC->getValue()->getValue(),SE);
2920     }
2921   } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2922     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2923     // the quadratic equation to solve it.
2924     std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
2925     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2926     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2927     if (R1) {
2928 #if 0
2929       errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2930              << "  sol#2: " << *R2 << "\n";
2931 #endif
2932       // Pick the smallest positive root value.
2933       if (ConstantInt *CB =
2934           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 
2935                                    R1->getValue(), R2->getValue()))) {
2936         if (CB->getZExtValue() == false)
2937           std::swap(R1, R2);   // R1 is the minimum root now.
2938
2939         // We can only use this value if the chrec ends up with an exact zero
2940         // value at this index.  When solving for "X*X != 5", for example, we
2941         // should not accept a root of 2.
2942         SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
2943         if (Val->isZero())
2944           return R1;  // We found a quadratic root!
2945       }
2946     }
2947   }
2948
2949   return UnknownValue;
2950 }
2951
2952 /// HowFarToNonZero - Return the number of times a backedge checking the
2953 /// specified value for nonzero will execute.  If not computable, return
2954 /// UnknownValue
2955 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2956   // Loops that look like: while (X == 0) are very strange indeed.  We don't
2957   // handle them yet except for the trivial case.  This could be expanded in the
2958   // future as needed.
2959
2960   // If the value is a constant, check to see if it is known to be non-zero
2961   // already.  If so, the backedge will execute zero times.
2962   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2963     if (!C->getValue()->isNullValue())
2964       return SE.getIntegerSCEV(0, C->getType());
2965     return UnknownValue;  // Otherwise it will loop infinitely.
2966   }
2967
2968   // We could implement others, but I really doubt anyone writes loops like
2969   // this, and if they did, they would already be constant folded.
2970   return UnknownValue;
2971 }
2972
2973 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2974 /// (which may not be an immediate predecessor) which has exactly one
2975 /// successor from which BB is reachable, or null if no such block is
2976 /// found.
2977 ///
2978 BasicBlock *
2979 ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2980   // If the block has a unique predecessor, the predecessor must have
2981   // no other successors from which BB is reachable.
2982   if (BasicBlock *Pred = BB->getSinglePredecessor())
2983     return Pred;
2984
2985   // A loop's header is defined to be a block that dominates the loop.
2986   // If the loop has a preheader, it must be a block that has exactly
2987   // one successor that can reach BB. This is slightly more strict
2988   // than necessary, but works if critical edges are split.
2989   if (Loop *L = LI.getLoopFor(BB))
2990     return L->getLoopPreheader();
2991
2992   return 0;
2993 }
2994
2995 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
2996 /// a conditional between LHS and RHS.
2997 bool ScalarEvolutionsImpl::isLoopGuardedByCond(const Loop *L,
2998                                                ICmpInst::Predicate Pred,
2999                                                SCEV *LHS, SCEV *RHS) {
3000   BasicBlock *Preheader = L->getLoopPreheader();
3001   BasicBlock *PreheaderDest = L->getHeader();
3002
3003   // Starting at the preheader, climb up the predecessor chain, as long as
3004   // there are predecessors that can be found that have unique successors
3005   // leading to the original header.
3006   for (; Preheader;
3007        PreheaderDest = Preheader,
3008        Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
3009
3010     BranchInst *LoopEntryPredicate =
3011       dyn_cast<BranchInst>(Preheader->getTerminator());
3012     if (!LoopEntryPredicate ||
3013         LoopEntryPredicate->isUnconditional())
3014       continue;
3015
3016     ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3017     if (!ICI) continue;
3018
3019     // Now that we found a conditional branch that dominates the loop, check to
3020     // see if it is the comparison we are looking for.
3021     Value *PreCondLHS = ICI->getOperand(0);
3022     Value *PreCondRHS = ICI->getOperand(1);
3023     ICmpInst::Predicate Cond;
3024     if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3025       Cond = ICI->getPredicate();
3026     else
3027       Cond = ICI->getInversePredicate();
3028
3029     if (Cond == Pred)
3030       ; // An exact match.
3031     else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3032       ; // The actual condition is beyond sufficient.
3033     else
3034       // Check a few special cases.
3035       switch (Cond) {
3036       case ICmpInst::ICMP_UGT:
3037         if (Pred == ICmpInst::ICMP_ULT) {
3038           std::swap(PreCondLHS, PreCondRHS);
3039           Cond = ICmpInst::ICMP_ULT;
3040           break;
3041         }
3042         continue;
3043       case ICmpInst::ICMP_SGT:
3044         if (Pred == ICmpInst::ICMP_SLT) {
3045           std::swap(PreCondLHS, PreCondRHS);
3046           Cond = ICmpInst::ICMP_SLT;
3047           break;
3048         }
3049         continue;
3050       case ICmpInst::ICMP_NE:
3051         // Expressions like (x >u 0) are often canonicalized to (x != 0),
3052         // so check for this case by checking if the NE is comparing against
3053         // a minimum or maximum constant.
3054         if (!ICmpInst::isTrueWhenEqual(Pred))
3055           if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3056             const APInt &A = CI->getValue();
3057             switch (Pred) {
3058             case ICmpInst::ICMP_SLT:
3059               if (A.isMaxSignedValue()) break;
3060               continue;
3061             case ICmpInst::ICMP_SGT:
3062               if (A.isMinSignedValue()) break;
3063               continue;
3064             case ICmpInst::ICMP_ULT:
3065               if (A.isMaxValue()) break;
3066               continue;
3067             case ICmpInst::ICMP_UGT:
3068               if (A.isMinValue()) break;
3069               continue;
3070             default:
3071               continue;
3072             }
3073             Cond = ICmpInst::ICMP_NE;
3074             // NE is symmetric but the original comparison may not be. Swap
3075             // the operands if necessary so that they match below.
3076             if (isa<SCEVConstant>(LHS))
3077               std::swap(PreCondLHS, PreCondRHS);
3078             break;
3079           }
3080         continue;
3081       default:
3082         // We weren't able to reconcile the condition.
3083         continue;
3084       }
3085
3086     if (!PreCondLHS->getType()->isInteger()) continue;
3087
3088     SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3089     SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3090     if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3091         (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
3092          RHS == SE.getNotSCEV(PreCondLHSSCEV)))
3093       return true;
3094   }
3095
3096   return false;
3097 }
3098
3099 /// HowManyLessThans - Return the number of times a backedge containing the
3100 /// specified less-than comparison will execute.  If not computable, return
3101 /// UnknownValue.
3102 SCEVHandle ScalarEvolutionsImpl::
3103 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
3104   // Only handle:  "ADDREC < LoopInvariant".
3105   if (!RHS->isLoopInvariant(L)) return UnknownValue;
3106
3107   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3108   if (!AddRec || AddRec->getLoop() != L)
3109     return UnknownValue;
3110
3111   if (AddRec->isAffine()) {
3112     // FORNOW: We only support unit strides.
3113     SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
3114     if (AddRec->getOperand(1) != One)
3115       return UnknownValue;
3116
3117     // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
3118     // m.  So, we count the number of iterations in which {n,+,1} < m is true.
3119     // Note that we cannot simply return max(m-n,0) because it's not safe to
3120     // treat m-n as signed nor unsigned due to overflow possibility.
3121
3122     // First, we get the value of the LHS in the first iteration: n
3123     SCEVHandle Start = AddRec->getOperand(0);
3124
3125     if (isLoopGuardedByCond(L,
3126                             isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3127                             SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
3128       // Since we know that the condition is true in order to enter the loop,
3129       // we know that it will run exactly m-n times.
3130       return SE.getMinusSCEV(RHS, Start);
3131     } else {
3132       // Then, we get the value of the LHS in the first iteration in which the
3133       // above condition doesn't hold.  This equals to max(m,n).
3134       SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
3135                                 : SE.getUMaxExpr(RHS, Start);
3136
3137       // Finally, we subtract these two values to get the number of times the
3138       // backedge is executed: max(m,n)-n.
3139       return SE.getMinusSCEV(End, Start);
3140     }
3141   }
3142
3143   return UnknownValue;
3144 }
3145
3146 /// getNumIterationsInRange - Return the number of iterations of this loop that
3147 /// produce values in the specified constant range.  Another way of looking at
3148 /// this is that it returns the first iteration number where the value is not in
3149 /// the condition, thus computing the exit count. If the iteration count can't
3150 /// be computed, an instance of SCEVCouldNotCompute is returned.
3151 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3152                                                    ScalarEvolution &SE) const {
3153   if (Range.isFullSet())  // Infinite loop.
3154     return SE.getCouldNotCompute();
3155
3156   // If the start is a non-zero constant, shift the range to simplify things.
3157   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3158     if (!SC->getValue()->isZero()) {
3159       std::vector<SCEVHandle> Operands(op_begin(), op_end());
3160       Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3161       SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3162       if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3163         return ShiftedAddRec->getNumIterationsInRange(
3164                            Range.subtract(SC->getValue()->getValue()), SE);
3165       // This is strange and shouldn't happen.
3166       return SE.getCouldNotCompute();
3167     }
3168
3169   // The only time we can solve this is when we have all constant indices.
3170   // Otherwise, we cannot determine the overflow conditions.
3171   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3172     if (!isa<SCEVConstant>(getOperand(i)))
3173       return SE.getCouldNotCompute();
3174
3175
3176   // Okay at this point we know that all elements of the chrec are constants and
3177   // that the start element is zero.
3178
3179   // First check to see if the range contains zero.  If not, the first
3180   // iteration exits.
3181   unsigned BitWidth = SE.getTypeSizeInBits(getType());
3182   if (!Range.contains(APInt(BitWidth, 0)))
3183     return SE.getConstant(ConstantInt::get(getType(),0));
3184
3185   if (isAffine()) {
3186     // If this is an affine expression then we have this situation:
3187     //   Solve {0,+,A} in Range  ===  Ax in Range
3188
3189     // We know that zero is in the range.  If A is positive then we know that
3190     // the upper value of the range must be the first possible exit value.
3191     // If A is negative then the lower of the range is the last possible loop
3192     // value.  Also note that we already checked for a full range.
3193     APInt One(BitWidth,1);
3194     APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3195     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3196
3197     // The exit value should be (End+A)/A.
3198     APInt ExitVal = (End + A).udiv(A);
3199     ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3200
3201     // Evaluate at the exit value.  If we really did fall out of the valid
3202     // range, then we computed our trip count, otherwise wrap around or other
3203     // things must have happened.
3204     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3205     if (Range.contains(Val->getValue()))
3206       return SE.getCouldNotCompute();  // Something strange happened
3207
3208     // Ensure that the previous value is in the range.  This is a sanity check.
3209     assert(Range.contains(
3210            EvaluateConstantChrecAtConstant(this, 
3211            ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3212            "Linear scev computation is off in a bad way!");
3213     return SE.getConstant(ExitValue);
3214   } else if (isQuadratic()) {
3215     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3216     // quadratic equation to solve it.  To do this, we must frame our problem in
3217     // terms of figuring out when zero is crossed, instead of when
3218     // Range.getUpper() is crossed.
3219     std::vector<SCEVHandle> NewOps(op_begin(), op_end());
3220     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3221     SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3222
3223     // Next, solve the constructed addrec
3224     std::pair<SCEVHandle,SCEVHandle> Roots =
3225       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3226     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3227     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3228     if (R1) {
3229       // Pick the smallest positive root value.
3230       if (ConstantInt *CB =
3231           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 
3232                                    R1->getValue(), R2->getValue()))) {
3233         if (CB->getZExtValue() == false)
3234           std::swap(R1, R2);   // R1 is the minimum root now.
3235
3236         // Make sure the root is not off by one.  The returned iteration should
3237         // not be in the range, but the previous one should be.  When solving
3238         // for "X*X < 5", for example, we should not return a root of 2.
3239         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3240                                                              R1->getValue(),
3241                                                              SE);
3242         if (Range.contains(R1Val->getValue())) {
3243           // The next iteration must be out of the range...
3244           ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3245
3246           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3247           if (!Range.contains(R1Val->getValue()))
3248             return SE.getConstant(NextVal);
3249           return SE.getCouldNotCompute();  // Something strange happened
3250         }
3251
3252         // If R1 was not in the range, then it is a good return value.  Make
3253         // sure that R1-1 WAS in the range though, just in case.
3254         ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3255         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3256         if (Range.contains(R1Val->getValue()))
3257           return R1;
3258         return SE.getCouldNotCompute();  // Something strange happened
3259       }
3260     }
3261   }
3262
3263   return SE.getCouldNotCompute();
3264 }
3265
3266
3267
3268 //===----------------------------------------------------------------------===//
3269 //                   ScalarEvolution Class Implementation
3270 //===----------------------------------------------------------------------===//
3271
3272 bool ScalarEvolution::runOnFunction(Function &F) {
3273   Impl = new ScalarEvolutionsImpl(*this, F,
3274                                   getAnalysis<LoopInfo>(),
3275                                   getAnalysisIfAvailable<TargetData>());
3276   return false;
3277 }
3278
3279 void ScalarEvolution::releaseMemory() {
3280   delete (ScalarEvolutionsImpl*)Impl;
3281   Impl = 0;
3282 }
3283
3284 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3285   AU.setPreservesAll();
3286   AU.addRequiredTransitive<LoopInfo>();
3287 }
3288
3289 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
3290   return ((ScalarEvolutionsImpl*)Impl)->isSCEVable(Ty);
3291 }
3292
3293 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
3294   return ((ScalarEvolutionsImpl*)Impl)->getTypeSizeInBits(Ty);
3295 }
3296
3297 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
3298   return ((ScalarEvolutionsImpl*)Impl)->getEffectiveSCEVType(Ty);
3299 }
3300
3301 SCEVHandle ScalarEvolution::getCouldNotCompute() {
3302   return ((ScalarEvolutionsImpl*)Impl)->getCouldNotCompute();
3303 }
3304
3305 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
3306   return ((ScalarEvolutionsImpl*)Impl)->getIntegerSCEV(Val, Ty);
3307 }
3308
3309 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3310   return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3311 }
3312
3313 /// hasSCEV - Return true if the SCEV for this value has already been
3314 /// computed.
3315 bool ScalarEvolution::hasSCEV(Value *V) const {
3316   return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3317 }
3318
3319
3320 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3321 /// the specified value.
3322 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3323   ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3324 }
3325
3326 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3327 ///
3328 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
3329   return ((ScalarEvolutionsImpl*)Impl)->getNegativeSCEV(V);
3330 }
3331
3332 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3333 ///
3334 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
3335   return ((ScalarEvolutionsImpl*)Impl)->getNotSCEV(V);
3336 }
3337
3338 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
3339 ///
3340 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
3341                                          const SCEVHandle &RHS) {
3342   return ((ScalarEvolutionsImpl*)Impl)->getMinusSCEV(LHS, RHS);
3343 }
3344
3345 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
3346 /// of the input value to the specified type.  If the type must be
3347 /// extended, it is zero extended.
3348 SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
3349                                                     const Type *Ty) {
3350   return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrZeroExtend(V, Ty);
3351 }
3352
3353 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
3354 /// of the input value to the specified type.  If the type must be
3355 /// extended, it is sign extended.
3356 SCEVHandle ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
3357                                                     const Type *Ty) {
3358   return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrSignExtend(V, Ty);
3359 }
3360
3361
3362 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3363                                           ICmpInst::Predicate Pred,
3364                                           SCEV *LHS, SCEV *RHS) {
3365   return ((ScalarEvolutionsImpl*)Impl)->isLoopGuardedByCond(L, Pred,
3366                                                             LHS, RHS);
3367 }
3368
3369 SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) const {
3370   return ((ScalarEvolutionsImpl*)Impl)->getBackedgeTakenCount(L);
3371 }
3372
3373 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) const {
3374   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
3375 }
3376
3377 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3378   return ((ScalarEvolutionsImpl*)Impl)->forgetLoopBackedgeTakenCount(L);
3379 }
3380
3381 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3382   return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3383 }
3384
3385 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3386   return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3387 }
3388
3389 static void PrintLoopInfo(raw_ostream &OS, const ScalarEvolution *SE,
3390                           const Loop *L) {
3391   // Print all inner loops first
3392   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3393     PrintLoopInfo(OS, SE, *I);
3394
3395   OS << "Loop " << L->getHeader()->getName() << ": ";
3396
3397   SmallVector<BasicBlock*, 8> ExitBlocks;
3398   L->getExitBlocks(ExitBlocks);
3399   if (ExitBlocks.size() != 1)
3400     OS << "<multiple exits> ";
3401
3402   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3403     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
3404   } else {
3405     OS << "Unpredictable backedge-taken count. ";
3406   }
3407
3408   OS << "\n";
3409 }
3410
3411 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
3412   Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3413   LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3414
3415   OS << "Classifying expressions for: " << F.getName() << "\n";
3416   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3417     if (I->getType()->isInteger()) {
3418       OS << *I;
3419       OS << "  -->  ";
3420       SCEVHandle SV = getSCEV(&*I);
3421       SV->print(OS);
3422       OS << "\t\t";
3423
3424       if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3425         OS << "Exits: ";
3426         SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3427         if (isa<SCEVCouldNotCompute>(ExitValue)) {
3428           OS << "<<Unknown>>";
3429         } else {
3430           OS << *ExitValue;
3431         }
3432       }
3433
3434
3435       OS << "\n";
3436     }
3437
3438   OS << "Determining loop execution counts for: " << F.getName() << "\n";
3439   for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3440     PrintLoopInfo(OS, this, *I);
3441 }
3442
3443 void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3444   raw_os_ostream OS(o);
3445   print(OS, M);
3446 }