ScalarEvolution.cpp revision 6ee2f3d840fd06f29aa3c5b64a5d0643fd02cef3
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file contains the implementation of the scalar evolution analysis 11// engine, which is used primarily to analyze expressions involving induction 12// variables in loops. 13// 14// There are several aspects to this library. First is the representation of 15// scalar expressions, which are represented as subclasses of the SCEV class. 16// These classes are used to represent certain types of subexpressions that we 17// can handle. These classes are reference counted, managed by the SCEVHandle 18// class. We only create one SCEV of a particular shape, so pointer-comparisons 19// for equality are legal. 20// 21// One important aspect of the SCEV objects is that they are never cyclic, even 22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If 23// the PHI node is one of the idioms that we can represent (e.g., a polynomial 24// recurrence) then we represent it directly as a recurrence node, otherwise we 25// represent it as a SCEVUnknown node. 26// 27// In addition to being able to represent expressions of various types, we also 28// have folders that are used to build the *canonical* representation for a 29// particular expression. These folders are capable of using a variety of 30// rewrite rules to simplify the expressions. 31// 32// Once the folders are defined, we can implement the more interesting 33// higher-level code, such as the code that recognizes PHI nodes of various 34// types, computes the execution count of a loop, etc. 35// 36// TODO: We should use these routines and value representations to implement 37// dependence analysis! 38// 39//===----------------------------------------------------------------------===// 40// 41// There are several good references for the techniques used in this analysis. 42// 43// Chains of recurrences -- a method to expedite the evaluation 44// of closed-form functions 45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima 46// 47// On computational properties of chains of recurrences 48// Eugene V. Zima 49// 50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization 51// Robert A. van Engelen 52// 53// Efficient Symbolic Analysis for Optimizing Compilers 54// Robert A. van Engelen 55// 56// Using the chains of recurrences algebra for data dependence testing and 57// induction variable substitution 58// MS Thesis, Johnie Birch 59// 60//===----------------------------------------------------------------------===// 61 62#define DEBUG_TYPE "scalar-evolution" 63#include "llvm/Analysis/ScalarEvolutionExpressions.h" 64#include "llvm/Constants.h" 65#include "llvm/DerivedTypes.h" 66#include "llvm/GlobalVariable.h" 67#include "llvm/Instructions.h" 68#include "llvm/Analysis/ConstantFolding.h" 69#include "llvm/Analysis/Dominators.h" 70#include "llvm/Analysis/LoopInfo.h" 71#include "llvm/Assembly/Writer.h" 72#include "llvm/Target/TargetData.h" 73#include "llvm/Support/CommandLine.h" 74#include "llvm/Support/Compiler.h" 75#include "llvm/Support/ConstantRange.h" 76#include "llvm/Support/GetElementPtrTypeIterator.h" 77#include "llvm/Support/InstIterator.h" 78#include "llvm/Support/ManagedStatic.h" 79#include "llvm/Support/MathExtras.h" 80#include "llvm/Support/raw_ostream.h" 81#include "llvm/ADT/Statistic.h" 82#include "llvm/ADT/STLExtras.h" 83#include <ostream> 84#include <algorithm> 85using namespace llvm; 86 87STATISTIC(NumArrayLenItCounts, 88 "Number of trip counts computed with array length"); 89STATISTIC(NumTripCountsComputed, 90 "Number of loops with predictable loop counts"); 91STATISTIC(NumTripCountsNotComputed, 92 "Number of loops without predictable loop counts"); 93STATISTIC(NumBruteForceTripCountsComputed, 94 "Number of loops with trip counts computed by force"); 95 96static cl::opt<unsigned> 97MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 98 cl::desc("Maximum number of iterations SCEV will " 99 "symbolically execute a constant derived loop"), 100 cl::init(100)); 101 102static RegisterPass<ScalarEvolution> 103R("scalar-evolution", "Scalar Evolution Analysis", false, true); 104char ScalarEvolution::ID = 0; 105 106//===----------------------------------------------------------------------===// 107// SCEV class definitions 108//===----------------------------------------------------------------------===// 109 110//===----------------------------------------------------------------------===// 111// Implementation of the SCEV class. 112// 113SCEV::~SCEV() {} 114void SCEV::dump() const { 115 print(errs()); 116 errs() << '\n'; 117} 118 119void SCEV::print(std::ostream &o) const { 120 raw_os_ostream OS(o); 121 print(OS); 122} 123 124bool SCEV::isZero() const { 125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 126 return SC->getValue()->isZero(); 127 return false; 128} 129 130 131SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {} 132SCEVCouldNotCompute::~SCEVCouldNotCompute() {} 133 134bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const { 135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 136 return false; 137} 138 139const Type *SCEVCouldNotCompute::getType() const { 140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 141 return 0; 142} 143 144bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const { 145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 146 return false; 147} 148 149SCEVHandle SCEVCouldNotCompute:: 150replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 151 const SCEVHandle &Conc, 152 ScalarEvolution &SE) const { 153 return this; 154} 155 156void SCEVCouldNotCompute::print(raw_ostream &OS) const { 157 OS << "***COULDNOTCOMPUTE***"; 158} 159 160bool SCEVCouldNotCompute::classof(const SCEV *S) { 161 return S->getSCEVType() == scCouldNotCompute; 162} 163 164 165// SCEVConstants - Only allow the creation of one SCEVConstant for any 166// particular value. Don't use a SCEVHandle here, or else the object will 167// never be deleted! 168static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants; 169 170 171SCEVConstant::~SCEVConstant() { 172 SCEVConstants->erase(V); 173} 174 175SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) { 176 SCEVConstant *&R = (*SCEVConstants)[V]; 177 if (R == 0) R = new SCEVConstant(V); 178 return R; 179} 180 181SCEVHandle ScalarEvolution::getConstant(const APInt& Val) { 182 return getConstant(ConstantInt::get(Val)); 183} 184 185const Type *SCEVConstant::getType() const { return V->getType(); } 186 187void SCEVConstant::print(raw_ostream &OS) const { 188 WriteAsOperand(OS, V, false); 189} 190 191SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy, 192 const SCEVHandle &op, const Type *ty) 193 : SCEV(SCEVTy), Op(op), Ty(ty) {} 194 195SCEVCastExpr::~SCEVCastExpr() {} 196 197bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const { 198 return Op->dominates(BB, DT); 199} 200 201// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any 202// particular input. Don't use a SCEVHandle here, or else the object will 203// never be deleted! 204static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>, 205 SCEVTruncateExpr*> > SCEVTruncates; 206 207SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty) 208 : SCEVCastExpr(scTruncate, op, ty) { 209 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) && 210 (Ty->isInteger() || isa<PointerType>(Ty)) && 211 "Cannot truncate non-integer value!"); 212} 213 214SCEVTruncateExpr::~SCEVTruncateExpr() { 215 SCEVTruncates->erase(std::make_pair(Op, Ty)); 216} 217 218void SCEVTruncateExpr::print(raw_ostream &OS) const { 219 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")"; 220} 221 222// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any 223// particular input. Don't use a SCEVHandle here, or else the object will never 224// be deleted! 225static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>, 226 SCEVZeroExtendExpr*> > SCEVZeroExtends; 227 228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty) 229 : SCEVCastExpr(scZeroExtend, op, ty) { 230 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) && 231 (Ty->isInteger() || isa<PointerType>(Ty)) && 232 "Cannot zero extend non-integer value!"); 233} 234 235SCEVZeroExtendExpr::~SCEVZeroExtendExpr() { 236 SCEVZeroExtends->erase(std::make_pair(Op, Ty)); 237} 238 239void SCEVZeroExtendExpr::print(raw_ostream &OS) const { 240 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")"; 241} 242 243// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any 244// particular input. Don't use a SCEVHandle here, or else the object will never 245// be deleted! 246static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>, 247 SCEVSignExtendExpr*> > SCEVSignExtends; 248 249SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty) 250 : SCEVCastExpr(scSignExtend, op, ty) { 251 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) && 252 (Ty->isInteger() || isa<PointerType>(Ty)) && 253 "Cannot sign extend non-integer value!"); 254} 255 256SCEVSignExtendExpr::~SCEVSignExtendExpr() { 257 SCEVSignExtends->erase(std::make_pair(Op, Ty)); 258} 259 260void SCEVSignExtendExpr::print(raw_ostream &OS) const { 261 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")"; 262} 263 264// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any 265// particular input. Don't use a SCEVHandle here, or else the object will never 266// be deleted! 267static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >, 268 SCEVCommutativeExpr*> > SCEVCommExprs; 269 270SCEVCommutativeExpr::~SCEVCommutativeExpr() { 271 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end()); 272 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps)); 273} 274 275void SCEVCommutativeExpr::print(raw_ostream &OS) const { 276 assert(Operands.size() > 1 && "This plus expr shouldn't exist!"); 277 const char *OpStr = getOperationStr(); 278 OS << "(" << *Operands[0]; 279 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 280 OS << OpStr << *Operands[i]; 281 OS << ")"; 282} 283 284SCEVHandle SCEVCommutativeExpr:: 285replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 286 const SCEVHandle &Conc, 287 ScalarEvolution &SE) const { 288 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 289 SCEVHandle H = 290 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE); 291 if (H != getOperand(i)) { 292 std::vector<SCEVHandle> NewOps; 293 NewOps.reserve(getNumOperands()); 294 for (unsigned j = 0; j != i; ++j) 295 NewOps.push_back(getOperand(j)); 296 NewOps.push_back(H); 297 for (++i; i != e; ++i) 298 NewOps.push_back(getOperand(i)-> 299 replaceSymbolicValuesWithConcrete(Sym, Conc, SE)); 300 301 if (isa<SCEVAddExpr>(this)) 302 return SE.getAddExpr(NewOps); 303 else if (isa<SCEVMulExpr>(this)) 304 return SE.getMulExpr(NewOps); 305 else if (isa<SCEVSMaxExpr>(this)) 306 return SE.getSMaxExpr(NewOps); 307 else if (isa<SCEVUMaxExpr>(this)) 308 return SE.getUMaxExpr(NewOps); 309 else 310 assert(0 && "Unknown commutative expr!"); 311 } 312 } 313 return this; 314} 315 316bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const { 317 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 318 if (!getOperand(i)->dominates(BB, DT)) 319 return false; 320 } 321 return true; 322} 323 324 325// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular 326// input. Don't use a SCEVHandle here, or else the object will never be 327// deleted! 328static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>, 329 SCEVUDivExpr*> > SCEVUDivs; 330 331SCEVUDivExpr::~SCEVUDivExpr() { 332 SCEVUDivs->erase(std::make_pair(LHS, RHS)); 333} 334 335bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const { 336 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT); 337} 338 339void SCEVUDivExpr::print(raw_ostream &OS) const { 340 OS << "(" << *LHS << " /u " << *RHS << ")"; 341} 342 343const Type *SCEVUDivExpr::getType() const { 344 return LHS->getType(); 345} 346 347// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any 348// particular input. Don't use a SCEVHandle here, or else the object will never 349// be deleted! 350static ManagedStatic<std::map<std::pair<const Loop *, 351 std::vector<const SCEV*> >, 352 SCEVAddRecExpr*> > SCEVAddRecExprs; 353 354SCEVAddRecExpr::~SCEVAddRecExpr() { 355 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end()); 356 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps)); 357} 358 359SCEVHandle SCEVAddRecExpr:: 360replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 361 const SCEVHandle &Conc, 362 ScalarEvolution &SE) const { 363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 364 SCEVHandle H = 365 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE); 366 if (H != getOperand(i)) { 367 std::vector<SCEVHandle> NewOps; 368 NewOps.reserve(getNumOperands()); 369 for (unsigned j = 0; j != i; ++j) 370 NewOps.push_back(getOperand(j)); 371 NewOps.push_back(H); 372 for (++i; i != e; ++i) 373 NewOps.push_back(getOperand(i)-> 374 replaceSymbolicValuesWithConcrete(Sym, Conc, SE)); 375 376 return SE.getAddRecExpr(NewOps, L); 377 } 378 } 379 return this; 380} 381 382 383bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const { 384 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't 385 // contain L and if the start is invariant. 386 return !QueryLoop->contains(L->getHeader()) && 387 getOperand(0)->isLoopInvariant(QueryLoop); 388} 389 390 391void SCEVAddRecExpr::print(raw_ostream &OS) const { 392 OS << "{" << *Operands[0]; 393 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 394 OS << ",+," << *Operands[i]; 395 OS << "}<" << L->getHeader()->getName() + ">"; 396} 397 398// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular 399// value. Don't use a SCEVHandle here, or else the object will never be 400// deleted! 401static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns; 402 403SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); } 404 405bool SCEVUnknown::isLoopInvariant(const Loop *L) const { 406 // All non-instruction values are loop invariant. All instructions are loop 407 // invariant if they are not contained in the specified loop. 408 if (Instruction *I = dyn_cast<Instruction>(V)) 409 return !L->contains(I->getParent()); 410 return true; 411} 412 413bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const { 414 if (Instruction *I = dyn_cast<Instruction>(getValue())) 415 return DT->dominates(I->getParent(), BB); 416 return true; 417} 418 419const Type *SCEVUnknown::getType() const { 420 return V->getType(); 421} 422 423void SCEVUnknown::print(raw_ostream &OS) const { 424 WriteAsOperand(OS, V, false); 425} 426 427//===----------------------------------------------------------------------===// 428// SCEV Utilities 429//===----------------------------------------------------------------------===// 430 431namespace { 432 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less 433 /// than the complexity of the RHS. This comparator is used to canonicalize 434 /// expressions. 435 struct VISIBILITY_HIDDEN SCEVComplexityCompare { 436 bool operator()(const SCEV *LHS, const SCEV *RHS) const { 437 return LHS->getSCEVType() < RHS->getSCEVType(); 438 } 439 }; 440} 441 442/// GroupByComplexity - Given a list of SCEV objects, order them by their 443/// complexity, and group objects of the same complexity together by value. 444/// When this routine is finished, we know that any duplicates in the vector are 445/// consecutive and that complexity is monotonically increasing. 446/// 447/// Note that we go take special precautions to ensure that we get determinstic 448/// results from this routine. In other words, we don't want the results of 449/// this to depend on where the addresses of various SCEV objects happened to 450/// land in memory. 451/// 452static void GroupByComplexity(std::vector<SCEVHandle> &Ops) { 453 if (Ops.size() < 2) return; // Noop 454 if (Ops.size() == 2) { 455 // This is the common case, which also happens to be trivially simple. 456 // Special case it. 457 if (SCEVComplexityCompare()(Ops[1], Ops[0])) 458 std::swap(Ops[0], Ops[1]); 459 return; 460 } 461 462 // Do the rough sort by complexity. 463 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare()); 464 465 // Now that we are sorted by complexity, group elements of the same 466 // complexity. Note that this is, at worst, N^2, but the vector is likely to 467 // be extremely short in practice. Note that we take this approach because we 468 // do not want to depend on the addresses of the objects we are grouping. 469 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 470 const SCEV *S = Ops[i]; 471 unsigned Complexity = S->getSCEVType(); 472 473 // If there are any objects of the same complexity and same value as this 474 // one, group them. 475 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 476 if (Ops[j] == S) { // Found a duplicate. 477 // Move it to immediately after i'th element. 478 std::swap(Ops[i+1], Ops[j]); 479 ++i; // no need to rescan it. 480 if (i == e-2) return; // Done! 481 } 482 } 483 } 484} 485 486 487 488//===----------------------------------------------------------------------===// 489// Simple SCEV method implementations 490//===----------------------------------------------------------------------===// 491 492/// BinomialCoefficient - Compute BC(It, K). The result has width W. 493// Assume, K > 0. 494static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K, 495 ScalarEvolution &SE, 496 const Type* ResultTy) { 497 // Handle the simplest case efficiently. 498 if (K == 1) 499 return SE.getTruncateOrZeroExtend(It, ResultTy); 500 501 // We are using the following formula for BC(It, K): 502 // 503 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 504 // 505 // Suppose, W is the bitwidth of the return value. We must be prepared for 506 // overflow. Hence, we must assure that the result of our computation is 507 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 508 // safe in modular arithmetic. 509 // 510 // However, this code doesn't use exactly that formula; the formula it uses 511 // is something like the following, where T is the number of factors of 2 in 512 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 513 // exponentiation: 514 // 515 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 516 // 517 // This formula is trivially equivalent to the previous formula. However, 518 // this formula can be implemented much more efficiently. The trick is that 519 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 520 // arithmetic. To do exact division in modular arithmetic, all we have 521 // to do is multiply by the inverse. Therefore, this step can be done at 522 // width W. 523 // 524 // The next issue is how to safely do the division by 2^T. The way this 525 // is done is by doing the multiplication step at a width of at least W + T 526 // bits. This way, the bottom W+T bits of the product are accurate. Then, 527 // when we perform the division by 2^T (which is equivalent to a right shift 528 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 529 // truncated out after the division by 2^T. 530 // 531 // In comparison to just directly using the first formula, this technique 532 // is much more efficient; using the first formula requires W * K bits, 533 // but this formula less than W + K bits. Also, the first formula requires 534 // a division step, whereas this formula only requires multiplies and shifts. 535 // 536 // It doesn't matter whether the subtraction step is done in the calculation 537 // width or the input iteration count's width; if the subtraction overflows, 538 // the result must be zero anyway. We prefer here to do it in the width of 539 // the induction variable because it helps a lot for certain cases; CodeGen 540 // isn't smart enough to ignore the overflow, which leads to much less 541 // efficient code if the width of the subtraction is wider than the native 542 // register width. 543 // 544 // (It's possible to not widen at all by pulling out factors of 2 before 545 // the multiplication; for example, K=2 can be calculated as 546 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 547 // extra arithmetic, so it's not an obvious win, and it gets 548 // much more complicated for K > 3.) 549 550 // Protection from insane SCEVs; this bound is conservative, 551 // but it probably doesn't matter. 552 if (K > 1000) 553 return SE.getCouldNotCompute(); 554 555 unsigned W = SE.getTypeSizeInBits(ResultTy); 556 557 // Calculate K! / 2^T and T; we divide out the factors of two before 558 // multiplying for calculating K! / 2^T to avoid overflow. 559 // Other overflow doesn't matter because we only care about the bottom 560 // W bits of the result. 561 APInt OddFactorial(W, 1); 562 unsigned T = 1; 563 for (unsigned i = 3; i <= K; ++i) { 564 APInt Mult(W, i); 565 unsigned TwoFactors = Mult.countTrailingZeros(); 566 T += TwoFactors; 567 Mult = Mult.lshr(TwoFactors); 568 OddFactorial *= Mult; 569 } 570 571 // We need at least W + T bits for the multiplication step 572 unsigned CalculationBits = W + T; 573 574 // Calcuate 2^T, at width T+W. 575 APInt DivFactor = APInt(CalculationBits, 1).shl(T); 576 577 // Calculate the multiplicative inverse of K! / 2^T; 578 // this multiplication factor will perform the exact division by 579 // K! / 2^T. 580 APInt Mod = APInt::getSignedMinValue(W+1); 581 APInt MultiplyFactor = OddFactorial.zext(W+1); 582 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 583 MultiplyFactor = MultiplyFactor.trunc(W); 584 585 // Calculate the product, at width T+W 586 const IntegerType *CalculationTy = IntegerType::get(CalculationBits); 587 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 588 for (unsigned i = 1; i != K; ++i) { 589 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType())); 590 Dividend = SE.getMulExpr(Dividend, 591 SE.getTruncateOrZeroExtend(S, CalculationTy)); 592 } 593 594 // Divide by 2^T 595 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 596 597 // Truncate the result, and divide by K! / 2^T. 598 599 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 600 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 601} 602 603/// evaluateAtIteration - Return the value of this chain of recurrences at 604/// the specified iteration number. We can evaluate this recurrence by 605/// multiplying each element in the chain by the binomial coefficient 606/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: 607/// 608/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 609/// 610/// where BC(It, k) stands for binomial coefficient. 611/// 612SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It, 613 ScalarEvolution &SE) const { 614 SCEVHandle Result = getStart(); 615 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 616 // The computation is correct in the face of overflow provided that the 617 // multiplication is performed _after_ the evaluation of the binomial 618 // coefficient. 619 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType()); 620 if (isa<SCEVCouldNotCompute>(Coeff)) 621 return Coeff; 622 623 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 624 } 625 return Result; 626} 627 628//===----------------------------------------------------------------------===// 629// SCEV Expression folder implementations 630//===----------------------------------------------------------------------===// 631 632SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, 633 const Type *Ty) { 634 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 635 "This is not a truncating conversion!"); 636 assert(isSCEVable(Ty) && 637 "This is not a conversion to a SCEVable type!"); 638 Ty = getEffectiveSCEVType(Ty); 639 640 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 641 return getUnknown( 642 ConstantExpr::getTrunc(SC->getValue(), Ty)); 643 644 // trunc(trunc(x)) --> trunc(x) 645 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 646 return getTruncateExpr(ST->getOperand(), Ty); 647 648 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 649 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 650 return getTruncateOrSignExtend(SS->getOperand(), Ty); 651 652 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 653 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 654 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 655 656 // If the input value is a chrec scev made out of constants, truncate 657 // all of the constants. 658 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 659 std::vector<SCEVHandle> Operands; 660 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 661 // FIXME: This should allow truncation of other expression types! 662 if (isa<SCEVConstant>(AddRec->getOperand(i))) 663 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty)); 664 else 665 break; 666 if (Operands.size() == AddRec->getNumOperands()) 667 return getAddRecExpr(Operands, AddRec->getLoop()); 668 } 669 670 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)]; 671 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty); 672 return Result; 673} 674 675SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, 676 const Type *Ty) { 677 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 678 "This is not an extending conversion!"); 679 assert(isSCEVable(Ty) && 680 "This is not a conversion to a SCEVable type!"); 681 Ty = getEffectiveSCEVType(Ty); 682 683 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) { 684 const Type *IntTy = getEffectiveSCEVType(Ty); 685 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy); 686 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty); 687 return getUnknown(C); 688 } 689 690 // zext(zext(x)) --> zext(x) 691 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 692 return getZeroExtendExpr(SZ->getOperand(), Ty); 693 694 // If the input value is a chrec scev, and we can prove that the value 695 // did not overflow the old, smaller, value, we can zero extend all of the 696 // operands (often constants). This allows analysis of something like 697 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 698 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 699 if (AR->isAffine()) { 700 // Check whether the backedge-taken count is SCEVCouldNotCompute. 701 // Note that this serves two purposes: It filters out loops that are 702 // simply not analyzable, and it covers the case where this code is 703 // being called from within backedge-taken count analysis, such that 704 // attempting to ask for the backedge-taken count would likely result 705 // in infinite recursion. In the later case, the analysis code will 706 // cope with a conservative value, and it will take care to purge 707 // that value once it has finished. 708 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop()); 709 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 710 // Manually compute the final value for AR, checking for 711 // overflow. 712 SCEVHandle Start = AR->getStart(); 713 SCEVHandle Step = AR->getStepRecurrence(*this); 714 715 // Check whether the backedge-taken count can be losslessly casted to 716 // the addrec's type. The count is always unsigned. 717 SCEVHandle CastedMaxBECount = 718 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 719 if (MaxBECount == 720 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) { 721 const Type *WideTy = 722 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2); 723 // Check whether Start+Step*MaxBECount has no unsigned overflow. 724 SCEVHandle ZMul = 725 getMulExpr(CastedMaxBECount, 726 getTruncateOrZeroExtend(Step, Start->getType())); 727 SCEVHandle Add = getAddExpr(Start, ZMul); 728 if (getZeroExtendExpr(Add, WideTy) == 729 getAddExpr(getZeroExtendExpr(Start, WideTy), 730 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 731 getZeroExtendExpr(Step, WideTy)))) 732 // Return the expression with the addrec on the outside. 733 return getAddRecExpr(getZeroExtendExpr(Start, Ty), 734 getZeroExtendExpr(Step, Ty), 735 AR->getLoop()); 736 737 // Similar to above, only this time treat the step value as signed. 738 // This covers loops that count down. 739 SCEVHandle SMul = 740 getMulExpr(CastedMaxBECount, 741 getTruncateOrSignExtend(Step, Start->getType())); 742 Add = getAddExpr(Start, SMul); 743 if (getZeroExtendExpr(Add, WideTy) == 744 getAddExpr(getZeroExtendExpr(Start, WideTy), 745 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 746 getSignExtendExpr(Step, WideTy)))) 747 // Return the expression with the addrec on the outside. 748 return getAddRecExpr(getZeroExtendExpr(Start, Ty), 749 getSignExtendExpr(Step, Ty), 750 AR->getLoop()); 751 } 752 } 753 } 754 755 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)]; 756 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty); 757 return Result; 758} 759 760SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, 761 const Type *Ty) { 762 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 763 "This is not an extending conversion!"); 764 assert(isSCEVable(Ty) && 765 "This is not a conversion to a SCEVable type!"); 766 Ty = getEffectiveSCEVType(Ty); 767 768 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) { 769 const Type *IntTy = getEffectiveSCEVType(Ty); 770 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy); 771 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty); 772 return getUnknown(C); 773 } 774 775 // sext(sext(x)) --> sext(x) 776 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 777 return getSignExtendExpr(SS->getOperand(), Ty); 778 779 // If the input value is a chrec scev, and we can prove that the value 780 // did not overflow the old, smaller, value, we can sign extend all of the 781 // operands (often constants). This allows analysis of something like 782 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 783 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 784 if (AR->isAffine()) { 785 // Check whether the backedge-taken count is SCEVCouldNotCompute. 786 // Note that this serves two purposes: It filters out loops that are 787 // simply not analyzable, and it covers the case where this code is 788 // being called from within backedge-taken count analysis, such that 789 // attempting to ask for the backedge-taken count would likely result 790 // in infinite recursion. In the later case, the analysis code will 791 // cope with a conservative value, and it will take care to purge 792 // that value once it has finished. 793 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop()); 794 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 795 // Manually compute the final value for AR, checking for 796 // overflow. 797 SCEVHandle Start = AR->getStart(); 798 SCEVHandle Step = AR->getStepRecurrence(*this); 799 800 // Check whether the backedge-taken count can be losslessly casted to 801 // the addrec's type. The count is always unsigned. 802 SCEVHandle CastedMaxBECount = 803 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 804 if (MaxBECount == 805 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) { 806 const Type *WideTy = 807 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2); 808 // Check whether Start+Step*MaxBECount has no signed overflow. 809 SCEVHandle SMul = 810 getMulExpr(CastedMaxBECount, 811 getTruncateOrSignExtend(Step, Start->getType())); 812 SCEVHandle Add = getAddExpr(Start, SMul); 813 if (getSignExtendExpr(Add, WideTy) == 814 getAddExpr(getSignExtendExpr(Start, WideTy), 815 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 816 getSignExtendExpr(Step, WideTy)))) 817 // Return the expression with the addrec on the outside. 818 return getAddRecExpr(getSignExtendExpr(Start, Ty), 819 getSignExtendExpr(Step, Ty), 820 AR->getLoop()); 821 } 822 } 823 } 824 825 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)]; 826 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty); 827 return Result; 828} 829 830// get - Get a canonical add expression, or something simpler if possible. 831SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) { 832 assert(!Ops.empty() && "Cannot get empty add!"); 833 if (Ops.size() == 1) return Ops[0]; 834 835 // Sort by complexity, this groups all similar expression types together. 836 GroupByComplexity(Ops); 837 838 // If there are any constants, fold them together. 839 unsigned Idx = 0; 840 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 841 ++Idx; 842 assert(Idx < Ops.size()); 843 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 844 // We found two constants, fold them together! 845 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() + 846 RHSC->getValue()->getValue()); 847 Ops[0] = getConstant(Fold); 848 Ops.erase(Ops.begin()+1); // Erase the folded element 849 if (Ops.size() == 1) return Ops[0]; 850 LHSC = cast<SCEVConstant>(Ops[0]); 851 } 852 853 // If we are left with a constant zero being added, strip it off. 854 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 855 Ops.erase(Ops.begin()); 856 --Idx; 857 } 858 } 859 860 if (Ops.size() == 1) return Ops[0]; 861 862 // Okay, check to see if the same value occurs in the operand list twice. If 863 // so, merge them together into an multiply expression. Since we sorted the 864 // list, these values are required to be adjacent. 865 const Type *Ty = Ops[0]->getType(); 866 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 867 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 868 // Found a match, merge the two values into a multiply, and add any 869 // remaining values to the result. 870 SCEVHandle Two = getIntegerSCEV(2, Ty); 871 SCEVHandle Mul = getMulExpr(Ops[i], Two); 872 if (Ops.size() == 2) 873 return Mul; 874 Ops.erase(Ops.begin()+i, Ops.begin()+i+2); 875 Ops.push_back(Mul); 876 return getAddExpr(Ops); 877 } 878 879 // Now we know the first non-constant operand. Skip past any cast SCEVs. 880 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 881 ++Idx; 882 883 // If there are add operands they would be next. 884 if (Idx < Ops.size()) { 885 bool DeletedAdd = false; 886 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 887 // If we have an add, expand the add operands onto the end of the operands 888 // list. 889 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end()); 890 Ops.erase(Ops.begin()+Idx); 891 DeletedAdd = true; 892 } 893 894 // If we deleted at least one add, we added operands to the end of the list, 895 // and they are not necessarily sorted. Recurse to resort and resimplify 896 // any operands we just aquired. 897 if (DeletedAdd) 898 return getAddExpr(Ops); 899 } 900 901 // Skip over the add expression until we get to a multiply. 902 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 903 ++Idx; 904 905 // If we are adding something to a multiply expression, make sure the 906 // something is not already an operand of the multiply. If so, merge it into 907 // the multiply. 908 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 909 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 910 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 911 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 912 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 913 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) { 914 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 915 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0); 916 if (Mul->getNumOperands() != 2) { 917 // If the multiply has more than two operands, we must get the 918 // Y*Z term. 919 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); 920 MulOps.erase(MulOps.begin()+MulOp); 921 InnerMul = getMulExpr(MulOps); 922 } 923 SCEVHandle One = getIntegerSCEV(1, Ty); 924 SCEVHandle AddOne = getAddExpr(InnerMul, One); 925 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]); 926 if (Ops.size() == 2) return OuterMul; 927 if (AddOp < Idx) { 928 Ops.erase(Ops.begin()+AddOp); 929 Ops.erase(Ops.begin()+Idx-1); 930 } else { 931 Ops.erase(Ops.begin()+Idx); 932 Ops.erase(Ops.begin()+AddOp-1); 933 } 934 Ops.push_back(OuterMul); 935 return getAddExpr(Ops); 936 } 937 938 // Check this multiply against other multiplies being added together. 939 for (unsigned OtherMulIdx = Idx+1; 940 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 941 ++OtherMulIdx) { 942 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 943 // If MulOp occurs in OtherMul, we can fold the two multiplies 944 // together. 945 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 946 OMulOp != e; ++OMulOp) 947 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 948 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 949 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0); 950 if (Mul->getNumOperands() != 2) { 951 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); 952 MulOps.erase(MulOps.begin()+MulOp); 953 InnerMul1 = getMulExpr(MulOps); 954 } 955 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0); 956 if (OtherMul->getNumOperands() != 2) { 957 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(), 958 OtherMul->op_end()); 959 MulOps.erase(MulOps.begin()+OMulOp); 960 InnerMul2 = getMulExpr(MulOps); 961 } 962 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 963 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 964 if (Ops.size() == 2) return OuterMul; 965 Ops.erase(Ops.begin()+Idx); 966 Ops.erase(Ops.begin()+OtherMulIdx-1); 967 Ops.push_back(OuterMul); 968 return getAddExpr(Ops); 969 } 970 } 971 } 972 } 973 974 // If there are any add recurrences in the operands list, see if any other 975 // added values are loop invariant. If so, we can fold them into the 976 // recurrence. 977 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 978 ++Idx; 979 980 // Scan over all recurrences, trying to fold loop invariants into them. 981 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 982 // Scan all of the other operands to this add and add them to the vector if 983 // they are loop invariant w.r.t. the recurrence. 984 std::vector<SCEVHandle> LIOps; 985 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 986 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 987 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 988 LIOps.push_back(Ops[i]); 989 Ops.erase(Ops.begin()+i); 990 --i; --e; 991 } 992 993 // If we found some loop invariants, fold them into the recurrence. 994 if (!LIOps.empty()) { 995 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 996 LIOps.push_back(AddRec->getStart()); 997 998 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end()); 999 AddRecOps[0] = getAddExpr(LIOps); 1000 1001 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop()); 1002 // If all of the other operands were loop invariant, we are done. 1003 if (Ops.size() == 1) return NewRec; 1004 1005 // Otherwise, add the folded AddRec by the non-liv parts. 1006 for (unsigned i = 0;; ++i) 1007 if (Ops[i] == AddRec) { 1008 Ops[i] = NewRec; 1009 break; 1010 } 1011 return getAddExpr(Ops); 1012 } 1013 1014 // Okay, if there weren't any loop invariants to be folded, check to see if 1015 // there are multiple AddRec's with the same loop induction variable being 1016 // added together. If so, we can fold them. 1017 for (unsigned OtherIdx = Idx+1; 1018 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 1019 if (OtherIdx != Idx) { 1020 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 1021 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 1022 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D} 1023 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end()); 1024 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) { 1025 if (i >= NewOps.size()) { 1026 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i, 1027 OtherAddRec->op_end()); 1028 break; 1029 } 1030 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i)); 1031 } 1032 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop()); 1033 1034 if (Ops.size() == 2) return NewAddRec; 1035 1036 Ops.erase(Ops.begin()+Idx); 1037 Ops.erase(Ops.begin()+OtherIdx-1); 1038 Ops.push_back(NewAddRec); 1039 return getAddExpr(Ops); 1040 } 1041 } 1042 1043 // Otherwise couldn't fold anything into this recurrence. Move onto the 1044 // next one. 1045 } 1046 1047 // Okay, it looks like we really DO need an add expr. Check to see if we 1048 // already have one, otherwise create a new one. 1049 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end()); 1050 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr, 1051 SCEVOps)]; 1052 if (Result == 0) Result = new SCEVAddExpr(Ops); 1053 return Result; 1054} 1055 1056 1057SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) { 1058 assert(!Ops.empty() && "Cannot get empty mul!"); 1059 1060 // Sort by complexity, this groups all similar expression types together. 1061 GroupByComplexity(Ops); 1062 1063 // If there are any constants, fold them together. 1064 unsigned Idx = 0; 1065 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1066 1067 // C1*(C2+V) -> C1*C2 + C1*V 1068 if (Ops.size() == 2) 1069 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 1070 if (Add->getNumOperands() == 2 && 1071 isa<SCEVConstant>(Add->getOperand(0))) 1072 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 1073 getMulExpr(LHSC, Add->getOperand(1))); 1074 1075 1076 ++Idx; 1077 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1078 // We found two constants, fold them together! 1079 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() * 1080 RHSC->getValue()->getValue()); 1081 Ops[0] = getConstant(Fold); 1082 Ops.erase(Ops.begin()+1); // Erase the folded element 1083 if (Ops.size() == 1) return Ops[0]; 1084 LHSC = cast<SCEVConstant>(Ops[0]); 1085 } 1086 1087 // If we are left with a constant one being multiplied, strip it off. 1088 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 1089 Ops.erase(Ops.begin()); 1090 --Idx; 1091 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 1092 // If we have a multiply of zero, it will always be zero. 1093 return Ops[0]; 1094 } 1095 } 1096 1097 // Skip over the add expression until we get to a multiply. 1098 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 1099 ++Idx; 1100 1101 if (Ops.size() == 1) 1102 return Ops[0]; 1103 1104 // If there are mul operands inline them all into this expression. 1105 if (Idx < Ops.size()) { 1106 bool DeletedMul = false; 1107 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 1108 // If we have an mul, expand the mul operands onto the end of the operands 1109 // list. 1110 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end()); 1111 Ops.erase(Ops.begin()+Idx); 1112 DeletedMul = true; 1113 } 1114 1115 // If we deleted at least one mul, we added operands to the end of the list, 1116 // and they are not necessarily sorted. Recurse to resort and resimplify 1117 // any operands we just aquired. 1118 if (DeletedMul) 1119 return getMulExpr(Ops); 1120 } 1121 1122 // If there are any add recurrences in the operands list, see if any other 1123 // added values are loop invariant. If so, we can fold them into the 1124 // recurrence. 1125 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 1126 ++Idx; 1127 1128 // Scan over all recurrences, trying to fold loop invariants into them. 1129 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 1130 // Scan all of the other operands to this mul and add them to the vector if 1131 // they are loop invariant w.r.t. the recurrence. 1132 std::vector<SCEVHandle> LIOps; 1133 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 1134 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1135 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 1136 LIOps.push_back(Ops[i]); 1137 Ops.erase(Ops.begin()+i); 1138 --i; --e; 1139 } 1140 1141 // If we found some loop invariants, fold them into the recurrence. 1142 if (!LIOps.empty()) { 1143 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 1144 std::vector<SCEVHandle> NewOps; 1145 NewOps.reserve(AddRec->getNumOperands()); 1146 if (LIOps.size() == 1) { 1147 const SCEV *Scale = LIOps[0]; 1148 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 1149 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 1150 } else { 1151 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 1152 std::vector<SCEVHandle> MulOps(LIOps); 1153 MulOps.push_back(AddRec->getOperand(i)); 1154 NewOps.push_back(getMulExpr(MulOps)); 1155 } 1156 } 1157 1158 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop()); 1159 1160 // If all of the other operands were loop invariant, we are done. 1161 if (Ops.size() == 1) return NewRec; 1162 1163 // Otherwise, multiply the folded AddRec by the non-liv parts. 1164 for (unsigned i = 0;; ++i) 1165 if (Ops[i] == AddRec) { 1166 Ops[i] = NewRec; 1167 break; 1168 } 1169 return getMulExpr(Ops); 1170 } 1171 1172 // Okay, if there weren't any loop invariants to be folded, check to see if 1173 // there are multiple AddRec's with the same loop induction variable being 1174 // multiplied together. If so, we can fold them. 1175 for (unsigned OtherIdx = Idx+1; 1176 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 1177 if (OtherIdx != Idx) { 1178 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 1179 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 1180 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D} 1181 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec; 1182 SCEVHandle NewStart = getMulExpr(F->getStart(), 1183 G->getStart()); 1184 SCEVHandle B = F->getStepRecurrence(*this); 1185 SCEVHandle D = G->getStepRecurrence(*this); 1186 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D), 1187 getMulExpr(G, B), 1188 getMulExpr(B, D)); 1189 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep, 1190 F->getLoop()); 1191 if (Ops.size() == 2) return NewAddRec; 1192 1193 Ops.erase(Ops.begin()+Idx); 1194 Ops.erase(Ops.begin()+OtherIdx-1); 1195 Ops.push_back(NewAddRec); 1196 return getMulExpr(Ops); 1197 } 1198 } 1199 1200 // Otherwise couldn't fold anything into this recurrence. Move onto the 1201 // next one. 1202 } 1203 1204 // Okay, it looks like we really DO need an mul expr. Check to see if we 1205 // already have one, otherwise create a new one. 1206 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end()); 1207 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr, 1208 SCEVOps)]; 1209 if (Result == 0) 1210 Result = new SCEVMulExpr(Ops); 1211 return Result; 1212} 1213 1214SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, 1215 const SCEVHandle &RHS) { 1216 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 1217 if (RHSC->getValue()->equalsInt(1)) 1218 return LHS; // X udiv 1 --> x 1219 1220 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 1221 Constant *LHSCV = LHSC->getValue(); 1222 Constant *RHSCV = RHSC->getValue(); 1223 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV)); 1224 } 1225 } 1226 1227 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow. 1228 1229 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)]; 1230 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS); 1231 return Result; 1232} 1233 1234 1235/// SCEVAddRecExpr::get - Get a add recurrence expression for the 1236/// specified loop. Simplify the expression as much as possible. 1237SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start, 1238 const SCEVHandle &Step, const Loop *L) { 1239 std::vector<SCEVHandle> Operands; 1240 Operands.push_back(Start); 1241 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 1242 if (StepChrec->getLoop() == L) { 1243 Operands.insert(Operands.end(), StepChrec->op_begin(), 1244 StepChrec->op_end()); 1245 return getAddRecExpr(Operands, L); 1246 } 1247 1248 Operands.push_back(Step); 1249 return getAddRecExpr(Operands, L); 1250} 1251 1252/// SCEVAddRecExpr::get - Get a add recurrence expression for the 1253/// specified loop. Simplify the expression as much as possible. 1254SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands, 1255 const Loop *L) { 1256 if (Operands.size() == 1) return Operands[0]; 1257 1258 if (Operands.back()->isZero()) { 1259 Operands.pop_back(); 1260 return getAddRecExpr(Operands, L); // {X,+,0} --> X 1261 } 1262 1263 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 1264 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 1265 const Loop* NestedLoop = NestedAR->getLoop(); 1266 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) { 1267 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(), 1268 NestedAR->op_end()); 1269 SCEVHandle NestedARHandle(NestedAR); 1270 Operands[0] = NestedAR->getStart(); 1271 NestedOperands[0] = getAddRecExpr(Operands, L); 1272 return getAddRecExpr(NestedOperands, NestedLoop); 1273 } 1274 } 1275 1276 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end()); 1277 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)]; 1278 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L); 1279 return Result; 1280} 1281 1282SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS, 1283 const SCEVHandle &RHS) { 1284 std::vector<SCEVHandle> Ops; 1285 Ops.push_back(LHS); 1286 Ops.push_back(RHS); 1287 return getSMaxExpr(Ops); 1288} 1289 1290SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) { 1291 assert(!Ops.empty() && "Cannot get empty smax!"); 1292 if (Ops.size() == 1) return Ops[0]; 1293 1294 // Sort by complexity, this groups all similar expression types together. 1295 GroupByComplexity(Ops); 1296 1297 // If there are any constants, fold them together. 1298 unsigned Idx = 0; 1299 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1300 ++Idx; 1301 assert(Idx < Ops.size()); 1302 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1303 // We found two constants, fold them together! 1304 ConstantInt *Fold = ConstantInt::get( 1305 APIntOps::smax(LHSC->getValue()->getValue(), 1306 RHSC->getValue()->getValue())); 1307 Ops[0] = getConstant(Fold); 1308 Ops.erase(Ops.begin()+1); // Erase the folded element 1309 if (Ops.size() == 1) return Ops[0]; 1310 LHSC = cast<SCEVConstant>(Ops[0]); 1311 } 1312 1313 // If we are left with a constant -inf, strip it off. 1314 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 1315 Ops.erase(Ops.begin()); 1316 --Idx; 1317 } 1318 } 1319 1320 if (Ops.size() == 1) return Ops[0]; 1321 1322 // Find the first SMax 1323 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 1324 ++Idx; 1325 1326 // Check to see if one of the operands is an SMax. If so, expand its operands 1327 // onto our operand list, and recurse to simplify. 1328 if (Idx < Ops.size()) { 1329 bool DeletedSMax = false; 1330 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 1331 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end()); 1332 Ops.erase(Ops.begin()+Idx); 1333 DeletedSMax = true; 1334 } 1335 1336 if (DeletedSMax) 1337 return getSMaxExpr(Ops); 1338 } 1339 1340 // Okay, check to see if the same value occurs in the operand list twice. If 1341 // so, delete one. Since we sorted the list, these values are required to 1342 // be adjacent. 1343 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 1344 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y 1345 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 1346 --i; --e; 1347 } 1348 1349 if (Ops.size() == 1) return Ops[0]; 1350 1351 assert(!Ops.empty() && "Reduced smax down to nothing!"); 1352 1353 // Okay, it looks like we really DO need an smax expr. Check to see if we 1354 // already have one, otherwise create a new one. 1355 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end()); 1356 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr, 1357 SCEVOps)]; 1358 if (Result == 0) Result = new SCEVSMaxExpr(Ops); 1359 return Result; 1360} 1361 1362SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS, 1363 const SCEVHandle &RHS) { 1364 std::vector<SCEVHandle> Ops; 1365 Ops.push_back(LHS); 1366 Ops.push_back(RHS); 1367 return getUMaxExpr(Ops); 1368} 1369 1370SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) { 1371 assert(!Ops.empty() && "Cannot get empty umax!"); 1372 if (Ops.size() == 1) return Ops[0]; 1373 1374 // Sort by complexity, this groups all similar expression types together. 1375 GroupByComplexity(Ops); 1376 1377 // If there are any constants, fold them together. 1378 unsigned Idx = 0; 1379 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1380 ++Idx; 1381 assert(Idx < Ops.size()); 1382 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1383 // We found two constants, fold them together! 1384 ConstantInt *Fold = ConstantInt::get( 1385 APIntOps::umax(LHSC->getValue()->getValue(), 1386 RHSC->getValue()->getValue())); 1387 Ops[0] = getConstant(Fold); 1388 Ops.erase(Ops.begin()+1); // Erase the folded element 1389 if (Ops.size() == 1) return Ops[0]; 1390 LHSC = cast<SCEVConstant>(Ops[0]); 1391 } 1392 1393 // If we are left with a constant zero, strip it off. 1394 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 1395 Ops.erase(Ops.begin()); 1396 --Idx; 1397 } 1398 } 1399 1400 if (Ops.size() == 1) return Ops[0]; 1401 1402 // Find the first UMax 1403 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 1404 ++Idx; 1405 1406 // Check to see if one of the operands is a UMax. If so, expand its operands 1407 // onto our operand list, and recurse to simplify. 1408 if (Idx < Ops.size()) { 1409 bool DeletedUMax = false; 1410 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 1411 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end()); 1412 Ops.erase(Ops.begin()+Idx); 1413 DeletedUMax = true; 1414 } 1415 1416 if (DeletedUMax) 1417 return getUMaxExpr(Ops); 1418 } 1419 1420 // Okay, check to see if the same value occurs in the operand list twice. If 1421 // so, delete one. Since we sorted the list, these values are required to 1422 // be adjacent. 1423 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 1424 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y 1425 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 1426 --i; --e; 1427 } 1428 1429 if (Ops.size() == 1) return Ops[0]; 1430 1431 assert(!Ops.empty() && "Reduced umax down to nothing!"); 1432 1433 // Okay, it looks like we really DO need a umax expr. Check to see if we 1434 // already have one, otherwise create a new one. 1435 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end()); 1436 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr, 1437 SCEVOps)]; 1438 if (Result == 0) Result = new SCEVUMaxExpr(Ops); 1439 return Result; 1440} 1441 1442SCEVHandle ScalarEvolution::getUnknown(Value *V) { 1443 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 1444 return getConstant(CI); 1445 if (isa<ConstantPointerNull>(V)) 1446 return getIntegerSCEV(0, V->getType()); 1447 SCEVUnknown *&Result = (*SCEVUnknowns)[V]; 1448 if (Result == 0) Result = new SCEVUnknown(V); 1449 return Result; 1450} 1451 1452//===----------------------------------------------------------------------===// 1453// Basic SCEV Analysis and PHI Idiom Recognition Code 1454// 1455 1456/// isSCEVable - Test if values of the given type are analyzable within 1457/// the SCEV framework. This primarily includes integer types, and it 1458/// can optionally include pointer types if the ScalarEvolution class 1459/// has access to target-specific information. 1460bool ScalarEvolution::isSCEVable(const Type *Ty) const { 1461 // Integers are always SCEVable. 1462 if (Ty->isInteger()) 1463 return true; 1464 1465 // Pointers are SCEVable if TargetData information is available 1466 // to provide pointer size information. 1467 if (isa<PointerType>(Ty)) 1468 return TD != NULL; 1469 1470 // Otherwise it's not SCEVable. 1471 return false; 1472} 1473 1474/// getTypeSizeInBits - Return the size in bits of the specified type, 1475/// for which isSCEVable must return true. 1476uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const { 1477 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 1478 1479 // If we have a TargetData, use it! 1480 if (TD) 1481 return TD->getTypeSizeInBits(Ty); 1482 1483 // Otherwise, we support only integer types. 1484 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!"); 1485 return Ty->getPrimitiveSizeInBits(); 1486} 1487 1488/// getEffectiveSCEVType - Return a type with the same bitwidth as 1489/// the given type and which represents how SCEV will treat the given 1490/// type, for which isSCEVable must return true. For pointer types, 1491/// this is the pointer-sized integer type. 1492const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const { 1493 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 1494 1495 if (Ty->isInteger()) 1496 return Ty; 1497 1498 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!"); 1499 return TD->getIntPtrType(); 1500} 1501 1502SCEVHandle ScalarEvolution::getCouldNotCompute() { 1503 return UnknownValue; 1504} 1505 1506/// hasSCEV - Return true if the SCEV for this value has already been 1507/// computed. 1508bool ScalarEvolution::hasSCEV(Value *V) const { 1509 return Scalars.count(V); 1510} 1511 1512/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 1513/// expression and create a new one. 1514SCEVHandle ScalarEvolution::getSCEV(Value *V) { 1515 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 1516 1517 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V); 1518 if (I != Scalars.end()) return I->second; 1519 SCEVHandle S = createSCEV(V); 1520 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S)); 1521 return S; 1522} 1523 1524/// getIntegerSCEV - Given an integer or FP type, create a constant for the 1525/// specified signed integer value and return a SCEV for the constant. 1526SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) { 1527 Ty = getEffectiveSCEVType(Ty); 1528 Constant *C; 1529 if (Val == 0) 1530 C = Constant::getNullValue(Ty); 1531 else if (Ty->isFloatingPoint()) 1532 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle : 1533 APFloat::IEEEdouble, Val)); 1534 else 1535 C = ConstantInt::get(Ty, Val); 1536 return getUnknown(C); 1537} 1538 1539/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V 1540/// 1541SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) { 1542 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 1543 return getUnknown(ConstantExpr::getNeg(VC->getValue())); 1544 1545 const Type *Ty = V->getType(); 1546 Ty = getEffectiveSCEVType(Ty); 1547 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty))); 1548} 1549 1550/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V 1551SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) { 1552 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 1553 return getUnknown(ConstantExpr::getNot(VC->getValue())); 1554 1555 const Type *Ty = V->getType(); 1556 Ty = getEffectiveSCEVType(Ty); 1557 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty)); 1558 return getMinusSCEV(AllOnes, V); 1559} 1560 1561/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS. 1562/// 1563SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS, 1564 const SCEVHandle &RHS) { 1565 // X - Y --> X + -Y 1566 return getAddExpr(LHS, getNegativeSCEV(RHS)); 1567} 1568 1569/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the 1570/// input value to the specified type. If the type must be extended, it is zero 1571/// extended. 1572SCEVHandle 1573ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V, 1574 const Type *Ty) { 1575 const Type *SrcTy = V->getType(); 1576 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) && 1577 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) && 1578 "Cannot truncate or zero extend with non-integer arguments!"); 1579 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 1580 return V; // No conversion 1581 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 1582 return getTruncateExpr(V, Ty); 1583 return getZeroExtendExpr(V, Ty); 1584} 1585 1586/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the 1587/// input value to the specified type. If the type must be extended, it is sign 1588/// extended. 1589SCEVHandle 1590ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V, 1591 const Type *Ty) { 1592 const Type *SrcTy = V->getType(); 1593 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) && 1594 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) && 1595 "Cannot truncate or zero extend with non-integer arguments!"); 1596 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 1597 return V; // No conversion 1598 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 1599 return getTruncateExpr(V, Ty); 1600 return getSignExtendExpr(V, Ty); 1601} 1602 1603/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for 1604/// the specified instruction and replaces any references to the symbolic value 1605/// SymName with the specified value. This is used during PHI resolution. 1606void ScalarEvolution:: 1607ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName, 1608 const SCEVHandle &NewVal) { 1609 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI = 1610 Scalars.find(SCEVCallbackVH(I, this)); 1611 if (SI == Scalars.end()) return; 1612 1613 SCEVHandle NV = 1614 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this); 1615 if (NV == SI->second) return; // No change. 1616 1617 SI->second = NV; // Update the scalars map! 1618 1619 // Any instruction values that use this instruction might also need to be 1620 // updated! 1621 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 1622 UI != E; ++UI) 1623 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal); 1624} 1625 1626/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in 1627/// a loop header, making it a potential recurrence, or it doesn't. 1628/// 1629SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) { 1630 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized. 1631 if (const Loop *L = LI->getLoopFor(PN->getParent())) 1632 if (L->getHeader() == PN->getParent()) { 1633 // If it lives in the loop header, it has two incoming values, one 1634 // from outside the loop, and one from inside. 1635 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 1636 unsigned BackEdge = IncomingEdge^1; 1637 1638 // While we are analyzing this PHI node, handle its value symbolically. 1639 SCEVHandle SymbolicName = getUnknown(PN); 1640 assert(Scalars.find(PN) == Scalars.end() && 1641 "PHI node already processed?"); 1642 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName)); 1643 1644 // Using this symbolic name for the PHI, analyze the value coming around 1645 // the back-edge. 1646 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge)); 1647 1648 // NOTE: If BEValue is loop invariant, we know that the PHI node just 1649 // has a special value for the first iteration of the loop. 1650 1651 // If the value coming around the backedge is an add with the symbolic 1652 // value we just inserted, then we found a simple induction variable! 1653 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 1654 // If there is a single occurrence of the symbolic value, replace it 1655 // with a recurrence. 1656 unsigned FoundIndex = Add->getNumOperands(); 1657 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 1658 if (Add->getOperand(i) == SymbolicName) 1659 if (FoundIndex == e) { 1660 FoundIndex = i; 1661 break; 1662 } 1663 1664 if (FoundIndex != Add->getNumOperands()) { 1665 // Create an add with everything but the specified operand. 1666 std::vector<SCEVHandle> Ops; 1667 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 1668 if (i != FoundIndex) 1669 Ops.push_back(Add->getOperand(i)); 1670 SCEVHandle Accum = getAddExpr(Ops); 1671 1672 // This is not a valid addrec if the step amount is varying each 1673 // loop iteration, but is not itself an addrec in this loop. 1674 if (Accum->isLoopInvariant(L) || 1675 (isa<SCEVAddRecExpr>(Accum) && 1676 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 1677 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); 1678 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L); 1679 1680 // Okay, for the entire analysis of this edge we assumed the PHI 1681 // to be symbolic. We now need to go back and update all of the 1682 // entries for the scalars that use the PHI (except for the PHI 1683 // itself) to use the new analyzed value instead of the "symbolic" 1684 // value. 1685 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 1686 return PHISCEV; 1687 } 1688 } 1689 } else if (const SCEVAddRecExpr *AddRec = 1690 dyn_cast<SCEVAddRecExpr>(BEValue)) { 1691 // Otherwise, this could be a loop like this: 1692 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 1693 // In this case, j = {1,+,1} and BEValue is j. 1694 // Because the other in-value of i (0) fits the evolution of BEValue 1695 // i really is an addrec evolution. 1696 if (AddRec->getLoop() == L && AddRec->isAffine()) { 1697 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); 1698 1699 // If StartVal = j.start - j.stride, we can use StartVal as the 1700 // initial step of the addrec evolution. 1701 if (StartVal == getMinusSCEV(AddRec->getOperand(0), 1702 AddRec->getOperand(1))) { 1703 SCEVHandle PHISCEV = 1704 getAddRecExpr(StartVal, AddRec->getOperand(1), L); 1705 1706 // Okay, for the entire analysis of this edge we assumed the PHI 1707 // to be symbolic. We now need to go back and update all of the 1708 // entries for the scalars that use the PHI (except for the PHI 1709 // itself) to use the new analyzed value instead of the "symbolic" 1710 // value. 1711 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 1712 return PHISCEV; 1713 } 1714 } 1715 } 1716 1717 return SymbolicName; 1718 } 1719 1720 // If it's not a loop phi, we can't handle it yet. 1721 return getUnknown(PN); 1722} 1723 1724/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is 1725/// guaranteed to end in (at every loop iteration). It is, at the same time, 1726/// the minimum number of times S is divisible by 2. For example, given {4,+,8} 1727/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S. 1728static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) { 1729 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 1730 return C->getValue()->getValue().countTrailingZeros(); 1731 1732 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 1733 return std::min(GetMinTrailingZeros(T->getOperand(), SE), 1734 (uint32_t)SE.getTypeSizeInBits(T->getType())); 1735 1736 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 1737 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE); 1738 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ? 1739 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes; 1740 } 1741 1742 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 1743 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE); 1744 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ? 1745 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes; 1746 } 1747 1748 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 1749 // The result is the min of all operands results. 1750 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE); 1751 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 1752 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE)); 1753 return MinOpRes; 1754 } 1755 1756 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 1757 // The result is the sum of all operands results. 1758 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE); 1759 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType()); 1760 for (unsigned i = 1, e = M->getNumOperands(); 1761 SumOpRes != BitWidth && i != e; ++i) 1762 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE), 1763 BitWidth); 1764 return SumOpRes; 1765 } 1766 1767 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 1768 // The result is the min of all operands results. 1769 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE); 1770 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 1771 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE)); 1772 return MinOpRes; 1773 } 1774 1775 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 1776 // The result is the min of all operands results. 1777 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE); 1778 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 1779 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE)); 1780 return MinOpRes; 1781 } 1782 1783 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 1784 // The result is the min of all operands results. 1785 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE); 1786 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 1787 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE)); 1788 return MinOpRes; 1789 } 1790 1791 // SCEVUDivExpr, SCEVUnknown 1792 return 0; 1793} 1794 1795/// createSCEV - We know that there is no SCEV for the specified value. 1796/// Analyze the expression. 1797/// 1798SCEVHandle ScalarEvolution::createSCEV(Value *V) { 1799 if (!isSCEVable(V->getType())) 1800 return getUnknown(V); 1801 1802 unsigned Opcode = Instruction::UserOp1; 1803 if (Instruction *I = dyn_cast<Instruction>(V)) 1804 Opcode = I->getOpcode(); 1805 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 1806 Opcode = CE->getOpcode(); 1807 else 1808 return getUnknown(V); 1809 1810 User *U = cast<User>(V); 1811 switch (Opcode) { 1812 case Instruction::Add: 1813 return getAddExpr(getSCEV(U->getOperand(0)), 1814 getSCEV(U->getOperand(1))); 1815 case Instruction::Mul: 1816 return getMulExpr(getSCEV(U->getOperand(0)), 1817 getSCEV(U->getOperand(1))); 1818 case Instruction::UDiv: 1819 return getUDivExpr(getSCEV(U->getOperand(0)), 1820 getSCEV(U->getOperand(1))); 1821 case Instruction::Sub: 1822 return getMinusSCEV(getSCEV(U->getOperand(0)), 1823 getSCEV(U->getOperand(1))); 1824 case Instruction::And: 1825 // For an expression like x&255 that merely masks off the high bits, 1826 // use zext(trunc(x)) as the SCEV expression. 1827 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 1828 if (CI->isNullValue()) 1829 return getSCEV(U->getOperand(1)); 1830 if (CI->isAllOnesValue()) 1831 return getSCEV(U->getOperand(0)); 1832 const APInt &A = CI->getValue(); 1833 unsigned Ones = A.countTrailingOnes(); 1834 if (APIntOps::isMask(Ones, A)) 1835 return 1836 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)), 1837 IntegerType::get(Ones)), 1838 U->getType()); 1839 } 1840 break; 1841 case Instruction::Or: 1842 // If the RHS of the Or is a constant, we may have something like: 1843 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 1844 // optimizations will transparently handle this case. 1845 // 1846 // In order for this transformation to be safe, the LHS must be of the 1847 // form X*(2^n) and the Or constant must be less than 2^n. 1848 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 1849 SCEVHandle LHS = getSCEV(U->getOperand(0)); 1850 const APInt &CIVal = CI->getValue(); 1851 if (GetMinTrailingZeros(LHS, *this) >= 1852 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) 1853 return getAddExpr(LHS, getSCEV(U->getOperand(1))); 1854 } 1855 break; 1856 case Instruction::Xor: 1857 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 1858 // If the RHS of the xor is a signbit, then this is just an add. 1859 // Instcombine turns add of signbit into xor as a strength reduction step. 1860 if (CI->getValue().isSignBit()) 1861 return getAddExpr(getSCEV(U->getOperand(0)), 1862 getSCEV(U->getOperand(1))); 1863 1864 // If the RHS of xor is -1, then this is a not operation. 1865 else if (CI->isAllOnesValue()) 1866 return getNotSCEV(getSCEV(U->getOperand(0))); 1867 } 1868 break; 1869 1870 case Instruction::Shl: 1871 // Turn shift left of a constant amount into a multiply. 1872 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 1873 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); 1874 Constant *X = ConstantInt::get( 1875 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth))); 1876 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X)); 1877 } 1878 break; 1879 1880 case Instruction::LShr: 1881 // Turn logical shift right of a constant into a unsigned divide. 1882 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 1883 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); 1884 Constant *X = ConstantInt::get( 1885 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth))); 1886 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X)); 1887 } 1888 break; 1889 1890 case Instruction::AShr: 1891 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 1892 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) 1893 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0))) 1894 if (L->getOpcode() == Instruction::Shl && 1895 L->getOperand(1) == U->getOperand(1)) { 1896 unsigned BitWidth = getTypeSizeInBits(U->getType()); 1897 uint64_t Amt = BitWidth - CI->getZExtValue(); 1898 if (Amt == BitWidth) 1899 return getSCEV(L->getOperand(0)); // shift by zero --> noop 1900 if (Amt > BitWidth) 1901 return getIntegerSCEV(0, U->getType()); // value is undefined 1902 return 1903 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)), 1904 IntegerType::get(Amt)), 1905 U->getType()); 1906 } 1907 break; 1908 1909 case Instruction::Trunc: 1910 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 1911 1912 case Instruction::ZExt: 1913 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 1914 1915 case Instruction::SExt: 1916 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 1917 1918 case Instruction::BitCast: 1919 // BitCasts are no-op casts so we just eliminate the cast. 1920 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 1921 return getSCEV(U->getOperand(0)); 1922 break; 1923 1924 case Instruction::IntToPtr: 1925 if (!TD) break; // Without TD we can't analyze pointers. 1926 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)), 1927 TD->getIntPtrType()); 1928 1929 case Instruction::PtrToInt: 1930 if (!TD) break; // Without TD we can't analyze pointers. 1931 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)), 1932 U->getType()); 1933 1934 case Instruction::GetElementPtr: { 1935 if (!TD) break; // Without TD we can't analyze pointers. 1936 const Type *IntPtrTy = TD->getIntPtrType(); 1937 Value *Base = U->getOperand(0); 1938 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy); 1939 gep_type_iterator GTI = gep_type_begin(U); 1940 for (GetElementPtrInst::op_iterator I = next(U->op_begin()), 1941 E = U->op_end(); 1942 I != E; ++I) { 1943 Value *Index = *I; 1944 // Compute the (potentially symbolic) offset in bytes for this index. 1945 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) { 1946 // For a struct, add the member offset. 1947 const StructLayout &SL = *TD->getStructLayout(STy); 1948 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue(); 1949 uint64_t Offset = SL.getElementOffset(FieldNo); 1950 TotalOffset = getAddExpr(TotalOffset, 1951 getIntegerSCEV(Offset, IntPtrTy)); 1952 } else { 1953 // For an array, add the element offset, explicitly scaled. 1954 SCEVHandle LocalOffset = getSCEV(Index); 1955 if (!isa<PointerType>(LocalOffset->getType())) 1956 // Getelementptr indicies are signed. 1957 LocalOffset = getTruncateOrSignExtend(LocalOffset, 1958 IntPtrTy); 1959 LocalOffset = 1960 getMulExpr(LocalOffset, 1961 getIntegerSCEV(TD->getTypePaddedSize(*GTI), 1962 IntPtrTy)); 1963 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 1964 } 1965 } 1966 return getAddExpr(getSCEV(Base), TotalOffset); 1967 } 1968 1969 case Instruction::PHI: 1970 return createNodeForPHI(cast<PHINode>(U)); 1971 1972 case Instruction::Select: 1973 // This could be a smax or umax that was lowered earlier. 1974 // Try to recover it. 1975 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) { 1976 Value *LHS = ICI->getOperand(0); 1977 Value *RHS = ICI->getOperand(1); 1978 switch (ICI->getPredicate()) { 1979 case ICmpInst::ICMP_SLT: 1980 case ICmpInst::ICMP_SLE: 1981 std::swap(LHS, RHS); 1982 // fall through 1983 case ICmpInst::ICMP_SGT: 1984 case ICmpInst::ICMP_SGE: 1985 if (LHS == U->getOperand(1) && RHS == U->getOperand(2)) 1986 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS)); 1987 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1)) 1988 // ~smax(~x, ~y) == smin(x, y). 1989 return getNotSCEV(getSMaxExpr( 1990 getNotSCEV(getSCEV(LHS)), 1991 getNotSCEV(getSCEV(RHS)))); 1992 break; 1993 case ICmpInst::ICMP_ULT: 1994 case ICmpInst::ICMP_ULE: 1995 std::swap(LHS, RHS); 1996 // fall through 1997 case ICmpInst::ICMP_UGT: 1998 case ICmpInst::ICMP_UGE: 1999 if (LHS == U->getOperand(1) && RHS == U->getOperand(2)) 2000 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS)); 2001 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1)) 2002 // ~umax(~x, ~y) == umin(x, y) 2003 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)), 2004 getNotSCEV(getSCEV(RHS)))); 2005 break; 2006 default: 2007 break; 2008 } 2009 } 2010 2011 default: // We cannot analyze this expression. 2012 break; 2013 } 2014 2015 return getUnknown(V); 2016} 2017 2018 2019 2020//===----------------------------------------------------------------------===// 2021// Iteration Count Computation Code 2022// 2023 2024/// getBackedgeTakenCount - If the specified loop has a predictable 2025/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute 2026/// object. The backedge-taken count is the number of times the loop header 2027/// will be branched to from within the loop. This is one less than the 2028/// trip count of the loop, since it doesn't count the first iteration, 2029/// when the header is branched to from outside the loop. 2030/// 2031/// Note that it is not valid to call this method on a loop without a 2032/// loop-invariant backedge-taken count (see 2033/// hasLoopInvariantBackedgeTakenCount). 2034/// 2035SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 2036 return getBackedgeTakenInfo(L).Exact; 2037} 2038 2039/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except 2040/// return the least SCEV value that is known never to be less than the 2041/// actual backedge taken count. 2042SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 2043 return getBackedgeTakenInfo(L).Max; 2044} 2045 2046const ScalarEvolution::BackedgeTakenInfo & 2047ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 2048 // Initially insert a CouldNotCompute for this loop. If the insertion 2049 // succeeds, procede to actually compute a backedge-taken count and 2050 // update the value. The temporary CouldNotCompute value tells SCEV 2051 // code elsewhere that it shouldn't attempt to request a new 2052 // backedge-taken count, which could result in infinite recursion. 2053 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair = 2054 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute())); 2055 if (Pair.second) { 2056 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L); 2057 if (ItCount.Exact != UnknownValue) { 2058 assert(ItCount.Exact->isLoopInvariant(L) && 2059 ItCount.Max->isLoopInvariant(L) && 2060 "Computed trip count isn't loop invariant for loop!"); 2061 ++NumTripCountsComputed; 2062 2063 // Update the value in the map. 2064 Pair.first->second = ItCount; 2065 } else if (isa<PHINode>(L->getHeader()->begin())) { 2066 // Only count loops that have phi nodes as not being computable. 2067 ++NumTripCountsNotComputed; 2068 } 2069 2070 // Now that we know more about the trip count for this loop, forget any 2071 // existing SCEV values for PHI nodes in this loop since they are only 2072 // conservative estimates made without the benefit 2073 // of trip count information. 2074 if (ItCount.hasAnyInfo()) 2075 forgetLoopPHIs(L); 2076 } 2077 return Pair.first->second; 2078} 2079 2080/// forgetLoopBackedgeTakenCount - This method should be called by the 2081/// client when it has changed a loop in a way that may effect 2082/// ScalarEvolution's ability to compute a trip count, or if the loop 2083/// is deleted. 2084void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) { 2085 BackedgeTakenCounts.erase(L); 2086 forgetLoopPHIs(L); 2087} 2088 2089/// forgetLoopPHIs - Delete the memoized SCEVs associated with the 2090/// PHI nodes in the given loop. This is used when the trip count of 2091/// the loop may have changed. 2092void ScalarEvolution::forgetLoopPHIs(const Loop *L) { 2093 BasicBlock *Header = L->getHeader(); 2094 2095 SmallVector<Instruction *, 16> Worklist; 2096 for (BasicBlock::iterator I = Header->begin(); 2097 PHINode *PN = dyn_cast<PHINode>(I); ++I) 2098 Worklist.push_back(PN); 2099 2100 while (!Worklist.empty()) { 2101 Instruction *I = Worklist.pop_back_val(); 2102 if (Scalars.erase(I)) 2103 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); 2104 UI != UE; ++UI) 2105 Worklist.push_back(cast<Instruction>(UI)); 2106 } 2107} 2108 2109/// ComputeBackedgeTakenCount - Compute the number of times the backedge 2110/// of the specified loop will execute. 2111ScalarEvolution::BackedgeTakenInfo 2112ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) { 2113 // If the loop has a non-one exit block count, we can't analyze it. 2114 SmallVector<BasicBlock*, 8> ExitBlocks; 2115 L->getExitBlocks(ExitBlocks); 2116 if (ExitBlocks.size() != 1) return UnknownValue; 2117 2118 // Okay, there is one exit block. Try to find the condition that causes the 2119 // loop to be exited. 2120 BasicBlock *ExitBlock = ExitBlocks[0]; 2121 2122 BasicBlock *ExitingBlock = 0; 2123 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock); 2124 PI != E; ++PI) 2125 if (L->contains(*PI)) { 2126 if (ExitingBlock == 0) 2127 ExitingBlock = *PI; 2128 else 2129 return UnknownValue; // More than one block exiting! 2130 } 2131 assert(ExitingBlock && "No exits from loop, something is broken!"); 2132 2133 // Okay, we've computed the exiting block. See what condition causes us to 2134 // exit. 2135 // 2136 // FIXME: we should be able to handle switch instructions (with a single exit) 2137 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 2138 if (ExitBr == 0) return UnknownValue; 2139 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!"); 2140 2141 // At this point, we know we have a conditional branch that determines whether 2142 // the loop is exited. However, we don't know if the branch is executed each 2143 // time through the loop. If not, then the execution count of the branch will 2144 // not be equal to the trip count of the loop. 2145 // 2146 // Currently we check for this by checking to see if the Exit branch goes to 2147 // the loop header. If so, we know it will always execute the same number of 2148 // times as the loop. We also handle the case where the exit block *is* the 2149 // loop header. This is common for un-rotated loops. More extensive analysis 2150 // could be done to handle more cases here. 2151 if (ExitBr->getSuccessor(0) != L->getHeader() && 2152 ExitBr->getSuccessor(1) != L->getHeader() && 2153 ExitBr->getParent() != L->getHeader()) 2154 return UnknownValue; 2155 2156 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition()); 2157 2158 // If it's not an integer comparison then compute it the hard way. 2159 // Note that ICmpInst deals with pointer comparisons too so we must check 2160 // the type of the operand. 2161 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType())) 2162 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(), 2163 ExitBr->getSuccessor(0) == ExitBlock); 2164 2165 // If the condition was exit on true, convert the condition to exit on false 2166 ICmpInst::Predicate Cond; 2167 if (ExitBr->getSuccessor(1) == ExitBlock) 2168 Cond = ExitCond->getPredicate(); 2169 else 2170 Cond = ExitCond->getInversePredicate(); 2171 2172 // Handle common loops like: for (X = "string"; *X; ++X) 2173 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 2174 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 2175 SCEVHandle ItCnt = 2176 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond); 2177 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt; 2178 } 2179 2180 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0)); 2181 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1)); 2182 2183 // Try to evaluate any dependencies out of the loop. 2184 SCEVHandle Tmp = getSCEVAtScope(LHS, L); 2185 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp; 2186 Tmp = getSCEVAtScope(RHS, L); 2187 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp; 2188 2189 // At this point, we would like to compute how many iterations of the 2190 // loop the predicate will return true for these inputs. 2191 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) { 2192 // If there is a loop-invariant, force it into the RHS. 2193 std::swap(LHS, RHS); 2194 Cond = ICmpInst::getSwappedPredicate(Cond); 2195 } 2196 2197 // If we have a comparison of a chrec against a constant, try to use value 2198 // ranges to answer this query. 2199 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 2200 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 2201 if (AddRec->getLoop() == L) { 2202 // Form the comparison range using the constant of the correct type so 2203 // that the ConstantRange class knows to do a signed or unsigned 2204 // comparison. 2205 ConstantInt *CompVal = RHSC->getValue(); 2206 const Type *RealTy = ExitCond->getOperand(0)->getType(); 2207 CompVal = dyn_cast<ConstantInt>( 2208 ConstantExpr::getBitCast(CompVal, RealTy)); 2209 if (CompVal) { 2210 // Form the constant range. 2211 ConstantRange CompRange( 2212 ICmpInst::makeConstantRange(Cond, CompVal->getValue())); 2213 2214 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this); 2215 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 2216 } 2217 } 2218 2219 switch (Cond) { 2220 case ICmpInst::ICMP_NE: { // while (X != Y) 2221 // Convert to: while (X-Y != 0) 2222 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L); 2223 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 2224 break; 2225 } 2226 case ICmpInst::ICMP_EQ: { 2227 // Convert to: while (X-Y == 0) // while (X == Y) 2228 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L); 2229 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 2230 break; 2231 } 2232 case ICmpInst::ICMP_SLT: { 2233 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true); 2234 if (BTI.hasAnyInfo()) return BTI; 2235 break; 2236 } 2237 case ICmpInst::ICMP_SGT: { 2238 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS), 2239 getNotSCEV(RHS), L, true); 2240 if (BTI.hasAnyInfo()) return BTI; 2241 break; 2242 } 2243 case ICmpInst::ICMP_ULT: { 2244 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false); 2245 if (BTI.hasAnyInfo()) return BTI; 2246 break; 2247 } 2248 case ICmpInst::ICMP_UGT: { 2249 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS), 2250 getNotSCEV(RHS), L, false); 2251 if (BTI.hasAnyInfo()) return BTI; 2252 break; 2253 } 2254 default: 2255#if 0 2256 errs() << "ComputeBackedgeTakenCount "; 2257 if (ExitCond->getOperand(0)->getType()->isUnsigned()) 2258 errs() << "[unsigned] "; 2259 errs() << *LHS << " " 2260 << Instruction::getOpcodeName(Instruction::ICmp) 2261 << " " << *RHS << "\n"; 2262#endif 2263 break; 2264 } 2265 return 2266 ComputeBackedgeTakenCountExhaustively(L, ExitCond, 2267 ExitBr->getSuccessor(0) == ExitBlock); 2268} 2269 2270static ConstantInt * 2271EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 2272 ScalarEvolution &SE) { 2273 SCEVHandle InVal = SE.getConstant(C); 2274 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE); 2275 assert(isa<SCEVConstant>(Val) && 2276 "Evaluation of SCEV at constant didn't fold correctly?"); 2277 return cast<SCEVConstant>(Val)->getValue(); 2278} 2279 2280/// GetAddressedElementFromGlobal - Given a global variable with an initializer 2281/// and a GEP expression (missing the pointer index) indexing into it, return 2282/// the addressed element of the initializer or null if the index expression is 2283/// invalid. 2284static Constant * 2285GetAddressedElementFromGlobal(GlobalVariable *GV, 2286 const std::vector<ConstantInt*> &Indices) { 2287 Constant *Init = GV->getInitializer(); 2288 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 2289 uint64_t Idx = Indices[i]->getZExtValue(); 2290 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { 2291 assert(Idx < CS->getNumOperands() && "Bad struct index!"); 2292 Init = cast<Constant>(CS->getOperand(Idx)); 2293 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { 2294 if (Idx >= CA->getNumOperands()) return 0; // Bogus program 2295 Init = cast<Constant>(CA->getOperand(Idx)); 2296 } else if (isa<ConstantAggregateZero>(Init)) { 2297 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) { 2298 assert(Idx < STy->getNumElements() && "Bad struct index!"); 2299 Init = Constant::getNullValue(STy->getElementType(Idx)); 2300 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) { 2301 if (Idx >= ATy->getNumElements()) return 0; // Bogus program 2302 Init = Constant::getNullValue(ATy->getElementType()); 2303 } else { 2304 assert(0 && "Unknown constant aggregate type!"); 2305 } 2306 return 0; 2307 } else { 2308 return 0; // Unknown initializer type 2309 } 2310 } 2311 return Init; 2312} 2313 2314/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of 2315/// 'icmp op load X, cst', try to see if we can compute the backedge 2316/// execution count. 2317SCEVHandle ScalarEvolution:: 2318ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS, 2319 const Loop *L, 2320 ICmpInst::Predicate predicate) { 2321 if (LI->isVolatile()) return UnknownValue; 2322 2323 // Check to see if the loaded pointer is a getelementptr of a global. 2324 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 2325 if (!GEP) return UnknownValue; 2326 2327 // Make sure that it is really a constant global we are gepping, with an 2328 // initializer, and make sure the first IDX is really 0. 2329 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 2330 if (!GV || !GV->isConstant() || !GV->hasInitializer() || 2331 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 2332 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 2333 return UnknownValue; 2334 2335 // Okay, we allow one non-constant index into the GEP instruction. 2336 Value *VarIdx = 0; 2337 std::vector<ConstantInt*> Indexes; 2338 unsigned VarIdxNum = 0; 2339 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 2340 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 2341 Indexes.push_back(CI); 2342 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 2343 if (VarIdx) return UnknownValue; // Multiple non-constant idx's. 2344 VarIdx = GEP->getOperand(i); 2345 VarIdxNum = i-2; 2346 Indexes.push_back(0); 2347 } 2348 2349 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 2350 // Check to see if X is a loop variant variable value now. 2351 SCEVHandle Idx = getSCEV(VarIdx); 2352 SCEVHandle Tmp = getSCEVAtScope(Idx, L); 2353 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp; 2354 2355 // We can only recognize very limited forms of loop index expressions, in 2356 // particular, only affine AddRec's like {C1,+,C2}. 2357 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 2358 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) || 2359 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 2360 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 2361 return UnknownValue; 2362 2363 unsigned MaxSteps = MaxBruteForceIterations; 2364 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 2365 ConstantInt *ItCst = 2366 ConstantInt::get(IdxExpr->getType(), IterationNum); 2367 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 2368 2369 // Form the GEP offset. 2370 Indexes[VarIdxNum] = Val; 2371 2372 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes); 2373 if (Result == 0) break; // Cannot compute! 2374 2375 // Evaluate the condition for this iteration. 2376 Result = ConstantExpr::getICmp(predicate, Result, RHS); 2377 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 2378 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 2379#if 0 2380 errs() << "\n***\n*** Computed loop count " << *ItCst 2381 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() 2382 << "***\n"; 2383#endif 2384 ++NumArrayLenItCounts; 2385 return getConstant(ItCst); // Found terminating iteration! 2386 } 2387 } 2388 return UnknownValue; 2389} 2390 2391 2392/// CanConstantFold - Return true if we can constant fold an instruction of the 2393/// specified type, assuming that all operands were constants. 2394static bool CanConstantFold(const Instruction *I) { 2395 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 2396 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I)) 2397 return true; 2398 2399 if (const CallInst *CI = dyn_cast<CallInst>(I)) 2400 if (const Function *F = CI->getCalledFunction()) 2401 return canConstantFoldCallTo(F); 2402 return false; 2403} 2404 2405/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 2406/// in the loop that V is derived from. We allow arbitrary operations along the 2407/// way, but the operands of an operation must either be constants or a value 2408/// derived from a constant PHI. If this expression does not fit with these 2409/// constraints, return null. 2410static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 2411 // If this is not an instruction, or if this is an instruction outside of the 2412 // loop, it can't be derived from a loop PHI. 2413 Instruction *I = dyn_cast<Instruction>(V); 2414 if (I == 0 || !L->contains(I->getParent())) return 0; 2415 2416 if (PHINode *PN = dyn_cast<PHINode>(I)) { 2417 if (L->getHeader() == I->getParent()) 2418 return PN; 2419 else 2420 // We don't currently keep track of the control flow needed to evaluate 2421 // PHIs, so we cannot handle PHIs inside of loops. 2422 return 0; 2423 } 2424 2425 // If we won't be able to constant fold this expression even if the operands 2426 // are constants, return early. 2427 if (!CanConstantFold(I)) return 0; 2428 2429 // Otherwise, we can evaluate this instruction if all of its operands are 2430 // constant or derived from a PHI node themselves. 2431 PHINode *PHI = 0; 2432 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op) 2433 if (!(isa<Constant>(I->getOperand(Op)) || 2434 isa<GlobalValue>(I->getOperand(Op)))) { 2435 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L); 2436 if (P == 0) return 0; // Not evolving from PHI 2437 if (PHI == 0) 2438 PHI = P; 2439 else if (PHI != P) 2440 return 0; // Evolving from multiple different PHIs. 2441 } 2442 2443 // This is a expression evolving from a constant PHI! 2444 return PHI; 2445} 2446 2447/// EvaluateExpression - Given an expression that passes the 2448/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 2449/// in the loop has the value PHIVal. If we can't fold this expression for some 2450/// reason, return null. 2451static Constant *EvaluateExpression(Value *V, Constant *PHIVal) { 2452 if (isa<PHINode>(V)) return PHIVal; 2453 if (Constant *C = dyn_cast<Constant>(V)) return C; 2454 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV; 2455 Instruction *I = cast<Instruction>(V); 2456 2457 std::vector<Constant*> Operands; 2458 Operands.resize(I->getNumOperands()); 2459 2460 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 2461 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal); 2462 if (Operands[i] == 0) return 0; 2463 } 2464 2465 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 2466 return ConstantFoldCompareInstOperands(CI->getPredicate(), 2467 &Operands[0], Operands.size()); 2468 else 2469 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), 2470 &Operands[0], Operands.size()); 2471} 2472 2473/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 2474/// in the header of its containing loop, we know the loop executes a 2475/// constant number of times, and the PHI node is just a recurrence 2476/// involving constants, fold it. 2477Constant *ScalarEvolution:: 2478getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){ 2479 std::map<PHINode*, Constant*>::iterator I = 2480 ConstantEvolutionLoopExitValue.find(PN); 2481 if (I != ConstantEvolutionLoopExitValue.end()) 2482 return I->second; 2483 2484 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations))) 2485 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it. 2486 2487 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 2488 2489 // Since the loop is canonicalized, the PHI node must have two entries. One 2490 // entry must be a constant (coming in from outside of the loop), and the 2491 // second must be derived from the same PHI. 2492 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 2493 Constant *StartCST = 2494 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 2495 if (StartCST == 0) 2496 return RetVal = 0; // Must be a constant. 2497 2498 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 2499 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 2500 if (PN2 != PN) 2501 return RetVal = 0; // Not derived from same PHI. 2502 2503 // Execute the loop symbolically to determine the exit value. 2504 if (BEs.getActiveBits() >= 32) 2505 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it! 2506 2507 unsigned NumIterations = BEs.getZExtValue(); // must be in range 2508 unsigned IterationNum = 0; 2509 for (Constant *PHIVal = StartCST; ; ++IterationNum) { 2510 if (IterationNum == NumIterations) 2511 return RetVal = PHIVal; // Got exit value! 2512 2513 // Compute the value of the PHI node for the next iteration. 2514 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 2515 if (NextPHI == PHIVal) 2516 return RetVal = NextPHI; // Stopped evolving! 2517 if (NextPHI == 0) 2518 return 0; // Couldn't evaluate! 2519 PHIVal = NextPHI; 2520 } 2521} 2522 2523/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a 2524/// constant number of times (the condition evolves only from constants), 2525/// try to evaluate a few iterations of the loop until we get the exit 2526/// condition gets a value of ExitWhen (true or false). If we cannot 2527/// evaluate the trip count of the loop, return UnknownValue. 2528SCEVHandle ScalarEvolution:: 2529ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) { 2530 PHINode *PN = getConstantEvolvingPHI(Cond, L); 2531 if (PN == 0) return UnknownValue; 2532 2533 // Since the loop is canonicalized, the PHI node must have two entries. One 2534 // entry must be a constant (coming in from outside of the loop), and the 2535 // second must be derived from the same PHI. 2536 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 2537 Constant *StartCST = 2538 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 2539 if (StartCST == 0) return UnknownValue; // Must be a constant. 2540 2541 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 2542 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 2543 if (PN2 != PN) return UnknownValue; // Not derived from same PHI. 2544 2545 // Okay, we find a PHI node that defines the trip count of this loop. Execute 2546 // the loop symbolically to determine when the condition gets a value of 2547 // "ExitWhen". 2548 unsigned IterationNum = 0; 2549 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 2550 for (Constant *PHIVal = StartCST; 2551 IterationNum != MaxIterations; ++IterationNum) { 2552 ConstantInt *CondVal = 2553 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal)); 2554 2555 // Couldn't symbolically evaluate. 2556 if (!CondVal) return UnknownValue; 2557 2558 if (CondVal->getValue() == uint64_t(ExitWhen)) { 2559 ConstantEvolutionLoopExitValue[PN] = PHIVal; 2560 ++NumBruteForceTripCountsComputed; 2561 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum)); 2562 } 2563 2564 // Compute the value of the PHI node for the next iteration. 2565 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 2566 if (NextPHI == 0 || NextPHI == PHIVal) 2567 return UnknownValue; // Couldn't evaluate or not making progress... 2568 PHIVal = NextPHI; 2569 } 2570 2571 // Too many iterations were needed to evaluate. 2572 return UnknownValue; 2573} 2574 2575/// getSCEVAtScope - Compute the value of the specified expression within the 2576/// indicated loop (which may be null to indicate in no loop). If the 2577/// expression cannot be evaluated, return UnknownValue. 2578SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 2579 // FIXME: this should be turned into a virtual method on SCEV! 2580 2581 if (isa<SCEVConstant>(V)) return V; 2582 2583 // If this instruction is evolved from a constant-evolving PHI, compute the 2584 // exit value from the loop without using SCEVs. 2585 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 2586 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 2587 const Loop *LI = (*this->LI)[I->getParent()]; 2588 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 2589 if (PHINode *PN = dyn_cast<PHINode>(I)) 2590 if (PN->getParent() == LI->getHeader()) { 2591 // Okay, there is no closed form solution for the PHI node. Check 2592 // to see if the loop that contains it has a known backedge-taken 2593 // count. If so, we may be able to force computation of the exit 2594 // value. 2595 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI); 2596 if (const SCEVConstant *BTCC = 2597 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 2598 // Okay, we know how many times the containing loop executes. If 2599 // this is a constant evolving PHI node, get the final value at 2600 // the specified iteration number. 2601 Constant *RV = getConstantEvolutionLoopExitValue(PN, 2602 BTCC->getValue()->getValue(), 2603 LI); 2604 if (RV) return getUnknown(RV); 2605 } 2606 } 2607 2608 // Okay, this is an expression that we cannot symbolically evaluate 2609 // into a SCEV. Check to see if it's possible to symbolically evaluate 2610 // the arguments into constants, and if so, try to constant propagate the 2611 // result. This is particularly useful for computing loop exit values. 2612 if (CanConstantFold(I)) { 2613 std::vector<Constant*> Operands; 2614 Operands.reserve(I->getNumOperands()); 2615 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 2616 Value *Op = I->getOperand(i); 2617 if (Constant *C = dyn_cast<Constant>(Op)) { 2618 Operands.push_back(C); 2619 } else { 2620 // If any of the operands is non-constant and if they are 2621 // non-integer and non-pointer, don't even try to analyze them 2622 // with scev techniques. 2623 if (!isSCEVable(Op->getType())) 2624 return V; 2625 2626 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L); 2627 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) { 2628 Constant *C = SC->getValue(); 2629 if (C->getType() != Op->getType()) 2630 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 2631 Op->getType(), 2632 false), 2633 C, Op->getType()); 2634 Operands.push_back(C); 2635 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) { 2636 if (Constant *C = dyn_cast<Constant>(SU->getValue())) { 2637 if (C->getType() != Op->getType()) 2638 C = 2639 ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 2640 Op->getType(), 2641 false), 2642 C, Op->getType()); 2643 Operands.push_back(C); 2644 } else 2645 return V; 2646 } else { 2647 return V; 2648 } 2649 } 2650 } 2651 2652 Constant *C; 2653 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 2654 C = ConstantFoldCompareInstOperands(CI->getPredicate(), 2655 &Operands[0], Operands.size()); 2656 else 2657 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(), 2658 &Operands[0], Operands.size()); 2659 return getUnknown(C); 2660 } 2661 } 2662 2663 // This is some other type of SCEVUnknown, just return it. 2664 return V; 2665 } 2666 2667 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 2668 // Avoid performing the look-up in the common case where the specified 2669 // expression has no loop-variant portions. 2670 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 2671 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 2672 if (OpAtScope != Comm->getOperand(i)) { 2673 if (OpAtScope == UnknownValue) return UnknownValue; 2674 // Okay, at least one of these operands is loop variant but might be 2675 // foldable. Build a new instance of the folded commutative expression. 2676 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i); 2677 NewOps.push_back(OpAtScope); 2678 2679 for (++i; i != e; ++i) { 2680 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 2681 if (OpAtScope == UnknownValue) return UnknownValue; 2682 NewOps.push_back(OpAtScope); 2683 } 2684 if (isa<SCEVAddExpr>(Comm)) 2685 return getAddExpr(NewOps); 2686 if (isa<SCEVMulExpr>(Comm)) 2687 return getMulExpr(NewOps); 2688 if (isa<SCEVSMaxExpr>(Comm)) 2689 return getSMaxExpr(NewOps); 2690 if (isa<SCEVUMaxExpr>(Comm)) 2691 return getUMaxExpr(NewOps); 2692 assert(0 && "Unknown commutative SCEV type!"); 2693 } 2694 } 2695 // If we got here, all operands are loop invariant. 2696 return Comm; 2697 } 2698 2699 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 2700 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L); 2701 if (LHS == UnknownValue) return LHS; 2702 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L); 2703 if (RHS == UnknownValue) return RHS; 2704 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 2705 return Div; // must be loop invariant 2706 return getUDivExpr(LHS, RHS); 2707 } 2708 2709 // If this is a loop recurrence for a loop that does not contain L, then we 2710 // are dealing with the final value computed by the loop. 2711 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 2712 if (!L || !AddRec->getLoop()->contains(L->getHeader())) { 2713 // To evaluate this recurrence, we need to know how many times the AddRec 2714 // loop iterates. Compute this now. 2715 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 2716 if (BackedgeTakenCount == UnknownValue) return UnknownValue; 2717 2718 // Then, evaluate the AddRec. 2719 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 2720 } 2721 return UnknownValue; 2722 } 2723 2724 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 2725 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L); 2726 if (Op == UnknownValue) return Op; 2727 if (Op == Cast->getOperand()) 2728 return Cast; // must be loop invariant 2729 return getZeroExtendExpr(Op, Cast->getType()); 2730 } 2731 2732 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 2733 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L); 2734 if (Op == UnknownValue) return Op; 2735 if (Op == Cast->getOperand()) 2736 return Cast; // must be loop invariant 2737 return getSignExtendExpr(Op, Cast->getType()); 2738 } 2739 2740 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 2741 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L); 2742 if (Op == UnknownValue) return Op; 2743 if (Op == Cast->getOperand()) 2744 return Cast; // must be loop invariant 2745 return getTruncateExpr(Op, Cast->getType()); 2746 } 2747 2748 assert(0 && "Unknown SCEV type!"); 2749} 2750 2751/// getSCEVAtScope - Return a SCEV expression handle for the specified value 2752/// at the specified scope in the program. The L value specifies a loop 2753/// nest to evaluate the expression at, where null is the top-level or a 2754/// specified loop is immediately inside of the loop. 2755/// 2756/// This method can be used to compute the exit value for a variable defined 2757/// in a loop by querying what the value will hold in the parent loop. 2758/// 2759/// If this value is not computable at this scope, a SCEVCouldNotCompute 2760/// object is returned. 2761SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 2762 return getSCEVAtScope(getSCEV(V), L); 2763} 2764 2765/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the 2766/// following equation: 2767/// 2768/// A * X = B (mod N) 2769/// 2770/// where N = 2^BW and BW is the common bit width of A and B. The signedness of 2771/// A and B isn't important. 2772/// 2773/// If the equation does not have a solution, SCEVCouldNotCompute is returned. 2774static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 2775 ScalarEvolution &SE) { 2776 uint32_t BW = A.getBitWidth(); 2777 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 2778 assert(A != 0 && "A must be non-zero."); 2779 2780 // 1. D = gcd(A, N) 2781 // 2782 // The gcd of A and N may have only one prime factor: 2. The number of 2783 // trailing zeros in A is its multiplicity 2784 uint32_t Mult2 = A.countTrailingZeros(); 2785 // D = 2^Mult2 2786 2787 // 2. Check if B is divisible by D. 2788 // 2789 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 2790 // is not less than multiplicity of this prime factor for D. 2791 if (B.countTrailingZeros() < Mult2) 2792 return SE.getCouldNotCompute(); 2793 2794 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 2795 // modulo (N / D). 2796 // 2797 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 2798 // bit width during computations. 2799 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 2800 APInt Mod(BW + 1, 0); 2801 Mod.set(BW - Mult2); // Mod = N / D 2802 APInt I = AD.multiplicativeInverse(Mod); 2803 2804 // 4. Compute the minimum unsigned root of the equation: 2805 // I * (B / D) mod (N / D) 2806 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 2807 2808 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 2809 // bits. 2810 return SE.getConstant(Result.trunc(BW)); 2811} 2812 2813/// SolveQuadraticEquation - Find the roots of the quadratic equation for the 2814/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which 2815/// might be the same) or two SCEVCouldNotCompute objects. 2816/// 2817static std::pair<SCEVHandle,SCEVHandle> 2818SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 2819 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 2820 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 2821 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 2822 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 2823 2824 // We currently can only solve this if the coefficients are constants. 2825 if (!LC || !MC || !NC) { 2826 const SCEV *CNC = SE.getCouldNotCompute(); 2827 return std::make_pair(CNC, CNC); 2828 } 2829 2830 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth(); 2831 const APInt &L = LC->getValue()->getValue(); 2832 const APInt &M = MC->getValue()->getValue(); 2833 const APInt &N = NC->getValue()->getValue(); 2834 APInt Two(BitWidth, 2); 2835 APInt Four(BitWidth, 4); 2836 2837 { 2838 using namespace APIntOps; 2839 const APInt& C = L; 2840 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 2841 // The B coefficient is M-N/2 2842 APInt B(M); 2843 B -= sdiv(N,Two); 2844 2845 // The A coefficient is N/2 2846 APInt A(N.sdiv(Two)); 2847 2848 // Compute the B^2-4ac term. 2849 APInt SqrtTerm(B); 2850 SqrtTerm *= B; 2851 SqrtTerm -= Four * (A * C); 2852 2853 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 2854 // integer value or else APInt::sqrt() will assert. 2855 APInt SqrtVal(SqrtTerm.sqrt()); 2856 2857 // Compute the two solutions for the quadratic formula. 2858 // The divisions must be performed as signed divisions. 2859 APInt NegB(-B); 2860 APInt TwoA( A << 1 ); 2861 if (TwoA.isMinValue()) { 2862 const SCEV *CNC = SE.getCouldNotCompute(); 2863 return std::make_pair(CNC, CNC); 2864 } 2865 2866 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA)); 2867 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA)); 2868 2869 return std::make_pair(SE.getConstant(Solution1), 2870 SE.getConstant(Solution2)); 2871 } // end APIntOps namespace 2872} 2873 2874/// HowFarToZero - Return the number of times a backedge comparing the specified 2875/// value to zero will execute. If not computable, return UnknownValue 2876SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) { 2877 // If the value is a constant 2878 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 2879 // If the value is already zero, the branch will execute zero times. 2880 if (C->getValue()->isZero()) return C; 2881 return UnknownValue; // Otherwise it will loop infinitely. 2882 } 2883 2884 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 2885 if (!AddRec || AddRec->getLoop() != L) 2886 return UnknownValue; 2887 2888 if (AddRec->isAffine()) { 2889 // If this is an affine expression, the execution count of this branch is 2890 // the minimum unsigned root of the following equation: 2891 // 2892 // Start + Step*N = 0 (mod 2^BW) 2893 // 2894 // equivalent to: 2895 // 2896 // Step*N = -Start (mod 2^BW) 2897 // 2898 // where BW is the common bit width of Start and Step. 2899 2900 // Get the initial value for the loop. 2901 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 2902 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue; 2903 2904 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 2905 2906 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) { 2907 // For now we handle only constant steps. 2908 2909 // First, handle unitary steps. 2910 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so: 2911 return getNegativeSCEV(Start); // N = -Start (as unsigned) 2912 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so: 2913 return Start; // N = Start (as unsigned) 2914 2915 // Then, try to solve the above equation provided that Start is constant. 2916 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) 2917 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(), 2918 -StartC->getValue()->getValue(), 2919 *this); 2920 } 2921 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) { 2922 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 2923 // the quadratic equation to solve it. 2924 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, 2925 *this); 2926 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 2927 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 2928 if (R1) { 2929#if 0 2930 errs() << "HFTZ: " << *V << " - sol#1: " << *R1 2931 << " sol#2: " << *R2 << "\n"; 2932#endif 2933 // Pick the smallest positive root value. 2934 if (ConstantInt *CB = 2935 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 2936 R1->getValue(), R2->getValue()))) { 2937 if (CB->getZExtValue() == false) 2938 std::swap(R1, R2); // R1 is the minimum root now. 2939 2940 // We can only use this value if the chrec ends up with an exact zero 2941 // value at this index. When solving for "X*X != 5", for example, we 2942 // should not accept a root of 2. 2943 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this); 2944 if (Val->isZero()) 2945 return R1; // We found a quadratic root! 2946 } 2947 } 2948 } 2949 2950 return UnknownValue; 2951} 2952 2953/// HowFarToNonZero - Return the number of times a backedge checking the 2954/// specified value for nonzero will execute. If not computable, return 2955/// UnknownValue 2956SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) { 2957 // Loops that look like: while (X == 0) are very strange indeed. We don't 2958 // handle them yet except for the trivial case. This could be expanded in the 2959 // future as needed. 2960 2961 // If the value is a constant, check to see if it is known to be non-zero 2962 // already. If so, the backedge will execute zero times. 2963 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 2964 if (!C->getValue()->isNullValue()) 2965 return getIntegerSCEV(0, C->getType()); 2966 return UnknownValue; // Otherwise it will loop infinitely. 2967 } 2968 2969 // We could implement others, but I really doubt anyone writes loops like 2970 // this, and if they did, they would already be constant folded. 2971 return UnknownValue; 2972} 2973 2974/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB 2975/// (which may not be an immediate predecessor) which has exactly one 2976/// successor from which BB is reachable, or null if no such block is 2977/// found. 2978/// 2979BasicBlock * 2980ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 2981 // If the block has a unique predecessor, then there is no path from the 2982 // predecessor to the block that does not go through the direct edge 2983 // from the predecessor to the block. 2984 if (BasicBlock *Pred = BB->getSinglePredecessor()) 2985 return Pred; 2986 2987 // A loop's header is defined to be a block that dominates the loop. 2988 // If the loop has a preheader, it must be a block that has exactly 2989 // one successor that can reach BB. This is slightly more strict 2990 // than necessary, but works if critical edges are split. 2991 if (Loop *L = LI->getLoopFor(BB)) 2992 return L->getLoopPreheader(); 2993 2994 return 0; 2995} 2996 2997/// isLoopGuardedByCond - Test whether entry to the loop is protected by 2998/// a conditional between LHS and RHS. This is used to help avoid max 2999/// expressions in loop trip counts. 3000bool ScalarEvolution::isLoopGuardedByCond(const Loop *L, 3001 ICmpInst::Predicate Pred, 3002 const SCEV *LHS, const SCEV *RHS) { 3003 BasicBlock *Preheader = L->getLoopPreheader(); 3004 BasicBlock *PreheaderDest = L->getHeader(); 3005 3006 // Starting at the preheader, climb up the predecessor chain, as long as 3007 // there are predecessors that can be found that have unique successors 3008 // leading to the original header. 3009 for (; Preheader; 3010 PreheaderDest = Preheader, 3011 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) { 3012 3013 BranchInst *LoopEntryPredicate = 3014 dyn_cast<BranchInst>(Preheader->getTerminator()); 3015 if (!LoopEntryPredicate || 3016 LoopEntryPredicate->isUnconditional()) 3017 continue; 3018 3019 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition()); 3020 if (!ICI) continue; 3021 3022 // Now that we found a conditional branch that dominates the loop, check to 3023 // see if it is the comparison we are looking for. 3024 Value *PreCondLHS = ICI->getOperand(0); 3025 Value *PreCondRHS = ICI->getOperand(1); 3026 ICmpInst::Predicate Cond; 3027 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest) 3028 Cond = ICI->getPredicate(); 3029 else 3030 Cond = ICI->getInversePredicate(); 3031 3032 if (Cond == Pred) 3033 ; // An exact match. 3034 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE) 3035 ; // The actual condition is beyond sufficient. 3036 else 3037 // Check a few special cases. 3038 switch (Cond) { 3039 case ICmpInst::ICMP_UGT: 3040 if (Pred == ICmpInst::ICMP_ULT) { 3041 std::swap(PreCondLHS, PreCondRHS); 3042 Cond = ICmpInst::ICMP_ULT; 3043 break; 3044 } 3045 continue; 3046 case ICmpInst::ICMP_SGT: 3047 if (Pred == ICmpInst::ICMP_SLT) { 3048 std::swap(PreCondLHS, PreCondRHS); 3049 Cond = ICmpInst::ICMP_SLT; 3050 break; 3051 } 3052 continue; 3053 case ICmpInst::ICMP_NE: 3054 // Expressions like (x >u 0) are often canonicalized to (x != 0), 3055 // so check for this case by checking if the NE is comparing against 3056 // a minimum or maximum constant. 3057 if (!ICmpInst::isTrueWhenEqual(Pred)) 3058 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) { 3059 const APInt &A = CI->getValue(); 3060 switch (Pred) { 3061 case ICmpInst::ICMP_SLT: 3062 if (A.isMaxSignedValue()) break; 3063 continue; 3064 case ICmpInst::ICMP_SGT: 3065 if (A.isMinSignedValue()) break; 3066 continue; 3067 case ICmpInst::ICMP_ULT: 3068 if (A.isMaxValue()) break; 3069 continue; 3070 case ICmpInst::ICMP_UGT: 3071 if (A.isMinValue()) break; 3072 continue; 3073 default: 3074 continue; 3075 } 3076 Cond = ICmpInst::ICMP_NE; 3077 // NE is symmetric but the original comparison may not be. Swap 3078 // the operands if necessary so that they match below. 3079 if (isa<SCEVConstant>(LHS)) 3080 std::swap(PreCondLHS, PreCondRHS); 3081 break; 3082 } 3083 continue; 3084 default: 3085 // We weren't able to reconcile the condition. 3086 continue; 3087 } 3088 3089 if (!PreCondLHS->getType()->isInteger()) continue; 3090 3091 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS); 3092 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS); 3093 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) || 3094 (LHS == getNotSCEV(PreCondRHSSCEV) && 3095 RHS == getNotSCEV(PreCondLHSSCEV))) 3096 return true; 3097 } 3098 3099 return false; 3100} 3101 3102/// HowManyLessThans - Return the number of times a backedge containing the 3103/// specified less-than comparison will execute. If not computable, return 3104/// UnknownValue. 3105ScalarEvolution::BackedgeTakenInfo ScalarEvolution:: 3106HowManyLessThans(const SCEV *LHS, const SCEV *RHS, 3107 const Loop *L, bool isSigned) { 3108 // Only handle: "ADDREC < LoopInvariant". 3109 if (!RHS->isLoopInvariant(L)) return UnknownValue; 3110 3111 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS); 3112 if (!AddRec || AddRec->getLoop() != L) 3113 return UnknownValue; 3114 3115 if (AddRec->isAffine()) { 3116 // FORNOW: We only support unit strides. 3117 unsigned BitWidth = getTypeSizeInBits(AddRec->getType()); 3118 SCEVHandle Step = AddRec->getStepRecurrence(*this); 3119 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType()); 3120 3121 // TODO: handle non-constant strides. 3122 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step); 3123 if (!CStep || CStep->isZero()) 3124 return UnknownValue; 3125 if (CStep->getValue()->getValue() == 1) { 3126 // With unit stride, the iteration never steps past the limit value. 3127 } else if (CStep->getValue()->getValue().isStrictlyPositive()) { 3128 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) { 3129 // Test whether a positive iteration iteration can step past the limit 3130 // value and past the maximum value for its type in a single step. 3131 if (isSigned) { 3132 APInt Max = APInt::getSignedMaxValue(BitWidth); 3133 if ((Max - CStep->getValue()->getValue()) 3134 .slt(CLimit->getValue()->getValue())) 3135 return UnknownValue; 3136 } else { 3137 APInt Max = APInt::getMaxValue(BitWidth); 3138 if ((Max - CStep->getValue()->getValue()) 3139 .ult(CLimit->getValue()->getValue())) 3140 return UnknownValue; 3141 } 3142 } else 3143 // TODO: handle non-constant limit values below. 3144 return UnknownValue; 3145 } else 3146 // TODO: handle negative strides below. 3147 return UnknownValue; 3148 3149 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant 3150 // m. So, we count the number of iterations in which {n,+,s} < m is true. 3151 // Note that we cannot simply return max(m-n,0)/s because it's not safe to 3152 // treat m-n as signed nor unsigned due to overflow possibility. 3153 3154 // First, we get the value of the LHS in the first iteration: n 3155 SCEVHandle Start = AddRec->getOperand(0); 3156 3157 // Determine the minimum constant start value. 3158 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start : 3159 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) : 3160 APInt::getMinValue(BitWidth)); 3161 3162 // If we know that the condition is true in order to enter the loop, 3163 // then we know that it will run exactly (m-n)/s times. Otherwise, we 3164 // only know if will execute (max(m,n)-n)/s times. In both cases, the 3165 // division must round up. 3166 SCEVHandle End = RHS; 3167 if (!isLoopGuardedByCond(L, 3168 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, 3169 getMinusSCEV(Start, Step), RHS)) 3170 End = isSigned ? getSMaxExpr(RHS, Start) 3171 : getUMaxExpr(RHS, Start); 3172 3173 // Determine the maximum constant end value. 3174 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End : 3175 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) : 3176 APInt::getMaxValue(BitWidth)); 3177 3178 // Finally, we subtract these two values and divide, rounding up, to get 3179 // the number of times the backedge is executed. 3180 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start), 3181 getAddExpr(Step, NegOne)), 3182 Step); 3183 3184 // The maximum backedge count is similar, except using the minimum start 3185 // value and the maximum end value. 3186 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd, 3187 MinStart), 3188 getAddExpr(Step, NegOne)), 3189 Step); 3190 3191 return BackedgeTakenInfo(BECount, MaxBECount); 3192 } 3193 3194 return UnknownValue; 3195} 3196 3197/// getNumIterationsInRange - Return the number of iterations of this loop that 3198/// produce values in the specified constant range. Another way of looking at 3199/// this is that it returns the first iteration number where the value is not in 3200/// the condition, thus computing the exit count. If the iteration count can't 3201/// be computed, an instance of SCEVCouldNotCompute is returned. 3202SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, 3203 ScalarEvolution &SE) const { 3204 if (Range.isFullSet()) // Infinite loop. 3205 return SE.getCouldNotCompute(); 3206 3207 // If the start is a non-zero constant, shift the range to simplify things. 3208 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 3209 if (!SC->getValue()->isZero()) { 3210 std::vector<SCEVHandle> Operands(op_begin(), op_end()); 3211 Operands[0] = SE.getIntegerSCEV(0, SC->getType()); 3212 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop()); 3213 if (const SCEVAddRecExpr *ShiftedAddRec = 3214 dyn_cast<SCEVAddRecExpr>(Shifted)) 3215 return ShiftedAddRec->getNumIterationsInRange( 3216 Range.subtract(SC->getValue()->getValue()), SE); 3217 // This is strange and shouldn't happen. 3218 return SE.getCouldNotCompute(); 3219 } 3220 3221 // The only time we can solve this is when we have all constant indices. 3222 // Otherwise, we cannot determine the overflow conditions. 3223 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 3224 if (!isa<SCEVConstant>(getOperand(i))) 3225 return SE.getCouldNotCompute(); 3226 3227 3228 // Okay at this point we know that all elements of the chrec are constants and 3229 // that the start element is zero. 3230 3231 // First check to see if the range contains zero. If not, the first 3232 // iteration exits. 3233 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 3234 if (!Range.contains(APInt(BitWidth, 0))) 3235 return SE.getConstant(ConstantInt::get(getType(),0)); 3236 3237 if (isAffine()) { 3238 // If this is an affine expression then we have this situation: 3239 // Solve {0,+,A} in Range === Ax in Range 3240 3241 // We know that zero is in the range. If A is positive then we know that 3242 // the upper value of the range must be the first possible exit value. 3243 // If A is negative then the lower of the range is the last possible loop 3244 // value. Also note that we already checked for a full range. 3245 APInt One(BitWidth,1); 3246 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue(); 3247 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 3248 3249 // The exit value should be (End+A)/A. 3250 APInt ExitVal = (End + A).udiv(A); 3251 ConstantInt *ExitValue = ConstantInt::get(ExitVal); 3252 3253 // Evaluate at the exit value. If we really did fall out of the valid 3254 // range, then we computed our trip count, otherwise wrap around or other 3255 // things must have happened. 3256 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 3257 if (Range.contains(Val->getValue())) 3258 return SE.getCouldNotCompute(); // Something strange happened 3259 3260 // Ensure that the previous value is in the range. This is a sanity check. 3261 assert(Range.contains( 3262 EvaluateConstantChrecAtConstant(this, 3263 ConstantInt::get(ExitVal - One), SE)->getValue()) && 3264 "Linear scev computation is off in a bad way!"); 3265 return SE.getConstant(ExitValue); 3266 } else if (isQuadratic()) { 3267 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 3268 // quadratic equation to solve it. To do this, we must frame our problem in 3269 // terms of figuring out when zero is crossed, instead of when 3270 // Range.getUpper() is crossed. 3271 std::vector<SCEVHandle> NewOps(op_begin(), op_end()); 3272 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 3273 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop()); 3274 3275 // Next, solve the constructed addrec 3276 std::pair<SCEVHandle,SCEVHandle> Roots = 3277 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE); 3278 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 3279 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 3280 if (R1) { 3281 // Pick the smallest positive root value. 3282 if (ConstantInt *CB = 3283 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 3284 R1->getValue(), R2->getValue()))) { 3285 if (CB->getZExtValue() == false) 3286 std::swap(R1, R2); // R1 is the minimum root now. 3287 3288 // Make sure the root is not off by one. The returned iteration should 3289 // not be in the range, but the previous one should be. When solving 3290 // for "X*X < 5", for example, we should not return a root of 2. 3291 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, 3292 R1->getValue(), 3293 SE); 3294 if (Range.contains(R1Val->getValue())) { 3295 // The next iteration must be out of the range... 3296 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1); 3297 3298 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 3299 if (!Range.contains(R1Val->getValue())) 3300 return SE.getConstant(NextVal); 3301 return SE.getCouldNotCompute(); // Something strange happened 3302 } 3303 3304 // If R1 was not in the range, then it is a good return value. Make 3305 // sure that R1-1 WAS in the range though, just in case. 3306 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1); 3307 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 3308 if (Range.contains(R1Val->getValue())) 3309 return R1; 3310 return SE.getCouldNotCompute(); // Something strange happened 3311 } 3312 } 3313 } 3314 3315 return SE.getCouldNotCompute(); 3316} 3317 3318 3319 3320//===----------------------------------------------------------------------===// 3321// SCEVCallbackVH Class Implementation 3322//===----------------------------------------------------------------------===// 3323 3324void SCEVCallbackVH::deleted() { 3325 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!"); 3326 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 3327 SE->ConstantEvolutionLoopExitValue.erase(PN); 3328 SE->Scalars.erase(getValPtr()); 3329 // this now dangles! 3330} 3331 3332void SCEVCallbackVH::allUsesReplacedWith(Value *) { 3333 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!"); 3334 3335 // Forget all the expressions associated with users of the old value, 3336 // so that future queries will recompute the expressions using the new 3337 // value. 3338 SmallVector<User *, 16> Worklist; 3339 Value *Old = getValPtr(); 3340 bool DeleteOld = false; 3341 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end(); 3342 UI != UE; ++UI) 3343 Worklist.push_back(*UI); 3344 while (!Worklist.empty()) { 3345 User *U = Worklist.pop_back_val(); 3346 // Deleting the Old value will cause this to dangle. Postpone 3347 // that until everything else is done. 3348 if (U == Old) { 3349 DeleteOld = true; 3350 continue; 3351 } 3352 if (PHINode *PN = dyn_cast<PHINode>(U)) 3353 SE->ConstantEvolutionLoopExitValue.erase(PN); 3354 if (SE->Scalars.erase(U)) 3355 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end(); 3356 UI != UE; ++UI) 3357 Worklist.push_back(*UI); 3358 } 3359 if (DeleteOld) { 3360 if (PHINode *PN = dyn_cast<PHINode>(Old)) 3361 SE->ConstantEvolutionLoopExitValue.erase(PN); 3362 SE->Scalars.erase(Old); 3363 // this now dangles! 3364 } 3365 // this may dangle! 3366} 3367 3368SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 3369 : CallbackVH(V), SE(se) {} 3370 3371//===----------------------------------------------------------------------===// 3372// ScalarEvolution Class Implementation 3373//===----------------------------------------------------------------------===// 3374 3375ScalarEvolution::ScalarEvolution() 3376 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) { 3377} 3378 3379bool ScalarEvolution::runOnFunction(Function &F) { 3380 this->F = &F; 3381 LI = &getAnalysis<LoopInfo>(); 3382 TD = getAnalysisIfAvailable<TargetData>(); 3383 return false; 3384} 3385 3386void ScalarEvolution::releaseMemory() { 3387 Scalars.clear(); 3388 BackedgeTakenCounts.clear(); 3389 ConstantEvolutionLoopExitValue.clear(); 3390} 3391 3392void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const { 3393 AU.setPreservesAll(); 3394 AU.addRequiredTransitive<LoopInfo>(); 3395} 3396 3397bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 3398 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 3399} 3400 3401static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 3402 const Loop *L) { 3403 // Print all inner loops first 3404 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 3405 PrintLoopInfo(OS, SE, *I); 3406 3407 OS << "Loop " << L->getHeader()->getName() << ": "; 3408 3409 SmallVector<BasicBlock*, 8> ExitBlocks; 3410 L->getExitBlocks(ExitBlocks); 3411 if (ExitBlocks.size() != 1) 3412 OS << "<multiple exits> "; 3413 3414 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 3415 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 3416 } else { 3417 OS << "Unpredictable backedge-taken count. "; 3418 } 3419 3420 OS << "\n"; 3421} 3422 3423void ScalarEvolution::print(raw_ostream &OS, const Module* ) const { 3424 // ScalarEvolution's implementaiton of the print method is to print 3425 // out SCEV values of all instructions that are interesting. Doing 3426 // this potentially causes it to create new SCEV objects though, 3427 // which technically conflicts with the const qualifier. This isn't 3428 // observable from outside the class though (the hasSCEV function 3429 // notwithstanding), so casting away the const isn't dangerous. 3430 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this); 3431 3432 OS << "Classifying expressions for: " << F->getName() << "\n"; 3433 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) 3434 if (isSCEVable(I->getType())) { 3435 OS << *I; 3436 OS << " --> "; 3437 SCEVHandle SV = SE.getSCEV(&*I); 3438 SV->print(OS); 3439 OS << "\t\t"; 3440 3441 if (const Loop *L = LI->getLoopFor((*I).getParent())) { 3442 OS << "Exits: "; 3443 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop()); 3444 if (isa<SCEVCouldNotCompute>(ExitValue)) { 3445 OS << "<<Unknown>>"; 3446 } else { 3447 OS << *ExitValue; 3448 } 3449 } 3450 3451 3452 OS << "\n"; 3453 } 3454 3455 OS << "Determining loop execution counts for: " << F->getName() << "\n"; 3456 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 3457 PrintLoopInfo(OS, &SE, *I); 3458} 3459 3460void ScalarEvolution::print(std::ostream &o, const Module *M) const { 3461 raw_os_ostream OS(o); 3462 print(OS, M); 3463} 3464