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