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