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