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