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