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