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