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