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