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