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