1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #define DEBUG_TYPE "scalar-evolution" 62 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 63 #include "llvm/Constants.h" 64 #include "llvm/DerivedTypes.h" 65 #include "llvm/GlobalVariable.h" 66 #include "llvm/GlobalAlias.h" 67 #include "llvm/Instructions.h" 68 #include "llvm/LLVMContext.h" 69 #include "llvm/Operator.h" 70 #include "llvm/Analysis/ConstantFolding.h" 71 #include "llvm/Analysis/Dominators.h" 72 #include "llvm/Analysis/InstructionSimplify.h" 73 #include "llvm/Analysis/LoopInfo.h" 74 #include "llvm/Analysis/ValueTracking.h" 75 #include "llvm/Assembly/Writer.h" 76 #include "llvm/Target/TargetData.h" 77 #include "llvm/Target/TargetLibraryInfo.h" 78 #include "llvm/Support/CommandLine.h" 79 #include "llvm/Support/ConstantRange.h" 80 #include "llvm/Support/Debug.h" 81 #include "llvm/Support/ErrorHandling.h" 82 #include "llvm/Support/GetElementPtrTypeIterator.h" 83 #include "llvm/Support/InstIterator.h" 84 #include "llvm/Support/MathExtras.h" 85 #include "llvm/Support/raw_ostream.h" 86 #include "llvm/ADT/Statistic.h" 87 #include "llvm/ADT/STLExtras.h" 88 #include "llvm/ADT/SmallPtrSet.h" 89 #include <algorithm> 90 using namespace llvm; 91 92 STATISTIC(NumArrayLenItCounts, 93 "Number of trip counts computed with array length"); 94 STATISTIC(NumTripCountsComputed, 95 "Number of loops with predictable loop counts"); 96 STATISTIC(NumTripCountsNotComputed, 97 "Number of loops without predictable loop counts"); 98 STATISTIC(NumBruteForceTripCountsComputed, 99 "Number of loops with trip counts computed by force"); 100 101 static cl::opt<unsigned> 102 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 103 cl::desc("Maximum number of iterations SCEV will " 104 "symbolically execute a constant " 105 "derived loop"), 106 cl::init(100)); 107 108 INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution", 109 "Scalar Evolution Analysis", false, true) 110 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 111 INITIALIZE_PASS_DEPENDENCY(DominatorTree) 112 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo) 113 INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution", 114 "Scalar Evolution Analysis", false, true) 115 char ScalarEvolution::ID = 0; 116 117 //===----------------------------------------------------------------------===// 118 // SCEV class definitions 119 //===----------------------------------------------------------------------===// 120 121 //===----------------------------------------------------------------------===// 122 // Implementation of the SCEV class. 123 // 124 125 void SCEV::dump() const { 126 print(dbgs()); 127 dbgs() << '\n'; 128 } 129 130 void SCEV::print(raw_ostream &OS) const { 131 switch (getSCEVType()) { 132 case scConstant: 133 WriteAsOperand(OS, cast<SCEVConstant>(this)->getValue(), false); 134 return; 135 case scTruncate: { 136 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 137 const SCEV *Op = Trunc->getOperand(); 138 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 139 << *Trunc->getType() << ")"; 140 return; 141 } 142 case scZeroExtend: { 143 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 144 const SCEV *Op = ZExt->getOperand(); 145 OS << "(zext " << *Op->getType() << " " << *Op << " to " 146 << *ZExt->getType() << ")"; 147 return; 148 } 149 case scSignExtend: { 150 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 151 const SCEV *Op = SExt->getOperand(); 152 OS << "(sext " << *Op->getType() << " " << *Op << " to " 153 << *SExt->getType() << ")"; 154 return; 155 } 156 case scAddRecExpr: { 157 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 158 OS << "{" << *AR->getOperand(0); 159 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 160 OS << ",+," << *AR->getOperand(i); 161 OS << "}<"; 162 if (AR->getNoWrapFlags(FlagNUW)) 163 OS << "nuw><"; 164 if (AR->getNoWrapFlags(FlagNSW)) 165 OS << "nsw><"; 166 if (AR->getNoWrapFlags(FlagNW) && 167 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 168 OS << "nw><"; 169 WriteAsOperand(OS, AR->getLoop()->getHeader(), /*PrintType=*/false); 170 OS << ">"; 171 return; 172 } 173 case scAddExpr: 174 case scMulExpr: 175 case scUMaxExpr: 176 case scSMaxExpr: { 177 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 178 const char *OpStr = 0; 179 switch (NAry->getSCEVType()) { 180 case scAddExpr: OpStr = " + "; break; 181 case scMulExpr: OpStr = " * "; break; 182 case scUMaxExpr: OpStr = " umax "; break; 183 case scSMaxExpr: OpStr = " smax "; break; 184 } 185 OS << "("; 186 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 187 I != E; ++I) { 188 OS << **I; 189 if (llvm::next(I) != E) 190 OS << OpStr; 191 } 192 OS << ")"; 193 switch (NAry->getSCEVType()) { 194 case scAddExpr: 195 case scMulExpr: 196 if (NAry->getNoWrapFlags(FlagNUW)) 197 OS << "<nuw>"; 198 if (NAry->getNoWrapFlags(FlagNSW)) 199 OS << "<nsw>"; 200 } 201 return; 202 } 203 case scUDivExpr: { 204 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 205 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 206 return; 207 } 208 case scUnknown: { 209 const SCEVUnknown *U = cast<SCEVUnknown>(this); 210 Type *AllocTy; 211 if (U->isSizeOf(AllocTy)) { 212 OS << "sizeof(" << *AllocTy << ")"; 213 return; 214 } 215 if (U->isAlignOf(AllocTy)) { 216 OS << "alignof(" << *AllocTy << ")"; 217 return; 218 } 219 220 Type *CTy; 221 Constant *FieldNo; 222 if (U->isOffsetOf(CTy, FieldNo)) { 223 OS << "offsetof(" << *CTy << ", "; 224 WriteAsOperand(OS, FieldNo, false); 225 OS << ")"; 226 return; 227 } 228 229 // Otherwise just print it normally. 230 WriteAsOperand(OS, U->getValue(), false); 231 return; 232 } 233 case scCouldNotCompute: 234 OS << "***COULDNOTCOMPUTE***"; 235 return; 236 default: break; 237 } 238 llvm_unreachable("Unknown SCEV kind!"); 239 } 240 241 Type *SCEV::getType() const { 242 switch (getSCEVType()) { 243 case scConstant: 244 return cast<SCEVConstant>(this)->getType(); 245 case scTruncate: 246 case scZeroExtend: 247 case scSignExtend: 248 return cast<SCEVCastExpr>(this)->getType(); 249 case scAddRecExpr: 250 case scMulExpr: 251 case scUMaxExpr: 252 case scSMaxExpr: 253 return cast<SCEVNAryExpr>(this)->getType(); 254 case scAddExpr: 255 return cast<SCEVAddExpr>(this)->getType(); 256 case scUDivExpr: 257 return cast<SCEVUDivExpr>(this)->getType(); 258 case scUnknown: 259 return cast<SCEVUnknown>(this)->getType(); 260 case scCouldNotCompute: 261 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 262 return 0; 263 default: break; 264 } 265 llvm_unreachable("Unknown SCEV kind!"); 266 return 0; 267 } 268 269 bool SCEV::isZero() const { 270 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 271 return SC->getValue()->isZero(); 272 return false; 273 } 274 275 bool SCEV::isOne() const { 276 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 277 return SC->getValue()->isOne(); 278 return false; 279 } 280 281 bool SCEV::isAllOnesValue() const { 282 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 283 return SC->getValue()->isAllOnesValue(); 284 return false; 285 } 286 287 SCEVCouldNotCompute::SCEVCouldNotCompute() : 288 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 289 290 bool SCEVCouldNotCompute::classof(const SCEV *S) { 291 return S->getSCEVType() == scCouldNotCompute; 292 } 293 294 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 295 FoldingSetNodeID ID; 296 ID.AddInteger(scConstant); 297 ID.AddPointer(V); 298 void *IP = 0; 299 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 300 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 301 UniqueSCEVs.InsertNode(S, IP); 302 return S; 303 } 304 305 const SCEV *ScalarEvolution::getConstant(const APInt& Val) { 306 return getConstant(ConstantInt::get(getContext(), Val)); 307 } 308 309 const SCEV * 310 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 311 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 312 return getConstant(ConstantInt::get(ITy, V, isSigned)); 313 } 314 315 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 316 unsigned SCEVTy, const SCEV *op, Type *ty) 317 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 318 319 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 320 const SCEV *op, Type *ty) 321 : SCEVCastExpr(ID, scTruncate, op, ty) { 322 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 323 (Ty->isIntegerTy() || Ty->isPointerTy()) && 324 "Cannot truncate non-integer value!"); 325 } 326 327 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 328 const SCEV *op, Type *ty) 329 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 330 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 331 (Ty->isIntegerTy() || Ty->isPointerTy()) && 332 "Cannot zero extend non-integer value!"); 333 } 334 335 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 336 const SCEV *op, Type *ty) 337 : SCEVCastExpr(ID, scSignExtend, op, ty) { 338 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 339 (Ty->isIntegerTy() || Ty->isPointerTy()) && 340 "Cannot sign extend non-integer value!"); 341 } 342 343 void SCEVUnknown::deleted() { 344 // Clear this SCEVUnknown from various maps. 345 SE->forgetMemoizedResults(this); 346 347 // Remove this SCEVUnknown from the uniquing map. 348 SE->UniqueSCEVs.RemoveNode(this); 349 350 // Release the value. 351 setValPtr(0); 352 } 353 354 void SCEVUnknown::allUsesReplacedWith(Value *New) { 355 // Clear this SCEVUnknown from various maps. 356 SE->forgetMemoizedResults(this); 357 358 // Remove this SCEVUnknown from the uniquing map. 359 SE->UniqueSCEVs.RemoveNode(this); 360 361 // Update this SCEVUnknown to point to the new value. This is needed 362 // because there may still be outstanding SCEVs which still point to 363 // this SCEVUnknown. 364 setValPtr(New); 365 } 366 367 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 368 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 369 if (VCE->getOpcode() == Instruction::PtrToInt) 370 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 371 if (CE->getOpcode() == Instruction::GetElementPtr && 372 CE->getOperand(0)->isNullValue() && 373 CE->getNumOperands() == 2) 374 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 375 if (CI->isOne()) { 376 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 377 ->getElementType(); 378 return true; 379 } 380 381 return false; 382 } 383 384 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 385 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 386 if (VCE->getOpcode() == Instruction::PtrToInt) 387 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 388 if (CE->getOpcode() == Instruction::GetElementPtr && 389 CE->getOperand(0)->isNullValue()) { 390 Type *Ty = 391 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 392 if (StructType *STy = dyn_cast<StructType>(Ty)) 393 if (!STy->isPacked() && 394 CE->getNumOperands() == 3 && 395 CE->getOperand(1)->isNullValue()) { 396 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 397 if (CI->isOne() && 398 STy->getNumElements() == 2 && 399 STy->getElementType(0)->isIntegerTy(1)) { 400 AllocTy = STy->getElementType(1); 401 return true; 402 } 403 } 404 } 405 406 return false; 407 } 408 409 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 410 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 411 if (VCE->getOpcode() == Instruction::PtrToInt) 412 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 413 if (CE->getOpcode() == Instruction::GetElementPtr && 414 CE->getNumOperands() == 3 && 415 CE->getOperand(0)->isNullValue() && 416 CE->getOperand(1)->isNullValue()) { 417 Type *Ty = 418 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 419 // Ignore vector types here so that ScalarEvolutionExpander doesn't 420 // emit getelementptrs that index into vectors. 421 if (Ty->isStructTy() || Ty->isArrayTy()) { 422 CTy = Ty; 423 FieldNo = CE->getOperand(2); 424 return true; 425 } 426 } 427 428 return false; 429 } 430 431 //===----------------------------------------------------------------------===// 432 // SCEV Utilities 433 //===----------------------------------------------------------------------===// 434 435 namespace { 436 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less 437 /// than the complexity of the RHS. This comparator is used to canonicalize 438 /// expressions. 439 class SCEVComplexityCompare { 440 const LoopInfo *const LI; 441 public: 442 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {} 443 444 // Return true or false if LHS is less than, or at least RHS, respectively. 445 bool operator()(const SCEV *LHS, const SCEV *RHS) const { 446 return compare(LHS, RHS) < 0; 447 } 448 449 // Return negative, zero, or positive, if LHS is less than, equal to, or 450 // greater than RHS, respectively. A three-way result allows recursive 451 // comparisons to be more efficient. 452 int compare(const SCEV *LHS, const SCEV *RHS) const { 453 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 454 if (LHS == RHS) 455 return 0; 456 457 // Primarily, sort the SCEVs by their getSCEVType(). 458 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 459 if (LType != RType) 460 return (int)LType - (int)RType; 461 462 // Aside from the getSCEVType() ordering, the particular ordering 463 // isn't very important except that it's beneficial to be consistent, 464 // so that (a + b) and (b + a) don't end up as different expressions. 465 switch (LType) { 466 case scUnknown: { 467 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 468 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 469 470 // Sort SCEVUnknown values with some loose heuristics. TODO: This is 471 // not as complete as it could be. 472 const Value *LV = LU->getValue(), *RV = RU->getValue(); 473 474 // Order pointer values after integer values. This helps SCEVExpander 475 // form GEPs. 476 bool LIsPointer = LV->getType()->isPointerTy(), 477 RIsPointer = RV->getType()->isPointerTy(); 478 if (LIsPointer != RIsPointer) 479 return (int)LIsPointer - (int)RIsPointer; 480 481 // Compare getValueID values. 482 unsigned LID = LV->getValueID(), 483 RID = RV->getValueID(); 484 if (LID != RID) 485 return (int)LID - (int)RID; 486 487 // Sort arguments by their position. 488 if (const Argument *LA = dyn_cast<Argument>(LV)) { 489 const Argument *RA = cast<Argument>(RV); 490 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 491 return (int)LArgNo - (int)RArgNo; 492 } 493 494 // For instructions, compare their loop depth, and their operand 495 // count. This is pretty loose. 496 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) { 497 const Instruction *RInst = cast<Instruction>(RV); 498 499 // Compare loop depths. 500 const BasicBlock *LParent = LInst->getParent(), 501 *RParent = RInst->getParent(); 502 if (LParent != RParent) { 503 unsigned LDepth = LI->getLoopDepth(LParent), 504 RDepth = LI->getLoopDepth(RParent); 505 if (LDepth != RDepth) 506 return (int)LDepth - (int)RDepth; 507 } 508 509 // Compare the number of operands. 510 unsigned LNumOps = LInst->getNumOperands(), 511 RNumOps = RInst->getNumOperands(); 512 return (int)LNumOps - (int)RNumOps; 513 } 514 515 return 0; 516 } 517 518 case scConstant: { 519 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 520 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 521 522 // Compare constant values. 523 const APInt &LA = LC->getValue()->getValue(); 524 const APInt &RA = RC->getValue()->getValue(); 525 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 526 if (LBitWidth != RBitWidth) 527 return (int)LBitWidth - (int)RBitWidth; 528 return LA.ult(RA) ? -1 : 1; 529 } 530 531 case scAddRecExpr: { 532 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 533 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 534 535 // Compare addrec loop depths. 536 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 537 if (LLoop != RLoop) { 538 unsigned LDepth = LLoop->getLoopDepth(), 539 RDepth = RLoop->getLoopDepth(); 540 if (LDepth != RDepth) 541 return (int)LDepth - (int)RDepth; 542 } 543 544 // Addrec complexity grows with operand count. 545 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 546 if (LNumOps != RNumOps) 547 return (int)LNumOps - (int)RNumOps; 548 549 // Lexicographically compare. 550 for (unsigned i = 0; i != LNumOps; ++i) { 551 long X = compare(LA->getOperand(i), RA->getOperand(i)); 552 if (X != 0) 553 return X; 554 } 555 556 return 0; 557 } 558 559 case scAddExpr: 560 case scMulExpr: 561 case scSMaxExpr: 562 case scUMaxExpr: { 563 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 564 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 565 566 // Lexicographically compare n-ary expressions. 567 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 568 for (unsigned i = 0; i != LNumOps; ++i) { 569 if (i >= RNumOps) 570 return 1; 571 long X = compare(LC->getOperand(i), RC->getOperand(i)); 572 if (X != 0) 573 return X; 574 } 575 return (int)LNumOps - (int)RNumOps; 576 } 577 578 case scUDivExpr: { 579 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 580 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 581 582 // Lexicographically compare udiv expressions. 583 long X = compare(LC->getLHS(), RC->getLHS()); 584 if (X != 0) 585 return X; 586 return compare(LC->getRHS(), RC->getRHS()); 587 } 588 589 case scTruncate: 590 case scZeroExtend: 591 case scSignExtend: { 592 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 593 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 594 595 // Compare cast expressions by operand. 596 return compare(LC->getOperand(), RC->getOperand()); 597 } 598 599 default: 600 break; 601 } 602 603 llvm_unreachable("Unknown SCEV kind!"); 604 return 0; 605 } 606 }; 607 } 608 609 /// GroupByComplexity - Given a list of SCEV objects, order them by their 610 /// complexity, and group objects of the same complexity together by value. 611 /// When this routine is finished, we know that any duplicates in the vector are 612 /// consecutive and that complexity is monotonically increasing. 613 /// 614 /// Note that we go take special precautions to ensure that we get deterministic 615 /// results from this routine. In other words, we don't want the results of 616 /// this to depend on where the addresses of various SCEV objects happened to 617 /// land in memory. 618 /// 619 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 620 LoopInfo *LI) { 621 if (Ops.size() < 2) return; // Noop 622 if (Ops.size() == 2) { 623 // This is the common case, which also happens to be trivially simple. 624 // Special case it. 625 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 626 if (SCEVComplexityCompare(LI)(RHS, LHS)) 627 std::swap(LHS, RHS); 628 return; 629 } 630 631 // Do the rough sort by complexity. 632 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI)); 633 634 // Now that we are sorted by complexity, group elements of the same 635 // complexity. Note that this is, at worst, N^2, but the vector is likely to 636 // be extremely short in practice. Note that we take this approach because we 637 // do not want to depend on the addresses of the objects we are grouping. 638 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 639 const SCEV *S = Ops[i]; 640 unsigned Complexity = S->getSCEVType(); 641 642 // If there are any objects of the same complexity and same value as this 643 // one, group them. 644 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 645 if (Ops[j] == S) { // Found a duplicate. 646 // Move it to immediately after i'th element. 647 std::swap(Ops[i+1], Ops[j]); 648 ++i; // no need to rescan it. 649 if (i == e-2) return; // Done! 650 } 651 } 652 } 653 } 654 655 656 657 //===----------------------------------------------------------------------===// 658 // Simple SCEV method implementations 659 //===----------------------------------------------------------------------===// 660 661 /// BinomialCoefficient - Compute BC(It, K). The result has width W. 662 /// Assume, K > 0. 663 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 664 ScalarEvolution &SE, 665 Type *ResultTy) { 666 // Handle the simplest case efficiently. 667 if (K == 1) 668 return SE.getTruncateOrZeroExtend(It, ResultTy); 669 670 // We are using the following formula for BC(It, K): 671 // 672 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 673 // 674 // Suppose, W is the bitwidth of the return value. We must be prepared for 675 // overflow. Hence, we must assure that the result of our computation is 676 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 677 // safe in modular arithmetic. 678 // 679 // However, this code doesn't use exactly that formula; the formula it uses 680 // is something like the following, where T is the number of factors of 2 in 681 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 682 // exponentiation: 683 // 684 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 685 // 686 // This formula is trivially equivalent to the previous formula. However, 687 // this formula can be implemented much more efficiently. The trick is that 688 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 689 // arithmetic. To do exact division in modular arithmetic, all we have 690 // to do is multiply by the inverse. Therefore, this step can be done at 691 // width W. 692 // 693 // The next issue is how to safely do the division by 2^T. The way this 694 // is done is by doing the multiplication step at a width of at least W + T 695 // bits. This way, the bottom W+T bits of the product are accurate. Then, 696 // when we perform the division by 2^T (which is equivalent to a right shift 697 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 698 // truncated out after the division by 2^T. 699 // 700 // In comparison to just directly using the first formula, this technique 701 // is much more efficient; using the first formula requires W * K bits, 702 // but this formula less than W + K bits. Also, the first formula requires 703 // a division step, whereas this formula only requires multiplies and shifts. 704 // 705 // It doesn't matter whether the subtraction step is done in the calculation 706 // width or the input iteration count's width; if the subtraction overflows, 707 // the result must be zero anyway. We prefer here to do it in the width of 708 // the induction variable because it helps a lot for certain cases; CodeGen 709 // isn't smart enough to ignore the overflow, which leads to much less 710 // efficient code if the width of the subtraction is wider than the native 711 // register width. 712 // 713 // (It's possible to not widen at all by pulling out factors of 2 before 714 // the multiplication; for example, K=2 can be calculated as 715 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 716 // extra arithmetic, so it's not an obvious win, and it gets 717 // much more complicated for K > 3.) 718 719 // Protection from insane SCEVs; this bound is conservative, 720 // but it probably doesn't matter. 721 if (K > 1000) 722 return SE.getCouldNotCompute(); 723 724 unsigned W = SE.getTypeSizeInBits(ResultTy); 725 726 // Calculate K! / 2^T and T; we divide out the factors of two before 727 // multiplying for calculating K! / 2^T to avoid overflow. 728 // Other overflow doesn't matter because we only care about the bottom 729 // W bits of the result. 730 APInt OddFactorial(W, 1); 731 unsigned T = 1; 732 for (unsigned i = 3; i <= K; ++i) { 733 APInt Mult(W, i); 734 unsigned TwoFactors = Mult.countTrailingZeros(); 735 T += TwoFactors; 736 Mult = Mult.lshr(TwoFactors); 737 OddFactorial *= Mult; 738 } 739 740 // We need at least W + T bits for the multiplication step 741 unsigned CalculationBits = W + T; 742 743 // Calculate 2^T, at width T+W. 744 APInt DivFactor = APInt(CalculationBits, 1).shl(T); 745 746 // Calculate the multiplicative inverse of K! / 2^T; 747 // this multiplication factor will perform the exact division by 748 // K! / 2^T. 749 APInt Mod = APInt::getSignedMinValue(W+1); 750 APInt MultiplyFactor = OddFactorial.zext(W+1); 751 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 752 MultiplyFactor = MultiplyFactor.trunc(W); 753 754 // Calculate the product, at width T+W 755 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 756 CalculationBits); 757 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 758 for (unsigned i = 1; i != K; ++i) { 759 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 760 Dividend = SE.getMulExpr(Dividend, 761 SE.getTruncateOrZeroExtend(S, CalculationTy)); 762 } 763 764 // Divide by 2^T 765 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 766 767 // Truncate the result, and divide by K! / 2^T. 768 769 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 770 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 771 } 772 773 /// evaluateAtIteration - Return the value of this chain of recurrences at 774 /// the specified iteration number. We can evaluate this recurrence by 775 /// multiplying each element in the chain by the binomial coefficient 776 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: 777 /// 778 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 779 /// 780 /// where BC(It, k) stands for binomial coefficient. 781 /// 782 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 783 ScalarEvolution &SE) const { 784 const SCEV *Result = getStart(); 785 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 786 // The computation is correct in the face of overflow provided that the 787 // multiplication is performed _after_ the evaluation of the binomial 788 // coefficient. 789 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 790 if (isa<SCEVCouldNotCompute>(Coeff)) 791 return Coeff; 792 793 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 794 } 795 return Result; 796 } 797 798 //===----------------------------------------------------------------------===// 799 // SCEV Expression folder implementations 800 //===----------------------------------------------------------------------===// 801 802 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 803 Type *Ty) { 804 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 805 "This is not a truncating conversion!"); 806 assert(isSCEVable(Ty) && 807 "This is not a conversion to a SCEVable type!"); 808 Ty = getEffectiveSCEVType(Ty); 809 810 FoldingSetNodeID ID; 811 ID.AddInteger(scTruncate); 812 ID.AddPointer(Op); 813 ID.AddPointer(Ty); 814 void *IP = 0; 815 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 816 817 // Fold if the operand is constant. 818 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 819 return getConstant( 820 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), 821 getEffectiveSCEVType(Ty)))); 822 823 // trunc(trunc(x)) --> trunc(x) 824 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 825 return getTruncateExpr(ST->getOperand(), Ty); 826 827 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 828 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 829 return getTruncateOrSignExtend(SS->getOperand(), Ty); 830 831 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 832 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 833 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 834 835 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 836 // eliminate all the truncates. 837 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 838 SmallVector<const SCEV *, 4> Operands; 839 bool hasTrunc = false; 840 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 841 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 842 hasTrunc = isa<SCEVTruncateExpr>(S); 843 Operands.push_back(S); 844 } 845 if (!hasTrunc) 846 return getAddExpr(Operands); 847 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 848 } 849 850 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 851 // eliminate all the truncates. 852 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 853 SmallVector<const SCEV *, 4> Operands; 854 bool hasTrunc = false; 855 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 856 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 857 hasTrunc = isa<SCEVTruncateExpr>(S); 858 Operands.push_back(S); 859 } 860 if (!hasTrunc) 861 return getMulExpr(Operands); 862 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 863 } 864 865 // If the input value is a chrec scev, truncate the chrec's operands. 866 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 867 SmallVector<const SCEV *, 4> Operands; 868 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 869 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty)); 870 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 871 } 872 873 // As a special case, fold trunc(undef) to undef. We don't want to 874 // know too much about SCEVUnknowns, but this special case is handy 875 // and harmless. 876 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op)) 877 if (isa<UndefValue>(U->getValue())) 878 return getSCEV(UndefValue::get(Ty)); 879 880 // The cast wasn't folded; create an explicit cast node. We can reuse 881 // the existing insert position since if we get here, we won't have 882 // made any changes which would invalidate it. 883 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 884 Op, Ty); 885 UniqueSCEVs.InsertNode(S, IP); 886 return S; 887 } 888 889 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, 890 Type *Ty) { 891 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 892 "This is not an extending conversion!"); 893 assert(isSCEVable(Ty) && 894 "This is not a conversion to a SCEVable type!"); 895 Ty = getEffectiveSCEVType(Ty); 896 897 // Fold if the operand is constant. 898 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 899 return getConstant( 900 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), 901 getEffectiveSCEVType(Ty)))); 902 903 // zext(zext(x)) --> zext(x) 904 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 905 return getZeroExtendExpr(SZ->getOperand(), Ty); 906 907 // Before doing any expensive analysis, check to see if we've already 908 // computed a SCEV for this Op and Ty. 909 FoldingSetNodeID ID; 910 ID.AddInteger(scZeroExtend); 911 ID.AddPointer(Op); 912 ID.AddPointer(Ty); 913 void *IP = 0; 914 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 915 916 // zext(trunc(x)) --> zext(x) or x or trunc(x) 917 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 918 // It's possible the bits taken off by the truncate were all zero bits. If 919 // so, we should be able to simplify this further. 920 const SCEV *X = ST->getOperand(); 921 ConstantRange CR = getUnsignedRange(X); 922 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 923 unsigned NewBits = getTypeSizeInBits(Ty); 924 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 925 CR.zextOrTrunc(NewBits))) 926 return getTruncateOrZeroExtend(X, Ty); 927 } 928 929 // If the input value is a chrec scev, and we can prove that the value 930 // did not overflow the old, smaller, value, we can zero extend all of the 931 // operands (often constants). This allows analysis of something like 932 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 933 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 934 if (AR->isAffine()) { 935 const SCEV *Start = AR->getStart(); 936 const SCEV *Step = AR->getStepRecurrence(*this); 937 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 938 const Loop *L = AR->getLoop(); 939 940 // If we have special knowledge that this addrec won't overflow, 941 // we don't need to do any further analysis. 942 if (AR->getNoWrapFlags(SCEV::FlagNUW)) 943 return getAddRecExpr(getZeroExtendExpr(Start, Ty), 944 getZeroExtendExpr(Step, Ty), 945 L, AR->getNoWrapFlags()); 946 947 // Check whether the backedge-taken count is SCEVCouldNotCompute. 948 // Note that this serves two purposes: It filters out loops that are 949 // simply not analyzable, and it covers the case where this code is 950 // being called from within backedge-taken count analysis, such that 951 // attempting to ask for the backedge-taken count would likely result 952 // in infinite recursion. In the later case, the analysis code will 953 // cope with a conservative value, and it will take care to purge 954 // that value once it has finished. 955 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 956 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 957 // Manually compute the final value for AR, checking for 958 // overflow. 959 960 // Check whether the backedge-taken count can be losslessly casted to 961 // the addrec's type. The count is always unsigned. 962 const SCEV *CastedMaxBECount = 963 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 964 const SCEV *RecastedMaxBECount = 965 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 966 if (MaxBECount == RecastedMaxBECount) { 967 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 968 // Check whether Start+Step*MaxBECount has no unsigned overflow. 969 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 970 const SCEV *Add = getAddExpr(Start, ZMul); 971 const SCEV *OperandExtendedAdd = 972 getAddExpr(getZeroExtendExpr(Start, WideTy), 973 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 974 getZeroExtendExpr(Step, WideTy))); 975 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) { 976 // Cache knowledge of AR NUW, which is propagated to this AddRec. 977 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 978 // Return the expression with the addrec on the outside. 979 return getAddRecExpr(getZeroExtendExpr(Start, Ty), 980 getZeroExtendExpr(Step, Ty), 981 L, AR->getNoWrapFlags()); 982 } 983 // Similar to above, only this time treat the step value as signed. 984 // This covers loops that count down. 985 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 986 Add = getAddExpr(Start, SMul); 987 OperandExtendedAdd = 988 getAddExpr(getZeroExtendExpr(Start, WideTy), 989 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 990 getSignExtendExpr(Step, WideTy))); 991 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) { 992 // Cache knowledge of AR NW, which is propagated to this AddRec. 993 // Negative step causes unsigned wrap, but it still can't self-wrap. 994 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 995 // Return the expression with the addrec on the outside. 996 return getAddRecExpr(getZeroExtendExpr(Start, Ty), 997 getSignExtendExpr(Step, Ty), 998 L, AR->getNoWrapFlags()); 999 } 1000 } 1001 1002 // If the backedge is guarded by a comparison with the pre-inc value 1003 // the addrec is safe. Also, if the entry is guarded by a comparison 1004 // with the start value and the backedge is guarded by a comparison 1005 // with the post-inc value, the addrec is safe. 1006 if (isKnownPositive(Step)) { 1007 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1008 getUnsignedRange(Step).getUnsignedMax()); 1009 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1010 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1011 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1012 AR->getPostIncExpr(*this), N))) { 1013 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1014 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1015 // Return the expression with the addrec on the outside. 1016 return getAddRecExpr(getZeroExtendExpr(Start, Ty), 1017 getZeroExtendExpr(Step, Ty), 1018 L, AR->getNoWrapFlags()); 1019 } 1020 } else if (isKnownNegative(Step)) { 1021 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1022 getSignedRange(Step).getSignedMin()); 1023 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1024 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1025 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1026 AR->getPostIncExpr(*this), N))) { 1027 // Cache knowledge of AR NW, which is propagated to this AddRec. 1028 // Negative step causes unsigned wrap, but it still can't self-wrap. 1029 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1030 // Return the expression with the addrec on the outside. 1031 return getAddRecExpr(getZeroExtendExpr(Start, Ty), 1032 getSignExtendExpr(Step, Ty), 1033 L, AR->getNoWrapFlags()); 1034 } 1035 } 1036 } 1037 } 1038 1039 // The cast wasn't folded; create an explicit cast node. 1040 // Recompute the insert position, as it may have been invalidated. 1041 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1042 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1043 Op, Ty); 1044 UniqueSCEVs.InsertNode(S, IP); 1045 return S; 1046 } 1047 1048 // Get the limit of a recurrence such that incrementing by Step cannot cause 1049 // signed overflow as long as the value of the recurrence within the loop does 1050 // not exceed this limit before incrementing. 1051 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1052 ICmpInst::Predicate *Pred, 1053 ScalarEvolution *SE) { 1054 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1055 if (SE->isKnownPositive(Step)) { 1056 *Pred = ICmpInst::ICMP_SLT; 1057 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1058 SE->getSignedRange(Step).getSignedMax()); 1059 } 1060 if (SE->isKnownNegative(Step)) { 1061 *Pred = ICmpInst::ICMP_SGT; 1062 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1063 SE->getSignedRange(Step).getSignedMin()); 1064 } 1065 return 0; 1066 } 1067 1068 // The recurrence AR has been shown to have no signed wrap. Typically, if we can 1069 // prove NSW for AR, then we can just as easily prove NSW for its preincrement 1070 // or postincrement sibling. This allows normalizing a sign extended AddRec as 1071 // such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a 1072 // result, the expression "Step + sext(PreIncAR)" is congruent with 1073 // "sext(PostIncAR)" 1074 static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR, 1075 Type *Ty, 1076 ScalarEvolution *SE) { 1077 const Loop *L = AR->getLoop(); 1078 const SCEV *Start = AR->getStart(); 1079 const SCEV *Step = AR->getStepRecurrence(*SE); 1080 1081 // Check for a simple looking step prior to loop entry. 1082 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1083 if (!SA) 1084 return 0; 1085 1086 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1087 // subtraction is expensive. For this purpose, perform a quick and dirty 1088 // difference, by checking for Step in the operand list. 1089 SmallVector<const SCEV *, 4> DiffOps; 1090 for (SCEVAddExpr::op_iterator I = SA->op_begin(), E = SA->op_end(); 1091 I != E; ++I) { 1092 if (*I != Step) 1093 DiffOps.push_back(*I); 1094 } 1095 if (DiffOps.size() == SA->getNumOperands()) 1096 return 0; 1097 1098 // This is a postinc AR. Check for overflow on the preinc recurrence using the 1099 // same three conditions that getSignExtendedExpr checks. 1100 1101 // 1. NSW flags on the step increment. 1102 const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags()); 1103 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1104 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1105 1106 if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW)) 1107 return PreStart; 1108 1109 // 2. Direct overflow check on the step operation's expression. 1110 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1111 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1112 const SCEV *OperandExtendedStart = 1113 SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy), 1114 SE->getSignExtendExpr(Step, WideTy)); 1115 if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) { 1116 // Cache knowledge of PreAR NSW. 1117 if (PreAR) 1118 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW); 1119 // FIXME: this optimization needs a unit test 1120 DEBUG(dbgs() << "SCEV: untested prestart overflow check\n"); 1121 return PreStart; 1122 } 1123 1124 // 3. Loop precondition. 1125 ICmpInst::Predicate Pred; 1126 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE); 1127 1128 if (OverflowLimit && 1129 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) { 1130 return PreStart; 1131 } 1132 return 0; 1133 } 1134 1135 // Get the normalized sign-extended expression for this AddRec's Start. 1136 static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR, 1137 Type *Ty, 1138 ScalarEvolution *SE) { 1139 const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE); 1140 if (!PreStart) 1141 return SE->getSignExtendExpr(AR->getStart(), Ty); 1142 1143 return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty), 1144 SE->getSignExtendExpr(PreStart, Ty)); 1145 } 1146 1147 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, 1148 Type *Ty) { 1149 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1150 "This is not an extending conversion!"); 1151 assert(isSCEVable(Ty) && 1152 "This is not a conversion to a SCEVable type!"); 1153 Ty = getEffectiveSCEVType(Ty); 1154 1155 // Fold if the operand is constant. 1156 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1157 return getConstant( 1158 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), 1159 getEffectiveSCEVType(Ty)))); 1160 1161 // sext(sext(x)) --> sext(x) 1162 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1163 return getSignExtendExpr(SS->getOperand(), Ty); 1164 1165 // sext(zext(x)) --> zext(x) 1166 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1167 return getZeroExtendExpr(SZ->getOperand(), Ty); 1168 1169 // Before doing any expensive analysis, check to see if we've already 1170 // computed a SCEV for this Op and Ty. 1171 FoldingSetNodeID ID; 1172 ID.AddInteger(scSignExtend); 1173 ID.AddPointer(Op); 1174 ID.AddPointer(Ty); 1175 void *IP = 0; 1176 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1177 1178 // If the input value is provably positive, build a zext instead. 1179 if (isKnownNonNegative(Op)) 1180 return getZeroExtendExpr(Op, Ty); 1181 1182 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1183 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1184 // It's possible the bits taken off by the truncate were all sign bits. If 1185 // so, we should be able to simplify this further. 1186 const SCEV *X = ST->getOperand(); 1187 ConstantRange CR = getSignedRange(X); 1188 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1189 unsigned NewBits = getTypeSizeInBits(Ty); 1190 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1191 CR.sextOrTrunc(NewBits))) 1192 return getTruncateOrSignExtend(X, Ty); 1193 } 1194 1195 // If the input value is a chrec scev, and we can prove that the value 1196 // did not overflow the old, smaller, value, we can sign extend all of the 1197 // operands (often constants). This allows analysis of something like 1198 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1199 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1200 if (AR->isAffine()) { 1201 const SCEV *Start = AR->getStart(); 1202 const SCEV *Step = AR->getStepRecurrence(*this); 1203 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1204 const Loop *L = AR->getLoop(); 1205 1206 // If we have special knowledge that this addrec won't overflow, 1207 // we don't need to do any further analysis. 1208 if (AR->getNoWrapFlags(SCEV::FlagNSW)) 1209 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this), 1210 getSignExtendExpr(Step, Ty), 1211 L, SCEV::FlagNSW); 1212 1213 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1214 // Note that this serves two purposes: It filters out loops that are 1215 // simply not analyzable, and it covers the case where this code is 1216 // being called from within backedge-taken count analysis, such that 1217 // attempting to ask for the backedge-taken count would likely result 1218 // in infinite recursion. In the later case, the analysis code will 1219 // cope with a conservative value, and it will take care to purge 1220 // that value once it has finished. 1221 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1222 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1223 // Manually compute the final value for AR, checking for 1224 // overflow. 1225 1226 // Check whether the backedge-taken count can be losslessly casted to 1227 // the addrec's type. The count is always unsigned. 1228 const SCEV *CastedMaxBECount = 1229 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1230 const SCEV *RecastedMaxBECount = 1231 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1232 if (MaxBECount == RecastedMaxBECount) { 1233 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1234 // Check whether Start+Step*MaxBECount has no signed overflow. 1235 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1236 const SCEV *Add = getAddExpr(Start, SMul); 1237 const SCEV *OperandExtendedAdd = 1238 getAddExpr(getSignExtendExpr(Start, WideTy), 1239 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 1240 getSignExtendExpr(Step, WideTy))); 1241 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) { 1242 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1243 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1244 // Return the expression with the addrec on the outside. 1245 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this), 1246 getSignExtendExpr(Step, Ty), 1247 L, AR->getNoWrapFlags()); 1248 } 1249 // Similar to above, only this time treat the step value as unsigned. 1250 // This covers loops that count up with an unsigned step. 1251 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step); 1252 Add = getAddExpr(Start, UMul); 1253 OperandExtendedAdd = 1254 getAddExpr(getSignExtendExpr(Start, WideTy), 1255 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 1256 getZeroExtendExpr(Step, WideTy))); 1257 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) { 1258 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1259 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1260 // Return the expression with the addrec on the outside. 1261 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this), 1262 getZeroExtendExpr(Step, Ty), 1263 L, AR->getNoWrapFlags()); 1264 } 1265 } 1266 1267 // If the backedge is guarded by a comparison with the pre-inc value 1268 // the addrec is safe. Also, if the entry is guarded by a comparison 1269 // with the start value and the backedge is guarded by a comparison 1270 // with the post-inc value, the addrec is safe. 1271 ICmpInst::Predicate Pred; 1272 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this); 1273 if (OverflowLimit && 1274 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1275 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1276 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1277 OverflowLimit)))) { 1278 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1279 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1280 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this), 1281 getSignExtendExpr(Step, Ty), 1282 L, AR->getNoWrapFlags()); 1283 } 1284 } 1285 } 1286 1287 // The cast wasn't folded; create an explicit cast node. 1288 // Recompute the insert position, as it may have been invalidated. 1289 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1290 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1291 Op, Ty); 1292 UniqueSCEVs.InsertNode(S, IP); 1293 return S; 1294 } 1295 1296 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1297 /// unspecified bits out to the given type. 1298 /// 1299 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1300 Type *Ty) { 1301 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1302 "This is not an extending conversion!"); 1303 assert(isSCEVable(Ty) && 1304 "This is not a conversion to a SCEVable type!"); 1305 Ty = getEffectiveSCEVType(Ty); 1306 1307 // Sign-extend negative constants. 1308 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1309 if (SC->getValue()->getValue().isNegative()) 1310 return getSignExtendExpr(Op, Ty); 1311 1312 // Peel off a truncate cast. 1313 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1314 const SCEV *NewOp = T->getOperand(); 1315 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1316 return getAnyExtendExpr(NewOp, Ty); 1317 return getTruncateOrNoop(NewOp, Ty); 1318 } 1319 1320 // Next try a zext cast. If the cast is folded, use it. 1321 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1322 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1323 return ZExt; 1324 1325 // Next try a sext cast. If the cast is folded, use it. 1326 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1327 if (!isa<SCEVSignExtendExpr>(SExt)) 1328 return SExt; 1329 1330 // Force the cast to be folded into the operands of an addrec. 1331 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1332 SmallVector<const SCEV *, 4> Ops; 1333 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end(); 1334 I != E; ++I) 1335 Ops.push_back(getAnyExtendExpr(*I, Ty)); 1336 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1337 } 1338 1339 // As a special case, fold anyext(undef) to undef. We don't want to 1340 // know too much about SCEVUnknowns, but this special case is handy 1341 // and harmless. 1342 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op)) 1343 if (isa<UndefValue>(U->getValue())) 1344 return getSCEV(UndefValue::get(Ty)); 1345 1346 // If the expression is obviously signed, use the sext cast value. 1347 if (isa<SCEVSMaxExpr>(Op)) 1348 return SExt; 1349 1350 // Absent any other information, use the zext cast value. 1351 return ZExt; 1352 } 1353 1354 /// CollectAddOperandsWithScales - Process the given Ops list, which is 1355 /// a list of operands to be added under the given scale, update the given 1356 /// map. This is a helper function for getAddRecExpr. As an example of 1357 /// what it does, given a sequence of operands that would form an add 1358 /// expression like this: 1359 /// 1360 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r) 1361 /// 1362 /// where A and B are constants, update the map with these values: 1363 /// 1364 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 1365 /// 1366 /// and add 13 + A*B*29 to AccumulatedConstant. 1367 /// This will allow getAddRecExpr to produce this: 1368 /// 1369 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 1370 /// 1371 /// This form often exposes folding opportunities that are hidden in 1372 /// the original operand list. 1373 /// 1374 /// Return true iff it appears that any interesting folding opportunities 1375 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 1376 /// the common case where no interesting opportunities are present, and 1377 /// is also used as a check to avoid infinite recursion. 1378 /// 1379 static bool 1380 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 1381 SmallVector<const SCEV *, 8> &NewOps, 1382 APInt &AccumulatedConstant, 1383 const SCEV *const *Ops, size_t NumOperands, 1384 const APInt &Scale, 1385 ScalarEvolution &SE) { 1386 bool Interesting = false; 1387 1388 // Iterate over the add operands. They are sorted, with constants first. 1389 unsigned i = 0; 1390 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1391 ++i; 1392 // Pull a buried constant out to the outside. 1393 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 1394 Interesting = true; 1395 AccumulatedConstant += Scale * C->getValue()->getValue(); 1396 } 1397 1398 // Next comes everything else. We're especially interested in multiplies 1399 // here, but they're in the middle, so just visit the rest with one loop. 1400 for (; i != NumOperands; ++i) { 1401 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 1402 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 1403 APInt NewScale = 1404 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue(); 1405 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 1406 // A multiplication of a constant with another add; recurse. 1407 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 1408 Interesting |= 1409 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 1410 Add->op_begin(), Add->getNumOperands(), 1411 NewScale, SE); 1412 } else { 1413 // A multiplication of a constant with some other value. Update 1414 // the map. 1415 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 1416 const SCEV *Key = SE.getMulExpr(MulOps); 1417 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 1418 M.insert(std::make_pair(Key, NewScale)); 1419 if (Pair.second) { 1420 NewOps.push_back(Pair.first->first); 1421 } else { 1422 Pair.first->second += NewScale; 1423 // The map already had an entry for this value, which may indicate 1424 // a folding opportunity. 1425 Interesting = true; 1426 } 1427 } 1428 } else { 1429 // An ordinary operand. Update the map. 1430 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 1431 M.insert(std::make_pair(Ops[i], Scale)); 1432 if (Pair.second) { 1433 NewOps.push_back(Pair.first->first); 1434 } else { 1435 Pair.first->second += Scale; 1436 // The map already had an entry for this value, which may indicate 1437 // a folding opportunity. 1438 Interesting = true; 1439 } 1440 } 1441 } 1442 1443 return Interesting; 1444 } 1445 1446 namespace { 1447 struct APIntCompare { 1448 bool operator()(const APInt &LHS, const APInt &RHS) const { 1449 return LHS.ult(RHS); 1450 } 1451 }; 1452 } 1453 1454 /// getAddExpr - Get a canonical add expression, or something simpler if 1455 /// possible. 1456 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 1457 SCEV::NoWrapFlags Flags) { 1458 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 1459 "only nuw or nsw allowed"); 1460 assert(!Ops.empty() && "Cannot get empty add!"); 1461 if (Ops.size() == 1) return Ops[0]; 1462 #ifndef NDEBUG 1463 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 1464 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 1465 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 1466 "SCEVAddExpr operand types don't match!"); 1467 #endif 1468 1469 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 1470 // And vice-versa. 1471 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 1472 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask); 1473 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) { 1474 bool All = true; 1475 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(), 1476 E = Ops.end(); I != E; ++I) 1477 if (!isKnownNonNegative(*I)) { 1478 All = false; 1479 break; 1480 } 1481 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 1482 } 1483 1484 // Sort by complexity, this groups all similar expression types together. 1485 GroupByComplexity(Ops, LI); 1486 1487 // If there are any constants, fold them together. 1488 unsigned Idx = 0; 1489 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1490 ++Idx; 1491 assert(Idx < Ops.size()); 1492 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1493 // We found two constants, fold them together! 1494 Ops[0] = getConstant(LHSC->getValue()->getValue() + 1495 RHSC->getValue()->getValue()); 1496 if (Ops.size() == 2) return Ops[0]; 1497 Ops.erase(Ops.begin()+1); // Erase the folded element 1498 LHSC = cast<SCEVConstant>(Ops[0]); 1499 } 1500 1501 // If we are left with a constant zero being added, strip it off. 1502 if (LHSC->getValue()->isZero()) { 1503 Ops.erase(Ops.begin()); 1504 --Idx; 1505 } 1506 1507 if (Ops.size() == 1) return Ops[0]; 1508 } 1509 1510 // Okay, check to see if the same value occurs in the operand list more than 1511 // once. If so, merge them together into an multiply expression. Since we 1512 // sorted the list, these values are required to be adjacent. 1513 Type *Ty = Ops[0]->getType(); 1514 bool FoundMatch = false; 1515 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 1516 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 1517 // Scan ahead to count how many equal operands there are. 1518 unsigned Count = 2; 1519 while (i+Count != e && Ops[i+Count] == Ops[i]) 1520 ++Count; 1521 // Merge the values into a multiply. 1522 const SCEV *Scale = getConstant(Ty, Count); 1523 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 1524 if (Ops.size() == Count) 1525 return Mul; 1526 Ops[i] = Mul; 1527 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 1528 --i; e -= Count - 1; 1529 FoundMatch = true; 1530 } 1531 if (FoundMatch) 1532 return getAddExpr(Ops, Flags); 1533 1534 // Check for truncates. If all the operands are truncated from the same 1535 // type, see if factoring out the truncate would permit the result to be 1536 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 1537 // if the contents of the resulting outer trunc fold to something simple. 1538 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 1539 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 1540 Type *DstType = Trunc->getType(); 1541 Type *SrcType = Trunc->getOperand()->getType(); 1542 SmallVector<const SCEV *, 8> LargeOps; 1543 bool Ok = true; 1544 // Check all the operands to see if they can be represented in the 1545 // source type of the truncate. 1546 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1547 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 1548 if (T->getOperand()->getType() != SrcType) { 1549 Ok = false; 1550 break; 1551 } 1552 LargeOps.push_back(T->getOperand()); 1553 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1554 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 1555 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 1556 SmallVector<const SCEV *, 8> LargeMulOps; 1557 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 1558 if (const SCEVTruncateExpr *T = 1559 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 1560 if (T->getOperand()->getType() != SrcType) { 1561 Ok = false; 1562 break; 1563 } 1564 LargeMulOps.push_back(T->getOperand()); 1565 } else if (const SCEVConstant *C = 1566 dyn_cast<SCEVConstant>(M->getOperand(j))) { 1567 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 1568 } else { 1569 Ok = false; 1570 break; 1571 } 1572 } 1573 if (Ok) 1574 LargeOps.push_back(getMulExpr(LargeMulOps)); 1575 } else { 1576 Ok = false; 1577 break; 1578 } 1579 } 1580 if (Ok) { 1581 // Evaluate the expression in the larger type. 1582 const SCEV *Fold = getAddExpr(LargeOps, Flags); 1583 // If it folds to something simple, use it. Otherwise, don't. 1584 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 1585 return getTruncateExpr(Fold, DstType); 1586 } 1587 } 1588 1589 // Skip past any other cast SCEVs. 1590 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 1591 ++Idx; 1592 1593 // If there are add operands they would be next. 1594 if (Idx < Ops.size()) { 1595 bool DeletedAdd = false; 1596 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 1597 // If we have an add, expand the add operands onto the end of the operands 1598 // list. 1599 Ops.erase(Ops.begin()+Idx); 1600 Ops.append(Add->op_begin(), Add->op_end()); 1601 DeletedAdd = true; 1602 } 1603 1604 // If we deleted at least one add, we added operands to the end of the list, 1605 // and they are not necessarily sorted. Recurse to resort and resimplify 1606 // any operands we just acquired. 1607 if (DeletedAdd) 1608 return getAddExpr(Ops); 1609 } 1610 1611 // Skip over the add expression until we get to a multiply. 1612 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 1613 ++Idx; 1614 1615 // Check to see if there are any folding opportunities present with 1616 // operands multiplied by constant values. 1617 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 1618 uint64_t BitWidth = getTypeSizeInBits(Ty); 1619 DenseMap<const SCEV *, APInt> M; 1620 SmallVector<const SCEV *, 8> NewOps; 1621 APInt AccumulatedConstant(BitWidth, 0); 1622 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 1623 Ops.data(), Ops.size(), 1624 APInt(BitWidth, 1), *this)) { 1625 // Some interesting folding opportunity is present, so its worthwhile to 1626 // re-generate the operands list. Group the operands by constant scale, 1627 // to avoid multiplying by the same constant scale multiple times. 1628 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 1629 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(), 1630 E = NewOps.end(); I != E; ++I) 1631 MulOpLists[M.find(*I)->second].push_back(*I); 1632 // Re-generate the operands list. 1633 Ops.clear(); 1634 if (AccumulatedConstant != 0) 1635 Ops.push_back(getConstant(AccumulatedConstant)); 1636 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator 1637 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I) 1638 if (I->first != 0) 1639 Ops.push_back(getMulExpr(getConstant(I->first), 1640 getAddExpr(I->second))); 1641 if (Ops.empty()) 1642 return getConstant(Ty, 0); 1643 if (Ops.size() == 1) 1644 return Ops[0]; 1645 return getAddExpr(Ops); 1646 } 1647 } 1648 1649 // If we are adding something to a multiply expression, make sure the 1650 // something is not already an operand of the multiply. If so, merge it into 1651 // the multiply. 1652 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 1653 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 1654 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 1655 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 1656 if (isa<SCEVConstant>(MulOpSCEV)) 1657 continue; 1658 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 1659 if (MulOpSCEV == Ops[AddOp]) { 1660 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 1661 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 1662 if (Mul->getNumOperands() != 2) { 1663 // If the multiply has more than two operands, we must get the 1664 // Y*Z term. 1665 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 1666 Mul->op_begin()+MulOp); 1667 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 1668 InnerMul = getMulExpr(MulOps); 1669 } 1670 const SCEV *One = getConstant(Ty, 1); 1671 const SCEV *AddOne = getAddExpr(One, InnerMul); 1672 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 1673 if (Ops.size() == 2) return OuterMul; 1674 if (AddOp < Idx) { 1675 Ops.erase(Ops.begin()+AddOp); 1676 Ops.erase(Ops.begin()+Idx-1); 1677 } else { 1678 Ops.erase(Ops.begin()+Idx); 1679 Ops.erase(Ops.begin()+AddOp-1); 1680 } 1681 Ops.push_back(OuterMul); 1682 return getAddExpr(Ops); 1683 } 1684 1685 // Check this multiply against other multiplies being added together. 1686 for (unsigned OtherMulIdx = Idx+1; 1687 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 1688 ++OtherMulIdx) { 1689 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 1690 // If MulOp occurs in OtherMul, we can fold the two multiplies 1691 // together. 1692 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 1693 OMulOp != e; ++OMulOp) 1694 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 1695 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 1696 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 1697 if (Mul->getNumOperands() != 2) { 1698 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 1699 Mul->op_begin()+MulOp); 1700 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 1701 InnerMul1 = getMulExpr(MulOps); 1702 } 1703 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 1704 if (OtherMul->getNumOperands() != 2) { 1705 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 1706 OtherMul->op_begin()+OMulOp); 1707 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 1708 InnerMul2 = getMulExpr(MulOps); 1709 } 1710 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 1711 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 1712 if (Ops.size() == 2) return OuterMul; 1713 Ops.erase(Ops.begin()+Idx); 1714 Ops.erase(Ops.begin()+OtherMulIdx-1); 1715 Ops.push_back(OuterMul); 1716 return getAddExpr(Ops); 1717 } 1718 } 1719 } 1720 } 1721 1722 // If there are any add recurrences in the operands list, see if any other 1723 // added values are loop invariant. If so, we can fold them into the 1724 // recurrence. 1725 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 1726 ++Idx; 1727 1728 // Scan over all recurrences, trying to fold loop invariants into them. 1729 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 1730 // Scan all of the other operands to this add and add them to the vector if 1731 // they are loop invariant w.r.t. the recurrence. 1732 SmallVector<const SCEV *, 8> LIOps; 1733 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 1734 const Loop *AddRecLoop = AddRec->getLoop(); 1735 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1736 if (isLoopInvariant(Ops[i], AddRecLoop)) { 1737 LIOps.push_back(Ops[i]); 1738 Ops.erase(Ops.begin()+i); 1739 --i; --e; 1740 } 1741 1742 // If we found some loop invariants, fold them into the recurrence. 1743 if (!LIOps.empty()) { 1744 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 1745 LIOps.push_back(AddRec->getStart()); 1746 1747 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 1748 AddRec->op_end()); 1749 AddRecOps[0] = getAddExpr(LIOps); 1750 1751 // Build the new addrec. Propagate the NUW and NSW flags if both the 1752 // outer add and the inner addrec are guaranteed to have no overflow. 1753 // Always propagate NW. 1754 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 1755 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 1756 1757 // If all of the other operands were loop invariant, we are done. 1758 if (Ops.size() == 1) return NewRec; 1759 1760 // Otherwise, add the folded AddRec by the non-invariant parts. 1761 for (unsigned i = 0;; ++i) 1762 if (Ops[i] == AddRec) { 1763 Ops[i] = NewRec; 1764 break; 1765 } 1766 return getAddExpr(Ops); 1767 } 1768 1769 // Okay, if there weren't any loop invariants to be folded, check to see if 1770 // there are multiple AddRec's with the same loop induction variable being 1771 // added together. If so, we can fold them. 1772 for (unsigned OtherIdx = Idx+1; 1773 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 1774 ++OtherIdx) 1775 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 1776 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 1777 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 1778 AddRec->op_end()); 1779 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 1780 ++OtherIdx) 1781 if (const SCEVAddRecExpr *OtherAddRec = 1782 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 1783 if (OtherAddRec->getLoop() == AddRecLoop) { 1784 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 1785 i != e; ++i) { 1786 if (i >= AddRecOps.size()) { 1787 AddRecOps.append(OtherAddRec->op_begin()+i, 1788 OtherAddRec->op_end()); 1789 break; 1790 } 1791 AddRecOps[i] = getAddExpr(AddRecOps[i], 1792 OtherAddRec->getOperand(i)); 1793 } 1794 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 1795 } 1796 // Step size has changed, so we cannot guarantee no self-wraparound. 1797 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 1798 return getAddExpr(Ops); 1799 } 1800 1801 // Otherwise couldn't fold anything into this recurrence. Move onto the 1802 // next one. 1803 } 1804 1805 // Okay, it looks like we really DO need an add expr. Check to see if we 1806 // already have one, otherwise create a new one. 1807 FoldingSetNodeID ID; 1808 ID.AddInteger(scAddExpr); 1809 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1810 ID.AddPointer(Ops[i]); 1811 void *IP = 0; 1812 SCEVAddExpr *S = 1813 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1814 if (!S) { 1815 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 1816 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 1817 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), 1818 O, Ops.size()); 1819 UniqueSCEVs.InsertNode(S, IP); 1820 } 1821 S->setNoWrapFlags(Flags); 1822 return S; 1823 } 1824 1825 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 1826 uint64_t k = i*j; 1827 if (j > 1 && k / j != i) Overflow = true; 1828 return k; 1829 } 1830 1831 /// Compute the result of "n choose k", the binomial coefficient. If an 1832 /// intermediate computation overflows, Overflow will be set and the return will 1833 /// be garbage. Overflow is not cleared on absense of overflow. 1834 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 1835 // We use the multiplicative formula: 1836 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 1837 // At each iteration, we take the n-th term of the numeral and divide by the 1838 // (k-n)th term of the denominator. This division will always produce an 1839 // integral result, and helps reduce the chance of overflow in the 1840 // intermediate computations. However, we can still overflow even when the 1841 // final result would fit. 1842 1843 if (n == 0 || n == k) return 1; 1844 if (k > n) return 0; 1845 1846 if (k > n/2) 1847 k = n-k; 1848 1849 uint64_t r = 1; 1850 for (uint64_t i = 1; i <= k; ++i) { 1851 r = umul_ov(r, n-(i-1), Overflow); 1852 r /= i; 1853 } 1854 return r; 1855 } 1856 1857 /// getMulExpr - Get a canonical multiply expression, or something simpler if 1858 /// possible. 1859 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 1860 SCEV::NoWrapFlags Flags) { 1861 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 1862 "only nuw or nsw allowed"); 1863 assert(!Ops.empty() && "Cannot get empty mul!"); 1864 if (Ops.size() == 1) return Ops[0]; 1865 #ifndef NDEBUG 1866 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 1867 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 1868 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 1869 "SCEVMulExpr operand types don't match!"); 1870 #endif 1871 1872 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 1873 // And vice-versa. 1874 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 1875 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask); 1876 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) { 1877 bool All = true; 1878 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(), 1879 E = Ops.end(); I != E; ++I) 1880 if (!isKnownNonNegative(*I)) { 1881 All = false; 1882 break; 1883 } 1884 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 1885 } 1886 1887 // Sort by complexity, this groups all similar expression types together. 1888 GroupByComplexity(Ops, LI); 1889 1890 // If there are any constants, fold them together. 1891 unsigned Idx = 0; 1892 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1893 1894 // C1*(C2+V) -> C1*C2 + C1*V 1895 if (Ops.size() == 2) 1896 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 1897 if (Add->getNumOperands() == 2 && 1898 isa<SCEVConstant>(Add->getOperand(0))) 1899 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 1900 getMulExpr(LHSC, Add->getOperand(1))); 1901 1902 ++Idx; 1903 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1904 // We found two constants, fold them together! 1905 ConstantInt *Fold = ConstantInt::get(getContext(), 1906 LHSC->getValue()->getValue() * 1907 RHSC->getValue()->getValue()); 1908 Ops[0] = getConstant(Fold); 1909 Ops.erase(Ops.begin()+1); // Erase the folded element 1910 if (Ops.size() == 1) return Ops[0]; 1911 LHSC = cast<SCEVConstant>(Ops[0]); 1912 } 1913 1914 // If we are left with a constant one being multiplied, strip it off. 1915 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 1916 Ops.erase(Ops.begin()); 1917 --Idx; 1918 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 1919 // If we have a multiply of zero, it will always be zero. 1920 return Ops[0]; 1921 } else if (Ops[0]->isAllOnesValue()) { 1922 // If we have a mul by -1 of an add, try distributing the -1 among the 1923 // add operands. 1924 if (Ops.size() == 2) { 1925 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 1926 SmallVector<const SCEV *, 4> NewOps; 1927 bool AnyFolded = false; 1928 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), 1929 E = Add->op_end(); I != E; ++I) { 1930 const SCEV *Mul = getMulExpr(Ops[0], *I); 1931 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 1932 NewOps.push_back(Mul); 1933 } 1934 if (AnyFolded) 1935 return getAddExpr(NewOps); 1936 } 1937 else if (const SCEVAddRecExpr * 1938 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 1939 // Negation preserves a recurrence's no self-wrap property. 1940 SmallVector<const SCEV *, 4> Operands; 1941 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(), 1942 E = AddRec->op_end(); I != E; ++I) { 1943 Operands.push_back(getMulExpr(Ops[0], *I)); 1944 } 1945 return getAddRecExpr(Operands, AddRec->getLoop(), 1946 AddRec->getNoWrapFlags(SCEV::FlagNW)); 1947 } 1948 } 1949 } 1950 1951 if (Ops.size() == 1) 1952 return Ops[0]; 1953 } 1954 1955 // Skip over the add expression until we get to a multiply. 1956 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 1957 ++Idx; 1958 1959 // If there are mul operands inline them all into this expression. 1960 if (Idx < Ops.size()) { 1961 bool DeletedMul = false; 1962 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 1963 // If we have an mul, expand the mul operands onto the end of the operands 1964 // list. 1965 Ops.erase(Ops.begin()+Idx); 1966 Ops.append(Mul->op_begin(), Mul->op_end()); 1967 DeletedMul = true; 1968 } 1969 1970 // If we deleted at least one mul, we added operands to the end of the list, 1971 // and they are not necessarily sorted. Recurse to resort and resimplify 1972 // any operands we just acquired. 1973 if (DeletedMul) 1974 return getMulExpr(Ops); 1975 } 1976 1977 // If there are any add recurrences in the operands list, see if any other 1978 // added values are loop invariant. If so, we can fold them into the 1979 // recurrence. 1980 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 1981 ++Idx; 1982 1983 // Scan over all recurrences, trying to fold loop invariants into them. 1984 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 1985 // Scan all of the other operands to this mul and add them to the vector if 1986 // they are loop invariant w.r.t. the recurrence. 1987 SmallVector<const SCEV *, 8> LIOps; 1988 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 1989 const Loop *AddRecLoop = AddRec->getLoop(); 1990 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1991 if (isLoopInvariant(Ops[i], AddRecLoop)) { 1992 LIOps.push_back(Ops[i]); 1993 Ops.erase(Ops.begin()+i); 1994 --i; --e; 1995 } 1996 1997 // If we found some loop invariants, fold them into the recurrence. 1998 if (!LIOps.empty()) { 1999 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2000 SmallVector<const SCEV *, 4> NewOps; 2001 NewOps.reserve(AddRec->getNumOperands()); 2002 const SCEV *Scale = getMulExpr(LIOps); 2003 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2004 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2005 2006 // Build the new addrec. Propagate the NUW and NSW flags if both the 2007 // outer mul and the inner addrec are guaranteed to have no overflow. 2008 // 2009 // No self-wrap cannot be guaranteed after changing the step size, but 2010 // will be inferred if either NUW or NSW is true. 2011 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2012 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2013 2014 // If all of the other operands were loop invariant, we are done. 2015 if (Ops.size() == 1) return NewRec; 2016 2017 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2018 for (unsigned i = 0;; ++i) 2019 if (Ops[i] == AddRec) { 2020 Ops[i] = NewRec; 2021 break; 2022 } 2023 return getMulExpr(Ops); 2024 } 2025 2026 // Okay, if there weren't any loop invariants to be folded, check to see if 2027 // there are multiple AddRec's with the same loop induction variable being 2028 // multiplied together. If so, we can fold them. 2029 for (unsigned OtherIdx = Idx+1; 2030 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2031 ++OtherIdx) { 2032 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2033 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2034 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2035 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2036 // ]]],+,...up to x=2n}. 2037 // Note that the arguments to choose() are always integers with values 2038 // known at compile time, never SCEV objects. 2039 // 2040 // The implementation avoids pointless extra computations when the two 2041 // addrec's are of different length (mathematically, it's equivalent to 2042 // an infinite stream of zeros on the right). 2043 bool OpsModified = false; 2044 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2045 ++OtherIdx) 2046 if (const SCEVAddRecExpr *OtherAddRec = 2047 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2048 if (OtherAddRec->getLoop() == AddRecLoop) { 2049 bool Overflow = false; 2050 Type *Ty = AddRec->getType(); 2051 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2052 SmallVector<const SCEV*, 7> AddRecOps; 2053 for (int x = 0, xe = AddRec->getNumOperands() + 2054 OtherAddRec->getNumOperands() - 1; 2055 x != xe && !Overflow; ++x) { 2056 const SCEV *Term = getConstant(Ty, 0); 2057 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2058 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2059 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2060 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2061 z < ze && !Overflow; ++z) { 2062 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2063 uint64_t Coeff; 2064 if (LargerThan64Bits) 2065 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2066 else 2067 Coeff = Coeff1*Coeff2; 2068 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2069 const SCEV *Term1 = AddRec->getOperand(y-z); 2070 const SCEV *Term2 = OtherAddRec->getOperand(z); 2071 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2072 } 2073 } 2074 AddRecOps.push_back(Term); 2075 } 2076 if (!Overflow) { 2077 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, 2078 AddRec->getLoop(), 2079 SCEV::FlagAnyWrap); 2080 if (Ops.size() == 2) return NewAddRec; 2081 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec); 2082 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2083 OpsModified = true; 2084 } 2085 } 2086 if (OpsModified) 2087 return getMulExpr(Ops); 2088 } 2089 } 2090 2091 // Otherwise couldn't fold anything into this recurrence. Move onto the 2092 // next one. 2093 } 2094 2095 // Okay, it looks like we really DO need an mul expr. Check to see if we 2096 // already have one, otherwise create a new one. 2097 FoldingSetNodeID ID; 2098 ID.AddInteger(scMulExpr); 2099 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2100 ID.AddPointer(Ops[i]); 2101 void *IP = 0; 2102 SCEVMulExpr *S = 2103 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2104 if (!S) { 2105 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2106 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2107 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2108 O, Ops.size()); 2109 UniqueSCEVs.InsertNode(S, IP); 2110 } 2111 S->setNoWrapFlags(Flags); 2112 return S; 2113 } 2114 2115 /// getUDivExpr - Get a canonical unsigned division expression, or something 2116 /// simpler if possible. 2117 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2118 const SCEV *RHS) { 2119 assert(getEffectiveSCEVType(LHS->getType()) == 2120 getEffectiveSCEVType(RHS->getType()) && 2121 "SCEVUDivExpr operand types don't match!"); 2122 2123 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2124 if (RHSC->getValue()->equalsInt(1)) 2125 return LHS; // X udiv 1 --> x 2126 // If the denominator is zero, the result of the udiv is undefined. Don't 2127 // try to analyze it, because the resolution chosen here may differ from 2128 // the resolution chosen in other parts of the compiler. 2129 if (!RHSC->getValue()->isZero()) { 2130 // Determine if the division can be folded into the operands of 2131 // its operands. 2132 // TODO: Generalize this to non-constants by using known-bits information. 2133 Type *Ty = LHS->getType(); 2134 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros(); 2135 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2136 // For non-power-of-two values, effectively round the value up to the 2137 // nearest power of two. 2138 if (!RHSC->getValue()->getValue().isPowerOf2()) 2139 ++MaxShiftAmt; 2140 IntegerType *ExtTy = 2141 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2142 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2143 if (const SCEVConstant *Step = 2144 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2145 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2146 const APInt &StepInt = Step->getValue()->getValue(); 2147 const APInt &DivInt = RHSC->getValue()->getValue(); 2148 if (!StepInt.urem(DivInt) && 2149 getZeroExtendExpr(AR, ExtTy) == 2150 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2151 getZeroExtendExpr(Step, ExtTy), 2152 AR->getLoop(), SCEV::FlagAnyWrap)) { 2153 SmallVector<const SCEV *, 4> Operands; 2154 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i) 2155 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS)); 2156 return getAddRecExpr(Operands, AR->getLoop(), 2157 SCEV::FlagNW); 2158 } 2159 /// Get a canonical UDivExpr for a recurrence. 2160 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2161 // We can currently only fold X%N if X is constant. 2162 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2163 if (StartC && !DivInt.urem(StepInt) && 2164 getZeroExtendExpr(AR, ExtTy) == 2165 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2166 getZeroExtendExpr(Step, ExtTy), 2167 AR->getLoop(), SCEV::FlagAnyWrap)) { 2168 const APInt &StartInt = StartC->getValue()->getValue(); 2169 const APInt &StartRem = StartInt.urem(StepInt); 2170 if (StartRem != 0) 2171 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2172 AR->getLoop(), SCEV::FlagNW); 2173 } 2174 } 2175 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2176 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2177 SmallVector<const SCEV *, 4> Operands; 2178 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) 2179 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy)); 2180 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2181 // Find an operand that's safely divisible. 2182 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2183 const SCEV *Op = M->getOperand(i); 2184 const SCEV *Div = getUDivExpr(Op, RHSC); 2185 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2186 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2187 M->op_end()); 2188 Operands[i] = Div; 2189 return getMulExpr(Operands); 2190 } 2191 } 2192 } 2193 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2194 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2195 SmallVector<const SCEV *, 4> Operands; 2196 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) 2197 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy)); 2198 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2199 Operands.clear(); 2200 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2201 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2202 if (isa<SCEVUDivExpr>(Op) || 2203 getMulExpr(Op, RHS) != A->getOperand(i)) 2204 break; 2205 Operands.push_back(Op); 2206 } 2207 if (Operands.size() == A->getNumOperands()) 2208 return getAddExpr(Operands); 2209 } 2210 } 2211 2212 // Fold if both operands are constant. 2213 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2214 Constant *LHSCV = LHSC->getValue(); 2215 Constant *RHSCV = RHSC->getValue(); 2216 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2217 RHSCV))); 2218 } 2219 } 2220 } 2221 2222 FoldingSetNodeID ID; 2223 ID.AddInteger(scUDivExpr); 2224 ID.AddPointer(LHS); 2225 ID.AddPointer(RHS); 2226 void *IP = 0; 2227 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2228 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2229 LHS, RHS); 2230 UniqueSCEVs.InsertNode(S, IP); 2231 return S; 2232 } 2233 2234 2235 /// getAddRecExpr - Get an add recurrence expression for the specified loop. 2236 /// Simplify the expression as much as possible. 2237 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 2238 const Loop *L, 2239 SCEV::NoWrapFlags Flags) { 2240 SmallVector<const SCEV *, 4> Operands; 2241 Operands.push_back(Start); 2242 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 2243 if (StepChrec->getLoop() == L) { 2244 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 2245 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 2246 } 2247 2248 Operands.push_back(Step); 2249 return getAddRecExpr(Operands, L, Flags); 2250 } 2251 2252 /// getAddRecExpr - Get an add recurrence expression for the specified loop. 2253 /// Simplify the expression as much as possible. 2254 const SCEV * 2255 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 2256 const Loop *L, SCEV::NoWrapFlags Flags) { 2257 if (Operands.size() == 1) return Operands[0]; 2258 #ifndef NDEBUG 2259 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 2260 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 2261 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 2262 "SCEVAddRecExpr operand types don't match!"); 2263 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2264 assert(isLoopInvariant(Operands[i], L) && 2265 "SCEVAddRecExpr operand is not loop-invariant!"); 2266 #endif 2267 2268 if (Operands.back()->isZero()) { 2269 Operands.pop_back(); 2270 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 2271 } 2272 2273 // It's tempting to want to call getMaxBackedgeTakenCount count here and 2274 // use that information to infer NUW and NSW flags. However, computing a 2275 // BE count requires calling getAddRecExpr, so we may not yet have a 2276 // meaningful BE count at this point (and if we don't, we'd be stuck 2277 // with a SCEVCouldNotCompute as the cached BE count). 2278 2279 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2280 // And vice-versa. 2281 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2282 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask); 2283 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) { 2284 bool All = true; 2285 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(), 2286 E = Operands.end(); I != E; ++I) 2287 if (!isKnownNonNegative(*I)) { 2288 All = false; 2289 break; 2290 } 2291 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2292 } 2293 2294 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 2295 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 2296 const Loop *NestedLoop = NestedAR->getLoop(); 2297 if (L->contains(NestedLoop) ? 2298 (L->getLoopDepth() < NestedLoop->getLoopDepth()) : 2299 (!NestedLoop->contains(L) && 2300 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) { 2301 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 2302 NestedAR->op_end()); 2303 Operands[0] = NestedAR->getStart(); 2304 // AddRecs require their operands be loop-invariant with respect to their 2305 // loops. Don't perform this transformation if it would break this 2306 // requirement. 2307 bool AllInvariant = true; 2308 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2309 if (!isLoopInvariant(Operands[i], L)) { 2310 AllInvariant = false; 2311 break; 2312 } 2313 if (AllInvariant) { 2314 // Create a recurrence for the outer loop with the same step size. 2315 // 2316 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 2317 // inner recurrence has the same property. 2318 SCEV::NoWrapFlags OuterFlags = 2319 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 2320 2321 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 2322 AllInvariant = true; 2323 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i) 2324 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) { 2325 AllInvariant = false; 2326 break; 2327 } 2328 if (AllInvariant) { 2329 // Ok, both add recurrences are valid after the transformation. 2330 // 2331 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 2332 // the outer recurrence has the same property. 2333 SCEV::NoWrapFlags InnerFlags = 2334 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 2335 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 2336 } 2337 } 2338 // Reset Operands to its original state. 2339 Operands[0] = NestedAR; 2340 } 2341 } 2342 2343 // Okay, it looks like we really DO need an addrec expr. Check to see if we 2344 // already have one, otherwise create a new one. 2345 FoldingSetNodeID ID; 2346 ID.AddInteger(scAddRecExpr); 2347 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2348 ID.AddPointer(Operands[i]); 2349 ID.AddPointer(L); 2350 void *IP = 0; 2351 SCEVAddRecExpr *S = 2352 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2353 if (!S) { 2354 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 2355 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 2356 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 2357 O, Operands.size(), L); 2358 UniqueSCEVs.InsertNode(S, IP); 2359 } 2360 S->setNoWrapFlags(Flags); 2361 return S; 2362 } 2363 2364 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 2365 const SCEV *RHS) { 2366 SmallVector<const SCEV *, 2> Ops; 2367 Ops.push_back(LHS); 2368 Ops.push_back(RHS); 2369 return getSMaxExpr(Ops); 2370 } 2371 2372 const SCEV * 2373 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 2374 assert(!Ops.empty() && "Cannot get empty smax!"); 2375 if (Ops.size() == 1) return Ops[0]; 2376 #ifndef NDEBUG 2377 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2378 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2379 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2380 "SCEVSMaxExpr operand types don't match!"); 2381 #endif 2382 2383 // Sort by complexity, this groups all similar expression types together. 2384 GroupByComplexity(Ops, LI); 2385 2386 // If there are any constants, fold them together. 2387 unsigned Idx = 0; 2388 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2389 ++Idx; 2390 assert(Idx < Ops.size()); 2391 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2392 // We found two constants, fold them together! 2393 ConstantInt *Fold = ConstantInt::get(getContext(), 2394 APIntOps::smax(LHSC->getValue()->getValue(), 2395 RHSC->getValue()->getValue())); 2396 Ops[0] = getConstant(Fold); 2397 Ops.erase(Ops.begin()+1); // Erase the folded element 2398 if (Ops.size() == 1) return Ops[0]; 2399 LHSC = cast<SCEVConstant>(Ops[0]); 2400 } 2401 2402 // If we are left with a constant minimum-int, strip it off. 2403 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 2404 Ops.erase(Ops.begin()); 2405 --Idx; 2406 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 2407 // If we have an smax with a constant maximum-int, it will always be 2408 // maximum-int. 2409 return Ops[0]; 2410 } 2411 2412 if (Ops.size() == 1) return Ops[0]; 2413 } 2414 2415 // Find the first SMax 2416 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 2417 ++Idx; 2418 2419 // Check to see if one of the operands is an SMax. If so, expand its operands 2420 // onto our operand list, and recurse to simplify. 2421 if (Idx < Ops.size()) { 2422 bool DeletedSMax = false; 2423 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 2424 Ops.erase(Ops.begin()+Idx); 2425 Ops.append(SMax->op_begin(), SMax->op_end()); 2426 DeletedSMax = true; 2427 } 2428 2429 if (DeletedSMax) 2430 return getSMaxExpr(Ops); 2431 } 2432 2433 // Okay, check to see if the same value occurs in the operand list twice. If 2434 // so, delete one. Since we sorted the list, these values are required to 2435 // be adjacent. 2436 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 2437 // X smax Y smax Y --> X smax Y 2438 // X smax Y --> X, if X is always greater than Y 2439 if (Ops[i] == Ops[i+1] || 2440 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 2441 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 2442 --i; --e; 2443 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 2444 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 2445 --i; --e; 2446 } 2447 2448 if (Ops.size() == 1) return Ops[0]; 2449 2450 assert(!Ops.empty() && "Reduced smax down to nothing!"); 2451 2452 // Okay, it looks like we really DO need an smax expr. Check to see if we 2453 // already have one, otherwise create a new one. 2454 FoldingSetNodeID ID; 2455 ID.AddInteger(scSMaxExpr); 2456 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2457 ID.AddPointer(Ops[i]); 2458 void *IP = 0; 2459 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2460 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2461 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2462 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 2463 O, Ops.size()); 2464 UniqueSCEVs.InsertNode(S, IP); 2465 return S; 2466 } 2467 2468 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 2469 const SCEV *RHS) { 2470 SmallVector<const SCEV *, 2> Ops; 2471 Ops.push_back(LHS); 2472 Ops.push_back(RHS); 2473 return getUMaxExpr(Ops); 2474 } 2475 2476 const SCEV * 2477 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 2478 assert(!Ops.empty() && "Cannot get empty umax!"); 2479 if (Ops.size() == 1) return Ops[0]; 2480 #ifndef NDEBUG 2481 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2482 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2483 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2484 "SCEVUMaxExpr operand types don't match!"); 2485 #endif 2486 2487 // Sort by complexity, this groups all similar expression types together. 2488 GroupByComplexity(Ops, LI); 2489 2490 // If there are any constants, fold them together. 2491 unsigned Idx = 0; 2492 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2493 ++Idx; 2494 assert(Idx < Ops.size()); 2495 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2496 // We found two constants, fold them together! 2497 ConstantInt *Fold = ConstantInt::get(getContext(), 2498 APIntOps::umax(LHSC->getValue()->getValue(), 2499 RHSC->getValue()->getValue())); 2500 Ops[0] = getConstant(Fold); 2501 Ops.erase(Ops.begin()+1); // Erase the folded element 2502 if (Ops.size() == 1) return Ops[0]; 2503 LHSC = cast<SCEVConstant>(Ops[0]); 2504 } 2505 2506 // If we are left with a constant minimum-int, strip it off. 2507 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 2508 Ops.erase(Ops.begin()); 2509 --Idx; 2510 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 2511 // If we have an umax with a constant maximum-int, it will always be 2512 // maximum-int. 2513 return Ops[0]; 2514 } 2515 2516 if (Ops.size() == 1) return Ops[0]; 2517 } 2518 2519 // Find the first UMax 2520 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 2521 ++Idx; 2522 2523 // Check to see if one of the operands is a UMax. If so, expand its operands 2524 // onto our operand list, and recurse to simplify. 2525 if (Idx < Ops.size()) { 2526 bool DeletedUMax = false; 2527 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 2528 Ops.erase(Ops.begin()+Idx); 2529 Ops.append(UMax->op_begin(), UMax->op_end()); 2530 DeletedUMax = true; 2531 } 2532 2533 if (DeletedUMax) 2534 return getUMaxExpr(Ops); 2535 } 2536 2537 // Okay, check to see if the same value occurs in the operand list twice. If 2538 // so, delete one. Since we sorted the list, these values are required to 2539 // be adjacent. 2540 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 2541 // X umax Y umax Y --> X umax Y 2542 // X umax Y --> X, if X is always greater than Y 2543 if (Ops[i] == Ops[i+1] || 2544 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 2545 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 2546 --i; --e; 2547 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 2548 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 2549 --i; --e; 2550 } 2551 2552 if (Ops.size() == 1) return Ops[0]; 2553 2554 assert(!Ops.empty() && "Reduced umax down to nothing!"); 2555 2556 // Okay, it looks like we really DO need a umax expr. Check to see if we 2557 // already have one, otherwise create a new one. 2558 FoldingSetNodeID ID; 2559 ID.AddInteger(scUMaxExpr); 2560 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2561 ID.AddPointer(Ops[i]); 2562 void *IP = 0; 2563 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2564 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2565 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2566 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 2567 O, Ops.size()); 2568 UniqueSCEVs.InsertNode(S, IP); 2569 return S; 2570 } 2571 2572 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 2573 const SCEV *RHS) { 2574 // ~smax(~x, ~y) == smin(x, y). 2575 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 2576 } 2577 2578 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 2579 const SCEV *RHS) { 2580 // ~umax(~x, ~y) == umin(x, y) 2581 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 2582 } 2583 2584 const SCEV *ScalarEvolution::getSizeOfExpr(Type *AllocTy) { 2585 // If we have TargetData, we can bypass creating a target-independent 2586 // constant expression and then folding it back into a ConstantInt. 2587 // This is just a compile-time optimization. 2588 if (TD) 2589 return getConstant(TD->getIntPtrType(getContext()), 2590 TD->getTypeAllocSize(AllocTy)); 2591 2592 Constant *C = ConstantExpr::getSizeOf(AllocTy); 2593 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) 2594 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD)) 2595 C = Folded; 2596 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy)); 2597 return getTruncateOrZeroExtend(getSCEV(C), Ty); 2598 } 2599 2600 const SCEV *ScalarEvolution::getAlignOfExpr(Type *AllocTy) { 2601 Constant *C = ConstantExpr::getAlignOf(AllocTy); 2602 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) 2603 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD)) 2604 C = Folded; 2605 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy)); 2606 return getTruncateOrZeroExtend(getSCEV(C), Ty); 2607 } 2608 2609 const SCEV *ScalarEvolution::getOffsetOfExpr(StructType *STy, 2610 unsigned FieldNo) { 2611 // If we have TargetData, we can bypass creating a target-independent 2612 // constant expression and then folding it back into a ConstantInt. 2613 // This is just a compile-time optimization. 2614 if (TD) 2615 return getConstant(TD->getIntPtrType(getContext()), 2616 TD->getStructLayout(STy)->getElementOffset(FieldNo)); 2617 2618 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo); 2619 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) 2620 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD)) 2621 C = Folded; 2622 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy)); 2623 return getTruncateOrZeroExtend(getSCEV(C), Ty); 2624 } 2625 2626 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *CTy, 2627 Constant *FieldNo) { 2628 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo); 2629 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) 2630 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD)) 2631 C = Folded; 2632 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy)); 2633 return getTruncateOrZeroExtend(getSCEV(C), Ty); 2634 } 2635 2636 const SCEV *ScalarEvolution::getUnknown(Value *V) { 2637 // Don't attempt to do anything other than create a SCEVUnknown object 2638 // here. createSCEV only calls getUnknown after checking for all other 2639 // interesting possibilities, and any other code that calls getUnknown 2640 // is doing so in order to hide a value from SCEV canonicalization. 2641 2642 FoldingSetNodeID ID; 2643 ID.AddInteger(scUnknown); 2644 ID.AddPointer(V); 2645 void *IP = 0; 2646 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 2647 assert(cast<SCEVUnknown>(S)->getValue() == V && 2648 "Stale SCEVUnknown in uniquing map!"); 2649 return S; 2650 } 2651 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 2652 FirstUnknown); 2653 FirstUnknown = cast<SCEVUnknown>(S); 2654 UniqueSCEVs.InsertNode(S, IP); 2655 return S; 2656 } 2657 2658 //===----------------------------------------------------------------------===// 2659 // Basic SCEV Analysis and PHI Idiom Recognition Code 2660 // 2661 2662 /// isSCEVable - Test if values of the given type are analyzable within 2663 /// the SCEV framework. This primarily includes integer types, and it 2664 /// can optionally include pointer types if the ScalarEvolution class 2665 /// has access to target-specific information. 2666 bool ScalarEvolution::isSCEVable(Type *Ty) const { 2667 // Integers and pointers are always SCEVable. 2668 return Ty->isIntegerTy() || Ty->isPointerTy(); 2669 } 2670 2671 /// getTypeSizeInBits - Return the size in bits of the specified type, 2672 /// for which isSCEVable must return true. 2673 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 2674 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 2675 2676 // If we have a TargetData, use it! 2677 if (TD) 2678 return TD->getTypeSizeInBits(Ty); 2679 2680 // Integer types have fixed sizes. 2681 if (Ty->isIntegerTy()) 2682 return Ty->getPrimitiveSizeInBits(); 2683 2684 // The only other support type is pointer. Without TargetData, conservatively 2685 // assume pointers are 64-bit. 2686 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!"); 2687 return 64; 2688 } 2689 2690 /// getEffectiveSCEVType - Return a type with the same bitwidth as 2691 /// the given type and which represents how SCEV will treat the given 2692 /// type, for which isSCEVable must return true. For pointer types, 2693 /// this is the pointer-sized integer type. 2694 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 2695 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 2696 2697 if (Ty->isIntegerTy()) 2698 return Ty; 2699 2700 // The only other support type is pointer. 2701 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 2702 if (TD) return TD->getIntPtrType(getContext()); 2703 2704 // Without TargetData, conservatively assume pointers are 64-bit. 2705 return Type::getInt64Ty(getContext()); 2706 } 2707 2708 const SCEV *ScalarEvolution::getCouldNotCompute() { 2709 return &CouldNotCompute; 2710 } 2711 2712 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 2713 /// expression and create a new one. 2714 const SCEV *ScalarEvolution::getSCEV(Value *V) { 2715 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 2716 2717 ValueExprMapType::const_iterator I = ValueExprMap.find(V); 2718 if (I != ValueExprMap.end()) return I->second; 2719 const SCEV *S = createSCEV(V); 2720 2721 // The process of creating a SCEV for V may have caused other SCEVs 2722 // to have been created, so it's necessary to insert the new entry 2723 // from scratch, rather than trying to remember the insert position 2724 // above. 2725 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S)); 2726 return S; 2727 } 2728 2729 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V 2730 /// 2731 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) { 2732 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 2733 return getConstant( 2734 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 2735 2736 Type *Ty = V->getType(); 2737 Ty = getEffectiveSCEVType(Ty); 2738 return getMulExpr(V, 2739 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)))); 2740 } 2741 2742 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V 2743 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 2744 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 2745 return getConstant( 2746 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 2747 2748 Type *Ty = V->getType(); 2749 Ty = getEffectiveSCEVType(Ty); 2750 const SCEV *AllOnes = 2751 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 2752 return getMinusSCEV(AllOnes, V); 2753 } 2754 2755 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1. 2756 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 2757 SCEV::NoWrapFlags Flags) { 2758 assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW"); 2759 2760 // Fast path: X - X --> 0. 2761 if (LHS == RHS) 2762 return getConstant(LHS->getType(), 0); 2763 2764 // X - Y --> X + -Y 2765 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags); 2766 } 2767 2768 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the 2769 /// input value to the specified type. If the type must be extended, it is zero 2770 /// extended. 2771 const SCEV * 2772 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 2773 Type *SrcTy = V->getType(); 2774 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 2775 (Ty->isIntegerTy() || Ty->isPointerTy()) && 2776 "Cannot truncate or zero extend with non-integer arguments!"); 2777 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2778 return V; // No conversion 2779 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 2780 return getTruncateExpr(V, Ty); 2781 return getZeroExtendExpr(V, Ty); 2782 } 2783 2784 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the 2785 /// input value to the specified type. If the type must be extended, it is sign 2786 /// extended. 2787 const SCEV * 2788 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 2789 Type *Ty) { 2790 Type *SrcTy = V->getType(); 2791 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 2792 (Ty->isIntegerTy() || Ty->isPointerTy()) && 2793 "Cannot truncate or zero extend with non-integer arguments!"); 2794 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2795 return V; // No conversion 2796 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 2797 return getTruncateExpr(V, Ty); 2798 return getSignExtendExpr(V, Ty); 2799 } 2800 2801 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the 2802 /// input value to the specified type. If the type must be extended, it is zero 2803 /// extended. The conversion must not be narrowing. 2804 const SCEV * 2805 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 2806 Type *SrcTy = V->getType(); 2807 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 2808 (Ty->isIntegerTy() || Ty->isPointerTy()) && 2809 "Cannot noop or zero extend with non-integer arguments!"); 2810 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 2811 "getNoopOrZeroExtend cannot truncate!"); 2812 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2813 return V; // No conversion 2814 return getZeroExtendExpr(V, Ty); 2815 } 2816 2817 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the 2818 /// input value to the specified type. If the type must be extended, it is sign 2819 /// extended. The conversion must not be narrowing. 2820 const SCEV * 2821 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 2822 Type *SrcTy = V->getType(); 2823 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 2824 (Ty->isIntegerTy() || Ty->isPointerTy()) && 2825 "Cannot noop or sign extend with non-integer arguments!"); 2826 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 2827 "getNoopOrSignExtend cannot truncate!"); 2828 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2829 return V; // No conversion 2830 return getSignExtendExpr(V, Ty); 2831 } 2832 2833 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of 2834 /// the input value to the specified type. If the type must be extended, 2835 /// it is extended with unspecified bits. The conversion must not be 2836 /// narrowing. 2837 const SCEV * 2838 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 2839 Type *SrcTy = V->getType(); 2840 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 2841 (Ty->isIntegerTy() || Ty->isPointerTy()) && 2842 "Cannot noop or any extend with non-integer arguments!"); 2843 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 2844 "getNoopOrAnyExtend cannot truncate!"); 2845 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2846 return V; // No conversion 2847 return getAnyExtendExpr(V, Ty); 2848 } 2849 2850 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the 2851 /// input value to the specified type. The conversion must not be widening. 2852 const SCEV * 2853 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 2854 Type *SrcTy = V->getType(); 2855 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 2856 (Ty->isIntegerTy() || Ty->isPointerTy()) && 2857 "Cannot truncate or noop with non-integer arguments!"); 2858 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 2859 "getTruncateOrNoop cannot extend!"); 2860 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2861 return V; // No conversion 2862 return getTruncateExpr(V, Ty); 2863 } 2864 2865 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of 2866 /// the types using zero-extension, and then perform a umax operation 2867 /// with them. 2868 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 2869 const SCEV *RHS) { 2870 const SCEV *PromotedLHS = LHS; 2871 const SCEV *PromotedRHS = RHS; 2872 2873 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 2874 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 2875 else 2876 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 2877 2878 return getUMaxExpr(PromotedLHS, PromotedRHS); 2879 } 2880 2881 /// getUMinFromMismatchedTypes - Promote the operands to the wider of 2882 /// the types using zero-extension, and then perform a umin operation 2883 /// with them. 2884 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 2885 const SCEV *RHS) { 2886 const SCEV *PromotedLHS = LHS; 2887 const SCEV *PromotedRHS = RHS; 2888 2889 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 2890 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 2891 else 2892 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 2893 2894 return getUMinExpr(PromotedLHS, PromotedRHS); 2895 } 2896 2897 /// getPointerBase - Transitively follow the chain of pointer-type operands 2898 /// until reaching a SCEV that does not have a single pointer operand. This 2899 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions, 2900 /// but corner cases do exist. 2901 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 2902 // A pointer operand may evaluate to a nonpointer expression, such as null. 2903 if (!V->getType()->isPointerTy()) 2904 return V; 2905 2906 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 2907 return getPointerBase(Cast->getOperand()); 2908 } 2909 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 2910 const SCEV *PtrOp = 0; 2911 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 2912 I != E; ++I) { 2913 if ((*I)->getType()->isPointerTy()) { 2914 // Cannot find the base of an expression with multiple pointer operands. 2915 if (PtrOp) 2916 return V; 2917 PtrOp = *I; 2918 } 2919 } 2920 if (!PtrOp) 2921 return V; 2922 return getPointerBase(PtrOp); 2923 } 2924 return V; 2925 } 2926 2927 /// PushDefUseChildren - Push users of the given Instruction 2928 /// onto the given Worklist. 2929 static void 2930 PushDefUseChildren(Instruction *I, 2931 SmallVectorImpl<Instruction *> &Worklist) { 2932 // Push the def-use children onto the Worklist stack. 2933 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); 2934 UI != UE; ++UI) 2935 Worklist.push_back(cast<Instruction>(*UI)); 2936 } 2937 2938 /// ForgetSymbolicValue - This looks up computed SCEV values for all 2939 /// instructions that depend on the given instruction and removes them from 2940 /// the ValueExprMapType map if they reference SymName. This is used during PHI 2941 /// resolution. 2942 void 2943 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) { 2944 SmallVector<Instruction *, 16> Worklist; 2945 PushDefUseChildren(PN, Worklist); 2946 2947 SmallPtrSet<Instruction *, 8> Visited; 2948 Visited.insert(PN); 2949 while (!Worklist.empty()) { 2950 Instruction *I = Worklist.pop_back_val(); 2951 if (!Visited.insert(I)) continue; 2952 2953 ValueExprMapType::iterator It = 2954 ValueExprMap.find(static_cast<Value *>(I)); 2955 if (It != ValueExprMap.end()) { 2956 const SCEV *Old = It->second; 2957 2958 // Short-circuit the def-use traversal if the symbolic name 2959 // ceases to appear in expressions. 2960 if (Old != SymName && !hasOperand(Old, SymName)) 2961 continue; 2962 2963 // SCEVUnknown for a PHI either means that it has an unrecognized 2964 // structure, it's a PHI that's in the progress of being computed 2965 // by createNodeForPHI, or it's a single-value PHI. In the first case, 2966 // additional loop trip count information isn't going to change anything. 2967 // In the second case, createNodeForPHI will perform the necessary 2968 // updates on its own when it gets to that point. In the third, we do 2969 // want to forget the SCEVUnknown. 2970 if (!isa<PHINode>(I) || 2971 !isa<SCEVUnknown>(Old) || 2972 (I != PN && Old == SymName)) { 2973 forgetMemoizedResults(Old); 2974 ValueExprMap.erase(It); 2975 } 2976 } 2977 2978 PushDefUseChildren(I, Worklist); 2979 } 2980 } 2981 2982 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in 2983 /// a loop header, making it a potential recurrence, or it doesn't. 2984 /// 2985 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 2986 if (const Loop *L = LI->getLoopFor(PN->getParent())) 2987 if (L->getHeader() == PN->getParent()) { 2988 // The loop may have multiple entrances or multiple exits; we can analyze 2989 // this phi as an addrec if it has a unique entry value and a unique 2990 // backedge value. 2991 Value *BEValueV = 0, *StartValueV = 0; 2992 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 2993 Value *V = PN->getIncomingValue(i); 2994 if (L->contains(PN->getIncomingBlock(i))) { 2995 if (!BEValueV) { 2996 BEValueV = V; 2997 } else if (BEValueV != V) { 2998 BEValueV = 0; 2999 break; 3000 } 3001 } else if (!StartValueV) { 3002 StartValueV = V; 3003 } else if (StartValueV != V) { 3004 StartValueV = 0; 3005 break; 3006 } 3007 } 3008 if (BEValueV && StartValueV) { 3009 // While we are analyzing this PHI node, handle its value symbolically. 3010 const SCEV *SymbolicName = getUnknown(PN); 3011 assert(ValueExprMap.find(PN) == ValueExprMap.end() && 3012 "PHI node already processed?"); 3013 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName)); 3014 3015 // Using this symbolic name for the PHI, analyze the value coming around 3016 // the back-edge. 3017 const SCEV *BEValue = getSCEV(BEValueV); 3018 3019 // NOTE: If BEValue is loop invariant, we know that the PHI node just 3020 // has a special value for the first iteration of the loop. 3021 3022 // If the value coming around the backedge is an add with the symbolic 3023 // value we just inserted, then we found a simple induction variable! 3024 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 3025 // If there is a single occurrence of the symbolic value, replace it 3026 // with a recurrence. 3027 unsigned FoundIndex = Add->getNumOperands(); 3028 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 3029 if (Add->getOperand(i) == SymbolicName) 3030 if (FoundIndex == e) { 3031 FoundIndex = i; 3032 break; 3033 } 3034 3035 if (FoundIndex != Add->getNumOperands()) { 3036 // Create an add with everything but the specified operand. 3037 SmallVector<const SCEV *, 8> Ops; 3038 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 3039 if (i != FoundIndex) 3040 Ops.push_back(Add->getOperand(i)); 3041 const SCEV *Accum = getAddExpr(Ops); 3042 3043 // This is not a valid addrec if the step amount is varying each 3044 // loop iteration, but is not itself an addrec in this loop. 3045 if (isLoopInvariant(Accum, L) || 3046 (isa<SCEVAddRecExpr>(Accum) && 3047 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 3048 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 3049 3050 // If the increment doesn't overflow, then neither the addrec nor 3051 // the post-increment will overflow. 3052 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) { 3053 if (OBO->hasNoUnsignedWrap()) 3054 Flags = setFlags(Flags, SCEV::FlagNUW); 3055 if (OBO->hasNoSignedWrap()) 3056 Flags = setFlags(Flags, SCEV::FlagNSW); 3057 } else if (const GEPOperator *GEP = 3058 dyn_cast<GEPOperator>(BEValueV)) { 3059 // If the increment is an inbounds GEP, then we know the address 3060 // space cannot be wrapped around. We cannot make any guarantee 3061 // about signed or unsigned overflow because pointers are 3062 // unsigned but we may have a negative index from the base 3063 // pointer. 3064 if (GEP->isInBounds()) 3065 Flags = setFlags(Flags, SCEV::FlagNW); 3066 } 3067 3068 const SCEV *StartVal = getSCEV(StartValueV); 3069 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 3070 3071 // Since the no-wrap flags are on the increment, they apply to the 3072 // post-incremented value as well. 3073 if (isLoopInvariant(Accum, L)) 3074 (void)getAddRecExpr(getAddExpr(StartVal, Accum), 3075 Accum, L, Flags); 3076 3077 // Okay, for the entire analysis of this edge we assumed the PHI 3078 // to be symbolic. We now need to go back and purge all of the 3079 // entries for the scalars that use the symbolic expression. 3080 ForgetSymbolicName(PN, SymbolicName); 3081 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 3082 return PHISCEV; 3083 } 3084 } 3085 } else if (const SCEVAddRecExpr *AddRec = 3086 dyn_cast<SCEVAddRecExpr>(BEValue)) { 3087 // Otherwise, this could be a loop like this: 3088 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 3089 // In this case, j = {1,+,1} and BEValue is j. 3090 // Because the other in-value of i (0) fits the evolution of BEValue 3091 // i really is an addrec evolution. 3092 if (AddRec->getLoop() == L && AddRec->isAffine()) { 3093 const SCEV *StartVal = getSCEV(StartValueV); 3094 3095 // If StartVal = j.start - j.stride, we can use StartVal as the 3096 // initial step of the addrec evolution. 3097 if (StartVal == getMinusSCEV(AddRec->getOperand(0), 3098 AddRec->getOperand(1))) { 3099 // FIXME: For constant StartVal, we should be able to infer 3100 // no-wrap flags. 3101 const SCEV *PHISCEV = 3102 getAddRecExpr(StartVal, AddRec->getOperand(1), L, 3103 SCEV::FlagAnyWrap); 3104 3105 // Okay, for the entire analysis of this edge we assumed the PHI 3106 // to be symbolic. We now need to go back and purge all of the 3107 // entries for the scalars that use the symbolic expression. 3108 ForgetSymbolicName(PN, SymbolicName); 3109 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 3110 return PHISCEV; 3111 } 3112 } 3113 } 3114 } 3115 } 3116 3117 // If the PHI has a single incoming value, follow that value, unless the 3118 // PHI's incoming blocks are in a different loop, in which case doing so 3119 // risks breaking LCSSA form. Instcombine would normally zap these, but 3120 // it doesn't have DominatorTree information, so it may miss cases. 3121 if (Value *V = SimplifyInstruction(PN, TD, TLI, DT)) 3122 if (LI->replacementPreservesLCSSAForm(PN, V)) 3123 return getSCEV(V); 3124 3125 // If it's not a loop phi, we can't handle it yet. 3126 return getUnknown(PN); 3127 } 3128 3129 /// createNodeForGEP - Expand GEP instructions into add and multiply 3130 /// operations. This allows them to be analyzed by regular SCEV code. 3131 /// 3132 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 3133 3134 // Don't blindly transfer the inbounds flag from the GEP instruction to the 3135 // Add expression, because the Instruction may be guarded by control flow 3136 // and the no-overflow bits may not be valid for the expression in any 3137 // context. 3138 bool isInBounds = GEP->isInBounds(); 3139 3140 Type *IntPtrTy = getEffectiveSCEVType(GEP->getType()); 3141 Value *Base = GEP->getOperand(0); 3142 // Don't attempt to analyze GEPs over unsized objects. 3143 if (!cast<PointerType>(Base->getType())->getElementType()->isSized()) 3144 return getUnknown(GEP); 3145 const SCEV *TotalOffset = getConstant(IntPtrTy, 0); 3146 gep_type_iterator GTI = gep_type_begin(GEP); 3147 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()), 3148 E = GEP->op_end(); 3149 I != E; ++I) { 3150 Value *Index = *I; 3151 // Compute the (potentially symbolic) offset in bytes for this index. 3152 if (StructType *STy = dyn_cast<StructType>(*GTI++)) { 3153 // For a struct, add the member offset. 3154 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue(); 3155 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo); 3156 3157 // Add the field offset to the running total offset. 3158 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3159 } else { 3160 // For an array, add the element offset, explicitly scaled. 3161 const SCEV *ElementSize = getSizeOfExpr(*GTI); 3162 const SCEV *IndexS = getSCEV(Index); 3163 // Getelementptr indices are signed. 3164 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy); 3165 3166 // Multiply the index by the element size to compute the element offset. 3167 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize, 3168 isInBounds ? SCEV::FlagNSW : 3169 SCEV::FlagAnyWrap); 3170 3171 // Add the element offset to the running total offset. 3172 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3173 } 3174 } 3175 3176 // Get the SCEV for the GEP base. 3177 const SCEV *BaseS = getSCEV(Base); 3178 3179 // Add the total offset from all the GEP indices to the base. 3180 return getAddExpr(BaseS, TotalOffset, 3181 isInBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap); 3182 } 3183 3184 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is 3185 /// guaranteed to end in (at every loop iteration). It is, at the same time, 3186 /// the minimum number of times S is divisible by 2. For example, given {4,+,8} 3187 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S. 3188 uint32_t 3189 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 3190 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 3191 return C->getValue()->getValue().countTrailingZeros(); 3192 3193 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 3194 return std::min(GetMinTrailingZeros(T->getOperand()), 3195 (uint32_t)getTypeSizeInBits(T->getType())); 3196 3197 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 3198 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 3199 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 3200 getTypeSizeInBits(E->getType()) : OpRes; 3201 } 3202 3203 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 3204 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 3205 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 3206 getTypeSizeInBits(E->getType()) : OpRes; 3207 } 3208 3209 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 3210 // The result is the min of all operands results. 3211 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 3212 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 3213 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 3214 return MinOpRes; 3215 } 3216 3217 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 3218 // The result is the sum of all operands results. 3219 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 3220 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 3221 for (unsigned i = 1, e = M->getNumOperands(); 3222 SumOpRes != BitWidth && i != e; ++i) 3223 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), 3224 BitWidth); 3225 return SumOpRes; 3226 } 3227 3228 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 3229 // The result is the min of all operands results. 3230 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 3231 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 3232 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 3233 return MinOpRes; 3234 } 3235 3236 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 3237 // The result is the min of all operands results. 3238 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 3239 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 3240 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 3241 return MinOpRes; 3242 } 3243 3244 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 3245 // The result is the min of all operands results. 3246 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 3247 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 3248 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 3249 return MinOpRes; 3250 } 3251 3252 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 3253 // For a SCEVUnknown, ask ValueTracking. 3254 unsigned BitWidth = getTypeSizeInBits(U->getType()); 3255 APInt Mask = APInt::getAllOnesValue(BitWidth); 3256 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 3257 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones); 3258 return Zeros.countTrailingOnes(); 3259 } 3260 3261 // SCEVUDivExpr 3262 return 0; 3263 } 3264 3265 /// getUnsignedRange - Determine the unsigned range for a particular SCEV. 3266 /// 3267 ConstantRange 3268 ScalarEvolution::getUnsignedRange(const SCEV *S) { 3269 // See if we've computed this range already. 3270 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S); 3271 if (I != UnsignedRanges.end()) 3272 return I->second; 3273 3274 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 3275 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue())); 3276 3277 unsigned BitWidth = getTypeSizeInBits(S->getType()); 3278 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 3279 3280 // If the value has known zeros, the maximum unsigned value will have those 3281 // known zeros as well. 3282 uint32_t TZ = GetMinTrailingZeros(S); 3283 if (TZ != 0) 3284 ConservativeResult = 3285 ConstantRange(APInt::getMinValue(BitWidth), 3286 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 3287 3288 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 3289 ConstantRange X = getUnsignedRange(Add->getOperand(0)); 3290 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 3291 X = X.add(getUnsignedRange(Add->getOperand(i))); 3292 return setUnsignedRange(Add, ConservativeResult.intersectWith(X)); 3293 } 3294 3295 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 3296 ConstantRange X = getUnsignedRange(Mul->getOperand(0)); 3297 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 3298 X = X.multiply(getUnsignedRange(Mul->getOperand(i))); 3299 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X)); 3300 } 3301 3302 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 3303 ConstantRange X = getUnsignedRange(SMax->getOperand(0)); 3304 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 3305 X = X.smax(getUnsignedRange(SMax->getOperand(i))); 3306 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X)); 3307 } 3308 3309 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 3310 ConstantRange X = getUnsignedRange(UMax->getOperand(0)); 3311 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 3312 X = X.umax(getUnsignedRange(UMax->getOperand(i))); 3313 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X)); 3314 } 3315 3316 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 3317 ConstantRange X = getUnsignedRange(UDiv->getLHS()); 3318 ConstantRange Y = getUnsignedRange(UDiv->getRHS()); 3319 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y))); 3320 } 3321 3322 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 3323 ConstantRange X = getUnsignedRange(ZExt->getOperand()); 3324 return setUnsignedRange(ZExt, 3325 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 3326 } 3327 3328 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 3329 ConstantRange X = getUnsignedRange(SExt->getOperand()); 3330 return setUnsignedRange(SExt, 3331 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 3332 } 3333 3334 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 3335 ConstantRange X = getUnsignedRange(Trunc->getOperand()); 3336 return setUnsignedRange(Trunc, 3337 ConservativeResult.intersectWith(X.truncate(BitWidth))); 3338 } 3339 3340 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 3341 // If there's no unsigned wrap, the value will never be less than its 3342 // initial value. 3343 if (AddRec->getNoWrapFlags(SCEV::FlagNUW)) 3344 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 3345 if (!C->getValue()->isZero()) 3346 ConservativeResult = 3347 ConservativeResult.intersectWith( 3348 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0))); 3349 3350 // TODO: non-affine addrec 3351 if (AddRec->isAffine()) { 3352 Type *Ty = AddRec->getType(); 3353 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 3354 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 3355 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 3356 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty); 3357 3358 const SCEV *Start = AddRec->getStart(); 3359 const SCEV *Step = AddRec->getStepRecurrence(*this); 3360 3361 ConstantRange StartRange = getUnsignedRange(Start); 3362 ConstantRange StepRange = getSignedRange(Step); 3363 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 3364 ConstantRange EndRange = 3365 StartRange.add(MaxBECountRange.multiply(StepRange)); 3366 3367 // Check for overflow. This must be done with ConstantRange arithmetic 3368 // because we could be called from within the ScalarEvolution overflow 3369 // checking code. 3370 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1); 3371 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1); 3372 ConstantRange ExtMaxBECountRange = 3373 MaxBECountRange.zextOrTrunc(BitWidth*2+1); 3374 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1); 3375 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) != 3376 ExtEndRange) 3377 return setUnsignedRange(AddRec, ConservativeResult); 3378 3379 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(), 3380 EndRange.getUnsignedMin()); 3381 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(), 3382 EndRange.getUnsignedMax()); 3383 if (Min.isMinValue() && Max.isMaxValue()) 3384 return setUnsignedRange(AddRec, ConservativeResult); 3385 return setUnsignedRange(AddRec, 3386 ConservativeResult.intersectWith(ConstantRange(Min, Max+1))); 3387 } 3388 } 3389 3390 return setUnsignedRange(AddRec, ConservativeResult); 3391 } 3392 3393 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 3394 // For a SCEVUnknown, ask ValueTracking. 3395 APInt Mask = APInt::getAllOnesValue(BitWidth); 3396 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 3397 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD); 3398 if (Ones == ~Zeros + 1) 3399 return setUnsignedRange(U, ConservativeResult); 3400 return setUnsignedRange(U, 3401 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1))); 3402 } 3403 3404 return setUnsignedRange(S, ConservativeResult); 3405 } 3406 3407 /// getSignedRange - Determine the signed range for a particular SCEV. 3408 /// 3409 ConstantRange 3410 ScalarEvolution::getSignedRange(const SCEV *S) { 3411 // See if we've computed this range already. 3412 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S); 3413 if (I != SignedRanges.end()) 3414 return I->second; 3415 3416 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 3417 return setSignedRange(C, ConstantRange(C->getValue()->getValue())); 3418 3419 unsigned BitWidth = getTypeSizeInBits(S->getType()); 3420 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 3421 3422 // If the value has known zeros, the maximum signed value will have those 3423 // known zeros as well. 3424 uint32_t TZ = GetMinTrailingZeros(S); 3425 if (TZ != 0) 3426 ConservativeResult = 3427 ConstantRange(APInt::getSignedMinValue(BitWidth), 3428 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 3429 3430 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 3431 ConstantRange X = getSignedRange(Add->getOperand(0)); 3432 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 3433 X = X.add(getSignedRange(Add->getOperand(i))); 3434 return setSignedRange(Add, ConservativeResult.intersectWith(X)); 3435 } 3436 3437 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 3438 ConstantRange X = getSignedRange(Mul->getOperand(0)); 3439 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 3440 X = X.multiply(getSignedRange(Mul->getOperand(i))); 3441 return setSignedRange(Mul, ConservativeResult.intersectWith(X)); 3442 } 3443 3444 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 3445 ConstantRange X = getSignedRange(SMax->getOperand(0)); 3446 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 3447 X = X.smax(getSignedRange(SMax->getOperand(i))); 3448 return setSignedRange(SMax, ConservativeResult.intersectWith(X)); 3449 } 3450 3451 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 3452 ConstantRange X = getSignedRange(UMax->getOperand(0)); 3453 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 3454 X = X.umax(getSignedRange(UMax->getOperand(i))); 3455 return setSignedRange(UMax, ConservativeResult.intersectWith(X)); 3456 } 3457 3458 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 3459 ConstantRange X = getSignedRange(UDiv->getLHS()); 3460 ConstantRange Y = getSignedRange(UDiv->getRHS()); 3461 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y))); 3462 } 3463 3464 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 3465 ConstantRange X = getSignedRange(ZExt->getOperand()); 3466 return setSignedRange(ZExt, 3467 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 3468 } 3469 3470 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 3471 ConstantRange X = getSignedRange(SExt->getOperand()); 3472 return setSignedRange(SExt, 3473 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 3474 } 3475 3476 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 3477 ConstantRange X = getSignedRange(Trunc->getOperand()); 3478 return setSignedRange(Trunc, 3479 ConservativeResult.intersectWith(X.truncate(BitWidth))); 3480 } 3481 3482 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 3483 // If there's no signed wrap, and all the operands have the same sign or 3484 // zero, the value won't ever change sign. 3485 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) { 3486 bool AllNonNeg = true; 3487 bool AllNonPos = true; 3488 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 3489 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 3490 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 3491 } 3492 if (AllNonNeg) 3493 ConservativeResult = ConservativeResult.intersectWith( 3494 ConstantRange(APInt(BitWidth, 0), 3495 APInt::getSignedMinValue(BitWidth))); 3496 else if (AllNonPos) 3497 ConservativeResult = ConservativeResult.intersectWith( 3498 ConstantRange(APInt::getSignedMinValue(BitWidth), 3499 APInt(BitWidth, 1))); 3500 } 3501 3502 // TODO: non-affine addrec 3503 if (AddRec->isAffine()) { 3504 Type *Ty = AddRec->getType(); 3505 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 3506 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 3507 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 3508 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty); 3509 3510 const SCEV *Start = AddRec->getStart(); 3511 const SCEV *Step = AddRec->getStepRecurrence(*this); 3512 3513 ConstantRange StartRange = getSignedRange(Start); 3514 ConstantRange StepRange = getSignedRange(Step); 3515 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 3516 ConstantRange EndRange = 3517 StartRange.add(MaxBECountRange.multiply(StepRange)); 3518 3519 // Check for overflow. This must be done with ConstantRange arithmetic 3520 // because we could be called from within the ScalarEvolution overflow 3521 // checking code. 3522 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1); 3523 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1); 3524 ConstantRange ExtMaxBECountRange = 3525 MaxBECountRange.zextOrTrunc(BitWidth*2+1); 3526 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1); 3527 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) != 3528 ExtEndRange) 3529 return setSignedRange(AddRec, ConservativeResult); 3530 3531 APInt Min = APIntOps::smin(StartRange.getSignedMin(), 3532 EndRange.getSignedMin()); 3533 APInt Max = APIntOps::smax(StartRange.getSignedMax(), 3534 EndRange.getSignedMax()); 3535 if (Min.isMinSignedValue() && Max.isMaxSignedValue()) 3536 return setSignedRange(AddRec, ConservativeResult); 3537 return setSignedRange(AddRec, 3538 ConservativeResult.intersectWith(ConstantRange(Min, Max+1))); 3539 } 3540 } 3541 3542 return setSignedRange(AddRec, ConservativeResult); 3543 } 3544 3545 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 3546 // For a SCEVUnknown, ask ValueTracking. 3547 if (!U->getValue()->getType()->isIntegerTy() && !TD) 3548 return setSignedRange(U, ConservativeResult); 3549 unsigned NS = ComputeNumSignBits(U->getValue(), TD); 3550 if (NS == 1) 3551 return setSignedRange(U, ConservativeResult); 3552 return setSignedRange(U, ConservativeResult.intersectWith( 3553 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 3554 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1))); 3555 } 3556 3557 return setSignedRange(S, ConservativeResult); 3558 } 3559 3560 /// createSCEV - We know that there is no SCEV for the specified value. 3561 /// Analyze the expression. 3562 /// 3563 const SCEV *ScalarEvolution::createSCEV(Value *V) { 3564 if (!isSCEVable(V->getType())) 3565 return getUnknown(V); 3566 3567 unsigned Opcode = Instruction::UserOp1; 3568 if (Instruction *I = dyn_cast<Instruction>(V)) { 3569 Opcode = I->getOpcode(); 3570 3571 // Don't attempt to analyze instructions in blocks that aren't 3572 // reachable. Such instructions don't matter, and they aren't required 3573 // to obey basic rules for definitions dominating uses which this 3574 // analysis depends on. 3575 if (!DT->isReachableFromEntry(I->getParent())) 3576 return getUnknown(V); 3577 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 3578 Opcode = CE->getOpcode(); 3579 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 3580 return getConstant(CI); 3581 else if (isa<ConstantPointerNull>(V)) 3582 return getConstant(V->getType(), 0); 3583 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 3584 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee()); 3585 else 3586 return getUnknown(V); 3587 3588 Operator *U = cast<Operator>(V); 3589 switch (Opcode) { 3590 case Instruction::Add: { 3591 // The simple thing to do would be to just call getSCEV on both operands 3592 // and call getAddExpr with the result. However if we're looking at a 3593 // bunch of things all added together, this can be quite inefficient, 3594 // because it leads to N-1 getAddExpr calls for N ultimate operands. 3595 // Instead, gather up all the operands and make a single getAddExpr call. 3596 // LLVM IR canonical form means we need only traverse the left operands. 3597 // 3598 // Don't apply this instruction's NSW or NUW flags to the new 3599 // expression. The instruction may be guarded by control flow that the 3600 // no-wrap behavior depends on. Non-control-equivalent instructions can be 3601 // mapped to the same SCEV expression, and it would be incorrect to transfer 3602 // NSW/NUW semantics to those operations. 3603 SmallVector<const SCEV *, 4> AddOps; 3604 AddOps.push_back(getSCEV(U->getOperand(1))); 3605 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) { 3606 unsigned Opcode = Op->getValueID() - Value::InstructionVal; 3607 if (Opcode != Instruction::Add && Opcode != Instruction::Sub) 3608 break; 3609 U = cast<Operator>(Op); 3610 const SCEV *Op1 = getSCEV(U->getOperand(1)); 3611 if (Opcode == Instruction::Sub) 3612 AddOps.push_back(getNegativeSCEV(Op1)); 3613 else 3614 AddOps.push_back(Op1); 3615 } 3616 AddOps.push_back(getSCEV(U->getOperand(0))); 3617 return getAddExpr(AddOps); 3618 } 3619 case Instruction::Mul: { 3620 // Don't transfer NSW/NUW for the same reason as AddExpr. 3621 SmallVector<const SCEV *, 4> MulOps; 3622 MulOps.push_back(getSCEV(U->getOperand(1))); 3623 for (Value *Op = U->getOperand(0); 3624 Op->getValueID() == Instruction::Mul + Value::InstructionVal; 3625 Op = U->getOperand(0)) { 3626 U = cast<Operator>(Op); 3627 MulOps.push_back(getSCEV(U->getOperand(1))); 3628 } 3629 MulOps.push_back(getSCEV(U->getOperand(0))); 3630 return getMulExpr(MulOps); 3631 } 3632 case Instruction::UDiv: 3633 return getUDivExpr(getSCEV(U->getOperand(0)), 3634 getSCEV(U->getOperand(1))); 3635 case Instruction::Sub: 3636 return getMinusSCEV(getSCEV(U->getOperand(0)), 3637 getSCEV(U->getOperand(1))); 3638 case Instruction::And: 3639 // For an expression like x&255 that merely masks off the high bits, 3640 // use zext(trunc(x)) as the SCEV expression. 3641 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 3642 if (CI->isNullValue()) 3643 return getSCEV(U->getOperand(1)); 3644 if (CI->isAllOnesValue()) 3645 return getSCEV(U->getOperand(0)); 3646 const APInt &A = CI->getValue(); 3647 3648 // Instcombine's ShrinkDemandedConstant may strip bits out of 3649 // constants, obscuring what would otherwise be a low-bits mask. 3650 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant 3651 // knew about to reconstruct a low-bits mask value. 3652 unsigned LZ = A.countLeadingZeros(); 3653 unsigned BitWidth = A.getBitWidth(); 3654 APInt AllOnes = APInt::getAllOnesValue(BitWidth); 3655 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 3656 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD); 3657 3658 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ); 3659 3660 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask)) 3661 return 3662 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)), 3663 IntegerType::get(getContext(), BitWidth - LZ)), 3664 U->getType()); 3665 } 3666 break; 3667 3668 case Instruction::Or: 3669 // If the RHS of the Or is a constant, we may have something like: 3670 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 3671 // optimizations will transparently handle this case. 3672 // 3673 // In order for this transformation to be safe, the LHS must be of the 3674 // form X*(2^n) and the Or constant must be less than 2^n. 3675 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 3676 const SCEV *LHS = getSCEV(U->getOperand(0)); 3677 const APInt &CIVal = CI->getValue(); 3678 if (GetMinTrailingZeros(LHS) >= 3679 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 3680 // Build a plain add SCEV. 3681 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 3682 // If the LHS of the add was an addrec and it has no-wrap flags, 3683 // transfer the no-wrap flags, since an or won't introduce a wrap. 3684 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 3685 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 3686 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 3687 OldAR->getNoWrapFlags()); 3688 } 3689 return S; 3690 } 3691 } 3692 break; 3693 case Instruction::Xor: 3694 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 3695 // If the RHS of the xor is a signbit, then this is just an add. 3696 // Instcombine turns add of signbit into xor as a strength reduction step. 3697 if (CI->getValue().isSignBit()) 3698 return getAddExpr(getSCEV(U->getOperand(0)), 3699 getSCEV(U->getOperand(1))); 3700 3701 // If the RHS of xor is -1, then this is a not operation. 3702 if (CI->isAllOnesValue()) 3703 return getNotSCEV(getSCEV(U->getOperand(0))); 3704 3705 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 3706 // This is a variant of the check for xor with -1, and it handles 3707 // the case where instcombine has trimmed non-demanded bits out 3708 // of an xor with -1. 3709 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0))) 3710 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1))) 3711 if (BO->getOpcode() == Instruction::And && 3712 LCI->getValue() == CI->getValue()) 3713 if (const SCEVZeroExtendExpr *Z = 3714 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) { 3715 Type *UTy = U->getType(); 3716 const SCEV *Z0 = Z->getOperand(); 3717 Type *Z0Ty = Z0->getType(); 3718 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 3719 3720 // If C is a low-bits mask, the zero extend is serving to 3721 // mask off the high bits. Complement the operand and 3722 // re-apply the zext. 3723 if (APIntOps::isMask(Z0TySize, CI->getValue())) 3724 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 3725 3726 // If C is a single bit, it may be in the sign-bit position 3727 // before the zero-extend. In this case, represent the xor 3728 // using an add, which is equivalent, and re-apply the zext. 3729 APInt Trunc = CI->getValue().trunc(Z0TySize); 3730 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 3731 Trunc.isSignBit()) 3732 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 3733 UTy); 3734 } 3735 } 3736 break; 3737 3738 case Instruction::Shl: 3739 // Turn shift left of a constant amount into a multiply. 3740 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 3741 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth(); 3742 3743 // If the shift count is not less than the bitwidth, the result of 3744 // the shift is undefined. Don't try to analyze it, because the 3745 // resolution chosen here may differ from the resolution chosen in 3746 // other parts of the compiler. 3747 if (SA->getValue().uge(BitWidth)) 3748 break; 3749 3750 Constant *X = ConstantInt::get(getContext(), 3751 APInt(BitWidth, 1).shl(SA->getZExtValue())); 3752 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X)); 3753 } 3754 break; 3755 3756 case Instruction::LShr: 3757 // Turn logical shift right of a constant into a unsigned divide. 3758 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 3759 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth(); 3760 3761 // If the shift count is not less than the bitwidth, the result of 3762 // the shift is undefined. Don't try to analyze it, because the 3763 // resolution chosen here may differ from the resolution chosen in 3764 // other parts of the compiler. 3765 if (SA->getValue().uge(BitWidth)) 3766 break; 3767 3768 Constant *X = ConstantInt::get(getContext(), 3769 APInt(BitWidth, 1).shl(SA->getZExtValue())); 3770 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X)); 3771 } 3772 break; 3773 3774 case Instruction::AShr: 3775 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 3776 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) 3777 if (Operator *L = dyn_cast<Operator>(U->getOperand(0))) 3778 if (L->getOpcode() == Instruction::Shl && 3779 L->getOperand(1) == U->getOperand(1)) { 3780 uint64_t BitWidth = getTypeSizeInBits(U->getType()); 3781 3782 // If the shift count is not less than the bitwidth, the result of 3783 // the shift is undefined. Don't try to analyze it, because the 3784 // resolution chosen here may differ from the resolution chosen in 3785 // other parts of the compiler. 3786 if (CI->getValue().uge(BitWidth)) 3787 break; 3788 3789 uint64_t Amt = BitWidth - CI->getZExtValue(); 3790 if (Amt == BitWidth) 3791 return getSCEV(L->getOperand(0)); // shift by zero --> noop 3792 return 3793 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)), 3794 IntegerType::get(getContext(), 3795 Amt)), 3796 U->getType()); 3797 } 3798 break; 3799 3800 case Instruction::Trunc: 3801 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 3802 3803 case Instruction::ZExt: 3804 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 3805 3806 case Instruction::SExt: 3807 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 3808 3809 case Instruction::BitCast: 3810 // BitCasts are no-op casts so we just eliminate the cast. 3811 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 3812 return getSCEV(U->getOperand(0)); 3813 break; 3814 3815 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 3816 // lead to pointer expressions which cannot safely be expanded to GEPs, 3817 // because ScalarEvolution doesn't respect the GEP aliasing rules when 3818 // simplifying integer expressions. 3819 3820 case Instruction::GetElementPtr: 3821 return createNodeForGEP(cast<GEPOperator>(U)); 3822 3823 case Instruction::PHI: 3824 return createNodeForPHI(cast<PHINode>(U)); 3825 3826 case Instruction::Select: 3827 // This could be a smax or umax that was lowered earlier. 3828 // Try to recover it. 3829 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) { 3830 Value *LHS = ICI->getOperand(0); 3831 Value *RHS = ICI->getOperand(1); 3832 switch (ICI->getPredicate()) { 3833 case ICmpInst::ICMP_SLT: 3834 case ICmpInst::ICMP_SLE: 3835 std::swap(LHS, RHS); 3836 // fall through 3837 case ICmpInst::ICMP_SGT: 3838 case ICmpInst::ICMP_SGE: 3839 // a >s b ? a+x : b+x -> smax(a, b)+x 3840 // a >s b ? b+x : a+x -> smin(a, b)+x 3841 if (LHS->getType() == U->getType()) { 3842 const SCEV *LS = getSCEV(LHS); 3843 const SCEV *RS = getSCEV(RHS); 3844 const SCEV *LA = getSCEV(U->getOperand(1)); 3845 const SCEV *RA = getSCEV(U->getOperand(2)); 3846 const SCEV *LDiff = getMinusSCEV(LA, LS); 3847 const SCEV *RDiff = getMinusSCEV(RA, RS); 3848 if (LDiff == RDiff) 3849 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 3850 LDiff = getMinusSCEV(LA, RS); 3851 RDiff = getMinusSCEV(RA, LS); 3852 if (LDiff == RDiff) 3853 return getAddExpr(getSMinExpr(LS, RS), LDiff); 3854 } 3855 break; 3856 case ICmpInst::ICMP_ULT: 3857 case ICmpInst::ICMP_ULE: 3858 std::swap(LHS, RHS); 3859 // fall through 3860 case ICmpInst::ICMP_UGT: 3861 case ICmpInst::ICMP_UGE: 3862 // a >u b ? a+x : b+x -> umax(a, b)+x 3863 // a >u b ? b+x : a+x -> umin(a, b)+x 3864 if (LHS->getType() == U->getType()) { 3865 const SCEV *LS = getSCEV(LHS); 3866 const SCEV *RS = getSCEV(RHS); 3867 const SCEV *LA = getSCEV(U->getOperand(1)); 3868 const SCEV *RA = getSCEV(U->getOperand(2)); 3869 const SCEV *LDiff = getMinusSCEV(LA, LS); 3870 const SCEV *RDiff = getMinusSCEV(RA, RS); 3871 if (LDiff == RDiff) 3872 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 3873 LDiff = getMinusSCEV(LA, RS); 3874 RDiff = getMinusSCEV(RA, LS); 3875 if (LDiff == RDiff) 3876 return getAddExpr(getUMinExpr(LS, RS), LDiff); 3877 } 3878 break; 3879 case ICmpInst::ICMP_NE: 3880 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 3881 if (LHS->getType() == U->getType() && 3882 isa<ConstantInt>(RHS) && 3883 cast<ConstantInt>(RHS)->isZero()) { 3884 const SCEV *One = getConstant(LHS->getType(), 1); 3885 const SCEV *LS = getSCEV(LHS); 3886 const SCEV *LA = getSCEV(U->getOperand(1)); 3887 const SCEV *RA = getSCEV(U->getOperand(2)); 3888 const SCEV *LDiff = getMinusSCEV(LA, LS); 3889 const SCEV *RDiff = getMinusSCEV(RA, One); 3890 if (LDiff == RDiff) 3891 return getAddExpr(getUMaxExpr(One, LS), LDiff); 3892 } 3893 break; 3894 case ICmpInst::ICMP_EQ: 3895 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 3896 if (LHS->getType() == U->getType() && 3897 isa<ConstantInt>(RHS) && 3898 cast<ConstantInt>(RHS)->isZero()) { 3899 const SCEV *One = getConstant(LHS->getType(), 1); 3900 const SCEV *LS = getSCEV(LHS); 3901 const SCEV *LA = getSCEV(U->getOperand(1)); 3902 const SCEV *RA = getSCEV(U->getOperand(2)); 3903 const SCEV *LDiff = getMinusSCEV(LA, One); 3904 const SCEV *RDiff = getMinusSCEV(RA, LS); 3905 if (LDiff == RDiff) 3906 return getAddExpr(getUMaxExpr(One, LS), LDiff); 3907 } 3908 break; 3909 default: 3910 break; 3911 } 3912 } 3913 3914 default: // We cannot analyze this expression. 3915 break; 3916 } 3917 3918 return getUnknown(V); 3919 } 3920 3921 3922 3923 //===----------------------------------------------------------------------===// 3924 // Iteration Count Computation Code 3925 // 3926 3927 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a 3928 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown 3929 /// or not constant. Will also return 0 if the maximum trip count is very large 3930 /// (>= 2^32) 3931 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, 3932 BasicBlock *ExitBlock) { 3933 const SCEVConstant *ExitCount = 3934 dyn_cast<SCEVConstant>(getExitCount(L, ExitBlock)); 3935 if (!ExitCount) 3936 return 0; 3937 3938 ConstantInt *ExitConst = ExitCount->getValue(); 3939 3940 // Guard against huge trip counts. 3941 if (ExitConst->getValue().getActiveBits() > 32) 3942 return 0; 3943 3944 // In case of integer overflow, this returns 0, which is correct. 3945 return ((unsigned)ExitConst->getZExtValue()) + 1; 3946 } 3947 3948 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the 3949 /// trip count of this loop as a normal unsigned value, if possible. This 3950 /// means that the actual trip count is always a multiple of the returned 3951 /// value (don't forget the trip count could very well be zero as well!). 3952 /// 3953 /// Returns 1 if the trip count is unknown or not guaranteed to be the 3954 /// multiple of a constant (which is also the case if the trip count is simply 3955 /// constant, use getSmallConstantTripCount for that case), Will also return 1 3956 /// if the trip count is very large (>= 2^32). 3957 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L, 3958 BasicBlock *ExitBlock) { 3959 const SCEV *ExitCount = getExitCount(L, ExitBlock); 3960 if (ExitCount == getCouldNotCompute()) 3961 return 1; 3962 3963 // Get the trip count from the BE count by adding 1. 3964 const SCEV *TCMul = getAddExpr(ExitCount, 3965 getConstant(ExitCount->getType(), 1)); 3966 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt 3967 // to factor simple cases. 3968 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) 3969 TCMul = Mul->getOperand(0); 3970 3971 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); 3972 if (!MulC) 3973 return 1; 3974 3975 ConstantInt *Result = MulC->getValue(); 3976 3977 // Guard against huge trip counts. 3978 if (!Result || Result->getValue().getActiveBits() > 32) 3979 return 1; 3980 3981 return (unsigned)Result->getZExtValue(); 3982 } 3983 3984 // getExitCount - Get the expression for the number of loop iterations for which 3985 // this loop is guaranteed not to exit via ExitintBlock. Otherwise return 3986 // SCEVCouldNotCompute. 3987 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { 3988 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 3989 } 3990 3991 /// getBackedgeTakenCount - If the specified loop has a predictable 3992 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute 3993 /// object. The backedge-taken count is the number of times the loop header 3994 /// will be branched to from within the loop. This is one less than the 3995 /// trip count of the loop, since it doesn't count the first iteration, 3996 /// when the header is branched to from outside the loop. 3997 /// 3998 /// Note that it is not valid to call this method on a loop without a 3999 /// loop-invariant backedge-taken count (see 4000 /// hasLoopInvariantBackedgeTakenCount). 4001 /// 4002 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 4003 return getBackedgeTakenInfo(L).getExact(this); 4004 } 4005 4006 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except 4007 /// return the least SCEV value that is known never to be less than the 4008 /// actual backedge taken count. 4009 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 4010 return getBackedgeTakenInfo(L).getMax(this); 4011 } 4012 4013 /// PushLoopPHIs - Push PHI nodes in the header of the given loop 4014 /// onto the given Worklist. 4015 static void 4016 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 4017 BasicBlock *Header = L->getHeader(); 4018 4019 // Push all Loop-header PHIs onto the Worklist stack. 4020 for (BasicBlock::iterator I = Header->begin(); 4021 PHINode *PN = dyn_cast<PHINode>(I); ++I) 4022 Worklist.push_back(PN); 4023 } 4024 4025 const ScalarEvolution::BackedgeTakenInfo & 4026 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 4027 // Initially insert an invalid entry for this loop. If the insertion 4028 // succeeds, proceed to actually compute a backedge-taken count and 4029 // update the value. The temporary CouldNotCompute value tells SCEV 4030 // code elsewhere that it shouldn't attempt to request a new 4031 // backedge-taken count, which could result in infinite recursion. 4032 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 4033 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo())); 4034 if (!Pair.second) 4035 return Pair.first->second; 4036 4037 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it 4038 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 4039 // must be cleared in this scope. 4040 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L); 4041 4042 if (Result.getExact(this) != getCouldNotCompute()) { 4043 assert(isLoopInvariant(Result.getExact(this), L) && 4044 isLoopInvariant(Result.getMax(this), L) && 4045 "Computed backedge-taken count isn't loop invariant for loop!"); 4046 ++NumTripCountsComputed; 4047 } 4048 else if (Result.getMax(this) == getCouldNotCompute() && 4049 isa<PHINode>(L->getHeader()->begin())) { 4050 // Only count loops that have phi nodes as not being computable. 4051 ++NumTripCountsNotComputed; 4052 } 4053 4054 // Now that we know more about the trip count for this loop, forget any 4055 // existing SCEV values for PHI nodes in this loop since they are only 4056 // conservative estimates made without the benefit of trip count 4057 // information. This is similar to the code in forgetLoop, except that 4058 // it handles SCEVUnknown PHI nodes specially. 4059 if (Result.hasAnyInfo()) { 4060 SmallVector<Instruction *, 16> Worklist; 4061 PushLoopPHIs(L, Worklist); 4062 4063 SmallPtrSet<Instruction *, 8> Visited; 4064 while (!Worklist.empty()) { 4065 Instruction *I = Worklist.pop_back_val(); 4066 if (!Visited.insert(I)) continue; 4067 4068 ValueExprMapType::iterator It = 4069 ValueExprMap.find(static_cast<Value *>(I)); 4070 if (It != ValueExprMap.end()) { 4071 const SCEV *Old = It->second; 4072 4073 // SCEVUnknown for a PHI either means that it has an unrecognized 4074 // structure, or it's a PHI that's in the progress of being computed 4075 // by createNodeForPHI. In the former case, additional loop trip 4076 // count information isn't going to change anything. In the later 4077 // case, createNodeForPHI will perform the necessary updates on its 4078 // own when it gets to that point. 4079 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 4080 forgetMemoizedResults(Old); 4081 ValueExprMap.erase(It); 4082 } 4083 if (PHINode *PN = dyn_cast<PHINode>(I)) 4084 ConstantEvolutionLoopExitValue.erase(PN); 4085 } 4086 4087 PushDefUseChildren(I, Worklist); 4088 } 4089 } 4090 4091 // Re-lookup the insert position, since the call to 4092 // ComputeBackedgeTakenCount above could result in a 4093 // recusive call to getBackedgeTakenInfo (on a different 4094 // loop), which would invalidate the iterator computed 4095 // earlier. 4096 return BackedgeTakenCounts.find(L)->second = Result; 4097 } 4098 4099 /// forgetLoop - This method should be called by the client when it has 4100 /// changed a loop in a way that may effect ScalarEvolution's ability to 4101 /// compute a trip count, or if the loop is deleted. 4102 void ScalarEvolution::forgetLoop(const Loop *L) { 4103 // Drop any stored trip count value. 4104 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos = 4105 BackedgeTakenCounts.find(L); 4106 if (BTCPos != BackedgeTakenCounts.end()) { 4107 BTCPos->second.clear(); 4108 BackedgeTakenCounts.erase(BTCPos); 4109 } 4110 4111 // Drop information about expressions based on loop-header PHIs. 4112 SmallVector<Instruction *, 16> Worklist; 4113 PushLoopPHIs(L, Worklist); 4114 4115 SmallPtrSet<Instruction *, 8> Visited; 4116 while (!Worklist.empty()) { 4117 Instruction *I = Worklist.pop_back_val(); 4118 if (!Visited.insert(I)) continue; 4119 4120 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I)); 4121 if (It != ValueExprMap.end()) { 4122 forgetMemoizedResults(It->second); 4123 ValueExprMap.erase(It); 4124 if (PHINode *PN = dyn_cast<PHINode>(I)) 4125 ConstantEvolutionLoopExitValue.erase(PN); 4126 } 4127 4128 PushDefUseChildren(I, Worklist); 4129 } 4130 4131 // Forget all contained loops too, to avoid dangling entries in the 4132 // ValuesAtScopes map. 4133 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 4134 forgetLoop(*I); 4135 } 4136 4137 /// forgetValue - This method should be called by the client when it has 4138 /// changed a value in a way that may effect its value, or which may 4139 /// disconnect it from a def-use chain linking it to a loop. 4140 void ScalarEvolution::forgetValue(Value *V) { 4141 Instruction *I = dyn_cast<Instruction>(V); 4142 if (!I) return; 4143 4144 // Drop information about expressions based on loop-header PHIs. 4145 SmallVector<Instruction *, 16> Worklist; 4146 Worklist.push_back(I); 4147 4148 SmallPtrSet<Instruction *, 8> Visited; 4149 while (!Worklist.empty()) { 4150 I = Worklist.pop_back_val(); 4151 if (!Visited.insert(I)) continue; 4152 4153 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I)); 4154 if (It != ValueExprMap.end()) { 4155 forgetMemoizedResults(It->second); 4156 ValueExprMap.erase(It); 4157 if (PHINode *PN = dyn_cast<PHINode>(I)) 4158 ConstantEvolutionLoopExitValue.erase(PN); 4159 } 4160 4161 PushDefUseChildren(I, Worklist); 4162 } 4163 } 4164 4165 /// getExact - Get the exact loop backedge taken count considering all loop 4166 /// exits. A computable result can only be return for loops with a single exit. 4167 /// Returning the minimum taken count among all exits is incorrect because one 4168 /// of the loop's exit limit's may have been skipped. HowFarToZero assumes that 4169 /// the limit of each loop test is never skipped. This is a valid assumption as 4170 /// long as the loop exits via that test. For precise results, it is the 4171 /// caller's responsibility to specify the relevant loop exit using 4172 /// getExact(ExitingBlock, SE). 4173 const SCEV * 4174 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const { 4175 // If any exits were not computable, the loop is not computable. 4176 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute(); 4177 4178 // We need exactly one computable exit. 4179 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute(); 4180 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info"); 4181 4182 const SCEV *BECount = 0; 4183 for (const ExitNotTakenInfo *ENT = &ExitNotTaken; 4184 ENT != 0; ENT = ENT->getNextExit()) { 4185 4186 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 4187 4188 if (!BECount) 4189 BECount = ENT->ExactNotTaken; 4190 else if (BECount != ENT->ExactNotTaken) 4191 return SE->getCouldNotCompute(); 4192 } 4193 assert(BECount && "Invalid not taken count for loop exit"); 4194 return BECount; 4195 } 4196 4197 /// getExact - Get the exact not taken count for this loop exit. 4198 const SCEV * 4199 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 4200 ScalarEvolution *SE) const { 4201 for (const ExitNotTakenInfo *ENT = &ExitNotTaken; 4202 ENT != 0; ENT = ENT->getNextExit()) { 4203 4204 if (ENT->ExitingBlock == ExitingBlock) 4205 return ENT->ExactNotTaken; 4206 } 4207 return SE->getCouldNotCompute(); 4208 } 4209 4210 /// getMax - Get the max backedge taken count for the loop. 4211 const SCEV * 4212 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 4213 return Max ? Max : SE->getCouldNotCompute(); 4214 } 4215 4216 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 4217 /// computable exit into a persistent ExitNotTakenInfo array. 4218 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 4219 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts, 4220 bool Complete, const SCEV *MaxCount) : Max(MaxCount) { 4221 4222 if (!Complete) 4223 ExitNotTaken.setIncomplete(); 4224 4225 unsigned NumExits = ExitCounts.size(); 4226 if (NumExits == 0) return; 4227 4228 ExitNotTaken.ExitingBlock = ExitCounts[0].first; 4229 ExitNotTaken.ExactNotTaken = ExitCounts[0].second; 4230 if (NumExits == 1) return; 4231 4232 // Handle the rare case of multiple computable exits. 4233 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1]; 4234 4235 ExitNotTakenInfo *PrevENT = &ExitNotTaken; 4236 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) { 4237 PrevENT->setNextExit(ENT); 4238 ENT->ExitingBlock = ExitCounts[i].first; 4239 ENT->ExactNotTaken = ExitCounts[i].second; 4240 } 4241 } 4242 4243 /// clear - Invalidate this result and free the ExitNotTakenInfo array. 4244 void ScalarEvolution::BackedgeTakenInfo::clear() { 4245 ExitNotTaken.ExitingBlock = 0; 4246 ExitNotTaken.ExactNotTaken = 0; 4247 delete[] ExitNotTaken.getNextExit(); 4248 } 4249 4250 /// ComputeBackedgeTakenCount - Compute the number of times the backedge 4251 /// of the specified loop will execute. 4252 ScalarEvolution::BackedgeTakenInfo 4253 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) { 4254 SmallVector<BasicBlock *, 8> ExitingBlocks; 4255 L->getExitingBlocks(ExitingBlocks); 4256 4257 // Examine all exits and pick the most conservative values. 4258 const SCEV *MaxBECount = getCouldNotCompute(); 4259 bool CouldComputeBECount = true; 4260 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts; 4261 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 4262 ExitLimit EL = ComputeExitLimit(L, ExitingBlocks[i]); 4263 if (EL.Exact == getCouldNotCompute()) 4264 // We couldn't compute an exact value for this exit, so 4265 // we won't be able to compute an exact value for the loop. 4266 CouldComputeBECount = false; 4267 else 4268 ExitCounts.push_back(std::make_pair(ExitingBlocks[i], EL.Exact)); 4269 4270 if (MaxBECount == getCouldNotCompute()) 4271 MaxBECount = EL.Max; 4272 else if (EL.Max != getCouldNotCompute()) { 4273 // We cannot take the "min" MaxBECount, because non-unit stride loops may 4274 // skip some loop tests. Taking the max over the exits is sufficiently 4275 // conservative. TODO: We could do better taking into consideration 4276 // that (1) the loop has unit stride (2) the last loop test is 4277 // less-than/greater-than (3) any loop test is less-than/greater-than AND 4278 // falls-through some constant times less then the other tests. 4279 MaxBECount = getUMaxFromMismatchedTypes(MaxBECount, EL.Max); 4280 } 4281 } 4282 4283 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount); 4284 } 4285 4286 /// ComputeExitLimit - Compute the number of times the backedge of the specified 4287 /// loop will execute if it exits via the specified block. 4288 ScalarEvolution::ExitLimit 4289 ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) { 4290 4291 // Okay, we've chosen an exiting block. See what condition causes us to 4292 // exit at this block. 4293 // 4294 // FIXME: we should be able to handle switch instructions (with a single exit) 4295 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 4296 if (ExitBr == 0) return getCouldNotCompute(); 4297 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!"); 4298 4299 // At this point, we know we have a conditional branch that determines whether 4300 // the loop is exited. However, we don't know if the branch is executed each 4301 // time through the loop. If not, then the execution count of the branch will 4302 // not be equal to the trip count of the loop. 4303 // 4304 // Currently we check for this by checking to see if the Exit branch goes to 4305 // the loop header. If so, we know it will always execute the same number of 4306 // times as the loop. We also handle the case where the exit block *is* the 4307 // loop header. This is common for un-rotated loops. 4308 // 4309 // If both of those tests fail, walk up the unique predecessor chain to the 4310 // header, stopping if there is an edge that doesn't exit the loop. If the 4311 // header is reached, the execution count of the branch will be equal to the 4312 // trip count of the loop. 4313 // 4314 // More extensive analysis could be done to handle more cases here. 4315 // 4316 if (ExitBr->getSuccessor(0) != L->getHeader() && 4317 ExitBr->getSuccessor(1) != L->getHeader() && 4318 ExitBr->getParent() != L->getHeader()) { 4319 // The simple checks failed, try climbing the unique predecessor chain 4320 // up to the header. 4321 bool Ok = false; 4322 for (BasicBlock *BB = ExitBr->getParent(); BB; ) { 4323 BasicBlock *Pred = BB->getUniquePredecessor(); 4324 if (!Pred) 4325 return getCouldNotCompute(); 4326 TerminatorInst *PredTerm = Pred->getTerminator(); 4327 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) { 4328 BasicBlock *PredSucc = PredTerm->getSuccessor(i); 4329 if (PredSucc == BB) 4330 continue; 4331 // If the predecessor has a successor that isn't BB and isn't 4332 // outside the loop, assume the worst. 4333 if (L->contains(PredSucc)) 4334 return getCouldNotCompute(); 4335 } 4336 if (Pred == L->getHeader()) { 4337 Ok = true; 4338 break; 4339 } 4340 BB = Pred; 4341 } 4342 if (!Ok) 4343 return getCouldNotCompute(); 4344 } 4345 4346 // Proceed to the next level to examine the exit condition expression. 4347 return ComputeExitLimitFromCond(L, ExitBr->getCondition(), 4348 ExitBr->getSuccessor(0), 4349 ExitBr->getSuccessor(1)); 4350 } 4351 4352 /// ComputeExitLimitFromCond - Compute the number of times the 4353 /// backedge of the specified loop will execute if its exit condition 4354 /// were a conditional branch of ExitCond, TBB, and FBB. 4355 ScalarEvolution::ExitLimit 4356 ScalarEvolution::ComputeExitLimitFromCond(const Loop *L, 4357 Value *ExitCond, 4358 BasicBlock *TBB, 4359 BasicBlock *FBB) { 4360 // Check if the controlling expression for this loop is an And or Or. 4361 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 4362 if (BO->getOpcode() == Instruction::And) { 4363 // Recurse on the operands of the and. 4364 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB); 4365 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB); 4366 const SCEV *BECount = getCouldNotCompute(); 4367 const SCEV *MaxBECount = getCouldNotCompute(); 4368 if (L->contains(TBB)) { 4369 // Both conditions must be true for the loop to continue executing. 4370 // Choose the less conservative count. 4371 if (EL0.Exact == getCouldNotCompute() || 4372 EL1.Exact == getCouldNotCompute()) 4373 BECount = getCouldNotCompute(); 4374 else 4375 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); 4376 if (EL0.Max == getCouldNotCompute()) 4377 MaxBECount = EL1.Max; 4378 else if (EL1.Max == getCouldNotCompute()) 4379 MaxBECount = EL0.Max; 4380 else 4381 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); 4382 } else { 4383 // Both conditions must be true at the same time for the loop to exit. 4384 // For now, be conservative. 4385 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 4386 if (EL0.Max == EL1.Max) 4387 MaxBECount = EL0.Max; 4388 if (EL0.Exact == EL1.Exact) 4389 BECount = EL0.Exact; 4390 } 4391 4392 return ExitLimit(BECount, MaxBECount); 4393 } 4394 if (BO->getOpcode() == Instruction::Or) { 4395 // Recurse on the operands of the or. 4396 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB); 4397 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB); 4398 const SCEV *BECount = getCouldNotCompute(); 4399 const SCEV *MaxBECount = getCouldNotCompute(); 4400 if (L->contains(FBB)) { 4401 // Both conditions must be false for the loop to continue executing. 4402 // Choose the less conservative count. 4403 if (EL0.Exact == getCouldNotCompute() || 4404 EL1.Exact == getCouldNotCompute()) 4405 BECount = getCouldNotCompute(); 4406 else 4407 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); 4408 if (EL0.Max == getCouldNotCompute()) 4409 MaxBECount = EL1.Max; 4410 else if (EL1.Max == getCouldNotCompute()) 4411 MaxBECount = EL0.Max; 4412 else 4413 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); 4414 } else { 4415 // Both conditions must be false at the same time for the loop to exit. 4416 // For now, be conservative. 4417 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 4418 if (EL0.Max == EL1.Max) 4419 MaxBECount = EL0.Max; 4420 if (EL0.Exact == EL1.Exact) 4421 BECount = EL0.Exact; 4422 } 4423 4424 return ExitLimit(BECount, MaxBECount); 4425 } 4426 } 4427 4428 // With an icmp, it may be feasible to compute an exact backedge-taken count. 4429 // Proceed to the next level to examine the icmp. 4430 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) 4431 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB); 4432 4433 // Check for a constant condition. These are normally stripped out by 4434 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 4435 // preserve the CFG and is temporarily leaving constant conditions 4436 // in place. 4437 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 4438 if (L->contains(FBB) == !CI->getZExtValue()) 4439 // The backedge is always taken. 4440 return getCouldNotCompute(); 4441 else 4442 // The backedge is never taken. 4443 return getConstant(CI->getType(), 0); 4444 } 4445 4446 // If it's not an integer or pointer comparison then compute it the hard way. 4447 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 4448 } 4449 4450 /// ComputeExitLimitFromICmp - Compute the number of times the 4451 /// backedge of the specified loop will execute if its exit condition 4452 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB. 4453 ScalarEvolution::ExitLimit 4454 ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L, 4455 ICmpInst *ExitCond, 4456 BasicBlock *TBB, 4457 BasicBlock *FBB) { 4458 4459 // If the condition was exit on true, convert the condition to exit on false 4460 ICmpInst::Predicate Cond; 4461 if (!L->contains(FBB)) 4462 Cond = ExitCond->getPredicate(); 4463 else 4464 Cond = ExitCond->getInversePredicate(); 4465 4466 // Handle common loops like: for (X = "string"; *X; ++X) 4467 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 4468 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 4469 ExitLimit ItCnt = 4470 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 4471 if (ItCnt.hasAnyInfo()) 4472 return ItCnt; 4473 } 4474 4475 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 4476 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 4477 4478 // Try to evaluate any dependencies out of the loop. 4479 LHS = getSCEVAtScope(LHS, L); 4480 RHS = getSCEVAtScope(RHS, L); 4481 4482 // At this point, we would like to compute how many iterations of the 4483 // loop the predicate will return true for these inputs. 4484 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 4485 // If there is a loop-invariant, force it into the RHS. 4486 std::swap(LHS, RHS); 4487 Cond = ICmpInst::getSwappedPredicate(Cond); 4488 } 4489 4490 // Simplify the operands before analyzing them. 4491 (void)SimplifyICmpOperands(Cond, LHS, RHS); 4492 4493 // If we have a comparison of a chrec against a constant, try to use value 4494 // ranges to answer this query. 4495 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 4496 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 4497 if (AddRec->getLoop() == L) { 4498 // Form the constant range. 4499 ConstantRange CompRange( 4500 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue())); 4501 4502 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 4503 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 4504 } 4505 4506 switch (Cond) { 4507 case ICmpInst::ICMP_NE: { // while (X != Y) 4508 // Convert to: while (X-Y != 0) 4509 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L); 4510 if (EL.hasAnyInfo()) return EL; 4511 break; 4512 } 4513 case ICmpInst::ICMP_EQ: { // while (X == Y) 4514 // Convert to: while (X-Y == 0) 4515 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L); 4516 if (EL.hasAnyInfo()) return EL; 4517 break; 4518 } 4519 case ICmpInst::ICMP_SLT: { 4520 ExitLimit EL = HowManyLessThans(LHS, RHS, L, true); 4521 if (EL.hasAnyInfo()) return EL; 4522 break; 4523 } 4524 case ICmpInst::ICMP_SGT: { 4525 ExitLimit EL = HowManyLessThans(getNotSCEV(LHS), 4526 getNotSCEV(RHS), L, true); 4527 if (EL.hasAnyInfo()) return EL; 4528 break; 4529 } 4530 case ICmpInst::ICMP_ULT: { 4531 ExitLimit EL = HowManyLessThans(LHS, RHS, L, false); 4532 if (EL.hasAnyInfo()) return EL; 4533 break; 4534 } 4535 case ICmpInst::ICMP_UGT: { 4536 ExitLimit EL = HowManyLessThans(getNotSCEV(LHS), 4537 getNotSCEV(RHS), L, false); 4538 if (EL.hasAnyInfo()) return EL; 4539 break; 4540 } 4541 default: 4542 #if 0 4543 dbgs() << "ComputeBackedgeTakenCount "; 4544 if (ExitCond->getOperand(0)->getType()->isUnsigned()) 4545 dbgs() << "[unsigned] "; 4546 dbgs() << *LHS << " " 4547 << Instruction::getOpcodeName(Instruction::ICmp) 4548 << " " << *RHS << "\n"; 4549 #endif 4550 break; 4551 } 4552 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 4553 } 4554 4555 static ConstantInt * 4556 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 4557 ScalarEvolution &SE) { 4558 const SCEV *InVal = SE.getConstant(C); 4559 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 4560 assert(isa<SCEVConstant>(Val) && 4561 "Evaluation of SCEV at constant didn't fold correctly?"); 4562 return cast<SCEVConstant>(Val)->getValue(); 4563 } 4564 4565 /// GetAddressedElementFromGlobal - Given a global variable with an initializer 4566 /// and a GEP expression (missing the pointer index) indexing into it, return 4567 /// the addressed element of the initializer or null if the index expression is 4568 /// invalid. 4569 static Constant * 4570 GetAddressedElementFromGlobal(GlobalVariable *GV, 4571 const std::vector<ConstantInt*> &Indices) { 4572 Constant *Init = GV->getInitializer(); 4573 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 4574 uint64_t Idx = Indices[i]->getZExtValue(); 4575 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { 4576 assert(Idx < CS->getNumOperands() && "Bad struct index!"); 4577 Init = cast<Constant>(CS->getOperand(Idx)); 4578 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { 4579 if (Idx >= CA->getNumOperands()) return 0; // Bogus program 4580 Init = cast<Constant>(CA->getOperand(Idx)); 4581 } else if (isa<ConstantAggregateZero>(Init)) { 4582 if (StructType *STy = dyn_cast<StructType>(Init->getType())) { 4583 assert(Idx < STy->getNumElements() && "Bad struct index!"); 4584 Init = Constant::getNullValue(STy->getElementType(Idx)); 4585 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) { 4586 if (Idx >= ATy->getNumElements()) return 0; // Bogus program 4587 Init = Constant::getNullValue(ATy->getElementType()); 4588 } else { 4589 llvm_unreachable("Unknown constant aggregate type!"); 4590 } 4591 return 0; 4592 } else { 4593 return 0; // Unknown initializer type 4594 } 4595 } 4596 return Init; 4597 } 4598 4599 /// ComputeLoadConstantCompareExitLimit - Given an exit condition of 4600 /// 'icmp op load X, cst', try to see if we can compute the backedge 4601 /// execution count. 4602 ScalarEvolution::ExitLimit 4603 ScalarEvolution::ComputeLoadConstantCompareExitLimit( 4604 LoadInst *LI, 4605 Constant *RHS, 4606 const Loop *L, 4607 ICmpInst::Predicate predicate) { 4608 4609 if (LI->isVolatile()) return getCouldNotCompute(); 4610 4611 // Check to see if the loaded pointer is a getelementptr of a global. 4612 // TODO: Use SCEV instead of manually grubbing with GEPs. 4613 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 4614 if (!GEP) return getCouldNotCompute(); 4615 4616 // Make sure that it is really a constant global we are gepping, with an 4617 // initializer, and make sure the first IDX is really 0. 4618 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 4619 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 4620 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 4621 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 4622 return getCouldNotCompute(); 4623 4624 // Okay, we allow one non-constant index into the GEP instruction. 4625 Value *VarIdx = 0; 4626 std::vector<ConstantInt*> Indexes; 4627 unsigned VarIdxNum = 0; 4628 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 4629 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 4630 Indexes.push_back(CI); 4631 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 4632 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 4633 VarIdx = GEP->getOperand(i); 4634 VarIdxNum = i-2; 4635 Indexes.push_back(0); 4636 } 4637 4638 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 4639 // Check to see if X is a loop variant variable value now. 4640 const SCEV *Idx = getSCEV(VarIdx); 4641 Idx = getSCEVAtScope(Idx, L); 4642 4643 // We can only recognize very limited forms of loop index expressions, in 4644 // particular, only affine AddRec's like {C1,+,C2}. 4645 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 4646 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 4647 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 4648 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 4649 return getCouldNotCompute(); 4650 4651 unsigned MaxSteps = MaxBruteForceIterations; 4652 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 4653 ConstantInt *ItCst = ConstantInt::get( 4654 cast<IntegerType>(IdxExpr->getType()), IterationNum); 4655 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 4656 4657 // Form the GEP offset. 4658 Indexes[VarIdxNum] = Val; 4659 4660 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes); 4661 if (Result == 0) break; // Cannot compute! 4662 4663 // Evaluate the condition for this iteration. 4664 Result = ConstantExpr::getICmp(predicate, Result, RHS); 4665 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 4666 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 4667 #if 0 4668 dbgs() << "\n***\n*** Computed loop count " << *ItCst 4669 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() 4670 << "***\n"; 4671 #endif 4672 ++NumArrayLenItCounts; 4673 return getConstant(ItCst); // Found terminating iteration! 4674 } 4675 } 4676 return getCouldNotCompute(); 4677 } 4678 4679 4680 /// CanConstantFold - Return true if we can constant fold an instruction of the 4681 /// specified type, assuming that all operands were constants. 4682 static bool CanConstantFold(const Instruction *I) { 4683 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 4684 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 4685 isa<LoadInst>(I)) 4686 return true; 4687 4688 if (const CallInst *CI = dyn_cast<CallInst>(I)) 4689 if (const Function *F = CI->getCalledFunction()) 4690 return canConstantFoldCallTo(F); 4691 return false; 4692 } 4693 4694 /// Determine whether this instruction can constant evolve within this loop 4695 /// assuming its operands can all constant evolve. 4696 static bool canConstantEvolve(Instruction *I, const Loop *L) { 4697 // An instruction outside of the loop can't be derived from a loop PHI. 4698 if (!L->contains(I)) return false; 4699 4700 if (isa<PHINode>(I)) { 4701 if (L->getHeader() == I->getParent()) 4702 return true; 4703 else 4704 // We don't currently keep track of the control flow needed to evaluate 4705 // PHIs, so we cannot handle PHIs inside of loops. 4706 return false; 4707 } 4708 4709 // If we won't be able to constant fold this expression even if the operands 4710 // are constants, bail early. 4711 return CanConstantFold(I); 4712 } 4713 4714 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 4715 /// recursing through each instruction operand until reaching a loop header phi. 4716 static PHINode * 4717 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 4718 DenseMap<Instruction *, PHINode *> &PHIMap) { 4719 4720 // Otherwise, we can evaluate this instruction if all of its operands are 4721 // constant or derived from a PHI node themselves. 4722 PHINode *PHI = 0; 4723 for (Instruction::op_iterator OpI = UseInst->op_begin(), 4724 OpE = UseInst->op_end(); OpI != OpE; ++OpI) { 4725 4726 if (isa<Constant>(*OpI)) continue; 4727 4728 Instruction *OpInst = dyn_cast<Instruction>(*OpI); 4729 if (!OpInst || !canConstantEvolve(OpInst, L)) return 0; 4730 4731 PHINode *P = dyn_cast<PHINode>(OpInst); 4732 if (!P) 4733 // If this operand is already visited, reuse the prior result. 4734 // We may have P != PHI if this is the deepest point at which the 4735 // inconsistent paths meet. 4736 P = PHIMap.lookup(OpInst); 4737 if (!P) { 4738 // Recurse and memoize the results, whether a phi is found or not. 4739 // This recursive call invalidates pointers into PHIMap. 4740 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); 4741 PHIMap[OpInst] = P; 4742 } 4743 if (P == 0) return 0; // Not evolving from PHI 4744 if (PHI && PHI != P) return 0; // Evolving from multiple different PHIs. 4745 PHI = P; 4746 } 4747 // This is a expression evolving from a constant PHI! 4748 return PHI; 4749 } 4750 4751 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 4752 /// in the loop that V is derived from. We allow arbitrary operations along the 4753 /// way, but the operands of an operation must either be constants or a value 4754 /// derived from a constant PHI. If this expression does not fit with these 4755 /// constraints, return null. 4756 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 4757 Instruction *I = dyn_cast<Instruction>(V); 4758 if (I == 0 || !canConstantEvolve(I, L)) return 0; 4759 4760 if (PHINode *PN = dyn_cast<PHINode>(I)) { 4761 return PN; 4762 } 4763 4764 // Record non-constant instructions contained by the loop. 4765 DenseMap<Instruction *, PHINode *> PHIMap; 4766 return getConstantEvolvingPHIOperands(I, L, PHIMap); 4767 } 4768 4769 /// EvaluateExpression - Given an expression that passes the 4770 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 4771 /// in the loop has the value PHIVal. If we can't fold this expression for some 4772 /// reason, return null. 4773 static Constant *EvaluateExpression(Value *V, const Loop *L, 4774 DenseMap<Instruction *, Constant *> &Vals, 4775 const TargetData *TD) { 4776 // Convenient constant check, but redundant for recursive calls. 4777 if (Constant *C = dyn_cast<Constant>(V)) return C; 4778 Instruction *I = dyn_cast<Instruction>(V); 4779 if (!I) return 0; 4780 4781 if (Constant *C = Vals.lookup(I)) return C; 4782 4783 // An instruction inside the loop depends on a value outside the loop that we 4784 // weren't given a mapping for, or a value such as a call inside the loop. 4785 if (!canConstantEvolve(I, L)) return 0; 4786 4787 // An unmapped PHI can be due to a branch or another loop inside this loop, 4788 // or due to this not being the initial iteration through a loop where we 4789 // couldn't compute the evolution of this particular PHI last time. 4790 if (isa<PHINode>(I)) return 0; 4791 4792 std::vector<Constant*> Operands(I->getNumOperands()); 4793 4794 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 4795 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 4796 if (!Operand) { 4797 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 4798 if (!Operands[i]) return 0; 4799 continue; 4800 } 4801 Constant *C = EvaluateExpression(Operand, L, Vals, TD); 4802 Vals[Operand] = C; 4803 if (!C) return 0; 4804 Operands[i] = C; 4805 } 4806 4807 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 4808 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 4809 Operands[1], TD); 4810 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 4811 if (!LI->isVolatile()) 4812 return ConstantFoldLoadFromConstPtr(Operands[0], TD); 4813 } 4814 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, TD); 4815 } 4816 4817 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 4818 /// in the header of its containing loop, we know the loop executes a 4819 /// constant number of times, and the PHI node is just a recurrence 4820 /// involving constants, fold it. 4821 Constant * 4822 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 4823 const APInt &BEs, 4824 const Loop *L) { 4825 DenseMap<PHINode*, Constant*>::const_iterator I = 4826 ConstantEvolutionLoopExitValue.find(PN); 4827 if (I != ConstantEvolutionLoopExitValue.end()) 4828 return I->second; 4829 4830 if (BEs.ugt(MaxBruteForceIterations)) 4831 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it. 4832 4833 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 4834 4835 DenseMap<Instruction *, Constant *> CurrentIterVals; 4836 BasicBlock *Header = L->getHeader(); 4837 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 4838 4839 // Since the loop is canonicalized, the PHI node must have two entries. One 4840 // entry must be a constant (coming in from outside of the loop), and the 4841 // second must be derived from the same PHI. 4842 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 4843 PHINode *PHI = 0; 4844 for (BasicBlock::iterator I = Header->begin(); 4845 (PHI = dyn_cast<PHINode>(I)); ++I) { 4846 Constant *StartCST = 4847 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge)); 4848 if (StartCST == 0) continue; 4849 CurrentIterVals[PHI] = StartCST; 4850 } 4851 if (!CurrentIterVals.count(PN)) 4852 return RetVal = 0; 4853 4854 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 4855 4856 // Execute the loop symbolically to determine the exit value. 4857 if (BEs.getActiveBits() >= 32) 4858 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it! 4859 4860 unsigned NumIterations = BEs.getZExtValue(); // must be in range 4861 unsigned IterationNum = 0; 4862 for (; ; ++IterationNum) { 4863 if (IterationNum == NumIterations) 4864 return RetVal = CurrentIterVals[PN]; // Got exit value! 4865 4866 // Compute the value of the PHIs for the next iteration. 4867 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 4868 DenseMap<Instruction *, Constant *> NextIterVals; 4869 Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, TD); 4870 if (NextPHI == 0) 4871 return 0; // Couldn't evaluate! 4872 NextIterVals[PN] = NextPHI; 4873 4874 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 4875 4876 // Also evaluate the other PHI nodes. However, we don't get to stop if we 4877 // cease to be able to evaluate one of them or if they stop evolving, 4878 // because that doesn't necessarily prevent us from computing PN. 4879 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 4880 for (DenseMap<Instruction *, Constant *>::const_iterator 4881 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){ 4882 PHINode *PHI = dyn_cast<PHINode>(I->first); 4883 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 4884 PHIsToCompute.push_back(std::make_pair(PHI, I->second)); 4885 } 4886 // We use two distinct loops because EvaluateExpression may invalidate any 4887 // iterators into CurrentIterVals. 4888 for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator 4889 I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) { 4890 PHINode *PHI = I->first; 4891 Constant *&NextPHI = NextIterVals[PHI]; 4892 if (!NextPHI) { // Not already computed. 4893 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge); 4894 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, TD); 4895 } 4896 if (NextPHI != I->second) 4897 StoppedEvolving = false; 4898 } 4899 4900 // If all entries in CurrentIterVals == NextIterVals then we can stop 4901 // iterating, the loop can't continue to change. 4902 if (StoppedEvolving) 4903 return RetVal = CurrentIterVals[PN]; 4904 4905 CurrentIterVals.swap(NextIterVals); 4906 } 4907 } 4908 4909 /// ComputeExitCountExhaustively - If the loop is known to execute a 4910 /// constant number of times (the condition evolves only from constants), 4911 /// try to evaluate a few iterations of the loop until we get the exit 4912 /// condition gets a value of ExitWhen (true or false). If we cannot 4913 /// evaluate the trip count of the loop, return getCouldNotCompute(). 4914 const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L, 4915 Value *Cond, 4916 bool ExitWhen) { 4917 PHINode *PN = getConstantEvolvingPHI(Cond, L); 4918 if (PN == 0) return getCouldNotCompute(); 4919 4920 // If the loop is canonicalized, the PHI will have exactly two entries. 4921 // That's the only form we support here. 4922 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 4923 4924 DenseMap<Instruction *, Constant *> CurrentIterVals; 4925 BasicBlock *Header = L->getHeader(); 4926 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 4927 4928 // One entry must be a constant (coming in from outside of the loop), and the 4929 // second must be derived from the same PHI. 4930 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 4931 PHINode *PHI = 0; 4932 for (BasicBlock::iterator I = Header->begin(); 4933 (PHI = dyn_cast<PHINode>(I)); ++I) { 4934 Constant *StartCST = 4935 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge)); 4936 if (StartCST == 0) continue; 4937 CurrentIterVals[PHI] = StartCST; 4938 } 4939 if (!CurrentIterVals.count(PN)) 4940 return getCouldNotCompute(); 4941 4942 // Okay, we find a PHI node that defines the trip count of this loop. Execute 4943 // the loop symbolically to determine when the condition gets a value of 4944 // "ExitWhen". 4945 4946 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 4947 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 4948 ConstantInt *CondVal = 4949 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, 4950 CurrentIterVals, TD)); 4951 4952 // Couldn't symbolically evaluate. 4953 if (!CondVal) return getCouldNotCompute(); 4954 4955 if (CondVal->getValue() == uint64_t(ExitWhen)) { 4956 ++NumBruteForceTripCountsComputed; 4957 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 4958 } 4959 4960 // Update all the PHI nodes for the next iteration. 4961 DenseMap<Instruction *, Constant *> NextIterVals; 4962 4963 // Create a list of which PHIs we need to compute. We want to do this before 4964 // calling EvaluateExpression on them because that may invalidate iterators 4965 // into CurrentIterVals. 4966 SmallVector<PHINode *, 8> PHIsToCompute; 4967 for (DenseMap<Instruction *, Constant *>::const_iterator 4968 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){ 4969 PHINode *PHI = dyn_cast<PHINode>(I->first); 4970 if (!PHI || PHI->getParent() != Header) continue; 4971 PHIsToCompute.push_back(PHI); 4972 } 4973 for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(), 4974 E = PHIsToCompute.end(); I != E; ++I) { 4975 PHINode *PHI = *I; 4976 Constant *&NextPHI = NextIterVals[PHI]; 4977 if (NextPHI) continue; // Already computed! 4978 4979 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge); 4980 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, TD); 4981 } 4982 CurrentIterVals.swap(NextIterVals); 4983 } 4984 4985 // Too many iterations were needed to evaluate. 4986 return getCouldNotCompute(); 4987 } 4988 4989 /// getSCEVAtScope - Return a SCEV expression for the specified value 4990 /// at the specified scope in the program. The L value specifies a loop 4991 /// nest to evaluate the expression at, where null is the top-level or a 4992 /// specified loop is immediately inside of the loop. 4993 /// 4994 /// This method can be used to compute the exit value for a variable defined 4995 /// in a loop by querying what the value will hold in the parent loop. 4996 /// 4997 /// In the case that a relevant loop exit value cannot be computed, the 4998 /// original value V is returned. 4999 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 5000 // Check to see if we've folded this expression at this loop before. 5001 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V]; 5002 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair = 5003 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0))); 5004 if (!Pair.second) 5005 return Pair.first->second ? Pair.first->second : V; 5006 5007 // Otherwise compute it. 5008 const SCEV *C = computeSCEVAtScope(V, L); 5009 ValuesAtScopes[V][L] = C; 5010 return C; 5011 } 5012 5013 /// This builds up a Constant using the ConstantExpr interface. That way, we 5014 /// will return Constants for objects which aren't represented by a 5015 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 5016 /// Returns NULL if the SCEV isn't representable as a Constant. 5017 static Constant *BuildConstantFromSCEV(const SCEV *V) { 5018 switch (V->getSCEVType()) { 5019 default: // TODO: smax, umax. 5020 case scCouldNotCompute: 5021 case scAddRecExpr: 5022 break; 5023 case scConstant: 5024 return cast<SCEVConstant>(V)->getValue(); 5025 case scUnknown: 5026 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 5027 case scSignExtend: { 5028 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 5029 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 5030 return ConstantExpr::getSExt(CastOp, SS->getType()); 5031 break; 5032 } 5033 case scZeroExtend: { 5034 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 5035 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 5036 return ConstantExpr::getZExt(CastOp, SZ->getType()); 5037 break; 5038 } 5039 case scTruncate: { 5040 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 5041 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 5042 return ConstantExpr::getTrunc(CastOp, ST->getType()); 5043 break; 5044 } 5045 case scAddExpr: { 5046 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 5047 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 5048 if (C->getType()->isPointerTy()) 5049 C = ConstantExpr::getBitCast(C, Type::getInt8PtrTy(C->getContext())); 5050 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 5051 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 5052 if (!C2) return 0; 5053 5054 // First pointer! 5055 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 5056 std::swap(C, C2); 5057 // The offsets have been converted to bytes. We can add bytes to an 5058 // i8* by GEP with the byte count in the first index. 5059 C = ConstantExpr::getBitCast(C,Type::getInt8PtrTy(C->getContext())); 5060 } 5061 5062 // Don't bother trying to sum two pointers. We probably can't 5063 // statically compute a load that results from it anyway. 5064 if (C2->getType()->isPointerTy()) 5065 return 0; 5066 5067 if (C->getType()->isPointerTy()) { 5068 if (cast<PointerType>(C->getType())->getElementType()->isStructTy()) 5069 C2 = ConstantExpr::getIntegerCast( 5070 C2, Type::getInt32Ty(C->getContext()), true); 5071 C = ConstantExpr::getGetElementPtr(C, C2); 5072 } else 5073 C = ConstantExpr::getAdd(C, C2); 5074 } 5075 return C; 5076 } 5077 break; 5078 } 5079 case scMulExpr: { 5080 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 5081 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 5082 // Don't bother with pointers at all. 5083 if (C->getType()->isPointerTy()) return 0; 5084 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 5085 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 5086 if (!C2 || C2->getType()->isPointerTy()) return 0; 5087 C = ConstantExpr::getMul(C, C2); 5088 } 5089 return C; 5090 } 5091 break; 5092 } 5093 case scUDivExpr: { 5094 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 5095 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 5096 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 5097 if (LHS->getType() == RHS->getType()) 5098 return ConstantExpr::getUDiv(LHS, RHS); 5099 break; 5100 } 5101 } 5102 return 0; 5103 } 5104 5105 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 5106 if (isa<SCEVConstant>(V)) return V; 5107 5108 // If this instruction is evolved from a constant-evolving PHI, compute the 5109 // exit value from the loop without using SCEVs. 5110 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 5111 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 5112 const Loop *LI = (*this->LI)[I->getParent()]; 5113 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 5114 if (PHINode *PN = dyn_cast<PHINode>(I)) 5115 if (PN->getParent() == LI->getHeader()) { 5116 // Okay, there is no closed form solution for the PHI node. Check 5117 // to see if the loop that contains it has a known backedge-taken 5118 // count. If so, we may be able to force computation of the exit 5119 // value. 5120 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 5121 if (const SCEVConstant *BTCC = 5122 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 5123 // Okay, we know how many times the containing loop executes. If 5124 // this is a constant evolving PHI node, get the final value at 5125 // the specified iteration number. 5126 Constant *RV = getConstantEvolutionLoopExitValue(PN, 5127 BTCC->getValue()->getValue(), 5128 LI); 5129 if (RV) return getSCEV(RV); 5130 } 5131 } 5132 5133 // Okay, this is an expression that we cannot symbolically evaluate 5134 // into a SCEV. Check to see if it's possible to symbolically evaluate 5135 // the arguments into constants, and if so, try to constant propagate the 5136 // result. This is particularly useful for computing loop exit values. 5137 if (CanConstantFold(I)) { 5138 SmallVector<Constant *, 4> Operands; 5139 bool MadeImprovement = false; 5140 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 5141 Value *Op = I->getOperand(i); 5142 if (Constant *C = dyn_cast<Constant>(Op)) { 5143 Operands.push_back(C); 5144 continue; 5145 } 5146 5147 // If any of the operands is non-constant and if they are 5148 // non-integer and non-pointer, don't even try to analyze them 5149 // with scev techniques. 5150 if (!isSCEVable(Op->getType())) 5151 return V; 5152 5153 const SCEV *OrigV = getSCEV(Op); 5154 const SCEV *OpV = getSCEVAtScope(OrigV, L); 5155 MadeImprovement |= OrigV != OpV; 5156 5157 Constant *C = BuildConstantFromSCEV(OpV); 5158 if (!C) return V; 5159 if (C->getType() != Op->getType()) 5160 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 5161 Op->getType(), 5162 false), 5163 C, Op->getType()); 5164 Operands.push_back(C); 5165 } 5166 5167 // Check to see if getSCEVAtScope actually made an improvement. 5168 if (MadeImprovement) { 5169 Constant *C = 0; 5170 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 5171 C = ConstantFoldCompareInstOperands(CI->getPredicate(), 5172 Operands[0], Operands[1], TD); 5173 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 5174 if (!LI->isVolatile()) 5175 C = ConstantFoldLoadFromConstPtr(Operands[0], TD); 5176 } else 5177 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(), 5178 Operands, TD); 5179 if (!C) return V; 5180 return getSCEV(C); 5181 } 5182 } 5183 } 5184 5185 // This is some other type of SCEVUnknown, just return it. 5186 return V; 5187 } 5188 5189 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 5190 // Avoid performing the look-up in the common case where the specified 5191 // expression has no loop-variant portions. 5192 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 5193 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 5194 if (OpAtScope != Comm->getOperand(i)) { 5195 // Okay, at least one of these operands is loop variant but might be 5196 // foldable. Build a new instance of the folded commutative expression. 5197 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 5198 Comm->op_begin()+i); 5199 NewOps.push_back(OpAtScope); 5200 5201 for (++i; i != e; ++i) { 5202 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 5203 NewOps.push_back(OpAtScope); 5204 } 5205 if (isa<SCEVAddExpr>(Comm)) 5206 return getAddExpr(NewOps); 5207 if (isa<SCEVMulExpr>(Comm)) 5208 return getMulExpr(NewOps); 5209 if (isa<SCEVSMaxExpr>(Comm)) 5210 return getSMaxExpr(NewOps); 5211 if (isa<SCEVUMaxExpr>(Comm)) 5212 return getUMaxExpr(NewOps); 5213 llvm_unreachable("Unknown commutative SCEV type!"); 5214 } 5215 } 5216 // If we got here, all operands are loop invariant. 5217 return Comm; 5218 } 5219 5220 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 5221 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 5222 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 5223 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 5224 return Div; // must be loop invariant 5225 return getUDivExpr(LHS, RHS); 5226 } 5227 5228 // If this is a loop recurrence for a loop that does not contain L, then we 5229 // are dealing with the final value computed by the loop. 5230 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 5231 // First, attempt to evaluate each operand. 5232 // Avoid performing the look-up in the common case where the specified 5233 // expression has no loop-variant portions. 5234 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5235 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 5236 if (OpAtScope == AddRec->getOperand(i)) 5237 continue; 5238 5239 // Okay, at least one of these operands is loop variant but might be 5240 // foldable. Build a new instance of the folded commutative expression. 5241 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 5242 AddRec->op_begin()+i); 5243 NewOps.push_back(OpAtScope); 5244 for (++i; i != e; ++i) 5245 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 5246 5247 const SCEV *FoldedRec = 5248 getAddRecExpr(NewOps, AddRec->getLoop(), 5249 AddRec->getNoWrapFlags(SCEV::FlagNW)); 5250 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 5251 // The addrec may be folded to a nonrecurrence, for example, if the 5252 // induction variable is multiplied by zero after constant folding. Go 5253 // ahead and return the folded value. 5254 if (!AddRec) 5255 return FoldedRec; 5256 break; 5257 } 5258 5259 // If the scope is outside the addrec's loop, evaluate it by using the 5260 // loop exit value of the addrec. 5261 if (!AddRec->getLoop()->contains(L)) { 5262 // To evaluate this recurrence, we need to know how many times the AddRec 5263 // loop iterates. Compute this now. 5264 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 5265 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 5266 5267 // Then, evaluate the AddRec. 5268 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 5269 } 5270 5271 return AddRec; 5272 } 5273 5274 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 5275 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 5276 if (Op == Cast->getOperand()) 5277 return Cast; // must be loop invariant 5278 return getZeroExtendExpr(Op, Cast->getType()); 5279 } 5280 5281 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 5282 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 5283 if (Op == Cast->getOperand()) 5284 return Cast; // must be loop invariant 5285 return getSignExtendExpr(Op, Cast->getType()); 5286 } 5287 5288 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 5289 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 5290 if (Op == Cast->getOperand()) 5291 return Cast; // must be loop invariant 5292 return getTruncateExpr(Op, Cast->getType()); 5293 } 5294 5295 llvm_unreachable("Unknown SCEV type!"); 5296 return 0; 5297 } 5298 5299 /// getSCEVAtScope - This is a convenience function which does 5300 /// getSCEVAtScope(getSCEV(V), L). 5301 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 5302 return getSCEVAtScope(getSCEV(V), L); 5303 } 5304 5305 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the 5306 /// following equation: 5307 /// 5308 /// A * X = B (mod N) 5309 /// 5310 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 5311 /// A and B isn't important. 5312 /// 5313 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 5314 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 5315 ScalarEvolution &SE) { 5316 uint32_t BW = A.getBitWidth(); 5317 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 5318 assert(A != 0 && "A must be non-zero."); 5319 5320 // 1. D = gcd(A, N) 5321 // 5322 // The gcd of A and N may have only one prime factor: 2. The number of 5323 // trailing zeros in A is its multiplicity 5324 uint32_t Mult2 = A.countTrailingZeros(); 5325 // D = 2^Mult2 5326 5327 // 2. Check if B is divisible by D. 5328 // 5329 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 5330 // is not less than multiplicity of this prime factor for D. 5331 if (B.countTrailingZeros() < Mult2) 5332 return SE.getCouldNotCompute(); 5333 5334 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 5335 // modulo (N / D). 5336 // 5337 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 5338 // bit width during computations. 5339 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 5340 APInt Mod(BW + 1, 0); 5341 Mod.setBit(BW - Mult2); // Mod = N / D 5342 APInt I = AD.multiplicativeInverse(Mod); 5343 5344 // 4. Compute the minimum unsigned root of the equation: 5345 // I * (B / D) mod (N / D) 5346 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 5347 5348 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 5349 // bits. 5350 return SE.getConstant(Result.trunc(BW)); 5351 } 5352 5353 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the 5354 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which 5355 /// might be the same) or two SCEVCouldNotCompute objects. 5356 /// 5357 static std::pair<const SCEV *,const SCEV *> 5358 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 5359 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 5360 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 5361 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 5362 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 5363 5364 // We currently can only solve this if the coefficients are constants. 5365 if (!LC || !MC || !NC) { 5366 const SCEV *CNC = SE.getCouldNotCompute(); 5367 return std::make_pair(CNC, CNC); 5368 } 5369 5370 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth(); 5371 const APInt &L = LC->getValue()->getValue(); 5372 const APInt &M = MC->getValue()->getValue(); 5373 const APInt &N = NC->getValue()->getValue(); 5374 APInt Two(BitWidth, 2); 5375 APInt Four(BitWidth, 4); 5376 5377 { 5378 using namespace APIntOps; 5379 const APInt& C = L; 5380 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 5381 // The B coefficient is M-N/2 5382 APInt B(M); 5383 B -= sdiv(N,Two); 5384 5385 // The A coefficient is N/2 5386 APInt A(N.sdiv(Two)); 5387 5388 // Compute the B^2-4ac term. 5389 APInt SqrtTerm(B); 5390 SqrtTerm *= B; 5391 SqrtTerm -= Four * (A * C); 5392 5393 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 5394 // integer value or else APInt::sqrt() will assert. 5395 APInt SqrtVal(SqrtTerm.sqrt()); 5396 5397 // Compute the two solutions for the quadratic formula. 5398 // The divisions must be performed as signed divisions. 5399 APInt NegB(-B); 5400 APInt TwoA(A << 1); 5401 if (TwoA.isMinValue()) { 5402 const SCEV *CNC = SE.getCouldNotCompute(); 5403 return std::make_pair(CNC, CNC); 5404 } 5405 5406 LLVMContext &Context = SE.getContext(); 5407 5408 ConstantInt *Solution1 = 5409 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 5410 ConstantInt *Solution2 = 5411 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 5412 5413 return std::make_pair(SE.getConstant(Solution1), 5414 SE.getConstant(Solution2)); 5415 } // end APIntOps namespace 5416 } 5417 5418 /// HowFarToZero - Return the number of times a backedge comparing the specified 5419 /// value to zero will execute. If not computable, return CouldNotCompute. 5420 /// 5421 /// This is only used for loops with a "x != y" exit test. The exit condition is 5422 /// now expressed as a single expression, V = x-y. So the exit test is 5423 /// effectively V != 0. We know and take advantage of the fact that this 5424 /// expression only being used in a comparison by zero context. 5425 ScalarEvolution::ExitLimit 5426 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) { 5427 // If the value is a constant 5428 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 5429 // If the value is already zero, the branch will execute zero times. 5430 if (C->getValue()->isZero()) return C; 5431 return getCouldNotCompute(); // Otherwise it will loop infinitely. 5432 } 5433 5434 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 5435 if (!AddRec || AddRec->getLoop() != L) 5436 return getCouldNotCompute(); 5437 5438 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 5439 // the quadratic equation to solve it. 5440 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 5441 std::pair<const SCEV *,const SCEV *> Roots = 5442 SolveQuadraticEquation(AddRec, *this); 5443 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 5444 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 5445 if (R1 && R2) { 5446 #if 0 5447 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1 5448 << " sol#2: " << *R2 << "\n"; 5449 #endif 5450 // Pick the smallest positive root value. 5451 if (ConstantInt *CB = 5452 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT, 5453 R1->getValue(), 5454 R2->getValue()))) { 5455 if (CB->getZExtValue() == false) 5456 std::swap(R1, R2); // R1 is the minimum root now. 5457 5458 // We can only use this value if the chrec ends up with an exact zero 5459 // value at this index. When solving for "X*X != 5", for example, we 5460 // should not accept a root of 2. 5461 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 5462 if (Val->isZero()) 5463 return R1; // We found a quadratic root! 5464 } 5465 } 5466 return getCouldNotCompute(); 5467 } 5468 5469 // Otherwise we can only handle this if it is affine. 5470 if (!AddRec->isAffine()) 5471 return getCouldNotCompute(); 5472 5473 // If this is an affine expression, the execution count of this branch is 5474 // the minimum unsigned root of the following equation: 5475 // 5476 // Start + Step*N = 0 (mod 2^BW) 5477 // 5478 // equivalent to: 5479 // 5480 // Step*N = -Start (mod 2^BW) 5481 // 5482 // where BW is the common bit width of Start and Step. 5483 5484 // Get the initial value for the loop. 5485 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 5486 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 5487 5488 // For now we handle only constant steps. 5489 // 5490 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 5491 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 5492 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 5493 // We have not yet seen any such cases. 5494 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 5495 if (StepC == 0) 5496 return getCouldNotCompute(); 5497 5498 // For positive steps (counting up until unsigned overflow): 5499 // N = -Start/Step (as unsigned) 5500 // For negative steps (counting down to zero): 5501 // N = Start/-Step 5502 // First compute the unsigned distance from zero in the direction of Step. 5503 bool CountDown = StepC->getValue()->getValue().isNegative(); 5504 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 5505 5506 // Handle unitary steps, which cannot wraparound. 5507 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 5508 // N = Distance (as unsigned) 5509 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 5510 ConstantRange CR = getUnsignedRange(Start); 5511 const SCEV *MaxBECount; 5512 if (!CountDown && CR.getUnsignedMin().isMinValue()) 5513 // When counting up, the worst starting value is 1, not 0. 5514 MaxBECount = CR.getUnsignedMax().isMinValue() 5515 ? getConstant(APInt::getMinValue(CR.getBitWidth())) 5516 : getConstant(APInt::getMaxValue(CR.getBitWidth())); 5517 else 5518 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() 5519 : -CR.getUnsignedMin()); 5520 return ExitLimit(Distance, MaxBECount); 5521 } 5522 5523 // If the recurrence is known not to wraparound, unsigned divide computes the 5524 // back edge count. We know that the value will either become zero (and thus 5525 // the loop terminates), that the loop will terminate through some other exit 5526 // condition first, or that the loop has undefined behavior. This means 5527 // we can't "miss" the exit value, even with nonunit stride. 5528 // 5529 // FIXME: Prove that loops always exhibits *acceptable* undefined 5530 // behavior. Loops must exhibit defined behavior until a wrapped value is 5531 // actually used. So the trip count computed by udiv could be smaller than the 5532 // number of well-defined iterations. 5533 if (AddRec->getNoWrapFlags(SCEV::FlagNW)) { 5534 // FIXME: We really want an "isexact" bit for udiv. 5535 return getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 5536 } 5537 // Then, try to solve the above equation provided that Start is constant. 5538 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) 5539 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(), 5540 -StartC->getValue()->getValue(), 5541 *this); 5542 return getCouldNotCompute(); 5543 } 5544 5545 /// HowFarToNonZero - Return the number of times a backedge checking the 5546 /// specified value for nonzero will execute. If not computable, return 5547 /// CouldNotCompute 5548 ScalarEvolution::ExitLimit 5549 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) { 5550 // Loops that look like: while (X == 0) are very strange indeed. We don't 5551 // handle them yet except for the trivial case. This could be expanded in the 5552 // future as needed. 5553 5554 // If the value is a constant, check to see if it is known to be non-zero 5555 // already. If so, the backedge will execute zero times. 5556 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 5557 if (!C->getValue()->isNullValue()) 5558 return getConstant(C->getType(), 0); 5559 return getCouldNotCompute(); // Otherwise it will loop infinitely. 5560 } 5561 5562 // We could implement others, but I really doubt anyone writes loops like 5563 // this, and if they did, they would already be constant folded. 5564 return getCouldNotCompute(); 5565 } 5566 5567 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB 5568 /// (which may not be an immediate predecessor) which has exactly one 5569 /// successor from which BB is reachable, or null if no such block is 5570 /// found. 5571 /// 5572 std::pair<BasicBlock *, BasicBlock *> 5573 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 5574 // If the block has a unique predecessor, then there is no path from the 5575 // predecessor to the block that does not go through the direct edge 5576 // from the predecessor to the block. 5577 if (BasicBlock *Pred = BB->getSinglePredecessor()) 5578 return std::make_pair(Pred, BB); 5579 5580 // A loop's header is defined to be a block that dominates the loop. 5581 // If the header has a unique predecessor outside the loop, it must be 5582 // a block that has exactly one successor that can reach the loop. 5583 if (Loop *L = LI->getLoopFor(BB)) 5584 return std::make_pair(L->getLoopPredecessor(), L->getHeader()); 5585 5586 return std::pair<BasicBlock *, BasicBlock *>(); 5587 } 5588 5589 /// HasSameValue - SCEV structural equivalence is usually sufficient for 5590 /// testing whether two expressions are equal, however for the purposes of 5591 /// looking for a condition guarding a loop, it can be useful to be a little 5592 /// more general, since a front-end may have replicated the controlling 5593 /// expression. 5594 /// 5595 static bool HasSameValue(const SCEV *A, const SCEV *B) { 5596 // Quick check to see if they are the same SCEV. 5597 if (A == B) return true; 5598 5599 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 5600 // two different instructions with the same value. Check for this case. 5601 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 5602 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 5603 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 5604 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 5605 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory()) 5606 return true; 5607 5608 // Otherwise assume they may have a different value. 5609 return false; 5610 } 5611 5612 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with 5613 /// predicate Pred. Return true iff any changes were made. 5614 /// 5615 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 5616 const SCEV *&LHS, const SCEV *&RHS) { 5617 bool Changed = false; 5618 5619 // Canonicalize a constant to the right side. 5620 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 5621 // Check for both operands constant. 5622 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 5623 if (ConstantExpr::getICmp(Pred, 5624 LHSC->getValue(), 5625 RHSC->getValue())->isNullValue()) 5626 goto trivially_false; 5627 else 5628 goto trivially_true; 5629 } 5630 // Otherwise swap the operands to put the constant on the right. 5631 std::swap(LHS, RHS); 5632 Pred = ICmpInst::getSwappedPredicate(Pred); 5633 Changed = true; 5634 } 5635 5636 // If we're comparing an addrec with a value which is loop-invariant in the 5637 // addrec's loop, put the addrec on the left. Also make a dominance check, 5638 // as both operands could be addrecs loop-invariant in each other's loop. 5639 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 5640 const Loop *L = AR->getLoop(); 5641 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 5642 std::swap(LHS, RHS); 5643 Pred = ICmpInst::getSwappedPredicate(Pred); 5644 Changed = true; 5645 } 5646 } 5647 5648 // If there's a constant operand, canonicalize comparisons with boundary 5649 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 5650 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 5651 const APInt &RA = RC->getValue()->getValue(); 5652 switch (Pred) { 5653 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 5654 case ICmpInst::ICMP_EQ: 5655 case ICmpInst::ICMP_NE: 5656 break; 5657 case ICmpInst::ICMP_UGE: 5658 if ((RA - 1).isMinValue()) { 5659 Pred = ICmpInst::ICMP_NE; 5660 RHS = getConstant(RA - 1); 5661 Changed = true; 5662 break; 5663 } 5664 if (RA.isMaxValue()) { 5665 Pred = ICmpInst::ICMP_EQ; 5666 Changed = true; 5667 break; 5668 } 5669 if (RA.isMinValue()) goto trivially_true; 5670 5671 Pred = ICmpInst::ICMP_UGT; 5672 RHS = getConstant(RA - 1); 5673 Changed = true; 5674 break; 5675 case ICmpInst::ICMP_ULE: 5676 if ((RA + 1).isMaxValue()) { 5677 Pred = ICmpInst::ICMP_NE; 5678 RHS = getConstant(RA + 1); 5679 Changed = true; 5680 break; 5681 } 5682 if (RA.isMinValue()) { 5683 Pred = ICmpInst::ICMP_EQ; 5684 Changed = true; 5685 break; 5686 } 5687 if (RA.isMaxValue()) goto trivially_true; 5688 5689 Pred = ICmpInst::ICMP_ULT; 5690 RHS = getConstant(RA + 1); 5691 Changed = true; 5692 break; 5693 case ICmpInst::ICMP_SGE: 5694 if ((RA - 1).isMinSignedValue()) { 5695 Pred = ICmpInst::ICMP_NE; 5696 RHS = getConstant(RA - 1); 5697 Changed = true; 5698 break; 5699 } 5700 if (RA.isMaxSignedValue()) { 5701 Pred = ICmpInst::ICMP_EQ; 5702 Changed = true; 5703 break; 5704 } 5705 if (RA.isMinSignedValue()) goto trivially_true; 5706 5707 Pred = ICmpInst::ICMP_SGT; 5708 RHS = getConstant(RA - 1); 5709 Changed = true; 5710 break; 5711 case ICmpInst::ICMP_SLE: 5712 if ((RA + 1).isMaxSignedValue()) { 5713 Pred = ICmpInst::ICMP_NE; 5714 RHS = getConstant(RA + 1); 5715 Changed = true; 5716 break; 5717 } 5718 if (RA.isMinSignedValue()) { 5719 Pred = ICmpInst::ICMP_EQ; 5720 Changed = true; 5721 break; 5722 } 5723 if (RA.isMaxSignedValue()) goto trivially_true; 5724 5725 Pred = ICmpInst::ICMP_SLT; 5726 RHS = getConstant(RA + 1); 5727 Changed = true; 5728 break; 5729 case ICmpInst::ICMP_UGT: 5730 if (RA.isMinValue()) { 5731 Pred = ICmpInst::ICMP_NE; 5732 Changed = true; 5733 break; 5734 } 5735 if ((RA + 1).isMaxValue()) { 5736 Pred = ICmpInst::ICMP_EQ; 5737 RHS = getConstant(RA + 1); 5738 Changed = true; 5739 break; 5740 } 5741 if (RA.isMaxValue()) goto trivially_false; 5742 break; 5743 case ICmpInst::ICMP_ULT: 5744 if (RA.isMaxValue()) { 5745 Pred = ICmpInst::ICMP_NE; 5746 Changed = true; 5747 break; 5748 } 5749 if ((RA - 1).isMinValue()) { 5750 Pred = ICmpInst::ICMP_EQ; 5751 RHS = getConstant(RA - 1); 5752 Changed = true; 5753 break; 5754 } 5755 if (RA.isMinValue()) goto trivially_false; 5756 break; 5757 case ICmpInst::ICMP_SGT: 5758 if (RA.isMinSignedValue()) { 5759 Pred = ICmpInst::ICMP_NE; 5760 Changed = true; 5761 break; 5762 } 5763 if ((RA + 1).isMaxSignedValue()) { 5764 Pred = ICmpInst::ICMP_EQ; 5765 RHS = getConstant(RA + 1); 5766 Changed = true; 5767 break; 5768 } 5769 if (RA.isMaxSignedValue()) goto trivially_false; 5770 break; 5771 case ICmpInst::ICMP_SLT: 5772 if (RA.isMaxSignedValue()) { 5773 Pred = ICmpInst::ICMP_NE; 5774 Changed = true; 5775 break; 5776 } 5777 if ((RA - 1).isMinSignedValue()) { 5778 Pred = ICmpInst::ICMP_EQ; 5779 RHS = getConstant(RA - 1); 5780 Changed = true; 5781 break; 5782 } 5783 if (RA.isMinSignedValue()) goto trivially_false; 5784 break; 5785 } 5786 } 5787 5788 // Check for obvious equality. 5789 if (HasSameValue(LHS, RHS)) { 5790 if (ICmpInst::isTrueWhenEqual(Pred)) 5791 goto trivially_true; 5792 if (ICmpInst::isFalseWhenEqual(Pred)) 5793 goto trivially_false; 5794 } 5795 5796 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 5797 // adding or subtracting 1 from one of the operands. 5798 switch (Pred) { 5799 case ICmpInst::ICMP_SLE: 5800 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 5801 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 5802 SCEV::FlagNSW); 5803 Pred = ICmpInst::ICMP_SLT; 5804 Changed = true; 5805 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 5806 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 5807 SCEV::FlagNSW); 5808 Pred = ICmpInst::ICMP_SLT; 5809 Changed = true; 5810 } 5811 break; 5812 case ICmpInst::ICMP_SGE: 5813 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 5814 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 5815 SCEV::FlagNSW); 5816 Pred = ICmpInst::ICMP_SGT; 5817 Changed = true; 5818 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 5819 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 5820 SCEV::FlagNSW); 5821 Pred = ICmpInst::ICMP_SGT; 5822 Changed = true; 5823 } 5824 break; 5825 case ICmpInst::ICMP_ULE: 5826 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 5827 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 5828 SCEV::FlagNUW); 5829 Pred = ICmpInst::ICMP_ULT; 5830 Changed = true; 5831 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 5832 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 5833 SCEV::FlagNUW); 5834 Pred = ICmpInst::ICMP_ULT; 5835 Changed = true; 5836 } 5837 break; 5838 case ICmpInst::ICMP_UGE: 5839 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 5840 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 5841 SCEV::FlagNUW); 5842 Pred = ICmpInst::ICMP_UGT; 5843 Changed = true; 5844 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 5845 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 5846 SCEV::FlagNUW); 5847 Pred = ICmpInst::ICMP_UGT; 5848 Changed = true; 5849 } 5850 break; 5851 default: 5852 break; 5853 } 5854 5855 // TODO: More simplifications are possible here. 5856 5857 return Changed; 5858 5859 trivially_true: 5860 // Return 0 == 0. 5861 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 5862 Pred = ICmpInst::ICMP_EQ; 5863 return true; 5864 5865 trivially_false: 5866 // Return 0 != 0. 5867 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 5868 Pred = ICmpInst::ICMP_NE; 5869 return true; 5870 } 5871 5872 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 5873 return getSignedRange(S).getSignedMax().isNegative(); 5874 } 5875 5876 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 5877 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 5878 } 5879 5880 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 5881 return !getSignedRange(S).getSignedMin().isNegative(); 5882 } 5883 5884 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 5885 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 5886 } 5887 5888 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 5889 return isKnownNegative(S) || isKnownPositive(S); 5890 } 5891 5892 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 5893 const SCEV *LHS, const SCEV *RHS) { 5894 // Canonicalize the inputs first. 5895 (void)SimplifyICmpOperands(Pred, LHS, RHS); 5896 5897 // If LHS or RHS is an addrec, check to see if the condition is true in 5898 // every iteration of the loop. 5899 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 5900 if (isLoopEntryGuardedByCond( 5901 AR->getLoop(), Pred, AR->getStart(), RHS) && 5902 isLoopBackedgeGuardedByCond( 5903 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS)) 5904 return true; 5905 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) 5906 if (isLoopEntryGuardedByCond( 5907 AR->getLoop(), Pred, LHS, AR->getStart()) && 5908 isLoopBackedgeGuardedByCond( 5909 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this))) 5910 return true; 5911 5912 // Otherwise see what can be done with known constant ranges. 5913 return isKnownPredicateWithRanges(Pred, LHS, RHS); 5914 } 5915 5916 bool 5917 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred, 5918 const SCEV *LHS, const SCEV *RHS) { 5919 if (HasSameValue(LHS, RHS)) 5920 return ICmpInst::isTrueWhenEqual(Pred); 5921 5922 // This code is split out from isKnownPredicate because it is called from 5923 // within isLoopEntryGuardedByCond. 5924 switch (Pred) { 5925 default: 5926 llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 5927 break; 5928 case ICmpInst::ICMP_SGT: 5929 Pred = ICmpInst::ICMP_SLT; 5930 std::swap(LHS, RHS); 5931 case ICmpInst::ICMP_SLT: { 5932 ConstantRange LHSRange = getSignedRange(LHS); 5933 ConstantRange RHSRange = getSignedRange(RHS); 5934 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin())) 5935 return true; 5936 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax())) 5937 return false; 5938 break; 5939 } 5940 case ICmpInst::ICMP_SGE: 5941 Pred = ICmpInst::ICMP_SLE; 5942 std::swap(LHS, RHS); 5943 case ICmpInst::ICMP_SLE: { 5944 ConstantRange LHSRange = getSignedRange(LHS); 5945 ConstantRange RHSRange = getSignedRange(RHS); 5946 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin())) 5947 return true; 5948 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax())) 5949 return false; 5950 break; 5951 } 5952 case ICmpInst::ICMP_UGT: 5953 Pred = ICmpInst::ICMP_ULT; 5954 std::swap(LHS, RHS); 5955 case ICmpInst::ICMP_ULT: { 5956 ConstantRange LHSRange = getUnsignedRange(LHS); 5957 ConstantRange RHSRange = getUnsignedRange(RHS); 5958 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin())) 5959 return true; 5960 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax())) 5961 return false; 5962 break; 5963 } 5964 case ICmpInst::ICMP_UGE: 5965 Pred = ICmpInst::ICMP_ULE; 5966 std::swap(LHS, RHS); 5967 case ICmpInst::ICMP_ULE: { 5968 ConstantRange LHSRange = getUnsignedRange(LHS); 5969 ConstantRange RHSRange = getUnsignedRange(RHS); 5970 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin())) 5971 return true; 5972 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax())) 5973 return false; 5974 break; 5975 } 5976 case ICmpInst::ICMP_NE: { 5977 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet()) 5978 return true; 5979 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet()) 5980 return true; 5981 5982 const SCEV *Diff = getMinusSCEV(LHS, RHS); 5983 if (isKnownNonZero(Diff)) 5984 return true; 5985 break; 5986 } 5987 case ICmpInst::ICMP_EQ: 5988 // The check at the top of the function catches the case where 5989 // the values are known to be equal. 5990 break; 5991 } 5992 return false; 5993 } 5994 5995 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 5996 /// protected by a conditional between LHS and RHS. This is used to 5997 /// to eliminate casts. 5998 bool 5999 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 6000 ICmpInst::Predicate Pred, 6001 const SCEV *LHS, const SCEV *RHS) { 6002 // Interpret a null as meaning no loop, where there is obviously no guard 6003 // (interprocedural conditions notwithstanding). 6004 if (!L) return true; 6005 6006 BasicBlock *Latch = L->getLoopLatch(); 6007 if (!Latch) 6008 return false; 6009 6010 BranchInst *LoopContinuePredicate = 6011 dyn_cast<BranchInst>(Latch->getTerminator()); 6012 if (!LoopContinuePredicate || 6013 LoopContinuePredicate->isUnconditional()) 6014 return false; 6015 6016 return isImpliedCond(Pred, LHS, RHS, 6017 LoopContinuePredicate->getCondition(), 6018 LoopContinuePredicate->getSuccessor(0) != L->getHeader()); 6019 } 6020 6021 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected 6022 /// by a conditional between LHS and RHS. This is used to help avoid max 6023 /// expressions in loop trip counts, and to eliminate casts. 6024 bool 6025 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 6026 ICmpInst::Predicate Pred, 6027 const SCEV *LHS, const SCEV *RHS) { 6028 // Interpret a null as meaning no loop, where there is obviously no guard 6029 // (interprocedural conditions notwithstanding). 6030 if (!L) return false; 6031 6032 // Starting at the loop predecessor, climb up the predecessor chain, as long 6033 // as there are predecessors that can be found that have unique successors 6034 // leading to the original header. 6035 for (std::pair<BasicBlock *, BasicBlock *> 6036 Pair(L->getLoopPredecessor(), L->getHeader()); 6037 Pair.first; 6038 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 6039 6040 BranchInst *LoopEntryPredicate = 6041 dyn_cast<BranchInst>(Pair.first->getTerminator()); 6042 if (!LoopEntryPredicate || 6043 LoopEntryPredicate->isUnconditional()) 6044 continue; 6045 6046 if (isImpliedCond(Pred, LHS, RHS, 6047 LoopEntryPredicate->getCondition(), 6048 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 6049 return true; 6050 } 6051 6052 return false; 6053 } 6054 6055 /// isImpliedCond - Test whether the condition described by Pred, LHS, 6056 /// and RHS is true whenever the given Cond value evaluates to true. 6057 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 6058 const SCEV *LHS, const SCEV *RHS, 6059 Value *FoundCondValue, 6060 bool Inverse) { 6061 // Recursively handle And and Or conditions. 6062 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 6063 if (BO->getOpcode() == Instruction::And) { 6064 if (!Inverse) 6065 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 6066 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 6067 } else if (BO->getOpcode() == Instruction::Or) { 6068 if (Inverse) 6069 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 6070 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 6071 } 6072 } 6073 6074 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 6075 if (!ICI) return false; 6076 6077 // Bail if the ICmp's operands' types are wider than the needed type 6078 // before attempting to call getSCEV on them. This avoids infinite 6079 // recursion, since the analysis of widening casts can require loop 6080 // exit condition information for overflow checking, which would 6081 // lead back here. 6082 if (getTypeSizeInBits(LHS->getType()) < 6083 getTypeSizeInBits(ICI->getOperand(0)->getType())) 6084 return false; 6085 6086 // Now that we found a conditional branch that dominates the loop, check to 6087 // see if it is the comparison we are looking for. 6088 ICmpInst::Predicate FoundPred; 6089 if (Inverse) 6090 FoundPred = ICI->getInversePredicate(); 6091 else 6092 FoundPred = ICI->getPredicate(); 6093 6094 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 6095 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 6096 6097 // Balance the types. The case where FoundLHS' type is wider than 6098 // LHS' type is checked for above. 6099 if (getTypeSizeInBits(LHS->getType()) > 6100 getTypeSizeInBits(FoundLHS->getType())) { 6101 if (CmpInst::isSigned(Pred)) { 6102 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 6103 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 6104 } else { 6105 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 6106 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 6107 } 6108 } 6109 6110 // Canonicalize the query to match the way instcombine will have 6111 // canonicalized the comparison. 6112 if (SimplifyICmpOperands(Pred, LHS, RHS)) 6113 if (LHS == RHS) 6114 return CmpInst::isTrueWhenEqual(Pred); 6115 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 6116 if (FoundLHS == FoundRHS) 6117 return CmpInst::isFalseWhenEqual(Pred); 6118 6119 // Check to see if we can make the LHS or RHS match. 6120 if (LHS == FoundRHS || RHS == FoundLHS) { 6121 if (isa<SCEVConstant>(RHS)) { 6122 std::swap(FoundLHS, FoundRHS); 6123 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 6124 } else { 6125 std::swap(LHS, RHS); 6126 Pred = ICmpInst::getSwappedPredicate(Pred); 6127 } 6128 } 6129 6130 // Check whether the found predicate is the same as the desired predicate. 6131 if (FoundPred == Pred) 6132 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 6133 6134 // Check whether swapping the found predicate makes it the same as the 6135 // desired predicate. 6136 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 6137 if (isa<SCEVConstant>(RHS)) 6138 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 6139 else 6140 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 6141 RHS, LHS, FoundLHS, FoundRHS); 6142 } 6143 6144 // Check whether the actual condition is beyond sufficient. 6145 if (FoundPred == ICmpInst::ICMP_EQ) 6146 if (ICmpInst::isTrueWhenEqual(Pred)) 6147 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 6148 return true; 6149 if (Pred == ICmpInst::ICMP_NE) 6150 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 6151 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 6152 return true; 6153 6154 // Otherwise assume the worst. 6155 return false; 6156 } 6157 6158 /// isImpliedCondOperands - Test whether the condition described by Pred, 6159 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS, 6160 /// and FoundRHS is true. 6161 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 6162 const SCEV *LHS, const SCEV *RHS, 6163 const SCEV *FoundLHS, 6164 const SCEV *FoundRHS) { 6165 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 6166 FoundLHS, FoundRHS) || 6167 // ~x < ~y --> x > y 6168 isImpliedCondOperandsHelper(Pred, LHS, RHS, 6169 getNotSCEV(FoundRHS), 6170 getNotSCEV(FoundLHS)); 6171 } 6172 6173 /// isImpliedCondOperandsHelper - Test whether the condition described by 6174 /// Pred, LHS, and RHS is true whenever the condition described by Pred, 6175 /// FoundLHS, and FoundRHS is true. 6176 bool 6177 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 6178 const SCEV *LHS, const SCEV *RHS, 6179 const SCEV *FoundLHS, 6180 const SCEV *FoundRHS) { 6181 switch (Pred) { 6182 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 6183 case ICmpInst::ICMP_EQ: 6184 case ICmpInst::ICMP_NE: 6185 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 6186 return true; 6187 break; 6188 case ICmpInst::ICMP_SLT: 6189 case ICmpInst::ICMP_SLE: 6190 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 6191 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 6192 return true; 6193 break; 6194 case ICmpInst::ICMP_SGT: 6195 case ICmpInst::ICMP_SGE: 6196 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 6197 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 6198 return true; 6199 break; 6200 case ICmpInst::ICMP_ULT: 6201 case ICmpInst::ICMP_ULE: 6202 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 6203 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 6204 return true; 6205 break; 6206 case ICmpInst::ICMP_UGT: 6207 case ICmpInst::ICMP_UGE: 6208 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 6209 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 6210 return true; 6211 break; 6212 } 6213 6214 return false; 6215 } 6216 6217 /// getBECount - Subtract the end and start values and divide by the step, 6218 /// rounding up, to get the number of times the backedge is executed. Return 6219 /// CouldNotCompute if an intermediate computation overflows. 6220 const SCEV *ScalarEvolution::getBECount(const SCEV *Start, 6221 const SCEV *End, 6222 const SCEV *Step, 6223 bool NoWrap) { 6224 assert(!isKnownNegative(Step) && 6225 "This code doesn't handle negative strides yet!"); 6226 6227 Type *Ty = Start->getType(); 6228 6229 // When Start == End, we have an exact BECount == 0. Short-circuit this case 6230 // here because SCEV may not be able to determine that the unsigned division 6231 // after rounding is zero. 6232 if (Start == End) 6233 return getConstant(Ty, 0); 6234 6235 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1); 6236 const SCEV *Diff = getMinusSCEV(End, Start); 6237 const SCEV *RoundUp = getAddExpr(Step, NegOne); 6238 6239 // Add an adjustment to the difference between End and Start so that 6240 // the division will effectively round up. 6241 const SCEV *Add = getAddExpr(Diff, RoundUp); 6242 6243 if (!NoWrap) { 6244 // Check Add for unsigned overflow. 6245 // TODO: More sophisticated things could be done here. 6246 Type *WideTy = IntegerType::get(getContext(), 6247 getTypeSizeInBits(Ty) + 1); 6248 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy); 6249 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy); 6250 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp); 6251 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd) 6252 return getCouldNotCompute(); 6253 } 6254 6255 return getUDivExpr(Add, Step); 6256 } 6257 6258 /// HowManyLessThans - Return the number of times a backedge containing the 6259 /// specified less-than comparison will execute. If not computable, return 6260 /// CouldNotCompute. 6261 ScalarEvolution::ExitLimit 6262 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS, 6263 const Loop *L, bool isSigned) { 6264 // Only handle: "ADDREC < LoopInvariant". 6265 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute(); 6266 6267 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS); 6268 if (!AddRec || AddRec->getLoop() != L) 6269 return getCouldNotCompute(); 6270 6271 // Check to see if we have a flag which makes analysis easy. 6272 bool NoWrap = isSigned ? 6273 AddRec->getNoWrapFlags((SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNW)) : 6274 AddRec->getNoWrapFlags((SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNW)); 6275 6276 if (AddRec->isAffine()) { 6277 unsigned BitWidth = getTypeSizeInBits(AddRec->getType()); 6278 const SCEV *Step = AddRec->getStepRecurrence(*this); 6279 6280 if (Step->isZero()) 6281 return getCouldNotCompute(); 6282 if (Step->isOne()) { 6283 // With unit stride, the iteration never steps past the limit value. 6284 } else if (isKnownPositive(Step)) { 6285 // Test whether a positive iteration can step past the limit 6286 // value and past the maximum value for its type in a single step. 6287 // Note that it's not sufficient to check NoWrap here, because even 6288 // though the value after a wrap is undefined, it's not undefined 6289 // behavior, so if wrap does occur, the loop could either terminate or 6290 // loop infinitely, but in either case, the loop is guaranteed to 6291 // iterate at least until the iteration where the wrapping occurs. 6292 const SCEV *One = getConstant(Step->getType(), 1); 6293 if (isSigned) { 6294 APInt Max = APInt::getSignedMaxValue(BitWidth); 6295 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax()) 6296 .slt(getSignedRange(RHS).getSignedMax())) 6297 return getCouldNotCompute(); 6298 } else { 6299 APInt Max = APInt::getMaxValue(BitWidth); 6300 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax()) 6301 .ult(getUnsignedRange(RHS).getUnsignedMax())) 6302 return getCouldNotCompute(); 6303 } 6304 } else 6305 // TODO: Handle negative strides here and below. 6306 return getCouldNotCompute(); 6307 6308 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant 6309 // m. So, we count the number of iterations in which {n,+,s} < m is true. 6310 // Note that we cannot simply return max(m-n,0)/s because it's not safe to 6311 // treat m-n as signed nor unsigned due to overflow possibility. 6312 6313 // First, we get the value of the LHS in the first iteration: n 6314 const SCEV *Start = AddRec->getOperand(0); 6315 6316 // Determine the minimum constant start value. 6317 const SCEV *MinStart = getConstant(isSigned ? 6318 getSignedRange(Start).getSignedMin() : 6319 getUnsignedRange(Start).getUnsignedMin()); 6320 6321 // If we know that the condition is true in order to enter the loop, 6322 // then we know that it will run exactly (m-n)/s times. Otherwise, we 6323 // only know that it will execute (max(m,n)-n)/s times. In both cases, 6324 // the division must round up. 6325 const SCEV *End = RHS; 6326 if (!isLoopEntryGuardedByCond(L, 6327 isSigned ? ICmpInst::ICMP_SLT : 6328 ICmpInst::ICMP_ULT, 6329 getMinusSCEV(Start, Step), RHS)) 6330 End = isSigned ? getSMaxExpr(RHS, Start) 6331 : getUMaxExpr(RHS, Start); 6332 6333 // Determine the maximum constant end value. 6334 const SCEV *MaxEnd = getConstant(isSigned ? 6335 getSignedRange(End).getSignedMax() : 6336 getUnsignedRange(End).getUnsignedMax()); 6337 6338 // If MaxEnd is within a step of the maximum integer value in its type, 6339 // adjust it down to the minimum value which would produce the same effect. 6340 // This allows the subsequent ceiling division of (N+(step-1))/step to 6341 // compute the correct value. 6342 const SCEV *StepMinusOne = getMinusSCEV(Step, 6343 getConstant(Step->getType(), 1)); 6344 MaxEnd = isSigned ? 6345 getSMinExpr(MaxEnd, 6346 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)), 6347 StepMinusOne)) : 6348 getUMinExpr(MaxEnd, 6349 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)), 6350 StepMinusOne)); 6351 6352 // Finally, we subtract these two values and divide, rounding up, to get 6353 // the number of times the backedge is executed. 6354 const SCEV *BECount = getBECount(Start, End, Step, NoWrap); 6355 6356 // The maximum backedge count is similar, except using the minimum start 6357 // value and the maximum end value. 6358 // If we already have an exact constant BECount, use it instead. 6359 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) ? BECount 6360 : getBECount(MinStart, MaxEnd, Step, NoWrap); 6361 6362 // If the stride is nonconstant, and NoWrap == true, then 6363 // getBECount(MinStart, MaxEnd) may not compute. This would result in an 6364 // exact BECount and invalid MaxBECount, which should be avoided to catch 6365 // more optimization opportunities. 6366 if (isa<SCEVCouldNotCompute>(MaxBECount)) 6367 MaxBECount = BECount; 6368 6369 return ExitLimit(BECount, MaxBECount); 6370 } 6371 6372 return getCouldNotCompute(); 6373 } 6374 6375 /// getNumIterationsInRange - Return the number of iterations of this loop that 6376 /// produce values in the specified constant range. Another way of looking at 6377 /// this is that it returns the first iteration number where the value is not in 6378 /// the condition, thus computing the exit count. If the iteration count can't 6379 /// be computed, an instance of SCEVCouldNotCompute is returned. 6380 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, 6381 ScalarEvolution &SE) const { 6382 if (Range.isFullSet()) // Infinite loop. 6383 return SE.getCouldNotCompute(); 6384 6385 // If the start is a non-zero constant, shift the range to simplify things. 6386 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 6387 if (!SC->getValue()->isZero()) { 6388 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 6389 Operands[0] = SE.getConstant(SC->getType(), 0); 6390 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 6391 getNoWrapFlags(FlagNW)); 6392 if (const SCEVAddRecExpr *ShiftedAddRec = 6393 dyn_cast<SCEVAddRecExpr>(Shifted)) 6394 return ShiftedAddRec->getNumIterationsInRange( 6395 Range.subtract(SC->getValue()->getValue()), SE); 6396 // This is strange and shouldn't happen. 6397 return SE.getCouldNotCompute(); 6398 } 6399 6400 // The only time we can solve this is when we have all constant indices. 6401 // Otherwise, we cannot determine the overflow conditions. 6402 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 6403 if (!isa<SCEVConstant>(getOperand(i))) 6404 return SE.getCouldNotCompute(); 6405 6406 6407 // Okay at this point we know that all elements of the chrec are constants and 6408 // that the start element is zero. 6409 6410 // First check to see if the range contains zero. If not, the first 6411 // iteration exits. 6412 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 6413 if (!Range.contains(APInt(BitWidth, 0))) 6414 return SE.getConstant(getType(), 0); 6415 6416 if (isAffine()) { 6417 // If this is an affine expression then we have this situation: 6418 // Solve {0,+,A} in Range === Ax in Range 6419 6420 // We know that zero is in the range. If A is positive then we know that 6421 // the upper value of the range must be the first possible exit value. 6422 // If A is negative then the lower of the range is the last possible loop 6423 // value. Also note that we already checked for a full range. 6424 APInt One(BitWidth,1); 6425 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue(); 6426 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 6427 6428 // The exit value should be (End+A)/A. 6429 APInt ExitVal = (End + A).udiv(A); 6430 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 6431 6432 // Evaluate at the exit value. If we really did fall out of the valid 6433 // range, then we computed our trip count, otherwise wrap around or other 6434 // things must have happened. 6435 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 6436 if (Range.contains(Val->getValue())) 6437 return SE.getCouldNotCompute(); // Something strange happened 6438 6439 // Ensure that the previous value is in the range. This is a sanity check. 6440 assert(Range.contains( 6441 EvaluateConstantChrecAtConstant(this, 6442 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 6443 "Linear scev computation is off in a bad way!"); 6444 return SE.getConstant(ExitValue); 6445 } else if (isQuadratic()) { 6446 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 6447 // quadratic equation to solve it. To do this, we must frame our problem in 6448 // terms of figuring out when zero is crossed, instead of when 6449 // Range.getUpper() is crossed. 6450 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 6451 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 6452 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), 6453 // getNoWrapFlags(FlagNW) 6454 FlagAnyWrap); 6455 6456 // Next, solve the constructed addrec 6457 std::pair<const SCEV *,const SCEV *> Roots = 6458 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE); 6459 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 6460 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 6461 if (R1) { 6462 // Pick the smallest positive root value. 6463 if (ConstantInt *CB = 6464 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 6465 R1->getValue(), R2->getValue()))) { 6466 if (CB->getZExtValue() == false) 6467 std::swap(R1, R2); // R1 is the minimum root now. 6468 6469 // Make sure the root is not off by one. The returned iteration should 6470 // not be in the range, but the previous one should be. When solving 6471 // for "X*X < 5", for example, we should not return a root of 2. 6472 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, 6473 R1->getValue(), 6474 SE); 6475 if (Range.contains(R1Val->getValue())) { 6476 // The next iteration must be out of the range... 6477 ConstantInt *NextVal = 6478 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1); 6479 6480 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 6481 if (!Range.contains(R1Val->getValue())) 6482 return SE.getConstant(NextVal); 6483 return SE.getCouldNotCompute(); // Something strange happened 6484 } 6485 6486 // If R1 was not in the range, then it is a good return value. Make 6487 // sure that R1-1 WAS in the range though, just in case. 6488 ConstantInt *NextVal = 6489 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1); 6490 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 6491 if (Range.contains(R1Val->getValue())) 6492 return R1; 6493 return SE.getCouldNotCompute(); // Something strange happened 6494 } 6495 } 6496 } 6497 6498 return SE.getCouldNotCompute(); 6499 } 6500 6501 6502 6503 //===----------------------------------------------------------------------===// 6504 // SCEVCallbackVH Class Implementation 6505 //===----------------------------------------------------------------------===// 6506 6507 void ScalarEvolution::SCEVCallbackVH::deleted() { 6508 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 6509 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 6510 SE->ConstantEvolutionLoopExitValue.erase(PN); 6511 SE->ValueExprMap.erase(getValPtr()); 6512 // this now dangles! 6513 } 6514 6515 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 6516 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 6517 6518 // Forget all the expressions associated with users of the old value, 6519 // so that future queries will recompute the expressions using the new 6520 // value. 6521 Value *Old = getValPtr(); 6522 SmallVector<User *, 16> Worklist; 6523 SmallPtrSet<User *, 8> Visited; 6524 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end(); 6525 UI != UE; ++UI) 6526 Worklist.push_back(*UI); 6527 while (!Worklist.empty()) { 6528 User *U = Worklist.pop_back_val(); 6529 // Deleting the Old value will cause this to dangle. Postpone 6530 // that until everything else is done. 6531 if (U == Old) 6532 continue; 6533 if (!Visited.insert(U)) 6534 continue; 6535 if (PHINode *PN = dyn_cast<PHINode>(U)) 6536 SE->ConstantEvolutionLoopExitValue.erase(PN); 6537 SE->ValueExprMap.erase(U); 6538 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end(); 6539 UI != UE; ++UI) 6540 Worklist.push_back(*UI); 6541 } 6542 // Delete the Old value. 6543 if (PHINode *PN = dyn_cast<PHINode>(Old)) 6544 SE->ConstantEvolutionLoopExitValue.erase(PN); 6545 SE->ValueExprMap.erase(Old); 6546 // this now dangles! 6547 } 6548 6549 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 6550 : CallbackVH(V), SE(se) {} 6551 6552 //===----------------------------------------------------------------------===// 6553 // ScalarEvolution Class Implementation 6554 //===----------------------------------------------------------------------===// 6555 6556 ScalarEvolution::ScalarEvolution() 6557 : FunctionPass(ID), FirstUnknown(0) { 6558 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry()); 6559 } 6560 6561 bool ScalarEvolution::runOnFunction(Function &F) { 6562 this->F = &F; 6563 LI = &getAnalysis<LoopInfo>(); 6564 TD = getAnalysisIfAvailable<TargetData>(); 6565 TLI = &getAnalysis<TargetLibraryInfo>(); 6566 DT = &getAnalysis<DominatorTree>(); 6567 return false; 6568 } 6569 6570 void ScalarEvolution::releaseMemory() { 6571 // Iterate through all the SCEVUnknown instances and call their 6572 // destructors, so that they release their references to their values. 6573 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next) 6574 U->~SCEVUnknown(); 6575 FirstUnknown = 0; 6576 6577 ValueExprMap.clear(); 6578 6579 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 6580 // that a loop had multiple computable exits. 6581 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I = 6582 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); 6583 I != E; ++I) { 6584 I->second.clear(); 6585 } 6586 6587 BackedgeTakenCounts.clear(); 6588 ConstantEvolutionLoopExitValue.clear(); 6589 ValuesAtScopes.clear(); 6590 LoopDispositions.clear(); 6591 BlockDispositions.clear(); 6592 UnsignedRanges.clear(); 6593 SignedRanges.clear(); 6594 UniqueSCEVs.clear(); 6595 SCEVAllocator.Reset(); 6596 } 6597 6598 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const { 6599 AU.setPreservesAll(); 6600 AU.addRequiredTransitive<LoopInfo>(); 6601 AU.addRequiredTransitive<DominatorTree>(); 6602 AU.addRequired<TargetLibraryInfo>(); 6603 } 6604 6605 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 6606 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 6607 } 6608 6609 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 6610 const Loop *L) { 6611 // Print all inner loops first 6612 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 6613 PrintLoopInfo(OS, SE, *I); 6614 6615 OS << "Loop "; 6616 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false); 6617 OS << ": "; 6618 6619 SmallVector<BasicBlock *, 8> ExitBlocks; 6620 L->getExitBlocks(ExitBlocks); 6621 if (ExitBlocks.size() != 1) 6622 OS << "<multiple exits> "; 6623 6624 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 6625 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 6626 } else { 6627 OS << "Unpredictable backedge-taken count. "; 6628 } 6629 6630 OS << "\n" 6631 "Loop "; 6632 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false); 6633 OS << ": "; 6634 6635 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 6636 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 6637 } else { 6638 OS << "Unpredictable max backedge-taken count. "; 6639 } 6640 6641 OS << "\n"; 6642 } 6643 6644 void ScalarEvolution::print(raw_ostream &OS, const Module *) const { 6645 // ScalarEvolution's implementation of the print method is to print 6646 // out SCEV values of all instructions that are interesting. Doing 6647 // this potentially causes it to create new SCEV objects though, 6648 // which technically conflicts with the const qualifier. This isn't 6649 // observable from outside the class though, so casting away the 6650 // const isn't dangerous. 6651 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 6652 6653 OS << "Classifying expressions for: "; 6654 WriteAsOperand(OS, F, /*PrintType=*/false); 6655 OS << "\n"; 6656 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) 6657 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) { 6658 OS << *I << '\n'; 6659 OS << " --> "; 6660 const SCEV *SV = SE.getSCEV(&*I); 6661 SV->print(OS); 6662 6663 const Loop *L = LI->getLoopFor((*I).getParent()); 6664 6665 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 6666 if (AtUse != SV) { 6667 OS << " --> "; 6668 AtUse->print(OS); 6669 } 6670 6671 if (L) { 6672 OS << "\t\t" "Exits: "; 6673 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 6674 if (!SE.isLoopInvariant(ExitValue, L)) { 6675 OS << "<<Unknown>>"; 6676 } else { 6677 OS << *ExitValue; 6678 } 6679 } 6680 6681 OS << "\n"; 6682 } 6683 6684 OS << "Determining loop execution counts for: "; 6685 WriteAsOperand(OS, F, /*PrintType=*/false); 6686 OS << "\n"; 6687 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 6688 PrintLoopInfo(OS, &SE, *I); 6689 } 6690 6691 ScalarEvolution::LoopDisposition 6692 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 6693 std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S]; 6694 std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair = 6695 Values.insert(std::make_pair(L, LoopVariant)); 6696 if (!Pair.second) 6697 return Pair.first->second; 6698 6699 LoopDisposition D = computeLoopDisposition(S, L); 6700 return LoopDispositions[S][L] = D; 6701 } 6702 6703 ScalarEvolution::LoopDisposition 6704 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 6705 switch (S->getSCEVType()) { 6706 case scConstant: 6707 return LoopInvariant; 6708 case scTruncate: 6709 case scZeroExtend: 6710 case scSignExtend: 6711 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 6712 case scAddRecExpr: { 6713 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 6714 6715 // If L is the addrec's loop, it's computable. 6716 if (AR->getLoop() == L) 6717 return LoopComputable; 6718 6719 // Add recurrences are never invariant in the function-body (null loop). 6720 if (!L) 6721 return LoopVariant; 6722 6723 // This recurrence is variant w.r.t. L if L contains AR's loop. 6724 if (L->contains(AR->getLoop())) 6725 return LoopVariant; 6726 6727 // This recurrence is invariant w.r.t. L if AR's loop contains L. 6728 if (AR->getLoop()->contains(L)) 6729 return LoopInvariant; 6730 6731 // This recurrence is variant w.r.t. L if any of its operands 6732 // are variant. 6733 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end(); 6734 I != E; ++I) 6735 if (!isLoopInvariant(*I, L)) 6736 return LoopVariant; 6737 6738 // Otherwise it's loop-invariant. 6739 return LoopInvariant; 6740 } 6741 case scAddExpr: 6742 case scMulExpr: 6743 case scUMaxExpr: 6744 case scSMaxExpr: { 6745 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 6746 bool HasVarying = false; 6747 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 6748 I != E; ++I) { 6749 LoopDisposition D = getLoopDisposition(*I, L); 6750 if (D == LoopVariant) 6751 return LoopVariant; 6752 if (D == LoopComputable) 6753 HasVarying = true; 6754 } 6755 return HasVarying ? LoopComputable : LoopInvariant; 6756 } 6757 case scUDivExpr: { 6758 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 6759 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 6760 if (LD == LoopVariant) 6761 return LoopVariant; 6762 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 6763 if (RD == LoopVariant) 6764 return LoopVariant; 6765 return (LD == LoopInvariant && RD == LoopInvariant) ? 6766 LoopInvariant : LoopComputable; 6767 } 6768 case scUnknown: 6769 // All non-instruction values are loop invariant. All instructions are loop 6770 // invariant if they are not contained in the specified loop. 6771 // Instructions are never considered invariant in the function body 6772 // (null loop) because they are defined within the "loop". 6773 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 6774 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 6775 return LoopInvariant; 6776 case scCouldNotCompute: 6777 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 6778 return LoopVariant; 6779 default: break; 6780 } 6781 llvm_unreachable("Unknown SCEV kind!"); 6782 return LoopVariant; 6783 } 6784 6785 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 6786 return getLoopDisposition(S, L) == LoopInvariant; 6787 } 6788 6789 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 6790 return getLoopDisposition(S, L) == LoopComputable; 6791 } 6792 6793 ScalarEvolution::BlockDisposition 6794 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 6795 std::map<const BasicBlock *, BlockDisposition> &Values = BlockDispositions[S]; 6796 std::pair<std::map<const BasicBlock *, BlockDisposition>::iterator, bool> 6797 Pair = Values.insert(std::make_pair(BB, DoesNotDominateBlock)); 6798 if (!Pair.second) 6799 return Pair.first->second; 6800 6801 BlockDisposition D = computeBlockDisposition(S, BB); 6802 return BlockDispositions[S][BB] = D; 6803 } 6804 6805 ScalarEvolution::BlockDisposition 6806 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 6807 switch (S->getSCEVType()) { 6808 case scConstant: 6809 return ProperlyDominatesBlock; 6810 case scTruncate: 6811 case scZeroExtend: 6812 case scSignExtend: 6813 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 6814 case scAddRecExpr: { 6815 // This uses a "dominates" query instead of "properly dominates" query 6816 // to test for proper dominance too, because the instruction which 6817 // produces the addrec's value is a PHI, and a PHI effectively properly 6818 // dominates its entire containing block. 6819 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 6820 if (!DT->dominates(AR->getLoop()->getHeader(), BB)) 6821 return DoesNotDominateBlock; 6822 } 6823 // FALL THROUGH into SCEVNAryExpr handling. 6824 case scAddExpr: 6825 case scMulExpr: 6826 case scUMaxExpr: 6827 case scSMaxExpr: { 6828 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 6829 bool Proper = true; 6830 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 6831 I != E; ++I) { 6832 BlockDisposition D = getBlockDisposition(*I, BB); 6833 if (D == DoesNotDominateBlock) 6834 return DoesNotDominateBlock; 6835 if (D == DominatesBlock) 6836 Proper = false; 6837 } 6838 return Proper ? ProperlyDominatesBlock : DominatesBlock; 6839 } 6840 case scUDivExpr: { 6841 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 6842 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 6843 BlockDisposition LD = getBlockDisposition(LHS, BB); 6844 if (LD == DoesNotDominateBlock) 6845 return DoesNotDominateBlock; 6846 BlockDisposition RD = getBlockDisposition(RHS, BB); 6847 if (RD == DoesNotDominateBlock) 6848 return DoesNotDominateBlock; 6849 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 6850 ProperlyDominatesBlock : DominatesBlock; 6851 } 6852 case scUnknown: 6853 if (Instruction *I = 6854 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 6855 if (I->getParent() == BB) 6856 return DominatesBlock; 6857 if (DT->properlyDominates(I->getParent(), BB)) 6858 return ProperlyDominatesBlock; 6859 return DoesNotDominateBlock; 6860 } 6861 return ProperlyDominatesBlock; 6862 case scCouldNotCompute: 6863 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 6864 return DoesNotDominateBlock; 6865 default: break; 6866 } 6867 llvm_unreachable("Unknown SCEV kind!"); 6868 return DoesNotDominateBlock; 6869 } 6870 6871 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 6872 return getBlockDisposition(S, BB) >= DominatesBlock; 6873 } 6874 6875 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 6876 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 6877 } 6878 6879 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 6880 switch (S->getSCEVType()) { 6881 case scConstant: 6882 return false; 6883 case scTruncate: 6884 case scZeroExtend: 6885 case scSignExtend: { 6886 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S); 6887 const SCEV *CastOp = Cast->getOperand(); 6888 return Op == CastOp || hasOperand(CastOp, Op); 6889 } 6890 case scAddRecExpr: 6891 case scAddExpr: 6892 case scMulExpr: 6893 case scUMaxExpr: 6894 case scSMaxExpr: { 6895 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 6896 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 6897 I != E; ++I) { 6898 const SCEV *NAryOp = *I; 6899 if (NAryOp == Op || hasOperand(NAryOp, Op)) 6900 return true; 6901 } 6902 return false; 6903 } 6904 case scUDivExpr: { 6905 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 6906 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 6907 return LHS == Op || hasOperand(LHS, Op) || 6908 RHS == Op || hasOperand(RHS, Op); 6909 } 6910 case scUnknown: 6911 return false; 6912 case scCouldNotCompute: 6913 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 6914 return false; 6915 default: break; 6916 } 6917 llvm_unreachable("Unknown SCEV kind!"); 6918 return false; 6919 } 6920 6921 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 6922 ValuesAtScopes.erase(S); 6923 LoopDispositions.erase(S); 6924 BlockDispositions.erase(S); 6925 UnsignedRanges.erase(S); 6926 SignedRanges.erase(S); 6927 } 6928