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