LLVM API Documentation

ScalarEvolution.cpp

Go to the documentation of this file.
00001 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the implementation of the scalar evolution analysis
00011 // engine, which is used primarily to analyze expressions involving induction
00012 // variables in loops.
00013 //
00014 // There are several aspects to this library.  First is the representation of
00015 // scalar expressions, which are represented as subclasses of the SCEV class.
00016 // These classes are used to represent certain types of subexpressions that we
00017 // can handle.  These classes are reference counted, managed by the SCEVHandle
00018 // class.  We only create one SCEV of a particular shape, so pointer-comparisons
00019 // for equality are legal.
00020 //
00021 // One important aspect of the SCEV objects is that they are never cyclic, even
00022 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
00023 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
00024 // recurrence) then we represent it directly as a recurrence node, otherwise we
00025 // represent it as a SCEVUnknown node.
00026 //
00027 // In addition to being able to represent expressions of various types, we also
00028 // have folders that are used to build the *canonical* representation for a
00029 // particular expression.  These folders are capable of using a variety of
00030 // rewrite rules to simplify the expressions.
00031 //
00032 // Once the folders are defined, we can implement the more interesting
00033 // higher-level code, such as the code that recognizes PHI nodes of various
00034 // types, computes the execution count of a loop, etc.
00035 //
00036 // TODO: We should use these routines and value representations to implement
00037 // dependence analysis!
00038 //
00039 //===----------------------------------------------------------------------===//
00040 //
00041 // There are several good references for the techniques used in this analysis.
00042 //
00043 //  Chains of recurrences -- a method to expedite the evaluation
00044 //  of closed-form functions
00045 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
00046 //
00047 //  On computational properties of chains of recurrences
00048 //  Eugene V. Zima
00049 //
00050 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
00051 //  Robert A. van Engelen
00052 //
00053 //  Efficient Symbolic Analysis for Optimizing Compilers
00054 //  Robert A. van Engelen
00055 //
00056 //  Using the chains of recurrences algebra for data dependence testing and
00057 //  induction variable substitution
00058 //  MS Thesis, Johnie Birch
00059 //
00060 //===----------------------------------------------------------------------===//
00061 
00062 #define DEBUG_TYPE "scalar-evolution"
00063 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00064 #include "llvm/Constants.h"
00065 #include "llvm/DerivedTypes.h"
00066 #include "llvm/GlobalVariable.h"
00067 #include "llvm/Instructions.h"
00068 #include "llvm/Analysis/ConstantFolding.h"
00069 #include "llvm/Analysis/LoopInfo.h"
00070 #include "llvm/Assembly/Writer.h"
00071 #include "llvm/Transforms/Scalar.h"
00072 #include "llvm/Support/CFG.h"
00073 #include "llvm/Support/CommandLine.h"
00074 #include "llvm/Support/Compiler.h"
00075 #include "llvm/Support/ConstantRange.h"
00076 #include "llvm/Support/InstIterator.h"
00077 #include "llvm/Support/ManagedStatic.h"
00078 #include "llvm/Support/MathExtras.h"
00079 #include "llvm/Support/Streams.h"
00080 #include "llvm/ADT/Statistic.h"
00081 #include <ostream>
00082 #include <algorithm>
00083 #include <cmath>
00084 using namespace llvm;
00085 
00086 STATISTIC(NumArrayLenItCounts,
00087           "Number of trip counts computed with array length");
00088 STATISTIC(NumTripCountsComputed,
00089           "Number of loops with predictable loop counts");
00090 STATISTIC(NumTripCountsNotComputed,
00091           "Number of loops without predictable loop counts");
00092 STATISTIC(NumBruteForceTripCountsComputed,
00093           "Number of loops with trip counts computed by force");
00094 
00095 static cl::opt<unsigned>
00096 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
00097                         cl::desc("Maximum number of iterations SCEV will "
00098                                  "symbolically execute a constant derived loop"),
00099                         cl::init(100));
00100 
00101 static RegisterPass<ScalarEvolution>
00102 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
00103 char ScalarEvolution::ID = 0;
00104 
00105 //===----------------------------------------------------------------------===//
00106 //                           SCEV class definitions
00107 //===----------------------------------------------------------------------===//
00108 
00109 //===----------------------------------------------------------------------===//
00110 // Implementation of the SCEV class.
00111 //
00112 SCEV::~SCEV() {}
00113 void SCEV::dump() const {
00114   print(cerr);
00115   cerr << '\n';
00116 }
00117 
00118 uint32_t SCEV::getBitWidth() const {
00119   if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
00120     return ITy->getBitWidth();
00121   return 0;
00122 }
00123 
00124 bool SCEV::isZero() const {
00125   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
00126     return SC->getValue()->isZero();
00127   return false;
00128 }
00129 
00130 
00131 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
00132 
00133 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
00134   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
00135   return false;
00136 }
00137 
00138 const Type *SCEVCouldNotCompute::getType() const {
00139   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
00140   return 0;
00141 }
00142 
00143 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
00144   assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
00145   return false;
00146 }
00147 
00148 SCEVHandle SCEVCouldNotCompute::
00149 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
00150                                   const SCEVHandle &Conc,
00151                                   ScalarEvolution &SE) const {
00152   return this;
00153 }
00154 
00155 void SCEVCouldNotCompute::print(std::ostream &OS) const {
00156   OS << "***COULDNOTCOMPUTE***";
00157 }
00158 
00159 bool SCEVCouldNotCompute::classof(const SCEV *S) {
00160   return S->getSCEVType() == scCouldNotCompute;
00161 }
00162 
00163 
00164 // SCEVConstants - Only allow the creation of one SCEVConstant for any
00165 // particular value.  Don't use a SCEVHandle here, or else the object will
00166 // never be deleted!
00167 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
00168 
00169 
00170 SCEVConstant::~SCEVConstant() {
00171   SCEVConstants->erase(V);
00172 }
00173 
00174 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
00175   SCEVConstant *&R = (*SCEVConstants)[V];
00176   if (R == 0) R = new SCEVConstant(V);
00177   return R;
00178 }
00179 
00180 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
00181   return getConstant(ConstantInt::get(Val));
00182 }
00183 
00184 const Type *SCEVConstant::getType() const { return V->getType(); }
00185 
00186 void SCEVConstant::print(std::ostream &OS) const {
00187   WriteAsOperand(OS, V, false);
00188 }
00189 
00190 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
00191 // particular input.  Don't use a SCEVHandle here, or else the object will
00192 // never be deleted!
00193 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, 
00194                      SCEVTruncateExpr*> > SCEVTruncates;
00195 
00196 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
00197   : SCEV(scTruncate), Op(op), Ty(ty) {
00198   assert(Op->getType()->isInteger() && Ty->isInteger() &&
00199          "Cannot truncate non-integer value!");
00200   assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
00201          && "This is not a truncating conversion!");
00202 }
00203 
00204 SCEVTruncateExpr::~SCEVTruncateExpr() {
00205   SCEVTruncates->erase(std::make_pair(Op, Ty));
00206 }
00207 
00208 void SCEVTruncateExpr::print(std::ostream &OS) const {
00209   OS << "(truncate " << *Op << " to " << *Ty << ")";
00210 }
00211 
00212 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
00213 // particular input.  Don't use a SCEVHandle here, or else the object will never
00214 // be deleted!
00215 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
00216                      SCEVZeroExtendExpr*> > SCEVZeroExtends;
00217 
00218 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
00219   : SCEV(scZeroExtend), Op(op), Ty(ty) {
00220   assert(Op->getType()->isInteger() && Ty->isInteger() &&
00221          "Cannot zero extend non-integer value!");
00222   assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
00223          && "This is not an extending conversion!");
00224 }
00225 
00226 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
00227   SCEVZeroExtends->erase(std::make_pair(Op, Ty));
00228 }
00229 
00230 void SCEVZeroExtendExpr::print(std::ostream &OS) const {
00231   OS << "(zeroextend " << *Op << " to " << *Ty << ")";
00232 }
00233 
00234 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
00235 // particular input.  Don't use a SCEVHandle here, or else the object will never
00236 // be deleted!
00237 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
00238                      SCEVSignExtendExpr*> > SCEVSignExtends;
00239 
00240 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
00241   : SCEV(scSignExtend), Op(op), Ty(ty) {
00242   assert(Op->getType()->isInteger() && Ty->isInteger() &&
00243          "Cannot sign extend non-integer value!");
00244   assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
00245          && "This is not an extending conversion!");
00246 }
00247 
00248 SCEVSignExtendExpr::~SCEVSignExtendExpr() {
00249   SCEVSignExtends->erase(std::make_pair(Op, Ty));
00250 }
00251 
00252 void SCEVSignExtendExpr::print(std::ostream &OS) const {
00253   OS << "(signextend " << *Op << " to " << *Ty << ")";
00254 }
00255 
00256 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
00257 // particular input.  Don't use a SCEVHandle here, or else the object will never
00258 // be deleted!
00259 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
00260                      SCEVCommutativeExpr*> > SCEVCommExprs;
00261 
00262 SCEVCommutativeExpr::~SCEVCommutativeExpr() {
00263   SCEVCommExprs->erase(std::make_pair(getSCEVType(),
00264                                       std::vector<SCEV*>(Operands.begin(),
00265                                                          Operands.end())));
00266 }
00267 
00268 void SCEVCommutativeExpr::print(std::ostream &OS) const {
00269   assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
00270   const char *OpStr = getOperationStr();
00271   OS << "(" << *Operands[0];
00272   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
00273     OS << OpStr << *Operands[i];
00274   OS << ")";
00275 }
00276 
00277 SCEVHandle SCEVCommutativeExpr::
00278 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
00279                                   const SCEVHandle &Conc,
00280                                   ScalarEvolution &SE) const {
00281   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
00282     SCEVHandle H =
00283       getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
00284     if (H != getOperand(i)) {
00285       std::vector<SCEVHandle> NewOps;
00286       NewOps.reserve(getNumOperands());
00287       for (unsigned j = 0; j != i; ++j)
00288         NewOps.push_back(getOperand(j));
00289       NewOps.push_back(H);
00290       for (++i; i != e; ++i)
00291         NewOps.push_back(getOperand(i)->
00292                          replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
00293 
00294       if (isa<SCEVAddExpr>(this))
00295         return SE.getAddExpr(NewOps);
00296       else if (isa<SCEVMulExpr>(this))
00297         return SE.getMulExpr(NewOps);
00298       else if (isa<SCEVSMaxExpr>(this))
00299         return SE.getSMaxExpr(NewOps);
00300       else if (isa<SCEVUMaxExpr>(this))
00301         return SE.getUMaxExpr(NewOps);
00302       else
00303         assert(0 && "Unknown commutative expr!");
00304     }
00305   }
00306   return this;
00307 }
00308 
00309 
00310 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
00311 // input.  Don't use a SCEVHandle here, or else the object will never be
00312 // deleted!
00313 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>, 
00314                      SCEVUDivExpr*> > SCEVUDivs;
00315 
00316 SCEVUDivExpr::~SCEVUDivExpr() {
00317   SCEVUDivs->erase(std::make_pair(LHS, RHS));
00318 }
00319 
00320 void SCEVUDivExpr::print(std::ostream &OS) const {
00321   OS << "(" << *LHS << " /u " << *RHS << ")";
00322 }
00323 
00324 const Type *SCEVUDivExpr::getType() const {
00325   return LHS->getType();
00326 }
00327 
00328 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
00329 // particular input.  Don't use a SCEVHandle here, or else the object will never
00330 // be deleted!
00331 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
00332                      SCEVAddRecExpr*> > SCEVAddRecExprs;
00333 
00334 SCEVAddRecExpr::~SCEVAddRecExpr() {
00335   SCEVAddRecExprs->erase(std::make_pair(L,
00336                                         std::vector<SCEV*>(Operands.begin(),
00337                                                            Operands.end())));
00338 }
00339 
00340 SCEVHandle SCEVAddRecExpr::
00341 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
00342                                   const SCEVHandle &Conc,
00343                                   ScalarEvolution &SE) const {
00344   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
00345     SCEVHandle H =
00346       getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
00347     if (H != getOperand(i)) {
00348       std::vector<SCEVHandle> NewOps;
00349       NewOps.reserve(getNumOperands());
00350       for (unsigned j = 0; j != i; ++j)
00351         NewOps.push_back(getOperand(j));
00352       NewOps.push_back(H);
00353       for (++i; i != e; ++i)
00354         NewOps.push_back(getOperand(i)->
00355                          replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
00356 
00357       return SE.getAddRecExpr(NewOps, L);
00358     }
00359   }
00360   return this;
00361 }
00362 
00363 
00364 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
00365   // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
00366   // contain L and if the start is invariant.
00367   return !QueryLoop->contains(L->getHeader()) &&
00368          getOperand(0)->isLoopInvariant(QueryLoop);
00369 }
00370 
00371 
00372 void SCEVAddRecExpr::print(std::ostream &OS) const {
00373   OS << "{" << *Operands[0];
00374   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
00375     OS << ",+," << *Operands[i];
00376   OS << "}<" << L->getHeader()->getName() + ">";
00377 }
00378 
00379 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
00380 // value.  Don't use a SCEVHandle here, or else the object will never be
00381 // deleted!
00382 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
00383 
00384 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
00385 
00386 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
00387   // All non-instruction values are loop invariant.  All instructions are loop
00388   // invariant if they are not contained in the specified loop.
00389   if (Instruction *I = dyn_cast<Instruction>(V))
00390     return !L->contains(I->getParent());
00391   return true;
00392 }
00393 
00394 const Type *SCEVUnknown::getType() const {
00395   return V->getType();
00396 }
00397 
00398 void SCEVUnknown::print(std::ostream &OS) const {
00399   WriteAsOperand(OS, V, false);
00400 }
00401 
00402 //===----------------------------------------------------------------------===//
00403 //                               SCEV Utilities
00404 //===----------------------------------------------------------------------===//
00405 
00406 namespace {
00407   /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
00408   /// than the complexity of the RHS.  This comparator is used to canonicalize
00409   /// expressions.
00410   struct VISIBILITY_HIDDEN SCEVComplexityCompare {
00411     bool operator()(const SCEV *LHS, const SCEV *RHS) const {
00412       return LHS->getSCEVType() < RHS->getSCEVType();
00413     }
00414   };
00415 }
00416 
00417 /// GroupByComplexity - Given a list of SCEV objects, order them by their
00418 /// complexity, and group objects of the same complexity together by value.
00419 /// When this routine is finished, we know that any duplicates in the vector are
00420 /// consecutive and that complexity is monotonically increasing.
00421 ///
00422 /// Note that we go take special precautions to ensure that we get determinstic
00423 /// results from this routine.  In other words, we don't want the results of
00424 /// this to depend on where the addresses of various SCEV objects happened to
00425 /// land in memory.
00426 ///
00427 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
00428   if (Ops.size() < 2) return;  // Noop
00429   if (Ops.size() == 2) {
00430     // This is the common case, which also happens to be trivially simple.
00431     // Special case it.
00432     if (SCEVComplexityCompare()(Ops[1], Ops[0]))
00433       std::swap(Ops[0], Ops[1]);
00434     return;
00435   }
00436 
00437   // Do the rough sort by complexity.
00438   std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
00439 
00440   // Now that we are sorted by complexity, group elements of the same
00441   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
00442   // be extremely short in practice.  Note that we take this approach because we
00443   // do not want to depend on the addresses of the objects we are grouping.
00444   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
00445     SCEV *S = Ops[i];
00446     unsigned Complexity = S->getSCEVType();
00447 
00448     // If there are any objects of the same complexity and same value as this
00449     // one, group them.
00450     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
00451       if (Ops[j] == S) { // Found a duplicate.
00452         // Move it to immediately after i'th element.
00453         std::swap(Ops[i+1], Ops[j]);
00454         ++i;   // no need to rescan it.
00455         if (i == e-2) return;  // Done!
00456       }
00457     }
00458   }
00459 }
00460 
00461 
00462 
00463 //===----------------------------------------------------------------------===//
00464 //                      Simple SCEV method implementations
00465 //===----------------------------------------------------------------------===//
00466 
00467 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
00468 /// specified signed integer value and return a SCEV for the constant.
00469 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
00470   Constant *C;
00471   if (Val == 0)
00472     C = Constant::getNullValue(Ty);
00473   else if (Ty->isFloatingPoint())
00474     C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle : 
00475                                 APFloat::IEEEdouble, Val));
00476   else 
00477     C = ConstantInt::get(Ty, Val);
00478   return getUnknown(C);
00479 }
00480 
00481 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
00482 ///
00483 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
00484   if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
00485     return getUnknown(ConstantExpr::getNeg(VC->getValue()));
00486 
00487   return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
00488 }
00489 
00490 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
00491 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
00492   if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
00493     return getUnknown(ConstantExpr::getNot(VC->getValue()));
00494 
00495   SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
00496   return getMinusSCEV(AllOnes, V);
00497 }
00498 
00499 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
00500 ///
00501 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
00502                                          const SCEVHandle &RHS) {
00503   // X - Y --> X + -Y
00504   return getAddExpr(LHS, getNegativeSCEV(RHS));
00505 }
00506 
00507 
00508 /// BinomialCoefficient - Compute BC(It, K).  The result has width W.
00509 // Assume, K > 0.
00510 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
00511                                       ScalarEvolution &SE,
00512                                       const IntegerType* ResultTy) {
00513   // Handle the simplest case efficiently.
00514   if (K == 1)
00515     return SE.getTruncateOrZeroExtend(It, ResultTy);
00516 
00517   // We are using the following formula for BC(It, K):
00518   //
00519   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
00520   //
00521   // Suppose, W is the bitwidth of the return value.  We must be prepared for
00522   // overflow.  Hence, we must assure that the result of our computation is
00523   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
00524   // safe in modular arithmetic.
00525   //
00526   // However, this code doesn't use exactly that formula; the formula it uses
00527   // is something like the following, where T is the number of factors of 2 in 
00528   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
00529   // exponentiation:
00530   //
00531   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
00532   //
00533   // This formula is trivially equivalent to the previous formula.  However,
00534   // this formula can be implemented much more efficiently.  The trick is that
00535   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
00536   // arithmetic.  To do exact division in modular arithmetic, all we have
00537   // to do is multiply by the inverse.  Therefore, this step can be done at
00538   // width W.
00539   // 
00540   // The next issue is how to safely do the division by 2^T.  The way this
00541   // is done is by doing the multiplication step at a width of at least W + T
00542   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
00543   // when we perform the division by 2^T (which is equivalent to a right shift
00544   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
00545   // truncated out after the division by 2^T.
00546   //
00547   // In comparison to just directly using the first formula, this technique
00548   // is much more efficient; using the first formula requires W * K bits,
00549   // but this formula less than W + K bits. Also, the first formula requires
00550   // a division step, whereas this formula only requires multiplies and shifts.
00551   //
00552   // It doesn't matter whether the subtraction step is done in the calculation
00553   // width or the input iteration count's width; if the subtraction overflows,
00554   // the result must be zero anyway.  We prefer here to do it in the width of
00555   // the induction variable because it helps a lot for certain cases; CodeGen
00556   // isn't smart enough to ignore the overflow, which leads to much less
00557   // efficient code if the width of the subtraction is wider than the native
00558   // register width.
00559   //
00560   // (It's possible to not widen at all by pulling out factors of 2 before
00561   // the multiplication; for example, K=2 can be calculated as
00562   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
00563   // extra arithmetic, so it's not an obvious win, and it gets
00564   // much more complicated for K > 3.)
00565 
00566   // Protection from insane SCEVs; this bound is conservative,
00567   // but it probably doesn't matter.
00568   if (K > 1000)
00569     return new SCEVCouldNotCompute();
00570 
00571   unsigned W = ResultTy->getBitWidth();
00572 
00573   // Calculate K! / 2^T and T; we divide out the factors of two before
00574   // multiplying for calculating K! / 2^T to avoid overflow.
00575   // Other overflow doesn't matter because we only care about the bottom
00576   // W bits of the result.
00577   APInt OddFactorial(W, 1);
00578   unsigned T = 1;
00579   for (unsigned i = 3; i <= K; ++i) {
00580     APInt Mult(W, i);
00581     unsigned TwoFactors = Mult.countTrailingZeros();
00582     T += TwoFactors;
00583     Mult = Mult.lshr(TwoFactors);
00584     OddFactorial *= Mult;
00585   }
00586 
00587   // We need at least W + T bits for the multiplication step
00588   // FIXME: A temporary hack; we round up the bitwidths
00589   // to the nearest power of 2 to be nice to the code generator.
00590   unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
00591   // FIXME: Temporary hack to avoid generating integers that are too wide.
00592   // Although, it's not completely clear how to determine how much
00593   // widening is safe; for example, on X86, we can't really widen
00594   // beyond 64 because we need to be able to do multiplication
00595   // that's CalculationBits wide, but on X86-64, we can safely widen up to
00596   // 128 bits.
00597   if (CalculationBits > 64)
00598     return new SCEVCouldNotCompute();
00599 
00600   // Calcuate 2^T, at width T+W.
00601   APInt DivFactor = APInt(CalculationBits, 1).shl(T);
00602 
00603   // Calculate the multiplicative inverse of K! / 2^T;
00604   // this multiplication factor will perform the exact division by
00605   // K! / 2^T.
00606   APInt Mod = APInt::getSignedMinValue(W+1);
00607   APInt MultiplyFactor = OddFactorial.zext(W+1);
00608   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
00609   MultiplyFactor = MultiplyFactor.trunc(W);
00610 
00611   // Calculate the product, at width T+W
00612   const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
00613   SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
00614   for (unsigned i = 1; i != K; ++i) {
00615     SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
00616     Dividend = SE.getMulExpr(Dividend,
00617                              SE.getTruncateOrZeroExtend(S, CalculationTy));
00618   }
00619 
00620   // Divide by 2^T
00621   SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
00622 
00623   // Truncate the result, and divide by K! / 2^T.
00624 
00625   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
00626                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
00627 }
00628 
00629 /// evaluateAtIteration - Return the value of this chain of recurrences at
00630 /// the specified iteration number.  We can evaluate this recurrence by
00631 /// multiplying each element in the chain by the binomial coefficient
00632 /// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
00633 ///
00634 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
00635 ///
00636 /// where BC(It, k) stands for binomial coefficient.
00637 ///
00638 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
00639                                                ScalarEvolution &SE) const {
00640   SCEVHandle Result = getStart();
00641   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
00642     // The computation is correct in the face of overflow provided that the
00643     // multiplication is performed _after_ the evaluation of the binomial
00644     // coefficient.
00645     SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
00646                                            cast<IntegerType>(getType()));
00647     if (isa<SCEVCouldNotCompute>(Coeff))
00648       return Coeff;
00649 
00650     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
00651   }
00652   return Result;
00653 }
00654 
00655 //===----------------------------------------------------------------------===//
00656 //                    SCEV Expression folder implementations
00657 //===----------------------------------------------------------------------===//
00658 
00659 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
00660   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
00661     return getUnknown(
00662         ConstantExpr::getTrunc(SC->getValue(), Ty));
00663 
00664   // If the input value is a chrec scev made out of constants, truncate
00665   // all of the constants.
00666   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
00667     std::vector<SCEVHandle> Operands;
00668     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
00669       // FIXME: This should allow truncation of other expression types!
00670       if (isa<SCEVConstant>(AddRec->getOperand(i)))
00671         Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
00672       else
00673         break;
00674     if (Operands.size() == AddRec->getNumOperands())
00675       return getAddRecExpr(Operands, AddRec->getLoop());
00676   }
00677 
00678   SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
00679   if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
00680   return Result;
00681 }
00682 
00683 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
00684   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
00685     return getUnknown(
00686         ConstantExpr::getZExt(SC->getValue(), Ty));
00687 
00688   // FIXME: If the input value is a chrec scev, and we can prove that the value
00689   // did not overflow the old, smaller, value, we can zero extend all of the
00690   // operands (often constants).  This would allow analysis of something like
00691   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
00692 
00693   SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
00694   if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
00695   return Result;
00696 }
00697 
00698 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
00699   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
00700     return getUnknown(
00701         ConstantExpr::getSExt(SC->getValue(), Ty));
00702 
00703   // FIXME: If the input value is a chrec scev, and we can prove that the value
00704   // did not overflow the old, smaller, value, we can sign extend all of the
00705   // operands (often constants).  This would allow analysis of something like
00706   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
00707 
00708   SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
00709   if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
00710   return Result;
00711 }
00712 
00713 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
00714 /// of the input value to the specified type.  If the type must be
00715 /// extended, it is zero extended.
00716 SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
00717                                                     const Type *Ty) {
00718   const Type *SrcTy = V->getType();
00719   assert(SrcTy->isInteger() && Ty->isInteger() &&
00720          "Cannot truncate or zero extend with non-integer arguments!");
00721   if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
00722     return V;  // No conversion
00723   if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
00724     return getTruncateExpr(V, Ty);
00725   return getZeroExtendExpr(V, Ty);
00726 }
00727 
00728 // get - Get a canonical add expression, or something simpler if possible.
00729 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
00730   assert(!Ops.empty() && "Cannot get empty add!");
00731   if (Ops.size() == 1) return Ops[0];
00732 
00733   // Sort by complexity, this groups all similar expression types together.
00734   GroupByComplexity(Ops);
00735 
00736   // If there are any constants, fold them together.
00737   unsigned Idx = 0;
00738   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
00739     ++Idx;
00740     assert(Idx < Ops.size());
00741     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
00742       // We found two constants, fold them together!
00743       ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() + 
00744                                            RHSC->getValue()->getValue());
00745       Ops[0] = getConstant(Fold);
00746       Ops.erase(Ops.begin()+1);  // Erase the folded element
00747       if (Ops.size() == 1) return Ops[0];
00748       LHSC = cast<SCEVConstant>(Ops[0]);
00749     }
00750 
00751     // If we are left with a constant zero being added, strip it off.
00752     if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
00753       Ops.erase(Ops.begin());
00754       --Idx;
00755     }
00756   }
00757 
00758   if (Ops.size() == 1) return Ops[0];
00759 
00760   // Okay, check to see if the same value occurs in the operand list twice.  If
00761   // so, merge them together into an multiply expression.  Since we sorted the
00762   // list, these values are required to be adjacent.
00763   const Type *Ty = Ops[0]->getType();
00764   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
00765     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
00766       // Found a match, merge the two values into a multiply, and add any
00767       // remaining values to the result.
00768       SCEVHandle Two = getIntegerSCEV(2, Ty);
00769       SCEVHandle Mul = getMulExpr(Ops[i], Two);
00770       if (Ops.size() == 2)
00771         return Mul;
00772       Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
00773       Ops.push_back(Mul);
00774       return getAddExpr(Ops);
00775     }
00776 
00777   // Now we know the first non-constant operand.  Skip past any cast SCEVs.
00778   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
00779     ++Idx;
00780 
00781   // If there are add operands they would be next.
00782   if (Idx < Ops.size()) {
00783     bool DeletedAdd = false;
00784     while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
00785       // If we have an add, expand the add operands onto the end of the operands
00786       // list.
00787       Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
00788       Ops.erase(Ops.begin()+Idx);
00789       DeletedAdd = true;
00790     }
00791 
00792     // If we deleted at least one add, we added operands to the end of the list,
00793     // and they are not necessarily sorted.  Recurse to resort and resimplify
00794     // any operands we just aquired.
00795     if (DeletedAdd)
00796       return getAddExpr(Ops);
00797   }
00798 
00799   // Skip over the add expression until we get to a multiply.
00800   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
00801     ++Idx;
00802 
00803   // If we are adding something to a multiply expression, make sure the
00804   // something is not already an operand of the multiply.  If so, merge it into
00805   // the multiply.
00806   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
00807     SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
00808     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
00809       SCEV *MulOpSCEV = Mul->getOperand(MulOp);
00810       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
00811         if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
00812           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
00813           SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
00814           if (Mul->getNumOperands() != 2) {
00815             // If the multiply has more than two operands, we must get the
00816             // Y*Z term.
00817             std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
00818             MulOps.erase(MulOps.begin()+MulOp);
00819             InnerMul = getMulExpr(MulOps);
00820           }
00821           SCEVHandle One = getIntegerSCEV(1, Ty);
00822           SCEVHandle AddOne = getAddExpr(InnerMul, One);
00823           SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
00824           if (Ops.size() == 2) return OuterMul;
00825           if (AddOp < Idx) {
00826             Ops.erase(Ops.begin()+AddOp);
00827             Ops.erase(Ops.begin()+Idx-1);
00828           } else {
00829             Ops.erase(Ops.begin()+Idx);
00830             Ops.erase(Ops.begin()+AddOp-1);
00831           }
00832           Ops.push_back(OuterMul);
00833           return getAddExpr(Ops);
00834         }
00835 
00836       // Check this multiply against other multiplies being added together.
00837       for (unsigned OtherMulIdx = Idx+1;
00838            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
00839            ++OtherMulIdx) {
00840         SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
00841         // If MulOp occurs in OtherMul, we can fold the two multiplies
00842         // together.
00843         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
00844              OMulOp != e; ++OMulOp)
00845           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
00846             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
00847             SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
00848             if (Mul->getNumOperands() != 2) {
00849               std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
00850               MulOps.erase(MulOps.begin()+MulOp);
00851               InnerMul1 = getMulExpr(MulOps);
00852             }
00853             SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
00854             if (OtherMul->getNumOperands() != 2) {
00855               std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
00856                                              OtherMul->op_end());
00857               MulOps.erase(MulOps.begin()+OMulOp);
00858               InnerMul2 = getMulExpr(MulOps);
00859             }
00860             SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
00861             SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
00862             if (Ops.size() == 2) return OuterMul;
00863             Ops.erase(Ops.begin()+Idx);
00864             Ops.erase(Ops.begin()+OtherMulIdx-1);
00865             Ops.push_back(OuterMul);
00866             return getAddExpr(Ops);
00867           }
00868       }
00869     }
00870   }
00871 
00872   // If there are any add recurrences in the operands list, see if any other
00873   // added values are loop invariant.  If so, we can fold them into the
00874   // recurrence.
00875   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
00876     ++Idx;
00877 
00878   // Scan over all recurrences, trying to fold loop invariants into them.
00879   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
00880     // Scan all of the other operands to this add and add them to the vector if
00881     // they are loop invariant w.r.t. the recurrence.
00882     std::vector<SCEVHandle> LIOps;
00883     SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
00884     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
00885       if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
00886         LIOps.push_back(Ops[i]);
00887         Ops.erase(Ops.begin()+i);
00888         --i; --e;
00889       }
00890 
00891     // If we found some loop invariants, fold them into the recurrence.
00892     if (!LIOps.empty()) {
00893       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
00894       LIOps.push_back(AddRec->getStart());
00895 
00896       std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
00897       AddRecOps[0] = getAddExpr(LIOps);
00898 
00899       SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
00900       // If all of the other operands were loop invariant, we are done.
00901       if (Ops.size() == 1) return NewRec;
00902 
00903       // Otherwise, add the folded AddRec by the non-liv parts.
00904       for (unsigned i = 0;; ++i)
00905         if (Ops[i] == AddRec) {
00906           Ops[i] = NewRec;
00907           break;
00908         }
00909       return getAddExpr(Ops);
00910     }
00911 
00912     // Okay, if there weren't any loop invariants to be folded, check to see if
00913     // there are multiple AddRec's with the same loop induction variable being
00914     // added together.  If so, we can fold them.
00915     for (unsigned OtherIdx = Idx+1;
00916          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
00917       if (OtherIdx != Idx) {
00918         SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
00919         if (AddRec->getLoop() == OtherAddRec->getLoop()) {
00920           // Other + {A,+,B} + {C,+,D}  -->  Other + {A+C,+,B+D}
00921           std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
00922           for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
00923             if (i >= NewOps.size()) {
00924               NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
00925                             OtherAddRec->op_end());
00926               break;
00927             }
00928             NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
00929           }
00930           SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
00931 
00932           if (Ops.size() == 2) return NewAddRec;
00933 
00934           Ops.erase(Ops.begin()+Idx);
00935           Ops.erase(Ops.begin()+OtherIdx-1);
00936           Ops.push_back(NewAddRec);
00937           return getAddExpr(Ops);
00938         }
00939       }
00940 
00941     // Otherwise couldn't fold anything into this recurrence.  Move onto the
00942     // next one.
00943   }
00944 
00945   // Okay, it looks like we really DO need an add expr.  Check to see if we
00946   // already have one, otherwise create a new one.
00947   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
00948   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
00949                                                                  SCEVOps)];
00950   if (Result == 0) Result = new SCEVAddExpr(Ops);
00951   return Result;
00952 }
00953 
00954 
00955 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
00956   assert(!Ops.empty() && "Cannot get empty mul!");
00957 
00958   // Sort by complexity, this groups all similar expression types together.
00959   GroupByComplexity(Ops);
00960 
00961   // If there are any constants, fold them together.
00962   unsigned Idx = 0;
00963   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
00964 
00965     // C1*(C2+V) -> C1*C2 + C1*V
00966     if (Ops.size() == 2)
00967       if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
00968         if (Add->getNumOperands() == 2 &&
00969             isa<SCEVConstant>(Add->getOperand(0)))
00970           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
00971                             getMulExpr(LHSC, Add->getOperand(1)));
00972 
00973 
00974     ++Idx;
00975     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
00976       // We found two constants, fold them together!
00977       ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() * 
00978                                            RHSC->getValue()->getValue());
00979       Ops[0] = getConstant(Fold);
00980       Ops.erase(Ops.begin()+1);  // Erase the folded element
00981       if (Ops.size() == 1) return Ops[0];
00982       LHSC = cast<SCEVConstant>(Ops[0]);
00983     }
00984 
00985     // If we are left with a constant one being multiplied, strip it off.
00986     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
00987       Ops.erase(Ops.begin());
00988       --Idx;
00989     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
00990       // If we have a multiply of zero, it will always be zero.
00991       return Ops[0];
00992     }
00993   }
00994 
00995   // Skip over the add expression until we get to a multiply.
00996   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
00997     ++Idx;
00998 
00999   if (Ops.size() == 1)
01000     return Ops[0];
01001 
01002   // If there are mul operands inline them all into this expression.
01003   if (Idx < Ops.size()) {
01004     bool DeletedMul = false;
01005     while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
01006       // If we have an mul, expand the mul operands onto the end of the operands
01007       // list.
01008       Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
01009       Ops.erase(Ops.begin()+Idx);
01010       DeletedMul = true;
01011     }
01012 
01013     // If we deleted at least one mul, we added operands to the end of the list,
01014     // and they are not necessarily sorted.  Recurse to resort and resimplify
01015     // any operands we just aquired.
01016     if (DeletedMul)
01017       return getMulExpr(Ops);
01018   }
01019 
01020   // If there are any add recurrences in the operands list, see if any other
01021   // added values are loop invariant.  If so, we can fold them into the
01022   // recurrence.
01023   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
01024     ++Idx;
01025 
01026   // Scan over all recurrences, trying to fold loop invariants into them.
01027   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
01028     // Scan all of the other operands to this mul and add them to the vector if
01029     // they are loop invariant w.r.t. the recurrence.
01030     std::vector<SCEVHandle> LIOps;
01031     SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
01032     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
01033       if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
01034         LIOps.push_back(Ops[i]);
01035         Ops.erase(Ops.begin()+i);
01036         --i; --e;
01037       }
01038 
01039     // If we found some loop invariants, fold them into the recurrence.
01040     if (!LIOps.empty()) {
01041       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
01042       std::vector<SCEVHandle> NewOps;
01043       NewOps.reserve(AddRec->getNumOperands());
01044       if (LIOps.size() == 1) {
01045         SCEV *Scale = LIOps[0];
01046         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
01047           NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
01048       } else {
01049         for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
01050           std::vector<SCEVHandle> MulOps(LIOps);
01051           MulOps.push_back(AddRec->getOperand(i));
01052           NewOps.push_back(getMulExpr(MulOps));
01053         }
01054       }
01055 
01056       SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
01057 
01058       // If all of the other operands were loop invariant, we are done.
01059       if (Ops.size() == 1) return NewRec;
01060 
01061       // Otherwise, multiply the folded AddRec by the non-liv parts.
01062       for (unsigned i = 0;; ++i)
01063         if (Ops[i] == AddRec) {
01064           Ops[i] = NewRec;
01065           break;
01066         }
01067       return getMulExpr(Ops);
01068     }
01069 
01070     // Okay, if there weren't any loop invariants to be folded, check to see if
01071     // there are multiple AddRec's with the same loop induction variable being
01072     // multiplied together.  If so, we can fold them.
01073     for (unsigned OtherIdx = Idx+1;
01074          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
01075       if (OtherIdx != Idx) {
01076         SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
01077         if (AddRec->getLoop() == OtherAddRec->getLoop()) {
01078           // F * G  -->  {A,+,B} * {C,+,D}  -->  {A*C,+,F*D + G*B + B*D}
01079           SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
01080           SCEVHandle NewStart = getMulExpr(F->getStart(),
01081                                                  G->getStart());
01082           SCEVHandle B = F->getStepRecurrence(*this);
01083           SCEVHandle D = G->getStepRecurrence(*this);
01084           SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
01085                                           getMulExpr(G, B),
01086                                           getMulExpr(B, D));
01087           SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
01088                                                F->getLoop());
01089           if (Ops.size() == 2) return NewAddRec;
01090 
01091           Ops.erase(Ops.begin()+Idx);
01092           Ops.erase(Ops.begin()+OtherIdx-1);
01093           Ops.push_back(NewAddRec);
01094           return getMulExpr(Ops);
01095         }
01096       }
01097 
01098     // Otherwise couldn't fold anything into this recurrence.  Move onto the
01099     // next one.
01100   }
01101 
01102   // Okay, it looks like we really DO need an mul expr.  Check to see if we
01103   // already have one, otherwise create a new one.
01104   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
01105   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
01106                                                                  SCEVOps)];
01107   if (Result == 0)
01108     Result = new SCEVMulExpr(Ops);
01109   return Result;
01110 }
01111 
01112 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
01113   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
01114     if (RHSC->getValue()->equalsInt(1))
01115       return LHS;                            // X udiv 1 --> x
01116 
01117     if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
01118       Constant *LHSCV = LHSC->getValue();
01119       Constant *RHSCV = RHSC->getValue();
01120       return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
01121     }
01122   }
01123 
01124   // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
01125 
01126   SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
01127   if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
01128   return Result;
01129 }
01130 
01131 
01132 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
01133 /// specified loop.  Simplify the expression as much as possible.
01134 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
01135                                const SCEVHandle &Step, const Loop *L) {
01136   std::vector<SCEVHandle> Operands;
01137   Operands.push_back(Start);
01138   if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
01139     if (StepChrec->getLoop() == L) {
01140       Operands.insert(Operands.end(), StepChrec->op_begin(),
01141                       StepChrec->op_end());
01142       return getAddRecExpr(Operands, L);
01143     }
01144 
01145   Operands.push_back(Step);
01146   return getAddRecExpr(Operands, L);
01147 }
01148 
01149 /// SCEVAddRecExpr::get - Get a add recurrence expression for the
01150 /// specified loop.  Simplify the expression as much as possible.
01151 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
01152                                const Loop *L) {
01153   if (Operands.size() == 1) return Operands[0];
01154 
01155   if (Operands.back()->isZero()) {
01156     Operands.pop_back();
01157     return getAddRecExpr(Operands, L);             // {X,+,0}  -->  X
01158   }
01159 
01160   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
01161   if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
01162     const Loop* NestedLoop = NestedAR->getLoop();
01163     if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
01164       std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
01165                                              NestedAR->op_end());
01166       SCEVHandle NestedARHandle(NestedAR);
01167       Operands[0] = NestedAR->getStart();
01168       NestedOperands[0] = getAddRecExpr(Operands, L);
01169       return getAddRecExpr(NestedOperands, NestedLoop);
01170     }
01171   }
01172 
01173   SCEVAddRecExpr *&Result =
01174     (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
01175                                                             Operands.end()))];
01176   if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
01177   return Result;
01178 }
01179 
01180 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
01181                                         const SCEVHandle &RHS) {
01182   std::vector<SCEVHandle> Ops;
01183   Ops.push_back(LHS);
01184   Ops.push_back(RHS);
01185   return getSMaxExpr(Ops);
01186 }
01187 
01188 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
01189   assert(!Ops.empty() && "Cannot get empty smax!");
01190   if (Ops.size() == 1) return Ops[0];
01191 
01192   // Sort by complexity, this groups all similar expression types together.
01193   GroupByComplexity(Ops);
01194 
01195   // If there are any constants, fold them together.
01196   unsigned Idx = 0;
01197   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
01198     ++Idx;
01199     assert(Idx < Ops.size());
01200     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
01201       // We found two constants, fold them together!
01202       ConstantInt *Fold = ConstantInt::get(
01203                               APIntOps::smax(LHSC->getValue()->getValue(),
01204                                              RHSC->getValue()->getValue()));
01205       Ops[0] = getConstant(Fold);
01206       Ops.erase(Ops.begin()+1);  // Erase the folded element
01207       if (Ops.size() == 1) return Ops[0];
01208       LHSC = cast<SCEVConstant>(Ops[0]);
01209     }
01210 
01211     // If we are left with a constant -inf, strip it off.
01212     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
01213       Ops.erase(Ops.begin());
01214       --Idx;
01215     }
01216   }
01217 
01218   if (Ops.size() == 1) return Ops[0];
01219 
01220   // Find the first SMax
01221   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
01222     ++Idx;
01223 
01224   // Check to see if one of the operands is an SMax. If so, expand its operands
01225   // onto our operand list, and recurse to simplify.
01226   if (Idx < Ops.size()) {
01227     bool DeletedSMax = false;
01228     while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
01229       Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
01230       Ops.erase(Ops.begin()+Idx);
01231       DeletedSMax = true;
01232     }
01233 
01234     if (DeletedSMax)
01235       return getSMaxExpr(Ops);
01236   }
01237 
01238   // Okay, check to see if the same value occurs in the operand list twice.  If
01239   // so, delete one.  Since we sorted the list, these values are required to
01240   // be adjacent.
01241   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
01242     if (Ops[i] == Ops[i+1]) {      //  X smax Y smax Y  -->  X smax Y
01243       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
01244       --i; --e;
01245     }
01246 
01247   if (Ops.size() == 1) return Ops[0];
01248 
01249   assert(!Ops.empty() && "Reduced smax down to nothing!");
01250 
01251   // Okay, it looks like we really DO need an smax expr.  Check to see if we
01252   // already have one, otherwise create a new one.
01253   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
01254   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
01255                                                                  SCEVOps)];
01256   if (Result == 0) Result = new SCEVSMaxExpr(Ops);
01257   return Result;
01258 }
01259 
01260 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
01261                                         const SCEVHandle &RHS) {
01262   std::vector<SCEVHandle> Ops;
01263   Ops.push_back(LHS);
01264   Ops.push_back(RHS);
01265   return getUMaxExpr(Ops);
01266 }
01267 
01268 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
01269   assert(!Ops.empty() && "Cannot get empty umax!");
01270   if (Ops.size() == 1) return Ops[0];
01271 
01272   // Sort by complexity, this groups all similar expression types together.
01273   GroupByComplexity(Ops);
01274 
01275   // If there are any constants, fold them together.
01276   unsigned Idx = 0;
01277   if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
01278     ++Idx;
01279     assert(Idx < Ops.size());
01280     while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
01281       // We found two constants, fold them together!
01282       ConstantInt *Fold = ConstantInt::get(
01283                               APIntOps::umax(LHSC->getValue()->getValue(),
01284                                              RHSC->getValue()->getValue()));
01285       Ops[0] = getConstant(Fold);
01286       Ops.erase(Ops.begin()+1);  // Erase the folded element
01287       if (Ops.size() == 1) return Ops[0];
01288       LHSC = cast<SCEVConstant>(Ops[0]);
01289     }
01290 
01291     // If we are left with a constant zero, strip it off.
01292     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
01293       Ops.erase(Ops.begin());
01294       --Idx;
01295     }
01296   }
01297 
01298   if (Ops.size() == 1) return Ops[0];
01299 
01300   // Find the first UMax
01301   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
01302     ++Idx;
01303 
01304   // Check to see if one of the operands is a UMax. If so, expand its operands
01305   // onto our operand list, and recurse to simplify.
01306   if (Idx < Ops.size()) {
01307     bool DeletedUMax = false;
01308     while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
01309       Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
01310       Ops.erase(Ops.begin()+Idx);
01311       DeletedUMax = true;
01312     }
01313 
01314     if (DeletedUMax)
01315       return getUMaxExpr(Ops);
01316   }
01317 
01318   // Okay, check to see if the same value occurs in the operand list twice.  If
01319   // so, delete one.  Since we sorted the list, these values are required to
01320   // be adjacent.
01321   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
01322     if (Ops[i] == Ops[i+1]) {      //  X umax Y umax Y  -->  X umax Y
01323       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
01324       --i; --e;
01325     }
01326 
01327   if (Ops.size() == 1) return Ops[0];
01328 
01329   assert(!Ops.empty() && "Reduced umax down to nothing!");
01330 
01331   // Okay, it looks like we really DO need a umax expr.  Check to see if we
01332   // already have one, otherwise create a new one.
01333   std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
01334   SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
01335                                                                  SCEVOps)];
01336   if (Result == 0) Result = new SCEVUMaxExpr(Ops);
01337   return Result;
01338 }
01339 
01340 SCEVHandle ScalarEvolution::getUnknown(Value *V) {
01341   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
01342     return getConstant(CI);
01343   SCEVUnknown *&Result = (*SCEVUnknowns)[V];
01344   if (Result == 0) Result = new SCEVUnknown(V);
01345   return Result;
01346 }
01347 
01348 
01349 //===----------------------------------------------------------------------===//
01350 //             ScalarEvolutionsImpl Definition and Implementation
01351 //===----------------------------------------------------------------------===//
01352 //
01353 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar
01354 /// evolution code.
01355 ///
01356 namespace {
01357   struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
01358     /// SE - A reference to the public ScalarEvolution object.
01359     ScalarEvolution &SE;
01360 
01361     /// F - The function we are analyzing.
01362     ///
01363     Function &F;
01364 
01365     /// LI - The loop information for the function we are currently analyzing.
01366     ///
01367     LoopInfo &LI;
01368 
01369     /// UnknownValue - This SCEV is used to represent unknown trip counts and
01370     /// things.
01371     SCEVHandle UnknownValue;
01372 
01373     /// Scalars - This is a cache of the scalars we have analyzed so far.
01374     ///
01375     std::map<Value*, SCEVHandle> Scalars;
01376 
01377     /// IterationCounts - Cache the iteration count of the loops for this
01378     /// function as they are computed.
01379     std::map<const Loop*, SCEVHandle> IterationCounts;
01380 
01381     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
01382     /// the PHI instructions that we attempt to compute constant evolutions for.
01383     /// This allows us to avoid potentially expensive recomputation of these
01384     /// properties.  An instruction maps to null if we are unable to compute its
01385     /// exit value.
01386     std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
01387 
01388   public:
01389     ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
01390       : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
01391 
01392     /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
01393     /// expression and create a new one.
01394     SCEVHandle getSCEV(Value *V);
01395 
01396     /// hasSCEV - Return true if the SCEV for this value has already been
01397     /// computed.
01398     bool hasSCEV(Value *V) const {
01399       return Scalars.count(V);
01400     }
01401 
01402     /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
01403     /// the specified value.
01404     void setSCEV(Value *V, const SCEVHandle &H) {
01405       bool isNew = Scalars.insert(std::make_pair(V, H)).second;
01406       assert(isNew && "This entry already existed!");
01407       isNew = false;
01408     }
01409 
01410 
01411     /// getSCEVAtScope - Compute the value of the specified expression within
01412     /// the indicated loop (which may be null to indicate in no loop).  If the
01413     /// expression cannot be evaluated, return UnknownValue itself.
01414     SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
01415 
01416 
01417     /// hasLoopInvariantIterationCount - Return true if the specified loop has
01418     /// an analyzable loop-invariant iteration count.
01419     bool hasLoopInvariantIterationCount(const Loop *L);
01420 
01421     /// getIterationCount - If the specified loop has a predictable iteration
01422     /// count, return it.  Note that it is not valid to call this method on a
01423     /// loop without a loop-invariant iteration count.
01424     SCEVHandle getIterationCount(const Loop *L);
01425 
01426     /// deleteValueFromRecords - This method should be called by the
01427     /// client before it removes a value from the program, to make sure
01428     /// that no dangling references are left around.
01429     void deleteValueFromRecords(Value *V);
01430 
01431   private:
01432     /// createSCEV - We know that there is no SCEV for the specified value.
01433     /// Analyze the expression.
01434     SCEVHandle createSCEV(Value *V);
01435 
01436     /// createNodeForPHI - Provide the special handling we need to analyze PHI
01437     /// SCEVs.
01438     SCEVHandle createNodeForPHI(PHINode *PN);
01439 
01440     /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
01441     /// for the specified instruction and replaces any references to the
01442     /// symbolic value SymName with the specified value.  This is used during
01443     /// PHI resolution.
01444     void ReplaceSymbolicValueWithConcrete(Instruction *I,
01445                                           const SCEVHandle &SymName,
01446                                           const SCEVHandle &NewVal);
01447 
01448     /// ComputeIterationCount - Compute the number of times the specified loop
01449     /// will iterate.
01450     SCEVHandle ComputeIterationCount(const Loop *L);
01451 
01452     /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
01453     /// 'icmp op load X, cst', try to see if we can compute the trip count.
01454     SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
01455                                                         Constant *RHS,
01456                                                         const Loop *L,
01457                                                         ICmpInst::Predicate p);
01458 
01459     /// ComputeIterationCountExhaustively - If the trip is known to execute a
01460     /// constant number of times (the condition evolves only from constants),
01461     /// try to evaluate a few iterations of the loop until we get the exit
01462     /// condition gets a value of ExitWhen (true or false).  If we cannot
01463     /// evaluate the trip count of the loop, return UnknownValue.
01464     SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
01465                                                  bool ExitWhen);
01466 
01467     /// HowFarToZero - Return the number of times a backedge comparing the
01468     /// specified value to zero will execute.  If not computable, return
01469     /// UnknownValue.
01470     SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
01471 
01472     /// HowFarToNonZero - Return the number of times a backedge checking the
01473     /// specified value for nonzero will execute.  If not computable, return
01474     /// UnknownValue.
01475     SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
01476 
01477     /// HowManyLessThans - Return the number of times a backedge containing the
01478     /// specified less-than comparison will execute.  If not computable, return
01479     /// UnknownValue. isSigned specifies whether the less-than is signed.
01480     SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
01481                                 bool isSigned);
01482 
01483     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
01484     /// (which may not be an immediate predecessor) which has exactly one
01485     /// successor from which BB is reachable, or null if no such block is
01486     /// found.
01487     BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
01488 
01489     /// executesAtLeastOnce - Test whether entry to the loop is protected by
01490     /// a conditional between LHS and RHS.
01491     bool executesAtLeastOnce(const Loop *L, bool isSigned, SCEV *LHS, SCEV *RHS);
01492 
01493     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
01494     /// in the header of its containing loop, we know the loop executes a
01495     /// constant number of times, and the PHI node is just a recurrence
01496     /// involving constants, fold it.
01497     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
01498                                                 const Loop *L);
01499   };
01500 }
01501 
01502 //===----------------------------------------------------------------------===//
01503 //            Basic SCEV Analysis and PHI Idiom Recognition Code
01504 //
01505 
01506 /// deleteValueFromRecords - This method should be called by the
01507 /// client before it removes an instruction from the program, to make sure
01508 /// that no dangling references are left around.
01509 void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
01510   SmallVector<Value *, 16> Worklist;
01511 
01512   if (Scalars.erase(V)) {
01513     if (PHINode *PN = dyn_cast<PHINode>(V))
01514       ConstantEvolutionLoopExitValue.erase(PN);
01515     Worklist.push_back(V);
01516   }
01517 
01518   while (!Worklist.empty()) {
01519     Value *VV = Worklist.back();
01520     Worklist.pop_back();
01521 
01522     for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
01523          UI != UE; ++UI) {
01524       Instruction *Inst = cast<Instruction>(*UI);
01525       if (Scalars.erase(Inst)) {
01526         if (PHINode *PN = dyn_cast<PHINode>(VV))
01527           ConstantEvolutionLoopExitValue.erase(PN);
01528         Worklist.push_back(Inst);
01529       }
01530     }
01531   }
01532 }
01533 
01534 
01535 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
01536 /// expression and create a new one.
01537 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
01538   assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
01539 
01540   std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
01541   if (I != Scalars.end()) return I->second;
01542   SCEVHandle S = createSCEV(V);
01543   Scalars.insert(std::make_pair(V, S));
01544   return S;
01545 }
01546 
01547 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
01548 /// the specified instruction and replaces any references to the symbolic value
01549 /// SymName with the specified value.  This is used during PHI resolution.
01550 void ScalarEvolutionsImpl::
01551 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
01552                                  const SCEVHandle &NewVal) {
01553   std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
01554   if (SI == Scalars.end()) return;
01555 
01556   SCEVHandle NV =
01557     SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
01558   if (NV == SI->second) return;  // No change.
01559 
01560   SI->second = NV;       // Update the scalars map!
01561 
01562   // Any instruction values that use this instruction might also need to be
01563   // updated!
01564   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
01565        UI != E; ++UI)
01566     ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
01567 }
01568 
01569 /// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
01570 /// a loop header, making it a potential recurrence, or it doesn't.
01571 ///
01572 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
01573   if (PN->getNumIncomingValues() == 2)  // The loops have been canonicalized.
01574     if (const Loop *L = LI.getLoopFor(PN->getParent()))
01575       if (L->getHeader() == PN->getParent()) {
01576         // If it lives in the loop header, it has two incoming values, one
01577         // from outside the loop, and one from inside.
01578         unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
01579         unsigned BackEdge     = IncomingEdge^1;
01580 
01581         // While we are analyzing this PHI node, handle its value symbolically.
01582         SCEVHandle SymbolicName = SE.getUnknown(PN);
01583         assert(Scalars.find(PN) == Scalars.end() &&
01584                "PHI node already processed?");
01585         Scalars.insert(std::make_pair(PN, SymbolicName));
01586 
01587         // Using this symbolic name for the PHI, analyze the value coming around
01588         // the back-edge.
01589         SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
01590 
01591         // NOTE: If BEValue is loop invariant, we know that the PHI node just
01592         // has a special value for the first iteration of the loop.
01593 
01594         // If the value coming around the backedge is an add with the symbolic
01595         // value we just inserted, then we found a simple induction variable!
01596         if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
01597           // If there is a single occurrence of the symbolic value, replace it
01598           // with a recurrence.
01599           unsigned FoundIndex = Add->getNumOperands();
01600           for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
01601             if (Add->getOperand(i) == SymbolicName)
01602               if (FoundIndex == e) {
01603                 FoundIndex = i;
01604                 break;
01605               }
01606 
01607           if (FoundIndex != Add->getNumOperands()) {
01608             // Create an add with everything but the specified operand.
01609             std::vector<SCEVHandle> Ops;
01610             for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
01611               if (i != FoundIndex)
01612                 Ops.push_back(Add->getOperand(i));
01613             SCEVHandle Accum = SE.getAddExpr(Ops);
01614 
01615             // This is not a valid addrec if the step amount is varying each
01616             // loop iteration, but is not itself an addrec in this loop.
01617             if (Accum->isLoopInvariant(L) ||
01618                 (isa<SCEVAddRecExpr>(Accum) &&
01619                  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
01620               SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
01621               SCEVHandle PHISCEV  = SE.getAddRecExpr(StartVal, Accum, L);
01622 
01623               // Okay, for the entire analysis of this edge we assumed the PHI
01624               // to be symbolic.  We now need to go back and update all of the
01625               // entries for the scalars that use the PHI (except for the PHI
01626               // itself) to use the new analyzed value instead of the "symbolic"
01627               // value.
01628               ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
01629               return PHISCEV;
01630             }
01631           }
01632         } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
01633           // Otherwise, this could be a loop like this:
01634           //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
01635           // In this case, j = {1,+,1}  and BEValue is j.
01636           // Because the other in-value of i (0) fits the evolution of BEValue
01637           // i really is an addrec evolution.
01638           if (AddRec->getLoop() == L && AddRec->isAffine()) {
01639             SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
01640 
01641             // If StartVal = j.start - j.stride, we can use StartVal as the
01642             // initial step of the addrec evolution.
01643             if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
01644                                             AddRec->getOperand(1))) {
01645               SCEVHandle PHISCEV = 
01646                  SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
01647 
01648               // Okay, for the entire analysis of this edge we assumed the PHI
01649               // to be symbolic.  We now need to go back and update all of the
01650               // entries for the scalars that use the PHI (except for the PHI
01651               // itself) to use the new analyzed value instead of the "symbolic"
01652               // value.
01653               ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
01654               return PHISCEV;
01655             }
01656           }
01657         }
01658 
01659         return SymbolicName;
01660       }
01661 
01662   // If it's not a loop phi, we can't handle it yet.
01663   return SE.getUnknown(PN);
01664 }
01665 
01666 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
01667 /// guaranteed to end in (at every loop iteration).  It is, at the same time,
01668 /// the minimum number of times S is divisible by 2.  For example, given {4,+,8}
01669 /// it returns 2.  If S is guaranteed to be 0, it returns the bitwidth of S.
01670 static uint32_t GetMinTrailingZeros(SCEVHandle S) {
01671   if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
01672     return C->getValue()->getValue().countTrailingZeros();
01673 
01674   if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
01675     return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
01676 
01677   if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
01678     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
01679     return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
01680   }
01681 
01682   if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
01683     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
01684     return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
01685   }
01686 
01687   if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
01688     // The result is the min of all operands results.
01689     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
01690     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
01691       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
01692     return MinOpRes;
01693   }
01694 
01695   if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
01696     // The result is the sum of all operands results.
01697     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
01698     uint32_t BitWidth = M->getBitWidth();
01699     for (unsigned i = 1, e = M->getNumOperands();
01700          SumOpRes != BitWidth && i != e; ++i)
01701       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
01702                           BitWidth);
01703     return SumOpRes;
01704   }
01705 
01706   if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
01707     // The result is the min of all operands results.
01708     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
01709     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
01710       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
01711     return MinOpRes;
01712   }
01713 
01714   if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
01715     // The result is the min of all operands results.
01716     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
01717     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
01718       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
01719     return MinOpRes;
01720   }
01721 
01722   if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
01723     // The result is the min of all operands results.
01724     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
01725     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
01726       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
01727     return MinOpRes;
01728   }
01729 
01730   // SCEVUDivExpr, SCEVUnknown
01731   return 0;
01732 }
01733 
01734 /// createSCEV - We know that there is no SCEV for the specified value.
01735 /// Analyze the expression.
01736 ///
01737 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
01738   if (!isa<IntegerType>(V->getType()))
01739     return SE.getUnknown(V);
01740     
01741   unsigned Opcode = Instruction::UserOp1;
01742   if (Instruction *I = dyn_cast<Instruction>(V))
01743     Opcode = I->getOpcode();
01744   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
01745     Opcode = CE->getOpcode();
01746   else
01747     return SE.getUnknown(V);
01748 
01749   User *U = cast<User>(V);
01750   switch (Opcode) {
01751   case Instruction::Add:
01752     return SE.getAddExpr(getSCEV(U->getOperand(0)),
01753                          getSCEV(U->getOperand(1)));
01754   case Instruction::Mul:
01755     return SE.getMulExpr(getSCEV(U->getOperand(0)),
01756                          getSCEV(U->getOperand(1)));
01757   case Instruction::UDiv:
01758     return SE.getUDivExpr(getSCEV(U->getOperand(0)),
01759                           getSCEV(U->getOperand(1)));
01760   case Instruction::Sub:
01761     return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
01762                            getSCEV(U->getOperand(1)));
01763   case Instruction::Or:
01764     // If the RHS of the Or is a constant, we may have something like:
01765     // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
01766     // optimizations will transparently handle this case.
01767     //
01768     // In order for this transformation to be safe, the LHS must be of the
01769     // form X*(2^n) and the Or constant must be less than 2^n.
01770     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
01771       SCEVHandle LHS = getSCEV(U->getOperand(0));
01772       const APInt &CIVal = CI->getValue();
01773       if (GetMinTrailingZeros(LHS) >=
01774           (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
01775         return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
01776     }
01777     break;
01778   case Instruction::Xor:
01779     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
01780       // If the RHS of the xor is a signbit, then this is just an add.
01781       // Instcombine turns add of signbit into xor as a strength reduction step.
01782       if (CI->getValue().isSignBit())
01783         return SE.getAddExpr(getSCEV(U->getOperand(0)),
01784                              getSCEV(U->getOperand(1)));
01785 
01786       // If the RHS of xor is -1, then this is a not operation.
01787       else if (CI->isAllOnesValue())
01788         return SE.getNotSCEV(getSCEV(U->getOperand(0)));
01789     }
01790     break;
01791 
01792   case Instruction::Shl:
01793     // Turn shift left of a constant amount into a multiply.
01794     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
01795       uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
01796       Constant *X = ConstantInt::get(
01797         APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
01798       return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
01799     }
01800     break;
01801 
01802   case Instruction::LShr:
01803     // Turn logical shift right of a constant into a unsigned divide.
01804     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
01805       uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
01806       Constant *X = ConstantInt::get(
01807         APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
01808       return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
01809     }
01810     break;
01811 
01812   case Instruction::Trunc:
01813     return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
01814 
01815   case Instruction::ZExt:
01816     return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
01817 
01818   case Instruction::SExt:
01819     return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
01820 
01821   case Instruction::BitCast:
01822     // BitCasts are no-op casts so we just eliminate the cast.
01823     if (U->getType()->isInteger() &&
01824         U->getOperand(0)->getType()->isInteger())
01825       return getSCEV(U->getOperand(0));
01826     break;
01827 
01828   case Instruction::PHI:
01829     return createNodeForPHI(cast<PHINode>(U));
01830 
01831   case Instruction::Select:
01832     // This could be a smax or umax that was lowered earlier.
01833     // Try to recover it.
01834     if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
01835       Value *LHS = ICI->getOperand(0);
01836       Value *RHS = ICI->getOperand(1);
01837       switch (ICI->getPredicate()) {
01838       case ICmpInst::ICMP_SLT:
01839       case ICmpInst::ICMP_SLE:
01840         std::swap(LHS, RHS);
01841         // fall through
01842       case ICmpInst::ICMP_SGT:
01843       case ICmpInst::ICMP_SGE:
01844         if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
01845           return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
01846         else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
01847           // ~smax(~x, ~y) == smin(x, y).
01848           return SE.getNotSCEV(SE.getSMaxExpr(
01849                                    SE.getNotSCEV(getSCEV(LHS)),
01850                                    SE.getNotSCEV(getSCEV(RHS))));
01851         break;
01852       case ICmpInst::ICMP_ULT:
01853       case ICmpInst::ICMP_ULE:
01854         std::swap(LHS, RHS);
01855         // fall through
01856       case ICmpInst::ICMP_UGT:
01857       case ICmpInst::ICMP_UGE:
01858         if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
01859           return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
01860         else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
01861           // ~umax(~x, ~y) == umin(x, y)
01862           return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
01863                                               SE.getNotSCEV(getSCEV(RHS))));
01864         break;
01865       default:
01866         break;
01867       }
01868     }
01869 
01870   default: // We cannot analyze this expression.
01871     break;
01872   }
01873 
01874   return SE.getUnknown(V);
01875 }
01876 
01877 
01878 
01879 //===----------------------------------------------------------------------===//
01880 //                   Iteration Count Computation Code
01881 //
01882 
01883 /// getIterationCount - If the specified loop has a predictable iteration
01884 /// count, return it.  Note that it is not valid to call this method on a
01885 /// loop without a loop-invariant iteration count.
01886 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
01887   std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
01888   if (I == IterationCounts.end()) {
01889     SCEVHandle ItCount = ComputeIterationCount(L);
01890     I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
01891     if (ItCount != UnknownValue) {
01892       assert(ItCount->isLoopInvariant(L) &&
01893              "Computed trip count isn't loop invariant for loop!");
01894       ++NumTripCountsComputed;
01895     } else if (isa<PHINode>(L->getHeader()->begin())) {
01896       // Only count loops that have phi nodes as not being computable.
01897       ++NumTripCountsNotComputed;
01898     }
01899   }
01900   return I->second;
01901 }
01902 
01903 /// ComputeIterationCount - Compute the number of times the specified loop
01904 /// will iterate.
01905 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
01906   // If the loop has a non-one exit block count, we can't analyze it.
01907   SmallVector<BasicBlock*, 8> ExitBlocks;
01908   L->getExitBlocks(ExitBlocks);
01909   if (ExitBlocks.size() != 1) return UnknownValue;
01910 
01911   // Okay, there is one exit block.  Try to find the condition that causes the
01912   // loop to be exited.
01913   BasicBlock *ExitBlock = ExitBlocks[0];
01914 
01915   BasicBlock *ExitingBlock = 0;
01916   for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
01917        PI != E; ++PI)
01918     if (L->contains(*PI)) {
01919       if (ExitingBlock == 0)
01920         ExitingBlock = *PI;
01921       else
01922         return UnknownValue;   // More than one block exiting!
01923     }
01924   assert(ExitingBlock && "No exits from loop, something is broken!");
01925 
01926   // Okay, we've computed the exiting block.  See what condition causes us to
01927   // exit.
01928   //
01929   // FIXME: we should be able to handle switch instructions (with a single exit)
01930   BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
01931   if (ExitBr == 0) return UnknownValue;
01932   assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
01933   
01934   // At this point, we know we have a conditional branch that determines whether
01935   // the loop is exited.  However, we don't know if the branch is executed each
01936   // time through the loop.  If not, then the execution count of the branch will
01937   // not be equal to the trip count of the loop.
01938   //
01939   // Currently we check for this by checking to see if the Exit branch goes to
01940   // the loop header.  If so, we know it will always execute the same number of
01941   // times as the loop.  We also handle the case where the exit block *is* the
01942   // loop header.  This is common for un-rotated loops.  More extensive analysis
01943   // could be done to handle more cases here.
01944   if (ExitBr->getSuccessor(0) != L->getHeader() &&
01945       ExitBr->getSuccessor(1) != L->getHeader() &&
01946       ExitBr->getParent() != L->getHeader())
01947     return UnknownValue;
01948   
01949   ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
01950 
01951   // If it's not an integer comparison then compute it the hard way. 
01952   // Note that ICmpInst deals with pointer comparisons too so we must check
01953   // the type of the operand.
01954   if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
01955     return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
01956                                           ExitBr->getSuccessor(0) == ExitBlock);
01957 
01958   // If the condition was exit on true, convert the condition to exit on false
01959   ICmpInst::Predicate Cond;
01960   if (ExitBr->getSuccessor(1) == ExitBlock)
01961     Cond = ExitCond->getPredicate();
01962   else
01963     Cond = ExitCond->getInversePredicate();
01964 
01965   // Handle common loops like: for (X = "string"; *X; ++X)
01966   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
01967     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
01968       SCEVHandle ItCnt =
01969         ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
01970       if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
01971     }
01972 
01973   SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
01974   SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
01975 
01976   // Try to evaluate any dependencies out of the loop.
01977   SCEVHandle Tmp = getSCEVAtScope(LHS, L);
01978   if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
01979   Tmp = getSCEVAtScope(RHS, L);
01980   if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
01981 
01982   // At this point, we would like to compute how many iterations of the 
01983   // loop the predicate will return true for these inputs.
01984   if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
01985     // If there is a loop-invariant, force it into the RHS.
01986     std::swap(LHS, RHS);
01987     Cond = ICmpInst::getSwappedPredicate(Cond);
01988   }
01989 
01990   // FIXME: think about handling pointer comparisons!  i.e.:
01991   // while (P != P+100) ++P;
01992 
01993   // If we have a comparison of a chrec against a constant, try to use value
01994   // ranges to answer this query.
01995   if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
01996     if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
01997       if (AddRec->getLoop() == L) {
01998         // Form the comparison range using the constant of the correct type so
01999         // that the ConstantRange class knows to do a signed or unsigned
02000         // comparison.
02001         ConstantInt *CompVal = RHSC->getValue();
02002         const Type *RealTy = ExitCond->getOperand(0)->getType();
02003         CompVal = dyn_cast<ConstantInt>(
02004           ConstantExpr::getBitCast(CompVal, RealTy));
02005         if (CompVal) {
02006           // Form the constant range.
02007           ConstantRange CompRange(
02008               ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
02009 
02010           SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
02011           if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
02012         }
02013       }
02014 
02015   switch (Cond) {
02016   case ICmpInst::ICMP_NE: {                     // while (X != Y)
02017     // Convert to: while (X-Y != 0)
02018     SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
02019     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
02020     break;
02021   }
02022   case ICmpInst::ICMP_EQ: {
02023     // Convert to: while (X-Y == 0)           // while (X == Y)
02024     SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
02025     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
02026     break;
02027   }
02028   case ICmpInst::ICMP_SLT: {
02029     SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
02030     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
02031     break;
02032   }
02033   case ICmpInst::ICMP_SGT: {
02034     SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
02035                                      SE.getNotSCEV(RHS), L, true);
02036     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
02037     break;
02038   }
02039   case ICmpInst::ICMP_ULT: {
02040     SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
02041     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
02042     break;
02043   }
02044   case ICmpInst::ICMP_UGT: {
02045     SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
02046                                      SE.getNotSCEV(RHS), L, false);
02047     if (!isa<SCEVCouldNotCompute>(TC)) return TC;
02048     break;
02049   }
02050   default:
02051 #if 0
02052     cerr << "ComputeIterationCount ";
02053     if (ExitCond->getOperand(0)->getType()->isUnsigned())
02054       cerr << "[unsigned] ";
02055     cerr << *LHS << "   "
02056          << Instruction::getOpcodeName(Instruction::ICmp) 
02057          << "   " << *RHS << "\n";
02058 #endif
02059     break;
02060   }
02061   return ComputeIterationCountExhaustively(L, ExitCond,
02062                                        ExitBr->getSuccessor(0) == ExitBlock);
02063 }
02064 
02065 static ConstantInt *
02066 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
02067                                 ScalarEvolution &SE) {
02068   SCEVHandle InVal = SE.getConstant(C);
02069   SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
02070   assert(isa<SCEVConstant>(Val) &&
02071          "Evaluation of SCEV at constant didn't fold correctly?");
02072   return cast<SCEVConstant>(Val)->getValue();
02073 }
02074 
02075 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
02076 /// and a GEP expression (missing the pointer index) indexing into it, return
02077 /// the addressed element of the initializer or null if the index expression is
02078 /// invalid.
02079 static Constant *
02080 GetAddressedElementFromGlobal(GlobalVariable *GV,
02081                               const std::vector<ConstantInt*> &Indices) {
02082   Constant *Init = GV->getInitializer();
02083   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
02084     uint64_t Idx = Indices[i]->getZExtValue();
02085     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
02086       assert(Idx < CS->getNumOperands() && "Bad struct index!");
02087       Init = cast<Constant>(CS->getOperand(Idx));
02088     } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
02089       if (Idx >= CA->getNumOperands()) return 0;  // Bogus program
02090       Init = cast<Constant>(CA->getOperand(Idx));
02091     } else if (isa<ConstantAggregateZero>(Init)) {
02092       if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
02093         assert(Idx < STy->getNumElements() && "Bad struct index!");
02094         Init = Constant::getNullValue(STy->getElementType(Idx));
02095       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
02096         if (Idx >= ATy->getNumElements()) return 0;  // Bogus program
02097         Init = Constant::getNullValue(ATy->getElementType());
02098       } else {
02099         assert(0 && "Unknown constant aggregate type!");
02100       }
02101       return 0;
02102     } else {
02103       return 0; // Unknown initializer type
02104     }
02105   }
02106   return Init;
02107 }
02108 
02109 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
02110 /// 'icmp op load X, cst', try to see if we can compute the trip count.
02111 SCEVHandle ScalarEvolutionsImpl::
02112 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
02113                                          const Loop *L, 
02114                                          ICmpInst::Predicate predicate) {
02115   if (LI->isVolatile()) return UnknownValue;
02116 
02117   // Check to see if the loaded pointer is a getelementptr of a global.
02118   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
02119   if (!GEP) return UnknownValue;
02120 
02121   // Make sure that it is really a constant global we are gepping, with an
02122   // initializer, and make sure the first IDX is really 0.
02123   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
02124   if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
02125       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
02126       !cast<Constant>(GEP->getOperand(1))->isNullValue())
02127     return UnknownValue;
02128 
02129   // Okay, we allow one non-constant index into the GEP instruction.
02130   Value *VarIdx = 0;
02131   std::vector<ConstantInt*> Indexes;
02132   unsigned VarIdxNum = 0;
02133   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
02134     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
02135       Indexes.push_back(CI);
02136     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
02137       if (VarIdx) return UnknownValue;  // Multiple non-constant idx's.
02138       VarIdx = GEP->getOperand(i);
02139       VarIdxNum = i-2;
02140       Indexes.push_back(0);
02141     }
02142 
02143   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
02144   // Check to see if X is a loop variant variable value now.
02145   SCEVHandle Idx = getSCEV(VarIdx);
02146   SCEVHandle Tmp = getSCEVAtScope(Idx, L);
02147   if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
02148 
02149   // We can only recognize very limited forms of loop index expressions, in
02150   // particular, only affine AddRec's like {C1,+,C2}.
02151   SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
02152   if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
02153       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
02154       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
02155     return UnknownValue;
02156 
02157   unsigned MaxSteps = MaxBruteForceIterations;
02158   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
02159     ConstantInt *ItCst =
02160       ConstantInt::get(IdxExpr->getType(), IterationNum);
02161     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
02162 
02163     // Form the GEP offset.
02164     Indexes[VarIdxNum] = Val;
02165 
02166     Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
02167     if (Result == 0) break;  // Cannot compute!
02168 
02169     // Evaluate the condition for this iteration.
02170     Result = ConstantExpr::getICmp(predicate, Result, RHS);
02171     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
02172     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
02173 #if 0
02174       cerr << "\n***\n*** Computed loop count " << *ItCst
02175            << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
02176            << "***\n";
02177 #endif
02178       ++NumArrayLenItCounts;
02179       return SE.getConstant(ItCst);   // Found terminating iteration!
02180     }
02181   }
02182   return UnknownValue;
02183 }
02184 
02185 
02186 /// CanConstantFold - Return true if we can constant fold an instruction of the
02187 /// specified type, assuming that all operands were constants.
02188 static bool CanConstantFold(const Instruction *I) {
02189   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
02190       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
02191     return true;
02192 
02193   if (const CallInst *CI = dyn_cast<CallInst>(I))
02194     if (const Function *F = CI->getCalledFunction())
02195       return canConstantFoldCallTo(F);
02196   return false;
02197 }
02198 
02199 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
02200 /// in the loop that V is derived from.  We allow arbitrary operations along the
02201 /// way, but the operands of an operation must either be constants or a value
02202 /// derived from a constant PHI.  If this expression does not fit with these
02203 /// constraints, return null.
02204 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
02205   // If this is not an instruction, or if this is an instruction outside of the
02206   // loop, it can't be derived from a loop PHI.
02207   Instruction *I = dyn_cast<Instruction>(V);
02208   if (I == 0 || !L->contains(I->getParent())) return 0;
02209 
02210   if (PHINode *PN = dyn_cast<PHINode>(I)) {
02211     if (L->getHeader() == I->getParent())
02212       return PN;
02213     else
02214       // We don't currently keep track of the control flow needed to evaluate
02215       // PHIs, so we cannot handle PHIs inside of loops.
02216       return 0;
02217   }
02218 
02219   // If we won't be able to constant fold this expression even if the operands
02220   // are constants, return early.
02221   if (!CanConstantFold(I)) return 0;
02222 
02223   // Otherwise, we can evaluate this instruction if all of its operands are
02224   // constant or derived from a PHI node themselves.
02225   PHINode *PHI = 0;
02226   for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
02227     if (!(isa<Constant>(I->getOperand(Op)) ||
02228           isa<GlobalValue>(I->getOperand(Op)))) {
02229       PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
02230       if (P == 0) return 0;  // Not evolving from PHI
02231       if (PHI == 0)
02232         PHI = P;
02233       else if (PHI != P)
02234         return 0;  // Evolving from multiple different PHIs.
02235     }
02236 
02237   // This is a expression evolving from a constant PHI!
02238   return PHI;
02239 }
02240 
02241 /// EvaluateExpression - Given an expression that passes the
02242 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
02243 /// in the loop has the value PHIVal.  If we can't fold this expression for some
02244 /// reason, return null.
02245 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
02246   if (isa<PHINode>(V)) return PHIVal;
02247   if (Constant *C = dyn_cast<Constant>(V)) return C;
02248   Instruction *I = cast<Instruction>(V);
02249 
02250   std::vector<Constant*> Operands;
02251   Operands.resize(I->getNumOperands());
02252 
02253   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
02254     Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
02255     if (Operands[i] == 0) return 0;
02256   }
02257 
02258   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
02259     return ConstantFoldCompareInstOperands(CI->getPredicate(),
02260                                            &Operands[0], Operands.size());
02261   else
02262     return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
02263                                     &Operands[0], Operands.size());
02264 }
02265 
02266 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
02267 /// in the header of its containing loop, we know the loop executes a
02268 /// constant number of times, and the PHI node is just a recurrence
02269 /// involving constants, fold it.
02270 Constant *ScalarEvolutionsImpl::
02271 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
02272   std::map<PHINode*, Constant*>::iterator I =
02273     ConstantEvolutionLoopExitValue.find(PN);
02274   if (I != ConstantEvolutionLoopExitValue.end())
02275     return I->second;
02276 
02277   if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
02278     return ConstantEvolutionLoopExitValue[PN] = 0;  // Not going to evaluate it.
02279 
02280   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
02281 
02282   // Since the loop is canonicalized, the PHI node must have two entries.  One
02283   // entry must be a constant (coming in from outside of the loop), and the
02284   // second must be derived from the same PHI.
02285   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
02286   Constant *StartCST =
02287     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
02288   if (StartCST == 0)
02289     return RetVal = 0;  // Must be a constant.
02290 
02291   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
02292   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
02293   if (PN2 != PN)
02294     return RetVal = 0;  // Not derived from same PHI.
02295 
02296   // Execute the loop symbolically to determine the exit value.
02297   if (Its.getActiveBits() >= 32)
02298     return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
02299 
02300   unsigned NumIterations = Its.getZExtValue(); // must be in range
02301   unsigned IterationNum = 0;
02302   for (Constant *PHIVal = StartCST; ; ++IterationNum) {
02303     if (IterationNum == NumIterations)
02304       return RetVal = PHIVal;  // Got exit value!
02305 
02306     // Compute the value of the PHI node for the next iteration.
02307     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
02308     if (NextPHI == PHIVal)
02309       return RetVal = NextPHI;  // Stopped evolving!
02310     if (NextPHI == 0)
02311       return 0;        // Couldn't evaluate!
02312     PHIVal = NextPHI;
02313   }
02314 }
02315 
02316 /// ComputeIterationCountExhaustively - If the trip is known to execute a
02317 /// constant number of times (the condition evolves only from constants),
02318 /// try to evaluate a few iterations of the loop until we get the exit
02319 /// condition gets a value of ExitWhen (true or false).  If we cannot
02320 /// evaluate the trip count of the loop, return UnknownValue.
02321 SCEVHandle ScalarEvolutionsImpl::
02322 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
02323   PHINode *PN = getConstantEvolvingPHI(Cond, L);
02324   if (PN == 0) return UnknownValue;
02325 
02326   // Since the loop is canonicalized, the PHI node must have two entries.  One
02327   // entry must be a constant (coming in from outside of the loop), and the
02328   // second must be derived from the same PHI.
02329   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
02330   Constant *StartCST =
02331     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
02332   if (StartCST == 0) return UnknownValue;  // Must be a constant.
02333 
02334   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
02335   PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
02336   if (PN2 != PN) return UnknownValue;  // Not derived from same PHI.
02337 
02338   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
02339   // the loop symbolically to determine when the condition gets a value of
02340   // "ExitWhen".
02341   unsigned IterationNum = 0;
02342   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
02343   for (Constant *PHIVal = StartCST;
02344        IterationNum != MaxIterations; ++IterationNum) {
02345     ConstantInt *CondVal =
02346       dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
02347 
02348     // Couldn't symbolically evaluate.
02349     if (!CondVal) return UnknownValue;
02350 
02351     if (CondVal->getValue() == uint64_t(ExitWhen)) {
02352       ConstantEvolutionLoopExitValue[PN] = PHIVal;
02353       ++NumBruteForceTripCountsComputed;
02354       return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
02355     }
02356 
02357     // Compute the value of the PHI node for the next iteration.
02358     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
02359     if (NextPHI == 0 || NextPHI == PHIVal)
02360       return UnknownValue;  // Couldn't evaluate or not making progress...
02361     PHIVal = NextPHI;
02362   }
02363 
02364   // Too many iterations were needed to evaluate.
02365   return UnknownValue;
02366 }
02367 
02368 /// getSCEVAtScope - Compute the value of the specified expression within the
02369 /// indicated loop (which may be null to indicate in no loop).  If the
02370 /// expression cannot be evaluated, return UnknownValue.
02371 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
02372   // FIXME: this should be turned into a virtual method on SCEV!
02373 
02374   if (isa<SCEVConstant>(V)) return V;
02375 
02376   // If this instruction is evolved from a constant-evolving PHI, compute the
02377   // exit value from the loop without using SCEVs.
02378   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
02379     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
02380       const Loop *LI = this->LI[I->getParent()];
02381       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
02382         if (PHINode *PN = dyn_cast<PHINode>(I))
02383           if (PN->getParent() == LI->getHeader()) {
02384             // Okay, there is no closed form solution for the PHI node.  Check
02385             // to see if the loop that contains it has a known iteration count.
02386             // If so, we may be able to force computation of the exit value.
02387             SCEVHandle IterationCount = getIterationCount(LI);
02388             if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
02389               // Okay, we know how many times the containing loop executes.  If
02390               // this is a constant evolving PHI node, get the final value at
02391               // the specified iteration number.
02392               Constant *RV = getConstantEvolutionLoopExitValue(PN,
02393                                                     ICC->getValue()->getValue(),
02394                                                                LI);
02395               if (RV) return SE.getUnknown(RV);
02396             }
02397           }
02398 
02399       // Okay, this is an expression that we cannot symbolically evaluate
02400       // into a SCEV.  Check to see if it's possible to symbolically evaluate
02401       // the arguments into constants, and if so, try to constant propagate the
02402       // result.  This is particularly useful for computing loop exit values.
02403       if (CanConstantFold(I)) {
02404         std::vector<Constant*> Operands;
02405         Operands.reserve(I->getNumOperands());
02406         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
02407           Value *Op = I->getOperand(i);
02408           if (Constant *C = dyn_cast<Constant>(Op)) {
02409             Operands.push_back(C);
02410           } else {
02411             // If any of the operands is non-constant and if they are
02412             // non-integer, don't even try to analyze them with scev techniques.
02413             if (!isa<IntegerType>(Op->getType()))
02414               return V;
02415               
02416             SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
02417             if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
02418               Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(), 
02419                                                               Op->getType(), 
02420                                                               false));
02421             else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
02422               if (Constant *C = dyn_cast<Constant>(SU->getValue()))
02423                 Operands.push_back(ConstantExpr::getIntegerCast(C, 
02424                                                                 Op->getType(), 
02425                                                                 false));
02426               else
02427                 return V;
02428             } else {
02429               return V;
02430             }
02431           }
02432         }
02433         
02434         Constant *C;
02435         if (const CmpInst *CI = dyn_cast<CmpInst>(I))
02436           C = ConstantFoldCompareInstOperands(CI->getPredicate(),
02437                                               &Operands[0], Operands.size());
02438         else
02439           C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
02440                                        &Operands[0], Operands.size());
02441         return SE.getUnknown(C);
02442       }
02443     }
02444 
02445     // This is some other type of SCEVUnknown, just return it.
02446     return V;
02447   }
02448 
02449   if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
02450     // Avoid performing the look-up in the common case where the specified
02451     // expression has no loop-variant portions.
02452     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
02453       SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
02454       if (OpAtScope != Comm->getOperand(i)) {
02455         if (OpAtScope == UnknownValue) return UnknownValue;
02456         // Okay, at least one of these operands is loop variant but might be
02457         // foldable.  Build a new instance of the folded commutative expression.
02458         std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
02459         NewOps.push_back(OpAtScope);
02460 
02461         for (++i; i != e; ++i) {
02462           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
02463           if (OpAtScope == UnknownValue) return UnknownValue;
02464           NewOps.push_back(OpAtScope);
02465         }
02466         if (isa<SCEVAddExpr>(Comm))
02467           return SE.getAddExpr(NewOps);
02468         if (isa<SCEVMulExpr>(Comm))
02469           return SE.getMulExpr(NewOps);
02470         if (isa<SCEVSMaxExpr>(Comm))
02471           return SE.getSMaxExpr(NewOps);
02472         if (isa<SCEVUMaxExpr>(Comm))
02473           return SE.getUMaxExpr(NewOps);
02474         assert(0 && "Unknown commutative SCEV type!");
02475       }
02476     }
02477     // If we got here, all operands are loop invariant.
02478     return Comm;
02479   }
02480 
02481   if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
02482     SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
02483     if (LHS == UnknownValue) return LHS;
02484     SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
02485     if (RHS == UnknownValue) return RHS;
02486     if (LHS == Div->getLHS() && RHS == Div->getRHS())
02487       return Div;   // must be loop invariant
02488     return SE.getUDivExpr(LHS, RHS);
02489   }
02490 
02491   // If this is a loop recurrence for a loop that does not contain L, then we
02492   // are dealing with the final value computed by the loop.
02493   if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
02494     if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
02495       // To evaluate this recurrence, we need to know how many times the AddRec
02496       // loop iterates.  Compute this now.
02497       SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
02498       if (IterationCount == UnknownValue) return UnknownValue;
02499 
02500       // Then, evaluate the AddRec.
02501       return AddRec->evaluateAtIteration(IterationCount, SE);
02502     }
02503     return UnknownValue;
02504   }
02505 
02506   //assert(0 && "Unknown SCEV type!");
02507   return UnknownValue;
02508 }
02509 
02510 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
02511 /// following equation:
02512 ///
02513 ///     A * X = B (mod N)
02514 ///
02515 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
02516 /// A and B isn't important.
02517 ///
02518 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
02519 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
02520                                                ScalarEvolution &SE) {
02521   uint32_t BW = A.getBitWidth();
02522   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
02523   assert(A != 0 && "A must be non-zero.");
02524 
02525   // 1. D = gcd(A, N)
02526   //
02527   // The gcd of A and N may have only one prime factor: 2. The number of
02528   // trailing zeros in A is its multiplicity
02529   uint32_t Mult2 = A.countTrailingZeros();
02530   // D = 2^Mult2
02531 
02532   // 2. Check if B is divisible by D.
02533   //
02534   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
02535   // is not less than multiplicity of this prime factor for D.
02536   if (B.countTrailingZeros() < Mult2)
02537     return new SCEVCouldNotCompute();
02538 
02539   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
02540   // modulo (N / D).
02541   //
02542   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
02543   // bit width during computations.
02544   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
02545   APInt Mod(BW + 1, 0);
02546   Mod.set(BW - Mult2);  // Mod = N / D
02547   APInt I = AD.multiplicativeInverse(Mod);
02548 
02549   // 4. Compute the minimum unsigned root of the equation:
02550   // I * (B / D) mod (N / D)
02551   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
02552 
02553   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
02554   // bits.
02555   return SE.getConstant(Result.trunc(BW));
02556 }
02557 
02558 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
02559 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
02560 /// might be the same) or two SCEVCouldNotCompute objects.
02561 ///
02562 static std::pair<SCEVHandle,SCEVHandle>
02563 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
02564   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
02565   SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
02566   SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
02567   SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
02568 
02569   // We currently can only solve this if the coefficients are constants.
02570   if (!LC || !MC || !NC) {
02571     SCEV *CNC = new SCEVCouldNotCompute();
02572     return std::make_pair(CNC, CNC);
02573   }
02574 
02575   uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
02576   const APInt &L = LC->getValue()->getValue();
02577   const APInt &M = MC->getValue()->getValue();
02578   const APInt &N = NC->getValue()->getValue();
02579   APInt Two(BitWidth, 2);
02580   APInt Four(BitWidth, 4);
02581 
02582   { 
02583     using namespace APIntOps;
02584     const APInt& C = L;
02585     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
02586     // The B coefficient is M-N/2
02587     APInt B(M);
02588     B -= sdiv(N,Two);
02589 
02590     // The A coefficient is N/2
02591     APInt A(N.sdiv(Two));
02592 
02593     // Compute the B^2-4ac term.
02594     APInt SqrtTerm(B);
02595     SqrtTerm *= B;
02596     SqrtTerm -= Four * (A * C);
02597 
02598     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
02599     // integer value or else APInt::sqrt() will assert.
02600     APInt SqrtVal(SqrtTerm.sqrt());
02601 
02602     // Compute the two solutions for the quadratic formula. 
02603     // The divisions must be performed as signed divisions.
02604     APInt NegB(-B);
02605     APInt TwoA( A << 1 );
02606     if (TwoA.isMinValue()) {
02607       SCEV *CNC = new SCEVCouldNotCompute();
02608       return std::make_pair(CNC, CNC);
02609     }
02610 
02611     ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
02612     ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
02613 
02614     return std::make_pair(SE.getConstant(Solution1), 
02615                           SE.getConstant(Solution2));
02616     } // end APIntOps namespace
02617 }
02618 
02619 /// HowFarToZero - Return the number of times a backedge comparing the specified
02620 /// value to zero will execute.  If not computable, return UnknownValue
02621 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
02622   // If the value is a constant
02623   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
02624     // If the value is already zero, the branch will execute zero times.
02625     if (C->getValue()->isZero()) return C;
02626     return UnknownValue;  // Otherwise it will loop infinitely.
02627   }
02628 
02629   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
02630   if (!AddRec || AddRec->getLoop() != L)
02631     return UnknownValue;
02632 
02633   if (AddRec->isAffine()) {
02634     // If this is an affine expression, the execution count of this branch is
02635     // the minimum unsigned root of the following equation:
02636     //
02637     //     Start + Step*N = 0 (mod 2^BW)
02638     //
02639     // equivalent to:
02640     //
02641     //             Step*N = -Start (mod 2^BW)
02642     //
02643     // where BW is the common bit width of Start and Step.
02644 
02645     // Get the initial value for the loop.
02646     SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
02647     if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
02648 
02649     SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
02650 
02651     if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
02652       // For now we handle only constant steps.
02653 
02654       // First, handle unitary steps.
02655       if (StepC->getValue()->equalsInt(1))      // 1*N = -Start (mod 2^BW), so:
02656         return SE.getNegativeSCEV(Start);       //   N = -Start (as unsigned)
02657       if (StepC->getValue()->isAllOnesValue())  // -1*N = -Start (mod 2^BW), so:
02658         return Start;                           //    N = Start (as unsigned)
02659 
02660       // Then, try to solve the above equation provided that Start is constant.
02661       if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
02662         return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
02663                                             -StartC->getValue()->getValue(),SE);
02664     }
02665   } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
02666     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
02667     // the quadratic equation to solve it.
02668     std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
02669     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
02670     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
02671     if (R1) {
02672 #if 0
02673       cerr << "HFTZ: " << *V << " - sol#1: " << *R1
02674            << "  sol#2: " << *R2 << "\n";
02675 #endif
02676       // Pick the smallest positive root value.
02677       if (ConstantInt *CB =
02678           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 
02679                                    R1->getValue(), R2->getValue()))) {
02680         if (CB->getZExtValue() == false)
02681           std::swap(R1, R2);   // R1 is the minimum root now.
02682 
02683         // We can only use this value if the chrec ends up with an exact zero
02684         // value at this index.  When solving for "X*X != 5", for example, we
02685         // should not accept a root of 2.
02686         SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
02687         if (Val->isZero())
02688           return R1;  // We found a quadratic root!
02689       }
02690     }
02691   }
02692 
02693   return UnknownValue;
02694 }
02695 
02696 /// HowFarToNonZero - Return the number of times a backedge checking the
02697 /// specified value for nonzero will execute.  If not computable, return
02698 /// UnknownValue
02699 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
02700   // Loops that look like: while (X == 0) are very strange indeed.  We don't
02701   // handle them yet except for the trivial case.  This could be expanded in the
02702   // future as needed.
02703 
02704   // If the value is a constant, check to see if it is known to be non-zero
02705   // already.  If so, the backedge will execute zero times.
02706   if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
02707     if (!C->getValue()->isNullValue())
02708       return SE.getIntegerSCEV(0, C->getType());
02709     return UnknownValue;  // Otherwise it will loop infinitely.
02710   }
02711 
02712   // We could implement others, but I really doubt anyone writes loops like
02713   // this, and if they did, they would already be constant folded.
02714   return UnknownValue;
02715 }
02716 
02717 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
02718 /// (which may not be an immediate predecessor) which has exactly one
02719 /// successor from which BB is reachable, or null if no such block is
02720 /// found.
02721 ///
02722 BasicBlock *
02723 ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
02724   // If the block has a unique predecessor, the predecessor must have
02725   // no other successors from which BB is reachable.
02726   if (BasicBlock *Pred = BB->getSinglePredecessor())
02727     return Pred;
02728 
02729   // A loop's header is defined to be a block that dominates the loop.
02730   // If the loop has a preheader, it must be a block that has exactly
02731   // one successor that can reach BB. This is slightly more strict
02732   // than necessary, but works if critical edges are split.
02733   if (Loop *L = LI.getLoopFor(BB))
02734     return L->getLoopPreheader();
02735 
02736   return 0;
02737 }
02738 
02739 /// executesAtLeastOnce - Test whether entry to the loop is protected by
02740 /// a conditional between LHS and RHS.
02741 bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
02742                                                SCEV *LHS, SCEV *RHS) {
02743   BasicBlock *Preheader = L->getLoopPreheader();
02744   BasicBlock *PreheaderDest = L->getHeader();
02745 
02746   // Starting at the preheader, climb up the predecessor chain, as long as
02747   // there are predecessors that can be found that have unique successors
02748   // leading to the original header.
02749   for (; Preheader;
02750        PreheaderDest = Preheader,
02751        Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
02752 
02753     BranchInst *LoopEntryPredicate =
02754       dyn_cast<BranchInst>(Preheader->getTerminator());
02755     if (!LoopEntryPredicate ||
02756         LoopEntryPredicate->isUnconditional())
02757       continue;
02758 
02759     ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
02760     if (!ICI) continue;
02761 
02762     // Now that we found a conditional branch that dominates the loop, check to
02763     // see if it is the comparison we are looking for.
02764     Value *PreCondLHS = ICI->getOperand(0);
02765     Value *PreCondRHS = ICI->getOperand(1);
02766     ICmpInst::Predicate Cond;
02767     if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
02768       Cond = ICI->getPredicate();
02769     else
02770       Cond = ICI->getInversePredicate();
02771 
02772     switch (Cond) {
02773     case ICmpInst::ICMP_UGT:
02774       if (isSigned) continue;
02775       std::swap(PreCondLHS, PreCondRHS);
02776       Cond = ICmpInst::ICMP_ULT;
02777       break;
02778     case ICmpInst::ICMP_SGT:
02779       if (!isSigned) continue;
02780       std::swap(PreCondLHS, PreCondRHS);
02781       Cond = ICmpInst::ICMP_SLT;
02782       break;
02783     case ICmpInst::ICMP_ULT:
02784       if (isSigned) continue;
02785       break;
02786     case ICmpInst::ICMP_SLT:
02787       if (!isSigned) continue;
02788       break;
02789     default:
02790       continue;
02791     }
02792 
02793     if (!PreCondLHS->getType()->isInteger()) continue;
02794 
02795     SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
02796     SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
02797     if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
02798         (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
02799          RHS == SE.getNotSCEV(PreCondLHSSCEV)))
02800       return true;
02801   }
02802 
02803   return false;
02804 }
02805 
02806 /// HowManyLessThans - Return the number of times a backedge containing the
02807 /// specified less-than comparison will execute.  If not computable, return
02808 /// UnknownValue.
02809 SCEVHandle ScalarEvolutionsImpl::
02810 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
02811   // Only handle:  "ADDREC < LoopInvariant".
02812   if (!RHS->isLoopInvariant(L)) return UnknownValue;
02813 
02814   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
02815   if (!AddRec || AddRec->getLoop() != L)
02816     return UnknownValue;
02817 
02818   if (AddRec->isAffine()) {
02819     // FORNOW: We only support unit strides.
02820     SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
02821     if (AddRec->getOperand(1) != One)
02822       return UnknownValue;
02823 
02824     // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
02825     // m.  So, we count the number of iterations in which {n,+,1} < m is true.
02826     // Note that we cannot simply return max(m-n,0) because it's not safe to
02827     // treat m-n as signed nor unsigned due to overflow possibility.
02828 
02829     // First, we get the value of the LHS in the first iteration: n
02830     SCEVHandle Start = AddRec->getOperand(0);
02831 
02832     if (executesAtLeastOnce(L, isSigned,
02833                             SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
02834       // Since we know that the condition is true in order to enter the loop,
02835       // we know that it will run exactly m-n times.
02836       return SE.getMinusSCEV(RHS, Start);
02837     } else {
02838       // Then, we get the value of the LHS in the first iteration in which the
02839       // above condition doesn't hold.  This equals to max(m,n).
02840       SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
02841                                 : SE.getUMaxExpr(RHS, Start);
02842 
02843       // Finally, we subtract these two values to get the number of times the
02844       // backedge is executed: max(m,n)-n.
02845       return SE.getMinusSCEV(End, Start);
02846     }
02847   }
02848 
02849   return UnknownValue;
02850 }
02851 
02852 /// getNumIterationsInRange - Return the number of iterations of this loop that
02853 /// produce values in the specified constant range.  Another way of looking at
02854 /// this is that it returns the first iteration number where the value is not in
02855 /// the condition, thus computing the exit count. If the iteration count can't
02856 /// be computed, an instance of SCEVCouldNotCompute is returned.
02857 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
02858                                                    ScalarEvolution &SE) const {
02859   if (Range.isFullSet())  // Infinite loop.
02860     return new SCEVCouldNotCompute();
02861 
02862   // If the start is a non-zero constant, shift the range to simplify things.
02863   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
02864     if (!SC->getValue()->isZero()) {
02865       std::vector<SCEVHandle> Operands(op_begin(), op_end());
02866       Operands[0] = SE.getIntegerSCEV(0, SC->getType());
02867       SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
02868       if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
02869         return ShiftedAddRec->getNumIterationsInRange(
02870                            Range.subtract(SC->getValue()->getValue()), SE);
02871       // This is strange and shouldn't happen.
02872       return new SCEVCouldNotCompute();
02873     }
02874 
02875   // The only time we can solve this is when we have all constant indices.
02876   // Otherwise, we cannot determine the overflow conditions.
02877   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
02878     if (!isa<SCEVConstant>(getOperand(i)))
02879       return new SCEVCouldNotCompute();
02880 
02881 
02882   // Okay at this point we know that all elements of the chrec are constants and
02883   // that the start element is zero.
02884 
02885   // First check to see if the range contains zero.  If not, the first
02886   // iteration exits.
02887   if (!Range.contains(APInt(getBitWidth(),0))) 
02888     return SE.getConstant(ConstantInt::get(getType(),0));
02889 
02890   if (isAffine()) {
02891     // If this is an affine expression then we have this situation:
02892     //   Solve {0,+,A} in Range  ===  Ax in Range
02893 
02894     // We know that zero is in the range.  If A is positive then we know that
02895     // the upper value of the range must be the first possible exit value.
02896     // If A is negative then the lower of the range is the last possible loop
02897     // value.  Also note that we already checked for a full range.
02898     APInt One(getBitWidth(),1);
02899     APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
02900     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
02901 
02902     // The exit value should be (End+A)/A.
02903     APInt ExitVal = (End + A).udiv(A);
02904     ConstantInt *ExitValue = ConstantInt::get(ExitVal);
02905 
02906     // Evaluate at the exit value.  If we really did fall out of the valid
02907     // range, then we computed our trip count, otherwise wrap around or other
02908     // things must have happened.
02909     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
02910     if (Range.contains(Val->getValue()))
02911       return new SCEVCouldNotCompute();  // Something strange happened
02912 
02913     // Ensure that the previous value is in the range.  This is a sanity check.
02914     assert(Range.contains(
02915            EvaluateConstantChrecAtConstant(this, 
02916            ConstantInt::get(ExitVal - One), SE)->getValue()) &&
02917            "Linear scev computation is off in a bad way!");
02918     return SE.getConstant(ExitValue);
02919   } else if (isQuadratic()) {
02920     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
02921     // quadratic equation to solve it.  To do this, we must frame our problem in
02922     // terms of figuring out when zero is crossed, instead of when
02923     // Range.getUpper() is crossed.
02924     std::vector<SCEVHandle> NewOps(op_begin(), op_end());
02925     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
02926     SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
02927 
02928     // Next, solve the constructed addrec
02929     std::pair<SCEVHandle,SCEVHandle> Roots =
02930       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
02931     SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
02932     SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
02933     if (R1) {
02934       // Pick the smallest positive root value.
02935       if (ConstantInt *CB =
02936           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 
02937                                    R1->getValue(), R2->getValue()))) {
02938         if (CB->getZExtValue() == false)
02939           std::swap(R1, R2);   // R1 is the minimum root now.
02940 
02941         // Make sure the root is not off by one.  The returned iteration should
02942         // not be in the range, but the previous one should be.  When solving
02943         // for "X*X < 5", for example, we should not return a root of 2.
02944         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
02945                                                              R1->getValue(),
02946                                                              SE);
02947         if (Range.contains(R1Val->getValue())) {
02948           // The next iteration must be out of the range...
02949           ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
02950 
02951           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
02952           if (!Range.contains(R1Val->getValue()))
02953             return SE.getConstant(NextVal);
02954           return new SCEVCouldNotCompute();  // Something strange happened
02955         }
02956 
02957         // If R1 was not in the range, then it is a good return value.  Make
02958         // sure that R1-1 WAS in the range though, just in case.
02959         ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
02960         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
02961         if (Range.contains(R1Val->getValue()))
02962           return R1;
02963         return new SCEVCouldNotCompute();  // Something strange happened
02964       }
02965     }
02966   }
02967 
02968   return new SCEVCouldNotCompute();
02969 }
02970 
02971 
02972 
02973 //===----------------------------------------------------------------------===//
02974 //                   ScalarEvolution Class Implementation
02975 //===----------------------------------------------------------------------===//
02976 
02977 bool ScalarEvolution::runOnFunction(Function &F) {
02978   Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
02979   return false;
02980 }
02981 
02982 void ScalarEvolution::releaseMemory() {
02983   delete (ScalarEvolutionsImpl*)Impl;
02984   Impl = 0;
02985 }
02986 
02987 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
02988   AU.setPreservesAll();
02989   AU.addRequiredTransitive<LoopInfo>();
02990 }
02991 
02992 SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
02993   return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
02994 }
02995 
02996 /// hasSCEV - Return true if the SCEV for this value has already been
02997 /// computed.
02998 bool ScalarEvolution::hasSCEV(Value *V) const {
02999   return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
03000 }
03001 
03002 
03003 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
03004 /// the specified value.
03005 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
03006   ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
03007 }
03008 
03009 
03010 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
03011   return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
03012 }
03013 
03014 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
03015   return !isa<SCEVCouldNotCompute>(getIterationCount(L));
03016 }
03017 
03018 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
03019   return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
03020 }
03021 
03022 void ScalarEvolution::deleteValueFromRecords(Value *V) const {
03023   return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
03024 }
03025 
03026 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
03027                           const Loop *L) {
03028   // Print all inner loops first
03029   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
03030     PrintLoopInfo(OS, SE, *I);
03031 
03032   OS << "Loop " << L->getHeader()->getName() << ": ";
03033 
03034   SmallVector<BasicBlock*, 8> ExitBlocks;
03035   L->getExitBlocks(ExitBlocks);
03036   if (ExitBlocks.size() != 1)
03037     OS << "<multiple exits> ";
03038 
03039   if (SE->hasLoopInvariantIterationCount(L)) {
03040     OS << *SE->getIterationCount(L) << " iterations! ";
03041   } else {
03042     OS << "Unpredictable iteration count. ";
03043   }
03044 
03045   OS << "\n";
03046 }
03047 
03048 void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
03049   Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
03050   LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
03051 
03052   OS << "Classifying expressions for: " << F.getName() << "\n";
03053   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
03054     if (I->getType()->isInteger()) {
03055       OS << *I;
03056       OS << "  -->  ";
03057       SCEVHandle SV = getSCEV(&*I);
03058       SV->print(OS);
03059       OS << "\t\t";
03060 
03061       if (const Loop *L = LI.getLoopFor((*I).getParent())) {
03062         OS << "Exits: ";
03063         SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
03064         if (isa<SCEVCouldNotCompute>(ExitValue)) {
03065           OS << "<<Unknown>>";
03066         } else {
03067           OS << *ExitValue;
03068         }
03069       }
03070 
03071 
03072       OS << "\n";
03073     }
03074 
03075   OS << "Determining loop execution counts for: " << F.getName() << "\n";
03076   for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
03077     PrintLoopInfo(OS, this, *I);
03078 }