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