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