3ae65286fa731547faf1862e7b637e21d4a3e6d8
[oota-llvm.git] / lib / Analysis / ScalarEvolution.cpp
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/LoopInfo.h"
70 #include "llvm/Assembly/Writer.h"
71 #include "llvm/Transforms/Scalar.h"
72 #include "llvm/Support/CFG.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/ConstantRange.h"
76 #include "llvm/Support/InstIterator.h"
77 #include "llvm/Support/ManagedStatic.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/Streams.h"
80 #include "llvm/ADT/Statistic.h"
81 #include <ostream>
82 #include <algorithm>
83 #include <cmath>
84 using namespace llvm;
85
86 STATISTIC(NumBruteForceEvaluations,
87           "Number of brute force evaluations needed to "
88           "calculate high-order polynomial exit values");
89 STATISTIC(NumArrayLenItCounts,
90           "Number of trip counts computed with array length");
91 STATISTIC(NumTripCountsComputed,
92           "Number of loops with predictable loop counts");
93 STATISTIC(NumTripCountsNotComputed,
94           "Number of loops without predictable loop counts");
95 STATISTIC(NumBruteForceTripCountsComputed,
96           "Number of loops with trip counts computed by force");
97
98 cl::opt<unsigned>
99 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100                         cl::desc("Maximum number of iterations SCEV will "
101                                  "symbolically execute a constant derived loop"),
102                         cl::init(100));
103
104 namespace {
105   RegisterPass<ScalarEvolution>
106   R("scalar-evolution", "Scalar Evolution Analysis");
107 }
108 char ScalarEvolution::ID = 0;
109
110 //===----------------------------------------------------------------------===//
111 //                           SCEV class definitions
112 //===----------------------------------------------------------------------===//
113
114 //===----------------------------------------------------------------------===//
115 // Implementation of the SCEV class.
116 //
117 SCEV::~SCEV() {}
118 void SCEV::dump() const {
119   print(cerr);
120 }
121
122 /// getValueRange - Return the tightest constant bounds that this value is
123 /// known to have.  This method is only valid on integer SCEV objects.
124 ConstantRange SCEV::getValueRange() const {
125   const Type *Ty = getType();
126   assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
127   // Default to a full range if no better information is available.
128   return ConstantRange(getBitWidth());
129 }
130
131 uint32_t SCEV::getBitWidth() const {
132   if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
133     return ITy->getBitWidth();
134   return 0;
135 }
136
137
138 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
139
140 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
142   return false;
143 }
144
145 const Type *SCEVCouldNotCompute::getType() const {
146   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147   return 0;
148 }
149
150 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152   return false;
153 }
154
155 SCEVHandle SCEVCouldNotCompute::
156 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
157                                   const SCEVHandle &Conc) const {
158   return this;
159 }
160
161 void SCEVCouldNotCompute::print(std::ostream &OS) const {
162   OS << "***COULDNOTCOMPUTE***";
163 }
164
165 bool SCEVCouldNotCompute::classof(const SCEV *S) {
166   return S->getSCEVType() == scCouldNotCompute;
167 }
168
169
170 // SCEVConstants - Only allow the creation of one SCEVConstant for any
171 // particular value.  Don't use a SCEVHandle here, or else the object will
172 // never be deleted!
173 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
174
175
176 SCEVConstant::~SCEVConstant() {
177   SCEVConstants->erase(V);
178 }
179
180 SCEVHandle SCEVConstant::get(ConstantInt *V) {
181   SCEVConstant *&R = (*SCEVConstants)[V];
182   if (R == 0) R = new SCEVConstant(V);
183   return R;
184 }
185
186 ConstantRange SCEVConstant::getValueRange() const {
187   return ConstantRange(V->getValue());
188 }
189
190 const Type *SCEVConstant::getType() const { return V->getType(); }
191
192 void SCEVConstant::print(std::ostream &OS) const {
193   WriteAsOperand(OS, V, false);
194 }
195
196 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
197 // particular input.  Don't use a SCEVHandle here, or else the object will
198 // never be deleted!
199 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, 
200                      SCEVTruncateExpr*> > SCEVTruncates;
201
202 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
203   : SCEV(scTruncate), Op(op), Ty(ty) {
204   assert(Op->getType()->isInteger() && Ty->isInteger() &&
205          "Cannot truncate non-integer value!");
206   assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
207          && "This is not a truncating conversion!");
208 }
209
210 SCEVTruncateExpr::~SCEVTruncateExpr() {
211   SCEVTruncates->erase(std::make_pair(Op, Ty));
212 }
213
214 ConstantRange SCEVTruncateExpr::getValueRange() const {
215   return getOperand()->getValueRange().truncate(getBitWidth());
216 }
217
218 void SCEVTruncateExpr::print(std::ostream &OS) const {
219   OS << "(truncate " << *Op << " to " << *Ty << ")";
220 }
221
222 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
223 // particular input.  Don't use a SCEVHandle here, or else the object will never
224 // be deleted!
225 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
226                      SCEVZeroExtendExpr*> > SCEVZeroExtends;
227
228 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
229   : SCEV(scZeroExtend), Op(op), Ty(ty) {
230   assert(Op->getType()->isInteger() && Ty->isInteger() &&
231          "Cannot zero extend non-integer value!");
232   assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
233          && "This is not an extending conversion!");
234 }
235
236 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
237   SCEVZeroExtends->erase(std::make_pair(Op, Ty));
238 }
239
240 ConstantRange SCEVZeroExtendExpr::getValueRange() const {
241   return getOperand()->getValueRange().zeroExtend(getBitWidth());
242 }
243
244 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
245   OS << "(zeroextend " << *Op << " to " << *Ty << ")";
246 }
247
248 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
249 // particular input.  Don't use a SCEVHandle here, or else the object will never
250 // be deleted!
251 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
252                      SCEVSignExtendExpr*> > SCEVSignExtends;
253
254 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
255   : SCEV(scSignExtend), Op(op), Ty(ty) {
256   assert(Op->getType()->isInteger() && Ty->isInteger() &&
257          "Cannot sign extend non-integer value!");
258   assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
259          && "This is not an extending conversion!");
260 }
261
262 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
263   SCEVSignExtends->erase(std::make_pair(Op, Ty));
264 }
265
266 ConstantRange SCEVSignExtendExpr::getValueRange() const {
267   return getOperand()->getValueRange().signExtend(getBitWidth());
268 }
269
270 void SCEVSignExtendExpr::print(std::ostream &OS) const {
271   OS << "(signextend " << *Op << " to " << *Ty << ")";
272 }
273
274 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
275 // particular input.  Don't use a SCEVHandle here, or else the object will never
276 // be deleted!
277 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
278                      SCEVCommutativeExpr*> > SCEVCommExprs;
279
280 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
281   SCEVCommExprs->erase(std::make_pair(getSCEVType(),
282                                       std::vector<SCEV*>(Operands.begin(),
283                                                          Operands.end())));
284 }
285
286 void SCEVCommutativeExpr::print(std::ostream &OS) const {
287   assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
288   const char *OpStr = getOperationStr();
289   OS << "(" << *Operands[0];
290   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
291     OS << OpStr << *Operands[i];
292   OS << ")";
293 }
294
295 SCEVHandle SCEVCommutativeExpr::
296 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
297                                   const SCEVHandle &Conc) const {
298   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
299     SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
300     if (H != getOperand(i)) {
301       std::vector<SCEVHandle> NewOps;
302       NewOps.reserve(getNumOperands());
303       for (unsigned j = 0; j != i; ++j)
304         NewOps.push_back(getOperand(j));
305       NewOps.push_back(H);
306       for (++i; i != e; ++i)
307         NewOps.push_back(getOperand(i)->
308                          replaceSymbolicValuesWithConcrete(Sym, Conc));
309
310       if (isa<SCEVAddExpr>(this))
311         return SCEVAddExpr::get(NewOps);
312       else if (isa<SCEVMulExpr>(this))
313         return SCEVMulExpr::get(NewOps);
314       else
315         assert(0 && "Unknown commutative expr!");
316     }
317   }
318   return this;
319 }
320
321
322 // SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
323 // input.  Don't use a SCEVHandle here, or else the object will never be
324 // deleted!
325 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>, 
326                      SCEVSDivExpr*> > SCEVSDivs;
327
328 SCEVSDivExpr::~SCEVSDivExpr() {
329   SCEVSDivs->erase(std::make_pair(LHS, RHS));
330 }
331
332 void SCEVSDivExpr::print(std::ostream &OS) const {
333   OS << "(" << *LHS << " /s " << *RHS << ")";
334 }
335
336 const Type *SCEVSDivExpr::getType() const {
337   return LHS->getType();
338 }
339
340 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
341 // particular input.  Don't use a SCEVHandle here, or else the object will never
342 // be deleted!
343 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
344                      SCEVAddRecExpr*> > SCEVAddRecExprs;
345
346 SCEVAddRecExpr::~SCEVAddRecExpr() {
347   SCEVAddRecExprs->erase(std::make_pair(L,
348                                         std::vector<SCEV*>(Operands.begin(),
349                                                            Operands.end())));
350 }
351
352 SCEVHandle SCEVAddRecExpr::
353 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
354                                   const SCEVHandle &Conc) const {
355   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
356     SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
357     if (H != getOperand(i)) {
358       std::vector<SCEVHandle> NewOps;
359       NewOps.reserve(getNumOperands());
360       for (unsigned j = 0; j != i; ++j)
361         NewOps.push_back(getOperand(j));
362       NewOps.push_back(H);
363       for (++i; i != e; ++i)
364         NewOps.push_back(getOperand(i)->
365                          replaceSymbolicValuesWithConcrete(Sym, Conc));
366
367       return get(NewOps, L);
368     }
369   }
370   return this;
371 }
372
373
374 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
375   // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
376   // contain L and if the start is invariant.
377   return !QueryLoop->contains(L->getHeader()) &&
378          getOperand(0)->isLoopInvariant(QueryLoop);
379 }
380
381
382 void SCEVAddRecExpr::print(std::ostream &OS) const {
383   OS << "{" << *Operands[0];
384   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
385     OS << ",+," << *Operands[i];
386   OS << "}<" << L->getHeader()->getName() + ">";
387 }
388
389 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
390 // value.  Don't use a SCEVHandle here, or else the object will never be
391 // deleted!
392 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
393
394 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
395
396 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
397   // All non-instruction values are loop invariant.  All instructions are loop
398   // invariant if they are not contained in the specified loop.
399   if (Instruction *I = dyn_cast<Instruction>(V))
400     return !L->contains(I->getParent());
401   return true;
402 }
403
404 const Type *SCEVUnknown::getType() const {
405   return V->getType();
406 }
407
408 void SCEVUnknown::print(std::ostream &OS) const {
409   WriteAsOperand(OS, V, false);
410 }
411
412 //===----------------------------------------------------------------------===//
413 //                               SCEV Utilities
414 //===----------------------------------------------------------------------===//
415
416 namespace {
417   /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
418   /// than the complexity of the RHS.  This comparator is used to canonicalize
419   /// expressions.
420   struct VISIBILITY_HIDDEN SCEVComplexityCompare {
421     bool operator()(SCEV *LHS, SCEV *RHS) {
422       return LHS->getSCEVType() < RHS->getSCEVType();
423     }
424   };
425 }
426
427 /// GroupByComplexity - Given a list of SCEV objects, order them by their
428 /// complexity, and group objects of the same complexity together by value.
429 /// When this routine is finished, we know that any duplicates in the vector are
430 /// consecutive and that complexity is monotonically increasing.
431 ///
432 /// Note that we go take special precautions to ensure that we get determinstic
433 /// results from this routine.  In other words, we don't want the results of
434 /// this to depend on where the addresses of various SCEV objects happened to
435 /// land in memory.
436 ///
437 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
438   if (Ops.size() < 2) return;  // Noop
439   if (Ops.size() == 2) {
440     // This is the common case, which also happens to be trivially simple.
441     // Special case it.
442     if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
443       std::swap(Ops[0], Ops[1]);
444     return;
445   }
446
447   // Do the rough sort by complexity.
448   std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
449
450   // Now that we are sorted by complexity, group elements of the same
451   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
452   // be extremely short in practice.  Note that we take this approach because we
453   // do not want to depend on the addresses of the objects we are grouping.
454   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
455     SCEV *S = Ops[i];
456     unsigned Complexity = S->getSCEVType();
457
458     // If there are any objects of the same complexity and same value as this
459     // one, group them.
460     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
461       if (Ops[j] == S) { // Found a duplicate.
462         // Move it to immediately after i'th element.
463         std::swap(Ops[i+1], Ops[j]);
464         ++i;   // no need to rescan it.
465         if (i == e-2) return;  // Done!
466       }
467     }
468   }
469 }
470
471
472
473 //===----------------------------------------------------------------------===//
474 //                      Simple SCEV method implementations
475 //===----------------------------------------------------------------------===//
476
477 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
478 /// specified signed integer value and return a SCEV for the constant.
479 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
480   Constant *C;
481   if (Val == 0)
482     C = Constant::getNullValue(Ty);
483   else if (Ty->isFloatingPoint())
484     C = ConstantFP::get(Ty, Val);
485   else 
486     C = ConstantInt::get(Ty, Val);
487   return SCEVUnknown::get(C);
488 }
489
490 SCEVHandle SCEVUnknown::getIntegerSCEV(const APInt& Val) {
491   return SCEVUnknown::get(ConstantInt::get(Val));
492 }
493
494 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
495 /// input value to the specified type.  If the type must be extended, it is zero
496 /// extended.
497 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
498   const Type *SrcTy = V->getType();
499   assert(SrcTy->isInteger() && Ty->isInteger() &&
500          "Cannot truncate or zero extend with non-integer arguments!");
501   if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
502     return V;  // No conversion
503   if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
504     return SCEVTruncateExpr::get(V, Ty);
505   return SCEVZeroExtendExpr::get(V, Ty);
506 }
507
508 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
509 ///
510 SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
511   if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
512     return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
513
514   return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
515 }
516
517 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
518 ///
519 SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
520   // X - Y --> X + -Y
521   return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
522 }
523
524
525 /// PartialFact - Compute V!/(V-NumSteps)!
526 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
527   // Handle this case efficiently, it is common to have constant iteration
528   // counts while computing loop exit values.
529   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
530     const APInt& Val = SC->getValue()->getValue();
531     APInt Result(Val.getBitWidth(), 1);
532     for (; NumSteps; --NumSteps)
533       Result *= Val-(NumSteps-1);
534     return SCEVUnknown::get(ConstantInt::get(Result));
535   }
536
537   const Type *Ty = V->getType();
538   if (NumSteps == 0)
539     return SCEVUnknown::getIntegerSCEV(1, Ty);
540
541   SCEVHandle Result = V;
542   for (unsigned i = 1; i != NumSteps; ++i)
543     Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
544                                           SCEVUnknown::getIntegerSCEV(i, Ty)));
545   return Result;
546 }
547
548
549 /// evaluateAtIteration - Return the value of this chain of recurrences at
550 /// the specified iteration number.  We can evaluate this recurrence by
551 /// multiplying each element in the chain by the binomial coefficient
552 /// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
553 ///
554 ///   A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
555 ///
556 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
557 /// Is the binomial equation safe using modular arithmetic??
558 ///
559 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
560   SCEVHandle Result = getStart();
561   int Divisor = 1;
562   const Type *Ty = It->getType();
563   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
564     SCEVHandle BC = PartialFact(It, i);
565     Divisor *= i;
566     SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
567                                        SCEVUnknown::getIntegerSCEV(Divisor,Ty));
568     Result = SCEVAddExpr::get(Result, Val);
569   }
570   return Result;
571 }
572
573
574 //===----------------------------------------------------------------------===//
575 //                    SCEV Expression folder implementations
576 //===----------------------------------------------------------------------===//
577
578 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
579   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
580     return SCEVUnknown::get(
581         ConstantExpr::getTrunc(SC->getValue(), Ty));
582
583   // If the input value is a chrec scev made out of constants, truncate
584   // all of the constants.
585   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
586     std::vector<SCEVHandle> Operands;
587     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
588       // FIXME: This should allow truncation of other expression types!
589       if (isa<SCEVConstant>(AddRec->getOperand(i)))
590         Operands.push_back(get(AddRec->getOperand(i), Ty));
591       else
592         break;
593     if (Operands.size() == AddRec->getNumOperands())
594       return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
595   }
596
597   SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
598   if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
599   return Result;
600 }
601
602 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
603   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
604     return SCEVUnknown::get(
605         ConstantExpr::getZExt(SC->getValue(), Ty));
606
607   // FIXME: If the input value is a chrec scev, and we can prove that the value
608   // did not overflow the old, smaller, value, we can zero extend all of the
609   // operands (often constants).  This would allow analysis of something like
610   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
611
612   SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
613   if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
614   return Result;
615 }
616
617 SCEVHandle SCEVSignExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
618   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
619     return SCEVUnknown::get(
620         ConstantExpr::getSExt(SC->getValue(), Ty));
621
622   // FIXME: If the input value is a chrec scev, and we can prove that the value
623   // did not overflow the old, smaller, value, we can sign extend all of the
624   // operands (often constants).  This would allow analysis of something like
625   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
626
627   SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
628   if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
629   return Result;
630 }
631
632 // get - Get a canonical add expression, or something simpler if possible.
633 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
634   assert(!Ops.empty() && "Cannot get empty add!");
635   if (Ops.size() == 1) return Ops[0];
636
637   // Sort by complexity, this groups all similar expression types together.
638   GroupByComplexity(Ops);
639
640   // If there are any constants, fold them together.
641   unsigned Idx = 0;
642   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
643     ++Idx;
644     assert(Idx < Ops.size());
645     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
646       // We found two constants, fold them together!
647       Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() + 
648                                         RHSC->getValue()->getValue());
649       if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
650         Ops[0] = SCEVConstant::get(CI);
651         Ops.erase(Ops.begin()+1);  // Erase the folded element
652         if (Ops.size() == 1) return Ops[0];
653         LHSC = cast<SCEVConstant>(Ops[0]);
654       } else {
655         // If we couldn't fold the expression, move to the next constant.  Note
656         // that this is impossible to happen in practice because we always
657         // constant fold constant ints to constant ints.
658         ++Idx;
659       }
660     }
661
662     // If we are left with a constant zero being added, strip it off.
663     if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
664       Ops.erase(Ops.begin());
665       --Idx;
666     }
667   }
668
669   if (Ops.size() == 1) return Ops[0];
670
671   // Okay, check to see if the same value occurs in the operand list twice.  If
672   // so, merge them together into an multiply expression.  Since we sorted the
673   // list, these values are required to be adjacent.
674   const Type *Ty = Ops[0]->getType();
675   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
676     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
677       // Found a match, merge the two values into a multiply, and add any
678       // remaining values to the result.
679       SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
680       SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
681       if (Ops.size() == 2)
682         return Mul;
683       Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
684       Ops.push_back(Mul);
685       return SCEVAddExpr::get(Ops);
686     }
687
688   // Okay, now we know the first non-constant operand.  If there are add
689   // operands they would be next.
690   if (Idx < Ops.size()) {
691     bool DeletedAdd = false;
692     while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
693       // If we have an add, expand the add operands onto the end of the operands
694       // list.
695       Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
696       Ops.erase(Ops.begin()+Idx);
697       DeletedAdd = true;
698     }
699
700     // If we deleted at least one add, we added operands to the end of the list,
701     // and they are not necessarily sorted.  Recurse to resort and resimplify
702     // any operands we just aquired.
703     if (DeletedAdd)
704       return get(Ops);
705   }
706
707   // Skip over the add expression until we get to a multiply.
708   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
709     ++Idx;
710
711   // If we are adding something to a multiply expression, make sure the
712   // something is not already an operand of the multiply.  If so, merge it into
713   // the multiply.
714   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
715     SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
716     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
717       SCEV *MulOpSCEV = Mul->getOperand(MulOp);
718       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
719         if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
720           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
721           SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
722           if (Mul->getNumOperands() != 2) {
723             // If the multiply has more than two operands, we must get the
724             // Y*Z term.
725             std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
726             MulOps.erase(MulOps.begin()+MulOp);
727             InnerMul = SCEVMulExpr::get(MulOps);
728           }
729           SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
730           SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
731           SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
732           if (Ops.size() == 2) return OuterMul;
733           if (AddOp < Idx) {
734             Ops.erase(Ops.begin()+AddOp);
735             Ops.erase(Ops.begin()+Idx-1);
736           } else {
737             Ops.erase(Ops.begin()+Idx);
738             Ops.erase(Ops.begin()+AddOp-1);
739           }
740           Ops.push_back(OuterMul);
741           return SCEVAddExpr::get(Ops);
742         }
743
744       // Check this multiply against other multiplies being added together.
745       for (unsigned OtherMulIdx = Idx+1;
746            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
747            ++OtherMulIdx) {
748         SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
749         // If MulOp occurs in OtherMul, we can fold the two multiplies
750         // together.
751         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
752              OMulOp != e; ++OMulOp)
753           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
754             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
755             SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
756             if (Mul->getNumOperands() != 2) {
757               std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
758               MulOps.erase(MulOps.begin()+MulOp);
759               InnerMul1 = SCEVMulExpr::get(MulOps);
760             }
761             SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
762             if (OtherMul->getNumOperands() != 2) {
763               std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
764                                              OtherMul->op_end());
765               MulOps.erase(MulOps.begin()+OMulOp);
766               InnerMul2 = SCEVMulExpr::get(MulOps);
767             }
768             SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
769             SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
770             if (Ops.size() == 2) return OuterMul;
771             Ops.erase(Ops.begin()+Idx);
772             Ops.erase(Ops.begin()+OtherMulIdx-1);
773             Ops.push_back(OuterMul);
774             return SCEVAddExpr::get(Ops);
775           }
776       }
777     }
778   }
779
780   // If there are any add recurrences in the operands list, see if any other
781   // added values are loop invariant.  If so, we can fold them into the
782   // recurrence.
783   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
784     ++Idx;
785
786   // Scan over all recurrences, trying to fold loop invariants into them.
787   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
788     // Scan all of the other operands to this add and add them to the vector if
789     // they are loop invariant w.r.t. the recurrence.
790     std::vector<SCEVHandle> LIOps;
791     SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
792     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
793       if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
794         LIOps.push_back(Ops[i]);
795         Ops.erase(Ops.begin()+i);
796         --i; --e;
797       }
798
799     // If we found some loop invariants, fold them into the recurrence.
800     if (!LIOps.empty()) {
801       //  NLI + LI + { Start,+,Step}  -->  NLI + { LI+Start,+,Step }
802       LIOps.push_back(AddRec->getStart());
803
804       std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
805       AddRecOps[0] = SCEVAddExpr::get(LIOps);
806
807       SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
808       // If all of the other operands were loop invariant, we are done.
809       if (Ops.size() == 1) return NewRec;
810
811       // Otherwise, add the folded AddRec by the non-liv parts.
812       for (unsigned i = 0;; ++i)
813         if (Ops[i] == AddRec) {
814           Ops[i] = NewRec;
815           break;
816         }
817       return SCEVAddExpr::get(Ops);
818     }
819
820     // Okay, if there weren't any loop invariants to be folded, check to see if
821     // there are multiple AddRec's with the same loop induction variable being
822     // added together.  If so, we can fold them.
823     for (unsigned OtherIdx = Idx+1;
824          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
825       if (OtherIdx != Idx) {
826         SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
827         if (AddRec->getLoop() == OtherAddRec->getLoop()) {
828           // Other + {A,+,B} + {C,+,D}  -->  Other + {A+C,+,B+D}
829           std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
830           for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
831             if (i >= NewOps.size()) {
832               NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
833                             OtherAddRec->op_end());
834               break;
835             }
836             NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
837           }
838           SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
839
840           if (Ops.size() == 2) return NewAddRec;
841
842           Ops.erase(Ops.begin()+Idx);
843           Ops.erase(Ops.begin()+OtherIdx-1);
844           Ops.push_back(NewAddRec);
845           return SCEVAddExpr::get(Ops);
846         }
847       }
848
849     // Otherwise couldn't fold anything into this recurrence.  Move onto the
850     // next one.
851   }
852
853   // Okay, it looks like we really DO need an add expr.  Check to see if we
854   // already have one, otherwise create a new one.
855   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
856   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
857                                                                  SCEVOps)];
858   if (Result == 0) Result = new SCEVAddExpr(Ops);
859   return Result;
860 }
861
862
863 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
864   assert(!Ops.empty() && "Cannot get empty mul!");
865
866   // Sort by complexity, this groups all similar expression types together.
867   GroupByComplexity(Ops);
868
869   // If there are any constants, fold them together.
870   unsigned Idx = 0;
871   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
872
873     // C1*(C2+V) -> C1*C2 + C1*V
874     if (Ops.size() == 2)
875       if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
876         if (Add->getNumOperands() == 2 &&
877             isa<SCEVConstant>(Add->getOperand(0)))
878           return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
879                                   SCEVMulExpr::get(LHSC, Add->getOperand(1)));
880
881
882     ++Idx;
883     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
884       // We found two constants, fold them together!
885       Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() * 
886                                         RHSC->getValue()->getValue());
887       if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
888         Ops[0] = SCEVConstant::get(CI);
889         Ops.erase(Ops.begin()+1);  // Erase the folded element
890         if (Ops.size() == 1) return Ops[0];
891         LHSC = cast<SCEVConstant>(Ops[0]);
892       } else {
893         // If we couldn't fold the expression, move to the next constant.  Note
894         // that this is impossible to happen in practice because we always
895         // constant fold constant ints to constant ints.
896         ++Idx;
897       }
898     }
899
900     // If we are left with a constant one being multiplied, strip it off.
901     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
902       Ops.erase(Ops.begin());
903       --Idx;
904     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
905       // If we have a multiply of zero, it will always be zero.
906       return Ops[0];
907     }
908   }
909
910   // Skip over the add expression until we get to a multiply.
911   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
912     ++Idx;
913
914   if (Ops.size() == 1)
915     return Ops[0];
916
917   // If there are mul operands inline them all into this expression.
918   if (Idx < Ops.size()) {
919     bool DeletedMul = false;
920     while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
921       // If we have an mul, expand the mul operands onto the end of the operands
922       // list.
923       Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
924       Ops.erase(Ops.begin()+Idx);
925       DeletedMul = true;
926     }
927
928     // If we deleted at least one mul, we added operands to the end of the list,
929     // and they are not necessarily sorted.  Recurse to resort and resimplify
930     // any operands we just aquired.
931     if (DeletedMul)
932       return get(Ops);
933   }
934
935   // If there are any add recurrences in the operands list, see if any other
936   // added values are loop invariant.  If so, we can fold them into the
937   // recurrence.
938   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
939     ++Idx;
940
941   // Scan over all recurrences, trying to fold loop invariants into them.
942   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
943     // Scan all of the other operands to this mul and add them to the vector if
944     // they are loop invariant w.r.t. the recurrence.
945     std::vector<SCEVHandle> LIOps;
946     SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
947     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
948       if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
949         LIOps.push_back(Ops[i]);
950         Ops.erase(Ops.begin()+i);
951         --i; --e;
952       }
953
954     // If we found some loop invariants, fold them into the recurrence.
955     if (!LIOps.empty()) {
956       //  NLI * LI * { Start,+,Step}  -->  NLI * { LI*Start,+,LI*Step }
957       std::vector<SCEVHandle> NewOps;
958       NewOps.reserve(AddRec->getNumOperands());
959       if (LIOps.size() == 1) {
960         SCEV *Scale = LIOps[0];
961         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
962           NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
963       } else {
964         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
965           std::vector<SCEVHandle> MulOps(LIOps);
966           MulOps.push_back(AddRec->getOperand(i));
967           NewOps.push_back(SCEVMulExpr::get(MulOps));
968         }
969       }
970
971       SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
972
973       // If all of the other operands were loop invariant, we are done.
974       if (Ops.size() == 1) return NewRec;
975
976       // Otherwise, multiply the folded AddRec by the non-liv parts.
977       for (unsigned i = 0;; ++i)
978         if (Ops[i] == AddRec) {
979           Ops[i] = NewRec;
980           break;
981         }
982       return SCEVMulExpr::get(Ops);
983     }
984
985     // Okay, if there weren't any loop invariants to be folded, check to see if
986     // there are multiple AddRec's with the same loop induction variable being
987     // multiplied together.  If so, we can fold them.
988     for (unsigned OtherIdx = Idx+1;
989          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
990       if (OtherIdx != Idx) {
991         SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
992         if (AddRec->getLoop() == OtherAddRec->getLoop()) {
993           // F * G  -->  {A,+,B} * {C,+,D}  -->  {A*C,+,F*D + G*B + B*D}
994           SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
995           SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
996                                                  G->getStart());
997           SCEVHandle B = F->getStepRecurrence();
998           SCEVHandle D = G->getStepRecurrence();
999           SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
1000                                                 SCEVMulExpr::get(G, B),
1001                                                 SCEVMulExpr::get(B, D));
1002           SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
1003                                                      F->getLoop());
1004           if (Ops.size() == 2) return NewAddRec;
1005
1006           Ops.erase(Ops.begin()+Idx);
1007           Ops.erase(Ops.begin()+OtherIdx-1);
1008           Ops.push_back(NewAddRec);
1009           return SCEVMulExpr::get(Ops);
1010         }
1011       }
1012
1013     // Otherwise couldn't fold anything into this recurrence.  Move onto the
1014     // next one.
1015   }
1016
1017   // Okay, it looks like we really DO need an mul expr.  Check to see if we
1018   // already have one, otherwise create a new one.
1019   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1020   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1021                                                                  SCEVOps)];
1022   if (Result == 0)
1023     Result = new SCEVMulExpr(Ops);
1024   return Result;
1025 }
1026
1027 SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1028   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1029     if (RHSC->getValue()->equalsInt(1))
1030       return LHS;                            // X sdiv 1 --> x
1031     if (RHSC->getValue()->isAllOnesValue())
1032       return SCEV::getNegativeSCEV(LHS);           // X sdiv -1  -->  -x
1033
1034     if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1035       Constant *LHSCV = LHSC->getValue();
1036       Constant *RHSCV = RHSC->getValue();
1037       return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
1038     }
1039   }
1040
1041   // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1042
1043   SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
1044   if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
1045   return Result;
1046 }
1047
1048
1049 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1050 /// specified loop.  Simplify the expression as much as possible.
1051 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1052                                const SCEVHandle &Step, const Loop *L) {
1053   std::vector<SCEVHandle> Operands;
1054   Operands.push_back(Start);
1055   if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1056     if (StepChrec->getLoop() == L) {
1057       Operands.insert(Operands.end(), StepChrec->op_begin(),
1058                       StepChrec->op_end());
1059       return get(Operands, L);
1060     }
1061
1062   Operands.push_back(Step);
1063   return get(Operands, L);
1064 }
1065
1066 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
1067 /// specified loop.  Simplify the expression as much as possible.
1068 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1069                                const Loop *L) {
1070   if (Operands.size() == 1) return Operands[0];
1071
1072   if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1073     if (StepC->getValue()->isZero()) {
1074       Operands.pop_back();
1075       return get(Operands, L);             // { X,+,0 }  -->  X
1076     }
1077
1078   SCEVAddRecExpr *&Result =
1079     (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1080                                                             Operands.end()))];
1081   if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1082   return Result;
1083 }
1084
1085 SCEVHandle SCEVUnknown::get(Value *V) {
1086   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1087     return SCEVConstant::get(CI);
1088   SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1089   if (Result == 0) Result = new SCEVUnknown(V);
1090   return Result;
1091 }
1092
1093
1094 //===----------------------------------------------------------------------===//
1095 //             ScalarEvolutionsImpl Definition and Implementation
1096 //===----------------------------------------------------------------------===//
1097 //
1098 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1099 /// evolution code.
1100 ///
1101 namespace {
1102   struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
1103     /// F - The function we are analyzing.
1104     ///
1105     Function &F;
1106
1107     /// LI - The loop information for the function we are currently analyzing.
1108     ///
1109     LoopInfo &LI;
1110
1111     /// UnknownValue - This SCEV is used to represent unknown trip counts and
1112     /// things.
1113     SCEVHandle UnknownValue;
1114
1115     /// Scalars - This is a cache of the scalars we have analyzed so far.
1116     ///
1117     std::map<Value*, SCEVHandle> Scalars;
1118
1119     /// IterationCounts - Cache the iteration count of the loops for this
1120     /// function as they are computed.
1121     std::map<const Loop*, SCEVHandle> IterationCounts;
1122
1123     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1124     /// the PHI instructions that we attempt to compute constant evolutions for.
1125     /// This allows us to avoid potentially expensive recomputation of these
1126     /// properties.  An instruction maps to null if we are unable to compute its
1127     /// exit value.
1128     std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1129
1130   public:
1131     ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1132       : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1133
1134     /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1135     /// expression and create a new one.
1136     SCEVHandle getSCEV(Value *V);
1137
1138     /// hasSCEV - Return true if the SCEV for this value has already been
1139     /// computed.
1140     bool hasSCEV(Value *V) const {
1141       return Scalars.count(V);
1142     }
1143
1144     /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1145     /// the specified value.
1146     void setSCEV(Value *V, const SCEVHandle &H) {
1147       bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1148       assert(isNew && "This entry already existed!");
1149     }
1150
1151
1152     /// getSCEVAtScope - Compute the value of the specified expression within
1153     /// the indicated loop (which may be null to indicate in no loop).  If the
1154     /// expression cannot be evaluated, return UnknownValue itself.
1155     SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1156
1157
1158     /// hasLoopInvariantIterationCount - Return true if the specified loop has
1159     /// an analyzable loop-invariant iteration count.
1160     bool hasLoopInvariantIterationCount(const Loop *L);
1161
1162     /// getIterationCount - If the specified loop has a predictable iteration
1163     /// count, return it.  Note that it is not valid to call this method on a
1164     /// loop without a loop-invariant iteration count.
1165     SCEVHandle getIterationCount(const Loop *L);
1166
1167     /// deleteInstructionFromRecords - This method should be called by the
1168     /// client before it removes an instruction from the program, to make sure
1169     /// that no dangling references are left around.
1170     void deleteInstructionFromRecords(Instruction *I);
1171
1172   private:
1173     /// createSCEV - We know that there is no SCEV for the specified value.
1174     /// Analyze the expression.
1175     SCEVHandle createSCEV(Value *V);
1176
1177     /// createNodeForPHI - Provide the special handling we need to analyze PHI
1178     /// SCEVs.
1179     SCEVHandle createNodeForPHI(PHINode *PN);
1180
1181     /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1182     /// for the specified instruction and replaces any references to the
1183     /// symbolic value SymName with the specified value.  This is used during
1184     /// PHI resolution.
1185     void ReplaceSymbolicValueWithConcrete(Instruction *I,
1186                                           const SCEVHandle &SymName,
1187                                           const SCEVHandle &NewVal);
1188
1189     /// ComputeIterationCount - Compute the number of times the specified loop
1190     /// will iterate.
1191     SCEVHandle ComputeIterationCount(const Loop *L);
1192
1193     /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1194     /// 'setcc load X, cst', try to see if we can compute the trip count.
1195     SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1196                                                         Constant *RHS,
1197                                                         const Loop *L,
1198                                                         ICmpInst::Predicate p);
1199
1200     /// ComputeIterationCountExhaustively - If the trip is known to execute a
1201     /// constant number of times (the condition evolves only from constants),
1202     /// try to evaluate a few iterations of the loop until we get the exit
1203     /// condition gets a value of ExitWhen (true or false).  If we cannot
1204     /// evaluate the trip count of the loop, return UnknownValue.
1205     SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1206                                                  bool ExitWhen);
1207
1208     /// HowFarToZero - Return the number of times a backedge comparing the
1209     /// specified value to zero will execute.  If not computable, return
1210     /// UnknownValue.
1211     SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1212
1213     /// HowFarToNonZero - Return the number of times a backedge checking the
1214     /// specified value for nonzero will execute.  If not computable, return
1215     /// UnknownValue.
1216     SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1217
1218     /// HowManyLessThans - Return the number of times a backedge containing the
1219     /// specified less-than comparison will execute.  If not computable, return
1220     /// UnknownValue.
1221     SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1222
1223     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1224     /// in the header of its containing loop, we know the loop executes a
1225     /// constant number of times, and the PHI node is just a recurrence
1226     /// involving constants, fold it.
1227     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1228                                                 const Loop *L);
1229   };
1230 }
1231
1232 //===----------------------------------------------------------------------===//
1233 //            Basic SCEV Analysis and PHI Idiom Recognition Code
1234 //
1235
1236 /// deleteInstructionFromRecords - This method should be called by the
1237 /// client before it removes an instruction from the program, to make sure
1238 /// that no dangling references are left around.
1239 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1240   SmallVector<Instruction *, 16> Worklist;
1241
1242   if (Scalars.erase(I)) {
1243     if (PHINode *PN = dyn_cast<PHINode>(I))
1244       ConstantEvolutionLoopExitValue.erase(PN);
1245     Worklist.push_back(I);
1246   }
1247
1248   while (!Worklist.empty()) {
1249     Instruction *II = Worklist.back();
1250     Worklist.pop_back();
1251
1252     for (Instruction::use_iterator UI = II->use_begin(), UE = II->use_end();
1253          UI != UE; ++UI) {
1254       Instruction *Inst = cast<Instruction>(*UI);
1255       if (Scalars.erase(Inst)) {
1256         if (PHINode *PN = dyn_cast<PHINode>(II))
1257           ConstantEvolutionLoopExitValue.erase(PN);
1258         Worklist.push_back(Inst);
1259       }
1260     }
1261   }
1262 }
1263
1264
1265 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1266 /// expression and create a new one.
1267 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1268   assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1269
1270   std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1271   if (I != Scalars.end()) return I->second;
1272   SCEVHandle S = createSCEV(V);
1273   Scalars.insert(std::make_pair(V, S));
1274   return S;
1275 }
1276
1277 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1278 /// the specified instruction and replaces any references to the symbolic value
1279 /// SymName with the specified value.  This is used during PHI resolution.
1280 void ScalarEvolutionsImpl::
1281 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1282                                  const SCEVHandle &NewVal) {
1283   std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1284   if (SI == Scalars.end()) return;
1285
1286   SCEVHandle NV =
1287     SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1288   if (NV == SI->second) return;  // No change.
1289
1290   SI->second = NV;       // Update the scalars map!
1291
1292   // Any instruction values that use this instruction might also need to be
1293   // updated!
1294   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1295        UI != E; ++UI)
1296     ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1297 }
1298
1299 /// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
1300 /// a loop header, making it a potential recurrence, or it doesn't.
1301 ///
1302 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1303   if (PN->getNumIncomingValues() == 2)  // The loops have been canonicalized.
1304     if (const Loop *L = LI.getLoopFor(PN->getParent()))
1305       if (L->getHeader() == PN->getParent()) {
1306         // If it lives in the loop header, it has two incoming values, one
1307         // from outside the loop, and one from inside.
1308         unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1309         unsigned BackEdge     = IncomingEdge^1;
1310
1311         // While we are analyzing this PHI node, handle its value symbolically.
1312         SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1313         assert(Scalars.find(PN) == Scalars.end() &&
1314                "PHI node already processed?");
1315         Scalars.insert(std::make_pair(PN, SymbolicName));
1316
1317         // Using this symbolic name for the PHI, analyze the value coming around
1318         // the back-edge.
1319         SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1320
1321         // NOTE: If BEValue is loop invariant, we know that the PHI node just
1322         // has a special value for the first iteration of the loop.
1323
1324         // If the value coming around the backedge is an add with the symbolic
1325         // value we just inserted, then we found a simple induction variable!
1326         if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1327           // If there is a single occurrence of the symbolic value, replace it
1328           // with a recurrence.
1329           unsigned FoundIndex = Add->getNumOperands();
1330           for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1331             if (Add->getOperand(i) == SymbolicName)
1332               if (FoundIndex == e) {
1333                 FoundIndex = i;
1334                 break;
1335               }
1336
1337           if (FoundIndex != Add->getNumOperands()) {
1338             // Create an add with everything but the specified operand.
1339             std::vector<SCEVHandle> Ops;
1340             for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1341               if (i != FoundIndex)
1342                 Ops.push_back(Add->getOperand(i));
1343             SCEVHandle Accum = SCEVAddExpr::get(Ops);
1344
1345             // This is not a valid addrec if the step amount is varying each
1346             // loop iteration, but is not itself an addrec in this loop.
1347             if (Accum->isLoopInvariant(L) ||
1348                 (isa<SCEVAddRecExpr>(Accum) &&
1349                  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1350               SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1351               SCEVHandle PHISCEV  = SCEVAddRecExpr::get(StartVal, Accum, L);
1352
1353               // Okay, for the entire analysis of this edge we assumed the PHI
1354               // to be symbolic.  We now need to go back and update all of the
1355               // entries for the scalars that use the PHI (except for the PHI
1356               // itself) to use the new analyzed value instead of the "symbolic"
1357               // value.
1358               ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1359               return PHISCEV;
1360             }
1361           }
1362         } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1363           // Otherwise, this could be a loop like this:
1364           //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
1365           // In this case, j = {1,+,1}  and BEValue is j.
1366           // Because the other in-value of i (0) fits the evolution of BEValue
1367           // i really is an addrec evolution.
1368           if (AddRec->getLoop() == L && AddRec->isAffine()) {
1369             SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1370
1371             // If StartVal = j.start - j.stride, we can use StartVal as the
1372             // initial step of the addrec evolution.
1373             if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1374                                                AddRec->getOperand(1))) {
1375               SCEVHandle PHISCEV = 
1376                  SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1377
1378               // Okay, for the entire analysis of this edge we assumed the PHI
1379               // to be symbolic.  We now need to go back and update all of the
1380               // entries for the scalars that use the PHI (except for the PHI
1381               // itself) to use the new analyzed value instead of the "symbolic"
1382               // value.
1383               ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1384               return PHISCEV;
1385             }
1386           }
1387         }
1388
1389         return SymbolicName;
1390       }
1391
1392   // If it's not a loop phi, we can't handle it yet.
1393   return SCEVUnknown::get(PN);
1394 }
1395
1396 /// GetConstantFactor - Determine the largest constant factor that S has.  For
1397 /// example, turn {4,+,8} -> 4.    (S umod result) should always equal zero.
1398 static APInt GetConstantFactor(SCEVHandle S) {
1399   if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
1400     const APInt& V = C->getValue()->getValue();
1401     if (!V.isMinValue())
1402       return V;
1403     else   // Zero is a multiple of everything.
1404       return APInt(C->getBitWidth(), 1).shl(C->getBitWidth()-1);
1405   }
1406
1407   if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) {
1408     return GetConstantFactor(T->getOperand()).trunc(
1409                                cast<IntegerType>(T->getType())->getBitWidth());
1410   }
1411   if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
1412     return GetConstantFactor(E->getOperand()).zext(
1413                                cast<IntegerType>(E->getType())->getBitWidth());
1414   if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S))
1415     return GetConstantFactor(E->getOperand()).sext(
1416                                cast<IntegerType>(E->getType())->getBitWidth());
1417   
1418   if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1419     // The result is the min of all operands.
1420     APInt Res(GetConstantFactor(A->getOperand(0)));
1421     for (unsigned i = 1, e = A->getNumOperands(); 
1422          i != e && Res.ugt(APInt(Res.getBitWidth(),1)); ++i) {
1423       APInt Tmp(GetConstantFactor(A->getOperand(i)));
1424       Res = APIntOps::umin(Res, Tmp);
1425     }
1426     return Res;
1427   }
1428
1429   if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1430     // The result is the product of all the operands.
1431     APInt Res(GetConstantFactor(M->getOperand(0)));
1432     for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i) {
1433       APInt Tmp(GetConstantFactor(M->getOperand(i)));
1434       Res *= Tmp;
1435     }
1436     return Res;
1437   }
1438     
1439   if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1440     // For now, we just handle linear expressions.
1441     if (A->getNumOperands() == 2) {
1442       // We want the GCD between the start and the stride value.
1443       APInt Start(GetConstantFactor(A->getOperand(0)));
1444       if (Start == 1) 
1445         return Start;
1446       APInt Stride(GetConstantFactor(A->getOperand(1)));
1447       return APIntOps::GreatestCommonDivisor(Start, Stride);
1448     }
1449   }
1450   
1451   // SCEVSDivExpr, SCEVUnknown.
1452   return APInt(S->getBitWidth(), 1);
1453 }
1454
1455 /// createSCEV - We know that there is no SCEV for the specified value.
1456 /// Analyze the expression.
1457 ///
1458 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1459   if (Instruction *I = dyn_cast<Instruction>(V)) {
1460     switch (I->getOpcode()) {
1461     case Instruction::Add:
1462       return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1463                               getSCEV(I->getOperand(1)));
1464     case Instruction::Mul:
1465       return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1466                               getSCEV(I->getOperand(1)));
1467     case Instruction::SDiv:
1468       return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1469                               getSCEV(I->getOperand(1)));
1470       break;
1471
1472     case Instruction::Sub:
1473       return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1474                                 getSCEV(I->getOperand(1)));
1475     case Instruction::Or:
1476       // If the RHS of the Or is a constant, we may have something like:
1477       // X*4+1 which got turned into X*4|1.  Handle this as an add so loop
1478       // optimizations will transparently handle this case.
1479       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1480         SCEVHandle LHS = getSCEV(I->getOperand(0));
1481         APInt CommonFact(GetConstantFactor(LHS));
1482         assert(!CommonFact.isMinValue() &&
1483                "Common factor should at least be 1!");
1484         if (CommonFact.ugt(CI->getValue())) {
1485           // If the LHS is a multiple that is larger than the RHS, use +.
1486           return SCEVAddExpr::get(LHS,
1487                                   getSCEV(I->getOperand(1)));
1488         }
1489       }
1490       break;
1491     case Instruction::Xor:
1492       // If the RHS of the xor is a signbit, then this is just an add.
1493       // Instcombine turns add of signbit into xor as a strength reduction step.
1494       if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1495         if (CI->getValue().isSignBit())
1496           return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1497                                   getSCEV(I->getOperand(1)));
1498       }
1499       break;
1500
1501     case Instruction::Shl:
1502       // Turn shift left of a constant amount into a multiply.
1503       if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1504         uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1505         Constant *X = ConstantInt::get(
1506           APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1507         return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1508       }
1509       break;
1510
1511     case Instruction::Trunc:
1512       return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)), I->getType());
1513
1514     case Instruction::ZExt:
1515       return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)), I->getType());
1516
1517     case Instruction::SExt:
1518       return SCEVSignExtendExpr::get(getSCEV(I->getOperand(0)), I->getType());
1519
1520     case Instruction::BitCast:
1521       // BitCasts are no-op casts so we just eliminate the cast.
1522       if (I->getType()->isInteger() &&
1523           I->getOperand(0)->getType()->isInteger())
1524         return getSCEV(I->getOperand(0));
1525       break;
1526
1527     case Instruction::PHI:
1528       return createNodeForPHI(cast<PHINode>(I));
1529
1530     default: // We cannot analyze this expression.
1531       break;
1532     }
1533   }
1534
1535   return SCEVUnknown::get(V);
1536 }
1537
1538
1539
1540 //===----------------------------------------------------------------------===//
1541 //                   Iteration Count Computation Code
1542 //
1543
1544 /// getIterationCount - If the specified loop has a predictable iteration
1545 /// count, return it.  Note that it is not valid to call this method on a
1546 /// loop without a loop-invariant iteration count.
1547 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1548   std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1549   if (I == IterationCounts.end()) {
1550     SCEVHandle ItCount = ComputeIterationCount(L);
1551     I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1552     if (ItCount != UnknownValue) {
1553       assert(ItCount->isLoopInvariant(L) &&
1554              "Computed trip count isn't loop invariant for loop!");
1555       ++NumTripCountsComputed;
1556     } else if (isa<PHINode>(L->getHeader()->begin())) {
1557       // Only count loops that have phi nodes as not being computable.
1558       ++NumTripCountsNotComputed;
1559     }
1560   }
1561   return I->second;
1562 }
1563
1564 /// ComputeIterationCount - Compute the number of times the specified loop
1565 /// will iterate.
1566 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1567   // If the loop has a non-one exit block count, we can't analyze it.
1568   std::vector<BasicBlock*> ExitBlocks;
1569   L->getExitBlocks(ExitBlocks);
1570   if (ExitBlocks.size() != 1) return UnknownValue;
1571
1572   // Okay, there is one exit block.  Try to find the condition that causes the
1573   // loop to be exited.
1574   BasicBlock *ExitBlock = ExitBlocks[0];
1575
1576   BasicBlock *ExitingBlock = 0;
1577   for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1578        PI != E; ++PI)
1579     if (L->contains(*PI)) {
1580       if (ExitingBlock == 0)
1581         ExitingBlock = *PI;
1582       else
1583         return UnknownValue;   // More than one block exiting!
1584     }
1585   assert(ExitingBlock && "No exits from loop, something is broken!");
1586
1587   // Okay, we've computed the exiting block.  See what condition causes us to
1588   // exit.
1589   //
1590   // FIXME: we should be able to handle switch instructions (with a single exit)
1591   BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1592   if (ExitBr == 0) return UnknownValue;
1593   assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1594   
1595   // At this point, we know we have a conditional branch that determines whether
1596   // the loop is exited.  However, we don't know if the branch is executed each
1597   // time through the loop.  If not, then the execution count of the branch will
1598   // not be equal to the trip count of the loop.
1599   //
1600   // Currently we check for this by checking to see if the Exit branch goes to
1601   // the loop header.  If so, we know it will always execute the same number of
1602   // times as the loop.  We also handle the case where the exit block *is* the
1603   // loop header.  This is common for un-rotated loops.  More extensive analysis
1604   // could be done to handle more cases here.
1605   if (ExitBr->getSuccessor(0) != L->getHeader() &&
1606       ExitBr->getSuccessor(1) != L->getHeader() &&
1607       ExitBr->getParent() != L->getHeader())
1608     return UnknownValue;
1609   
1610   ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1611
1612   // If its not an integer comparison then compute it the hard way. 
1613   // Note that ICmpInst deals with pointer comparisons too so we must check
1614   // the type of the operand.
1615   if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1616     return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1617                                           ExitBr->getSuccessor(0) == ExitBlock);
1618
1619   // If the condition was exit on true, convert the condition to exit on false
1620   ICmpInst::Predicate Cond;
1621   if (ExitBr->getSuccessor(1) == ExitBlock)
1622     Cond = ExitCond->getPredicate();
1623   else
1624     Cond = ExitCond->getInversePredicate();
1625
1626   // Handle common loops like: for (X = "string"; *X; ++X)
1627   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1628     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1629       SCEVHandle ItCnt =
1630         ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1631       if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1632     }
1633
1634   SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1635   SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1636
1637   // Try to evaluate any dependencies out of the loop.
1638   SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1639   if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1640   Tmp = getSCEVAtScope(RHS, L);
1641   if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1642
1643   // At this point, we would like to compute how many iterations of the 
1644   // loop the predicate will return true for these inputs.
1645   if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1646     // If there is a constant, force it into the RHS.
1647     std::swap(LHS, RHS);
1648     Cond = ICmpInst::getSwappedPredicate(Cond);
1649   }
1650
1651   // FIXME: think about handling pointer comparisons!  i.e.:
1652   // while (P != P+100) ++P;
1653
1654   // If we have a comparison of a chrec against a constant, try to use value
1655   // ranges to answer this query.
1656   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1657     if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1658       if (AddRec->getLoop() == L) {
1659         // Form the comparison range using the constant of the correct type so
1660         // that the ConstantRange class knows to do a signed or unsigned
1661         // comparison.
1662         ConstantInt *CompVal = RHSC->getValue();
1663         const Type *RealTy = ExitCond->getOperand(0)->getType();
1664         CompVal = dyn_cast<ConstantInt>(
1665           ConstantExpr::getBitCast(CompVal, RealTy));
1666         if (CompVal) {
1667           // Form the constant range.
1668           ConstantRange CompRange(
1669               ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
1670
1671           SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, 
1672               false /*Always treat as unsigned range*/);
1673           if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1674         }
1675       }
1676
1677   switch (Cond) {
1678   case ICmpInst::ICMP_NE: {                     // while (X != Y)
1679     // Convert to: while (X-Y != 0)
1680     SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
1681     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1682     break;
1683   }
1684   case ICmpInst::ICMP_EQ: {
1685     // Convert to: while (X-Y == 0)           // while (X == Y)
1686     SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
1687     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1688     break;
1689   }
1690   case ICmpInst::ICMP_SLT: {
1691     SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1692     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1693     break;
1694   }
1695   case ICmpInst::ICMP_SGT: {
1696     SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1697     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1698     break;
1699   }
1700   default:
1701 #if 0
1702     cerr << "ComputeIterationCount ";
1703     if (ExitCond->getOperand(0)->getType()->isUnsigned())
1704       cerr << "[unsigned] ";
1705     cerr << *LHS << "   "
1706          << Instruction::getOpcodeName(Instruction::ICmp) 
1707          << "   " << *RHS << "\n";
1708 #endif
1709     break;
1710   }
1711   return ComputeIterationCountExhaustively(L, ExitCond,
1712                                        ExitBr->getSuccessor(0) == ExitBlock);
1713 }
1714
1715 static ConstantInt *
1716 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1717   SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1718   SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1719   assert(isa<SCEVConstant>(Val) &&
1720          "Evaluation of SCEV at constant didn't fold correctly?");
1721   return cast<SCEVConstant>(Val)->getValue();
1722 }
1723
1724 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
1725 /// and a GEP expression (missing the pointer index) indexing into it, return
1726 /// the addressed element of the initializer or null if the index expression is
1727 /// invalid.
1728 static Constant *
1729 GetAddressedElementFromGlobal(GlobalVariable *GV,
1730                               const std::vector<ConstantInt*> &Indices) {
1731   Constant *Init = GV->getInitializer();
1732   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1733     uint64_t Idx = Indices[i]->getZExtValue();
1734     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1735       assert(Idx < CS->getNumOperands() && "Bad struct index!");
1736       Init = cast<Constant>(CS->getOperand(Idx));
1737     } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1738       if (Idx >= CA->getNumOperands()) return 0;  // Bogus program
1739       Init = cast<Constant>(CA->getOperand(Idx));
1740     } else if (isa<ConstantAggregateZero>(Init)) {
1741       if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1742         assert(Idx < STy->getNumElements() && "Bad struct index!");
1743         Init = Constant::getNullValue(STy->getElementType(Idx));
1744       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1745         if (Idx >= ATy->getNumElements()) return 0;  // Bogus program
1746         Init = Constant::getNullValue(ATy->getElementType());
1747       } else {
1748         assert(0 && "Unknown constant aggregate type!");
1749       }
1750       return 0;
1751     } else {
1752       return 0; // Unknown initializer type
1753     }
1754   }
1755   return Init;
1756 }
1757
1758 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1759 /// 'setcc load X, cst', try to se if we can compute the trip count.
1760 SCEVHandle ScalarEvolutionsImpl::
1761 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1762                                          const Loop *L, 
1763                                          ICmpInst::Predicate predicate) {
1764   if (LI->isVolatile()) return UnknownValue;
1765
1766   // Check to see if the loaded pointer is a getelementptr of a global.
1767   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1768   if (!GEP) return UnknownValue;
1769
1770   // Make sure that it is really a constant global we are gepping, with an
1771   // initializer, and make sure the first IDX is really 0.
1772   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1773   if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1774       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1775       !cast<Constant>(GEP->getOperand(1))->isNullValue())
1776     return UnknownValue;
1777
1778   // Okay, we allow one non-constant index into the GEP instruction.
1779   Value *VarIdx = 0;
1780   std::vector<ConstantInt*> Indexes;
1781   unsigned VarIdxNum = 0;
1782   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1783     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1784       Indexes.push_back(CI);
1785     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1786       if (VarIdx) return UnknownValue;  // Multiple non-constant idx's.
1787       VarIdx = GEP->getOperand(i);
1788       VarIdxNum = i-2;
1789       Indexes.push_back(0);
1790     }
1791
1792   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1793   // Check to see if X is a loop variant variable value now.
1794   SCEVHandle Idx = getSCEV(VarIdx);
1795   SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1796   if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1797
1798   // We can only recognize very limited forms of loop index expressions, in
1799   // particular, only affine AddRec's like {C1,+,C2}.
1800   SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1801   if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1802       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1803       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1804     return UnknownValue;
1805
1806   unsigned MaxSteps = MaxBruteForceIterations;
1807   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1808     ConstantInt *ItCst =
1809       ConstantInt::get(IdxExpr->getType(), IterationNum);
1810     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1811
1812     // Form the GEP offset.
1813     Indexes[VarIdxNum] = Val;
1814
1815     Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1816     if (Result == 0) break;  // Cannot compute!
1817
1818     // Evaluate the condition for this iteration.
1819     Result = ConstantExpr::getICmp(predicate, Result, RHS);
1820     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
1821     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
1822 #if 0
1823       cerr << "\n***\n*** Computed loop count " << *ItCst
1824            << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1825            << "***\n";
1826 #endif
1827       ++NumArrayLenItCounts;
1828       return SCEVConstant::get(ItCst);   // Found terminating iteration!
1829     }
1830   }
1831   return UnknownValue;
1832 }
1833
1834
1835 /// CanConstantFold - Return true if we can constant fold an instruction of the
1836 /// specified type, assuming that all operands were constants.
1837 static bool CanConstantFold(const Instruction *I) {
1838   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1839       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1840     return true;
1841
1842   if (const CallInst *CI = dyn_cast<CallInst>(I))
1843     if (const Function *F = CI->getCalledFunction())
1844       return canConstantFoldCallTo((Function*)F);  // FIXME: elim cast
1845   return false;
1846 }
1847
1848 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1849 /// in the loop that V is derived from.  We allow arbitrary operations along the
1850 /// way, but the operands of an operation must either be constants or a value
1851 /// derived from a constant PHI.  If this expression does not fit with these
1852 /// constraints, return null.
1853 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1854   // If this is not an instruction, or if this is an instruction outside of the
1855   // loop, it can't be derived from a loop PHI.
1856   Instruction *I = dyn_cast<Instruction>(V);
1857   if (I == 0 || !L->contains(I->getParent())) return 0;
1858
1859   if (PHINode *PN = dyn_cast<PHINode>(I))
1860     if (L->getHeader() == I->getParent())
1861       return PN;
1862     else
1863       // We don't currently keep track of the control flow needed to evaluate
1864       // PHIs, so we cannot handle PHIs inside of loops.
1865       return 0;
1866
1867   // If we won't be able to constant fold this expression even if the operands
1868   // are constants, return early.
1869   if (!CanConstantFold(I)) return 0;
1870
1871   // Otherwise, we can evaluate this instruction if all of its operands are
1872   // constant or derived from a PHI node themselves.
1873   PHINode *PHI = 0;
1874   for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1875     if (!(isa<Constant>(I->getOperand(Op)) ||
1876           isa<GlobalValue>(I->getOperand(Op)))) {
1877       PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1878       if (P == 0) return 0;  // Not evolving from PHI
1879       if (PHI == 0)
1880         PHI = P;
1881       else if (PHI != P)
1882         return 0;  // Evolving from multiple different PHIs.
1883     }
1884
1885   // This is a expression evolving from a constant PHI!
1886   return PHI;
1887 }
1888
1889 /// EvaluateExpression - Given an expression that passes the
1890 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1891 /// in the loop has the value PHIVal.  If we can't fold this expression for some
1892 /// reason, return null.
1893 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1894   if (isa<PHINode>(V)) return PHIVal;
1895   if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1896     return GV;
1897   if (Constant *C = dyn_cast<Constant>(V)) return C;
1898   Instruction *I = cast<Instruction>(V);
1899
1900   std::vector<Constant*> Operands;
1901   Operands.resize(I->getNumOperands());
1902
1903   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1904     Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1905     if (Operands[i] == 0) return 0;
1906   }
1907
1908   return ConstantFoldInstOperands(I, &Operands[0], Operands.size());
1909 }
1910
1911 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1912 /// in the header of its containing loop, we know the loop executes a
1913 /// constant number of times, and the PHI node is just a recurrence
1914 /// involving constants, fold it.
1915 Constant *ScalarEvolutionsImpl::
1916 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
1917   std::map<PHINode*, Constant*>::iterator I =
1918     ConstantEvolutionLoopExitValue.find(PN);
1919   if (I != ConstantEvolutionLoopExitValue.end())
1920     return I->second;
1921
1922   if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
1923     return ConstantEvolutionLoopExitValue[PN] = 0;  // Not going to evaluate it.
1924
1925   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1926
1927   // Since the loop is canonicalized, the PHI node must have two entries.  One
1928   // entry must be a constant (coming in from outside of the loop), and the
1929   // second must be derived from the same PHI.
1930   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1931   Constant *StartCST =
1932     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1933   if (StartCST == 0)
1934     return RetVal = 0;  // Must be a constant.
1935
1936   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1937   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1938   if (PN2 != PN)
1939     return RetVal = 0;  // Not derived from same PHI.
1940
1941   // Execute the loop symbolically to determine the exit value.
1942   if (Its.getActiveBits() >= 32)
1943     return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
1944
1945   unsigned NumIterations = Its.getZExtValue(); // must be in range
1946   unsigned IterationNum = 0;
1947   for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1948     if (IterationNum == NumIterations)
1949       return RetVal = PHIVal;  // Got exit value!
1950
1951     // Compute the value of the PHI node for the next iteration.
1952     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1953     if (NextPHI == PHIVal)
1954       return RetVal = NextPHI;  // Stopped evolving!
1955     if (NextPHI == 0)
1956       return 0;        // Couldn't evaluate!
1957     PHIVal = NextPHI;
1958   }
1959 }
1960
1961 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1962 /// constant number of times (the condition evolves only from constants),
1963 /// try to evaluate a few iterations of the loop until we get the exit
1964 /// condition gets a value of ExitWhen (true or false).  If we cannot
1965 /// evaluate the trip count of the loop, return UnknownValue.
1966 SCEVHandle ScalarEvolutionsImpl::
1967 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1968   PHINode *PN = getConstantEvolvingPHI(Cond, L);
1969   if (PN == 0) return UnknownValue;
1970
1971   // Since the loop is canonicalized, the PHI node must have two entries.  One
1972   // entry must be a constant (coming in from outside of the loop), and the
1973   // second must be derived from the same PHI.
1974   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1975   Constant *StartCST =
1976     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1977   if (StartCST == 0) return UnknownValue;  // Must be a constant.
1978
1979   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1980   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1981   if (PN2 != PN) return UnknownValue;  // Not derived from same PHI.
1982
1983   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
1984   // the loop symbolically to determine when the condition gets a value of
1985   // "ExitWhen".
1986   unsigned IterationNum = 0;
1987   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
1988   for (Constant *PHIVal = StartCST;
1989        IterationNum != MaxIterations; ++IterationNum) {
1990     ConstantInt *CondVal =
1991       dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
1992
1993     // Couldn't symbolically evaluate.
1994     if (!CondVal) return UnknownValue;
1995
1996     if (CondVal->getValue() == uint64_t(ExitWhen)) {
1997       ConstantEvolutionLoopExitValue[PN] = PHIVal;
1998       ++NumBruteForceTripCountsComputed;
1999       return SCEVConstant::get(ConstantInt::get(Type::Int32Ty, IterationNum));
2000     }
2001
2002     // Compute the value of the PHI node for the next iteration.
2003     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2004     if (NextPHI == 0 || NextPHI == PHIVal)
2005       return UnknownValue;  // Couldn't evaluate or not making progress...
2006     PHIVal = NextPHI;
2007   }
2008
2009   // Too many iterations were needed to evaluate.
2010   return UnknownValue;
2011 }
2012
2013 /// getSCEVAtScope - Compute the value of the specified expression within the
2014 /// indicated loop (which may be null to indicate in no loop).  If the
2015 /// expression cannot be evaluated, return UnknownValue.
2016 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2017   // FIXME: this should be turned into a virtual method on SCEV!
2018
2019   if (isa<SCEVConstant>(V)) return V;
2020
2021   // If this instruction is evolves from a constant-evolving PHI, compute the
2022   // exit value from the loop without using SCEVs.
2023   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2024     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2025       const Loop *LI = this->LI[I->getParent()];
2026       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
2027         if (PHINode *PN = dyn_cast<PHINode>(I))
2028           if (PN->getParent() == LI->getHeader()) {
2029             // Okay, there is no closed form solution for the PHI node.  Check
2030             // to see if the loop that contains it has a known iteration count.
2031             // If so, we may be able to force computation of the exit value.
2032             SCEVHandle IterationCount = getIterationCount(LI);
2033             if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2034               // Okay, we know how many times the containing loop executes.  If
2035               // this is a constant evolving PHI node, get the final value at
2036               // the specified iteration number.
2037               Constant *RV = getConstantEvolutionLoopExitValue(PN,
2038                                                     ICC->getValue()->getValue(),
2039                                                                LI);
2040               if (RV) return SCEVUnknown::get(RV);
2041             }
2042           }
2043
2044       // Okay, this is an expression that we cannot symbolically evaluate
2045       // into a SCEV.  Check to see if it's possible to symbolically evaluate
2046       // the arguments into constants, and if so, try to constant propagate the
2047       // result.  This is particularly useful for computing loop exit values.
2048       if (CanConstantFold(I)) {
2049         std::vector<Constant*> Operands;
2050         Operands.reserve(I->getNumOperands());
2051         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2052           Value *Op = I->getOperand(i);
2053           if (Constant *C = dyn_cast<Constant>(Op)) {
2054             Operands.push_back(C);
2055           } else {
2056             SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2057             if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2058               Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(), 
2059                                                               Op->getType(), 
2060                                                               false));
2061             else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2062               if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2063                 Operands.push_back(ConstantExpr::getIntegerCast(C, 
2064                                                                 Op->getType(), 
2065                                                                 false));
2066               else
2067                 return V;
2068             } else {
2069               return V;
2070             }
2071           }
2072         }
2073         Constant *C =ConstantFoldInstOperands(I, &Operands[0], Operands.size());
2074         return SCEVUnknown::get(C);
2075       }
2076     }
2077
2078     // This is some other type of SCEVUnknown, just return it.
2079     return V;
2080   }
2081
2082   if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2083     // Avoid performing the look-up in the common case where the specified
2084     // expression has no loop-variant portions.
2085     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2086       SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2087       if (OpAtScope != Comm->getOperand(i)) {
2088         if (OpAtScope == UnknownValue) return UnknownValue;
2089         // Okay, at least one of these operands is loop variant but might be
2090         // foldable.  Build a new instance of the folded commutative expression.
2091         std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2092         NewOps.push_back(OpAtScope);
2093
2094         for (++i; i != e; ++i) {
2095           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2096           if (OpAtScope == UnknownValue) return UnknownValue;
2097           NewOps.push_back(OpAtScope);
2098         }
2099         if (isa<SCEVAddExpr>(Comm))
2100           return SCEVAddExpr::get(NewOps);
2101         assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
2102         return SCEVMulExpr::get(NewOps);
2103       }
2104     }
2105     // If we got here, all operands are loop invariant.
2106     return Comm;
2107   }
2108
2109   if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2110     SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2111     if (LHS == UnknownValue) return LHS;
2112     SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2113     if (RHS == UnknownValue) return RHS;
2114     if (LHS == Div->getLHS() && RHS == Div->getRHS())
2115       return Div;   // must be loop invariant
2116     return SCEVSDivExpr::get(LHS, RHS);
2117   }
2118
2119   // If this is a loop recurrence for a loop that does not contain L, then we
2120   // are dealing with the final value computed by the loop.
2121   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2122     if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2123       // To evaluate this recurrence, we need to know how many times the AddRec
2124       // loop iterates.  Compute this now.
2125       SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2126       if (IterationCount == UnknownValue) return UnknownValue;
2127       IterationCount = getTruncateOrZeroExtend(IterationCount,
2128                                                AddRec->getType());
2129
2130       // If the value is affine, simplify the expression evaluation to just
2131       // Start + Step*IterationCount.
2132       if (AddRec->isAffine())
2133         return SCEVAddExpr::get(AddRec->getStart(),
2134                                 SCEVMulExpr::get(IterationCount,
2135                                                  AddRec->getOperand(1)));
2136
2137       // Otherwise, evaluate it the hard way.
2138       return AddRec->evaluateAtIteration(IterationCount);
2139     }
2140     return UnknownValue;
2141   }
2142
2143   //assert(0 && "Unknown SCEV type!");
2144   return UnknownValue;
2145 }
2146
2147
2148 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2149 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
2150 /// might be the same) or two SCEVCouldNotCompute objects.
2151 ///
2152 static std::pair<SCEVHandle,SCEVHandle>
2153 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2154   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2155   SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2156   SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2157   SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2158
2159   // We currently can only solve this if the coefficients are constants.
2160   if (!LC || !MC || !NC) {
2161     SCEV *CNC = new SCEVCouldNotCompute();
2162     return std::make_pair(CNC, CNC);
2163   }
2164
2165   uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2166   const APInt &L = LC->getValue()->getValue();
2167   const APInt &M = MC->getValue()->getValue();
2168   const APInt &N = NC->getValue()->getValue();
2169   APInt Two(BitWidth, 2);
2170   APInt Four(BitWidth, 4);
2171
2172   { 
2173     using namespace APIntOps;
2174     const APInt& C = L;
2175     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2176     // The B coefficient is M-N/2
2177     APInt B(M);
2178     B -= sdiv(N,Two);
2179
2180     // The A coefficient is N/2
2181     APInt A(N.sdiv(Two));
2182
2183     // Compute the B^2-4ac term.
2184     APInt SqrtTerm(B);
2185     SqrtTerm *= B;
2186     SqrtTerm -= Four * (A * C);
2187
2188     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2189     // integer value or else APInt::sqrt() will assert.
2190     APInt SqrtVal(SqrtTerm.sqrt());
2191
2192     // Compute the two solutions for the quadratic formula. 
2193     // The divisions must be performed as signed divisions.
2194     APInt NegB(-B);
2195     APInt TwoA( A << 1 );
2196     ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2197     ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2198
2199     return std::make_pair(SCEVUnknown::get(Solution1), 
2200                           SCEVUnknown::get(Solution2));
2201     } // end APIntOps namespace
2202 }
2203
2204 /// HowFarToZero - Return the number of times a backedge comparing the specified
2205 /// value to zero will execute.  If not computable, return UnknownValue
2206 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2207   // If the value is a constant
2208   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2209     // If the value is already zero, the branch will execute zero times.
2210     if (C->getValue()->isZero()) return C;
2211     return UnknownValue;  // Otherwise it will loop infinitely.
2212   }
2213
2214   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2215   if (!AddRec || AddRec->getLoop() != L)
2216     return UnknownValue;
2217
2218   if (AddRec->isAffine()) {
2219     // If this is an affine expression the execution count of this branch is
2220     // equal to:
2221     //
2222     //     (0 - Start/Step)    iff   Start % Step == 0
2223     //
2224     // Get the initial value for the loop.
2225     SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2226     if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2227     SCEVHandle Step = AddRec->getOperand(1);
2228
2229     Step = getSCEVAtScope(Step, L->getParentLoop());
2230
2231     // Figure out if Start % Step == 0.
2232     // FIXME: We should add DivExpr and RemExpr operations to our AST.
2233     if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2234       if (StepC->getValue()->equalsInt(1))      // N % 1 == 0
2235         return SCEV::getNegativeSCEV(Start);  // 0 - Start/1 == -Start
2236       if (StepC->getValue()->isAllOnesValue())  // N % -1 == 0
2237         return Start;                   // 0 - Start/-1 == Start
2238
2239       // Check to see if Start is divisible by SC with no remainder.
2240       if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2241         ConstantInt *StartCC = StartC->getValue();
2242         Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2243         Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
2244         if (Rem->isNullValue()) {
2245           Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
2246           return SCEVUnknown::get(Result);
2247         }
2248       }
2249     }
2250   } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2251     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2252     // the quadratic equation to solve it.
2253     std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2254     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2255     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2256     if (R1) {
2257 #if 0
2258       cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2259            << "  sol#2: " << *R2 << "\n";
2260 #endif
2261       // Pick the smallest positive root value.
2262       if (ConstantInt *CB =
2263           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 
2264                                    R1->getValue(), R2->getValue()))) {
2265         if (CB->getZExtValue() == false)
2266           std::swap(R1, R2);   // R1 is the minimum root now.
2267
2268         // We can only use this value if the chrec ends up with an exact zero
2269         // value at this index.  When solving for "X*X != 5", for example, we
2270         // should not accept a root of 2.
2271         SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2272         if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2273           if (EvalVal->getValue()->isZero())
2274             return R1;  // We found a quadratic root!
2275       }
2276     }
2277   }
2278
2279   return UnknownValue;
2280 }
2281
2282 /// HowFarToNonZero - Return the number of times a backedge checking the
2283 /// specified value for nonzero will execute.  If not computable, return
2284 /// UnknownValue
2285 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2286   // Loops that look like: while (X == 0) are very strange indeed.  We don't
2287   // handle them yet except for the trivial case.  This could be expanded in the
2288   // future as needed.
2289
2290   // If the value is a constant, check to see if it is known to be non-zero
2291   // already.  If so, the backedge will execute zero times.
2292   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2293     Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2294     Constant *NonZero = 
2295       ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
2296     if (NonZero == ConstantInt::getTrue())
2297       return getSCEV(Zero);
2298     return UnknownValue;  // Otherwise it will loop infinitely.
2299   }
2300
2301   // We could implement others, but I really doubt anyone writes loops like
2302   // this, and if they did, they would already be constant folded.
2303   return UnknownValue;
2304 }
2305
2306 /// HowManyLessThans - Return the number of times a backedge containing the
2307 /// specified less-than comparison will execute.  If not computable, return
2308 /// UnknownValue.
2309 SCEVHandle ScalarEvolutionsImpl::
2310 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2311   // Only handle:  "ADDREC < LoopInvariant".
2312   if (!RHS->isLoopInvariant(L)) return UnknownValue;
2313
2314   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2315   if (!AddRec || AddRec->getLoop() != L)
2316     return UnknownValue;
2317
2318   if (AddRec->isAffine()) {
2319     // FORNOW: We only support unit strides.
2320     SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2321     if (AddRec->getOperand(1) != One)
2322       return UnknownValue;
2323
2324     // The number of iterations for "[n,+,1] < m", is m-n.  However, we don't
2325     // know that m is >= n on input to the loop.  If it is, the condition return
2326     // true zero times.  What we really should return, for full generality, is
2327     // SMAX(0, m-n).  Since we cannot check this, we will instead check for a
2328     // canonical loop form: most do-loops will have a check that dominates the
2329     // loop, that only enters the loop if [n-1]<m.  If we can find this check,
2330     // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2331
2332     // Search for the check.
2333     BasicBlock *Preheader = L->getLoopPreheader();
2334     BasicBlock *PreheaderDest = L->getHeader();
2335     if (Preheader == 0) return UnknownValue;
2336
2337     BranchInst *LoopEntryPredicate =
2338       dyn_cast<BranchInst>(Preheader->getTerminator());
2339     if (!LoopEntryPredicate) return UnknownValue;
2340
2341     // This might be a critical edge broken out.  If the loop preheader ends in
2342     // an unconditional branch to the loop, check to see if the preheader has a
2343     // single predecessor, and if so, look for its terminator.
2344     while (LoopEntryPredicate->isUnconditional()) {
2345       PreheaderDest = Preheader;
2346       Preheader = Preheader->getSinglePredecessor();
2347       if (!Preheader) return UnknownValue;  // Multiple preds.
2348       
2349       LoopEntryPredicate =
2350         dyn_cast<BranchInst>(Preheader->getTerminator());
2351       if (!LoopEntryPredicate) return UnknownValue;
2352     }
2353
2354     // Now that we found a conditional branch that dominates the loop, check to
2355     // see if it is the comparison we are looking for.
2356     if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){
2357       Value *PreCondLHS = ICI->getOperand(0);
2358       Value *PreCondRHS = ICI->getOperand(1);
2359       ICmpInst::Predicate Cond;
2360       if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2361         Cond = ICI->getPredicate();
2362       else
2363         Cond = ICI->getInversePredicate();
2364     
2365       switch (Cond) {
2366       case ICmpInst::ICMP_UGT:
2367         std::swap(PreCondLHS, PreCondRHS);
2368         Cond = ICmpInst::ICMP_ULT;
2369         break;
2370       case ICmpInst::ICMP_SGT:
2371         std::swap(PreCondLHS, PreCondRHS);
2372         Cond = ICmpInst::ICMP_SLT;
2373         break;
2374       default: break;
2375       }
2376
2377       if (Cond == ICmpInst::ICMP_SLT) {
2378         if (PreCondLHS->getType()->isInteger()) {
2379           if (RHS != getSCEV(PreCondRHS))
2380             return UnknownValue;  // Not a comparison against 'm'.
2381
2382           if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2383                       != getSCEV(PreCondLHS))
2384             return UnknownValue;  // Not a comparison against 'n-1'.
2385         }
2386         else return UnknownValue;
2387       } else if (Cond == ICmpInst::ICMP_ULT)
2388         return UnknownValue;
2389
2390       // cerr << "Computed Loop Trip Count as: " 
2391       //      << //  *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2392       return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2393     }
2394     else 
2395       return UnknownValue;
2396   }
2397
2398   return UnknownValue;
2399 }
2400
2401 /// getNumIterationsInRange - Return the number of iterations of this loop that
2402 /// produce values in the specified constant range.  Another way of looking at
2403 /// this is that it returns the first iteration number where the value is not in
2404 /// the condition, thus computing the exit count. If the iteration count can't
2405 /// be computed, an instance of SCEVCouldNotCompute is returned.
2406 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, 
2407                                                    bool isSigned) const {
2408   if (Range.isFullSet())  // Infinite loop.
2409     return new SCEVCouldNotCompute();
2410
2411   // If the start is a non-zero constant, shift the range to simplify things.
2412   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2413     if (!SC->getValue()->isZero()) {
2414       std::vector<SCEVHandle> Operands(op_begin(), op_end());
2415       Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
2416       SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2417       if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2418         return ShiftedAddRec->getNumIterationsInRange(
2419                            Range.subtract(SC->getValue()->getValue()),isSigned);
2420       // This is strange and shouldn't happen.
2421       return new SCEVCouldNotCompute();
2422     }
2423
2424   // The only time we can solve this is when we have all constant indices.
2425   // Otherwise, we cannot determine the overflow conditions.
2426   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2427     if (!isa<SCEVConstant>(getOperand(i)))
2428       return new SCEVCouldNotCompute();
2429
2430
2431   // Okay at this point we know that all elements of the chrec are constants and
2432   // that the start element is zero.
2433
2434   // First check to see if the range contains zero.  If not, the first
2435   // iteration exits.
2436   if (!Range.contains(APInt(getBitWidth(),0))) 
2437     return SCEVConstant::get(ConstantInt::get(getType(),0));
2438
2439   if (isAffine()) {
2440     // If this is an affine expression then we have this situation:
2441     //   Solve {0,+,A} in Range  ===  Ax in Range
2442
2443     // Since we know that zero is in the range, we know that the upper value of
2444     // the range must be the first possible exit value.  Also note that we
2445     // already checked for a full range.
2446     const APInt &Upper = Range.getUpper();
2447     APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2448     APInt One(getBitWidth(),1);
2449
2450     // The exit value should be (Upper+A-1)/A.
2451     APInt ExitVal(Upper);
2452     if (A != One)
2453       ExitVal = (Upper + A - One).sdiv(A);
2454     ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2455
2456     // Evaluate at the exit value.  If we really did fall out of the valid
2457     // range, then we computed our trip count, otherwise wrap around or other
2458     // things must have happened.
2459     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2460     if (Range.contains(Val->getValue()))
2461       return new SCEVCouldNotCompute();  // Something strange happened
2462
2463     // Ensure that the previous value is in the range.  This is a sanity check.
2464     assert(Range.contains(
2465            EvaluateConstantChrecAtConstant(this, 
2466            ConstantInt::get(ExitVal - One))->getValue()) &&
2467            "Linear scev computation is off in a bad way!");
2468     return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2469   } else if (isQuadratic()) {
2470     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2471     // quadratic equation to solve it.  To do this, we must frame our problem in
2472     // terms of figuring out when zero is crossed, instead of when
2473     // Range.getUpper() is crossed.
2474     std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2475     NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(
2476                                            ConstantInt::get(Range.getUpper())));
2477     SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2478
2479     // Next, solve the constructed addrec
2480     std::pair<SCEVHandle,SCEVHandle> Roots =
2481       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2482     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2483     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2484     if (R1) {
2485       // Pick the smallest positive root value.
2486       if (ConstantInt *CB =
2487           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 
2488                                    R1->getValue(), R2->getValue()))) {
2489         if (CB->getZExtValue() == false)
2490           std::swap(R1, R2);   // R1 is the minimum root now.
2491
2492         // Make sure the root is not off by one.  The returned iteration should
2493         // not be in the range, but the previous one should be.  When solving
2494         // for "X*X < 5", for example, we should not return a root of 2.
2495         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2496                                                              R1->getValue());
2497         if (Range.contains(R1Val->getValue())) {
2498           // The next iteration must be out of the range...
2499           Constant *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2500
2501           R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2502           if (!Range.contains(R1Val->getValue()))
2503             return SCEVUnknown::get(NextVal);
2504           return new SCEVCouldNotCompute();  // Something strange happened
2505         }
2506
2507         // If R1 was not in the range, then it is a good return value.  Make
2508         // sure that R1-1 WAS in the range though, just in case.
2509         Constant *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
2510         R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2511         if (Range.contains(R1Val->getValue()))
2512           return R1;
2513         return new SCEVCouldNotCompute();  // Something strange happened
2514       }
2515     }
2516   }
2517
2518   // Fallback, if this is a general polynomial, figure out the progression
2519   // through brute force: evaluate until we find an iteration that fails the
2520   // test.  This is likely to be slow, but getting an accurate trip count is
2521   // incredibly important, we will be able to simplify the exit test a lot, and
2522   // we are almost guaranteed to get a trip count in this case.
2523   ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2524   ConstantInt *EndVal  = TestVal;  // Stop when we wrap around.
2525   do {
2526     ++NumBruteForceEvaluations;
2527     SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2528     if (!isa<SCEVConstant>(Val))  // This shouldn't happen.
2529       return new SCEVCouldNotCompute();
2530
2531     // Check to see if we found the value!
2532     if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
2533       return SCEVConstant::get(TestVal);
2534
2535     // Increment to test the next index.
2536     TestVal = ConstantInt::get(TestVal->getValue()+1);
2537   } while (TestVal != EndVal);
2538
2539   return new SCEVCouldNotCompute();
2540 }
2541
2542
2543
2544 //===----------------------------------------------------------------------===//
2545 //                   ScalarEvolution Class Implementation
2546 //===----------------------------------------------------------------------===//
2547
2548 bool ScalarEvolution::runOnFunction(Function &F) {
2549   Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2550   return false;
2551 }
2552
2553 void ScalarEvolution::releaseMemory() {
2554   delete (ScalarEvolutionsImpl*)Impl;
2555   Impl = 0;
2556 }
2557
2558 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2559   AU.setPreservesAll();
2560   AU.addRequiredTransitive<LoopInfo>();
2561 }
2562
2563 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2564   return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2565 }
2566
2567 /// hasSCEV - Return true if the SCEV for this value has already been
2568 /// computed.
2569 bool ScalarEvolution::hasSCEV(Value *V) const {
2570   return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2571 }
2572
2573
2574 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2575 /// the specified value.
2576 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2577   ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2578 }
2579
2580
2581 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2582   return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2583 }
2584
2585 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2586   return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2587 }
2588
2589 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2590   return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2591 }
2592
2593 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2594   return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2595 }
2596
2597 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2598                           const Loop *L) {
2599   // Print all inner loops first
2600   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2601     PrintLoopInfo(OS, SE, *I);
2602
2603   cerr << "Loop " << L->getHeader()->getName() << ": ";
2604
2605   std::vector<BasicBlock*> ExitBlocks;
2606   L->getExitBlocks(ExitBlocks);
2607   if (ExitBlocks.size() != 1)
2608     cerr << "<multiple exits> ";
2609
2610   if (SE->hasLoopInvariantIterationCount(L)) {
2611     cerr << *SE->getIterationCount(L) << " iterations! ";
2612   } else {
2613     cerr << "Unpredictable iteration count. ";
2614   }
2615
2616   cerr << "\n";
2617 }
2618
2619 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2620   Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2621   LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2622
2623   OS << "Classifying expressions for: " << F.getName() << "\n";
2624   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2625     if (I->getType()->isInteger()) {
2626       OS << *I;
2627       OS << "  --> ";
2628       SCEVHandle SV = getSCEV(&*I);
2629       SV->print(OS);
2630       OS << "\t\t";
2631
2632       if ((*I).getType()->isInteger()) {
2633         ConstantRange Bounds = SV->getValueRange();
2634         if (!Bounds.isFullSet())
2635           OS << "Bounds: " << Bounds << " ";
2636       }
2637
2638       if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2639         OS << "Exits: ";
2640         SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2641         if (isa<SCEVCouldNotCompute>(ExitValue)) {
2642           OS << "<<Unknown>>";
2643         } else {
2644           OS << *ExitValue;
2645         }
2646       }
2647
2648
2649       OS << "\n";
2650     }
2651
2652   OS << "Determining loop execution counts for: " << F.getName() << "\n";
2653   for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2654     PrintLoopInfo(OS, this, *I);
2655 }
2656