ScalarEvolution.cpp revision a0740fbcc735eb87d7fe5111d302e4b8245120b6
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 /// hasSCEV - Return true if the SCEV for this value has already been 1099 /// computed. 1100 bool hasSCEV(Value *V) const { 1101 return Scalars.count(V); 1102 } 1103 1104 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for 1105 /// the specified value. 1106 void setSCEV(Value *V, const SCEVHandle &H) { 1107 bool isNew = Scalars.insert(std::make_pair(V, H)).second; 1108 assert(isNew && "This entry already existed!"); 1109 } 1110 1111 1112 /// getSCEVAtScope - Compute the value of the specified expression within 1113 /// the indicated loop (which may be null to indicate in no loop). If the 1114 /// expression cannot be evaluated, return UnknownValue itself. 1115 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L); 1116 1117 1118 /// hasLoopInvariantIterationCount - Return true if the specified loop has 1119 /// an analyzable loop-invariant iteration count. 1120 bool hasLoopInvariantIterationCount(const Loop *L); 1121 1122 /// getIterationCount - If the specified loop has a predictable iteration 1123 /// count, return it. Note that it is not valid to call this method on a 1124 /// loop without a loop-invariant iteration count. 1125 SCEVHandle getIterationCount(const Loop *L); 1126 1127 /// deleteInstructionFromRecords - This method should be called by the 1128 /// client before it removes an instruction from the program, to make sure 1129 /// that no dangling references are left around. 1130 void deleteInstructionFromRecords(Instruction *I); 1131 1132 private: 1133 /// createSCEV - We know that there is no SCEV for the specified value. 1134 /// Analyze the expression. 1135 SCEVHandle createSCEV(Value *V); 1136 SCEVHandle createNodeForCast(CastInst *CI); 1137 1138 /// createNodeForPHI - Provide the special handling we need to analyze PHI 1139 /// SCEVs. 1140 SCEVHandle createNodeForPHI(PHINode *PN); 1141 1142 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value 1143 /// for the specified instruction and replaces any references to the 1144 /// symbolic value SymName with the specified value. This is used during 1145 /// PHI resolution. 1146 void ReplaceSymbolicValueWithConcrete(Instruction *I, 1147 const SCEVHandle &SymName, 1148 const SCEVHandle &NewVal); 1149 1150 /// ComputeIterationCount - Compute the number of times the specified loop 1151 /// will iterate. 1152 SCEVHandle ComputeIterationCount(const Loop *L); 1153 1154 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of 1155 /// 'setcc load X, cst', try to se if we can compute the trip count. 1156 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI, 1157 Constant *RHS, 1158 const Loop *L, 1159 unsigned SetCCOpcode); 1160 1161 /// ComputeIterationCountExhaustively - If the trip is known to execute a 1162 /// constant number of times (the condition evolves only from constants), 1163 /// try to evaluate a few iterations of the loop until we get the exit 1164 /// condition gets a value of ExitWhen (true or false). If we cannot 1165 /// evaluate the trip count of the loop, return UnknownValue. 1166 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond, 1167 bool ExitWhen); 1168 1169 /// HowFarToZero - Return the number of times a backedge comparing the 1170 /// specified value to zero will execute. If not computable, return 1171 /// UnknownValue 1172 SCEVHandle HowFarToZero(SCEV *V, const Loop *L); 1173 1174 /// HowFarToNonZero - Return the number of times a backedge checking the 1175 /// specified value for nonzero will execute. If not computable, return 1176 /// UnknownValue 1177 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L); 1178 1179 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 1180 /// in the header of its containing loop, we know the loop executes a 1181 /// constant number of times, and the PHI node is just a recurrence 1182 /// involving constants, fold it. 1183 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, 1184 const Loop *L); 1185 }; 1186} 1187 1188//===----------------------------------------------------------------------===// 1189// Basic SCEV Analysis and PHI Idiom Recognition Code 1190// 1191 1192/// deleteInstructionFromRecords - This method should be called by the 1193/// client before it removes an instruction from the program, to make sure 1194/// that no dangling references are left around. 1195void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) { 1196 Scalars.erase(I); 1197 if (PHINode *PN = dyn_cast<PHINode>(I)) 1198 ConstantEvolutionLoopExitValue.erase(PN); 1199} 1200 1201 1202/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 1203/// expression and create a new one. 1204SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) { 1205 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!"); 1206 1207 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V); 1208 if (I != Scalars.end()) return I->second; 1209 SCEVHandle S = createSCEV(V); 1210 Scalars.insert(std::make_pair(V, S)); 1211 return S; 1212} 1213 1214/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for 1215/// the specified instruction and replaces any references to the symbolic value 1216/// SymName with the specified value. This is used during PHI resolution. 1217void ScalarEvolutionsImpl:: 1218ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName, 1219 const SCEVHandle &NewVal) { 1220 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I); 1221 if (SI == Scalars.end()) return; 1222 1223 SCEVHandle NV = 1224 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal); 1225 if (NV == SI->second) return; // No change. 1226 1227 SI->second = NV; // Update the scalars map! 1228 1229 // Any instruction values that use this instruction might also need to be 1230 // updated! 1231 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 1232 UI != E; ++UI) 1233 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal); 1234} 1235 1236/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in 1237/// a loop header, making it a potential recurrence, or it doesn't. 1238/// 1239SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) { 1240 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized. 1241 if (const Loop *L = LI.getLoopFor(PN->getParent())) 1242 if (L->getHeader() == PN->getParent()) { 1243 // If it lives in the loop header, it has two incoming values, one 1244 // from outside the loop, and one from inside. 1245 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 1246 unsigned BackEdge = IncomingEdge^1; 1247 1248 // While we are analyzing this PHI node, handle its value symbolically. 1249 SCEVHandle SymbolicName = SCEVUnknown::get(PN); 1250 assert(Scalars.find(PN) == Scalars.end() && 1251 "PHI node already processed?"); 1252 Scalars.insert(std::make_pair(PN, SymbolicName)); 1253 1254 // Using this symbolic name for the PHI, analyze the value coming around 1255 // the back-edge. 1256 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge)); 1257 1258 // NOTE: If BEValue is loop invariant, we know that the PHI node just 1259 // has a special value for the first iteration of the loop. 1260 1261 // If the value coming around the backedge is an add with the symbolic 1262 // value we just inserted, then we found a simple induction variable! 1263 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 1264 // If there is a single occurrence of the symbolic value, replace it 1265 // with a recurrence. 1266 unsigned FoundIndex = Add->getNumOperands(); 1267 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 1268 if (Add->getOperand(i) == SymbolicName) 1269 if (FoundIndex == e) { 1270 FoundIndex = i; 1271 break; 1272 } 1273 1274 if (FoundIndex != Add->getNumOperands()) { 1275 // Create an add with everything but the specified operand. 1276 std::vector<SCEVHandle> Ops; 1277 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 1278 if (i != FoundIndex) 1279 Ops.push_back(Add->getOperand(i)); 1280 SCEVHandle Accum = SCEVAddExpr::get(Ops); 1281 1282 // This is not a valid addrec if the step amount is varying each 1283 // loop iteration, but is not itself an addrec in this loop. 1284 if (Accum->isLoopInvariant(L) || 1285 (isa<SCEVAddRecExpr>(Accum) && 1286 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 1287 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); 1288 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L); 1289 1290 // Okay, for the entire analysis of this edge we assumed the PHI 1291 // to be symbolic. We now need to go back and update all of the 1292 // entries for the scalars that use the PHI (except for the PHI 1293 // itself) to use the new analyzed value instead of the "symbolic" 1294 // value. 1295 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 1296 return PHISCEV; 1297 } 1298 } 1299 } 1300 1301 return SymbolicName; 1302 } 1303 1304 // If it's not a loop phi, we can't handle it yet. 1305 return SCEVUnknown::get(PN); 1306} 1307 1308/// createNodeForCast - Handle the various forms of casts that we support. 1309/// 1310SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) { 1311 const Type *SrcTy = CI->getOperand(0)->getType(); 1312 const Type *DestTy = CI->getType(); 1313 1314 // If this is a noop cast (ie, conversion from int to uint), ignore it. 1315 if (SrcTy->isLosslesslyConvertibleTo(DestTy)) 1316 return getSCEV(CI->getOperand(0)); 1317 1318 if (SrcTy->isInteger() && DestTy->isInteger()) { 1319 // Otherwise, if this is a truncating integer cast, we can represent this 1320 // cast. 1321 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize()) 1322 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)), 1323 CI->getType()->getUnsignedVersion()); 1324 if (SrcTy->isUnsigned() && 1325 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize()) 1326 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)), 1327 CI->getType()->getUnsignedVersion()); 1328 } 1329 1330 // If this is an sign or zero extending cast and we can prove that the value 1331 // will never overflow, we could do similar transformations. 1332 1333 // Otherwise, we can't handle this cast! 1334 return SCEVUnknown::get(CI); 1335} 1336 1337 1338/// createSCEV - We know that there is no SCEV for the specified value. 1339/// Analyze the expression. 1340/// 1341SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) { 1342 if (Instruction *I = dyn_cast<Instruction>(V)) { 1343 switch (I->getOpcode()) { 1344 case Instruction::Add: 1345 return SCEVAddExpr::get(getSCEV(I->getOperand(0)), 1346 getSCEV(I->getOperand(1))); 1347 case Instruction::Mul: 1348 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), 1349 getSCEV(I->getOperand(1))); 1350 case Instruction::Div: 1351 if (V->getType()->isInteger() && V->getType()->isUnsigned()) 1352 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), 1353 getSCEV(I->getOperand(1))); 1354 break; 1355 1356 case Instruction::Sub: 1357 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)), 1358 getSCEV(I->getOperand(1))); 1359 1360 case Instruction::Shl: 1361 // Turn shift left of a constant amount into a multiply. 1362 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { 1363 Constant *X = ConstantInt::get(V->getType(), 1); 1364 X = ConstantExpr::getShl(X, SA); 1365 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X)); 1366 } 1367 break; 1368 1369 case Instruction::Shr: 1370 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) 1371 if (V->getType()->isUnsigned()) { 1372 Constant *X = ConstantInt::get(V->getType(), 1); 1373 X = ConstantExpr::getShl(X, SA); 1374 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X)); 1375 } 1376 break; 1377 1378 case Instruction::Cast: 1379 return createNodeForCast(cast<CastInst>(I)); 1380 1381 case Instruction::PHI: 1382 return createNodeForPHI(cast<PHINode>(I)); 1383 1384 default: // We cannot analyze this expression. 1385 break; 1386 } 1387 } 1388 1389 return SCEVUnknown::get(V); 1390} 1391 1392 1393 1394//===----------------------------------------------------------------------===// 1395// Iteration Count Computation Code 1396// 1397 1398/// getIterationCount - If the specified loop has a predictable iteration 1399/// count, return it. Note that it is not valid to call this method on a 1400/// loop without a loop-invariant iteration count. 1401SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) { 1402 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L); 1403 if (I == IterationCounts.end()) { 1404 SCEVHandle ItCount = ComputeIterationCount(L); 1405 I = IterationCounts.insert(std::make_pair(L, ItCount)).first; 1406 if (ItCount != UnknownValue) { 1407 assert(ItCount->isLoopInvariant(L) && 1408 "Computed trip count isn't loop invariant for loop!"); 1409 ++NumTripCountsComputed; 1410 } else if (isa<PHINode>(L->getHeader()->begin())) { 1411 // Only count loops that have phi nodes as not being computable. 1412 ++NumTripCountsNotComputed; 1413 } 1414 } 1415 return I->second; 1416} 1417 1418/// ComputeIterationCount - Compute the number of times the specified loop 1419/// will iterate. 1420SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) { 1421 // If the loop has a non-one exit block count, we can't analyze it. 1422 std::vector<BasicBlock*> ExitBlocks; 1423 L->getExitBlocks(ExitBlocks); 1424 if (ExitBlocks.size() != 1) return UnknownValue; 1425 1426 // Okay, there is one exit block. Try to find the condition that causes the 1427 // loop to be exited. 1428 BasicBlock *ExitBlock = ExitBlocks[0]; 1429 1430 BasicBlock *ExitingBlock = 0; 1431 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock); 1432 PI != E; ++PI) 1433 if (L->contains(*PI)) { 1434 if (ExitingBlock == 0) 1435 ExitingBlock = *PI; 1436 else 1437 return UnknownValue; // More than one block exiting! 1438 } 1439 assert(ExitingBlock && "No exits from loop, something is broken!"); 1440 1441 // Okay, we've computed the exiting block. See what condition causes us to 1442 // exit. 1443 // 1444 // FIXME: we should be able to handle switch instructions (with a single exit) 1445 // FIXME: We should handle cast of int to bool as well 1446 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 1447 if (ExitBr == 0) return UnknownValue; 1448 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!"); 1449 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition()); 1450 if (ExitCond == 0) // Not a setcc 1451 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(), 1452 ExitBr->getSuccessor(0) == ExitBlock); 1453 1454 // If the condition was exit on true, convert the condition to exit on false. 1455 Instruction::BinaryOps Cond; 1456 if (ExitBr->getSuccessor(1) == ExitBlock) 1457 Cond = ExitCond->getOpcode(); 1458 else 1459 Cond = ExitCond->getInverseCondition(); 1460 1461 // Handle common loops like: for (X = "string"; *X; ++X) 1462 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 1463 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 1464 SCEVHandle ItCnt = 1465 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond); 1466 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt; 1467 } 1468 1469 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0)); 1470 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1)); 1471 1472 // Try to evaluate any dependencies out of the loop. 1473 SCEVHandle Tmp = getSCEVAtScope(LHS, L); 1474 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp; 1475 Tmp = getSCEVAtScope(RHS, L); 1476 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp; 1477 1478 // At this point, we would like to compute how many iterations of the loop the 1479 // predicate will return true for these inputs. 1480 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) { 1481 // If there is a constant, force it into the RHS. 1482 std::swap(LHS, RHS); 1483 Cond = SetCondInst::getSwappedCondition(Cond); 1484 } 1485 1486 // FIXME: think about handling pointer comparisons! i.e.: 1487 // while (P != P+100) ++P; 1488 1489 // If we have a comparison of a chrec against a constant, try to use value 1490 // ranges to answer this query. 1491 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 1492 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 1493 if (AddRec->getLoop() == L) { 1494 // Form the comparison range using the constant of the correct type so 1495 // that the ConstantRange class knows to do a signed or unsigned 1496 // comparison. 1497 ConstantInt *CompVal = RHSC->getValue(); 1498 const Type *RealTy = ExitCond->getOperand(0)->getType(); 1499 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy)); 1500 if (CompVal) { 1501 // Form the constant range. 1502 ConstantRange CompRange(Cond, CompVal); 1503 1504 // Now that we have it, if it's signed, convert it to an unsigned 1505 // range. 1506 if (CompRange.getLower()->getType()->isSigned()) { 1507 const Type *NewTy = RHSC->getValue()->getType(); 1508 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy); 1509 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy); 1510 CompRange = ConstantRange(NewL, NewU); 1511 } 1512 1513 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange); 1514 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 1515 } 1516 } 1517 1518 switch (Cond) { 1519 case Instruction::SetNE: // while (X != Y) 1520 // Convert to: while (X-Y != 0) 1521 if (LHS->getType()->isInteger()) { 1522 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L); 1523 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 1524 } 1525 break; 1526 case Instruction::SetEQ: 1527 // Convert to: while (X-Y == 0) // while (X == Y) 1528 if (LHS->getType()->isInteger()) { 1529 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L); 1530 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 1531 } 1532 break; 1533 default: 1534#if 0 1535 std::cerr << "ComputeIterationCount "; 1536 if (ExitCond->getOperand(0)->getType()->isUnsigned()) 1537 std::cerr << "[unsigned] "; 1538 std::cerr << *LHS << " " 1539 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n"; 1540#endif 1541 break; 1542 } 1543 1544 return ComputeIterationCountExhaustively(L, ExitCond, 1545 ExitBr->getSuccessor(0) == ExitBlock); 1546} 1547 1548static ConstantInt * 1549EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) { 1550 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C)); 1551 SCEVHandle Val = AddRec->evaluateAtIteration(InVal); 1552 assert(isa<SCEVConstant>(Val) && 1553 "Evaluation of SCEV at constant didn't fold correctly?"); 1554 return cast<SCEVConstant>(Val)->getValue(); 1555} 1556 1557/// GetAddressedElementFromGlobal - Given a global variable with an initializer 1558/// and a GEP expression (missing the pointer index) indexing into it, return 1559/// the addressed element of the initializer or null if the index expression is 1560/// invalid. 1561static Constant * 1562GetAddressedElementFromGlobal(GlobalVariable *GV, 1563 const std::vector<ConstantInt*> &Indices) { 1564 Constant *Init = GV->getInitializer(); 1565 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 1566 uint64_t Idx = Indices[i]->getRawValue(); 1567 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { 1568 assert(Idx < CS->getNumOperands() && "Bad struct index!"); 1569 Init = cast<Constant>(CS->getOperand(Idx)); 1570 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { 1571 if (Idx >= CA->getNumOperands()) return 0; // Bogus program 1572 Init = cast<Constant>(CA->getOperand(Idx)); 1573 } else if (isa<ConstantAggregateZero>(Init)) { 1574 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) { 1575 assert(Idx < STy->getNumElements() && "Bad struct index!"); 1576 Init = Constant::getNullValue(STy->getElementType(Idx)); 1577 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) { 1578 if (Idx >= ATy->getNumElements()) return 0; // Bogus program 1579 Init = Constant::getNullValue(ATy->getElementType()); 1580 } else { 1581 assert(0 && "Unknown constant aggregate type!"); 1582 } 1583 return 0; 1584 } else { 1585 return 0; // Unknown initializer type 1586 } 1587 } 1588 return Init; 1589} 1590 1591/// ComputeLoadConstantCompareIterationCount - Given an exit condition of 1592/// 'setcc load X, cst', try to se if we can compute the trip count. 1593SCEVHandle ScalarEvolutionsImpl:: 1594ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS, 1595 const Loop *L, unsigned SetCCOpcode) { 1596 if (LI->isVolatile()) return UnknownValue; 1597 1598 // Check to see if the loaded pointer is a getelementptr of a global. 1599 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 1600 if (!GEP) return UnknownValue; 1601 1602 // Make sure that it is really a constant global we are gepping, with an 1603 // initializer, and make sure the first IDX is really 0. 1604 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 1605 if (!GV || !GV->isConstant() || !GV->hasInitializer() || 1606 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 1607 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 1608 return UnknownValue; 1609 1610 // Okay, we allow one non-constant index into the GEP instruction. 1611 Value *VarIdx = 0; 1612 std::vector<ConstantInt*> Indexes; 1613 unsigned VarIdxNum = 0; 1614 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 1615 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 1616 Indexes.push_back(CI); 1617 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 1618 if (VarIdx) return UnknownValue; // Multiple non-constant idx's. 1619 VarIdx = GEP->getOperand(i); 1620 VarIdxNum = i-2; 1621 Indexes.push_back(0); 1622 } 1623 1624 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 1625 // Check to see if X is a loop variant variable value now. 1626 SCEVHandle Idx = getSCEV(VarIdx); 1627 SCEVHandle Tmp = getSCEVAtScope(Idx, L); 1628 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp; 1629 1630 // We can only recognize very limited forms of loop index expressions, in 1631 // particular, only affine AddRec's like {C1,+,C2}. 1632 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 1633 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) || 1634 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 1635 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 1636 return UnknownValue; 1637 1638 unsigned MaxSteps = MaxBruteForceIterations; 1639 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 1640 ConstantUInt *ItCst = 1641 ConstantUInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum); 1642 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst); 1643 1644 // Form the GEP offset. 1645 Indexes[VarIdxNum] = Val; 1646 1647 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes); 1648 if (Result == 0) break; // Cannot compute! 1649 1650 // Evaluate the condition for this iteration. 1651 Result = ConstantExpr::get(SetCCOpcode, Result, RHS); 1652 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure 1653 if (Result == ConstantBool::False) { 1654#if 0 1655 std::cerr << "\n***\n*** Computed loop count " << *ItCst 1656 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() 1657 << "***\n"; 1658#endif 1659 ++NumArrayLenItCounts; 1660 return SCEVConstant::get(ItCst); // Found terminating iteration! 1661 } 1662 } 1663 return UnknownValue; 1664} 1665 1666 1667/// CanConstantFold - Return true if we can constant fold an instruction of the 1668/// specified type, assuming that all operands were constants. 1669static bool CanConstantFold(const Instruction *I) { 1670 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) || 1671 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I)) 1672 return true; 1673 1674 if (const CallInst *CI = dyn_cast<CallInst>(I)) 1675 if (const Function *F = CI->getCalledFunction()) 1676 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast 1677 return false; 1678} 1679 1680/// ConstantFold - Constant fold an instruction of the specified type with the 1681/// specified constant operands. This function may modify the operands vector. 1682static Constant *ConstantFold(const Instruction *I, 1683 std::vector<Constant*> &Operands) { 1684 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) 1685 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]); 1686 1687 switch (I->getOpcode()) { 1688 case Instruction::Cast: 1689 return ConstantExpr::getCast(Operands[0], I->getType()); 1690 case Instruction::Select: 1691 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]); 1692 case Instruction::Call: 1693 if (Function *GV = dyn_cast<Function>(Operands[0])) { 1694 Operands.erase(Operands.begin()); 1695 return ConstantFoldCall(cast<Function>(GV), Operands); 1696 } 1697 1698 return 0; 1699 case Instruction::GetElementPtr: 1700 Constant *Base = Operands[0]; 1701 Operands.erase(Operands.begin()); 1702 return ConstantExpr::getGetElementPtr(Base, Operands); 1703 } 1704 return 0; 1705} 1706 1707 1708/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 1709/// in the loop that V is derived from. We allow arbitrary operations along the 1710/// way, but the operands of an operation must either be constants or a value 1711/// derived from a constant PHI. If this expression does not fit with these 1712/// constraints, return null. 1713static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 1714 // If this is not an instruction, or if this is an instruction outside of the 1715 // loop, it can't be derived from a loop PHI. 1716 Instruction *I = dyn_cast<Instruction>(V); 1717 if (I == 0 || !L->contains(I->getParent())) return 0; 1718 1719 if (PHINode *PN = dyn_cast<PHINode>(I)) 1720 if (L->getHeader() == I->getParent()) 1721 return PN; 1722 else 1723 // We don't currently keep track of the control flow needed to evaluate 1724 // PHIs, so we cannot handle PHIs inside of loops. 1725 return 0; 1726 1727 // If we won't be able to constant fold this expression even if the operands 1728 // are constants, return early. 1729 if (!CanConstantFold(I)) return 0; 1730 1731 // Otherwise, we can evaluate this instruction if all of its operands are 1732 // constant or derived from a PHI node themselves. 1733 PHINode *PHI = 0; 1734 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op) 1735 if (!(isa<Constant>(I->getOperand(Op)) || 1736 isa<GlobalValue>(I->getOperand(Op)))) { 1737 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L); 1738 if (P == 0) return 0; // Not evolving from PHI 1739 if (PHI == 0) 1740 PHI = P; 1741 else if (PHI != P) 1742 return 0; // Evolving from multiple different PHIs. 1743 } 1744 1745 // This is a expression evolving from a constant PHI! 1746 return PHI; 1747} 1748 1749/// EvaluateExpression - Given an expression that passes the 1750/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 1751/// in the loop has the value PHIVal. If we can't fold this expression for some 1752/// reason, return null. 1753static Constant *EvaluateExpression(Value *V, Constant *PHIVal) { 1754 if (isa<PHINode>(V)) return PHIVal; 1755 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) 1756 return GV; 1757 if (Constant *C = dyn_cast<Constant>(V)) return C; 1758 Instruction *I = cast<Instruction>(V); 1759 1760 std::vector<Constant*> Operands; 1761 Operands.resize(I->getNumOperands()); 1762 1763 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 1764 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal); 1765 if (Operands[i] == 0) return 0; 1766 } 1767 1768 return ConstantFold(I, Operands); 1769} 1770 1771/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 1772/// in the header of its containing loop, we know the loop executes a 1773/// constant number of times, and the PHI node is just a recurrence 1774/// involving constants, fold it. 1775Constant *ScalarEvolutionsImpl:: 1776getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) { 1777 std::map<PHINode*, Constant*>::iterator I = 1778 ConstantEvolutionLoopExitValue.find(PN); 1779 if (I != ConstantEvolutionLoopExitValue.end()) 1780 return I->second; 1781 1782 if (Its > MaxBruteForceIterations) 1783 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it. 1784 1785 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 1786 1787 // Since the loop is canonicalized, the PHI node must have two entries. One 1788 // entry must be a constant (coming in from outside of the loop), and the 1789 // second must be derived from the same PHI. 1790 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 1791 Constant *StartCST = 1792 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 1793 if (StartCST == 0) 1794 return RetVal = 0; // Must be a constant. 1795 1796 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 1797 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 1798 if (PN2 != PN) 1799 return RetVal = 0; // Not derived from same PHI. 1800 1801 // Execute the loop symbolically to determine the exit value. 1802 unsigned IterationNum = 0; 1803 unsigned NumIterations = Its; 1804 if (NumIterations != Its) 1805 return RetVal = 0; // More than 2^32 iterations?? 1806 1807 for (Constant *PHIVal = StartCST; ; ++IterationNum) { 1808 if (IterationNum == NumIterations) 1809 return RetVal = PHIVal; // Got exit value! 1810 1811 // Compute the value of the PHI node for the next iteration. 1812 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 1813 if (NextPHI == PHIVal) 1814 return RetVal = NextPHI; // Stopped evolving! 1815 if (NextPHI == 0) 1816 return 0; // Couldn't evaluate! 1817 PHIVal = NextPHI; 1818 } 1819} 1820 1821/// ComputeIterationCountExhaustively - If the trip is known to execute a 1822/// constant number of times (the condition evolves only from constants), 1823/// try to evaluate a few iterations of the loop until we get the exit 1824/// condition gets a value of ExitWhen (true or false). If we cannot 1825/// evaluate the trip count of the loop, return UnknownValue. 1826SCEVHandle ScalarEvolutionsImpl:: 1827ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) { 1828 PHINode *PN = getConstantEvolvingPHI(Cond, L); 1829 if (PN == 0) return UnknownValue; 1830 1831 // Since the loop is canonicalized, the PHI node must have two entries. One 1832 // entry must be a constant (coming in from outside of the loop), and the 1833 // second must be derived from the same PHI. 1834 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 1835 Constant *StartCST = 1836 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 1837 if (StartCST == 0) return UnknownValue; // Must be a constant. 1838 1839 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 1840 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 1841 if (PN2 != PN) return UnknownValue; // Not derived from same PHI. 1842 1843 // Okay, we find a PHI node that defines the trip count of this loop. Execute 1844 // the loop symbolically to determine when the condition gets a value of 1845 // "ExitWhen". 1846 unsigned IterationNum = 0; 1847 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 1848 for (Constant *PHIVal = StartCST; 1849 IterationNum != MaxIterations; ++IterationNum) { 1850 ConstantBool *CondVal = 1851 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal)); 1852 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate. 1853 1854 if (CondVal->getValue() == ExitWhen) { 1855 ConstantEvolutionLoopExitValue[PN] = PHIVal; 1856 ++NumBruteForceTripCountsComputed; 1857 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum)); 1858 } 1859 1860 // Compute the value of the PHI node for the next iteration. 1861 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 1862 if (NextPHI == 0 || NextPHI == PHIVal) 1863 return UnknownValue; // Couldn't evaluate or not making progress... 1864 PHIVal = NextPHI; 1865 } 1866 1867 // Too many iterations were needed to evaluate. 1868 return UnknownValue; 1869} 1870 1871/// getSCEVAtScope - Compute the value of the specified expression within the 1872/// indicated loop (which may be null to indicate in no loop). If the 1873/// expression cannot be evaluated, return UnknownValue. 1874SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) { 1875 // FIXME: this should be turned into a virtual method on SCEV! 1876 1877 if (isa<SCEVConstant>(V)) return V; 1878 1879 // If this instruction is evolves from a constant-evolving PHI, compute the 1880 // exit value from the loop without using SCEVs. 1881 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 1882 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 1883 const Loop *LI = this->LI[I->getParent()]; 1884 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 1885 if (PHINode *PN = dyn_cast<PHINode>(I)) 1886 if (PN->getParent() == LI->getHeader()) { 1887 // Okay, there is no closed form solution for the PHI node. Check 1888 // to see if the loop that contains it has a known iteration count. 1889 // If so, we may be able to force computation of the exit value. 1890 SCEVHandle IterationCount = getIterationCount(LI); 1891 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) { 1892 // Okay, we know how many times the containing loop executes. If 1893 // this is a constant evolving PHI node, get the final value at 1894 // the specified iteration number. 1895 Constant *RV = getConstantEvolutionLoopExitValue(PN, 1896 ICC->getValue()->getRawValue(), 1897 LI); 1898 if (RV) return SCEVUnknown::get(RV); 1899 } 1900 } 1901 1902 // Okay, this is a some expression that we cannot symbolically evaluate 1903 // into a SCEV. Check to see if it's possible to symbolically evaluate 1904 // the arguments into constants, and if see, try to constant propagate the 1905 // result. This is particularly useful for computing loop exit values. 1906 if (CanConstantFold(I)) { 1907 std::vector<Constant*> Operands; 1908 Operands.reserve(I->getNumOperands()); 1909 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 1910 Value *Op = I->getOperand(i); 1911 if (Constant *C = dyn_cast<Constant>(Op)) { 1912 Operands.push_back(C); 1913 } else { 1914 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L); 1915 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) 1916 Operands.push_back(ConstantExpr::getCast(SC->getValue(), 1917 Op->getType())); 1918 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) { 1919 if (Constant *C = dyn_cast<Constant>(SU->getValue())) 1920 Operands.push_back(ConstantExpr::getCast(C, Op->getType())); 1921 else 1922 return V; 1923 } else { 1924 return V; 1925 } 1926 } 1927 } 1928 return SCEVUnknown::get(ConstantFold(I, Operands)); 1929 } 1930 } 1931 1932 // This is some other type of SCEVUnknown, just return it. 1933 return V; 1934 } 1935 1936 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 1937 // Avoid performing the look-up in the common case where the specified 1938 // expression has no loop-variant portions. 1939 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 1940 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 1941 if (OpAtScope != Comm->getOperand(i)) { 1942 if (OpAtScope == UnknownValue) return UnknownValue; 1943 // Okay, at least one of these operands is loop variant but might be 1944 // foldable. Build a new instance of the folded commutative expression. 1945 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i); 1946 NewOps.push_back(OpAtScope); 1947 1948 for (++i; i != e; ++i) { 1949 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 1950 if (OpAtScope == UnknownValue) return UnknownValue; 1951 NewOps.push_back(OpAtScope); 1952 } 1953 if (isa<SCEVAddExpr>(Comm)) 1954 return SCEVAddExpr::get(NewOps); 1955 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!"); 1956 return SCEVMulExpr::get(NewOps); 1957 } 1958 } 1959 // If we got here, all operands are loop invariant. 1960 return Comm; 1961 } 1962 1963 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) { 1964 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L); 1965 if (LHS == UnknownValue) return LHS; 1966 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L); 1967 if (RHS == UnknownValue) return RHS; 1968 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS()) 1969 return UDiv; // must be loop invariant 1970 return SCEVUDivExpr::get(LHS, RHS); 1971 } 1972 1973 // If this is a loop recurrence for a loop that does not contain L, then we 1974 // are dealing with the final value computed by the loop. 1975 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 1976 if (!L || !AddRec->getLoop()->contains(L->getHeader())) { 1977 // To evaluate this recurrence, we need to know how many times the AddRec 1978 // loop iterates. Compute this now. 1979 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop()); 1980 if (IterationCount == UnknownValue) return UnknownValue; 1981 IterationCount = getTruncateOrZeroExtend(IterationCount, 1982 AddRec->getType()); 1983 1984 // If the value is affine, simplify the expression evaluation to just 1985 // Start + Step*IterationCount. 1986 if (AddRec->isAffine()) 1987 return SCEVAddExpr::get(AddRec->getStart(), 1988 SCEVMulExpr::get(IterationCount, 1989 AddRec->getOperand(1))); 1990 1991 // Otherwise, evaluate it the hard way. 1992 return AddRec->evaluateAtIteration(IterationCount); 1993 } 1994 return UnknownValue; 1995 } 1996 1997 //assert(0 && "Unknown SCEV type!"); 1998 return UnknownValue; 1999} 2000 2001 2002/// SolveQuadraticEquation - Find the roots of the quadratic equation for the 2003/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which 2004/// might be the same) or two SCEVCouldNotCompute objects. 2005/// 2006static std::pair<SCEVHandle,SCEVHandle> 2007SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) { 2008 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 2009 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 2010 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 2011 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 2012 2013 // We currently can only solve this if the coefficients are constants. 2014 if (!L || !M || !N) { 2015 SCEV *CNC = new SCEVCouldNotCompute(); 2016 return std::make_pair(CNC, CNC); 2017 } 2018 2019 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2); 2020 2021 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 2022 Constant *C = L->getValue(); 2023 // The B coefficient is M-N/2 2024 Constant *B = ConstantExpr::getSub(M->getValue(), 2025 ConstantExpr::getDiv(N->getValue(), 2026 Two)); 2027 // The A coefficient is N/2 2028 Constant *A = ConstantExpr::getDiv(N->getValue(), Two); 2029 2030 // Compute the B^2-4ac term. 2031 Constant *SqrtTerm = 2032 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4), 2033 ConstantExpr::getMul(A, C)); 2034 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm); 2035 2036 // Compute floor(sqrt(B^2-4ac)) 2037 ConstantUInt *SqrtVal = 2038 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm, 2039 SqrtTerm->getType()->getUnsignedVersion())); 2040 uint64_t SqrtValV = SqrtVal->getValue(); 2041 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV); 2042 // The square root might not be precise for arbitrary 64-bit integer 2043 // values. Do some sanity checks to ensure it's correct. 2044 if (SqrtValV2*SqrtValV2 > SqrtValV || 2045 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) { 2046 SCEV *CNC = new SCEVCouldNotCompute(); 2047 return std::make_pair(CNC, CNC); 2048 } 2049 2050 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2); 2051 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType()); 2052 2053 Constant *NegB = ConstantExpr::getNeg(B); 2054 Constant *TwoA = ConstantExpr::getMul(A, Two); 2055 2056 // The divisions must be performed as signed divisions. 2057 const Type *SignedTy = NegB->getType()->getSignedVersion(); 2058 NegB = ConstantExpr::getCast(NegB, SignedTy); 2059 TwoA = ConstantExpr::getCast(TwoA, SignedTy); 2060 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy); 2061 2062 Constant *Solution1 = 2063 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA); 2064 Constant *Solution2 = 2065 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA); 2066 return std::make_pair(SCEVUnknown::get(Solution1), 2067 SCEVUnknown::get(Solution2)); 2068} 2069 2070/// HowFarToZero - Return the number of times a backedge comparing the specified 2071/// value to zero will execute. If not computable, return UnknownValue 2072SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) { 2073 // If the value is a constant 2074 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 2075 // If the value is already zero, the branch will execute zero times. 2076 if (C->getValue()->isNullValue()) return C; 2077 return UnknownValue; // Otherwise it will loop infinitely. 2078 } 2079 2080 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 2081 if (!AddRec || AddRec->getLoop() != L) 2082 return UnknownValue; 2083 2084 if (AddRec->isAffine()) { 2085 // If this is an affine expression the execution count of this branch is 2086 // equal to: 2087 // 2088 // (0 - Start/Step) iff Start % Step == 0 2089 // 2090 // Get the initial value for the loop. 2091 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 2092 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue; 2093 SCEVHandle Step = AddRec->getOperand(1); 2094 2095 Step = getSCEVAtScope(Step, L->getParentLoop()); 2096 2097 // Figure out if Start % Step == 0. 2098 // FIXME: We should add DivExpr and RemExpr operations to our AST. 2099 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) { 2100 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0 2101 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start 2102 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0 2103 return Start; // 0 - Start/-1 == Start 2104 2105 // Check to see if Start is divisible by SC with no remainder. 2106 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { 2107 ConstantInt *StartCC = StartC->getValue(); 2108 Constant *StartNegC = ConstantExpr::getNeg(StartCC); 2109 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue()); 2110 if (Rem->isNullValue()) { 2111 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue()); 2112 return SCEVUnknown::get(Result); 2113 } 2114 } 2115 } 2116 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) { 2117 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 2118 // the quadratic equation to solve it. 2119 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec); 2120 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 2121 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 2122 if (R1) { 2123#if 0 2124 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1 2125 << " sol#2: " << *R2 << "\n"; 2126#endif 2127 // Pick the smallest positive root value. 2128 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?"); 2129 if (ConstantBool *CB = 2130 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(), 2131 R2->getValue()))) { 2132 if (CB != ConstantBool::True) 2133 std::swap(R1, R2); // R1 is the minimum root now. 2134 2135 // We can only use this value if the chrec ends up with an exact zero 2136 // value at this index. When solving for "X*X != 5", for example, we 2137 // should not accept a root of 2. 2138 SCEVHandle Val = AddRec->evaluateAtIteration(R1); 2139 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val)) 2140 if (EvalVal->getValue()->isNullValue()) 2141 return R1; // We found a quadratic root! 2142 } 2143 } 2144 } 2145 2146 return UnknownValue; 2147} 2148 2149/// HowFarToNonZero - Return the number of times a backedge checking the 2150/// specified value for nonzero will execute. If not computable, return 2151/// UnknownValue 2152SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) { 2153 // Loops that look like: while (X == 0) are very strange indeed. We don't 2154 // handle them yet except for the trivial case. This could be expanded in the 2155 // future as needed. 2156 2157 // If the value is a constant, check to see if it is known to be non-zero 2158 // already. If so, the backedge will execute zero times. 2159 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 2160 Constant *Zero = Constant::getNullValue(C->getValue()->getType()); 2161 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero); 2162 if (NonZero == ConstantBool::True) 2163 return getSCEV(Zero); 2164 return UnknownValue; // Otherwise it will loop infinitely. 2165 } 2166 2167 // We could implement others, but I really doubt anyone writes loops like 2168 // this, and if they did, they would already be constant folded. 2169 return UnknownValue; 2170} 2171 2172/// getNumIterationsInRange - Return the number of iterations of this loop that 2173/// produce values in the specified constant range. Another way of looking at 2174/// this is that it returns the first iteration number where the value is not in 2175/// the condition, thus computing the exit count. If the iteration count can't 2176/// be computed, an instance of SCEVCouldNotCompute is returned. 2177SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const { 2178 if (Range.isFullSet()) // Infinite loop. 2179 return new SCEVCouldNotCompute(); 2180 2181 // If the start is a non-zero constant, shift the range to simplify things. 2182 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 2183 if (!SC->getValue()->isNullValue()) { 2184 std::vector<SCEVHandle> Operands(op_begin(), op_end()); 2185 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType()); 2186 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop()); 2187 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 2188 return ShiftedAddRec->getNumIterationsInRange( 2189 Range.subtract(SC->getValue())); 2190 // This is strange and shouldn't happen. 2191 return new SCEVCouldNotCompute(); 2192 } 2193 2194 // The only time we can solve this is when we have all constant indices. 2195 // Otherwise, we cannot determine the overflow conditions. 2196 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 2197 if (!isa<SCEVConstant>(getOperand(i))) 2198 return new SCEVCouldNotCompute(); 2199 2200 2201 // Okay at this point we know that all elements of the chrec are constants and 2202 // that the start element is zero. 2203 2204 // First check to see if the range contains zero. If not, the first 2205 // iteration exits. 2206 ConstantInt *Zero = ConstantInt::get(getType(), 0); 2207 if (!Range.contains(Zero)) return SCEVConstant::get(Zero); 2208 2209 if (isAffine()) { 2210 // If this is an affine expression then we have this situation: 2211 // Solve {0,+,A} in Range === Ax in Range 2212 2213 // Since we know that zero is in the range, we know that the upper value of 2214 // the range must be the first possible exit value. Also note that we 2215 // already checked for a full range. 2216 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper()); 2217 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue(); 2218 ConstantInt *One = ConstantInt::get(getType(), 1); 2219 2220 // The exit value should be (Upper+A-1)/A. 2221 Constant *ExitValue = Upper; 2222 if (A != One) { 2223 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One); 2224 ExitValue = ConstantExpr::getDiv(ExitValue, A); 2225 } 2226 assert(isa<ConstantInt>(ExitValue) && 2227 "Constant folding of integers not implemented?"); 2228 2229 // Evaluate at the exit value. If we really did fall out of the valid 2230 // range, then we computed our trip count, otherwise wrap around or other 2231 // things must have happened. 2232 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue); 2233 if (Range.contains(Val)) 2234 return new SCEVCouldNotCompute(); // Something strange happened 2235 2236 // Ensure that the previous value is in the range. This is a sanity check. 2237 assert(Range.contains(EvaluateConstantChrecAtConstant(this, 2238 ConstantExpr::getSub(ExitValue, One))) && 2239 "Linear scev computation is off in a bad way!"); 2240 return SCEVConstant::get(cast<ConstantInt>(ExitValue)); 2241 } else if (isQuadratic()) { 2242 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 2243 // quadratic equation to solve it. To do this, we must frame our problem in 2244 // terms of figuring out when zero is crossed, instead of when 2245 // Range.getUpper() is crossed. 2246 std::vector<SCEVHandle> NewOps(op_begin(), op_end()); 2247 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper())); 2248 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop()); 2249 2250 // Next, solve the constructed addrec 2251 std::pair<SCEVHandle,SCEVHandle> Roots = 2252 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec)); 2253 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 2254 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 2255 if (R1) { 2256 // Pick the smallest positive root value. 2257 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?"); 2258 if (ConstantBool *CB = 2259 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(), 2260 R2->getValue()))) { 2261 if (CB != ConstantBool::True) 2262 std::swap(R1, R2); // R1 is the minimum root now. 2263 2264 // Make sure the root is not off by one. The returned iteration should 2265 // not be in the range, but the previous one should be. When solving 2266 // for "X*X < 5", for example, we should not return a root of 2. 2267 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, 2268 R1->getValue()); 2269 if (Range.contains(R1Val)) { 2270 // The next iteration must be out of the range... 2271 Constant *NextVal = 2272 ConstantExpr::getAdd(R1->getValue(), 2273 ConstantInt::get(R1->getType(), 1)); 2274 2275 R1Val = EvaluateConstantChrecAtConstant(this, NextVal); 2276 if (!Range.contains(R1Val)) 2277 return SCEVUnknown::get(NextVal); 2278 return new SCEVCouldNotCompute(); // Something strange happened 2279 } 2280 2281 // If R1 was not in the range, then it is a good return value. Make 2282 // sure that R1-1 WAS in the range though, just in case. 2283 Constant *NextVal = 2284 ConstantExpr::getSub(R1->getValue(), 2285 ConstantInt::get(R1->getType(), 1)); 2286 R1Val = EvaluateConstantChrecAtConstant(this, NextVal); 2287 if (Range.contains(R1Val)) 2288 return R1; 2289 return new SCEVCouldNotCompute(); // Something strange happened 2290 } 2291 } 2292 } 2293 2294 // Fallback, if this is a general polynomial, figure out the progression 2295 // through brute force: evaluate until we find an iteration that fails the 2296 // test. This is likely to be slow, but getting an accurate trip count is 2297 // incredibly important, we will be able to simplify the exit test a lot, and 2298 // we are almost guaranteed to get a trip count in this case. 2299 ConstantInt *TestVal = ConstantInt::get(getType(), 0); 2300 ConstantInt *One = ConstantInt::get(getType(), 1); 2301 ConstantInt *EndVal = TestVal; // Stop when we wrap around. 2302 do { 2303 ++NumBruteForceEvaluations; 2304 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal)); 2305 if (!isa<SCEVConstant>(Val)) // This shouldn't happen. 2306 return new SCEVCouldNotCompute(); 2307 2308 // Check to see if we found the value! 2309 if (!Range.contains(cast<SCEVConstant>(Val)->getValue())) 2310 return SCEVConstant::get(TestVal); 2311 2312 // Increment to test the next index. 2313 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One)); 2314 } while (TestVal != EndVal); 2315 2316 return new SCEVCouldNotCompute(); 2317} 2318 2319 2320 2321//===----------------------------------------------------------------------===// 2322// ScalarEvolution Class Implementation 2323//===----------------------------------------------------------------------===// 2324 2325bool ScalarEvolution::runOnFunction(Function &F) { 2326 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>()); 2327 return false; 2328} 2329 2330void ScalarEvolution::releaseMemory() { 2331 delete (ScalarEvolutionsImpl*)Impl; 2332 Impl = 0; 2333} 2334 2335void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const { 2336 AU.setPreservesAll(); 2337 AU.addRequiredTransitive<LoopInfo>(); 2338} 2339 2340SCEVHandle ScalarEvolution::getSCEV(Value *V) const { 2341 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V); 2342} 2343 2344/// hasSCEV - Return true if the SCEV for this value has already been 2345/// computed. 2346bool ScalarEvolution::hasSCEV(Value *V) const { 2347 ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V); 2348} 2349 2350 2351/// setSCEV - Insert the specified SCEV into the map of current SCEVs for 2352/// the specified value. 2353void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) { 2354 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H); 2355} 2356 2357 2358SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const { 2359 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L); 2360} 2361 2362bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const { 2363 return !isa<SCEVCouldNotCompute>(getIterationCount(L)); 2364} 2365 2366SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const { 2367 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L); 2368} 2369 2370void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const { 2371 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I); 2372} 2373 2374static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE, 2375 const Loop *L) { 2376 // Print all inner loops first 2377 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 2378 PrintLoopInfo(OS, SE, *I); 2379 2380 std::cerr << "Loop " << L->getHeader()->getName() << ": "; 2381 2382 std::vector<BasicBlock*> ExitBlocks; 2383 L->getExitBlocks(ExitBlocks); 2384 if (ExitBlocks.size() != 1) 2385 std::cerr << "<multiple exits> "; 2386 2387 if (SE->hasLoopInvariantIterationCount(L)) { 2388 std::cerr << *SE->getIterationCount(L) << " iterations! "; 2389 } else { 2390 std::cerr << "Unpredictable iteration count. "; 2391 } 2392 2393 std::cerr << "\n"; 2394} 2395 2396void ScalarEvolution::print(std::ostream &OS, const Module* ) const { 2397 Function &F = ((ScalarEvolutionsImpl*)Impl)->F; 2398 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI; 2399 2400 OS << "Classifying expressions for: " << F.getName() << "\n"; 2401 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) 2402 if (I->getType()->isInteger()) { 2403 OS << *I; 2404 OS << " --> "; 2405 SCEVHandle SV = getSCEV(&*I); 2406 SV->print(OS); 2407 OS << "\t\t"; 2408 2409 if ((*I).getType()->isIntegral()) { 2410 ConstantRange Bounds = SV->getValueRange(); 2411 if (!Bounds.isFullSet()) 2412 OS << "Bounds: " << Bounds << " "; 2413 } 2414 2415 if (const Loop *L = LI.getLoopFor((*I).getParent())) { 2416 OS << "Exits: "; 2417 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop()); 2418 if (isa<SCEVCouldNotCompute>(ExitValue)) { 2419 OS << "<<Unknown>>"; 2420 } else { 2421 OS << *ExitValue; 2422 } 2423 } 2424 2425 2426 OS << "\n"; 2427 } 2428 2429 OS << "Determining loop execution counts for: " << F.getName() << "\n"; 2430 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) 2431 PrintLoopInfo(OS, this, *I); 2432} 2433 2434