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