LLVM API Documentation
00001 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file was developed by the LLVM research group and is distributed under 00006 // the University of Illinois Open Source 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 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 00063 #include "llvm/Constants.h" 00064 #include "llvm/DerivedTypes.h" 00065 #include "llvm/GlobalVariable.h" 00066 #include "llvm/Instructions.h" 00067 #include "llvm/Analysis/ConstantFolding.h" 00068 #include "llvm/Analysis/LoopInfo.h" 00069 #include "llvm/Assembly/Writer.h" 00070 #include "llvm/Transforms/Scalar.h" 00071 #include "llvm/Support/CFG.h" 00072 #include "llvm/Support/CommandLine.h" 00073 #include "llvm/Support/ConstantRange.h" 00074 #include "llvm/Support/InstIterator.h" 00075 #include "llvm/Support/Visibility.h" 00076 #include "llvm/ADT/Statistic.h" 00077 #include <cmath> 00078 #include <iostream> 00079 #include <algorithm> 00080 using namespace llvm; 00081 00082 namespace { 00083 RegisterAnalysis<ScalarEvolution> 00084 R("scalar-evolution", "Scalar Evolution Analysis"); 00085 00086 Statistic<> 00087 NumBruteForceEvaluations("scalar-evolution", 00088 "Number of brute force evaluations needed to " 00089 "calculate high-order polynomial exit values"); 00090 Statistic<> 00091 NumArrayLenItCounts("scalar-evolution", 00092 "Number of trip counts computed with array length"); 00093 Statistic<> 00094 NumTripCountsComputed("scalar-evolution", 00095 "Number of loops with predictable loop counts"); 00096 Statistic<> 00097 NumTripCountsNotComputed("scalar-evolution", 00098 "Number of loops without predictable loop counts"); 00099 Statistic<> 00100 NumBruteForceTripCountsComputed("scalar-evolution", 00101 "Number of loops with trip counts computed by force"); 00102 00103 cl::opt<unsigned> 00104 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 00105 cl::desc("Maximum number of iterations SCEV will " 00106 "symbolically execute a constant derived loop"), 00107 cl::init(100)); 00108 } 00109 00110 //===----------------------------------------------------------------------===// 00111 // SCEV class definitions 00112 //===----------------------------------------------------------------------===// 00113 00114 //===----------------------------------------------------------------------===// 00115 // Implementation of the SCEV class. 00116 // 00117 SCEV::~SCEV() {} 00118 void SCEV::dump() const { 00119 print(std::cerr); 00120 } 00121 00122 /// getValueRange - Return the tightest constant bounds that this value is 00123 /// known to have. This method is only valid on integer SCEV objects. 00124 ConstantRange SCEV::getValueRange() const { 00125 const Type *Ty = getType(); 00126 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!"); 00127 Ty = Ty->getUnsignedVersion(); 00128 // Default to a full range if no better information is available. 00129 return ConstantRange(getType()); 00130 } 00131 00132 00133 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {} 00134 00135 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const { 00136 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 00137 return false; 00138 } 00139 00140 const Type *SCEVCouldNotCompute::getType() const { 00141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 00142 return 0; 00143 } 00144 00145 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const { 00146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 00147 return false; 00148 } 00149 00150 SCEVHandle SCEVCouldNotCompute:: 00151 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 00152 const SCEVHandle &Conc) const { 00153 return this; 00154 } 00155 00156 void SCEVCouldNotCompute::print(std::ostream &OS) const { 00157 OS << "***COULDNOTCOMPUTE***"; 00158 } 00159 00160 bool SCEVCouldNotCompute::classof(const SCEV *S) { 00161 return S->getSCEVType() == scCouldNotCompute; 00162 } 00163 00164 00165 // SCEVConstants - Only allow the creation of one SCEVConstant for any 00166 // particular value. Don't use a SCEVHandle here, or else the object will 00167 // never be deleted! 00168 static std::map<ConstantInt*, SCEVConstant*> SCEVConstants; 00169 00170 00171 SCEVConstant::~SCEVConstant() { 00172 SCEVConstants.erase(V); 00173 } 00174 00175 SCEVHandle SCEVConstant::get(ConstantInt *V) { 00176 // Make sure that SCEVConstant instances are all unsigned. 00177 if (V->getType()->isSigned()) { 00178 const Type *NewTy = V->getType()->getUnsignedVersion(); 00179 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy)); 00180 } 00181 00182 SCEVConstant *&R = SCEVConstants[V]; 00183 if (R == 0) R = new SCEVConstant(V); 00184 return R; 00185 } 00186 00187 ConstantRange SCEVConstant::getValueRange() const { 00188 return ConstantRange(V); 00189 } 00190 00191 const Type *SCEVConstant::getType() const { return V->getType(); } 00192 00193 void SCEVConstant::print(std::ostream &OS) const { 00194 WriteAsOperand(OS, V, false); 00195 } 00196 00197 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any 00198 // particular input. Don't use a SCEVHandle here, or else the object will 00199 // never be deleted! 00200 static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates; 00201 00202 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty) 00203 : SCEV(scTruncate), Op(op), Ty(ty) { 00204 assert(Op->getType()->isInteger() && Ty->isInteger() && 00205 Ty->isUnsigned() && 00206 "Cannot truncate non-integer value!"); 00207 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() && 00208 "This is not a truncating conversion!"); 00209 } 00210 00211 SCEVTruncateExpr::~SCEVTruncateExpr() { 00212 SCEVTruncates.erase(std::make_pair(Op, Ty)); 00213 } 00214 00215 ConstantRange SCEVTruncateExpr::getValueRange() const { 00216 return getOperand()->getValueRange().truncate(getType()); 00217 } 00218 00219 void SCEVTruncateExpr::print(std::ostream &OS) const { 00220 OS << "(truncate " << *Op << " to " << *Ty << ")"; 00221 } 00222 00223 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any 00224 // particular input. Don't use a SCEVHandle here, or else the object will never 00225 // be deleted! 00226 static std::map<std::pair<SCEV*, const Type*>, 00227 SCEVZeroExtendExpr*> SCEVZeroExtends; 00228 00229 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty) 00230 : SCEV(scTruncate), Op(op), Ty(ty) { 00231 assert(Op->getType()->isInteger() && Ty->isInteger() && 00232 Ty->isUnsigned() && 00233 "Cannot zero extend non-integer value!"); 00234 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() && 00235 "This is not an extending conversion!"); 00236 } 00237 00238 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() { 00239 SCEVZeroExtends.erase(std::make_pair(Op, Ty)); 00240 } 00241 00242 ConstantRange SCEVZeroExtendExpr::getValueRange() const { 00243 return getOperand()->getValueRange().zeroExtend(getType()); 00244 } 00245 00246 void SCEVZeroExtendExpr::print(std::ostream &OS) const { 00247 OS << "(zeroextend " << *Op << " to " << *Ty << ")"; 00248 } 00249 00250 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any 00251 // particular input. Don't use a SCEVHandle here, or else the object will never 00252 // be deleted! 00253 static std::map<std::pair<unsigned, std::vector<SCEV*> >, 00254 SCEVCommutativeExpr*> SCEVCommExprs; 00255 00256 SCEVCommutativeExpr::~SCEVCommutativeExpr() { 00257 SCEVCommExprs.erase(std::make_pair(getSCEVType(), 00258 std::vector<SCEV*>(Operands.begin(), 00259 Operands.end()))); 00260 } 00261 00262 void SCEVCommutativeExpr::print(std::ostream &OS) const { 00263 assert(Operands.size() > 1 && "This plus expr shouldn't exist!"); 00264 const char *OpStr = getOperationStr(); 00265 OS << "(" << *Operands[0]; 00266 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 00267 OS << OpStr << *Operands[i]; 00268 OS << ")"; 00269 } 00270 00271 SCEVHandle SCEVCommutativeExpr:: 00272 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 00273 const SCEVHandle &Conc) const { 00274 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 00275 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc); 00276 if (H != getOperand(i)) { 00277 std::vector<SCEVHandle> NewOps; 00278 NewOps.reserve(getNumOperands()); 00279 for (unsigned j = 0; j != i; ++j) 00280 NewOps.push_back(getOperand(j)); 00281 NewOps.push_back(H); 00282 for (++i; i != e; ++i) 00283 NewOps.push_back(getOperand(i)-> 00284 replaceSymbolicValuesWithConcrete(Sym, Conc)); 00285 00286 if (isa<SCEVAddExpr>(this)) 00287 return SCEVAddExpr::get(NewOps); 00288 else if (isa<SCEVMulExpr>(this)) 00289 return SCEVMulExpr::get(NewOps); 00290 else 00291 assert(0 && "Unknown commutative expr!"); 00292 } 00293 } 00294 return this; 00295 } 00296 00297 00298 // SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular 00299 // input. Don't use a SCEVHandle here, or else the object will never be 00300 // deleted! 00301 static std::map<std::pair<SCEV*, SCEV*>, SCEVSDivExpr*> SCEVSDivs; 00302 00303 SCEVSDivExpr::~SCEVSDivExpr() { 00304 SCEVSDivs.erase(std::make_pair(LHS, RHS)); 00305 } 00306 00307 void SCEVSDivExpr::print(std::ostream &OS) const { 00308 OS << "(" << *LHS << " /s " << *RHS << ")"; 00309 } 00310 00311 const Type *SCEVSDivExpr::getType() const { 00312 const Type *Ty = LHS->getType(); 00313 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion(); 00314 return Ty; 00315 } 00316 00317 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any 00318 // particular input. Don't use a SCEVHandle here, or else the object will never 00319 // be deleted! 00320 static std::map<std::pair<const Loop *, std::vector<SCEV*> >, 00321 SCEVAddRecExpr*> SCEVAddRecExprs; 00322 00323 SCEVAddRecExpr::~SCEVAddRecExpr() { 00324 SCEVAddRecExprs.erase(std::make_pair(L, 00325 std::vector<SCEV*>(Operands.begin(), 00326 Operands.end()))); 00327 } 00328 00329 SCEVHandle SCEVAddRecExpr:: 00330 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 00331 const SCEVHandle &Conc) const { 00332 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 00333 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc); 00334 if (H != getOperand(i)) { 00335 std::vector<SCEVHandle> NewOps; 00336 NewOps.reserve(getNumOperands()); 00337 for (unsigned j = 0; j != i; ++j) 00338 NewOps.push_back(getOperand(j)); 00339 NewOps.push_back(H); 00340 for (++i; i != e; ++i) 00341 NewOps.push_back(getOperand(i)-> 00342 replaceSymbolicValuesWithConcrete(Sym, Conc)); 00343 00344 return get(NewOps, L); 00345 } 00346 } 00347 return this; 00348 } 00349 00350 00351 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const { 00352 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't 00353 // contain L and if the start is invariant. 00354 return !QueryLoop->contains(L->getHeader()) && 00355 getOperand(0)->isLoopInvariant(QueryLoop); 00356 } 00357 00358 00359 void SCEVAddRecExpr::print(std::ostream &OS) const { 00360 OS << "{" << *Operands[0]; 00361 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 00362 OS << ",+," << *Operands[i]; 00363 OS << "}<" << L->getHeader()->getName() + ">"; 00364 } 00365 00366 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular 00367 // value. Don't use a SCEVHandle here, or else the object will never be 00368 // deleted! 00369 static std::map<Value*, SCEVUnknown*> SCEVUnknowns; 00370 00371 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); } 00372 00373 bool SCEVUnknown::isLoopInvariant(const Loop *L) const { 00374 // All non-instruction values are loop invariant. All instructions are loop 00375 // invariant if they are not contained in the specified loop. 00376 if (Instruction *I = dyn_cast<Instruction>(V)) 00377 return !L->contains(I->getParent()); 00378 return true; 00379 } 00380 00381 const Type *SCEVUnknown::getType() const { 00382 return V->getType(); 00383 } 00384 00385 void SCEVUnknown::print(std::ostream &OS) const { 00386 WriteAsOperand(OS, V, false); 00387 } 00388 00389 //===----------------------------------------------------------------------===// 00390 // SCEV Utilities 00391 //===----------------------------------------------------------------------===// 00392 00393 namespace { 00394 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less 00395 /// than the complexity of the RHS. This comparator is used to canonicalize 00396 /// expressions. 00397 struct VISIBILITY_HIDDEN SCEVComplexityCompare { 00398 bool operator()(SCEV *LHS, SCEV *RHS) { 00399 return LHS->getSCEVType() < RHS->getSCEVType(); 00400 } 00401 }; 00402 } 00403 00404 /// GroupByComplexity - Given a list of SCEV objects, order them by their 00405 /// complexity, and group objects of the same complexity together by value. 00406 /// When this routine is finished, we know that any duplicates in the vector are 00407 /// consecutive and that complexity is monotonically increasing. 00408 /// 00409 /// Note that we go take special precautions to ensure that we get determinstic 00410 /// results from this routine. In other words, we don't want the results of 00411 /// this to depend on where the addresses of various SCEV objects happened to 00412 /// land in memory. 00413 /// 00414 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) { 00415 if (Ops.size() < 2) return; // Noop 00416 if (Ops.size() == 2) { 00417 // This is the common case, which also happens to be trivially simple. 00418 // Special case it. 00419 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType()) 00420 std::swap(Ops[0], Ops[1]); 00421 return; 00422 } 00423 00424 // Do the rough sort by complexity. 00425 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare()); 00426 00427 // Now that we are sorted by complexity, group elements of the same 00428 // complexity. Note that this is, at worst, N^2, but the vector is likely to 00429 // be extremely short in practice. Note that we take this approach because we 00430 // do not want to depend on the addresses of the objects we are grouping. 00431 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 00432 SCEV *S = Ops[i]; 00433 unsigned Complexity = S->getSCEVType(); 00434 00435 // If there are any objects of the same complexity and same value as this 00436 // one, group them. 00437 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 00438 if (Ops[j] == S) { // Found a duplicate. 00439 // Move it to immediately after i'th element. 00440 std::swap(Ops[i+1], Ops[j]); 00441 ++i; // no need to rescan it. 00442 if (i == e-2) return; // Done! 00443 } 00444 } 00445 } 00446 } 00447 00448 00449 00450 //===----------------------------------------------------------------------===// 00451 // Simple SCEV method implementations 00452 //===----------------------------------------------------------------------===// 00453 00454 /// getIntegerSCEV - Given an integer or FP type, create a constant for the 00455 /// specified signed integer value and return a SCEV for the constant. 00456 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) { 00457 Constant *C; 00458 if (Val == 0) 00459 C = Constant::getNullValue(Ty); 00460 else if (Ty->isFloatingPoint()) 00461 C = ConstantFP::get(Ty, Val); 00462 else if (Ty->isSigned()) 00463 C = ConstantSInt::get(Ty, Val); 00464 else { 00465 C = ConstantSInt::get(Ty->getSignedVersion(), Val); 00466 C = ConstantExpr::getCast(C, Ty); 00467 } 00468 return SCEVUnknown::get(C); 00469 } 00470 00471 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the 00472 /// input value to the specified type. If the type must be extended, it is zero 00473 /// extended. 00474 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) { 00475 const Type *SrcTy = V->getType(); 00476 assert(SrcTy->isInteger() && Ty->isInteger() && 00477 "Cannot truncate or zero extend with non-integer arguments!"); 00478 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize()) 00479 return V; // No conversion 00480 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize()) 00481 return SCEVTruncateExpr::get(V, Ty); 00482 return SCEVZeroExtendExpr::get(V, Ty); 00483 } 00484 00485 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V 00486 /// 00487 SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) { 00488 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 00489 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue())); 00490 00491 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType())); 00492 } 00493 00494 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS. 00495 /// 00496 SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) { 00497 // X - Y --> X + -Y 00498 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS)); 00499 } 00500 00501 00502 /// PartialFact - Compute V!/(V-NumSteps)! 00503 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) { 00504 // Handle this case efficiently, it is common to have constant iteration 00505 // counts while computing loop exit values. 00506 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) { 00507 uint64_t Val = SC->getValue()->getRawValue(); 00508 uint64_t Result = 1; 00509 for (; NumSteps; --NumSteps) 00510 Result *= Val-(NumSteps-1); 00511 Constant *Res = ConstantUInt::get(Type::ULongTy, Result); 00512 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType())); 00513 } 00514 00515 const Type *Ty = V->getType(); 00516 if (NumSteps == 0) 00517 return SCEVUnknown::getIntegerSCEV(1, Ty); 00518 00519 SCEVHandle Result = V; 00520 for (unsigned i = 1; i != NumSteps; ++i) 00521 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V, 00522 SCEVUnknown::getIntegerSCEV(i, Ty))); 00523 return Result; 00524 } 00525 00526 00527 /// evaluateAtIteration - Return the value of this chain of recurrences at 00528 /// the specified iteration number. We can evaluate this recurrence by 00529 /// multiplying each element in the chain by the binomial coefficient 00530 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: 00531 /// 00532 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3) 00533 /// 00534 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow. 00535 /// Is the binomial equation safe using modular arithmetic?? 00536 /// 00537 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const { 00538 SCEVHandle Result = getStart(); 00539 int Divisor = 1; 00540 const Type *Ty = It->getType(); 00541 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 00542 SCEVHandle BC = PartialFact(It, i); 00543 Divisor *= i; 00544 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)), 00545 SCEVUnknown::getIntegerSCEV(Divisor,Ty)); 00546 Result = SCEVAddExpr::get(Result, Val); 00547 } 00548 return Result; 00549 } 00550 00551 00552 //===----------------------------------------------------------------------===// 00553 // SCEV Expression folder implementations 00554 //===----------------------------------------------------------------------===// 00555 00556 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) { 00557 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 00558 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty)); 00559 00560 // If the input value is a chrec scev made out of constants, truncate 00561 // all of the constants. 00562 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 00563 std::vector<SCEVHandle> Operands; 00564 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 00565 // FIXME: This should allow truncation of other expression types! 00566 if (isa<SCEVConstant>(AddRec->getOperand(i))) 00567 Operands.push_back(get(AddRec->getOperand(i), Ty)); 00568 else 00569 break; 00570 if (Operands.size() == AddRec->getNumOperands()) 00571 return SCEVAddRecExpr::get(Operands, AddRec->getLoop()); 00572 } 00573 00574 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)]; 00575 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty); 00576 return Result; 00577 } 00578 00579 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) { 00580 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 00581 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty)); 00582 00583 // FIXME: If the input value is a chrec scev, and we can prove that the value 00584 // did not overflow the old, smaller, value, we can zero extend all of the 00585 // operands (often constants). This would allow analysis of something like 00586 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 00587 00588 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)]; 00589 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty); 00590 return Result; 00591 } 00592 00593 // get - Get a canonical add expression, or something simpler if possible. 00594 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) { 00595 assert(!Ops.empty() && "Cannot get empty add!"); 00596 if (Ops.size() == 1) return Ops[0]; 00597 00598 // Sort by complexity, this groups all similar expression types together. 00599 GroupByComplexity(Ops); 00600 00601 // If there are any constants, fold them together. 00602 unsigned Idx = 0; 00603 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 00604 ++Idx; 00605 assert(Idx < Ops.size()); 00606 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 00607 // We found two constants, fold them together! 00608 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue()); 00609 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) { 00610 Ops[0] = SCEVConstant::get(CI); 00611 Ops.erase(Ops.begin()+1); // Erase the folded element 00612 if (Ops.size() == 1) return Ops[0]; 00613 LHSC = cast<SCEVConstant>(Ops[0]); 00614 } else { 00615 // If we couldn't fold the expression, move to the next constant. Note 00616 // that this is impossible to happen in practice because we always 00617 // constant fold constant ints to constant ints. 00618 ++Idx; 00619 } 00620 } 00621 00622 // If we are left with a constant zero being added, strip it off. 00623 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) { 00624 Ops.erase(Ops.begin()); 00625 --Idx; 00626 } 00627 } 00628 00629 if (Ops.size() == 1) return Ops[0]; 00630 00631 // Okay, check to see if the same value occurs in the operand list twice. If 00632 // so, merge them together into an multiply expression. Since we sorted the 00633 // list, these values are required to be adjacent. 00634 const Type *Ty = Ops[0]->getType(); 00635 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 00636 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 00637 // Found a match, merge the two values into a multiply, and add any 00638 // remaining values to the result. 00639 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty); 00640 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two); 00641 if (Ops.size() == 2) 00642 return Mul; 00643 Ops.erase(Ops.begin()+i, Ops.begin()+i+2); 00644 Ops.push_back(Mul); 00645 return SCEVAddExpr::get(Ops); 00646 } 00647 00648 // Okay, now we know the first non-constant operand. If there are add 00649 // operands they would be next. 00650 if (Idx < Ops.size()) { 00651 bool DeletedAdd = false; 00652 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 00653 // If we have an add, expand the add operands onto the end of the operands 00654 // list. 00655 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end()); 00656 Ops.erase(Ops.begin()+Idx); 00657 DeletedAdd = true; 00658 } 00659 00660 // If we deleted at least one add, we added operands to the end of the list, 00661 // and they are not necessarily sorted. Recurse to resort and resimplify 00662 // any operands we just aquired. 00663 if (DeletedAdd) 00664 return get(Ops); 00665 } 00666 00667 // Skip over the add expression until we get to a multiply. 00668 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 00669 ++Idx; 00670 00671 // If we are adding something to a multiply expression, make sure the 00672 // something is not already an operand of the multiply. If so, merge it into 00673 // the multiply. 00674 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 00675 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 00676 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 00677 SCEV *MulOpSCEV = Mul->getOperand(MulOp); 00678 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 00679 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) { 00680 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 00681 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0); 00682 if (Mul->getNumOperands() != 2) { 00683 // If the multiply has more than two operands, we must get the 00684 // Y*Z term. 00685 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); 00686 MulOps.erase(MulOps.begin()+MulOp); 00687 InnerMul = SCEVMulExpr::get(MulOps); 00688 } 00689 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty); 00690 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One); 00691 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]); 00692 if (Ops.size() == 2) return OuterMul; 00693 if (AddOp < Idx) { 00694 Ops.erase(Ops.begin()+AddOp); 00695 Ops.erase(Ops.begin()+Idx-1); 00696 } else { 00697 Ops.erase(Ops.begin()+Idx); 00698 Ops.erase(Ops.begin()+AddOp-1); 00699 } 00700 Ops.push_back(OuterMul); 00701 return SCEVAddExpr::get(Ops); 00702 } 00703 00704 // Check this multiply against other multiplies being added together. 00705 for (unsigned OtherMulIdx = Idx+1; 00706 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 00707 ++OtherMulIdx) { 00708 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 00709 // If MulOp occurs in OtherMul, we can fold the two multiplies 00710 // together. 00711 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 00712 OMulOp != e; ++OMulOp) 00713 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 00714 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 00715 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0); 00716 if (Mul->getNumOperands() != 2) { 00717 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); 00718 MulOps.erase(MulOps.begin()+MulOp); 00719 InnerMul1 = SCEVMulExpr::get(MulOps); 00720 } 00721 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0); 00722 if (OtherMul->getNumOperands() != 2) { 00723 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(), 00724 OtherMul->op_end()); 00725 MulOps.erase(MulOps.begin()+OMulOp); 00726 InnerMul2 = SCEVMulExpr::get(MulOps); 00727 } 00728 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2); 00729 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum); 00730 if (Ops.size() == 2) return OuterMul; 00731 Ops.erase(Ops.begin()+Idx); 00732 Ops.erase(Ops.begin()+OtherMulIdx-1); 00733 Ops.push_back(OuterMul); 00734 return SCEVAddExpr::get(Ops); 00735 } 00736 } 00737 } 00738 } 00739 00740 // If there are any add recurrences in the operands list, see if any other 00741 // added values are loop invariant. If so, we can fold them into the 00742 // recurrence. 00743 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 00744 ++Idx; 00745 00746 // Scan over all recurrences, trying to fold loop invariants into them. 00747 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 00748 // Scan all of the other operands to this add and add them to the vector if 00749 // they are loop invariant w.r.t. the recurrence. 00750 std::vector<SCEVHandle> LIOps; 00751 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 00752 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 00753 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 00754 LIOps.push_back(Ops[i]); 00755 Ops.erase(Ops.begin()+i); 00756 --i; --e; 00757 } 00758 00759 // If we found some loop invariants, fold them into the recurrence. 00760 if (!LIOps.empty()) { 00761 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step } 00762 LIOps.push_back(AddRec->getStart()); 00763 00764 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end()); 00765 AddRecOps[0] = SCEVAddExpr::get(LIOps); 00766 00767 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop()); 00768 // If all of the other operands were loop invariant, we are done. 00769 if (Ops.size() == 1) return NewRec; 00770 00771 // Otherwise, add the folded AddRec by the non-liv parts. 00772 for (unsigned i = 0;; ++i) 00773 if (Ops[i] == AddRec) { 00774 Ops[i] = NewRec; 00775 break; 00776 } 00777 return SCEVAddExpr::get(Ops); 00778 } 00779 00780 // Okay, if there weren't any loop invariants to be folded, check to see if 00781 // there are multiple AddRec's with the same loop induction variable being 00782 // added together. If so, we can fold them. 00783 for (unsigned OtherIdx = Idx+1; 00784 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 00785 if (OtherIdx != Idx) { 00786 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 00787 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 00788 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D} 00789 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end()); 00790 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) { 00791 if (i >= NewOps.size()) { 00792 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i, 00793 OtherAddRec->op_end()); 00794 break; 00795 } 00796 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i)); 00797 } 00798 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop()); 00799 00800 if (Ops.size() == 2) return NewAddRec; 00801 00802 Ops.erase(Ops.begin()+Idx); 00803 Ops.erase(Ops.begin()+OtherIdx-1); 00804 Ops.push_back(NewAddRec); 00805 return SCEVAddExpr::get(Ops); 00806 } 00807 } 00808 00809 // Otherwise couldn't fold anything into this recurrence. Move onto the 00810 // next one. 00811 } 00812 00813 // Okay, it looks like we really DO need an add expr. Check to see if we 00814 // already have one, otherwise create a new one. 00815 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); 00816 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr, 00817 SCEVOps)]; 00818 if (Result == 0) Result = new SCEVAddExpr(Ops); 00819 return Result; 00820 } 00821 00822 00823 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) { 00824 assert(!Ops.empty() && "Cannot get empty mul!"); 00825 00826 // Sort by complexity, this groups all similar expression types together. 00827 GroupByComplexity(Ops); 00828 00829 // If there are any constants, fold them together. 00830 unsigned Idx = 0; 00831 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 00832 00833 // C1*(C2+V) -> C1*C2 + C1*V 00834 if (Ops.size() == 2) 00835 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 00836 if (Add->getNumOperands() == 2 && 00837 isa<SCEVConstant>(Add->getOperand(0))) 00838 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)), 00839 SCEVMulExpr::get(LHSC, Add->getOperand(1))); 00840 00841 00842 ++Idx; 00843 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 00844 // We found two constants, fold them together! 00845 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue()); 00846 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) { 00847 Ops[0] = SCEVConstant::get(CI); 00848 Ops.erase(Ops.begin()+1); // Erase the folded element 00849 if (Ops.size() == 1) return Ops[0]; 00850 LHSC = cast<SCEVConstant>(Ops[0]); 00851 } else { 00852 // If we couldn't fold the expression, move to the next constant. Note 00853 // that this is impossible to happen in practice because we always 00854 // constant fold constant ints to constant ints. 00855 ++Idx; 00856 } 00857 } 00858 00859 // If we are left with a constant one being multiplied, strip it off. 00860 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 00861 Ops.erase(Ops.begin()); 00862 --Idx; 00863 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) { 00864 // If we have a multiply of zero, it will always be zero. 00865 return Ops[0]; 00866 } 00867 } 00868 00869 // Skip over the add expression until we get to a multiply. 00870 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 00871 ++Idx; 00872 00873 if (Ops.size() == 1) 00874 return Ops[0]; 00875 00876 // If there are mul operands inline them all into this expression. 00877 if (Idx < Ops.size()) { 00878 bool DeletedMul = false; 00879 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 00880 // If we have an mul, expand the mul operands onto the end of the operands 00881 // list. 00882 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end()); 00883 Ops.erase(Ops.begin()+Idx); 00884 DeletedMul = true; 00885 } 00886 00887 // If we deleted at least one mul, we added operands to the end of the list, 00888 // and they are not necessarily sorted. Recurse to resort and resimplify 00889 // any operands we just aquired. 00890 if (DeletedMul) 00891 return get(Ops); 00892 } 00893 00894 // If there are any add recurrences in the operands list, see if any other 00895 // added values are loop invariant. If so, we can fold them into the 00896 // recurrence. 00897 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 00898 ++Idx; 00899 00900 // Scan over all recurrences, trying to fold loop invariants into them. 00901 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 00902 // Scan all of the other operands to this mul and add them to the vector if 00903 // they are loop invariant w.r.t. the recurrence. 00904 std::vector<SCEVHandle> LIOps; 00905 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 00906 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 00907 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 00908 LIOps.push_back(Ops[i]); 00909 Ops.erase(Ops.begin()+i); 00910 --i; --e; 00911 } 00912 00913 // If we found some loop invariants, fold them into the recurrence. 00914 if (!LIOps.empty()) { 00915 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step } 00916 std::vector<SCEVHandle> NewOps; 00917 NewOps.reserve(AddRec->getNumOperands()); 00918 if (LIOps.size() == 1) { 00919 SCEV *Scale = LIOps[0]; 00920 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 00921 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i))); 00922 } else { 00923 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 00924 std::vector<SCEVHandle> MulOps(LIOps); 00925 MulOps.push_back(AddRec->getOperand(i)); 00926 NewOps.push_back(SCEVMulExpr::get(MulOps)); 00927 } 00928 } 00929 00930 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop()); 00931 00932 // If all of the other operands were loop invariant, we are done. 00933 if (Ops.size() == 1) return NewRec; 00934 00935 // Otherwise, multiply the folded AddRec by the non-liv parts. 00936 for (unsigned i = 0;; ++i) 00937 if (Ops[i] == AddRec) { 00938 Ops[i] = NewRec; 00939 break; 00940 } 00941 return SCEVMulExpr::get(Ops); 00942 } 00943 00944 // Okay, if there weren't any loop invariants to be folded, check to see if 00945 // there are multiple AddRec's with the same loop induction variable being 00946 // multiplied together. If so, we can fold them. 00947 for (unsigned OtherIdx = Idx+1; 00948 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 00949 if (OtherIdx != Idx) { 00950 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 00951 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 00952 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D} 00953 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec; 00954 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(), 00955 G->getStart()); 00956 SCEVHandle B = F->getStepRecurrence(); 00957 SCEVHandle D = G->getStepRecurrence(); 00958 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D), 00959 SCEVMulExpr::get(G, B), 00960 SCEVMulExpr::get(B, D)); 00961 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep, 00962 F->getLoop()); 00963 if (Ops.size() == 2) return NewAddRec; 00964 00965 Ops.erase(Ops.begin()+Idx); 00966 Ops.erase(Ops.begin()+OtherIdx-1); 00967 Ops.push_back(NewAddRec); 00968 return SCEVMulExpr::get(Ops); 00969 } 00970 } 00971 00972 // Otherwise couldn't fold anything into this recurrence. Move onto the 00973 // next one. 00974 } 00975 00976 // Okay, it looks like we really DO need an mul expr. Check to see if we 00977 // already have one, otherwise create a new one. 00978 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); 00979 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr, 00980 SCEVOps)]; 00981 if (Result == 0) 00982 Result = new SCEVMulExpr(Ops); 00983 return Result; 00984 } 00985 00986 SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) { 00987 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 00988 if (RHSC->getValue()->equalsInt(1)) 00989 return LHS; // X /s 1 --> x 00990 if (RHSC->getValue()->isAllOnesValue()) 00991 return SCEV::getNegativeSCEV(LHS); // X /s -1 --> -x 00992 00993 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 00994 Constant *LHSCV = LHSC->getValue(); 00995 Constant *RHSCV = RHSC->getValue(); 00996 if (LHSCV->getType()->isUnsigned()) 00997 LHSCV = ConstantExpr::getCast(LHSCV, 00998 LHSCV->getType()->getSignedVersion()); 00999 if (RHSCV->getType()->isUnsigned()) 01000 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType()); 01001 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV)); 01002 } 01003 } 01004 01005 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow. 01006 01007 SCEVSDivExpr *&Result = SCEVSDivs[std::make_pair(LHS, RHS)]; 01008 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS); 01009 return Result; 01010 } 01011 01012 01013 /// SCEVAddRecExpr::get - Get a add recurrence expression for the 01014 /// specified loop. Simplify the expression as much as possible. 01015 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start, 01016 const SCEVHandle &Step, const Loop *L) { 01017 std::vector<SCEVHandle> Operands; 01018 Operands.push_back(Start); 01019 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 01020 if (StepChrec->getLoop() == L) { 01021 Operands.insert(Operands.end(), StepChrec->op_begin(), 01022 StepChrec->op_end()); 01023 return get(Operands, L); 01024 } 01025 01026 Operands.push_back(Step); 01027 return get(Operands, L); 01028 } 01029 01030 /// SCEVAddRecExpr::get - Get a add recurrence expression for the 01031 /// specified loop. Simplify the expression as much as possible. 01032 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands, 01033 const Loop *L) { 01034 if (Operands.size() == 1) return Operands[0]; 01035 01036 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back())) 01037 if (StepC->getValue()->isNullValue()) { 01038 Operands.pop_back(); 01039 return get(Operands, L); // { X,+,0 } --> X 01040 } 01041 01042 SCEVAddRecExpr *&Result = 01043 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(), 01044 Operands.end()))]; 01045 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L); 01046 return Result; 01047 } 01048 01049 SCEVHandle SCEVUnknown::get(Value *V) { 01050 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 01051 return SCEVConstant::get(CI); 01052 SCEVUnknown *&Result = SCEVUnknowns[V]; 01053 if (Result == 0) Result = new SCEVUnknown(V); 01054 return Result; 01055 } 01056 01057 01058 //===----------------------------------------------------------------------===// 01059 // ScalarEvolutionsImpl Definition and Implementation 01060 //===----------------------------------------------------------------------===// 01061 // 01062 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar 01063 /// evolution code. 01064 /// 01065 namespace { 01066 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl { 01067 /// F - The function we are analyzing. 01068 /// 01069 Function &F; 01070 01071 /// LI - The loop information for the function we are currently analyzing. 01072 /// 01073 LoopInfo &LI; 01074 01075 /// UnknownValue - This SCEV is used to represent unknown trip counts and 01076 /// things. 01077 SCEVHandle UnknownValue; 01078 01079 /// Scalars - This is a cache of the scalars we have analyzed so far. 01080 /// 01081 std::map<Value*, SCEVHandle> Scalars; 01082 01083 /// IterationCounts - Cache the iteration count of the loops for this 01084 /// function as they are computed. 01085 std::map<const Loop*, SCEVHandle> IterationCounts; 01086 01087 /// ConstantEvolutionLoopExitValue - This map contains entries for all of 01088 /// the PHI instructions that we attempt to compute constant evolutions for. 01089 /// This allows us to avoid potentially expensive recomputation of these 01090 /// properties. An instruction maps to null if we are unable to compute its 01091 /// exit value. 01092 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue; 01093 01094 public: 01095 ScalarEvolutionsImpl(Function &f, LoopInfo &li) 01096 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {} 01097 01098 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 01099 /// expression and create a new one. 01100 SCEVHandle getSCEV(Value *V); 01101 01102 /// hasSCEV - Return true if the SCEV for this value has already been 01103 /// computed. 01104 bool hasSCEV(Value *V) const { 01105 return Scalars.count(V); 01106 } 01107 01108 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for 01109 /// the specified value. 01110 void setSCEV(Value *V, const SCEVHandle &H) { 01111 bool isNew = Scalars.insert(std::make_pair(V, H)).second; 01112 assert(isNew && "This entry already existed!"); 01113 } 01114 01115 01116 /// getSCEVAtScope - Compute the value of the specified expression within 01117 /// the indicated loop (which may be null to indicate in no loop). If the 01118 /// expression cannot be evaluated, return UnknownValue itself. 01119 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L); 01120 01121 01122 /// hasLoopInvariantIterationCount - Return true if the specified loop has 01123 /// an analyzable loop-invariant iteration count. 01124 bool hasLoopInvariantIterationCount(const Loop *L); 01125 01126 /// getIterationCount - If the specified loop has a predictable iteration 01127 /// count, return it. Note that it is not valid to call this method on a 01128 /// loop without a loop-invariant iteration count. 01129 SCEVHandle getIterationCount(const Loop *L); 01130 01131 /// deleteInstructionFromRecords - This method should be called by the 01132 /// client before it removes an instruction from the program, to make sure 01133 /// that no dangling references are left around. 01134 void deleteInstructionFromRecords(Instruction *I); 01135 01136 private: 01137 /// createSCEV - We know that there is no SCEV for the specified value. 01138 /// Analyze the expression. 01139 SCEVHandle createSCEV(Value *V); 01140 SCEVHandle createNodeForCast(CastInst *CI); 01141 01142 /// createNodeForPHI - Provide the special handling we need to analyze PHI 01143 /// SCEVs. 01144 SCEVHandle createNodeForPHI(PHINode *PN); 01145 01146 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value 01147 /// for the specified instruction and replaces any references to the 01148 /// symbolic value SymName with the specified value. This is used during 01149 /// PHI resolution. 01150 void ReplaceSymbolicValueWithConcrete(Instruction *I, 01151 const SCEVHandle &SymName, 01152 const SCEVHandle &NewVal); 01153 01154 /// ComputeIterationCount - Compute the number of times the specified loop 01155 /// will iterate. 01156 SCEVHandle ComputeIterationCount(const Loop *L); 01157 01158 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of 01159 /// 'setcc load X, cst', try to se if we can compute the trip count. 01160 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI, 01161 Constant *RHS, 01162 const Loop *L, 01163 unsigned SetCCOpcode); 01164 01165 /// ComputeIterationCountExhaustively - If the trip is known to execute a 01166 /// constant number of times (the condition evolves only from constants), 01167 /// try to evaluate a few iterations of the loop until we get the exit 01168 /// condition gets a value of ExitWhen (true or false). If we cannot 01169 /// evaluate the trip count of the loop, return UnknownValue. 01170 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond, 01171 bool ExitWhen); 01172 01173 /// HowFarToZero - Return the number of times a backedge comparing the 01174 /// specified value to zero will execute. If not computable, return 01175 /// UnknownValue. 01176 SCEVHandle HowFarToZero(SCEV *V, const Loop *L); 01177 01178 /// HowFarToNonZero - Return the number of times a backedge checking the 01179 /// specified value for nonzero will execute. If not computable, return 01180 /// UnknownValue. 01181 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L); 01182 01183 /// HowManyLessThans - Return the number of times a backedge containing the 01184 /// specified less-than comparison will execute. If not computable, return 01185 /// UnknownValue. 01186 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L); 01187 01188 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 01189 /// in the header of its containing loop, we know the loop executes a 01190 /// constant number of times, and the PHI node is just a recurrence 01191 /// involving constants, fold it. 01192 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, 01193 const Loop *L); 01194 }; 01195 } 01196 01197 //===----------------------------------------------------------------------===// 01198 // Basic SCEV Analysis and PHI Idiom Recognition Code 01199 // 01200 01201 /// deleteInstructionFromRecords - This method should be called by the 01202 /// client before it removes an instruction from the program, to make sure 01203 /// that no dangling references are left around. 01204 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) { 01205 Scalars.erase(I); 01206 if (PHINode *PN = dyn_cast<PHINode>(I)) 01207 ConstantEvolutionLoopExitValue.erase(PN); 01208 } 01209 01210 01211 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 01212 /// expression and create a new one. 01213 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) { 01214 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!"); 01215 01216 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V); 01217 if (I != Scalars.end()) return I->second; 01218 SCEVHandle S = createSCEV(V); 01219 Scalars.insert(std::make_pair(V, S)); 01220 return S; 01221 } 01222 01223 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for 01224 /// the specified instruction and replaces any references to the symbolic value 01225 /// SymName with the specified value. This is used during PHI resolution. 01226 void ScalarEvolutionsImpl:: 01227 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName, 01228 const SCEVHandle &NewVal) { 01229 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I); 01230 if (SI == Scalars.end()) return; 01231 01232 SCEVHandle NV = 01233 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal); 01234 if (NV == SI->second) return; // No change. 01235 01236 SI->second = NV; // Update the scalars map! 01237 01238 // Any instruction values that use this instruction might also need to be 01239 // updated! 01240 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 01241 UI != E; ++UI) 01242 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal); 01243 } 01244 01245 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in 01246 /// a loop header, making it a potential recurrence, or it doesn't. 01247 /// 01248 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) { 01249 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized. 01250 if (const Loop *L = LI.getLoopFor(PN->getParent())) 01251 if (L->getHeader() == PN->getParent()) { 01252 // If it lives in the loop header, it has two incoming values, one 01253 // from outside the loop, and one from inside. 01254 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 01255 unsigned BackEdge = IncomingEdge^1; 01256 01257 // While we are analyzing this PHI node, handle its value symbolically. 01258 SCEVHandle SymbolicName = SCEVUnknown::get(PN); 01259 assert(Scalars.find(PN) == Scalars.end() && 01260 "PHI node already processed?"); 01261 Scalars.insert(std::make_pair(PN, SymbolicName)); 01262 01263 // Using this symbolic name for the PHI, analyze the value coming around 01264 // the back-edge. 01265 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge)); 01266 01267 // NOTE: If BEValue is loop invariant, we know that the PHI node just 01268 // has a special value for the first iteration of the loop. 01269 01270 // If the value coming around the backedge is an add with the symbolic 01271 // value we just inserted, then we found a simple induction variable! 01272 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 01273 // If there is a single occurrence of the symbolic value, replace it 01274 // with a recurrence. 01275 unsigned FoundIndex = Add->getNumOperands(); 01276 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 01277 if (Add->getOperand(i) == SymbolicName) 01278 if (FoundIndex == e) { 01279 FoundIndex = i; 01280 break; 01281 } 01282 01283 if (FoundIndex != Add->getNumOperands()) { 01284 // Create an add with everything but the specified operand. 01285 std::vector<SCEVHandle> Ops; 01286 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 01287 if (i != FoundIndex) 01288 Ops.push_back(Add->getOperand(i)); 01289 SCEVHandle Accum = SCEVAddExpr::get(Ops); 01290 01291 // This is not a valid addrec if the step amount is varying each 01292 // loop iteration, but is not itself an addrec in this loop. 01293 if (Accum->isLoopInvariant(L) || 01294 (isa<SCEVAddRecExpr>(Accum) && 01295 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 01296 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); 01297 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L); 01298 01299 // Okay, for the entire analysis of this edge we assumed the PHI 01300 // to be symbolic. We now need to go back and update all of the 01301 // entries for the scalars that use the PHI (except for the PHI 01302 // itself) to use the new analyzed value instead of the "symbolic" 01303 // value. 01304 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 01305 return PHISCEV; 01306 } 01307 } 01308 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) { 01309 // Otherwise, this could be a loop like this: 01310 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 01311 // In this case, j = {1,+,1} and BEValue is j. 01312 // Because the other in-value of i (0) fits the evolution of BEValue 01313 // i really is an addrec evolution. 01314 if (AddRec->getLoop() == L && AddRec->isAffine()) { 01315 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); 01316 01317 // If StartVal = j.start - j.stride, we can use StartVal as the 01318 // initial step of the addrec evolution. 01319 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0), 01320 AddRec->getOperand(1))) { 01321 SCEVHandle PHISCEV = 01322 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L); 01323 01324 // Okay, for the entire analysis of this edge we assumed the PHI 01325 // to be symbolic. We now need to go back and update all of the 01326 // entries for the scalars that use the PHI (except for the PHI 01327 // itself) to use the new analyzed value instead of the "symbolic" 01328 // value. 01329 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 01330 return PHISCEV; 01331 } 01332 } 01333 } 01334 01335 return SymbolicName; 01336 } 01337 01338 // If it's not a loop phi, we can't handle it yet. 01339 return SCEVUnknown::get(PN); 01340 } 01341 01342 /// createNodeForCast - Handle the various forms of casts that we support. 01343 /// 01344 SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) { 01345 const Type *SrcTy = CI->getOperand(0)->getType(); 01346 const Type *DestTy = CI->getType(); 01347 01348 // If this is a noop cast (ie, conversion from int to uint), ignore it. 01349 if (SrcTy->isLosslesslyConvertibleTo(DestTy)) 01350 return getSCEV(CI->getOperand(0)); 01351 01352 if (SrcTy->isInteger() && DestTy->isInteger()) { 01353 // Otherwise, if this is a truncating integer cast, we can represent this 01354 // cast. 01355 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize()) 01356 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)), 01357 CI->getType()->getUnsignedVersion()); 01358 if (SrcTy->isUnsigned() && 01359 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize()) 01360 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)), 01361 CI->getType()->getUnsignedVersion()); 01362 } 01363 01364 // If this is an sign or zero extending cast and we can prove that the value 01365 // will never overflow, we could do similar transformations. 01366 01367 // Otherwise, we can't handle this cast! 01368 return SCEVUnknown::get(CI); 01369 } 01370 01371 01372 /// createSCEV - We know that there is no SCEV for the specified value. 01373 /// Analyze the expression. 01374 /// 01375 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) { 01376 if (Instruction *I = dyn_cast<Instruction>(V)) { 01377 switch (I->getOpcode()) { 01378 case Instruction::Add: 01379 return SCEVAddExpr::get(getSCEV(I->getOperand(0)), 01380 getSCEV(I->getOperand(1))); 01381 case Instruction::Mul: 01382 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), 01383 getSCEV(I->getOperand(1))); 01384 case Instruction::Div: 01385 if (V->getType()->isInteger() && V->getType()->isSigned()) 01386 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)), 01387 getSCEV(I->getOperand(1))); 01388 break; 01389 01390 case Instruction::Sub: 01391 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)), 01392 getSCEV(I->getOperand(1))); 01393 01394 case Instruction::Shl: 01395 // Turn shift left of a constant amount into a multiply. 01396 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { 01397 Constant *X = ConstantInt::get(V->getType(), 1); 01398 X = ConstantExpr::getShl(X, SA); 01399 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X)); 01400 } 01401 break; 01402 01403 case Instruction::Cast: 01404 return createNodeForCast(cast<CastInst>(I)); 01405 01406 case Instruction::PHI: 01407 return createNodeForPHI(cast<PHINode>(I)); 01408 01409 default: // We cannot analyze this expression. 01410 break; 01411 } 01412 } 01413 01414 return SCEVUnknown::get(V); 01415 } 01416 01417 01418 01419 //===----------------------------------------------------------------------===// 01420 // Iteration Count Computation Code 01421 // 01422 01423 /// getIterationCount - If the specified loop has a predictable iteration 01424 /// count, return it. Note that it is not valid to call this method on a 01425 /// loop without a loop-invariant iteration count. 01426 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) { 01427 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L); 01428 if (I == IterationCounts.end()) { 01429 SCEVHandle ItCount = ComputeIterationCount(L); 01430 I = IterationCounts.insert(std::make_pair(L, ItCount)).first; 01431 if (ItCount != UnknownValue) { 01432 assert(ItCount->isLoopInvariant(L) && 01433 "Computed trip count isn't loop invariant for loop!"); 01434 ++NumTripCountsComputed; 01435 } else if (isa<PHINode>(L->getHeader()->begin())) { 01436 // Only count loops that have phi nodes as not being computable. 01437 ++NumTripCountsNotComputed; 01438 } 01439 } 01440 return I->second; 01441 } 01442 01443 /// ComputeIterationCount - Compute the number of times the specified loop 01444 /// will iterate. 01445 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) { 01446 // If the loop has a non-one exit block count, we can't analyze it. 01447 std::vector<BasicBlock*> ExitBlocks; 01448 L->getExitBlocks(ExitBlocks); 01449 if (ExitBlocks.size() != 1) return UnknownValue; 01450 01451 // Okay, there is one exit block. Try to find the condition that causes the 01452 // loop to be exited. 01453 BasicBlock *ExitBlock = ExitBlocks[0]; 01454 01455 BasicBlock *ExitingBlock = 0; 01456 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock); 01457 PI != E; ++PI) 01458 if (L->contains(*PI)) { 01459 if (ExitingBlock == 0) 01460 ExitingBlock = *PI; 01461 else 01462 return UnknownValue; // More than one block exiting! 01463 } 01464 assert(ExitingBlock && "No exits from loop, something is broken!"); 01465 01466 // Okay, we've computed the exiting block. See what condition causes us to 01467 // exit. 01468 // 01469 // FIXME: we should be able to handle switch instructions (with a single exit) 01470 // FIXME: We should handle cast of int to bool as well 01471 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 01472 if (ExitBr == 0) return UnknownValue; 01473 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!"); 01474 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition()); 01475 if (ExitCond == 0) // Not a setcc 01476 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(), 01477 ExitBr->getSuccessor(0) == ExitBlock); 01478 01479 // If the condition was exit on true, convert the condition to exit on false. 01480 Instruction::BinaryOps Cond; 01481 if (ExitBr->getSuccessor(1) == ExitBlock) 01482 Cond = ExitCond->getOpcode(); 01483 else 01484 Cond = ExitCond->getInverseCondition(); 01485 01486 // Handle common loops like: for (X = "string"; *X; ++X) 01487 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 01488 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 01489 SCEVHandle ItCnt = 01490 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond); 01491 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt; 01492 } 01493 01494 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0)); 01495 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1)); 01496 01497 // Try to evaluate any dependencies out of the loop. 01498 SCEVHandle Tmp = getSCEVAtScope(LHS, L); 01499 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp; 01500 Tmp = getSCEVAtScope(RHS, L); 01501 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp; 01502 01503 // At this point, we would like to compute how many iterations of the loop the 01504 // predicate will return true for these inputs. 01505 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) { 01506 // If there is a constant, force it into the RHS. 01507 std::swap(LHS, RHS); 01508 Cond = SetCondInst::getSwappedCondition(Cond); 01509 } 01510 01511 // FIXME: think about handling pointer comparisons! i.e.: 01512 // while (P != P+100) ++P; 01513 01514 // If we have a comparison of a chrec against a constant, try to use value 01515 // ranges to answer this query. 01516 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 01517 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 01518 if (AddRec->getLoop() == L) { 01519 // Form the comparison range using the constant of the correct type so 01520 // that the ConstantRange class knows to do a signed or unsigned 01521 // comparison. 01522 ConstantInt *CompVal = RHSC->getValue(); 01523 const Type *RealTy = ExitCond->getOperand(0)->getType(); 01524 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy)); 01525 if (CompVal) { 01526 // Form the constant range. 01527 ConstantRange CompRange(Cond, CompVal); 01528 01529 // Now that we have it, if it's signed, convert it to an unsigned 01530 // range. 01531 if (CompRange.getLower()->getType()->isSigned()) { 01532 const Type *NewTy = RHSC->getValue()->getType(); 01533 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy); 01534 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy); 01535 CompRange = ConstantRange(NewL, NewU); 01536 } 01537 01538 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange); 01539 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 01540 } 01541 } 01542 01543 switch (Cond) { 01544 case Instruction::SetNE: // while (X != Y) 01545 // Convert to: while (X-Y != 0) 01546 if (LHS->getType()->isInteger()) { 01547 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L); 01548 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 01549 } 01550 break; 01551 case Instruction::SetEQ: 01552 // Convert to: while (X-Y == 0) // while (X == Y) 01553 if (LHS->getType()->isInteger()) { 01554 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L); 01555 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 01556 } 01557 break; 01558 case Instruction::SetLT: 01559 if (LHS->getType()->isInteger() && 01560 ExitCond->getOperand(0)->getType()->isSigned()) { 01561 SCEVHandle TC = HowManyLessThans(LHS, RHS, L); 01562 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 01563 } 01564 break; 01565 case Instruction::SetGT: 01566 if (LHS->getType()->isInteger() && 01567 ExitCond->getOperand(0)->getType()->isSigned()) { 01568 SCEVHandle TC = HowManyLessThans(RHS, LHS, L); 01569 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 01570 } 01571 break; 01572 default: 01573 #if 0 01574 std::cerr << "ComputeIterationCount "; 01575 if (ExitCond->getOperand(0)->getType()->isUnsigned()) 01576 std::cerr << "[unsigned] "; 01577 std::cerr << *LHS << " " 01578 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n"; 01579 #endif 01580 break; 01581 } 01582 01583 return ComputeIterationCountExhaustively(L, ExitCond, 01584 ExitBr->getSuccessor(0) == ExitBlock); 01585 } 01586 01587 static ConstantInt * 01588 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) { 01589 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C)); 01590 SCEVHandle Val = AddRec->evaluateAtIteration(InVal); 01591 assert(isa<SCEVConstant>(Val) && 01592 "Evaluation of SCEV at constant didn't fold correctly?"); 01593 return cast<SCEVConstant>(Val)->getValue(); 01594 } 01595 01596 /// GetAddressedElementFromGlobal - Given a global variable with an initializer 01597 /// and a GEP expression (missing the pointer index) indexing into it, return 01598 /// the addressed element of the initializer or null if the index expression is 01599 /// invalid. 01600 static Constant * 01601 GetAddressedElementFromGlobal(GlobalVariable *GV, 01602 const std::vector<ConstantInt*> &Indices) { 01603 Constant *Init = GV->getInitializer(); 01604 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 01605 uint64_t Idx = Indices[i]->getRawValue(); 01606 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { 01607 assert(Idx < CS->getNumOperands() && "Bad struct index!"); 01608 Init = cast<Constant>(CS->getOperand(Idx)); 01609 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { 01610 if (Idx >= CA->getNumOperands()) return 0; // Bogus program 01611 Init = cast<Constant>(CA->getOperand(Idx)); 01612 } else if (isa<ConstantAggregateZero>(Init)) { 01613 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) { 01614 assert(Idx < STy->getNumElements() && "Bad struct index!"); 01615 Init = Constant::getNullValue(STy->getElementType(Idx)); 01616 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) { 01617 if (Idx >= ATy->getNumElements()) return 0; // Bogus program 01618 Init = Constant::getNullValue(ATy->getElementType()); 01619 } else { 01620 assert(0 && "Unknown constant aggregate type!"); 01621 } 01622 return 0; 01623 } else { 01624 return 0; // Unknown initializer type 01625 } 01626 } 01627 return Init; 01628 } 01629 01630 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of 01631 /// 'setcc load X, cst', try to se if we can compute the trip count. 01632 SCEVHandle ScalarEvolutionsImpl:: 01633 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS, 01634 const Loop *L, unsigned SetCCOpcode) { 01635 if (LI->isVolatile()) return UnknownValue; 01636 01637 // Check to see if the loaded pointer is a getelementptr of a global. 01638 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 01639 if (!GEP) return UnknownValue; 01640 01641 // Make sure that it is really a constant global we are gepping, with an 01642 // initializer, and make sure the first IDX is really 0. 01643 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 01644 if (!GV || !GV->isConstant() || !GV->hasInitializer() || 01645 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 01646 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 01647 return UnknownValue; 01648 01649 // Okay, we allow one non-constant index into the GEP instruction. 01650 Value *VarIdx = 0; 01651 std::vector<ConstantInt*> Indexes; 01652 unsigned VarIdxNum = 0; 01653 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 01654 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 01655 Indexes.push_back(CI); 01656 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 01657 if (VarIdx) return UnknownValue; // Multiple non-constant idx's. 01658 VarIdx = GEP->getOperand(i); 01659 VarIdxNum = i-2; 01660 Indexes.push_back(0); 01661 } 01662 01663 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 01664 // Check to see if X is a loop variant variable value now. 01665 SCEVHandle Idx = getSCEV(VarIdx); 01666 SCEVHandle Tmp = getSCEVAtScope(Idx, L); 01667 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp; 01668 01669 // We can only recognize very limited forms of loop index expressions, in 01670 // particular, only affine AddRec's like {C1,+,C2}. 01671 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 01672 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) || 01673 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 01674 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 01675 return UnknownValue; 01676 01677 unsigned MaxSteps = MaxBruteForceIterations; 01678 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 01679 ConstantUInt *ItCst = 01680 ConstantUInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum); 01681 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst); 01682 01683 // Form the GEP offset. 01684 Indexes[VarIdxNum] = Val; 01685 01686 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes); 01687 if (Result == 0) break; // Cannot compute! 01688 01689 // Evaluate the condition for this iteration. 01690 Result = ConstantExpr::get(SetCCOpcode, Result, RHS); 01691 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure 01692 if (Result == ConstantBool::False) { 01693 #if 0 01694 std::cerr << "\n***\n*** Computed loop count " << *ItCst 01695 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() 01696 << "***\n"; 01697 #endif 01698 ++NumArrayLenItCounts; 01699 return SCEVConstant::get(ItCst); // Found terminating iteration! 01700 } 01701 } 01702 return UnknownValue; 01703 } 01704 01705 01706 /// CanConstantFold - Return true if we can constant fold an instruction of the 01707 /// specified type, assuming that all operands were constants. 01708 static bool CanConstantFold(const Instruction *I) { 01709 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) || 01710 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I)) 01711 return true; 01712 01713 if (const CallInst *CI = dyn_cast<CallInst>(I)) 01714 if (const Function *F = CI->getCalledFunction()) 01715 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast 01716 return false; 01717 } 01718 01719 /// ConstantFold - Constant fold an instruction of the specified type with the 01720 /// specified constant operands. This function may modify the operands vector. 01721 static Constant *ConstantFold(const Instruction *I, 01722 std::vector<Constant*> &Operands) { 01723 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) 01724 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]); 01725 01726 switch (I->getOpcode()) { 01727 case Instruction::Cast: 01728 return ConstantExpr::getCast(Operands[0], I->getType()); 01729 case Instruction::Select: 01730 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]); 01731 case Instruction::Call: 01732 if (Function *GV = dyn_cast<Function>(Operands[0])) { 01733 Operands.erase(Operands.begin()); 01734 return ConstantFoldCall(cast<Function>(GV), Operands); 01735 } 01736 01737 return 0; 01738 case Instruction::GetElementPtr: 01739 Constant *Base = Operands[0]; 01740 Operands.erase(Operands.begin()); 01741 return ConstantExpr::getGetElementPtr(Base, Operands); 01742 } 01743 return 0; 01744 } 01745 01746 01747 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 01748 /// in the loop that V is derived from. We allow arbitrary operations along the 01749 /// way, but the operands of an operation must either be constants or a value 01750 /// derived from a constant PHI. If this expression does not fit with these 01751 /// constraints, return null. 01752 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 01753 // If this is not an instruction, or if this is an instruction outside of the 01754 // loop, it can't be derived from a loop PHI. 01755 Instruction *I = dyn_cast<Instruction>(V); 01756 if (I == 0 || !L->contains(I->getParent())) return 0; 01757 01758 if (PHINode *PN = dyn_cast<PHINode>(I)) 01759 if (L->getHeader() == I->getParent()) 01760 return PN; 01761 else 01762 // We don't currently keep track of the control flow needed to evaluate 01763 // PHIs, so we cannot handle PHIs inside of loops. 01764 return 0; 01765 01766 // If we won't be able to constant fold this expression even if the operands 01767 // are constants, return early. 01768 if (!CanConstantFold(I)) return 0; 01769 01770 // Otherwise, we can evaluate this instruction if all of its operands are 01771 // constant or derived from a PHI node themselves. 01772 PHINode *PHI = 0; 01773 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op) 01774 if (!(isa<Constant>(I->getOperand(Op)) || 01775 isa<GlobalValue>(I->getOperand(Op)))) { 01776 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L); 01777 if (P == 0) return 0; // Not evolving from PHI 01778 if (PHI == 0) 01779 PHI = P; 01780 else if (PHI != P) 01781 return 0; // Evolving from multiple different PHIs. 01782 } 01783 01784 // This is a expression evolving from a constant PHI! 01785 return PHI; 01786 } 01787 01788 /// EvaluateExpression - Given an expression that passes the 01789 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 01790 /// in the loop has the value PHIVal. If we can't fold this expression for some 01791 /// reason, return null. 01792 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) { 01793 if (isa<PHINode>(V)) return PHIVal; 01794 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) 01795 return GV; 01796 if (Constant *C = dyn_cast<Constant>(V)) return C; 01797 Instruction *I = cast<Instruction>(V); 01798 01799 std::vector<Constant*> Operands; 01800 Operands.resize(I->getNumOperands()); 01801 01802 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 01803 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal); 01804 if (Operands[i] == 0) return 0; 01805 } 01806 01807 return ConstantFold(I, Operands); 01808 } 01809 01810 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 01811 /// in the header of its containing loop, we know the loop executes a 01812 /// constant number of times, and the PHI node is just a recurrence 01813 /// involving constants, fold it. 01814 Constant *ScalarEvolutionsImpl:: 01815 getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) { 01816 std::map<PHINode*, Constant*>::iterator I = 01817 ConstantEvolutionLoopExitValue.find(PN); 01818 if (I != ConstantEvolutionLoopExitValue.end()) 01819 return I->second; 01820 01821 if (Its > MaxBruteForceIterations) 01822 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it. 01823 01824 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 01825 01826 // Since the loop is canonicalized, the PHI node must have two entries. One 01827 // entry must be a constant (coming in from outside of the loop), and the 01828 // second must be derived from the same PHI. 01829 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 01830 Constant *StartCST = 01831 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 01832 if (StartCST == 0) 01833 return RetVal = 0; // Must be a constant. 01834 01835 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 01836 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 01837 if (PN2 != PN) 01838 return RetVal = 0; // Not derived from same PHI. 01839 01840 // Execute the loop symbolically to determine the exit value. 01841 unsigned IterationNum = 0; 01842 unsigned NumIterations = Its; 01843 if (NumIterations != Its) 01844 return RetVal = 0; // More than 2^32 iterations?? 01845 01846 for (Constant *PHIVal = StartCST; ; ++IterationNum) { 01847 if (IterationNum == NumIterations) 01848 return RetVal = PHIVal; // Got exit value! 01849 01850 // Compute the value of the PHI node for the next iteration. 01851 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 01852 if (NextPHI == PHIVal) 01853 return RetVal = NextPHI; // Stopped evolving! 01854 if (NextPHI == 0) 01855 return 0; // Couldn't evaluate! 01856 PHIVal = NextPHI; 01857 } 01858 } 01859 01860 /// ComputeIterationCountExhaustively - If the trip is known to execute a 01861 /// constant number of times (the condition evolves only from constants), 01862 /// try to evaluate a few iterations of the loop until we get the exit 01863 /// condition gets a value of ExitWhen (true or false). If we cannot 01864 /// evaluate the trip count of the loop, return UnknownValue. 01865 SCEVHandle ScalarEvolutionsImpl:: 01866 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) { 01867 PHINode *PN = getConstantEvolvingPHI(Cond, L); 01868 if (PN == 0) return UnknownValue; 01869 01870 // Since the loop is canonicalized, the PHI node must have two entries. One 01871 // entry must be a constant (coming in from outside of the loop), and the 01872 // second must be derived from the same PHI. 01873 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 01874 Constant *StartCST = 01875 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 01876 if (StartCST == 0) return UnknownValue; // Must be a constant. 01877 01878 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 01879 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 01880 if (PN2 != PN) return UnknownValue; // Not derived from same PHI. 01881 01882 // Okay, we find a PHI node that defines the trip count of this loop. Execute 01883 // the loop symbolically to determine when the condition gets a value of 01884 // "ExitWhen". 01885 unsigned IterationNum = 0; 01886 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 01887 for (Constant *PHIVal = StartCST; 01888 IterationNum != MaxIterations; ++IterationNum) { 01889 ConstantBool *CondVal = 01890 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal)); 01891 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate. 01892 01893 if (CondVal->getValue() == ExitWhen) { 01894 ConstantEvolutionLoopExitValue[PN] = PHIVal; 01895 ++NumBruteForceTripCountsComputed; 01896 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum)); 01897 } 01898 01899 // Compute the value of the PHI node for the next iteration. 01900 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 01901 if (NextPHI == 0 || NextPHI == PHIVal) 01902 return UnknownValue; // Couldn't evaluate or not making progress... 01903 PHIVal = NextPHI; 01904 } 01905 01906 // Too many iterations were needed to evaluate. 01907 return UnknownValue; 01908 } 01909 01910 /// getSCEVAtScope - Compute the value of the specified expression within the 01911 /// indicated loop (which may be null to indicate in no loop). If the 01912 /// expression cannot be evaluated, return UnknownValue. 01913 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) { 01914 // FIXME: this should be turned into a virtual method on SCEV! 01915 01916 if (isa<SCEVConstant>(V)) return V; 01917 01918 // If this instruction is evolves from a constant-evolving PHI, compute the 01919 // exit value from the loop without using SCEVs. 01920 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 01921 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 01922 const Loop *LI = this->LI[I->getParent()]; 01923 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 01924 if (PHINode *PN = dyn_cast<PHINode>(I)) 01925 if (PN->getParent() == LI->getHeader()) { 01926 // Okay, there is no closed form solution for the PHI node. Check 01927 // to see if the loop that contains it has a known iteration count. 01928 // If so, we may be able to force computation of the exit value. 01929 SCEVHandle IterationCount = getIterationCount(LI); 01930 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) { 01931 // Okay, we know how many times the containing loop executes. If 01932 // this is a constant evolving PHI node, get the final value at 01933 // the specified iteration number. 01934 Constant *RV = getConstantEvolutionLoopExitValue(PN, 01935 ICC->getValue()->getRawValue(), 01936 LI); 01937 if (RV) return SCEVUnknown::get(RV); 01938 } 01939 } 01940 01941 // Okay, this is a some expression that we cannot symbolically evaluate 01942 // into a SCEV. Check to see if it's possible to symbolically evaluate 01943 // the arguments into constants, and if see, try to constant propagate the 01944 // result. This is particularly useful for computing loop exit values. 01945 if (CanConstantFold(I)) { 01946 std::vector<Constant*> Operands; 01947 Operands.reserve(I->getNumOperands()); 01948 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 01949 Value *Op = I->getOperand(i); 01950 if (Constant *C = dyn_cast<Constant>(Op)) { 01951 Operands.push_back(C); 01952 } else { 01953 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L); 01954 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) 01955 Operands.push_back(ConstantExpr::getCast(SC->getValue(), 01956 Op->getType())); 01957 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) { 01958 if (Constant *C = dyn_cast<Constant>(SU->getValue())) 01959 Operands.push_back(ConstantExpr::getCast(C, Op->getType())); 01960 else 01961 return V; 01962 } else { 01963 return V; 01964 } 01965 } 01966 } 01967 return SCEVUnknown::get(ConstantFold(I, Operands)); 01968 } 01969 } 01970 01971 // This is some other type of SCEVUnknown, just return it. 01972 return V; 01973 } 01974 01975 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 01976 // Avoid performing the look-up in the common case where the specified 01977 // expression has no loop-variant portions. 01978 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 01979 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 01980 if (OpAtScope != Comm->getOperand(i)) { 01981 if (OpAtScope == UnknownValue) return UnknownValue; 01982 // Okay, at least one of these operands is loop variant but might be 01983 // foldable. Build a new instance of the folded commutative expression. 01984 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i); 01985 NewOps.push_back(OpAtScope); 01986 01987 for (++i; i != e; ++i) { 01988 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 01989 if (OpAtScope == UnknownValue) return UnknownValue; 01990 NewOps.push_back(OpAtScope); 01991 } 01992 if (isa<SCEVAddExpr>(Comm)) 01993 return SCEVAddExpr::get(NewOps); 01994 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!"); 01995 return SCEVMulExpr::get(NewOps); 01996 } 01997 } 01998 // If we got here, all operands are loop invariant. 01999 return Comm; 02000 } 02001 02002 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) { 02003 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L); 02004 if (LHS == UnknownValue) return LHS; 02005 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L); 02006 if (RHS == UnknownValue) return RHS; 02007 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 02008 return Div; // must be loop invariant 02009 return SCEVSDivExpr::get(LHS, RHS); 02010 } 02011 02012 // If this is a loop recurrence for a loop that does not contain L, then we 02013 // are dealing with the final value computed by the loop. 02014 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 02015 if (!L || !AddRec->getLoop()->contains(L->getHeader())) { 02016 // To evaluate this recurrence, we need to know how many times the AddRec 02017 // loop iterates. Compute this now. 02018 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop()); 02019 if (IterationCount == UnknownValue) return UnknownValue; 02020 IterationCount = getTruncateOrZeroExtend(IterationCount, 02021 AddRec->getType()); 02022 02023 // If the value is affine, simplify the expression evaluation to just 02024 // Start + Step*IterationCount. 02025 if (AddRec->isAffine()) 02026 return SCEVAddExpr::get(AddRec->getStart(), 02027 SCEVMulExpr::get(IterationCount, 02028 AddRec->getOperand(1))); 02029 02030 // Otherwise, evaluate it the hard way. 02031 return AddRec->evaluateAtIteration(IterationCount); 02032 } 02033 return UnknownValue; 02034 } 02035 02036 //assert(0 && "Unknown SCEV type!"); 02037 return UnknownValue; 02038 } 02039 02040 02041 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the 02042 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which 02043 /// might be the same) or two SCEVCouldNotCompute objects. 02044 /// 02045 static std::pair<SCEVHandle,SCEVHandle> 02046 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) { 02047 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 02048 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 02049 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 02050 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 02051 02052 // We currently can only solve this if the coefficients are constants. 02053 if (!L || !M || !N) { 02054 SCEV *CNC = new SCEVCouldNotCompute(); 02055 return std::make_pair(CNC, CNC); 02056 } 02057 02058 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2); 02059 02060 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 02061 Constant *C = L->getValue(); 02062 // The B coefficient is M-N/2 02063 Constant *B = ConstantExpr::getSub(M->getValue(), 02064 ConstantExpr::getDiv(N->getValue(), 02065 Two)); 02066 // The A coefficient is N/2 02067 Constant *A = ConstantExpr::getDiv(N->getValue(), Two); 02068 02069 // Compute the B^2-4ac term. 02070 Constant *SqrtTerm = 02071 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4), 02072 ConstantExpr::getMul(A, C)); 02073 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm); 02074 02075 // Compute floor(sqrt(B^2-4ac)) 02076 ConstantUInt *SqrtVal = 02077 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm, 02078 SqrtTerm->getType()->getUnsignedVersion())); 02079 uint64_t SqrtValV = SqrtVal->getValue(); 02080 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV); 02081 // The square root might not be precise for arbitrary 64-bit integer 02082 // values. Do some sanity checks to ensure it's correct. 02083 if (SqrtValV2*SqrtValV2 > SqrtValV || 02084 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) { 02085 SCEV *CNC = new SCEVCouldNotCompute(); 02086 return std::make_pair(CNC, CNC); 02087 } 02088 02089 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2); 02090 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType()); 02091 02092 Constant *NegB = ConstantExpr::getNeg(B); 02093 Constant *TwoA = ConstantExpr::getMul(A, Two); 02094 02095 // The divisions must be performed as signed divisions. 02096 const Type *SignedTy = NegB->getType()->getSignedVersion(); 02097 NegB = ConstantExpr::getCast(NegB, SignedTy); 02098 TwoA = ConstantExpr::getCast(TwoA, SignedTy); 02099 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy); 02100 02101 Constant *Solution1 = 02102 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA); 02103 Constant *Solution2 = 02104 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA); 02105 return std::make_pair(SCEVUnknown::get(Solution1), 02106 SCEVUnknown::get(Solution2)); 02107 } 02108 02109 /// HowFarToZero - Return the number of times a backedge comparing the specified 02110 /// value to zero will execute. If not computable, return UnknownValue 02111 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) { 02112 // If the value is a constant 02113 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 02114 // If the value is already zero, the branch will execute zero times. 02115 if (C->getValue()->isNullValue()) return C; 02116 return UnknownValue; // Otherwise it will loop infinitely. 02117 } 02118 02119 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 02120 if (!AddRec || AddRec->getLoop() != L) 02121 return UnknownValue; 02122 02123 if (AddRec->isAffine()) { 02124 // If this is an affine expression the execution count of this branch is 02125 // equal to: 02126 // 02127 // (0 - Start/Step) iff Start % Step == 0 02128 // 02129 // Get the initial value for the loop. 02130 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 02131 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue; 02132 SCEVHandle Step = AddRec->getOperand(1); 02133 02134 Step = getSCEVAtScope(Step, L->getParentLoop()); 02135 02136 // Figure out if Start % Step == 0. 02137 // FIXME: We should add DivExpr and RemExpr operations to our AST. 02138 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) { 02139 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0 02140 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start 02141 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0 02142 return Start; // 0 - Start/-1 == Start 02143 02144 // Check to see if Start is divisible by SC with no remainder. 02145 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { 02146 ConstantInt *StartCC = StartC->getValue(); 02147 Constant *StartNegC = ConstantExpr::getNeg(StartCC); 02148 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue()); 02149 if (Rem->isNullValue()) { 02150 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue()); 02151 return SCEVUnknown::get(Result); 02152 } 02153 } 02154 } 02155 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) { 02156 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 02157 // the quadratic equation to solve it. 02158 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec); 02159 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 02160 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 02161 if (R1) { 02162 #if 0 02163 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1 02164 << " sol#2: " << *R2 << "\n"; 02165 #endif 02166 // Pick the smallest positive root value. 02167 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?"); 02168 if (ConstantBool *CB = 02169 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(), 02170 R2->getValue()))) { 02171 if (CB != ConstantBool::True) 02172 std::swap(R1, R2); // R1 is the minimum root now. 02173 02174 // We can only use this value if the chrec ends up with an exact zero 02175 // value at this index. When solving for "X*X != 5", for example, we 02176 // should not accept a root of 2. 02177 SCEVHandle Val = AddRec->evaluateAtIteration(R1); 02178 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val)) 02179 if (EvalVal->getValue()->isNullValue()) 02180 return R1; // We found a quadratic root! 02181 } 02182 } 02183 } 02184 02185 return UnknownValue; 02186 } 02187 02188 /// HowFarToNonZero - Return the number of times a backedge checking the 02189 /// specified value for nonzero will execute. If not computable, return 02190 /// UnknownValue 02191 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) { 02192 // Loops that look like: while (X == 0) are very strange indeed. We don't 02193 // handle them yet except for the trivial case. This could be expanded in the 02194 // future as needed. 02195 02196 // If the value is a constant, check to see if it is known to be non-zero 02197 // already. If so, the backedge will execute zero times. 02198 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 02199 Constant *Zero = Constant::getNullValue(C->getValue()->getType()); 02200 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero); 02201 if (NonZero == ConstantBool::True) 02202 return getSCEV(Zero); 02203 return UnknownValue; // Otherwise it will loop infinitely. 02204 } 02205 02206 // We could implement others, but I really doubt anyone writes loops like 02207 // this, and if they did, they would already be constant folded. 02208 return UnknownValue; 02209 } 02210 02211 /// HowManyLessThans - Return the number of times a backedge containing the 02212 /// specified less-than comparison will execute. If not computable, return 02213 /// UnknownValue. 02214 SCEVHandle ScalarEvolutionsImpl:: 02215 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) { 02216 // Only handle: "ADDREC < LoopInvariant". 02217 if (!RHS->isLoopInvariant(L)) return UnknownValue; 02218 02219 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS); 02220 if (!AddRec || AddRec->getLoop() != L) 02221 return UnknownValue; 02222 02223 if (AddRec->isAffine()) { 02224 // FORNOW: We only support unit strides. 02225 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType()); 02226 if (AddRec->getOperand(1) != One) 02227 return UnknownValue; 02228 02229 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't 02230 // know that m is >= n on input to the loop. If it is, the condition return 02231 // true zero times. What we really should return, for full generality, is 02232 // SMAX(0, m-n). Since we cannot check this, we will instead check for a 02233 // canonical loop form: most do-loops will have a check that dominates the 02234 // loop, that only enters the loop if [n-1]<m. If we can find this check, 02235 // we know that the SMAX will evaluate to m-n, because we know that m >= n. 02236 02237 // Search for the check. 02238 BasicBlock *Preheader = L->getLoopPreheader(); 02239 BasicBlock *PreheaderDest = L->getHeader(); 02240 if (Preheader == 0) return UnknownValue; 02241 02242 BranchInst *LoopEntryPredicate = 02243 dyn_cast<BranchInst>(Preheader->getTerminator()); 02244 if (!LoopEntryPredicate) return UnknownValue; 02245 02246 // This might be a critical edge broken out. If the loop preheader ends in 02247 // an unconditional branch to the loop, check to see if the preheader has a 02248 // single predecessor, and if so, look for its terminator. 02249 while (LoopEntryPredicate->isUnconditional()) { 02250 PreheaderDest = Preheader; 02251 Preheader = Preheader->getSinglePredecessor(); 02252 if (!Preheader) return UnknownValue; // Multiple preds. 02253 02254 LoopEntryPredicate = 02255 dyn_cast<BranchInst>(Preheader->getTerminator()); 02256 if (!LoopEntryPredicate) return UnknownValue; 02257 } 02258 02259 // Now that we found a conditional branch that dominates the loop, check to 02260 // see if it is the comparison we are looking for. 02261 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition()); 02262 if (!SCI) return UnknownValue; 02263 Value *PreCondLHS = SCI->getOperand(0); 02264 Value *PreCondRHS = SCI->getOperand(1); 02265 Instruction::BinaryOps Cond; 02266 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest) 02267 Cond = SCI->getOpcode(); 02268 else 02269 Cond = SCI->getInverseCondition(); 02270 02271 switch (Cond) { 02272 case Instruction::SetGT: 02273 std::swap(PreCondLHS, PreCondRHS); 02274 Cond = Instruction::SetLT; 02275 // Fall Through. 02276 case Instruction::SetLT: 02277 if (PreCondLHS->getType()->isInteger() && 02278 PreCondLHS->getType()->isSigned()) { 02279 if (RHS != getSCEV(PreCondRHS)) 02280 return UnknownValue; // Not a comparison against 'm'. 02281 02282 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One) 02283 != getSCEV(PreCondLHS)) 02284 return UnknownValue; // Not a comparison against 'n-1'. 02285 break; 02286 } else { 02287 return UnknownValue; 02288 } 02289 default: break; 02290 } 02291 02292 //std::cerr << "Computed Loop Trip Count as: " << 02293 // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n"; 02294 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)); 02295 } 02296 02297 return UnknownValue; 02298 } 02299 02300 /// getNumIterationsInRange - Return the number of iterations of this loop that 02301 /// produce values in the specified constant range. Another way of looking at 02302 /// this is that it returns the first iteration number where the value is not in 02303 /// the condition, thus computing the exit count. If the iteration count can't 02304 /// be computed, an instance of SCEVCouldNotCompute is returned. 02305 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const { 02306 if (Range.isFullSet()) // Infinite loop. 02307 return new SCEVCouldNotCompute(); 02308 02309 // If the start is a non-zero constant, shift the range to simplify things. 02310 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 02311 if (!SC->getValue()->isNullValue()) { 02312 std::vector<SCEVHandle> Operands(op_begin(), op_end()); 02313 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType()); 02314 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop()); 02315 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 02316 return ShiftedAddRec->getNumIterationsInRange( 02317 Range.subtract(SC->getValue())); 02318 // This is strange and shouldn't happen. 02319 return new SCEVCouldNotCompute(); 02320 } 02321 02322 // The only time we can solve this is when we have all constant indices. 02323 // Otherwise, we cannot determine the overflow conditions. 02324 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 02325 if (!isa<SCEVConstant>(getOperand(i))) 02326 return new SCEVCouldNotCompute(); 02327 02328 02329 // Okay at this point we know that all elements of the chrec are constants and 02330 // that the start element is zero. 02331 02332 // First check to see if the range contains zero. If not, the first 02333 // iteration exits. 02334 ConstantInt *Zero = ConstantInt::get(getType(), 0); 02335 if (!Range.contains(Zero)) return SCEVConstant::get(Zero); 02336 02337 if (isAffine()) { 02338 // If this is an affine expression then we have this situation: 02339 // Solve {0,+,A} in Range === Ax in Range 02340 02341 // Since we know that zero is in the range, we know that the upper value of 02342 // the range must be the first possible exit value. Also note that we 02343 // already checked for a full range. 02344 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper()); 02345 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue(); 02346 ConstantInt *One = ConstantInt::get(getType(), 1); 02347 02348 // The exit value should be (Upper+A-1)/A. 02349 Constant *ExitValue = Upper; 02350 if (A != One) { 02351 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One); 02352 ExitValue = ConstantExpr::getDiv(ExitValue, A); 02353 } 02354 assert(isa<ConstantInt>(ExitValue) && 02355 "Constant folding of integers not implemented?"); 02356 02357 // Evaluate at the exit value. If we really did fall out of the valid 02358 // range, then we computed our trip count, otherwise wrap around or other 02359 // things must have happened. 02360 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue); 02361 if (Range.contains(Val)) 02362 return new SCEVCouldNotCompute(); // Something strange happened 02363 02364 // Ensure that the previous value is in the range. This is a sanity check. 02365 assert(Range.contains(EvaluateConstantChrecAtConstant(this, 02366 ConstantExpr::getSub(ExitValue, One))) && 02367 "Linear scev computation is off in a bad way!"); 02368 return SCEVConstant::get(cast<ConstantInt>(ExitValue)); 02369 } else if (isQuadratic()) { 02370 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 02371 // quadratic equation to solve it. To do this, we must frame our problem in 02372 // terms of figuring out when zero is crossed, instead of when 02373 // Range.getUpper() is crossed. 02374 std::vector<SCEVHandle> NewOps(op_begin(), op_end()); 02375 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper())); 02376 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop()); 02377 02378 // Next, solve the constructed addrec 02379 std::pair<SCEVHandle,SCEVHandle> Roots = 02380 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec)); 02381 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 02382 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 02383 if (R1) { 02384 // Pick the smallest positive root value. 02385 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?"); 02386 if (ConstantBool *CB = 02387 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(), 02388 R2->getValue()))) { 02389 if (CB != ConstantBool::True) 02390 std::swap(R1, R2); // R1 is the minimum root now. 02391 02392 // Make sure the root is not off by one. The returned iteration should 02393 // not be in the range, but the previous one should be. When solving 02394 // for "X*X < 5", for example, we should not return a root of 2. 02395 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, 02396 R1->getValue()); 02397 if (Range.contains(R1Val)) { 02398 // The next iteration must be out of the range... 02399 Constant *NextVal = 02400 ConstantExpr::getAdd(R1->getValue(), 02401 ConstantInt::get(R1->getType(), 1)); 02402 02403 R1Val = EvaluateConstantChrecAtConstant(this, NextVal); 02404 if (!Range.contains(R1Val)) 02405 return SCEVUnknown::get(NextVal); 02406 return new SCEVCouldNotCompute(); // Something strange happened 02407 } 02408 02409 // If R1 was not in the range, then it is a good return value. Make 02410 // sure that R1-1 WAS in the range though, just in case. 02411 Constant *NextVal = 02412 ConstantExpr::getSub(R1->getValue(), 02413 ConstantInt::get(R1->getType(), 1)); 02414 R1Val = EvaluateConstantChrecAtConstant(this, NextVal); 02415 if (Range.contains(R1Val)) 02416 return R1; 02417 return new SCEVCouldNotCompute(); // Something strange happened 02418 } 02419 } 02420 } 02421 02422 // Fallback, if this is a general polynomial, figure out the progression 02423 // through brute force: evaluate until we find an iteration that fails the 02424 // test. This is likely to be slow, but getting an accurate trip count is 02425 // incredibly important, we will be able to simplify the exit test a lot, and 02426 // we are almost guaranteed to get a trip count in this case. 02427 ConstantInt *TestVal = ConstantInt::get(getType(), 0); 02428 ConstantInt *One = ConstantInt::get(getType(), 1); 02429 ConstantInt *EndVal = TestVal; // Stop when we wrap around. 02430 do { 02431 ++NumBruteForceEvaluations; 02432 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal)); 02433 if (!isa<SCEVConstant>(Val)) // This shouldn't happen. 02434 return new SCEVCouldNotCompute(); 02435 02436 // Check to see if we found the value! 02437 if (!Range.contains(cast<SCEVConstant>(Val)->getValue())) 02438 return SCEVConstant::get(TestVal); 02439 02440 // Increment to test the next index. 02441 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One)); 02442 } while (TestVal != EndVal); 02443 02444 return new SCEVCouldNotCompute(); 02445 } 02446 02447 02448 02449 //===----------------------------------------------------------------------===// 02450 // ScalarEvolution Class Implementation 02451 //===----------------------------------------------------------------------===// 02452 02453 bool ScalarEvolution::runOnFunction(Function &F) { 02454 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>()); 02455 return false; 02456 } 02457 02458 void ScalarEvolution::releaseMemory() { 02459 delete (ScalarEvolutionsImpl*)Impl; 02460 Impl = 0; 02461 } 02462 02463 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const { 02464 AU.setPreservesAll(); 02465 AU.addRequiredTransitive<LoopInfo>(); 02466 } 02467 02468 SCEVHandle ScalarEvolution::getSCEV(Value *V) const { 02469 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V); 02470 } 02471 02472 /// hasSCEV - Return true if the SCEV for this value has already been 02473 /// computed. 02474 bool ScalarEvolution::hasSCEV(Value *V) const { 02475 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V); 02476 } 02477 02478 02479 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for 02480 /// the specified value. 02481 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) { 02482 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H); 02483 } 02484 02485 02486 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const { 02487 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L); 02488 } 02489 02490 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const { 02491 return !isa<SCEVCouldNotCompute>(getIterationCount(L)); 02492 } 02493 02494 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const { 02495 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L); 02496 } 02497 02498 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const { 02499 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I); 02500 } 02501 02502 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE, 02503 const Loop *L) { 02504 // Print all inner loops first 02505 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 02506 PrintLoopInfo(OS, SE, *I); 02507 02508 std::cerr << "Loop " << L->getHeader()->getName() << ": "; 02509 02510 std::vector<BasicBlock*> ExitBlocks; 02511 L->getExitBlocks(ExitBlocks); 02512 if (ExitBlocks.size() != 1) 02513 std::cerr << "<multiple exits> "; 02514 02515 if (SE->hasLoopInvariantIterationCount(L)) { 02516 std::cerr << *SE->getIterationCount(L) << " iterations! "; 02517 } else { 02518 std::cerr << "Unpredictable iteration count. "; 02519 } 02520 02521 std::cerr << "\n"; 02522 } 02523 02524 void ScalarEvolution::print(std::ostream &OS, const Module* ) const { 02525 Function &F = ((ScalarEvolutionsImpl*)Impl)->F; 02526 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI; 02527 02528 OS << "Classifying expressions for: " << F.getName() << "\n"; 02529 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) 02530 if (I->getType()->isInteger()) { 02531 OS << *I; 02532 OS << " --> "; 02533 SCEVHandle SV = getSCEV(&*I); 02534 SV->print(OS); 02535 OS << "\t\t"; 02536 02537 if ((*I).getType()->isIntegral()) { 02538 ConstantRange Bounds = SV->getValueRange(); 02539 if (!Bounds.isFullSet()) 02540 OS << "Bounds: " << Bounds << " "; 02541 } 02542 02543 if (const Loop *L = LI.getLoopFor((*I).getParent())) { 02544 OS << "Exits: "; 02545 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop()); 02546 if (isa<SCEVCouldNotCompute>(ExitValue)) { 02547 OS << "<<Unknown>>"; 02548 } else { 02549 OS << *ExitValue; 02550 } 02551 } 02552 02553 02554 OS << "\n"; 02555 } 02556 02557 OS << "Determining loop execution counts for: " << F.getName() << "\n"; 02558 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) 02559 PrintLoopInfo(OS, this, *I); 02560 } 02561