1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/Config/llvm-config.h" 86 #include "llvm/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/CallSite.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/Pass.h" 116 #include "llvm/Support/Casting.h" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Compiler.h" 119 #include "llvm/Support/Debug.h" 120 #include "llvm/Support/ErrorHandling.h" 121 #include "llvm/Support/KnownBits.h" 122 #include "llvm/Support/SaveAndRestore.h" 123 #include "llvm/Support/raw_ostream.h" 124 #include <algorithm> 125 #include <cassert> 126 #include <climits> 127 #include <cstddef> 128 #include <cstdint> 129 #include <cstdlib> 130 #include <map> 131 #include <memory> 132 #include <tuple> 133 #include <utility> 134 #include <vector> 135 136 using namespace llvm; 137 138 #define DEBUG_TYPE "scalar-evolution" 139 140 STATISTIC(NumArrayLenItCounts, 141 "Number of trip counts computed with array length"); 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::desc("Maximum number of iterations SCEV will " 152 "symbolically execute a constant " 153 "derived loop"), 154 cl::init(100)); 155 156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 157 static cl::opt<bool> VerifySCEV( 158 "verify-scev", cl::Hidden, 159 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 160 static cl::opt<bool> 161 VerifySCEVMap("verify-scev-maps", cl::Hidden, 162 cl::desc("Verify no dangling value in ScalarEvolution's " 163 "ExprValueMap (slow)")); 164 165 static cl::opt<bool> VerifyIR( 166 "scev-verify-ir", cl::Hidden, 167 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 168 cl::init(false)); 169 170 static cl::opt<unsigned> MulOpsInlineThreshold( 171 "scev-mulops-inline-threshold", cl::Hidden, 172 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 173 cl::init(32)); 174 175 static cl::opt<unsigned> AddOpsInlineThreshold( 176 "scev-addops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining addition operands into a SCEV"), 178 cl::init(500)); 179 180 static cl::opt<unsigned> MaxSCEVCompareDepth( 181 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 182 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 183 cl::init(32)); 184 185 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 186 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 188 cl::init(2)); 189 190 static cl::opt<unsigned> MaxValueCompareDepth( 191 "scalar-evolution-max-value-compare-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive value complexity comparisons"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> 196 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive arithmetics"), 198 cl::init(32)); 199 200 static cl::opt<unsigned> MaxConstantEvolvingDepth( 201 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 203 204 static cl::opt<unsigned> 205 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 207 cl::init(8)); 208 209 static cl::opt<unsigned> 210 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 211 cl::desc("Max coefficients in AddRec during evolving"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 216 cl::desc("Size of the expression which is considered huge"), 217 cl::init(4096)); 218 219 //===----------------------------------------------------------------------===// 220 // SCEV class definitions 221 //===----------------------------------------------------------------------===// 222 223 //===----------------------------------------------------------------------===// 224 // Implementation of the SCEV class. 225 // 226 227 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 228 LLVM_DUMP_METHOD void SCEV::dump() const { 229 print(dbgs()); 230 dbgs() << '\n'; 231 } 232 #endif 233 234 void SCEV::print(raw_ostream &OS) const { 235 switch (static_cast<SCEVTypes>(getSCEVType())) { 236 case scConstant: 237 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 238 return; 239 case scTruncate: { 240 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 241 const SCEV *Op = Trunc->getOperand(); 242 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 243 << *Trunc->getType() << ")"; 244 return; 245 } 246 case scZeroExtend: { 247 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 248 const SCEV *Op = ZExt->getOperand(); 249 OS << "(zext " << *Op->getType() << " " << *Op << " to " 250 << *ZExt->getType() << ")"; 251 return; 252 } 253 case scSignExtend: { 254 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 255 const SCEV *Op = SExt->getOperand(); 256 OS << "(sext " << *Op->getType() << " " << *Op << " to " 257 << *SExt->getType() << ")"; 258 return; 259 } 260 case scAddRecExpr: { 261 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 262 OS << "{" << *AR->getOperand(0); 263 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 264 OS << ",+," << *AR->getOperand(i); 265 OS << "}<"; 266 if (AR->hasNoUnsignedWrap()) 267 OS << "nuw><"; 268 if (AR->hasNoSignedWrap()) 269 OS << "nsw><"; 270 if (AR->hasNoSelfWrap() && 271 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 272 OS << "nw><"; 273 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 274 OS << ">"; 275 return; 276 } 277 case scAddExpr: 278 case scMulExpr: 279 case scUMaxExpr: 280 case scSMaxExpr: { 281 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 282 const char *OpStr = nullptr; 283 switch (NAry->getSCEVType()) { 284 case scAddExpr: OpStr = " + "; break; 285 case scMulExpr: OpStr = " * "; break; 286 case scUMaxExpr: OpStr = " umax "; break; 287 case scSMaxExpr: OpStr = " smax "; break; 288 } 289 OS << "("; 290 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 291 I != E; ++I) { 292 OS << **I; 293 if (std::next(I) != E) 294 OS << OpStr; 295 } 296 OS << ")"; 297 switch (NAry->getSCEVType()) { 298 case scAddExpr: 299 case scMulExpr: 300 if (NAry->hasNoUnsignedWrap()) 301 OS << "<nuw>"; 302 if (NAry->hasNoSignedWrap()) 303 OS << "<nsw>"; 304 } 305 return; 306 } 307 case scUDivExpr: { 308 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 309 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 310 return; 311 } 312 case scUnknown: { 313 const SCEVUnknown *U = cast<SCEVUnknown>(this); 314 Type *AllocTy; 315 if (U->isSizeOf(AllocTy)) { 316 OS << "sizeof(" << *AllocTy << ")"; 317 return; 318 } 319 if (U->isAlignOf(AllocTy)) { 320 OS << "alignof(" << *AllocTy << ")"; 321 return; 322 } 323 324 Type *CTy; 325 Constant *FieldNo; 326 if (U->isOffsetOf(CTy, FieldNo)) { 327 OS << "offsetof(" << *CTy << ", "; 328 FieldNo->printAsOperand(OS, false); 329 OS << ")"; 330 return; 331 } 332 333 // Otherwise just print it normally. 334 U->getValue()->printAsOperand(OS, false); 335 return; 336 } 337 case scCouldNotCompute: 338 OS << "***COULDNOTCOMPUTE***"; 339 return; 340 } 341 llvm_unreachable("Unknown SCEV kind!"); 342 } 343 344 Type *SCEV::getType() const { 345 switch (static_cast<SCEVTypes>(getSCEVType())) { 346 case scConstant: 347 return cast<SCEVConstant>(this)->getType(); 348 case scTruncate: 349 case scZeroExtend: 350 case scSignExtend: 351 return cast<SCEVCastExpr>(this)->getType(); 352 case scAddRecExpr: 353 case scMulExpr: 354 case scUMaxExpr: 355 case scSMaxExpr: 356 return cast<SCEVNAryExpr>(this)->getType(); 357 case scAddExpr: 358 return cast<SCEVAddExpr>(this)->getType(); 359 case scUDivExpr: 360 return cast<SCEVUDivExpr>(this)->getType(); 361 case scUnknown: 362 return cast<SCEVUnknown>(this)->getType(); 363 case scCouldNotCompute: 364 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 365 } 366 llvm_unreachable("Unknown SCEV kind!"); 367 } 368 369 bool SCEV::isZero() const { 370 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 371 return SC->getValue()->isZero(); 372 return false; 373 } 374 375 bool SCEV::isOne() const { 376 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 377 return SC->getValue()->isOne(); 378 return false; 379 } 380 381 bool SCEV::isAllOnesValue() const { 382 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 383 return SC->getValue()->isMinusOne(); 384 return false; 385 } 386 387 bool SCEV::isNonConstantNegative() const { 388 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 389 if (!Mul) return false; 390 391 // If there is a constant factor, it will be first. 392 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 393 if (!SC) return false; 394 395 // Return true if the value is negative, this matches things like (-42 * V). 396 return SC->getAPInt().isNegative(); 397 } 398 399 SCEVCouldNotCompute::SCEVCouldNotCompute() : 400 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 401 402 bool SCEVCouldNotCompute::classof(const SCEV *S) { 403 return S->getSCEVType() == scCouldNotCompute; 404 } 405 406 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 407 FoldingSetNodeID ID; 408 ID.AddInteger(scConstant); 409 ID.AddPointer(V); 410 void *IP = nullptr; 411 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 412 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 413 UniqueSCEVs.InsertNode(S, IP); 414 return S; 415 } 416 417 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 418 return getConstant(ConstantInt::get(getContext(), Val)); 419 } 420 421 const SCEV * 422 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 423 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 424 return getConstant(ConstantInt::get(ITy, V, isSigned)); 425 } 426 427 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 428 unsigned SCEVTy, const SCEV *op, Type *ty) 429 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 430 431 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 432 const SCEV *op, Type *ty) 433 : SCEVCastExpr(ID, scTruncate, op, ty) { 434 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 435 "Cannot truncate non-integer value!"); 436 } 437 438 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 439 const SCEV *op, Type *ty) 440 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 441 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 442 "Cannot zero extend non-integer value!"); 443 } 444 445 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 446 const SCEV *op, Type *ty) 447 : SCEVCastExpr(ID, scSignExtend, op, ty) { 448 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 449 "Cannot sign extend non-integer value!"); 450 } 451 452 void SCEVUnknown::deleted() { 453 // Clear this SCEVUnknown from various maps. 454 SE->forgetMemoizedResults(this); 455 456 // Remove this SCEVUnknown from the uniquing map. 457 SE->UniqueSCEVs.RemoveNode(this); 458 459 // Release the value. 460 setValPtr(nullptr); 461 } 462 463 void SCEVUnknown::allUsesReplacedWith(Value *New) { 464 // Remove this SCEVUnknown from the uniquing map. 465 SE->UniqueSCEVs.RemoveNode(this); 466 467 // Update this SCEVUnknown to point to the new value. This is needed 468 // because there may still be outstanding SCEVs which still point to 469 // this SCEVUnknown. 470 setValPtr(New); 471 } 472 473 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 474 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 475 if (VCE->getOpcode() == Instruction::PtrToInt) 476 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 477 if (CE->getOpcode() == Instruction::GetElementPtr && 478 CE->getOperand(0)->isNullValue() && 479 CE->getNumOperands() == 2) 480 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 481 if (CI->isOne()) { 482 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 483 ->getElementType(); 484 return true; 485 } 486 487 return false; 488 } 489 490 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 491 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 492 if (VCE->getOpcode() == Instruction::PtrToInt) 493 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 494 if (CE->getOpcode() == Instruction::GetElementPtr && 495 CE->getOperand(0)->isNullValue()) { 496 Type *Ty = 497 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 498 if (StructType *STy = dyn_cast<StructType>(Ty)) 499 if (!STy->isPacked() && 500 CE->getNumOperands() == 3 && 501 CE->getOperand(1)->isNullValue()) { 502 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 503 if (CI->isOne() && 504 STy->getNumElements() == 2 && 505 STy->getElementType(0)->isIntegerTy(1)) { 506 AllocTy = STy->getElementType(1); 507 return true; 508 } 509 } 510 } 511 512 return false; 513 } 514 515 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 516 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 517 if (VCE->getOpcode() == Instruction::PtrToInt) 518 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 519 if (CE->getOpcode() == Instruction::GetElementPtr && 520 CE->getNumOperands() == 3 && 521 CE->getOperand(0)->isNullValue() && 522 CE->getOperand(1)->isNullValue()) { 523 Type *Ty = 524 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 525 // Ignore vector types here so that ScalarEvolutionExpander doesn't 526 // emit getelementptrs that index into vectors. 527 if (Ty->isStructTy() || Ty->isArrayTy()) { 528 CTy = Ty; 529 FieldNo = CE->getOperand(2); 530 return true; 531 } 532 } 533 534 return false; 535 } 536 537 //===----------------------------------------------------------------------===// 538 // SCEV Utilities 539 //===----------------------------------------------------------------------===// 540 541 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 542 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 543 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 544 /// have been previously deemed to be "equally complex" by this routine. It is 545 /// intended to avoid exponential time complexity in cases like: 546 /// 547 /// %a = f(%x, %y) 548 /// %b = f(%a, %a) 549 /// %c = f(%b, %b) 550 /// 551 /// %d = f(%x, %y) 552 /// %e = f(%d, %d) 553 /// %f = f(%e, %e) 554 /// 555 /// CompareValueComplexity(%f, %c) 556 /// 557 /// Since we do not continue running this routine on expression trees once we 558 /// have seen unequal values, there is no need to track them in the cache. 559 static int 560 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 561 const LoopInfo *const LI, Value *LV, Value *RV, 562 unsigned Depth) { 563 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 564 return 0; 565 566 // Order pointer values after integer values. This helps SCEVExpander form 567 // GEPs. 568 bool LIsPointer = LV->getType()->isPointerTy(), 569 RIsPointer = RV->getType()->isPointerTy(); 570 if (LIsPointer != RIsPointer) 571 return (int)LIsPointer - (int)RIsPointer; 572 573 // Compare getValueID values. 574 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 575 if (LID != RID) 576 return (int)LID - (int)RID; 577 578 // Sort arguments by their position. 579 if (const auto *LA = dyn_cast<Argument>(LV)) { 580 const auto *RA = cast<Argument>(RV); 581 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 582 return (int)LArgNo - (int)RArgNo; 583 } 584 585 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 586 const auto *RGV = cast<GlobalValue>(RV); 587 588 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 589 auto LT = GV->getLinkage(); 590 return !(GlobalValue::isPrivateLinkage(LT) || 591 GlobalValue::isInternalLinkage(LT)); 592 }; 593 594 // Use the names to distinguish the two values, but only if the 595 // names are semantically important. 596 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 597 return LGV->getName().compare(RGV->getName()); 598 } 599 600 // For instructions, compare their loop depth, and their operand count. This 601 // is pretty loose. 602 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 603 const auto *RInst = cast<Instruction>(RV); 604 605 // Compare loop depths. 606 const BasicBlock *LParent = LInst->getParent(), 607 *RParent = RInst->getParent(); 608 if (LParent != RParent) { 609 unsigned LDepth = LI->getLoopDepth(LParent), 610 RDepth = LI->getLoopDepth(RParent); 611 if (LDepth != RDepth) 612 return (int)LDepth - (int)RDepth; 613 } 614 615 // Compare the number of operands. 616 unsigned LNumOps = LInst->getNumOperands(), 617 RNumOps = RInst->getNumOperands(); 618 if (LNumOps != RNumOps) 619 return (int)LNumOps - (int)RNumOps; 620 621 for (unsigned Idx : seq(0u, LNumOps)) { 622 int Result = 623 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 624 RInst->getOperand(Idx), Depth + 1); 625 if (Result != 0) 626 return Result; 627 } 628 } 629 630 EqCacheValue.unionSets(LV, RV); 631 return 0; 632 } 633 634 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 635 // than RHS, respectively. A three-way result allows recursive comparisons to be 636 // more efficient. 637 static int CompareSCEVComplexity( 638 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 639 EquivalenceClasses<const Value *> &EqCacheValue, 640 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 641 DominatorTree &DT, unsigned Depth = 0) { 642 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 643 if (LHS == RHS) 644 return 0; 645 646 // Primarily, sort the SCEVs by their getSCEVType(). 647 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 648 if (LType != RType) 649 return (int)LType - (int)RType; 650 651 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 652 return 0; 653 // Aside from the getSCEVType() ordering, the particular ordering 654 // isn't very important except that it's beneficial to be consistent, 655 // so that (a + b) and (b + a) don't end up as different expressions. 656 switch (static_cast<SCEVTypes>(LType)) { 657 case scUnknown: { 658 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 659 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 660 661 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 662 RU->getValue(), Depth + 1); 663 if (X == 0) 664 EqCacheSCEV.unionSets(LHS, RHS); 665 return X; 666 } 667 668 case scConstant: { 669 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 670 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 671 672 // Compare constant values. 673 const APInt &LA = LC->getAPInt(); 674 const APInt &RA = RC->getAPInt(); 675 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 676 if (LBitWidth != RBitWidth) 677 return (int)LBitWidth - (int)RBitWidth; 678 return LA.ult(RA) ? -1 : 1; 679 } 680 681 case scAddRecExpr: { 682 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 683 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 684 685 // There is always a dominance between two recs that are used by one SCEV, 686 // so we can safely sort recs by loop header dominance. We require such 687 // order in getAddExpr. 688 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 689 if (LLoop != RLoop) { 690 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 691 assert(LHead != RHead && "Two loops share the same header?"); 692 if (DT.dominates(LHead, RHead)) 693 return 1; 694 else 695 assert(DT.dominates(RHead, LHead) && 696 "No dominance between recurrences used by one SCEV?"); 697 return -1; 698 } 699 700 // Addrec complexity grows with operand count. 701 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 702 if (LNumOps != RNumOps) 703 return (int)LNumOps - (int)RNumOps; 704 705 // Lexicographically compare. 706 for (unsigned i = 0; i != LNumOps; ++i) { 707 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 708 LA->getOperand(i), RA->getOperand(i), DT, 709 Depth + 1); 710 if (X != 0) 711 return X; 712 } 713 EqCacheSCEV.unionSets(LHS, RHS); 714 return 0; 715 } 716 717 case scAddExpr: 718 case scMulExpr: 719 case scSMaxExpr: 720 case scUMaxExpr: { 721 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 722 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 723 724 // Lexicographically compare n-ary expressions. 725 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 726 if (LNumOps != RNumOps) 727 return (int)LNumOps - (int)RNumOps; 728 729 for (unsigned i = 0; i != LNumOps; ++i) { 730 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 731 LC->getOperand(i), RC->getOperand(i), DT, 732 Depth + 1); 733 if (X != 0) 734 return X; 735 } 736 EqCacheSCEV.unionSets(LHS, RHS); 737 return 0; 738 } 739 740 case scUDivExpr: { 741 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 742 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 743 744 // Lexicographically compare udiv expressions. 745 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 746 RC->getLHS(), DT, Depth + 1); 747 if (X != 0) 748 return X; 749 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 750 RC->getRHS(), DT, Depth + 1); 751 if (X == 0) 752 EqCacheSCEV.unionSets(LHS, RHS); 753 return X; 754 } 755 756 case scTruncate: 757 case scZeroExtend: 758 case scSignExtend: { 759 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 760 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 761 762 // Compare cast expressions by operand. 763 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 764 LC->getOperand(), RC->getOperand(), DT, 765 Depth + 1); 766 if (X == 0) 767 EqCacheSCEV.unionSets(LHS, RHS); 768 return X; 769 } 770 771 case scCouldNotCompute: 772 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 773 } 774 llvm_unreachable("Unknown SCEV kind!"); 775 } 776 777 /// Given a list of SCEV objects, order them by their complexity, and group 778 /// objects of the same complexity together by value. When this routine is 779 /// finished, we know that any duplicates in the vector are consecutive and that 780 /// complexity is monotonically increasing. 781 /// 782 /// Note that we go take special precautions to ensure that we get deterministic 783 /// results from this routine. In other words, we don't want the results of 784 /// this to depend on where the addresses of various SCEV objects happened to 785 /// land in memory. 786 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 787 LoopInfo *LI, DominatorTree &DT) { 788 if (Ops.size() < 2) return; // Noop 789 790 EquivalenceClasses<const SCEV *> EqCacheSCEV; 791 EquivalenceClasses<const Value *> EqCacheValue; 792 if (Ops.size() == 2) { 793 // This is the common case, which also happens to be trivially simple. 794 // Special case it. 795 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 796 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 797 std::swap(LHS, RHS); 798 return; 799 } 800 801 // Do the rough sort by complexity. 802 std::stable_sort(Ops.begin(), Ops.end(), 803 [&](const SCEV *LHS, const SCEV *RHS) { 804 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 805 LHS, RHS, DT) < 0; 806 }); 807 808 // Now that we are sorted by complexity, group elements of the same 809 // complexity. Note that this is, at worst, N^2, but the vector is likely to 810 // be extremely short in practice. Note that we take this approach because we 811 // do not want to depend on the addresses of the objects we are grouping. 812 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 813 const SCEV *S = Ops[i]; 814 unsigned Complexity = S->getSCEVType(); 815 816 // If there are any objects of the same complexity and same value as this 817 // one, group them. 818 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 819 if (Ops[j] == S) { // Found a duplicate. 820 // Move it to immediately after i'th element. 821 std::swap(Ops[i+1], Ops[j]); 822 ++i; // no need to rescan it. 823 if (i == e-2) return; // Done! 824 } 825 } 826 } 827 } 828 829 // Returns the size of the SCEV S. 830 static inline int sizeOfSCEV(const SCEV *S) { 831 struct FindSCEVSize { 832 int Size = 0; 833 834 FindSCEVSize() = default; 835 836 bool follow(const SCEV *S) { 837 ++Size; 838 // Keep looking at all operands of S. 839 return true; 840 } 841 842 bool isDone() const { 843 return false; 844 } 845 }; 846 847 FindSCEVSize F; 848 SCEVTraversal<FindSCEVSize> ST(F); 849 ST.visitAll(S); 850 return F.Size; 851 } 852 853 /// Returns true if the subtree of \p S contains at least HugeExprThreshold 854 /// nodes. 855 static bool isHugeExpression(const SCEV *S) { 856 return S->getExpressionSize() >= HugeExprThreshold; 857 } 858 859 /// Returns true of \p Ops contains a huge SCEV (see definition above). 860 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 861 return any_of(Ops, isHugeExpression); 862 } 863 864 namespace { 865 866 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 867 public: 868 // Computes the Quotient and Remainder of the division of Numerator by 869 // Denominator. 870 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 871 const SCEV *Denominator, const SCEV **Quotient, 872 const SCEV **Remainder) { 873 assert(Numerator && Denominator && "Uninitialized SCEV"); 874 875 SCEVDivision D(SE, Numerator, Denominator); 876 877 // Check for the trivial case here to avoid having to check for it in the 878 // rest of the code. 879 if (Numerator == Denominator) { 880 *Quotient = D.One; 881 *Remainder = D.Zero; 882 return; 883 } 884 885 if (Numerator->isZero()) { 886 *Quotient = D.Zero; 887 *Remainder = D.Zero; 888 return; 889 } 890 891 // A simple case when N/1. The quotient is N. 892 if (Denominator->isOne()) { 893 *Quotient = Numerator; 894 *Remainder = D.Zero; 895 return; 896 } 897 898 // Split the Denominator when it is a product. 899 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 900 const SCEV *Q, *R; 901 *Quotient = Numerator; 902 for (const SCEV *Op : T->operands()) { 903 divide(SE, *Quotient, Op, &Q, &R); 904 *Quotient = Q; 905 906 // Bail out when the Numerator is not divisible by one of the terms of 907 // the Denominator. 908 if (!R->isZero()) { 909 *Quotient = D.Zero; 910 *Remainder = Numerator; 911 return; 912 } 913 } 914 *Remainder = D.Zero; 915 return; 916 } 917 918 D.visit(Numerator); 919 *Quotient = D.Quotient; 920 *Remainder = D.Remainder; 921 } 922 923 // Except in the trivial case described above, we do not know how to divide 924 // Expr by Denominator for the following functions with empty implementation. 925 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 926 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 927 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 928 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 929 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 930 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 931 void visitUnknown(const SCEVUnknown *Numerator) {} 932 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 933 934 void visitConstant(const SCEVConstant *Numerator) { 935 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 936 APInt NumeratorVal = Numerator->getAPInt(); 937 APInt DenominatorVal = D->getAPInt(); 938 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 939 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 940 941 if (NumeratorBW > DenominatorBW) 942 DenominatorVal = DenominatorVal.sext(NumeratorBW); 943 else if (NumeratorBW < DenominatorBW) 944 NumeratorVal = NumeratorVal.sext(DenominatorBW); 945 946 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 947 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 948 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 949 Quotient = SE.getConstant(QuotientVal); 950 Remainder = SE.getConstant(RemainderVal); 951 return; 952 } 953 } 954 955 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 956 const SCEV *StartQ, *StartR, *StepQ, *StepR; 957 if (!Numerator->isAffine()) 958 return cannotDivide(Numerator); 959 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 960 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 961 // Bail out if the types do not match. 962 Type *Ty = Denominator->getType(); 963 if (Ty != StartQ->getType() || Ty != StartR->getType() || 964 Ty != StepQ->getType() || Ty != StepR->getType()) 965 return cannotDivide(Numerator); 966 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 967 Numerator->getNoWrapFlags()); 968 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 969 Numerator->getNoWrapFlags()); 970 } 971 972 void visitAddExpr(const SCEVAddExpr *Numerator) { 973 SmallVector<const SCEV *, 2> Qs, Rs; 974 Type *Ty = Denominator->getType(); 975 976 for (const SCEV *Op : Numerator->operands()) { 977 const SCEV *Q, *R; 978 divide(SE, Op, Denominator, &Q, &R); 979 980 // Bail out if types do not match. 981 if (Ty != Q->getType() || Ty != R->getType()) 982 return cannotDivide(Numerator); 983 984 Qs.push_back(Q); 985 Rs.push_back(R); 986 } 987 988 if (Qs.size() == 1) { 989 Quotient = Qs[0]; 990 Remainder = Rs[0]; 991 return; 992 } 993 994 Quotient = SE.getAddExpr(Qs); 995 Remainder = SE.getAddExpr(Rs); 996 } 997 998 void visitMulExpr(const SCEVMulExpr *Numerator) { 999 SmallVector<const SCEV *, 2> Qs; 1000 Type *Ty = Denominator->getType(); 1001 1002 bool FoundDenominatorTerm = false; 1003 for (const SCEV *Op : Numerator->operands()) { 1004 // Bail out if types do not match. 1005 if (Ty != Op->getType()) 1006 return cannotDivide(Numerator); 1007 1008 if (FoundDenominatorTerm) { 1009 Qs.push_back(Op); 1010 continue; 1011 } 1012 1013 // Check whether Denominator divides one of the product operands. 1014 const SCEV *Q, *R; 1015 divide(SE, Op, Denominator, &Q, &R); 1016 if (!R->isZero()) { 1017 Qs.push_back(Op); 1018 continue; 1019 } 1020 1021 // Bail out if types do not match. 1022 if (Ty != Q->getType()) 1023 return cannotDivide(Numerator); 1024 1025 FoundDenominatorTerm = true; 1026 Qs.push_back(Q); 1027 } 1028 1029 if (FoundDenominatorTerm) { 1030 Remainder = Zero; 1031 if (Qs.size() == 1) 1032 Quotient = Qs[0]; 1033 else 1034 Quotient = SE.getMulExpr(Qs); 1035 return; 1036 } 1037 1038 if (!isa<SCEVUnknown>(Denominator)) 1039 return cannotDivide(Numerator); 1040 1041 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1042 ValueToValueMap RewriteMap; 1043 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1044 cast<SCEVConstant>(Zero)->getValue(); 1045 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1046 1047 if (Remainder->isZero()) { 1048 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1049 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1050 cast<SCEVConstant>(One)->getValue(); 1051 Quotient = 1052 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1053 return; 1054 } 1055 1056 // Quotient is (Numerator - Remainder) divided by Denominator. 1057 const SCEV *Q, *R; 1058 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1059 // This SCEV does not seem to simplify: fail the division here. 1060 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1061 return cannotDivide(Numerator); 1062 divide(SE, Diff, Denominator, &Q, &R); 1063 if (R != Zero) 1064 return cannotDivide(Numerator); 1065 Quotient = Q; 1066 } 1067 1068 private: 1069 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1070 const SCEV *Denominator) 1071 : SE(S), Denominator(Denominator) { 1072 Zero = SE.getZero(Denominator->getType()); 1073 One = SE.getOne(Denominator->getType()); 1074 1075 // We generally do not know how to divide Expr by Denominator. We 1076 // initialize the division to a "cannot divide" state to simplify the rest 1077 // of the code. 1078 cannotDivide(Numerator); 1079 } 1080 1081 // Convenience function for giving up on the division. We set the quotient to 1082 // be equal to zero and the remainder to be equal to the numerator. 1083 void cannotDivide(const SCEV *Numerator) { 1084 Quotient = Zero; 1085 Remainder = Numerator; 1086 } 1087 1088 ScalarEvolution &SE; 1089 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1090 }; 1091 1092 } // end anonymous namespace 1093 1094 //===----------------------------------------------------------------------===// 1095 // Simple SCEV method implementations 1096 //===----------------------------------------------------------------------===// 1097 1098 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1099 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1100 ScalarEvolution &SE, 1101 Type *ResultTy) { 1102 // Handle the simplest case efficiently. 1103 if (K == 1) 1104 return SE.getTruncateOrZeroExtend(It, ResultTy); 1105 1106 // We are using the following formula for BC(It, K): 1107 // 1108 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1109 // 1110 // Suppose, W is the bitwidth of the return value. We must be prepared for 1111 // overflow. Hence, we must assure that the result of our computation is 1112 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1113 // safe in modular arithmetic. 1114 // 1115 // However, this code doesn't use exactly that formula; the formula it uses 1116 // is something like the following, where T is the number of factors of 2 in 1117 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1118 // exponentiation: 1119 // 1120 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1121 // 1122 // This formula is trivially equivalent to the previous formula. However, 1123 // this formula can be implemented much more efficiently. The trick is that 1124 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1125 // arithmetic. To do exact division in modular arithmetic, all we have 1126 // to do is multiply by the inverse. Therefore, this step can be done at 1127 // width W. 1128 // 1129 // The next issue is how to safely do the division by 2^T. The way this 1130 // is done is by doing the multiplication step at a width of at least W + T 1131 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1132 // when we perform the division by 2^T (which is equivalent to a right shift 1133 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1134 // truncated out after the division by 2^T. 1135 // 1136 // In comparison to just directly using the first formula, this technique 1137 // is much more efficient; using the first formula requires W * K bits, 1138 // but this formula less than W + K bits. Also, the first formula requires 1139 // a division step, whereas this formula only requires multiplies and shifts. 1140 // 1141 // It doesn't matter whether the subtraction step is done in the calculation 1142 // width or the input iteration count's width; if the subtraction overflows, 1143 // the result must be zero anyway. We prefer here to do it in the width of 1144 // the induction variable because it helps a lot for certain cases; CodeGen 1145 // isn't smart enough to ignore the overflow, which leads to much less 1146 // efficient code if the width of the subtraction is wider than the native 1147 // register width. 1148 // 1149 // (It's possible to not widen at all by pulling out factors of 2 before 1150 // the multiplication; for example, K=2 can be calculated as 1151 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1152 // extra arithmetic, so it's not an obvious win, and it gets 1153 // much more complicated for K > 3.) 1154 1155 // Protection from insane SCEVs; this bound is conservative, 1156 // but it probably doesn't matter. 1157 if (K > 1000) 1158 return SE.getCouldNotCompute(); 1159 1160 unsigned W = SE.getTypeSizeInBits(ResultTy); 1161 1162 // Calculate K! / 2^T and T; we divide out the factors of two before 1163 // multiplying for calculating K! / 2^T to avoid overflow. 1164 // Other overflow doesn't matter because we only care about the bottom 1165 // W bits of the result. 1166 APInt OddFactorial(W, 1); 1167 unsigned T = 1; 1168 for (unsigned i = 3; i <= K; ++i) { 1169 APInt Mult(W, i); 1170 unsigned TwoFactors = Mult.countTrailingZeros(); 1171 T += TwoFactors; 1172 Mult.lshrInPlace(TwoFactors); 1173 OddFactorial *= Mult; 1174 } 1175 1176 // We need at least W + T bits for the multiplication step 1177 unsigned CalculationBits = W + T; 1178 1179 // Calculate 2^T, at width T+W. 1180 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1181 1182 // Calculate the multiplicative inverse of K! / 2^T; 1183 // this multiplication factor will perform the exact division by 1184 // K! / 2^T. 1185 APInt Mod = APInt::getSignedMinValue(W+1); 1186 APInt MultiplyFactor = OddFactorial.zext(W+1); 1187 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1188 MultiplyFactor = MultiplyFactor.trunc(W); 1189 1190 // Calculate the product, at width T+W 1191 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1192 CalculationBits); 1193 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1194 for (unsigned i = 1; i != K; ++i) { 1195 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1196 Dividend = SE.getMulExpr(Dividend, 1197 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1198 } 1199 1200 // Divide by 2^T 1201 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1202 1203 // Truncate the result, and divide by K! / 2^T. 1204 1205 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1206 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1207 } 1208 1209 /// Return the value of this chain of recurrences at the specified iteration 1210 /// number. We can evaluate this recurrence by multiplying each element in the 1211 /// chain by the binomial coefficient corresponding to it. In other words, we 1212 /// can evaluate {A,+,B,+,C,+,D} as: 1213 /// 1214 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1215 /// 1216 /// where BC(It, k) stands for binomial coefficient. 1217 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1218 ScalarEvolution &SE) const { 1219 const SCEV *Result = getStart(); 1220 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1221 // The computation is correct in the face of overflow provided that the 1222 // multiplication is performed _after_ the evaluation of the binomial 1223 // coefficient. 1224 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1225 if (isa<SCEVCouldNotCompute>(Coeff)) 1226 return Coeff; 1227 1228 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1229 } 1230 return Result; 1231 } 1232 1233 //===----------------------------------------------------------------------===// 1234 // SCEV Expression folder implementations 1235 //===----------------------------------------------------------------------===// 1236 1237 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1238 unsigned Depth) { 1239 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1240 "This is not a truncating conversion!"); 1241 assert(isSCEVable(Ty) && 1242 "This is not a conversion to a SCEVable type!"); 1243 Ty = getEffectiveSCEVType(Ty); 1244 1245 FoldingSetNodeID ID; 1246 ID.AddInteger(scTruncate); 1247 ID.AddPointer(Op); 1248 ID.AddPointer(Ty); 1249 void *IP = nullptr; 1250 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1251 1252 // Fold if the operand is constant. 1253 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1254 return getConstant( 1255 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1256 1257 // trunc(trunc(x)) --> trunc(x) 1258 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1259 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1260 1261 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1262 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1263 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1264 1265 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1266 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1267 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1268 1269 if (Depth > MaxCastDepth) { 1270 SCEV *S = 1271 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1272 UniqueSCEVs.InsertNode(S, IP); 1273 addToLoopUseLists(S); 1274 return S; 1275 } 1276 1277 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1278 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1279 // if after transforming we have at most one truncate, not counting truncates 1280 // that replace other casts. 1281 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1282 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1283 SmallVector<const SCEV *, 4> Operands; 1284 unsigned numTruncs = 0; 1285 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1286 ++i) { 1287 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1288 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1289 numTruncs++; 1290 Operands.push_back(S); 1291 } 1292 if (numTruncs < 2) { 1293 if (isa<SCEVAddExpr>(Op)) 1294 return getAddExpr(Operands); 1295 else if (isa<SCEVMulExpr>(Op)) 1296 return getMulExpr(Operands); 1297 else 1298 llvm_unreachable("Unexpected SCEV type for Op."); 1299 } 1300 // Although we checked in the beginning that ID is not in the cache, it is 1301 // possible that during recursion and different modification ID was inserted 1302 // into the cache. So if we find it, just return it. 1303 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1304 return S; 1305 } 1306 1307 // If the input value is a chrec scev, truncate the chrec's operands. 1308 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1309 SmallVector<const SCEV *, 4> Operands; 1310 for (const SCEV *Op : AddRec->operands()) 1311 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1312 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1313 } 1314 1315 // The cast wasn't folded; create an explicit cast node. We can reuse 1316 // the existing insert position since if we get here, we won't have 1317 // made any changes which would invalidate it. 1318 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1319 Op, Ty); 1320 UniqueSCEVs.InsertNode(S, IP); 1321 addToLoopUseLists(S); 1322 return S; 1323 } 1324 1325 // Get the limit of a recurrence such that incrementing by Step cannot cause 1326 // signed overflow as long as the value of the recurrence within the 1327 // loop does not exceed this limit before incrementing. 1328 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1329 ICmpInst::Predicate *Pred, 1330 ScalarEvolution *SE) { 1331 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1332 if (SE->isKnownPositive(Step)) { 1333 *Pred = ICmpInst::ICMP_SLT; 1334 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1335 SE->getSignedRangeMax(Step)); 1336 } 1337 if (SE->isKnownNegative(Step)) { 1338 *Pred = ICmpInst::ICMP_SGT; 1339 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1340 SE->getSignedRangeMin(Step)); 1341 } 1342 return nullptr; 1343 } 1344 1345 // Get the limit of a recurrence such that incrementing by Step cannot cause 1346 // unsigned overflow as long as the value of the recurrence within the loop does 1347 // not exceed this limit before incrementing. 1348 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1349 ICmpInst::Predicate *Pred, 1350 ScalarEvolution *SE) { 1351 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1352 *Pred = ICmpInst::ICMP_ULT; 1353 1354 return SE->getConstant(APInt::getMinValue(BitWidth) - 1355 SE->getUnsignedRangeMax(Step)); 1356 } 1357 1358 namespace { 1359 1360 struct ExtendOpTraitsBase { 1361 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1362 unsigned); 1363 }; 1364 1365 // Used to make code generic over signed and unsigned overflow. 1366 template <typename ExtendOp> struct ExtendOpTraits { 1367 // Members present: 1368 // 1369 // static const SCEV::NoWrapFlags WrapType; 1370 // 1371 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1372 // 1373 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1374 // ICmpInst::Predicate *Pred, 1375 // ScalarEvolution *SE); 1376 }; 1377 1378 template <> 1379 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1380 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1381 1382 static const GetExtendExprTy GetExtendExpr; 1383 1384 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1385 ICmpInst::Predicate *Pred, 1386 ScalarEvolution *SE) { 1387 return getSignedOverflowLimitForStep(Step, Pred, SE); 1388 } 1389 }; 1390 1391 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1392 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1393 1394 template <> 1395 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1396 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1397 1398 static const GetExtendExprTy GetExtendExpr; 1399 1400 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1401 ICmpInst::Predicate *Pred, 1402 ScalarEvolution *SE) { 1403 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1404 } 1405 }; 1406 1407 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1408 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1409 1410 } // end anonymous namespace 1411 1412 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1413 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1414 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1415 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1416 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1417 // expression "Step + sext/zext(PreIncAR)" is congruent with 1418 // "sext/zext(PostIncAR)" 1419 template <typename ExtendOpTy> 1420 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1421 ScalarEvolution *SE, unsigned Depth) { 1422 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1423 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1424 1425 const Loop *L = AR->getLoop(); 1426 const SCEV *Start = AR->getStart(); 1427 const SCEV *Step = AR->getStepRecurrence(*SE); 1428 1429 // Check for a simple looking step prior to loop entry. 1430 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1431 if (!SA) 1432 return nullptr; 1433 1434 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1435 // subtraction is expensive. For this purpose, perform a quick and dirty 1436 // difference, by checking for Step in the operand list. 1437 SmallVector<const SCEV *, 4> DiffOps; 1438 for (const SCEV *Op : SA->operands()) 1439 if (Op != Step) 1440 DiffOps.push_back(Op); 1441 1442 if (DiffOps.size() == SA->getNumOperands()) 1443 return nullptr; 1444 1445 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1446 // `Step`: 1447 1448 // 1. NSW/NUW flags on the step increment. 1449 auto PreStartFlags = 1450 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1451 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1452 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1453 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1454 1455 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1456 // "S+X does not sign/unsign-overflow". 1457 // 1458 1459 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1460 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1461 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1462 return PreStart; 1463 1464 // 2. Direct overflow check on the step operation's expression. 1465 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1466 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1467 const SCEV *OperandExtendedStart = 1468 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1469 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1470 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1471 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1472 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1473 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1474 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1475 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1476 } 1477 return PreStart; 1478 } 1479 1480 // 3. Loop precondition. 1481 ICmpInst::Predicate Pred; 1482 const SCEV *OverflowLimit = 1483 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1484 1485 if (OverflowLimit && 1486 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1487 return PreStart; 1488 1489 return nullptr; 1490 } 1491 1492 // Get the normalized zero or sign extended expression for this AddRec's Start. 1493 template <typename ExtendOpTy> 1494 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1495 ScalarEvolution *SE, 1496 unsigned Depth) { 1497 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1498 1499 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1500 if (!PreStart) 1501 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1502 1503 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1504 Depth), 1505 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1506 } 1507 1508 // Try to prove away overflow by looking at "nearby" add recurrences. A 1509 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1510 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1511 // 1512 // Formally: 1513 // 1514 // {S,+,X} == {S-T,+,X} + T 1515 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1516 // 1517 // If ({S-T,+,X} + T) does not overflow ... (1) 1518 // 1519 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1520 // 1521 // If {S-T,+,X} does not overflow ... (2) 1522 // 1523 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1524 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1525 // 1526 // If (S-T)+T does not overflow ... (3) 1527 // 1528 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1529 // == {Ext(S),+,Ext(X)} == LHS 1530 // 1531 // Thus, if (1), (2) and (3) are true for some T, then 1532 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1533 // 1534 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1535 // does not overflow" restricted to the 0th iteration. Therefore we only need 1536 // to check for (1) and (2). 1537 // 1538 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1539 // is `Delta` (defined below). 1540 template <typename ExtendOpTy> 1541 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1542 const SCEV *Step, 1543 const Loop *L) { 1544 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1545 1546 // We restrict `Start` to a constant to prevent SCEV from spending too much 1547 // time here. It is correct (but more expensive) to continue with a 1548 // non-constant `Start` and do a general SCEV subtraction to compute 1549 // `PreStart` below. 1550 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1551 if (!StartC) 1552 return false; 1553 1554 APInt StartAI = StartC->getAPInt(); 1555 1556 for (unsigned Delta : {-2, -1, 1, 2}) { 1557 const SCEV *PreStart = getConstant(StartAI - Delta); 1558 1559 FoldingSetNodeID ID; 1560 ID.AddInteger(scAddRecExpr); 1561 ID.AddPointer(PreStart); 1562 ID.AddPointer(Step); 1563 ID.AddPointer(L); 1564 void *IP = nullptr; 1565 const auto *PreAR = 1566 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1567 1568 // Give up if we don't already have the add recurrence we need because 1569 // actually constructing an add recurrence is relatively expensive. 1570 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1571 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1572 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1573 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1574 DeltaS, &Pred, this); 1575 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1576 return true; 1577 } 1578 } 1579 1580 return false; 1581 } 1582 1583 // Finds an integer D for an expression (C + x + y + ...) such that the top 1584 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1585 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1586 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1587 // the (C + x + y + ...) expression is \p WholeAddExpr. 1588 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1589 const SCEVConstant *ConstantTerm, 1590 const SCEVAddExpr *WholeAddExpr) { 1591 const APInt C = ConstantTerm->getAPInt(); 1592 const unsigned BitWidth = C.getBitWidth(); 1593 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1594 uint32_t TZ = BitWidth; 1595 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1596 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1597 if (TZ) { 1598 // Set D to be as many least significant bits of C as possible while still 1599 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1600 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1601 } 1602 return APInt(BitWidth, 0); 1603 } 1604 1605 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1606 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1607 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1608 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1609 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1610 const APInt &ConstantStart, 1611 const SCEV *Step) { 1612 const unsigned BitWidth = ConstantStart.getBitWidth(); 1613 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1614 if (TZ) 1615 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1616 : ConstantStart; 1617 return APInt(BitWidth, 0); 1618 } 1619 1620 const SCEV * 1621 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1622 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1623 "This is not an extending conversion!"); 1624 assert(isSCEVable(Ty) && 1625 "This is not a conversion to a SCEVable type!"); 1626 Ty = getEffectiveSCEVType(Ty); 1627 1628 // Fold if the operand is constant. 1629 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1630 return getConstant( 1631 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1632 1633 // zext(zext(x)) --> zext(x) 1634 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1635 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1636 1637 // Before doing any expensive analysis, check to see if we've already 1638 // computed a SCEV for this Op and Ty. 1639 FoldingSetNodeID ID; 1640 ID.AddInteger(scZeroExtend); 1641 ID.AddPointer(Op); 1642 ID.AddPointer(Ty); 1643 void *IP = nullptr; 1644 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1645 if (Depth > MaxCastDepth) { 1646 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1647 Op, Ty); 1648 UniqueSCEVs.InsertNode(S, IP); 1649 addToLoopUseLists(S); 1650 return S; 1651 } 1652 1653 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1654 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1655 // It's possible the bits taken off by the truncate were all zero bits. If 1656 // so, we should be able to simplify this further. 1657 const SCEV *X = ST->getOperand(); 1658 ConstantRange CR = getUnsignedRange(X); 1659 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1660 unsigned NewBits = getTypeSizeInBits(Ty); 1661 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1662 CR.zextOrTrunc(NewBits))) 1663 return getTruncateOrZeroExtend(X, Ty, Depth); 1664 } 1665 1666 // If the input value is a chrec scev, and we can prove that the value 1667 // did not overflow the old, smaller, value, we can zero extend all of the 1668 // operands (often constants). This allows analysis of something like 1669 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1670 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1671 if (AR->isAffine()) { 1672 const SCEV *Start = AR->getStart(); 1673 const SCEV *Step = AR->getStepRecurrence(*this); 1674 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1675 const Loop *L = AR->getLoop(); 1676 1677 if (!AR->hasNoUnsignedWrap()) { 1678 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1679 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1680 } 1681 1682 // If we have special knowledge that this addrec won't overflow, 1683 // we don't need to do any further analysis. 1684 if (AR->hasNoUnsignedWrap()) 1685 return getAddRecExpr( 1686 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1687 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1688 1689 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1690 // Note that this serves two purposes: It filters out loops that are 1691 // simply not analyzable, and it covers the case where this code is 1692 // being called from within backedge-taken count analysis, such that 1693 // attempting to ask for the backedge-taken count would likely result 1694 // in infinite recursion. In the later case, the analysis code will 1695 // cope with a conservative value, and it will take care to purge 1696 // that value once it has finished. 1697 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1698 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1699 // Manually compute the final value for AR, checking for 1700 // overflow. 1701 1702 // Check whether the backedge-taken count can be losslessly casted to 1703 // the addrec's type. The count is always unsigned. 1704 const SCEV *CastedMaxBECount = 1705 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1706 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1707 CastedMaxBECount, MaxBECount->getType(), Depth); 1708 if (MaxBECount == RecastedMaxBECount) { 1709 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1710 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1711 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1712 SCEV::FlagAnyWrap, Depth + 1); 1713 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1714 SCEV::FlagAnyWrap, 1715 Depth + 1), 1716 WideTy, Depth + 1); 1717 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1718 const SCEV *WideMaxBECount = 1719 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1720 const SCEV *OperandExtendedAdd = 1721 getAddExpr(WideStart, 1722 getMulExpr(WideMaxBECount, 1723 getZeroExtendExpr(Step, WideTy, Depth + 1), 1724 SCEV::FlagAnyWrap, Depth + 1), 1725 SCEV::FlagAnyWrap, Depth + 1); 1726 if (ZAdd == OperandExtendedAdd) { 1727 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1728 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1729 // Return the expression with the addrec on the outside. 1730 return getAddRecExpr( 1731 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1732 Depth + 1), 1733 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1734 AR->getNoWrapFlags()); 1735 } 1736 // Similar to above, only this time treat the step value as signed. 1737 // This covers loops that count down. 1738 OperandExtendedAdd = 1739 getAddExpr(WideStart, 1740 getMulExpr(WideMaxBECount, 1741 getSignExtendExpr(Step, WideTy, Depth + 1), 1742 SCEV::FlagAnyWrap, Depth + 1), 1743 SCEV::FlagAnyWrap, Depth + 1); 1744 if (ZAdd == OperandExtendedAdd) { 1745 // Cache knowledge of AR NW, which is propagated to this AddRec. 1746 // Negative step causes unsigned wrap, but it still can't self-wrap. 1747 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1748 // Return the expression with the addrec on the outside. 1749 return getAddRecExpr( 1750 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1751 Depth + 1), 1752 getSignExtendExpr(Step, Ty, Depth + 1), L, 1753 AR->getNoWrapFlags()); 1754 } 1755 } 1756 } 1757 1758 // Normally, in the cases we can prove no-overflow via a 1759 // backedge guarding condition, we can also compute a backedge 1760 // taken count for the loop. The exceptions are assumptions and 1761 // guards present in the loop -- SCEV is not great at exploiting 1762 // these to compute max backedge taken counts, but can still use 1763 // these to prove lack of overflow. Use this fact to avoid 1764 // doing extra work that may not pay off. 1765 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1766 !AC.assumptions().empty()) { 1767 // If the backedge is guarded by a comparison with the pre-inc 1768 // value the addrec is safe. Also, if the entry is guarded by 1769 // a comparison with the start value and the backedge is 1770 // guarded by a comparison with the post-inc value, the addrec 1771 // is safe. 1772 if (isKnownPositive(Step)) { 1773 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1774 getUnsignedRangeMax(Step)); 1775 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1776 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1777 // Cache knowledge of AR NUW, which is propagated to this 1778 // AddRec. 1779 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1780 // Return the expression with the addrec on the outside. 1781 return getAddRecExpr( 1782 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1783 Depth + 1), 1784 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1785 AR->getNoWrapFlags()); 1786 } 1787 } else if (isKnownNegative(Step)) { 1788 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1789 getSignedRangeMin(Step)); 1790 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1791 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1792 // Cache knowledge of AR NW, which is propagated to this 1793 // AddRec. Negative step causes unsigned wrap, but it 1794 // still can't self-wrap. 1795 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1796 // Return the expression with the addrec on the outside. 1797 return getAddRecExpr( 1798 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1799 Depth + 1), 1800 getSignExtendExpr(Step, Ty, Depth + 1), L, 1801 AR->getNoWrapFlags()); 1802 } 1803 } 1804 } 1805 1806 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1807 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1808 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1809 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1810 const APInt &C = SC->getAPInt(); 1811 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1812 if (D != 0) { 1813 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1814 const SCEV *SResidual = 1815 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1816 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1817 return getAddExpr(SZExtD, SZExtR, 1818 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1819 Depth + 1); 1820 } 1821 } 1822 1823 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1824 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1825 return getAddRecExpr( 1826 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1827 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1828 } 1829 } 1830 1831 // zext(A % B) --> zext(A) % zext(B) 1832 { 1833 const SCEV *LHS; 1834 const SCEV *RHS; 1835 if (matchURem(Op, LHS, RHS)) 1836 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1837 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1838 } 1839 1840 // zext(A / B) --> zext(A) / zext(B). 1841 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1842 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1843 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1844 1845 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1846 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1847 if (SA->hasNoUnsignedWrap()) { 1848 // If the addition does not unsign overflow then we can, by definition, 1849 // commute the zero extension with the addition operation. 1850 SmallVector<const SCEV *, 4> Ops; 1851 for (const auto *Op : SA->operands()) 1852 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1853 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1854 } 1855 1856 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1857 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1858 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1859 // 1860 // Often address arithmetics contain expressions like 1861 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1862 // This transformation is useful while proving that such expressions are 1863 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1864 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1865 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1866 if (D != 0) { 1867 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1868 const SCEV *SResidual = 1869 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1870 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1871 return getAddExpr(SZExtD, SZExtR, 1872 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1873 Depth + 1); 1874 } 1875 } 1876 } 1877 1878 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1879 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1880 if (SM->hasNoUnsignedWrap()) { 1881 // If the multiply does not unsign overflow then we can, by definition, 1882 // commute the zero extension with the multiply operation. 1883 SmallVector<const SCEV *, 4> Ops; 1884 for (const auto *Op : SM->operands()) 1885 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1886 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1887 } 1888 1889 // zext(2^K * (trunc X to iN)) to iM -> 1890 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1891 // 1892 // Proof: 1893 // 1894 // zext(2^K * (trunc X to iN)) to iM 1895 // = zext((trunc X to iN) << K) to iM 1896 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1897 // (because shl removes the top K bits) 1898 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1899 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1900 // 1901 if (SM->getNumOperands() == 2) 1902 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1903 if (MulLHS->getAPInt().isPowerOf2()) 1904 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1905 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1906 MulLHS->getAPInt().logBase2(); 1907 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1908 return getMulExpr( 1909 getZeroExtendExpr(MulLHS, Ty), 1910 getZeroExtendExpr( 1911 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1912 SCEV::FlagNUW, Depth + 1); 1913 } 1914 } 1915 1916 // The cast wasn't folded; create an explicit cast node. 1917 // Recompute the insert position, as it may have been invalidated. 1918 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1919 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1920 Op, Ty); 1921 UniqueSCEVs.InsertNode(S, IP); 1922 addToLoopUseLists(S); 1923 return S; 1924 } 1925 1926 const SCEV * 1927 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1928 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1929 "This is not an extending conversion!"); 1930 assert(isSCEVable(Ty) && 1931 "This is not a conversion to a SCEVable type!"); 1932 Ty = getEffectiveSCEVType(Ty); 1933 1934 // Fold if the operand is constant. 1935 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1936 return getConstant( 1937 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1938 1939 // sext(sext(x)) --> sext(x) 1940 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1941 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1942 1943 // sext(zext(x)) --> zext(x) 1944 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1945 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1946 1947 // Before doing any expensive analysis, check to see if we've already 1948 // computed a SCEV for this Op and Ty. 1949 FoldingSetNodeID ID; 1950 ID.AddInteger(scSignExtend); 1951 ID.AddPointer(Op); 1952 ID.AddPointer(Ty); 1953 void *IP = nullptr; 1954 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1955 // Limit recursion depth. 1956 if (Depth > MaxCastDepth) { 1957 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1958 Op, Ty); 1959 UniqueSCEVs.InsertNode(S, IP); 1960 addToLoopUseLists(S); 1961 return S; 1962 } 1963 1964 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1965 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1966 // It's possible the bits taken off by the truncate were all sign bits. If 1967 // so, we should be able to simplify this further. 1968 const SCEV *X = ST->getOperand(); 1969 ConstantRange CR = getSignedRange(X); 1970 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1971 unsigned NewBits = getTypeSizeInBits(Ty); 1972 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1973 CR.sextOrTrunc(NewBits))) 1974 return getTruncateOrSignExtend(X, Ty, Depth); 1975 } 1976 1977 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1978 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1979 if (SA->hasNoSignedWrap()) { 1980 // If the addition does not sign overflow then we can, by definition, 1981 // commute the sign extension with the addition operation. 1982 SmallVector<const SCEV *, 4> Ops; 1983 for (const auto *Op : SA->operands()) 1984 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1985 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1986 } 1987 1988 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1989 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1990 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1991 // 1992 // For instance, this will bring two seemingly different expressions: 1993 // 1 + sext(5 + 20 * %x + 24 * %y) and 1994 // sext(6 + 20 * %x + 24 * %y) 1995 // to the same form: 1996 // 2 + sext(4 + 20 * %x + 24 * %y) 1997 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1998 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1999 if (D != 0) { 2000 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2001 const SCEV *SResidual = 2002 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2003 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2004 return getAddExpr(SSExtD, SSExtR, 2005 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2006 Depth + 1); 2007 } 2008 } 2009 } 2010 // If the input value is a chrec scev, and we can prove that the value 2011 // did not overflow the old, smaller, value, we can sign extend all of the 2012 // operands (often constants). This allows analysis of something like 2013 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2014 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2015 if (AR->isAffine()) { 2016 const SCEV *Start = AR->getStart(); 2017 const SCEV *Step = AR->getStepRecurrence(*this); 2018 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2019 const Loop *L = AR->getLoop(); 2020 2021 if (!AR->hasNoSignedWrap()) { 2022 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2023 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2024 } 2025 2026 // If we have special knowledge that this addrec won't overflow, 2027 // we don't need to do any further analysis. 2028 if (AR->hasNoSignedWrap()) 2029 return getAddRecExpr( 2030 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2031 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2032 2033 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2034 // Note that this serves two purposes: It filters out loops that are 2035 // simply not analyzable, and it covers the case where this code is 2036 // being called from within backedge-taken count analysis, such that 2037 // attempting to ask for the backedge-taken count would likely result 2038 // in infinite recursion. In the later case, the analysis code will 2039 // cope with a conservative value, and it will take care to purge 2040 // that value once it has finished. 2041 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 2042 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2043 // Manually compute the final value for AR, checking for 2044 // overflow. 2045 2046 // Check whether the backedge-taken count can be losslessly casted to 2047 // the addrec's type. The count is always unsigned. 2048 const SCEV *CastedMaxBECount = 2049 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2050 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2051 CastedMaxBECount, MaxBECount->getType(), Depth); 2052 if (MaxBECount == RecastedMaxBECount) { 2053 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2054 // Check whether Start+Step*MaxBECount has no signed overflow. 2055 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2056 SCEV::FlagAnyWrap, Depth + 1); 2057 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2058 SCEV::FlagAnyWrap, 2059 Depth + 1), 2060 WideTy, Depth + 1); 2061 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2062 const SCEV *WideMaxBECount = 2063 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2064 const SCEV *OperandExtendedAdd = 2065 getAddExpr(WideStart, 2066 getMulExpr(WideMaxBECount, 2067 getSignExtendExpr(Step, WideTy, Depth + 1), 2068 SCEV::FlagAnyWrap, Depth + 1), 2069 SCEV::FlagAnyWrap, Depth + 1); 2070 if (SAdd == OperandExtendedAdd) { 2071 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2072 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2073 // Return the expression with the addrec on the outside. 2074 return getAddRecExpr( 2075 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2076 Depth + 1), 2077 getSignExtendExpr(Step, Ty, Depth + 1), L, 2078 AR->getNoWrapFlags()); 2079 } 2080 // Similar to above, only this time treat the step value as unsigned. 2081 // This covers loops that count up with an unsigned step. 2082 OperandExtendedAdd = 2083 getAddExpr(WideStart, 2084 getMulExpr(WideMaxBECount, 2085 getZeroExtendExpr(Step, WideTy, Depth + 1), 2086 SCEV::FlagAnyWrap, Depth + 1), 2087 SCEV::FlagAnyWrap, Depth + 1); 2088 if (SAdd == OperandExtendedAdd) { 2089 // If AR wraps around then 2090 // 2091 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2092 // => SAdd != OperandExtendedAdd 2093 // 2094 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2095 // (SAdd == OperandExtendedAdd => AR is NW) 2096 2097 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2098 2099 // Return the expression with the addrec on the outside. 2100 return getAddRecExpr( 2101 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2102 Depth + 1), 2103 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2104 AR->getNoWrapFlags()); 2105 } 2106 } 2107 } 2108 2109 // Normally, in the cases we can prove no-overflow via a 2110 // backedge guarding condition, we can also compute a backedge 2111 // taken count for the loop. The exceptions are assumptions and 2112 // guards present in the loop -- SCEV is not great at exploiting 2113 // these to compute max backedge taken counts, but can still use 2114 // these to prove lack of overflow. Use this fact to avoid 2115 // doing extra work that may not pay off. 2116 2117 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2118 !AC.assumptions().empty()) { 2119 // If the backedge is guarded by a comparison with the pre-inc 2120 // value the addrec is safe. Also, if the entry is guarded by 2121 // a comparison with the start value and the backedge is 2122 // guarded by a comparison with the post-inc value, the addrec 2123 // is safe. 2124 ICmpInst::Predicate Pred; 2125 const SCEV *OverflowLimit = 2126 getSignedOverflowLimitForStep(Step, &Pred, this); 2127 if (OverflowLimit && 2128 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2129 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2130 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2131 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2132 return getAddRecExpr( 2133 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2134 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2135 } 2136 } 2137 2138 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2139 // if D + (C - D + Step * n) could be proven to not signed wrap 2140 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2141 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2142 const APInt &C = SC->getAPInt(); 2143 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2144 if (D != 0) { 2145 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2146 const SCEV *SResidual = 2147 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2148 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2149 return getAddExpr(SSExtD, SSExtR, 2150 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2151 Depth + 1); 2152 } 2153 } 2154 2155 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2156 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2157 return getAddRecExpr( 2158 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2159 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2160 } 2161 } 2162 2163 // If the input value is provably positive and we could not simplify 2164 // away the sext build a zext instead. 2165 if (isKnownNonNegative(Op)) 2166 return getZeroExtendExpr(Op, Ty, Depth + 1); 2167 2168 // The cast wasn't folded; create an explicit cast node. 2169 // Recompute the insert position, as it may have been invalidated. 2170 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2171 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2172 Op, Ty); 2173 UniqueSCEVs.InsertNode(S, IP); 2174 addToLoopUseLists(S); 2175 return S; 2176 } 2177 2178 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2179 /// unspecified bits out to the given type. 2180 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2181 Type *Ty) { 2182 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2183 "This is not an extending conversion!"); 2184 assert(isSCEVable(Ty) && 2185 "This is not a conversion to a SCEVable type!"); 2186 Ty = getEffectiveSCEVType(Ty); 2187 2188 // Sign-extend negative constants. 2189 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2190 if (SC->getAPInt().isNegative()) 2191 return getSignExtendExpr(Op, Ty); 2192 2193 // Peel off a truncate cast. 2194 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2195 const SCEV *NewOp = T->getOperand(); 2196 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2197 return getAnyExtendExpr(NewOp, Ty); 2198 return getTruncateOrNoop(NewOp, Ty); 2199 } 2200 2201 // Next try a zext cast. If the cast is folded, use it. 2202 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2203 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2204 return ZExt; 2205 2206 // Next try a sext cast. If the cast is folded, use it. 2207 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2208 if (!isa<SCEVSignExtendExpr>(SExt)) 2209 return SExt; 2210 2211 // Force the cast to be folded into the operands of an addrec. 2212 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2213 SmallVector<const SCEV *, 4> Ops; 2214 for (const SCEV *Op : AR->operands()) 2215 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2216 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2217 } 2218 2219 // If the expression is obviously signed, use the sext cast value. 2220 if (isa<SCEVSMaxExpr>(Op)) 2221 return SExt; 2222 2223 // Absent any other information, use the zext cast value. 2224 return ZExt; 2225 } 2226 2227 /// Process the given Ops list, which is a list of operands to be added under 2228 /// the given scale, update the given map. This is a helper function for 2229 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2230 /// that would form an add expression like this: 2231 /// 2232 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2233 /// 2234 /// where A and B are constants, update the map with these values: 2235 /// 2236 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2237 /// 2238 /// and add 13 + A*B*29 to AccumulatedConstant. 2239 /// This will allow getAddRecExpr to produce this: 2240 /// 2241 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2242 /// 2243 /// This form often exposes folding opportunities that are hidden in 2244 /// the original operand list. 2245 /// 2246 /// Return true iff it appears that any interesting folding opportunities 2247 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2248 /// the common case where no interesting opportunities are present, and 2249 /// is also used as a check to avoid infinite recursion. 2250 static bool 2251 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2252 SmallVectorImpl<const SCEV *> &NewOps, 2253 APInt &AccumulatedConstant, 2254 const SCEV *const *Ops, size_t NumOperands, 2255 const APInt &Scale, 2256 ScalarEvolution &SE) { 2257 bool Interesting = false; 2258 2259 // Iterate over the add operands. They are sorted, with constants first. 2260 unsigned i = 0; 2261 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2262 ++i; 2263 // Pull a buried constant out to the outside. 2264 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2265 Interesting = true; 2266 AccumulatedConstant += Scale * C->getAPInt(); 2267 } 2268 2269 // Next comes everything else. We're especially interested in multiplies 2270 // here, but they're in the middle, so just visit the rest with one loop. 2271 for (; i != NumOperands; ++i) { 2272 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2273 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2274 APInt NewScale = 2275 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2276 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2277 // A multiplication of a constant with another add; recurse. 2278 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2279 Interesting |= 2280 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2281 Add->op_begin(), Add->getNumOperands(), 2282 NewScale, SE); 2283 } else { 2284 // A multiplication of a constant with some other value. Update 2285 // the map. 2286 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2287 const SCEV *Key = SE.getMulExpr(MulOps); 2288 auto Pair = M.insert({Key, NewScale}); 2289 if (Pair.second) { 2290 NewOps.push_back(Pair.first->first); 2291 } else { 2292 Pair.first->second += NewScale; 2293 // The map already had an entry for this value, which may indicate 2294 // a folding opportunity. 2295 Interesting = true; 2296 } 2297 } 2298 } else { 2299 // An ordinary operand. Update the map. 2300 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2301 M.insert({Ops[i], Scale}); 2302 if (Pair.second) { 2303 NewOps.push_back(Pair.first->first); 2304 } else { 2305 Pair.first->second += Scale; 2306 // The map already had an entry for this value, which may indicate 2307 // a folding opportunity. 2308 Interesting = true; 2309 } 2310 } 2311 } 2312 2313 return Interesting; 2314 } 2315 2316 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2317 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2318 // can't-overflow flags for the operation if possible. 2319 static SCEV::NoWrapFlags 2320 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2321 const ArrayRef<const SCEV *> Ops, 2322 SCEV::NoWrapFlags Flags) { 2323 using namespace std::placeholders; 2324 2325 using OBO = OverflowingBinaryOperator; 2326 2327 bool CanAnalyze = 2328 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2329 (void)CanAnalyze; 2330 assert(CanAnalyze && "don't call from other places!"); 2331 2332 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2333 SCEV::NoWrapFlags SignOrUnsignWrap = 2334 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2335 2336 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2337 auto IsKnownNonNegative = [&](const SCEV *S) { 2338 return SE->isKnownNonNegative(S); 2339 }; 2340 2341 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2342 Flags = 2343 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2344 2345 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2346 2347 if (SignOrUnsignWrap != SignOrUnsignMask && 2348 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2349 isa<SCEVConstant>(Ops[0])) { 2350 2351 auto Opcode = [&] { 2352 switch (Type) { 2353 case scAddExpr: 2354 return Instruction::Add; 2355 case scMulExpr: 2356 return Instruction::Mul; 2357 default: 2358 llvm_unreachable("Unexpected SCEV op."); 2359 } 2360 }(); 2361 2362 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2363 2364 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2365 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2366 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2367 Opcode, C, OBO::NoSignedWrap); 2368 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2369 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2370 } 2371 2372 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2373 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2374 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2375 Opcode, C, OBO::NoUnsignedWrap); 2376 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2377 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2378 } 2379 } 2380 2381 return Flags; 2382 } 2383 2384 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2385 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2386 } 2387 2388 /// Get a canonical add expression, or something simpler if possible. 2389 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2390 SCEV::NoWrapFlags Flags, 2391 unsigned Depth) { 2392 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2393 "only nuw or nsw allowed"); 2394 assert(!Ops.empty() && "Cannot get empty add!"); 2395 if (Ops.size() == 1) return Ops[0]; 2396 #ifndef NDEBUG 2397 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2398 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2399 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2400 "SCEVAddExpr operand types don't match!"); 2401 #endif 2402 2403 // Sort by complexity, this groups all similar expression types together. 2404 GroupByComplexity(Ops, &LI, DT); 2405 2406 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2407 2408 // If there are any constants, fold them together. 2409 unsigned Idx = 0; 2410 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2411 ++Idx; 2412 assert(Idx < Ops.size()); 2413 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2414 // We found two constants, fold them together! 2415 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2416 if (Ops.size() == 2) return Ops[0]; 2417 Ops.erase(Ops.begin()+1); // Erase the folded element 2418 LHSC = cast<SCEVConstant>(Ops[0]); 2419 } 2420 2421 // If we are left with a constant zero being added, strip it off. 2422 if (LHSC->getValue()->isZero()) { 2423 Ops.erase(Ops.begin()); 2424 --Idx; 2425 } 2426 2427 if (Ops.size() == 1) return Ops[0]; 2428 } 2429 2430 // Limit recursion calls depth. 2431 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2432 return getOrCreateAddExpr(Ops, Flags); 2433 2434 // Okay, check to see if the same value occurs in the operand list more than 2435 // once. If so, merge them together into an multiply expression. Since we 2436 // sorted the list, these values are required to be adjacent. 2437 Type *Ty = Ops[0]->getType(); 2438 bool FoundMatch = false; 2439 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2440 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2441 // Scan ahead to count how many equal operands there are. 2442 unsigned Count = 2; 2443 while (i+Count != e && Ops[i+Count] == Ops[i]) 2444 ++Count; 2445 // Merge the values into a multiply. 2446 const SCEV *Scale = getConstant(Ty, Count); 2447 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2448 if (Ops.size() == Count) 2449 return Mul; 2450 Ops[i] = Mul; 2451 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2452 --i; e -= Count - 1; 2453 FoundMatch = true; 2454 } 2455 if (FoundMatch) 2456 return getAddExpr(Ops, Flags, Depth + 1); 2457 2458 // Check for truncates. If all the operands are truncated from the same 2459 // type, see if factoring out the truncate would permit the result to be 2460 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2461 // if the contents of the resulting outer trunc fold to something simple. 2462 auto FindTruncSrcType = [&]() -> Type * { 2463 // We're ultimately looking to fold an addrec of truncs and muls of only 2464 // constants and truncs, so if we find any other types of SCEV 2465 // as operands of the addrec then we bail and return nullptr here. 2466 // Otherwise, we return the type of the operand of a trunc that we find. 2467 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2468 return T->getOperand()->getType(); 2469 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2470 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2471 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2472 return T->getOperand()->getType(); 2473 } 2474 return nullptr; 2475 }; 2476 if (auto *SrcType = FindTruncSrcType()) { 2477 SmallVector<const SCEV *, 8> LargeOps; 2478 bool Ok = true; 2479 // Check all the operands to see if they can be represented in the 2480 // source type of the truncate. 2481 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2482 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2483 if (T->getOperand()->getType() != SrcType) { 2484 Ok = false; 2485 break; 2486 } 2487 LargeOps.push_back(T->getOperand()); 2488 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2489 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2490 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2491 SmallVector<const SCEV *, 8> LargeMulOps; 2492 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2493 if (const SCEVTruncateExpr *T = 2494 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2495 if (T->getOperand()->getType() != SrcType) { 2496 Ok = false; 2497 break; 2498 } 2499 LargeMulOps.push_back(T->getOperand()); 2500 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2501 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2502 } else { 2503 Ok = false; 2504 break; 2505 } 2506 } 2507 if (Ok) 2508 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2509 } else { 2510 Ok = false; 2511 break; 2512 } 2513 } 2514 if (Ok) { 2515 // Evaluate the expression in the larger type. 2516 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2517 // If it folds to something simple, use it. Otherwise, don't. 2518 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2519 return getTruncateExpr(Fold, Ty); 2520 } 2521 } 2522 2523 // Skip past any other cast SCEVs. 2524 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2525 ++Idx; 2526 2527 // If there are add operands they would be next. 2528 if (Idx < Ops.size()) { 2529 bool DeletedAdd = false; 2530 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2531 if (Ops.size() > AddOpsInlineThreshold || 2532 Add->getNumOperands() > AddOpsInlineThreshold) 2533 break; 2534 // If we have an add, expand the add operands onto the end of the operands 2535 // list. 2536 Ops.erase(Ops.begin()+Idx); 2537 Ops.append(Add->op_begin(), Add->op_end()); 2538 DeletedAdd = true; 2539 } 2540 2541 // If we deleted at least one add, we added operands to the end of the list, 2542 // and they are not necessarily sorted. Recurse to resort and resimplify 2543 // any operands we just acquired. 2544 if (DeletedAdd) 2545 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2546 } 2547 2548 // Skip over the add expression until we get to a multiply. 2549 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2550 ++Idx; 2551 2552 // Check to see if there are any folding opportunities present with 2553 // operands multiplied by constant values. 2554 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2555 uint64_t BitWidth = getTypeSizeInBits(Ty); 2556 DenseMap<const SCEV *, APInt> M; 2557 SmallVector<const SCEV *, 8> NewOps; 2558 APInt AccumulatedConstant(BitWidth, 0); 2559 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2560 Ops.data(), Ops.size(), 2561 APInt(BitWidth, 1), *this)) { 2562 struct APIntCompare { 2563 bool operator()(const APInt &LHS, const APInt &RHS) const { 2564 return LHS.ult(RHS); 2565 } 2566 }; 2567 2568 // Some interesting folding opportunity is present, so its worthwhile to 2569 // re-generate the operands list. Group the operands by constant scale, 2570 // to avoid multiplying by the same constant scale multiple times. 2571 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2572 for (const SCEV *NewOp : NewOps) 2573 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2574 // Re-generate the operands list. 2575 Ops.clear(); 2576 if (AccumulatedConstant != 0) 2577 Ops.push_back(getConstant(AccumulatedConstant)); 2578 for (auto &MulOp : MulOpLists) 2579 if (MulOp.first != 0) 2580 Ops.push_back(getMulExpr( 2581 getConstant(MulOp.first), 2582 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2583 SCEV::FlagAnyWrap, Depth + 1)); 2584 if (Ops.empty()) 2585 return getZero(Ty); 2586 if (Ops.size() == 1) 2587 return Ops[0]; 2588 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2589 } 2590 } 2591 2592 // If we are adding something to a multiply expression, make sure the 2593 // something is not already an operand of the multiply. If so, merge it into 2594 // the multiply. 2595 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2596 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2597 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2598 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2599 if (isa<SCEVConstant>(MulOpSCEV)) 2600 continue; 2601 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2602 if (MulOpSCEV == Ops[AddOp]) { 2603 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2604 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2605 if (Mul->getNumOperands() != 2) { 2606 // If the multiply has more than two operands, we must get the 2607 // Y*Z term. 2608 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2609 Mul->op_begin()+MulOp); 2610 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2611 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2612 } 2613 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2614 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2615 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2616 SCEV::FlagAnyWrap, Depth + 1); 2617 if (Ops.size() == 2) return OuterMul; 2618 if (AddOp < Idx) { 2619 Ops.erase(Ops.begin()+AddOp); 2620 Ops.erase(Ops.begin()+Idx-1); 2621 } else { 2622 Ops.erase(Ops.begin()+Idx); 2623 Ops.erase(Ops.begin()+AddOp-1); 2624 } 2625 Ops.push_back(OuterMul); 2626 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2627 } 2628 2629 // Check this multiply against other multiplies being added together. 2630 for (unsigned OtherMulIdx = Idx+1; 2631 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2632 ++OtherMulIdx) { 2633 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2634 // If MulOp occurs in OtherMul, we can fold the two multiplies 2635 // together. 2636 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2637 OMulOp != e; ++OMulOp) 2638 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2639 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2640 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2641 if (Mul->getNumOperands() != 2) { 2642 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2643 Mul->op_begin()+MulOp); 2644 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2645 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2646 } 2647 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2648 if (OtherMul->getNumOperands() != 2) { 2649 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2650 OtherMul->op_begin()+OMulOp); 2651 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2652 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2653 } 2654 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2655 const SCEV *InnerMulSum = 2656 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2657 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2658 SCEV::FlagAnyWrap, Depth + 1); 2659 if (Ops.size() == 2) return OuterMul; 2660 Ops.erase(Ops.begin()+Idx); 2661 Ops.erase(Ops.begin()+OtherMulIdx-1); 2662 Ops.push_back(OuterMul); 2663 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2664 } 2665 } 2666 } 2667 } 2668 2669 // If there are any add recurrences in the operands list, see if any other 2670 // added values are loop invariant. If so, we can fold them into the 2671 // recurrence. 2672 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2673 ++Idx; 2674 2675 // Scan over all recurrences, trying to fold loop invariants into them. 2676 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2677 // Scan all of the other operands to this add and add them to the vector if 2678 // they are loop invariant w.r.t. the recurrence. 2679 SmallVector<const SCEV *, 8> LIOps; 2680 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2681 const Loop *AddRecLoop = AddRec->getLoop(); 2682 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2683 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2684 LIOps.push_back(Ops[i]); 2685 Ops.erase(Ops.begin()+i); 2686 --i; --e; 2687 } 2688 2689 // If we found some loop invariants, fold them into the recurrence. 2690 if (!LIOps.empty()) { 2691 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2692 LIOps.push_back(AddRec->getStart()); 2693 2694 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2695 AddRec->op_end()); 2696 // This follows from the fact that the no-wrap flags on the outer add 2697 // expression are applicable on the 0th iteration, when the add recurrence 2698 // will be equal to its start value. 2699 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2700 2701 // Build the new addrec. Propagate the NUW and NSW flags if both the 2702 // outer add and the inner addrec are guaranteed to have no overflow. 2703 // Always propagate NW. 2704 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2705 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2706 2707 // If all of the other operands were loop invariant, we are done. 2708 if (Ops.size() == 1) return NewRec; 2709 2710 // Otherwise, add the folded AddRec by the non-invariant parts. 2711 for (unsigned i = 0;; ++i) 2712 if (Ops[i] == AddRec) { 2713 Ops[i] = NewRec; 2714 break; 2715 } 2716 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2717 } 2718 2719 // Okay, if there weren't any loop invariants to be folded, check to see if 2720 // there are multiple AddRec's with the same loop induction variable being 2721 // added together. If so, we can fold them. 2722 for (unsigned OtherIdx = Idx+1; 2723 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2724 ++OtherIdx) { 2725 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2726 // so that the 1st found AddRecExpr is dominated by all others. 2727 assert(DT.dominates( 2728 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2729 AddRec->getLoop()->getHeader()) && 2730 "AddRecExprs are not sorted in reverse dominance order?"); 2731 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2732 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2733 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2734 AddRec->op_end()); 2735 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2736 ++OtherIdx) { 2737 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2738 if (OtherAddRec->getLoop() == AddRecLoop) { 2739 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2740 i != e; ++i) { 2741 if (i >= AddRecOps.size()) { 2742 AddRecOps.append(OtherAddRec->op_begin()+i, 2743 OtherAddRec->op_end()); 2744 break; 2745 } 2746 SmallVector<const SCEV *, 2> TwoOps = { 2747 AddRecOps[i], OtherAddRec->getOperand(i)}; 2748 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2749 } 2750 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2751 } 2752 } 2753 // Step size has changed, so we cannot guarantee no self-wraparound. 2754 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2755 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2756 } 2757 } 2758 2759 // Otherwise couldn't fold anything into this recurrence. Move onto the 2760 // next one. 2761 } 2762 2763 // Okay, it looks like we really DO need an add expr. Check to see if we 2764 // already have one, otherwise create a new one. 2765 return getOrCreateAddExpr(Ops, Flags); 2766 } 2767 2768 const SCEV * 2769 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2770 SCEV::NoWrapFlags Flags) { 2771 FoldingSetNodeID ID; 2772 ID.AddInteger(scAddExpr); 2773 for (const SCEV *Op : Ops) 2774 ID.AddPointer(Op); 2775 void *IP = nullptr; 2776 SCEVAddExpr *S = 2777 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2778 if (!S) { 2779 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2780 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2781 S = new (SCEVAllocator) 2782 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2783 UniqueSCEVs.InsertNode(S, IP); 2784 addToLoopUseLists(S); 2785 } 2786 S->setNoWrapFlags(Flags); 2787 return S; 2788 } 2789 2790 const SCEV * 2791 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2792 const Loop *L, SCEV::NoWrapFlags Flags) { 2793 FoldingSetNodeID ID; 2794 ID.AddInteger(scAddRecExpr); 2795 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2796 ID.AddPointer(Ops[i]); 2797 ID.AddPointer(L); 2798 void *IP = nullptr; 2799 SCEVAddRecExpr *S = 2800 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2801 if (!S) { 2802 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2803 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2804 S = new (SCEVAllocator) 2805 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2806 UniqueSCEVs.InsertNode(S, IP); 2807 addToLoopUseLists(S); 2808 } 2809 S->setNoWrapFlags(Flags); 2810 return S; 2811 } 2812 2813 const SCEV * 2814 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2815 SCEV::NoWrapFlags Flags) { 2816 FoldingSetNodeID ID; 2817 ID.AddInteger(scMulExpr); 2818 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2819 ID.AddPointer(Ops[i]); 2820 void *IP = nullptr; 2821 SCEVMulExpr *S = 2822 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2823 if (!S) { 2824 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2825 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2826 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2827 O, Ops.size()); 2828 UniqueSCEVs.InsertNode(S, IP); 2829 addToLoopUseLists(S); 2830 } 2831 S->setNoWrapFlags(Flags); 2832 return S; 2833 } 2834 2835 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2836 uint64_t k = i*j; 2837 if (j > 1 && k / j != i) Overflow = true; 2838 return k; 2839 } 2840 2841 /// Compute the result of "n choose k", the binomial coefficient. If an 2842 /// intermediate computation overflows, Overflow will be set and the return will 2843 /// be garbage. Overflow is not cleared on absence of overflow. 2844 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2845 // We use the multiplicative formula: 2846 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2847 // At each iteration, we take the n-th term of the numeral and divide by the 2848 // (k-n)th term of the denominator. This division will always produce an 2849 // integral result, and helps reduce the chance of overflow in the 2850 // intermediate computations. However, we can still overflow even when the 2851 // final result would fit. 2852 2853 if (n == 0 || n == k) return 1; 2854 if (k > n) return 0; 2855 2856 if (k > n/2) 2857 k = n-k; 2858 2859 uint64_t r = 1; 2860 for (uint64_t i = 1; i <= k; ++i) { 2861 r = umul_ov(r, n-(i-1), Overflow); 2862 r /= i; 2863 } 2864 return r; 2865 } 2866 2867 /// Determine if any of the operands in this SCEV are a constant or if 2868 /// any of the add or multiply expressions in this SCEV contain a constant. 2869 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2870 struct FindConstantInAddMulChain { 2871 bool FoundConstant = false; 2872 2873 bool follow(const SCEV *S) { 2874 FoundConstant |= isa<SCEVConstant>(S); 2875 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2876 } 2877 2878 bool isDone() const { 2879 return FoundConstant; 2880 } 2881 }; 2882 2883 FindConstantInAddMulChain F; 2884 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2885 ST.visitAll(StartExpr); 2886 return F.FoundConstant; 2887 } 2888 2889 /// Get a canonical multiply expression, or something simpler if possible. 2890 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2891 SCEV::NoWrapFlags Flags, 2892 unsigned Depth) { 2893 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2894 "only nuw or nsw allowed"); 2895 assert(!Ops.empty() && "Cannot get empty mul!"); 2896 if (Ops.size() == 1) return Ops[0]; 2897 #ifndef NDEBUG 2898 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2899 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2900 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2901 "SCEVMulExpr operand types don't match!"); 2902 #endif 2903 2904 // Sort by complexity, this groups all similar expression types together. 2905 GroupByComplexity(Ops, &LI, DT); 2906 2907 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2908 2909 // Limit recursion calls depth. 2910 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2911 return getOrCreateMulExpr(Ops, Flags); 2912 2913 // If there are any constants, fold them together. 2914 unsigned Idx = 0; 2915 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2916 2917 if (Ops.size() == 2) 2918 // C1*(C2+V) -> C1*C2 + C1*V 2919 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2920 // If any of Add's ops are Adds or Muls with a constant, apply this 2921 // transformation as well. 2922 // 2923 // TODO: There are some cases where this transformation is not 2924 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2925 // this transformation should be narrowed down. 2926 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2927 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2928 SCEV::FlagAnyWrap, Depth + 1), 2929 getMulExpr(LHSC, Add->getOperand(1), 2930 SCEV::FlagAnyWrap, Depth + 1), 2931 SCEV::FlagAnyWrap, Depth + 1); 2932 2933 ++Idx; 2934 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2935 // We found two constants, fold them together! 2936 ConstantInt *Fold = 2937 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2938 Ops[0] = getConstant(Fold); 2939 Ops.erase(Ops.begin()+1); // Erase the folded element 2940 if (Ops.size() == 1) return Ops[0]; 2941 LHSC = cast<SCEVConstant>(Ops[0]); 2942 } 2943 2944 // If we are left with a constant one being multiplied, strip it off. 2945 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2946 Ops.erase(Ops.begin()); 2947 --Idx; 2948 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2949 // If we have a multiply of zero, it will always be zero. 2950 return Ops[0]; 2951 } else if (Ops[0]->isAllOnesValue()) { 2952 // If we have a mul by -1 of an add, try distributing the -1 among the 2953 // add operands. 2954 if (Ops.size() == 2) { 2955 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2956 SmallVector<const SCEV *, 4> NewOps; 2957 bool AnyFolded = false; 2958 for (const SCEV *AddOp : Add->operands()) { 2959 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2960 Depth + 1); 2961 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2962 NewOps.push_back(Mul); 2963 } 2964 if (AnyFolded) 2965 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2966 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2967 // Negation preserves a recurrence's no self-wrap property. 2968 SmallVector<const SCEV *, 4> Operands; 2969 for (const SCEV *AddRecOp : AddRec->operands()) 2970 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2971 Depth + 1)); 2972 2973 return getAddRecExpr(Operands, AddRec->getLoop(), 2974 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2975 } 2976 } 2977 } 2978 2979 if (Ops.size() == 1) 2980 return Ops[0]; 2981 } 2982 2983 // Skip over the add expression until we get to a multiply. 2984 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2985 ++Idx; 2986 2987 // If there are mul operands inline them all into this expression. 2988 if (Idx < Ops.size()) { 2989 bool DeletedMul = false; 2990 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2991 if (Ops.size() > MulOpsInlineThreshold) 2992 break; 2993 // If we have an mul, expand the mul operands onto the end of the 2994 // operands list. 2995 Ops.erase(Ops.begin()+Idx); 2996 Ops.append(Mul->op_begin(), Mul->op_end()); 2997 DeletedMul = true; 2998 } 2999 3000 // If we deleted at least one mul, we added operands to the end of the 3001 // list, and they are not necessarily sorted. Recurse to resort and 3002 // resimplify any operands we just acquired. 3003 if (DeletedMul) 3004 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3005 } 3006 3007 // If there are any add recurrences in the operands list, see if any other 3008 // added values are loop invariant. If so, we can fold them into the 3009 // recurrence. 3010 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3011 ++Idx; 3012 3013 // Scan over all recurrences, trying to fold loop invariants into them. 3014 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3015 // Scan all of the other operands to this mul and add them to the vector 3016 // if they are loop invariant w.r.t. the recurrence. 3017 SmallVector<const SCEV *, 8> LIOps; 3018 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3019 const Loop *AddRecLoop = AddRec->getLoop(); 3020 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3021 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3022 LIOps.push_back(Ops[i]); 3023 Ops.erase(Ops.begin()+i); 3024 --i; --e; 3025 } 3026 3027 // If we found some loop invariants, fold them into the recurrence. 3028 if (!LIOps.empty()) { 3029 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3030 SmallVector<const SCEV *, 4> NewOps; 3031 NewOps.reserve(AddRec->getNumOperands()); 3032 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3033 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3034 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3035 SCEV::FlagAnyWrap, Depth + 1)); 3036 3037 // Build the new addrec. Propagate the NUW and NSW flags if both the 3038 // outer mul and the inner addrec are guaranteed to have no overflow. 3039 // 3040 // No self-wrap cannot be guaranteed after changing the step size, but 3041 // will be inferred if either NUW or NSW is true. 3042 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3043 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3044 3045 // If all of the other operands were loop invariant, we are done. 3046 if (Ops.size() == 1) return NewRec; 3047 3048 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3049 for (unsigned i = 0;; ++i) 3050 if (Ops[i] == AddRec) { 3051 Ops[i] = NewRec; 3052 break; 3053 } 3054 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3055 } 3056 3057 // Okay, if there weren't any loop invariants to be folded, check to see 3058 // if there are multiple AddRec's with the same loop induction variable 3059 // being multiplied together. If so, we can fold them. 3060 3061 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3062 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3063 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3064 // ]]],+,...up to x=2n}. 3065 // Note that the arguments to choose() are always integers with values 3066 // known at compile time, never SCEV objects. 3067 // 3068 // The implementation avoids pointless extra computations when the two 3069 // addrec's are of different length (mathematically, it's equivalent to 3070 // an infinite stream of zeros on the right). 3071 bool OpsModified = false; 3072 for (unsigned OtherIdx = Idx+1; 3073 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3074 ++OtherIdx) { 3075 const SCEVAddRecExpr *OtherAddRec = 3076 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3077 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3078 continue; 3079 3080 // Limit max number of arguments to avoid creation of unreasonably big 3081 // SCEVAddRecs with very complex operands. 3082 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3083 MaxAddRecSize || isHugeExpression(AddRec) || 3084 isHugeExpression(OtherAddRec)) 3085 continue; 3086 3087 bool Overflow = false; 3088 Type *Ty = AddRec->getType(); 3089 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3090 SmallVector<const SCEV*, 7> AddRecOps; 3091 for (int x = 0, xe = AddRec->getNumOperands() + 3092 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3093 SmallVector <const SCEV *, 7> SumOps; 3094 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3095 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3096 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3097 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3098 z < ze && !Overflow; ++z) { 3099 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3100 uint64_t Coeff; 3101 if (LargerThan64Bits) 3102 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3103 else 3104 Coeff = Coeff1*Coeff2; 3105 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3106 const SCEV *Term1 = AddRec->getOperand(y-z); 3107 const SCEV *Term2 = OtherAddRec->getOperand(z); 3108 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3109 SCEV::FlagAnyWrap, Depth + 1)); 3110 } 3111 } 3112 if (SumOps.empty()) 3113 SumOps.push_back(getZero(Ty)); 3114 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3115 } 3116 if (!Overflow) { 3117 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3118 SCEV::FlagAnyWrap); 3119 if (Ops.size() == 2) return NewAddRec; 3120 Ops[Idx] = NewAddRec; 3121 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3122 OpsModified = true; 3123 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3124 if (!AddRec) 3125 break; 3126 } 3127 } 3128 if (OpsModified) 3129 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3130 3131 // Otherwise couldn't fold anything into this recurrence. Move onto the 3132 // next one. 3133 } 3134 3135 // Okay, it looks like we really DO need an mul expr. Check to see if we 3136 // already have one, otherwise create a new one. 3137 return getOrCreateMulExpr(Ops, Flags); 3138 } 3139 3140 /// Represents an unsigned remainder expression based on unsigned division. 3141 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3142 const SCEV *RHS) { 3143 assert(getEffectiveSCEVType(LHS->getType()) == 3144 getEffectiveSCEVType(RHS->getType()) && 3145 "SCEVURemExpr operand types don't match!"); 3146 3147 // Short-circuit easy cases 3148 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3149 // If constant is one, the result is trivial 3150 if (RHSC->getValue()->isOne()) 3151 return getZero(LHS->getType()); // X urem 1 --> 0 3152 3153 // If constant is a power of two, fold into a zext(trunc(LHS)). 3154 if (RHSC->getAPInt().isPowerOf2()) { 3155 Type *FullTy = LHS->getType(); 3156 Type *TruncTy = 3157 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3158 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3159 } 3160 } 3161 3162 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3163 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3164 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3165 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3166 } 3167 3168 /// Get a canonical unsigned division expression, or something simpler if 3169 /// possible. 3170 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3171 const SCEV *RHS) { 3172 assert(getEffectiveSCEVType(LHS->getType()) == 3173 getEffectiveSCEVType(RHS->getType()) && 3174 "SCEVUDivExpr operand types don't match!"); 3175 3176 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3177 if (RHSC->getValue()->isOne()) 3178 return LHS; // X udiv 1 --> x 3179 // If the denominator is zero, the result of the udiv is undefined. Don't 3180 // try to analyze it, because the resolution chosen here may differ from 3181 // the resolution chosen in other parts of the compiler. 3182 if (!RHSC->getValue()->isZero()) { 3183 // Determine if the division can be folded into the operands of 3184 // its operands. 3185 // TODO: Generalize this to non-constants by using known-bits information. 3186 Type *Ty = LHS->getType(); 3187 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3188 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3189 // For non-power-of-two values, effectively round the value up to the 3190 // nearest power of two. 3191 if (!RHSC->getAPInt().isPowerOf2()) 3192 ++MaxShiftAmt; 3193 IntegerType *ExtTy = 3194 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3195 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3196 if (const SCEVConstant *Step = 3197 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3198 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3199 const APInt &StepInt = Step->getAPInt(); 3200 const APInt &DivInt = RHSC->getAPInt(); 3201 if (!StepInt.urem(DivInt) && 3202 getZeroExtendExpr(AR, ExtTy) == 3203 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3204 getZeroExtendExpr(Step, ExtTy), 3205 AR->getLoop(), SCEV::FlagAnyWrap)) { 3206 SmallVector<const SCEV *, 4> Operands; 3207 for (const SCEV *Op : AR->operands()) 3208 Operands.push_back(getUDivExpr(Op, RHS)); 3209 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3210 } 3211 /// Get a canonical UDivExpr for a recurrence. 3212 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3213 // We can currently only fold X%N if X is constant. 3214 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3215 if (StartC && !DivInt.urem(StepInt) && 3216 getZeroExtendExpr(AR, ExtTy) == 3217 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3218 getZeroExtendExpr(Step, ExtTy), 3219 AR->getLoop(), SCEV::FlagAnyWrap)) { 3220 const APInt &StartInt = StartC->getAPInt(); 3221 const APInt &StartRem = StartInt.urem(StepInt); 3222 if (StartRem != 0) 3223 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3224 AR->getLoop(), SCEV::FlagNW); 3225 } 3226 } 3227 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3228 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3229 SmallVector<const SCEV *, 4> Operands; 3230 for (const SCEV *Op : M->operands()) 3231 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3232 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3233 // Find an operand that's safely divisible. 3234 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3235 const SCEV *Op = M->getOperand(i); 3236 const SCEV *Div = getUDivExpr(Op, RHSC); 3237 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3238 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3239 M->op_end()); 3240 Operands[i] = Div; 3241 return getMulExpr(Operands); 3242 } 3243 } 3244 } 3245 3246 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3247 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3248 if (auto *DivisorConstant = 3249 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3250 bool Overflow = false; 3251 APInt NewRHS = 3252 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3253 if (Overflow) { 3254 return getConstant(RHSC->getType(), 0, false); 3255 } 3256 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3257 } 3258 } 3259 3260 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3261 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3262 SmallVector<const SCEV *, 4> Operands; 3263 for (const SCEV *Op : A->operands()) 3264 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3265 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3266 Operands.clear(); 3267 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3268 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3269 if (isa<SCEVUDivExpr>(Op) || 3270 getMulExpr(Op, RHS) != A->getOperand(i)) 3271 break; 3272 Operands.push_back(Op); 3273 } 3274 if (Operands.size() == A->getNumOperands()) 3275 return getAddExpr(Operands); 3276 } 3277 } 3278 3279 // Fold if both operands are constant. 3280 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3281 Constant *LHSCV = LHSC->getValue(); 3282 Constant *RHSCV = RHSC->getValue(); 3283 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3284 RHSCV))); 3285 } 3286 } 3287 } 3288 3289 FoldingSetNodeID ID; 3290 ID.AddInteger(scUDivExpr); 3291 ID.AddPointer(LHS); 3292 ID.AddPointer(RHS); 3293 void *IP = nullptr; 3294 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3295 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3296 LHS, RHS); 3297 UniqueSCEVs.InsertNode(S, IP); 3298 addToLoopUseLists(S); 3299 return S; 3300 } 3301 3302 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3303 APInt A = C1->getAPInt().abs(); 3304 APInt B = C2->getAPInt().abs(); 3305 uint32_t ABW = A.getBitWidth(); 3306 uint32_t BBW = B.getBitWidth(); 3307 3308 if (ABW > BBW) 3309 B = B.zext(ABW); 3310 else if (ABW < BBW) 3311 A = A.zext(BBW); 3312 3313 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3314 } 3315 3316 /// Get a canonical unsigned division expression, or something simpler if 3317 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3318 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3319 /// it's not exact because the udiv may be clearing bits. 3320 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3321 const SCEV *RHS) { 3322 // TODO: we could try to find factors in all sorts of things, but for now we 3323 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3324 // end of this file for inspiration. 3325 3326 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3327 if (!Mul || !Mul->hasNoUnsignedWrap()) 3328 return getUDivExpr(LHS, RHS); 3329 3330 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3331 // If the mulexpr multiplies by a constant, then that constant must be the 3332 // first element of the mulexpr. 3333 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3334 if (LHSCst == RHSCst) { 3335 SmallVector<const SCEV *, 2> Operands; 3336 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3337 return getMulExpr(Operands); 3338 } 3339 3340 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3341 // that there's a factor provided by one of the other terms. We need to 3342 // check. 3343 APInt Factor = gcd(LHSCst, RHSCst); 3344 if (!Factor.isIntN(1)) { 3345 LHSCst = 3346 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3347 RHSCst = 3348 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3349 SmallVector<const SCEV *, 2> Operands; 3350 Operands.push_back(LHSCst); 3351 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3352 LHS = getMulExpr(Operands); 3353 RHS = RHSCst; 3354 Mul = dyn_cast<SCEVMulExpr>(LHS); 3355 if (!Mul) 3356 return getUDivExactExpr(LHS, RHS); 3357 } 3358 } 3359 } 3360 3361 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3362 if (Mul->getOperand(i) == RHS) { 3363 SmallVector<const SCEV *, 2> Operands; 3364 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3365 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3366 return getMulExpr(Operands); 3367 } 3368 } 3369 3370 return getUDivExpr(LHS, RHS); 3371 } 3372 3373 /// Get an add recurrence expression for the specified loop. Simplify the 3374 /// expression as much as possible. 3375 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3376 const Loop *L, 3377 SCEV::NoWrapFlags Flags) { 3378 SmallVector<const SCEV *, 4> Operands; 3379 Operands.push_back(Start); 3380 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3381 if (StepChrec->getLoop() == L) { 3382 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3383 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3384 } 3385 3386 Operands.push_back(Step); 3387 return getAddRecExpr(Operands, L, Flags); 3388 } 3389 3390 /// Get an add recurrence expression for the specified loop. Simplify the 3391 /// expression as much as possible. 3392 const SCEV * 3393 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3394 const Loop *L, SCEV::NoWrapFlags Flags) { 3395 if (Operands.size() == 1) return Operands[0]; 3396 #ifndef NDEBUG 3397 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3398 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3399 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3400 "SCEVAddRecExpr operand types don't match!"); 3401 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3402 assert(isLoopInvariant(Operands[i], L) && 3403 "SCEVAddRecExpr operand is not loop-invariant!"); 3404 #endif 3405 3406 if (Operands.back()->isZero()) { 3407 Operands.pop_back(); 3408 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3409 } 3410 3411 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3412 // use that information to infer NUW and NSW flags. However, computing a 3413 // BE count requires calling getAddRecExpr, so we may not yet have a 3414 // meaningful BE count at this point (and if we don't, we'd be stuck 3415 // with a SCEVCouldNotCompute as the cached BE count). 3416 3417 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3418 3419 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3420 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3421 const Loop *NestedLoop = NestedAR->getLoop(); 3422 if (L->contains(NestedLoop) 3423 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3424 : (!NestedLoop->contains(L) && 3425 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3426 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3427 NestedAR->op_end()); 3428 Operands[0] = NestedAR->getStart(); 3429 // AddRecs require their operands be loop-invariant with respect to their 3430 // loops. Don't perform this transformation if it would break this 3431 // requirement. 3432 bool AllInvariant = all_of( 3433 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3434 3435 if (AllInvariant) { 3436 // Create a recurrence for the outer loop with the same step size. 3437 // 3438 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3439 // inner recurrence has the same property. 3440 SCEV::NoWrapFlags OuterFlags = 3441 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3442 3443 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3444 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3445 return isLoopInvariant(Op, NestedLoop); 3446 }); 3447 3448 if (AllInvariant) { 3449 // Ok, both add recurrences are valid after the transformation. 3450 // 3451 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3452 // the outer recurrence has the same property. 3453 SCEV::NoWrapFlags InnerFlags = 3454 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3455 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3456 } 3457 } 3458 // Reset Operands to its original state. 3459 Operands[0] = NestedAR; 3460 } 3461 } 3462 3463 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3464 // already have one, otherwise create a new one. 3465 return getOrCreateAddRecExpr(Operands, L, Flags); 3466 } 3467 3468 const SCEV * 3469 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3470 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3471 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3472 // getSCEV(Base)->getType() has the same address space as Base->getType() 3473 // because SCEV::getType() preserves the address space. 3474 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3475 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3476 // instruction to its SCEV, because the Instruction may be guarded by control 3477 // flow and the no-overflow bits may not be valid for the expression in any 3478 // context. This can be fixed similarly to how these flags are handled for 3479 // adds. 3480 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3481 : SCEV::FlagAnyWrap; 3482 3483 const SCEV *TotalOffset = getZero(IntPtrTy); 3484 // The array size is unimportant. The first thing we do on CurTy is getting 3485 // its element type. 3486 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3487 for (const SCEV *IndexExpr : IndexExprs) { 3488 // Compute the (potentially symbolic) offset in bytes for this index. 3489 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3490 // For a struct, add the member offset. 3491 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3492 unsigned FieldNo = Index->getZExtValue(); 3493 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3494 3495 // Add the field offset to the running total offset. 3496 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3497 3498 // Update CurTy to the type of the field at Index. 3499 CurTy = STy->getTypeAtIndex(Index); 3500 } else { 3501 // Update CurTy to its element type. 3502 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3503 // For an array, add the element offset, explicitly scaled. 3504 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3505 // Getelementptr indices are signed. 3506 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3507 3508 // Multiply the index by the element size to compute the element offset. 3509 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3510 3511 // Add the element offset to the running total offset. 3512 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3513 } 3514 } 3515 3516 // Add the total offset from all the GEP indices to the base. 3517 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3518 } 3519 3520 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3521 const SCEV *RHS) { 3522 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3523 return getSMaxExpr(Ops); 3524 } 3525 3526 std::tuple<const SCEV *, FoldingSetNodeID, void *> 3527 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3528 ArrayRef<const SCEV *> Ops) { 3529 FoldingSetNodeID ID; 3530 void *IP = nullptr; 3531 ID.AddInteger(SCEVType); 3532 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3533 ID.AddPointer(Ops[i]); 3534 return std::tuple<const SCEV *, FoldingSetNodeID, void *>( 3535 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3536 } 3537 3538 const SCEV * 3539 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3540 assert(!Ops.empty() && "Cannot get empty smax!"); 3541 if (Ops.size() == 1) return Ops[0]; 3542 #ifndef NDEBUG 3543 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3544 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3545 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3546 "SCEVSMaxExpr operand types don't match!"); 3547 #endif 3548 3549 // Sort by complexity, this groups all similar expression types together. 3550 GroupByComplexity(Ops, &LI, DT); 3551 3552 // Check if we have created the same SMax expression before. 3553 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(scSMaxExpr, Ops))) { 3554 return S; 3555 } 3556 3557 // If there are any constants, fold them together. 3558 unsigned Idx = 0; 3559 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3560 ++Idx; 3561 assert(Idx < Ops.size()); 3562 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3563 // We found two constants, fold them together! 3564 ConstantInt *Fold = ConstantInt::get( 3565 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3566 Ops[0] = getConstant(Fold); 3567 Ops.erase(Ops.begin()+1); // Erase the folded element 3568 if (Ops.size() == 1) return Ops[0]; 3569 LHSC = cast<SCEVConstant>(Ops[0]); 3570 } 3571 3572 // If we are left with a constant minimum-int, strip it off. 3573 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3574 Ops.erase(Ops.begin()); 3575 --Idx; 3576 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3577 // If we have an smax with a constant maximum-int, it will always be 3578 // maximum-int. 3579 return Ops[0]; 3580 } 3581 3582 if (Ops.size() == 1) return Ops[0]; 3583 } 3584 3585 // Find the first SMax 3586 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3587 ++Idx; 3588 3589 // Check to see if one of the operands is an SMax. If so, expand its operands 3590 // onto our operand list, and recurse to simplify. 3591 if (Idx < Ops.size()) { 3592 bool DeletedSMax = false; 3593 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3594 Ops.erase(Ops.begin()+Idx); 3595 Ops.append(SMax->op_begin(), SMax->op_end()); 3596 DeletedSMax = true; 3597 } 3598 3599 if (DeletedSMax) 3600 return getSMaxExpr(Ops); 3601 } 3602 3603 // Okay, check to see if the same value occurs in the operand list twice. If 3604 // so, delete one. Since we sorted the list, these values are required to 3605 // be adjacent. 3606 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3607 // X smax Y smax Y --> X smax Y 3608 // X smax Y --> X, if X is always greater than Y 3609 if (Ops[i] == Ops[i+1] || 3610 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3611 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3612 --i; --e; 3613 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3614 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3615 --i; --e; 3616 } 3617 3618 if (Ops.size() == 1) return Ops[0]; 3619 3620 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3621 3622 // Okay, it looks like we really DO need an smax expr. Check to see if we 3623 // already have one, otherwise create a new one. 3624 const SCEV *ExistingSCEV; 3625 FoldingSetNodeID ID; 3626 void *IP; 3627 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(scSMaxExpr, Ops); 3628 if (ExistingSCEV) 3629 return ExistingSCEV; 3630 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3631 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3632 SCEV *S = 3633 new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 3634 UniqueSCEVs.InsertNode(S, IP); 3635 addToLoopUseLists(S); 3636 return S; 3637 } 3638 3639 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3640 const SCEV *RHS) { 3641 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3642 return getUMaxExpr(Ops); 3643 } 3644 3645 const SCEV * 3646 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3647 assert(!Ops.empty() && "Cannot get empty umax!"); 3648 if (Ops.size() == 1) return Ops[0]; 3649 #ifndef NDEBUG 3650 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3651 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3652 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3653 "SCEVUMaxExpr operand types don't match!"); 3654 #endif 3655 3656 // Sort by complexity, this groups all similar expression types together. 3657 GroupByComplexity(Ops, &LI, DT); 3658 3659 // Check if we have created the same UMax expression before. 3660 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(scUMaxExpr, Ops))) { 3661 return S; 3662 } 3663 3664 // If there are any constants, fold them together. 3665 unsigned Idx = 0; 3666 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3667 ++Idx; 3668 assert(Idx < Ops.size()); 3669 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3670 // We found two constants, fold them together! 3671 ConstantInt *Fold = ConstantInt::get( 3672 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3673 Ops[0] = getConstant(Fold); 3674 Ops.erase(Ops.begin()+1); // Erase the folded element 3675 if (Ops.size() == 1) return Ops[0]; 3676 LHSC = cast<SCEVConstant>(Ops[0]); 3677 } 3678 3679 // If we are left with a constant minimum-int, strip it off. 3680 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3681 Ops.erase(Ops.begin()); 3682 --Idx; 3683 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3684 // If we have an umax with a constant maximum-int, it will always be 3685 // maximum-int. 3686 return Ops[0]; 3687 } 3688 3689 if (Ops.size() == 1) return Ops[0]; 3690 } 3691 3692 // Find the first UMax 3693 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3694 ++Idx; 3695 3696 // Check to see if one of the operands is a UMax. If so, expand its operands 3697 // onto our operand list, and recurse to simplify. 3698 if (Idx < Ops.size()) { 3699 bool DeletedUMax = false; 3700 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3701 Ops.erase(Ops.begin()+Idx); 3702 Ops.append(UMax->op_begin(), UMax->op_end()); 3703 DeletedUMax = true; 3704 } 3705 3706 if (DeletedUMax) 3707 return getUMaxExpr(Ops); 3708 } 3709 3710 // Okay, check to see if the same value occurs in the operand list twice. If 3711 // so, delete one. Since we sorted the list, these values are required to 3712 // be adjacent. 3713 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3714 // X umax Y umax Y --> X umax Y 3715 // X umax Y --> X, if X is always greater than Y 3716 if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning( 3717 ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) { 3718 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3719 --i; --e; 3720 } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i], 3721 Ops[i + 1])) { 3722 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3723 --i; --e; 3724 } 3725 3726 if (Ops.size() == 1) return Ops[0]; 3727 3728 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3729 3730 // Okay, it looks like we really DO need a umax expr. Check to see if we 3731 // already have one, otherwise create a new one. 3732 const SCEV *ExistingSCEV; 3733 FoldingSetNodeID ID; 3734 void *IP; 3735 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(scUMaxExpr, Ops); 3736 if (ExistingSCEV) 3737 return ExistingSCEV; 3738 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3739 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3740 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3741 O, Ops.size()); 3742 UniqueSCEVs.InsertNode(S, IP); 3743 addToLoopUseLists(S); 3744 return S; 3745 } 3746 3747 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3748 const SCEV *RHS) { 3749 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3750 return getSMinExpr(Ops); 3751 } 3752 3753 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3754 // ~smax(~x, ~y, ~z) == smin(x, y, z). 3755 SmallVector<const SCEV *, 2> NotOps; 3756 for (auto *S : Ops) 3757 NotOps.push_back(getNotSCEV(S)); 3758 return getNotSCEV(getSMaxExpr(NotOps)); 3759 } 3760 3761 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3762 const SCEV *RHS) { 3763 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3764 return getUMinExpr(Ops); 3765 } 3766 3767 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3768 assert(!Ops.empty() && "At least one operand must be!"); 3769 // Trivial case. 3770 if (Ops.size() == 1) 3771 return Ops[0]; 3772 3773 // ~umax(~x, ~y, ~z) == umin(x, y, z). 3774 SmallVector<const SCEV *, 2> NotOps; 3775 for (auto *S : Ops) 3776 NotOps.push_back(getNotSCEV(S)); 3777 return getNotSCEV(getUMaxExpr(NotOps)); 3778 } 3779 3780 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3781 // We can bypass creating a target-independent 3782 // constant expression and then folding it back into a ConstantInt. 3783 // This is just a compile-time optimization. 3784 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3785 } 3786 3787 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3788 StructType *STy, 3789 unsigned FieldNo) { 3790 // We can bypass creating a target-independent 3791 // constant expression and then folding it back into a ConstantInt. 3792 // This is just a compile-time optimization. 3793 return getConstant( 3794 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3795 } 3796 3797 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3798 // Don't attempt to do anything other than create a SCEVUnknown object 3799 // here. createSCEV only calls getUnknown after checking for all other 3800 // interesting possibilities, and any other code that calls getUnknown 3801 // is doing so in order to hide a value from SCEV canonicalization. 3802 3803 FoldingSetNodeID ID; 3804 ID.AddInteger(scUnknown); 3805 ID.AddPointer(V); 3806 void *IP = nullptr; 3807 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3808 assert(cast<SCEVUnknown>(S)->getValue() == V && 3809 "Stale SCEVUnknown in uniquing map!"); 3810 return S; 3811 } 3812 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3813 FirstUnknown); 3814 FirstUnknown = cast<SCEVUnknown>(S); 3815 UniqueSCEVs.InsertNode(S, IP); 3816 return S; 3817 } 3818 3819 //===----------------------------------------------------------------------===// 3820 // Basic SCEV Analysis and PHI Idiom Recognition Code 3821 // 3822 3823 /// Test if values of the given type are analyzable within the SCEV 3824 /// framework. This primarily includes integer types, and it can optionally 3825 /// include pointer types if the ScalarEvolution class has access to 3826 /// target-specific information. 3827 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3828 // Integers and pointers are always SCEVable. 3829 return Ty->isIntOrPtrTy(); 3830 } 3831 3832 /// Return the size in bits of the specified type, for which isSCEVable must 3833 /// return true. 3834 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3835 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3836 if (Ty->isPointerTy()) 3837 return getDataLayout().getIndexTypeSizeInBits(Ty); 3838 return getDataLayout().getTypeSizeInBits(Ty); 3839 } 3840 3841 /// Return a type with the same bitwidth as the given type and which represents 3842 /// how SCEV will treat the given type, for which isSCEVable must return 3843 /// true. For pointer types, this is the pointer-sized integer type. 3844 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3845 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3846 3847 if (Ty->isIntegerTy()) 3848 return Ty; 3849 3850 // The only other support type is pointer. 3851 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3852 return getDataLayout().getIntPtrType(Ty); 3853 } 3854 3855 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3856 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3857 } 3858 3859 const SCEV *ScalarEvolution::getCouldNotCompute() { 3860 return CouldNotCompute.get(); 3861 } 3862 3863 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3864 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3865 auto *SU = dyn_cast<SCEVUnknown>(S); 3866 return SU && SU->getValue() == nullptr; 3867 }); 3868 3869 return !ContainsNulls; 3870 } 3871 3872 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3873 HasRecMapType::iterator I = HasRecMap.find(S); 3874 if (I != HasRecMap.end()) 3875 return I->second; 3876 3877 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3878 HasRecMap.insert({S, FoundAddRec}); 3879 return FoundAddRec; 3880 } 3881 3882 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3883 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3884 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3885 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3886 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3887 if (!Add) 3888 return {S, nullptr}; 3889 3890 if (Add->getNumOperands() != 2) 3891 return {S, nullptr}; 3892 3893 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3894 if (!ConstOp) 3895 return {S, nullptr}; 3896 3897 return {Add->getOperand(1), ConstOp->getValue()}; 3898 } 3899 3900 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3901 /// by the value and offset from any ValueOffsetPair in the set. 3902 SetVector<ScalarEvolution::ValueOffsetPair> * 3903 ScalarEvolution::getSCEVValues(const SCEV *S) { 3904 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3905 if (SI == ExprValueMap.end()) 3906 return nullptr; 3907 #ifndef NDEBUG 3908 if (VerifySCEVMap) { 3909 // Check there is no dangling Value in the set returned. 3910 for (const auto &VE : SI->second) 3911 assert(ValueExprMap.count(VE.first)); 3912 } 3913 #endif 3914 return &SI->second; 3915 } 3916 3917 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3918 /// cannot be used separately. eraseValueFromMap should be used to remove 3919 /// V from ValueExprMap and ExprValueMap at the same time. 3920 void ScalarEvolution::eraseValueFromMap(Value *V) { 3921 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3922 if (I != ValueExprMap.end()) { 3923 const SCEV *S = I->second; 3924 // Remove {V, 0} from the set of ExprValueMap[S] 3925 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3926 SV->remove({V, nullptr}); 3927 3928 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3929 const SCEV *Stripped; 3930 ConstantInt *Offset; 3931 std::tie(Stripped, Offset) = splitAddExpr(S); 3932 if (Offset != nullptr) { 3933 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3934 SV->remove({V, Offset}); 3935 } 3936 ValueExprMap.erase(V); 3937 } 3938 } 3939 3940 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3941 /// TODO: In reality it is better to check the poison recursively 3942 /// but this is better than nothing. 3943 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3944 if (auto *I = dyn_cast<Instruction>(V)) { 3945 if (isa<OverflowingBinaryOperator>(I)) { 3946 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3947 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3948 return true; 3949 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3950 return true; 3951 } 3952 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3953 return true; 3954 } 3955 return false; 3956 } 3957 3958 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3959 /// create a new one. 3960 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3961 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3962 3963 const SCEV *S = getExistingSCEV(V); 3964 if (S == nullptr) { 3965 S = createSCEV(V); 3966 // During PHI resolution, it is possible to create two SCEVs for the same 3967 // V, so it is needed to double check whether V->S is inserted into 3968 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3969 std::pair<ValueExprMapType::iterator, bool> Pair = 3970 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3971 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3972 ExprValueMap[S].insert({V, nullptr}); 3973 3974 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3975 // ExprValueMap. 3976 const SCEV *Stripped = S; 3977 ConstantInt *Offset = nullptr; 3978 std::tie(Stripped, Offset) = splitAddExpr(S); 3979 // If stripped is SCEVUnknown, don't bother to save 3980 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3981 // increase the complexity of the expansion code. 3982 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3983 // because it may generate add/sub instead of GEP in SCEV expansion. 3984 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3985 !isa<GetElementPtrInst>(V)) 3986 ExprValueMap[Stripped].insert({V, Offset}); 3987 } 3988 } 3989 return S; 3990 } 3991 3992 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3993 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3994 3995 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3996 if (I != ValueExprMap.end()) { 3997 const SCEV *S = I->second; 3998 if (checkValidity(S)) 3999 return S; 4000 eraseValueFromMap(V); 4001 forgetMemoizedResults(S); 4002 } 4003 return nullptr; 4004 } 4005 4006 /// Return a SCEV corresponding to -V = -1*V 4007 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4008 SCEV::NoWrapFlags Flags) { 4009 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4010 return getConstant( 4011 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4012 4013 Type *Ty = V->getType(); 4014 Ty = getEffectiveSCEVType(Ty); 4015 return getMulExpr( 4016 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 4017 } 4018 4019 /// Return a SCEV corresponding to ~V = -1-V 4020 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4021 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4022 return getConstant( 4023 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4024 4025 Type *Ty = V->getType(); 4026 Ty = getEffectiveSCEVType(Ty); 4027 const SCEV *AllOnes = 4028 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4029 return getMinusSCEV(AllOnes, V); 4030 } 4031 4032 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4033 SCEV::NoWrapFlags Flags, 4034 unsigned Depth) { 4035 // Fast path: X - X --> 0. 4036 if (LHS == RHS) 4037 return getZero(LHS->getType()); 4038 4039 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4040 // makes it so that we cannot make much use of NUW. 4041 auto AddFlags = SCEV::FlagAnyWrap; 4042 const bool RHSIsNotMinSigned = 4043 !getSignedRangeMin(RHS).isMinSignedValue(); 4044 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4045 // Let M be the minimum representable signed value. Then (-1)*RHS 4046 // signed-wraps if and only if RHS is M. That can happen even for 4047 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4048 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4049 // (-1)*RHS, we need to prove that RHS != M. 4050 // 4051 // If LHS is non-negative and we know that LHS - RHS does not 4052 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4053 // either by proving that RHS > M or that LHS >= 0. 4054 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4055 AddFlags = SCEV::FlagNSW; 4056 } 4057 } 4058 4059 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4060 // RHS is NSW and LHS >= 0. 4061 // 4062 // The difficulty here is that the NSW flag may have been proven 4063 // relative to a loop that is to be found in a recurrence in LHS and 4064 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4065 // larger scope than intended. 4066 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4067 4068 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4069 } 4070 4071 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4072 unsigned Depth) { 4073 Type *SrcTy = V->getType(); 4074 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4075 "Cannot truncate or zero extend with non-integer arguments!"); 4076 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4077 return V; // No conversion 4078 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4079 return getTruncateExpr(V, Ty, Depth); 4080 return getZeroExtendExpr(V, Ty, Depth); 4081 } 4082 4083 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4084 unsigned Depth) { 4085 Type *SrcTy = V->getType(); 4086 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4087 "Cannot truncate or zero extend with non-integer arguments!"); 4088 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4089 return V; // No conversion 4090 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4091 return getTruncateExpr(V, Ty, Depth); 4092 return getSignExtendExpr(V, Ty, Depth); 4093 } 4094 4095 const SCEV * 4096 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4097 Type *SrcTy = V->getType(); 4098 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4099 "Cannot noop or zero extend with non-integer arguments!"); 4100 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4101 "getNoopOrZeroExtend cannot truncate!"); 4102 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4103 return V; // No conversion 4104 return getZeroExtendExpr(V, Ty); 4105 } 4106 4107 const SCEV * 4108 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4109 Type *SrcTy = V->getType(); 4110 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4111 "Cannot noop or sign extend with non-integer arguments!"); 4112 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4113 "getNoopOrSignExtend cannot truncate!"); 4114 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4115 return V; // No conversion 4116 return getSignExtendExpr(V, Ty); 4117 } 4118 4119 const SCEV * 4120 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4121 Type *SrcTy = V->getType(); 4122 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4123 "Cannot noop or any extend with non-integer arguments!"); 4124 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4125 "getNoopOrAnyExtend cannot truncate!"); 4126 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4127 return V; // No conversion 4128 return getAnyExtendExpr(V, Ty); 4129 } 4130 4131 const SCEV * 4132 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4133 Type *SrcTy = V->getType(); 4134 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4135 "Cannot truncate or noop with non-integer arguments!"); 4136 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4137 "getTruncateOrNoop cannot extend!"); 4138 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4139 return V; // No conversion 4140 return getTruncateExpr(V, Ty); 4141 } 4142 4143 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4144 const SCEV *RHS) { 4145 const SCEV *PromotedLHS = LHS; 4146 const SCEV *PromotedRHS = RHS; 4147 4148 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4149 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4150 else 4151 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4152 4153 return getUMaxExpr(PromotedLHS, PromotedRHS); 4154 } 4155 4156 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4157 const SCEV *RHS) { 4158 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4159 return getUMinFromMismatchedTypes(Ops); 4160 } 4161 4162 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4163 SmallVectorImpl<const SCEV *> &Ops) { 4164 assert(!Ops.empty() && "At least one operand must be!"); 4165 // Trivial case. 4166 if (Ops.size() == 1) 4167 return Ops[0]; 4168 4169 // Find the max type first. 4170 Type *MaxType = nullptr; 4171 for (auto *S : Ops) 4172 if (MaxType) 4173 MaxType = getWiderType(MaxType, S->getType()); 4174 else 4175 MaxType = S->getType(); 4176 4177 // Extend all ops to max type. 4178 SmallVector<const SCEV *, 2> PromotedOps; 4179 for (auto *S : Ops) 4180 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4181 4182 // Generate umin. 4183 return getUMinExpr(PromotedOps); 4184 } 4185 4186 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4187 // A pointer operand may evaluate to a nonpointer expression, such as null. 4188 if (!V->getType()->isPointerTy()) 4189 return V; 4190 4191 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4192 return getPointerBase(Cast->getOperand()); 4193 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4194 const SCEV *PtrOp = nullptr; 4195 for (const SCEV *NAryOp : NAry->operands()) { 4196 if (NAryOp->getType()->isPointerTy()) { 4197 // Cannot find the base of an expression with multiple pointer operands. 4198 if (PtrOp) 4199 return V; 4200 PtrOp = NAryOp; 4201 } 4202 } 4203 if (!PtrOp) 4204 return V; 4205 return getPointerBase(PtrOp); 4206 } 4207 return V; 4208 } 4209 4210 /// Push users of the given Instruction onto the given Worklist. 4211 static void 4212 PushDefUseChildren(Instruction *I, 4213 SmallVectorImpl<Instruction *> &Worklist) { 4214 // Push the def-use children onto the Worklist stack. 4215 for (User *U : I->users()) 4216 Worklist.push_back(cast<Instruction>(U)); 4217 } 4218 4219 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4220 SmallVector<Instruction *, 16> Worklist; 4221 PushDefUseChildren(PN, Worklist); 4222 4223 SmallPtrSet<Instruction *, 8> Visited; 4224 Visited.insert(PN); 4225 while (!Worklist.empty()) { 4226 Instruction *I = Worklist.pop_back_val(); 4227 if (!Visited.insert(I).second) 4228 continue; 4229 4230 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4231 if (It != ValueExprMap.end()) { 4232 const SCEV *Old = It->second; 4233 4234 // Short-circuit the def-use traversal if the symbolic name 4235 // ceases to appear in expressions. 4236 if (Old != SymName && !hasOperand(Old, SymName)) 4237 continue; 4238 4239 // SCEVUnknown for a PHI either means that it has an unrecognized 4240 // structure, it's a PHI that's in the progress of being computed 4241 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4242 // additional loop trip count information isn't going to change anything. 4243 // In the second case, createNodeForPHI will perform the necessary 4244 // updates on its own when it gets to that point. In the third, we do 4245 // want to forget the SCEVUnknown. 4246 if (!isa<PHINode>(I) || 4247 !isa<SCEVUnknown>(Old) || 4248 (I != PN && Old == SymName)) { 4249 eraseValueFromMap(It->first); 4250 forgetMemoizedResults(Old); 4251 } 4252 } 4253 4254 PushDefUseChildren(I, Worklist); 4255 } 4256 } 4257 4258 namespace { 4259 4260 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4261 /// expression in case its Loop is L. If it is not L then 4262 /// if IgnoreOtherLoops is true then use AddRec itself 4263 /// otherwise rewrite cannot be done. 4264 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4265 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4266 public: 4267 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4268 bool IgnoreOtherLoops = true) { 4269 SCEVInitRewriter Rewriter(L, SE); 4270 const SCEV *Result = Rewriter.visit(S); 4271 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4272 return SE.getCouldNotCompute(); 4273 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4274 ? SE.getCouldNotCompute() 4275 : Result; 4276 } 4277 4278 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4279 if (!SE.isLoopInvariant(Expr, L)) 4280 SeenLoopVariantSCEVUnknown = true; 4281 return Expr; 4282 } 4283 4284 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4285 // Only re-write AddRecExprs for this loop. 4286 if (Expr->getLoop() == L) 4287 return Expr->getStart(); 4288 SeenOtherLoops = true; 4289 return Expr; 4290 } 4291 4292 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4293 4294 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4295 4296 private: 4297 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4298 : SCEVRewriteVisitor(SE), L(L) {} 4299 4300 const Loop *L; 4301 bool SeenLoopVariantSCEVUnknown = false; 4302 bool SeenOtherLoops = false; 4303 }; 4304 4305 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4306 /// increment expression in case its Loop is L. If it is not L then 4307 /// use AddRec itself. 4308 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4309 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4310 public: 4311 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4312 SCEVPostIncRewriter Rewriter(L, SE); 4313 const SCEV *Result = Rewriter.visit(S); 4314 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4315 ? SE.getCouldNotCompute() 4316 : Result; 4317 } 4318 4319 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4320 if (!SE.isLoopInvariant(Expr, L)) 4321 SeenLoopVariantSCEVUnknown = true; 4322 return Expr; 4323 } 4324 4325 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4326 // Only re-write AddRecExprs for this loop. 4327 if (Expr->getLoop() == L) 4328 return Expr->getPostIncExpr(SE); 4329 SeenOtherLoops = true; 4330 return Expr; 4331 } 4332 4333 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4334 4335 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4336 4337 private: 4338 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4339 : SCEVRewriteVisitor(SE), L(L) {} 4340 4341 const Loop *L; 4342 bool SeenLoopVariantSCEVUnknown = false; 4343 bool SeenOtherLoops = false; 4344 }; 4345 4346 /// This class evaluates the compare condition by matching it against the 4347 /// condition of loop latch. If there is a match we assume a true value 4348 /// for the condition while building SCEV nodes. 4349 class SCEVBackedgeConditionFolder 4350 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4351 public: 4352 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4353 ScalarEvolution &SE) { 4354 bool IsPosBECond = false; 4355 Value *BECond = nullptr; 4356 if (BasicBlock *Latch = L->getLoopLatch()) { 4357 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4358 if (BI && BI->isConditional()) { 4359 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4360 "Both outgoing branches should not target same header!"); 4361 BECond = BI->getCondition(); 4362 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4363 } else { 4364 return S; 4365 } 4366 } 4367 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4368 return Rewriter.visit(S); 4369 } 4370 4371 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4372 const SCEV *Result = Expr; 4373 bool InvariantF = SE.isLoopInvariant(Expr, L); 4374 4375 if (!InvariantF) { 4376 Instruction *I = cast<Instruction>(Expr->getValue()); 4377 switch (I->getOpcode()) { 4378 case Instruction::Select: { 4379 SelectInst *SI = cast<SelectInst>(I); 4380 Optional<const SCEV *> Res = 4381 compareWithBackedgeCondition(SI->getCondition()); 4382 if (Res.hasValue()) { 4383 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4384 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4385 } 4386 break; 4387 } 4388 default: { 4389 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4390 if (Res.hasValue()) 4391 Result = Res.getValue(); 4392 break; 4393 } 4394 } 4395 } 4396 return Result; 4397 } 4398 4399 private: 4400 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4401 bool IsPosBECond, ScalarEvolution &SE) 4402 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4403 IsPositiveBECond(IsPosBECond) {} 4404 4405 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4406 4407 const Loop *L; 4408 /// Loop back condition. 4409 Value *BackedgeCond = nullptr; 4410 /// Set to true if loop back is on positive branch condition. 4411 bool IsPositiveBECond; 4412 }; 4413 4414 Optional<const SCEV *> 4415 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4416 4417 // If value matches the backedge condition for loop latch, 4418 // then return a constant evolution node based on loopback 4419 // branch taken. 4420 if (BackedgeCond == IC) 4421 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4422 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4423 return None; 4424 } 4425 4426 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4427 public: 4428 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4429 ScalarEvolution &SE) { 4430 SCEVShiftRewriter Rewriter(L, SE); 4431 const SCEV *Result = Rewriter.visit(S); 4432 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4433 } 4434 4435 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4436 // Only allow AddRecExprs for this loop. 4437 if (!SE.isLoopInvariant(Expr, L)) 4438 Valid = false; 4439 return Expr; 4440 } 4441 4442 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4443 if (Expr->getLoop() == L && Expr->isAffine()) 4444 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4445 Valid = false; 4446 return Expr; 4447 } 4448 4449 bool isValid() { return Valid; } 4450 4451 private: 4452 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4453 : SCEVRewriteVisitor(SE), L(L) {} 4454 4455 const Loop *L; 4456 bool Valid = true; 4457 }; 4458 4459 } // end anonymous namespace 4460 4461 SCEV::NoWrapFlags 4462 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4463 if (!AR->isAffine()) 4464 return SCEV::FlagAnyWrap; 4465 4466 using OBO = OverflowingBinaryOperator; 4467 4468 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4469 4470 if (!AR->hasNoSignedWrap()) { 4471 ConstantRange AddRecRange = getSignedRange(AR); 4472 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4473 4474 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4475 Instruction::Add, IncRange, OBO::NoSignedWrap); 4476 if (NSWRegion.contains(AddRecRange)) 4477 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4478 } 4479 4480 if (!AR->hasNoUnsignedWrap()) { 4481 ConstantRange AddRecRange = getUnsignedRange(AR); 4482 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4483 4484 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4485 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4486 if (NUWRegion.contains(AddRecRange)) 4487 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4488 } 4489 4490 return Result; 4491 } 4492 4493 namespace { 4494 4495 /// Represents an abstract binary operation. This may exist as a 4496 /// normal instruction or constant expression, or may have been 4497 /// derived from an expression tree. 4498 struct BinaryOp { 4499 unsigned Opcode; 4500 Value *LHS; 4501 Value *RHS; 4502 bool IsNSW = false; 4503 bool IsNUW = false; 4504 4505 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4506 /// constant expression. 4507 Operator *Op = nullptr; 4508 4509 explicit BinaryOp(Operator *Op) 4510 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4511 Op(Op) { 4512 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4513 IsNSW = OBO->hasNoSignedWrap(); 4514 IsNUW = OBO->hasNoUnsignedWrap(); 4515 } 4516 } 4517 4518 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4519 bool IsNUW = false) 4520 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4521 }; 4522 4523 } // end anonymous namespace 4524 4525 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4526 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4527 auto *Op = dyn_cast<Operator>(V); 4528 if (!Op) 4529 return None; 4530 4531 // Implementation detail: all the cleverness here should happen without 4532 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4533 // SCEV expressions when possible, and we should not break that. 4534 4535 switch (Op->getOpcode()) { 4536 case Instruction::Add: 4537 case Instruction::Sub: 4538 case Instruction::Mul: 4539 case Instruction::UDiv: 4540 case Instruction::URem: 4541 case Instruction::And: 4542 case Instruction::Or: 4543 case Instruction::AShr: 4544 case Instruction::Shl: 4545 return BinaryOp(Op); 4546 4547 case Instruction::Xor: 4548 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4549 // If the RHS of the xor is a signmask, then this is just an add. 4550 // Instcombine turns add of signmask into xor as a strength reduction step. 4551 if (RHSC->getValue().isSignMask()) 4552 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4553 return BinaryOp(Op); 4554 4555 case Instruction::LShr: 4556 // Turn logical shift right of a constant into a unsigned divide. 4557 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4558 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4559 4560 // If the shift count is not less than the bitwidth, the result of 4561 // the shift is undefined. Don't try to analyze it, because the 4562 // resolution chosen here may differ from the resolution chosen in 4563 // other parts of the compiler. 4564 if (SA->getValue().ult(BitWidth)) { 4565 Constant *X = 4566 ConstantInt::get(SA->getContext(), 4567 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4568 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4569 } 4570 } 4571 return BinaryOp(Op); 4572 4573 case Instruction::ExtractValue: { 4574 auto *EVI = cast<ExtractValueInst>(Op); 4575 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4576 break; 4577 4578 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4579 if (!WO) 4580 break; 4581 4582 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4583 bool Signed = WO->isSigned(); 4584 // TODO: Should add nuw/nsw flags for mul as well. 4585 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4586 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4587 4588 // Now that we know that all uses of the arithmetic-result component of 4589 // CI are guarded by the overflow check, we can go ahead and pretend 4590 // that the arithmetic is non-overflowing. 4591 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4592 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4593 } 4594 4595 default: 4596 break; 4597 } 4598 4599 return None; 4600 } 4601 4602 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4603 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4604 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4605 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4606 /// follows one of the following patterns: 4607 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4608 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4609 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4610 /// we return the type of the truncation operation, and indicate whether the 4611 /// truncated type should be treated as signed/unsigned by setting 4612 /// \p Signed to true/false, respectively. 4613 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4614 bool &Signed, ScalarEvolution &SE) { 4615 // The case where Op == SymbolicPHI (that is, with no type conversions on 4616 // the way) is handled by the regular add recurrence creating logic and 4617 // would have already been triggered in createAddRecForPHI. Reaching it here 4618 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4619 // because one of the other operands of the SCEVAddExpr updating this PHI is 4620 // not invariant). 4621 // 4622 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4623 // this case predicates that allow us to prove that Op == SymbolicPHI will 4624 // be added. 4625 if (Op == SymbolicPHI) 4626 return nullptr; 4627 4628 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4629 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4630 if (SourceBits != NewBits) 4631 return nullptr; 4632 4633 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4634 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4635 if (!SExt && !ZExt) 4636 return nullptr; 4637 const SCEVTruncateExpr *Trunc = 4638 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4639 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4640 if (!Trunc) 4641 return nullptr; 4642 const SCEV *X = Trunc->getOperand(); 4643 if (X != SymbolicPHI) 4644 return nullptr; 4645 Signed = SExt != nullptr; 4646 return Trunc->getType(); 4647 } 4648 4649 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4650 if (!PN->getType()->isIntegerTy()) 4651 return nullptr; 4652 const Loop *L = LI.getLoopFor(PN->getParent()); 4653 if (!L || L->getHeader() != PN->getParent()) 4654 return nullptr; 4655 return L; 4656 } 4657 4658 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4659 // computation that updates the phi follows the following pattern: 4660 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4661 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4662 // If so, try to see if it can be rewritten as an AddRecExpr under some 4663 // Predicates. If successful, return them as a pair. Also cache the results 4664 // of the analysis. 4665 // 4666 // Example usage scenario: 4667 // Say the Rewriter is called for the following SCEV: 4668 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4669 // where: 4670 // %X = phi i64 (%Start, %BEValue) 4671 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4672 // and call this function with %SymbolicPHI = %X. 4673 // 4674 // The analysis will find that the value coming around the backedge has 4675 // the following SCEV: 4676 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4677 // Upon concluding that this matches the desired pattern, the function 4678 // will return the pair {NewAddRec, SmallPredsVec} where: 4679 // NewAddRec = {%Start,+,%Step} 4680 // SmallPredsVec = {P1, P2, P3} as follows: 4681 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4682 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4683 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4684 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4685 // under the predicates {P1,P2,P3}. 4686 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4687 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4688 // 4689 // TODO's: 4690 // 4691 // 1) Extend the Induction descriptor to also support inductions that involve 4692 // casts: When needed (namely, when we are called in the context of the 4693 // vectorizer induction analysis), a Set of cast instructions will be 4694 // populated by this method, and provided back to isInductionPHI. This is 4695 // needed to allow the vectorizer to properly record them to be ignored by 4696 // the cost model and to avoid vectorizing them (otherwise these casts, 4697 // which are redundant under the runtime overflow checks, will be 4698 // vectorized, which can be costly). 4699 // 4700 // 2) Support additional induction/PHISCEV patterns: We also want to support 4701 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4702 // after the induction update operation (the induction increment): 4703 // 4704 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4705 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4706 // 4707 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4708 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4709 // 4710 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4711 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4712 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4713 SmallVector<const SCEVPredicate *, 3> Predicates; 4714 4715 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4716 // return an AddRec expression under some predicate. 4717 4718 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4719 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4720 assert(L && "Expecting an integer loop header phi"); 4721 4722 // The loop may have multiple entrances or multiple exits; we can analyze 4723 // this phi as an addrec if it has a unique entry value and a unique 4724 // backedge value. 4725 Value *BEValueV = nullptr, *StartValueV = nullptr; 4726 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4727 Value *V = PN->getIncomingValue(i); 4728 if (L->contains(PN->getIncomingBlock(i))) { 4729 if (!BEValueV) { 4730 BEValueV = V; 4731 } else if (BEValueV != V) { 4732 BEValueV = nullptr; 4733 break; 4734 } 4735 } else if (!StartValueV) { 4736 StartValueV = V; 4737 } else if (StartValueV != V) { 4738 StartValueV = nullptr; 4739 break; 4740 } 4741 } 4742 if (!BEValueV || !StartValueV) 4743 return None; 4744 4745 const SCEV *BEValue = getSCEV(BEValueV); 4746 4747 // If the value coming around the backedge is an add with the symbolic 4748 // value we just inserted, possibly with casts that we can ignore under 4749 // an appropriate runtime guard, then we found a simple induction variable! 4750 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4751 if (!Add) 4752 return None; 4753 4754 // If there is a single occurrence of the symbolic value, possibly 4755 // casted, replace it with a recurrence. 4756 unsigned FoundIndex = Add->getNumOperands(); 4757 Type *TruncTy = nullptr; 4758 bool Signed; 4759 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4760 if ((TruncTy = 4761 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4762 if (FoundIndex == e) { 4763 FoundIndex = i; 4764 break; 4765 } 4766 4767 if (FoundIndex == Add->getNumOperands()) 4768 return None; 4769 4770 // Create an add with everything but the specified operand. 4771 SmallVector<const SCEV *, 8> Ops; 4772 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4773 if (i != FoundIndex) 4774 Ops.push_back(Add->getOperand(i)); 4775 const SCEV *Accum = getAddExpr(Ops); 4776 4777 // The runtime checks will not be valid if the step amount is 4778 // varying inside the loop. 4779 if (!isLoopInvariant(Accum, L)) 4780 return None; 4781 4782 // *** Part2: Create the predicates 4783 4784 // Analysis was successful: we have a phi-with-cast pattern for which we 4785 // can return an AddRec expression under the following predicates: 4786 // 4787 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4788 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4789 // P2: An Equal predicate that guarantees that 4790 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4791 // P3: An Equal predicate that guarantees that 4792 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4793 // 4794 // As we next prove, the above predicates guarantee that: 4795 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4796 // 4797 // 4798 // More formally, we want to prove that: 4799 // Expr(i+1) = Start + (i+1) * Accum 4800 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4801 // 4802 // Given that: 4803 // 1) Expr(0) = Start 4804 // 2) Expr(1) = Start + Accum 4805 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4806 // 3) Induction hypothesis (step i): 4807 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4808 // 4809 // Proof: 4810 // Expr(i+1) = 4811 // = Start + (i+1)*Accum 4812 // = (Start + i*Accum) + Accum 4813 // = Expr(i) + Accum 4814 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4815 // :: from step i 4816 // 4817 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4818 // 4819 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4820 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4821 // + Accum :: from P3 4822 // 4823 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4824 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4825 // 4826 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4827 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4828 // 4829 // By induction, the same applies to all iterations 1<=i<n: 4830 // 4831 4832 // Create a truncated addrec for which we will add a no overflow check (P1). 4833 const SCEV *StartVal = getSCEV(StartValueV); 4834 const SCEV *PHISCEV = 4835 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4836 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4837 4838 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4839 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4840 // will be constant. 4841 // 4842 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4843 // add P1. 4844 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4845 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4846 Signed ? SCEVWrapPredicate::IncrementNSSW 4847 : SCEVWrapPredicate::IncrementNUSW; 4848 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4849 Predicates.push_back(AddRecPred); 4850 } 4851 4852 // Create the Equal Predicates P2,P3: 4853 4854 // It is possible that the predicates P2 and/or P3 are computable at 4855 // compile time due to StartVal and/or Accum being constants. 4856 // If either one is, then we can check that now and escape if either P2 4857 // or P3 is false. 4858 4859 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4860 // for each of StartVal and Accum 4861 auto getExtendedExpr = [&](const SCEV *Expr, 4862 bool CreateSignExtend) -> const SCEV * { 4863 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4864 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4865 const SCEV *ExtendedExpr = 4866 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4867 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4868 return ExtendedExpr; 4869 }; 4870 4871 // Given: 4872 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4873 // = getExtendedExpr(Expr) 4874 // Determine whether the predicate P: Expr == ExtendedExpr 4875 // is known to be false at compile time 4876 auto PredIsKnownFalse = [&](const SCEV *Expr, 4877 const SCEV *ExtendedExpr) -> bool { 4878 return Expr != ExtendedExpr && 4879 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4880 }; 4881 4882 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4883 if (PredIsKnownFalse(StartVal, StartExtended)) { 4884 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4885 return None; 4886 } 4887 4888 // The Step is always Signed (because the overflow checks are either 4889 // NSSW or NUSW) 4890 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4891 if (PredIsKnownFalse(Accum, AccumExtended)) { 4892 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4893 return None; 4894 } 4895 4896 auto AppendPredicate = [&](const SCEV *Expr, 4897 const SCEV *ExtendedExpr) -> void { 4898 if (Expr != ExtendedExpr && 4899 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4900 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4901 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4902 Predicates.push_back(Pred); 4903 } 4904 }; 4905 4906 AppendPredicate(StartVal, StartExtended); 4907 AppendPredicate(Accum, AccumExtended); 4908 4909 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4910 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4911 // into NewAR if it will also add the runtime overflow checks specified in 4912 // Predicates. 4913 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4914 4915 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4916 std::make_pair(NewAR, Predicates); 4917 // Remember the result of the analysis for this SCEV at this locayyytion. 4918 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4919 return PredRewrite; 4920 } 4921 4922 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4923 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4924 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4925 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4926 if (!L) 4927 return None; 4928 4929 // Check to see if we already analyzed this PHI. 4930 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4931 if (I != PredicatedSCEVRewrites.end()) { 4932 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4933 I->second; 4934 // Analysis was done before and failed to create an AddRec: 4935 if (Rewrite.first == SymbolicPHI) 4936 return None; 4937 // Analysis was done before and succeeded to create an AddRec under 4938 // a predicate: 4939 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4940 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4941 return Rewrite; 4942 } 4943 4944 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4945 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4946 4947 // Record in the cache that the analysis failed 4948 if (!Rewrite) { 4949 SmallVector<const SCEVPredicate *, 3> Predicates; 4950 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4951 return None; 4952 } 4953 4954 return Rewrite; 4955 } 4956 4957 // FIXME: This utility is currently required because the Rewriter currently 4958 // does not rewrite this expression: 4959 // {0, +, (sext ix (trunc iy to ix) to iy)} 4960 // into {0, +, %step}, 4961 // even when the following Equal predicate exists: 4962 // "%step == (sext ix (trunc iy to ix) to iy)". 4963 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4964 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4965 if (AR1 == AR2) 4966 return true; 4967 4968 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4969 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4970 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4971 return false; 4972 return true; 4973 }; 4974 4975 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4976 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4977 return false; 4978 return true; 4979 } 4980 4981 /// A helper function for createAddRecFromPHI to handle simple cases. 4982 /// 4983 /// This function tries to find an AddRec expression for the simplest (yet most 4984 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4985 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4986 /// technique for finding the AddRec expression. 4987 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4988 Value *BEValueV, 4989 Value *StartValueV) { 4990 const Loop *L = LI.getLoopFor(PN->getParent()); 4991 assert(L && L->getHeader() == PN->getParent()); 4992 assert(BEValueV && StartValueV); 4993 4994 auto BO = MatchBinaryOp(BEValueV, DT); 4995 if (!BO) 4996 return nullptr; 4997 4998 if (BO->Opcode != Instruction::Add) 4999 return nullptr; 5000 5001 const SCEV *Accum = nullptr; 5002 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5003 Accum = getSCEV(BO->RHS); 5004 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5005 Accum = getSCEV(BO->LHS); 5006 5007 if (!Accum) 5008 return nullptr; 5009 5010 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5011 if (BO->IsNUW) 5012 Flags = setFlags(Flags, SCEV::FlagNUW); 5013 if (BO->IsNSW) 5014 Flags = setFlags(Flags, SCEV::FlagNSW); 5015 5016 const SCEV *StartVal = getSCEV(StartValueV); 5017 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5018 5019 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5020 5021 // We can add Flags to the post-inc expression only if we 5022 // know that it is *undefined behavior* for BEValueV to 5023 // overflow. 5024 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5025 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5026 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5027 5028 return PHISCEV; 5029 } 5030 5031 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5032 const Loop *L = LI.getLoopFor(PN->getParent()); 5033 if (!L || L->getHeader() != PN->getParent()) 5034 return nullptr; 5035 5036 // The loop may have multiple entrances or multiple exits; we can analyze 5037 // this phi as an addrec if it has a unique entry value and a unique 5038 // backedge value. 5039 Value *BEValueV = nullptr, *StartValueV = nullptr; 5040 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5041 Value *V = PN->getIncomingValue(i); 5042 if (L->contains(PN->getIncomingBlock(i))) { 5043 if (!BEValueV) { 5044 BEValueV = V; 5045 } else if (BEValueV != V) { 5046 BEValueV = nullptr; 5047 break; 5048 } 5049 } else if (!StartValueV) { 5050 StartValueV = V; 5051 } else if (StartValueV != V) { 5052 StartValueV = nullptr; 5053 break; 5054 } 5055 } 5056 if (!BEValueV || !StartValueV) 5057 return nullptr; 5058 5059 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5060 "PHI node already processed?"); 5061 5062 // First, try to find AddRec expression without creating a fictituos symbolic 5063 // value for PN. 5064 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5065 return S; 5066 5067 // Handle PHI node value symbolically. 5068 const SCEV *SymbolicName = getUnknown(PN); 5069 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5070 5071 // Using this symbolic name for the PHI, analyze the value coming around 5072 // the back-edge. 5073 const SCEV *BEValue = getSCEV(BEValueV); 5074 5075 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5076 // has a special value for the first iteration of the loop. 5077 5078 // If the value coming around the backedge is an add with the symbolic 5079 // value we just inserted, then we found a simple induction variable! 5080 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5081 // If there is a single occurrence of the symbolic value, replace it 5082 // with a recurrence. 5083 unsigned FoundIndex = Add->getNumOperands(); 5084 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5085 if (Add->getOperand(i) == SymbolicName) 5086 if (FoundIndex == e) { 5087 FoundIndex = i; 5088 break; 5089 } 5090 5091 if (FoundIndex != Add->getNumOperands()) { 5092 // Create an add with everything but the specified operand. 5093 SmallVector<const SCEV *, 8> Ops; 5094 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5095 if (i != FoundIndex) 5096 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5097 L, *this)); 5098 const SCEV *Accum = getAddExpr(Ops); 5099 5100 // This is not a valid addrec if the step amount is varying each 5101 // loop iteration, but is not itself an addrec in this loop. 5102 if (isLoopInvariant(Accum, L) || 5103 (isa<SCEVAddRecExpr>(Accum) && 5104 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5105 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5106 5107 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5108 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5109 if (BO->IsNUW) 5110 Flags = setFlags(Flags, SCEV::FlagNUW); 5111 if (BO->IsNSW) 5112 Flags = setFlags(Flags, SCEV::FlagNSW); 5113 } 5114 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5115 // If the increment is an inbounds GEP, then we know the address 5116 // space cannot be wrapped around. We cannot make any guarantee 5117 // about signed or unsigned overflow because pointers are 5118 // unsigned but we may have a negative index from the base 5119 // pointer. We can guarantee that no unsigned wrap occurs if the 5120 // indices form a positive value. 5121 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5122 Flags = setFlags(Flags, SCEV::FlagNW); 5123 5124 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5125 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5126 Flags = setFlags(Flags, SCEV::FlagNUW); 5127 } 5128 5129 // We cannot transfer nuw and nsw flags from subtraction 5130 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5131 // for instance. 5132 } 5133 5134 const SCEV *StartVal = getSCEV(StartValueV); 5135 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5136 5137 // Okay, for the entire analysis of this edge we assumed the PHI 5138 // to be symbolic. We now need to go back and purge all of the 5139 // entries for the scalars that use the symbolic expression. 5140 forgetSymbolicName(PN, SymbolicName); 5141 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5142 5143 // We can add Flags to the post-inc expression only if we 5144 // know that it is *undefined behavior* for BEValueV to 5145 // overflow. 5146 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5147 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5148 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5149 5150 return PHISCEV; 5151 } 5152 } 5153 } else { 5154 // Otherwise, this could be a loop like this: 5155 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5156 // In this case, j = {1,+,1} and BEValue is j. 5157 // Because the other in-value of i (0) fits the evolution of BEValue 5158 // i really is an addrec evolution. 5159 // 5160 // We can generalize this saying that i is the shifted value of BEValue 5161 // by one iteration: 5162 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5163 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5164 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5165 if (Shifted != getCouldNotCompute() && 5166 Start != getCouldNotCompute()) { 5167 const SCEV *StartVal = getSCEV(StartValueV); 5168 if (Start == StartVal) { 5169 // Okay, for the entire analysis of this edge we assumed the PHI 5170 // to be symbolic. We now need to go back and purge all of the 5171 // entries for the scalars that use the symbolic expression. 5172 forgetSymbolicName(PN, SymbolicName); 5173 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5174 return Shifted; 5175 } 5176 } 5177 } 5178 5179 // Remove the temporary PHI node SCEV that has been inserted while intending 5180 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5181 // as it will prevent later (possibly simpler) SCEV expressions to be added 5182 // to the ValueExprMap. 5183 eraseValueFromMap(PN); 5184 5185 return nullptr; 5186 } 5187 5188 // Checks if the SCEV S is available at BB. S is considered available at BB 5189 // if S can be materialized at BB without introducing a fault. 5190 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5191 BasicBlock *BB) { 5192 struct CheckAvailable { 5193 bool TraversalDone = false; 5194 bool Available = true; 5195 5196 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5197 BasicBlock *BB = nullptr; 5198 DominatorTree &DT; 5199 5200 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5201 : L(L), BB(BB), DT(DT) {} 5202 5203 bool setUnavailable() { 5204 TraversalDone = true; 5205 Available = false; 5206 return false; 5207 } 5208 5209 bool follow(const SCEV *S) { 5210 switch (S->getSCEVType()) { 5211 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5212 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5213 // These expressions are available if their operand(s) is/are. 5214 return true; 5215 5216 case scAddRecExpr: { 5217 // We allow add recurrences that are on the loop BB is in, or some 5218 // outer loop. This guarantees availability because the value of the 5219 // add recurrence at BB is simply the "current" value of the induction 5220 // variable. We can relax this in the future; for instance an add 5221 // recurrence on a sibling dominating loop is also available at BB. 5222 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5223 if (L && (ARLoop == L || ARLoop->contains(L))) 5224 return true; 5225 5226 return setUnavailable(); 5227 } 5228 5229 case scUnknown: { 5230 // For SCEVUnknown, we check for simple dominance. 5231 const auto *SU = cast<SCEVUnknown>(S); 5232 Value *V = SU->getValue(); 5233 5234 if (isa<Argument>(V)) 5235 return false; 5236 5237 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5238 return false; 5239 5240 return setUnavailable(); 5241 } 5242 5243 case scUDivExpr: 5244 case scCouldNotCompute: 5245 // We do not try to smart about these at all. 5246 return setUnavailable(); 5247 } 5248 llvm_unreachable("switch should be fully covered!"); 5249 } 5250 5251 bool isDone() { return TraversalDone; } 5252 }; 5253 5254 CheckAvailable CA(L, BB, DT); 5255 SCEVTraversal<CheckAvailable> ST(CA); 5256 5257 ST.visitAll(S); 5258 return CA.Available; 5259 } 5260 5261 // Try to match a control flow sequence that branches out at BI and merges back 5262 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5263 // match. 5264 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5265 Value *&C, Value *&LHS, Value *&RHS) { 5266 C = BI->getCondition(); 5267 5268 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5269 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5270 5271 if (!LeftEdge.isSingleEdge()) 5272 return false; 5273 5274 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5275 5276 Use &LeftUse = Merge->getOperandUse(0); 5277 Use &RightUse = Merge->getOperandUse(1); 5278 5279 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5280 LHS = LeftUse; 5281 RHS = RightUse; 5282 return true; 5283 } 5284 5285 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5286 LHS = RightUse; 5287 RHS = LeftUse; 5288 return true; 5289 } 5290 5291 return false; 5292 } 5293 5294 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5295 auto IsReachable = 5296 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5297 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5298 const Loop *L = LI.getLoopFor(PN->getParent()); 5299 5300 // We don't want to break LCSSA, even in a SCEV expression tree. 5301 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5302 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5303 return nullptr; 5304 5305 // Try to match 5306 // 5307 // br %cond, label %left, label %right 5308 // left: 5309 // br label %merge 5310 // right: 5311 // br label %merge 5312 // merge: 5313 // V = phi [ %x, %left ], [ %y, %right ] 5314 // 5315 // as "select %cond, %x, %y" 5316 5317 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5318 assert(IDom && "At least the entry block should dominate PN"); 5319 5320 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5321 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5322 5323 if (BI && BI->isConditional() && 5324 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5325 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5326 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5327 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5328 } 5329 5330 return nullptr; 5331 } 5332 5333 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5334 if (const SCEV *S = createAddRecFromPHI(PN)) 5335 return S; 5336 5337 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5338 return S; 5339 5340 // If the PHI has a single incoming value, follow that value, unless the 5341 // PHI's incoming blocks are in a different loop, in which case doing so 5342 // risks breaking LCSSA form. Instcombine would normally zap these, but 5343 // it doesn't have DominatorTree information, so it may miss cases. 5344 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5345 if (LI.replacementPreservesLCSSAForm(PN, V)) 5346 return getSCEV(V); 5347 5348 // If it's not a loop phi, we can't handle it yet. 5349 return getUnknown(PN); 5350 } 5351 5352 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5353 Value *Cond, 5354 Value *TrueVal, 5355 Value *FalseVal) { 5356 // Handle "constant" branch or select. This can occur for instance when a 5357 // loop pass transforms an inner loop and moves on to process the outer loop. 5358 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5359 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5360 5361 // Try to match some simple smax or umax patterns. 5362 auto *ICI = dyn_cast<ICmpInst>(Cond); 5363 if (!ICI) 5364 return getUnknown(I); 5365 5366 Value *LHS = ICI->getOperand(0); 5367 Value *RHS = ICI->getOperand(1); 5368 5369 switch (ICI->getPredicate()) { 5370 case ICmpInst::ICMP_SLT: 5371 case ICmpInst::ICMP_SLE: 5372 std::swap(LHS, RHS); 5373 LLVM_FALLTHROUGH; 5374 case ICmpInst::ICMP_SGT: 5375 case ICmpInst::ICMP_SGE: 5376 // a >s b ? a+x : b+x -> smax(a, b)+x 5377 // a >s b ? b+x : a+x -> smin(a, b)+x 5378 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5379 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5380 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5381 const SCEV *LA = getSCEV(TrueVal); 5382 const SCEV *RA = getSCEV(FalseVal); 5383 const SCEV *LDiff = getMinusSCEV(LA, LS); 5384 const SCEV *RDiff = getMinusSCEV(RA, RS); 5385 if (LDiff == RDiff) 5386 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5387 LDiff = getMinusSCEV(LA, RS); 5388 RDiff = getMinusSCEV(RA, LS); 5389 if (LDiff == RDiff) 5390 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5391 } 5392 break; 5393 case ICmpInst::ICMP_ULT: 5394 case ICmpInst::ICMP_ULE: 5395 std::swap(LHS, RHS); 5396 LLVM_FALLTHROUGH; 5397 case ICmpInst::ICMP_UGT: 5398 case ICmpInst::ICMP_UGE: 5399 // a >u b ? a+x : b+x -> umax(a, b)+x 5400 // a >u b ? b+x : a+x -> umin(a, b)+x 5401 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5402 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5403 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5404 const SCEV *LA = getSCEV(TrueVal); 5405 const SCEV *RA = getSCEV(FalseVal); 5406 const SCEV *LDiff = getMinusSCEV(LA, LS); 5407 const SCEV *RDiff = getMinusSCEV(RA, RS); 5408 if (LDiff == RDiff) 5409 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5410 LDiff = getMinusSCEV(LA, RS); 5411 RDiff = getMinusSCEV(RA, LS); 5412 if (LDiff == RDiff) 5413 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5414 } 5415 break; 5416 case ICmpInst::ICMP_NE: 5417 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5418 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5419 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5420 const SCEV *One = getOne(I->getType()); 5421 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5422 const SCEV *LA = getSCEV(TrueVal); 5423 const SCEV *RA = getSCEV(FalseVal); 5424 const SCEV *LDiff = getMinusSCEV(LA, LS); 5425 const SCEV *RDiff = getMinusSCEV(RA, One); 5426 if (LDiff == RDiff) 5427 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5428 } 5429 break; 5430 case ICmpInst::ICMP_EQ: 5431 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5432 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5433 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5434 const SCEV *One = getOne(I->getType()); 5435 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5436 const SCEV *LA = getSCEV(TrueVal); 5437 const SCEV *RA = getSCEV(FalseVal); 5438 const SCEV *LDiff = getMinusSCEV(LA, One); 5439 const SCEV *RDiff = getMinusSCEV(RA, LS); 5440 if (LDiff == RDiff) 5441 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5442 } 5443 break; 5444 default: 5445 break; 5446 } 5447 5448 return getUnknown(I); 5449 } 5450 5451 /// Expand GEP instructions into add and multiply operations. This allows them 5452 /// to be analyzed by regular SCEV code. 5453 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5454 // Don't attempt to analyze GEPs over unsized objects. 5455 if (!GEP->getSourceElementType()->isSized()) 5456 return getUnknown(GEP); 5457 5458 SmallVector<const SCEV *, 4> IndexExprs; 5459 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5460 IndexExprs.push_back(getSCEV(*Index)); 5461 return getGEPExpr(GEP, IndexExprs); 5462 } 5463 5464 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5465 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5466 return C->getAPInt().countTrailingZeros(); 5467 5468 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5469 return std::min(GetMinTrailingZeros(T->getOperand()), 5470 (uint32_t)getTypeSizeInBits(T->getType())); 5471 5472 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5473 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5474 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5475 ? getTypeSizeInBits(E->getType()) 5476 : OpRes; 5477 } 5478 5479 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5480 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5481 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5482 ? getTypeSizeInBits(E->getType()) 5483 : OpRes; 5484 } 5485 5486 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5487 // The result is the min of all operands results. 5488 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5489 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5490 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5491 return MinOpRes; 5492 } 5493 5494 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5495 // The result is the sum of all operands results. 5496 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5497 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5498 for (unsigned i = 1, e = M->getNumOperands(); 5499 SumOpRes != BitWidth && i != e; ++i) 5500 SumOpRes = 5501 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5502 return SumOpRes; 5503 } 5504 5505 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5506 // The result is the min of all operands results. 5507 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5508 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5509 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5510 return MinOpRes; 5511 } 5512 5513 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5514 // The result is the min of all operands results. 5515 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5516 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5517 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5518 return MinOpRes; 5519 } 5520 5521 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5522 // The result is the min of all operands results. 5523 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5524 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5525 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5526 return MinOpRes; 5527 } 5528 5529 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5530 // For a SCEVUnknown, ask ValueTracking. 5531 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5532 return Known.countMinTrailingZeros(); 5533 } 5534 5535 // SCEVUDivExpr 5536 return 0; 5537 } 5538 5539 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5540 auto I = MinTrailingZerosCache.find(S); 5541 if (I != MinTrailingZerosCache.end()) 5542 return I->second; 5543 5544 uint32_t Result = GetMinTrailingZerosImpl(S); 5545 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5546 assert(InsertPair.second && "Should insert a new key"); 5547 return InsertPair.first->second; 5548 } 5549 5550 /// Helper method to assign a range to V from metadata present in the IR. 5551 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5552 if (Instruction *I = dyn_cast<Instruction>(V)) 5553 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5554 return getConstantRangeFromMetadata(*MD); 5555 5556 return None; 5557 } 5558 5559 /// Determine the range for a particular SCEV. If SignHint is 5560 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5561 /// with a "cleaner" unsigned (resp. signed) representation. 5562 const ConstantRange & 5563 ScalarEvolution::getRangeRef(const SCEV *S, 5564 ScalarEvolution::RangeSignHint SignHint) { 5565 DenseMap<const SCEV *, ConstantRange> &Cache = 5566 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5567 : SignedRanges; 5568 5569 // See if we've computed this range already. 5570 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5571 if (I != Cache.end()) 5572 return I->second; 5573 5574 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5575 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5576 5577 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5578 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5579 5580 // If the value has known zeros, the maximum value will have those known zeros 5581 // as well. 5582 uint32_t TZ = GetMinTrailingZeros(S); 5583 if (TZ != 0) { 5584 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5585 ConservativeResult = 5586 ConstantRange(APInt::getMinValue(BitWidth), 5587 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5588 else 5589 ConservativeResult = ConstantRange( 5590 APInt::getSignedMinValue(BitWidth), 5591 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5592 } 5593 5594 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5595 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5596 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5597 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5598 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5599 } 5600 5601 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5602 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5603 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5604 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5605 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5606 } 5607 5608 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5609 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5610 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5611 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5612 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5613 } 5614 5615 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5616 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5617 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5618 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5619 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5620 } 5621 5622 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5623 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5624 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5625 return setRange(UDiv, SignHint, 5626 ConservativeResult.intersectWith(X.udiv(Y))); 5627 } 5628 5629 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5630 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5631 return setRange(ZExt, SignHint, 5632 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5633 } 5634 5635 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5636 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5637 return setRange(SExt, SignHint, 5638 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5639 } 5640 5641 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5642 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5643 return setRange(Trunc, SignHint, 5644 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5645 } 5646 5647 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5648 // If there's no unsigned wrap, the value will never be less than its 5649 // initial value. 5650 if (AddRec->hasNoUnsignedWrap()) 5651 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5652 if (!C->getValue()->isZero()) 5653 ConservativeResult = ConservativeResult.intersectWith( 5654 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5655 5656 // If there's no signed wrap, and all the operands have the same sign or 5657 // zero, the value won't ever change sign. 5658 if (AddRec->hasNoSignedWrap()) { 5659 bool AllNonNeg = true; 5660 bool AllNonPos = true; 5661 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5662 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5663 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5664 } 5665 if (AllNonNeg) 5666 ConservativeResult = ConservativeResult.intersectWith( 5667 ConstantRange(APInt(BitWidth, 0), 5668 APInt::getSignedMinValue(BitWidth))); 5669 else if (AllNonPos) 5670 ConservativeResult = ConservativeResult.intersectWith( 5671 ConstantRange(APInt::getSignedMinValue(BitWidth), 5672 APInt(BitWidth, 1))); 5673 } 5674 5675 // TODO: non-affine addrec 5676 if (AddRec->isAffine()) { 5677 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5678 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5679 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5680 auto RangeFromAffine = getRangeForAffineAR( 5681 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5682 BitWidth); 5683 if (!RangeFromAffine.isFullSet()) 5684 ConservativeResult = 5685 ConservativeResult.intersectWith(RangeFromAffine); 5686 5687 auto RangeFromFactoring = getRangeViaFactoring( 5688 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5689 BitWidth); 5690 if (!RangeFromFactoring.isFullSet()) 5691 ConservativeResult = 5692 ConservativeResult.intersectWith(RangeFromFactoring); 5693 } 5694 } 5695 5696 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5697 } 5698 5699 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5700 // Check if the IR explicitly contains !range metadata. 5701 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5702 if (MDRange.hasValue()) 5703 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5704 5705 // Split here to avoid paying the compile-time cost of calling both 5706 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5707 // if needed. 5708 const DataLayout &DL = getDataLayout(); 5709 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5710 // For a SCEVUnknown, ask ValueTracking. 5711 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5712 if (Known.One != ~Known.Zero + 1) 5713 ConservativeResult = 5714 ConservativeResult.intersectWith(ConstantRange(Known.One, 5715 ~Known.Zero + 1)); 5716 } else { 5717 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5718 "generalize as needed!"); 5719 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5720 if (NS > 1) 5721 ConservativeResult = ConservativeResult.intersectWith( 5722 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5723 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5724 } 5725 5726 // A range of Phi is a subset of union of all ranges of its input. 5727 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5728 // Make sure that we do not run over cycled Phis. 5729 if (PendingPhiRanges.insert(Phi).second) { 5730 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5731 for (auto &Op : Phi->operands()) { 5732 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5733 RangeFromOps = RangeFromOps.unionWith(OpRange); 5734 // No point to continue if we already have a full set. 5735 if (RangeFromOps.isFullSet()) 5736 break; 5737 } 5738 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps); 5739 bool Erased = PendingPhiRanges.erase(Phi); 5740 assert(Erased && "Failed to erase Phi properly?"); 5741 (void) Erased; 5742 } 5743 } 5744 5745 return setRange(U, SignHint, std::move(ConservativeResult)); 5746 } 5747 5748 return setRange(S, SignHint, std::move(ConservativeResult)); 5749 } 5750 5751 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5752 // values that the expression can take. Initially, the expression has a value 5753 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5754 // argument defines if we treat Step as signed or unsigned. 5755 static ConstantRange getRangeForAffineARHelper(APInt Step, 5756 const ConstantRange &StartRange, 5757 const APInt &MaxBECount, 5758 unsigned BitWidth, bool Signed) { 5759 // If either Step or MaxBECount is 0, then the expression won't change, and we 5760 // just need to return the initial range. 5761 if (Step == 0 || MaxBECount == 0) 5762 return StartRange; 5763 5764 // If we don't know anything about the initial value (i.e. StartRange is 5765 // FullRange), then we don't know anything about the final range either. 5766 // Return FullRange. 5767 if (StartRange.isFullSet()) 5768 return ConstantRange::getFull(BitWidth); 5769 5770 // If Step is signed and negative, then we use its absolute value, but we also 5771 // note that we're moving in the opposite direction. 5772 bool Descending = Signed && Step.isNegative(); 5773 5774 if (Signed) 5775 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5776 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5777 // This equations hold true due to the well-defined wrap-around behavior of 5778 // APInt. 5779 Step = Step.abs(); 5780 5781 // Check if Offset is more than full span of BitWidth. If it is, the 5782 // expression is guaranteed to overflow. 5783 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5784 return ConstantRange::getFull(BitWidth); 5785 5786 // Offset is by how much the expression can change. Checks above guarantee no 5787 // overflow here. 5788 APInt Offset = Step * MaxBECount; 5789 5790 // Minimum value of the final range will match the minimal value of StartRange 5791 // if the expression is increasing and will be decreased by Offset otherwise. 5792 // Maximum value of the final range will match the maximal value of StartRange 5793 // if the expression is decreasing and will be increased by Offset otherwise. 5794 APInt StartLower = StartRange.getLower(); 5795 APInt StartUpper = StartRange.getUpper() - 1; 5796 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5797 : (StartUpper + std::move(Offset)); 5798 5799 // It's possible that the new minimum/maximum value will fall into the initial 5800 // range (due to wrap around). This means that the expression can take any 5801 // value in this bitwidth, and we have to return full range. 5802 if (StartRange.contains(MovedBoundary)) 5803 return ConstantRange::getFull(BitWidth); 5804 5805 APInt NewLower = 5806 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5807 APInt NewUpper = 5808 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5809 NewUpper += 1; 5810 5811 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5812 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5813 } 5814 5815 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5816 const SCEV *Step, 5817 const SCEV *MaxBECount, 5818 unsigned BitWidth) { 5819 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5820 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5821 "Precondition!"); 5822 5823 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5824 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5825 5826 // First, consider step signed. 5827 ConstantRange StartSRange = getSignedRange(Start); 5828 ConstantRange StepSRange = getSignedRange(Step); 5829 5830 // If Step can be both positive and negative, we need to find ranges for the 5831 // maximum absolute step values in both directions and union them. 5832 ConstantRange SR = 5833 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5834 MaxBECountValue, BitWidth, /* Signed = */ true); 5835 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5836 StartSRange, MaxBECountValue, 5837 BitWidth, /* Signed = */ true)); 5838 5839 // Next, consider step unsigned. 5840 ConstantRange UR = getRangeForAffineARHelper( 5841 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5842 MaxBECountValue, BitWidth, /* Signed = */ false); 5843 5844 // Finally, intersect signed and unsigned ranges. 5845 return SR.intersectWith(UR); 5846 } 5847 5848 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5849 const SCEV *Step, 5850 const SCEV *MaxBECount, 5851 unsigned BitWidth) { 5852 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5853 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5854 5855 struct SelectPattern { 5856 Value *Condition = nullptr; 5857 APInt TrueValue; 5858 APInt FalseValue; 5859 5860 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5861 const SCEV *S) { 5862 Optional<unsigned> CastOp; 5863 APInt Offset(BitWidth, 0); 5864 5865 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5866 "Should be!"); 5867 5868 // Peel off a constant offset: 5869 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5870 // In the future we could consider being smarter here and handle 5871 // {Start+Step,+,Step} too. 5872 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5873 return; 5874 5875 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5876 S = SA->getOperand(1); 5877 } 5878 5879 // Peel off a cast operation 5880 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5881 CastOp = SCast->getSCEVType(); 5882 S = SCast->getOperand(); 5883 } 5884 5885 using namespace llvm::PatternMatch; 5886 5887 auto *SU = dyn_cast<SCEVUnknown>(S); 5888 const APInt *TrueVal, *FalseVal; 5889 if (!SU || 5890 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5891 m_APInt(FalseVal)))) { 5892 Condition = nullptr; 5893 return; 5894 } 5895 5896 TrueValue = *TrueVal; 5897 FalseValue = *FalseVal; 5898 5899 // Re-apply the cast we peeled off earlier 5900 if (CastOp.hasValue()) 5901 switch (*CastOp) { 5902 default: 5903 llvm_unreachable("Unknown SCEV cast type!"); 5904 5905 case scTruncate: 5906 TrueValue = TrueValue.trunc(BitWidth); 5907 FalseValue = FalseValue.trunc(BitWidth); 5908 break; 5909 case scZeroExtend: 5910 TrueValue = TrueValue.zext(BitWidth); 5911 FalseValue = FalseValue.zext(BitWidth); 5912 break; 5913 case scSignExtend: 5914 TrueValue = TrueValue.sext(BitWidth); 5915 FalseValue = FalseValue.sext(BitWidth); 5916 break; 5917 } 5918 5919 // Re-apply the constant offset we peeled off earlier 5920 TrueValue += Offset; 5921 FalseValue += Offset; 5922 } 5923 5924 bool isRecognized() { return Condition != nullptr; } 5925 }; 5926 5927 SelectPattern StartPattern(*this, BitWidth, Start); 5928 if (!StartPattern.isRecognized()) 5929 return ConstantRange::getFull(BitWidth); 5930 5931 SelectPattern StepPattern(*this, BitWidth, Step); 5932 if (!StepPattern.isRecognized()) 5933 return ConstantRange::getFull(BitWidth); 5934 5935 if (StartPattern.Condition != StepPattern.Condition) { 5936 // We don't handle this case today; but we could, by considering four 5937 // possibilities below instead of two. I'm not sure if there are cases where 5938 // that will help over what getRange already does, though. 5939 return ConstantRange::getFull(BitWidth); 5940 } 5941 5942 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5943 // construct arbitrary general SCEV expressions here. This function is called 5944 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5945 // say) can end up caching a suboptimal value. 5946 5947 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5948 // C2352 and C2512 (otherwise it isn't needed). 5949 5950 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5951 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5952 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5953 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5954 5955 ConstantRange TrueRange = 5956 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5957 ConstantRange FalseRange = 5958 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5959 5960 return TrueRange.unionWith(FalseRange); 5961 } 5962 5963 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5964 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5965 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5966 5967 // Return early if there are no flags to propagate to the SCEV. 5968 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5969 if (BinOp->hasNoUnsignedWrap()) 5970 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5971 if (BinOp->hasNoSignedWrap()) 5972 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5973 if (Flags == SCEV::FlagAnyWrap) 5974 return SCEV::FlagAnyWrap; 5975 5976 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5977 } 5978 5979 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5980 // Here we check that I is in the header of the innermost loop containing I, 5981 // since we only deal with instructions in the loop header. The actual loop we 5982 // need to check later will come from an add recurrence, but getting that 5983 // requires computing the SCEV of the operands, which can be expensive. This 5984 // check we can do cheaply to rule out some cases early. 5985 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5986 if (InnermostContainingLoop == nullptr || 5987 InnermostContainingLoop->getHeader() != I->getParent()) 5988 return false; 5989 5990 // Only proceed if we can prove that I does not yield poison. 5991 if (!programUndefinedIfFullPoison(I)) 5992 return false; 5993 5994 // At this point we know that if I is executed, then it does not wrap 5995 // according to at least one of NSW or NUW. If I is not executed, then we do 5996 // not know if the calculation that I represents would wrap. Multiple 5997 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5998 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5999 // derived from other instructions that map to the same SCEV. We cannot make 6000 // that guarantee for cases where I is not executed. So we need to find the 6001 // loop that I is considered in relation to and prove that I is executed for 6002 // every iteration of that loop. That implies that the value that I 6003 // calculates does not wrap anywhere in the loop, so then we can apply the 6004 // flags to the SCEV. 6005 // 6006 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6007 // from different loops, so that we know which loop to prove that I is 6008 // executed in. 6009 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6010 // I could be an extractvalue from a call to an overflow intrinsic. 6011 // TODO: We can do better here in some cases. 6012 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6013 return false; 6014 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6015 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6016 bool AllOtherOpsLoopInvariant = true; 6017 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6018 ++OtherOpIndex) { 6019 if (OtherOpIndex != OpIndex) { 6020 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6021 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6022 AllOtherOpsLoopInvariant = false; 6023 break; 6024 } 6025 } 6026 } 6027 if (AllOtherOpsLoopInvariant && 6028 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6029 return true; 6030 } 6031 } 6032 return false; 6033 } 6034 6035 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6036 // If we know that \c I can never be poison period, then that's enough. 6037 if (isSCEVExprNeverPoison(I)) 6038 return true; 6039 6040 // For an add recurrence specifically, we assume that infinite loops without 6041 // side effects are undefined behavior, and then reason as follows: 6042 // 6043 // If the add recurrence is poison in any iteration, it is poison on all 6044 // future iterations (since incrementing poison yields poison). If the result 6045 // of the add recurrence is fed into the loop latch condition and the loop 6046 // does not contain any throws or exiting blocks other than the latch, we now 6047 // have the ability to "choose" whether the backedge is taken or not (by 6048 // choosing a sufficiently evil value for the poison feeding into the branch) 6049 // for every iteration including and after the one in which \p I first became 6050 // poison. There are two possibilities (let's call the iteration in which \p 6051 // I first became poison as K): 6052 // 6053 // 1. In the set of iterations including and after K, the loop body executes 6054 // no side effects. In this case executing the backege an infinte number 6055 // of times will yield undefined behavior. 6056 // 6057 // 2. In the set of iterations including and after K, the loop body executes 6058 // at least one side effect. In this case, that specific instance of side 6059 // effect is control dependent on poison, which also yields undefined 6060 // behavior. 6061 6062 auto *ExitingBB = L->getExitingBlock(); 6063 auto *LatchBB = L->getLoopLatch(); 6064 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6065 return false; 6066 6067 SmallPtrSet<const Instruction *, 16> Pushed; 6068 SmallVector<const Instruction *, 8> PoisonStack; 6069 6070 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6071 // things that are known to be fully poison under that assumption go on the 6072 // PoisonStack. 6073 Pushed.insert(I); 6074 PoisonStack.push_back(I); 6075 6076 bool LatchControlDependentOnPoison = false; 6077 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6078 const Instruction *Poison = PoisonStack.pop_back_val(); 6079 6080 for (auto *PoisonUser : Poison->users()) { 6081 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6082 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6083 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6084 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6085 assert(BI->isConditional() && "Only possibility!"); 6086 if (BI->getParent() == LatchBB) { 6087 LatchControlDependentOnPoison = true; 6088 break; 6089 } 6090 } 6091 } 6092 } 6093 6094 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6095 } 6096 6097 ScalarEvolution::LoopProperties 6098 ScalarEvolution::getLoopProperties(const Loop *L) { 6099 using LoopProperties = ScalarEvolution::LoopProperties; 6100 6101 auto Itr = LoopPropertiesCache.find(L); 6102 if (Itr == LoopPropertiesCache.end()) { 6103 auto HasSideEffects = [](Instruction *I) { 6104 if (auto *SI = dyn_cast<StoreInst>(I)) 6105 return !SI->isSimple(); 6106 6107 return I->mayHaveSideEffects(); 6108 }; 6109 6110 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6111 /*HasNoSideEffects*/ true}; 6112 6113 for (auto *BB : L->getBlocks()) 6114 for (auto &I : *BB) { 6115 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6116 LP.HasNoAbnormalExits = false; 6117 if (HasSideEffects(&I)) 6118 LP.HasNoSideEffects = false; 6119 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6120 break; // We're already as pessimistic as we can get. 6121 } 6122 6123 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6124 assert(InsertPair.second && "We just checked!"); 6125 Itr = InsertPair.first; 6126 } 6127 6128 return Itr->second; 6129 } 6130 6131 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6132 if (!isSCEVable(V->getType())) 6133 return getUnknown(V); 6134 6135 if (Instruction *I = dyn_cast<Instruction>(V)) { 6136 // Don't attempt to analyze instructions in blocks that aren't 6137 // reachable. Such instructions don't matter, and they aren't required 6138 // to obey basic rules for definitions dominating uses which this 6139 // analysis depends on. 6140 if (!DT.isReachableFromEntry(I->getParent())) 6141 return getUnknown(UndefValue::get(V->getType())); 6142 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6143 return getConstant(CI); 6144 else if (isa<ConstantPointerNull>(V)) 6145 return getZero(V->getType()); 6146 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6147 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6148 else if (!isa<ConstantExpr>(V)) 6149 return getUnknown(V); 6150 6151 Operator *U = cast<Operator>(V); 6152 if (auto BO = MatchBinaryOp(U, DT)) { 6153 switch (BO->Opcode) { 6154 case Instruction::Add: { 6155 // The simple thing to do would be to just call getSCEV on both operands 6156 // and call getAddExpr with the result. However if we're looking at a 6157 // bunch of things all added together, this can be quite inefficient, 6158 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6159 // Instead, gather up all the operands and make a single getAddExpr call. 6160 // LLVM IR canonical form means we need only traverse the left operands. 6161 SmallVector<const SCEV *, 4> AddOps; 6162 do { 6163 if (BO->Op) { 6164 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6165 AddOps.push_back(OpSCEV); 6166 break; 6167 } 6168 6169 // If a NUW or NSW flag can be applied to the SCEV for this 6170 // addition, then compute the SCEV for this addition by itself 6171 // with a separate call to getAddExpr. We need to do that 6172 // instead of pushing the operands of the addition onto AddOps, 6173 // since the flags are only known to apply to this particular 6174 // addition - they may not apply to other additions that can be 6175 // formed with operands from AddOps. 6176 const SCEV *RHS = getSCEV(BO->RHS); 6177 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6178 if (Flags != SCEV::FlagAnyWrap) { 6179 const SCEV *LHS = getSCEV(BO->LHS); 6180 if (BO->Opcode == Instruction::Sub) 6181 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6182 else 6183 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6184 break; 6185 } 6186 } 6187 6188 if (BO->Opcode == Instruction::Sub) 6189 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6190 else 6191 AddOps.push_back(getSCEV(BO->RHS)); 6192 6193 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6194 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6195 NewBO->Opcode != Instruction::Sub)) { 6196 AddOps.push_back(getSCEV(BO->LHS)); 6197 break; 6198 } 6199 BO = NewBO; 6200 } while (true); 6201 6202 return getAddExpr(AddOps); 6203 } 6204 6205 case Instruction::Mul: { 6206 SmallVector<const SCEV *, 4> MulOps; 6207 do { 6208 if (BO->Op) { 6209 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6210 MulOps.push_back(OpSCEV); 6211 break; 6212 } 6213 6214 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6215 if (Flags != SCEV::FlagAnyWrap) { 6216 MulOps.push_back( 6217 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6218 break; 6219 } 6220 } 6221 6222 MulOps.push_back(getSCEV(BO->RHS)); 6223 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6224 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6225 MulOps.push_back(getSCEV(BO->LHS)); 6226 break; 6227 } 6228 BO = NewBO; 6229 } while (true); 6230 6231 return getMulExpr(MulOps); 6232 } 6233 case Instruction::UDiv: 6234 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6235 case Instruction::URem: 6236 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6237 case Instruction::Sub: { 6238 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6239 if (BO->Op) 6240 Flags = getNoWrapFlagsFromUB(BO->Op); 6241 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6242 } 6243 case Instruction::And: 6244 // For an expression like x&255 that merely masks off the high bits, 6245 // use zext(trunc(x)) as the SCEV expression. 6246 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6247 if (CI->isZero()) 6248 return getSCEV(BO->RHS); 6249 if (CI->isMinusOne()) 6250 return getSCEV(BO->LHS); 6251 const APInt &A = CI->getValue(); 6252 6253 // Instcombine's ShrinkDemandedConstant may strip bits out of 6254 // constants, obscuring what would otherwise be a low-bits mask. 6255 // Use computeKnownBits to compute what ShrinkDemandedConstant 6256 // knew about to reconstruct a low-bits mask value. 6257 unsigned LZ = A.countLeadingZeros(); 6258 unsigned TZ = A.countTrailingZeros(); 6259 unsigned BitWidth = A.getBitWidth(); 6260 KnownBits Known(BitWidth); 6261 computeKnownBits(BO->LHS, Known, getDataLayout(), 6262 0, &AC, nullptr, &DT); 6263 6264 APInt EffectiveMask = 6265 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6266 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6267 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6268 const SCEV *LHS = getSCEV(BO->LHS); 6269 const SCEV *ShiftedLHS = nullptr; 6270 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6271 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6272 // For an expression like (x * 8) & 8, simplify the multiply. 6273 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6274 unsigned GCD = std::min(MulZeros, TZ); 6275 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6276 SmallVector<const SCEV*, 4> MulOps; 6277 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6278 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6279 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6280 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6281 } 6282 } 6283 if (!ShiftedLHS) 6284 ShiftedLHS = getUDivExpr(LHS, MulCount); 6285 return getMulExpr( 6286 getZeroExtendExpr( 6287 getTruncateExpr(ShiftedLHS, 6288 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6289 BO->LHS->getType()), 6290 MulCount); 6291 } 6292 } 6293 break; 6294 6295 case Instruction::Or: 6296 // If the RHS of the Or is a constant, we may have something like: 6297 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6298 // optimizations will transparently handle this case. 6299 // 6300 // In order for this transformation to be safe, the LHS must be of the 6301 // form X*(2^n) and the Or constant must be less than 2^n. 6302 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6303 const SCEV *LHS = getSCEV(BO->LHS); 6304 const APInt &CIVal = CI->getValue(); 6305 if (GetMinTrailingZeros(LHS) >= 6306 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6307 // Build a plain add SCEV. 6308 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6309 // If the LHS of the add was an addrec and it has no-wrap flags, 6310 // transfer the no-wrap flags, since an or won't introduce a wrap. 6311 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6312 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6313 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6314 OldAR->getNoWrapFlags()); 6315 } 6316 return S; 6317 } 6318 } 6319 break; 6320 6321 case Instruction::Xor: 6322 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6323 // If the RHS of xor is -1, then this is a not operation. 6324 if (CI->isMinusOne()) 6325 return getNotSCEV(getSCEV(BO->LHS)); 6326 6327 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6328 // This is a variant of the check for xor with -1, and it handles 6329 // the case where instcombine has trimmed non-demanded bits out 6330 // of an xor with -1. 6331 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6332 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6333 if (LBO->getOpcode() == Instruction::And && 6334 LCI->getValue() == CI->getValue()) 6335 if (const SCEVZeroExtendExpr *Z = 6336 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6337 Type *UTy = BO->LHS->getType(); 6338 const SCEV *Z0 = Z->getOperand(); 6339 Type *Z0Ty = Z0->getType(); 6340 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6341 6342 // If C is a low-bits mask, the zero extend is serving to 6343 // mask off the high bits. Complement the operand and 6344 // re-apply the zext. 6345 if (CI->getValue().isMask(Z0TySize)) 6346 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6347 6348 // If C is a single bit, it may be in the sign-bit position 6349 // before the zero-extend. In this case, represent the xor 6350 // using an add, which is equivalent, and re-apply the zext. 6351 APInt Trunc = CI->getValue().trunc(Z0TySize); 6352 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6353 Trunc.isSignMask()) 6354 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6355 UTy); 6356 } 6357 } 6358 break; 6359 6360 case Instruction::Shl: 6361 // Turn shift left of a constant amount into a multiply. 6362 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6363 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6364 6365 // If the shift count is not less than the bitwidth, the result of 6366 // the shift is undefined. Don't try to analyze it, because the 6367 // resolution chosen here may differ from the resolution chosen in 6368 // other parts of the compiler. 6369 if (SA->getValue().uge(BitWidth)) 6370 break; 6371 6372 // It is currently not resolved how to interpret NSW for left 6373 // shift by BitWidth - 1, so we avoid applying flags in that 6374 // case. Remove this check (or this comment) once the situation 6375 // is resolved. See 6376 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6377 // and http://reviews.llvm.org/D8890 . 6378 auto Flags = SCEV::FlagAnyWrap; 6379 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6380 Flags = getNoWrapFlagsFromUB(BO->Op); 6381 6382 Constant *X = ConstantInt::get( 6383 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6384 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6385 } 6386 break; 6387 6388 case Instruction::AShr: { 6389 // AShr X, C, where C is a constant. 6390 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6391 if (!CI) 6392 break; 6393 6394 Type *OuterTy = BO->LHS->getType(); 6395 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6396 // If the shift count is not less than the bitwidth, the result of 6397 // the shift is undefined. Don't try to analyze it, because the 6398 // resolution chosen here may differ from the resolution chosen in 6399 // other parts of the compiler. 6400 if (CI->getValue().uge(BitWidth)) 6401 break; 6402 6403 if (CI->isZero()) 6404 return getSCEV(BO->LHS); // shift by zero --> noop 6405 6406 uint64_t AShrAmt = CI->getZExtValue(); 6407 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6408 6409 Operator *L = dyn_cast<Operator>(BO->LHS); 6410 if (L && L->getOpcode() == Instruction::Shl) { 6411 // X = Shl A, n 6412 // Y = AShr X, m 6413 // Both n and m are constant. 6414 6415 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6416 if (L->getOperand(1) == BO->RHS) 6417 // For a two-shift sext-inreg, i.e. n = m, 6418 // use sext(trunc(x)) as the SCEV expression. 6419 return getSignExtendExpr( 6420 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6421 6422 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6423 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6424 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6425 if (ShlAmt > AShrAmt) { 6426 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6427 // expression. We already checked that ShlAmt < BitWidth, so 6428 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6429 // ShlAmt - AShrAmt < Amt. 6430 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6431 ShlAmt - AShrAmt); 6432 return getSignExtendExpr( 6433 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6434 getConstant(Mul)), OuterTy); 6435 } 6436 } 6437 } 6438 break; 6439 } 6440 } 6441 } 6442 6443 switch (U->getOpcode()) { 6444 case Instruction::Trunc: 6445 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6446 6447 case Instruction::ZExt: 6448 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6449 6450 case Instruction::SExt: 6451 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6452 // The NSW flag of a subtract does not always survive the conversion to 6453 // A + (-1)*B. By pushing sign extension onto its operands we are much 6454 // more likely to preserve NSW and allow later AddRec optimisations. 6455 // 6456 // NOTE: This is effectively duplicating this logic from getSignExtend: 6457 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6458 // but by that point the NSW information has potentially been lost. 6459 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6460 Type *Ty = U->getType(); 6461 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6462 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6463 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6464 } 6465 } 6466 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6467 6468 case Instruction::BitCast: 6469 // BitCasts are no-op casts so we just eliminate the cast. 6470 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6471 return getSCEV(U->getOperand(0)); 6472 break; 6473 6474 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6475 // lead to pointer expressions which cannot safely be expanded to GEPs, 6476 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6477 // simplifying integer expressions. 6478 6479 case Instruction::GetElementPtr: 6480 return createNodeForGEP(cast<GEPOperator>(U)); 6481 6482 case Instruction::PHI: 6483 return createNodeForPHI(cast<PHINode>(U)); 6484 6485 case Instruction::Select: 6486 // U can also be a select constant expr, which let fall through. Since 6487 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6488 // constant expressions cannot have instructions as operands, we'd have 6489 // returned getUnknown for a select constant expressions anyway. 6490 if (isa<Instruction>(U)) 6491 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6492 U->getOperand(1), U->getOperand(2)); 6493 break; 6494 6495 case Instruction::Call: 6496 case Instruction::Invoke: 6497 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6498 return getSCEV(RV); 6499 break; 6500 } 6501 6502 return getUnknown(V); 6503 } 6504 6505 //===----------------------------------------------------------------------===// 6506 // Iteration Count Computation Code 6507 // 6508 6509 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6510 if (!ExitCount) 6511 return 0; 6512 6513 ConstantInt *ExitConst = ExitCount->getValue(); 6514 6515 // Guard against huge trip counts. 6516 if (ExitConst->getValue().getActiveBits() > 32) 6517 return 0; 6518 6519 // In case of integer overflow, this returns 0, which is correct. 6520 return ((unsigned)ExitConst->getZExtValue()) + 1; 6521 } 6522 6523 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6524 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6525 return getSmallConstantTripCount(L, ExitingBB); 6526 6527 // No trip count information for multiple exits. 6528 return 0; 6529 } 6530 6531 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6532 BasicBlock *ExitingBlock) { 6533 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6534 assert(L->isLoopExiting(ExitingBlock) && 6535 "Exiting block must actually branch out of the loop!"); 6536 const SCEVConstant *ExitCount = 6537 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6538 return getConstantTripCount(ExitCount); 6539 } 6540 6541 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6542 const auto *MaxExitCount = 6543 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6544 return getConstantTripCount(MaxExitCount); 6545 } 6546 6547 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6548 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6549 return getSmallConstantTripMultiple(L, ExitingBB); 6550 6551 // No trip multiple information for multiple exits. 6552 return 0; 6553 } 6554 6555 /// Returns the largest constant divisor of the trip count of this loop as a 6556 /// normal unsigned value, if possible. This means that the actual trip count is 6557 /// always a multiple of the returned value (don't forget the trip count could 6558 /// very well be zero as well!). 6559 /// 6560 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6561 /// multiple of a constant (which is also the case if the trip count is simply 6562 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6563 /// if the trip count is very large (>= 2^32). 6564 /// 6565 /// As explained in the comments for getSmallConstantTripCount, this assumes 6566 /// that control exits the loop via ExitingBlock. 6567 unsigned 6568 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6569 BasicBlock *ExitingBlock) { 6570 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6571 assert(L->isLoopExiting(ExitingBlock) && 6572 "Exiting block must actually branch out of the loop!"); 6573 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6574 if (ExitCount == getCouldNotCompute()) 6575 return 1; 6576 6577 // Get the trip count from the BE count by adding 1. 6578 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6579 6580 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6581 if (!TC) 6582 // Attempt to factor more general cases. Returns the greatest power of 6583 // two divisor. If overflow happens, the trip count expression is still 6584 // divisible by the greatest power of 2 divisor returned. 6585 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6586 6587 ConstantInt *Result = TC->getValue(); 6588 6589 // Guard against huge trip counts (this requires checking 6590 // for zero to handle the case where the trip count == -1 and the 6591 // addition wraps). 6592 if (!Result || Result->getValue().getActiveBits() > 32 || 6593 Result->getValue().getActiveBits() == 0) 6594 return 1; 6595 6596 return (unsigned)Result->getZExtValue(); 6597 } 6598 6599 /// Get the expression for the number of loop iterations for which this loop is 6600 /// guaranteed not to exit via ExitingBlock. Otherwise return 6601 /// SCEVCouldNotCompute. 6602 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6603 BasicBlock *ExitingBlock) { 6604 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6605 } 6606 6607 const SCEV * 6608 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6609 SCEVUnionPredicate &Preds) { 6610 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6611 } 6612 6613 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6614 return getBackedgeTakenInfo(L).getExact(L, this); 6615 } 6616 6617 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6618 /// known never to be less than the actual backedge taken count. 6619 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6620 return getBackedgeTakenInfo(L).getMax(this); 6621 } 6622 6623 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6624 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6625 } 6626 6627 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6628 static void 6629 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6630 BasicBlock *Header = L->getHeader(); 6631 6632 // Push all Loop-header PHIs onto the Worklist stack. 6633 for (PHINode &PN : Header->phis()) 6634 Worklist.push_back(&PN); 6635 } 6636 6637 const ScalarEvolution::BackedgeTakenInfo & 6638 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6639 auto &BTI = getBackedgeTakenInfo(L); 6640 if (BTI.hasFullInfo()) 6641 return BTI; 6642 6643 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6644 6645 if (!Pair.second) 6646 return Pair.first->second; 6647 6648 BackedgeTakenInfo Result = 6649 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6650 6651 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6652 } 6653 6654 const ScalarEvolution::BackedgeTakenInfo & 6655 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6656 // Initially insert an invalid entry for this loop. If the insertion 6657 // succeeds, proceed to actually compute a backedge-taken count and 6658 // update the value. The temporary CouldNotCompute value tells SCEV 6659 // code elsewhere that it shouldn't attempt to request a new 6660 // backedge-taken count, which could result in infinite recursion. 6661 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6662 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6663 if (!Pair.second) 6664 return Pair.first->second; 6665 6666 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6667 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6668 // must be cleared in this scope. 6669 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6670 6671 // In product build, there are no usage of statistic. 6672 (void)NumTripCountsComputed; 6673 (void)NumTripCountsNotComputed; 6674 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6675 const SCEV *BEExact = Result.getExact(L, this); 6676 if (BEExact != getCouldNotCompute()) { 6677 assert(isLoopInvariant(BEExact, L) && 6678 isLoopInvariant(Result.getMax(this), L) && 6679 "Computed backedge-taken count isn't loop invariant for loop!"); 6680 ++NumTripCountsComputed; 6681 } 6682 else if (Result.getMax(this) == getCouldNotCompute() && 6683 isa<PHINode>(L->getHeader()->begin())) { 6684 // Only count loops that have phi nodes as not being computable. 6685 ++NumTripCountsNotComputed; 6686 } 6687 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6688 6689 // Now that we know more about the trip count for this loop, forget any 6690 // existing SCEV values for PHI nodes in this loop since they are only 6691 // conservative estimates made without the benefit of trip count 6692 // information. This is similar to the code in forgetLoop, except that 6693 // it handles SCEVUnknown PHI nodes specially. 6694 if (Result.hasAnyInfo()) { 6695 SmallVector<Instruction *, 16> Worklist; 6696 PushLoopPHIs(L, Worklist); 6697 6698 SmallPtrSet<Instruction *, 8> Discovered; 6699 while (!Worklist.empty()) { 6700 Instruction *I = Worklist.pop_back_val(); 6701 6702 ValueExprMapType::iterator It = 6703 ValueExprMap.find_as(static_cast<Value *>(I)); 6704 if (It != ValueExprMap.end()) { 6705 const SCEV *Old = It->second; 6706 6707 // SCEVUnknown for a PHI either means that it has an unrecognized 6708 // structure, or it's a PHI that's in the progress of being computed 6709 // by createNodeForPHI. In the former case, additional loop trip 6710 // count information isn't going to change anything. In the later 6711 // case, createNodeForPHI will perform the necessary updates on its 6712 // own when it gets to that point. 6713 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6714 eraseValueFromMap(It->first); 6715 forgetMemoizedResults(Old); 6716 } 6717 if (PHINode *PN = dyn_cast<PHINode>(I)) 6718 ConstantEvolutionLoopExitValue.erase(PN); 6719 } 6720 6721 // Since we don't need to invalidate anything for correctness and we're 6722 // only invalidating to make SCEV's results more precise, we get to stop 6723 // early to avoid invalidating too much. This is especially important in 6724 // cases like: 6725 // 6726 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6727 // loop0: 6728 // %pn0 = phi 6729 // ... 6730 // loop1: 6731 // %pn1 = phi 6732 // ... 6733 // 6734 // where both loop0 and loop1's backedge taken count uses the SCEV 6735 // expression for %v. If we don't have the early stop below then in cases 6736 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6737 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6738 // count for loop1, effectively nullifying SCEV's trip count cache. 6739 for (auto *U : I->users()) 6740 if (auto *I = dyn_cast<Instruction>(U)) { 6741 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6742 if (LoopForUser && L->contains(LoopForUser) && 6743 Discovered.insert(I).second) 6744 Worklist.push_back(I); 6745 } 6746 } 6747 } 6748 6749 // Re-lookup the insert position, since the call to 6750 // computeBackedgeTakenCount above could result in a 6751 // recusive call to getBackedgeTakenInfo (on a different 6752 // loop), which would invalidate the iterator computed 6753 // earlier. 6754 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6755 } 6756 6757 void ScalarEvolution::forgetAllLoops() { 6758 // This method is intended to forget all info about loops. It should 6759 // invalidate caches as if the following happened: 6760 // - The trip counts of all loops have changed arbitrarily 6761 // - Every llvm::Value has been updated in place to produce a different 6762 // result. 6763 BackedgeTakenCounts.clear(); 6764 PredicatedBackedgeTakenCounts.clear(); 6765 LoopPropertiesCache.clear(); 6766 ConstantEvolutionLoopExitValue.clear(); 6767 ValueExprMap.clear(); 6768 ValuesAtScopes.clear(); 6769 LoopDispositions.clear(); 6770 BlockDispositions.clear(); 6771 UnsignedRanges.clear(); 6772 SignedRanges.clear(); 6773 ExprValueMap.clear(); 6774 HasRecMap.clear(); 6775 MinTrailingZerosCache.clear(); 6776 PredicatedSCEVRewrites.clear(); 6777 } 6778 6779 void ScalarEvolution::forgetLoop(const Loop *L) { 6780 // Drop any stored trip count value. 6781 auto RemoveLoopFromBackedgeMap = 6782 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6783 auto BTCPos = Map.find(L); 6784 if (BTCPos != Map.end()) { 6785 BTCPos->second.clear(); 6786 Map.erase(BTCPos); 6787 } 6788 }; 6789 6790 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6791 SmallVector<Instruction *, 32> Worklist; 6792 SmallPtrSet<Instruction *, 16> Visited; 6793 6794 // Iterate over all the loops and sub-loops to drop SCEV information. 6795 while (!LoopWorklist.empty()) { 6796 auto *CurrL = LoopWorklist.pop_back_val(); 6797 6798 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6799 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6800 6801 // Drop information about predicated SCEV rewrites for this loop. 6802 for (auto I = PredicatedSCEVRewrites.begin(); 6803 I != PredicatedSCEVRewrites.end();) { 6804 std::pair<const SCEV *, const Loop *> Entry = I->first; 6805 if (Entry.second == CurrL) 6806 PredicatedSCEVRewrites.erase(I++); 6807 else 6808 ++I; 6809 } 6810 6811 auto LoopUsersItr = LoopUsers.find(CurrL); 6812 if (LoopUsersItr != LoopUsers.end()) { 6813 for (auto *S : LoopUsersItr->second) 6814 forgetMemoizedResults(S); 6815 LoopUsers.erase(LoopUsersItr); 6816 } 6817 6818 // Drop information about expressions based on loop-header PHIs. 6819 PushLoopPHIs(CurrL, Worklist); 6820 6821 while (!Worklist.empty()) { 6822 Instruction *I = Worklist.pop_back_val(); 6823 if (!Visited.insert(I).second) 6824 continue; 6825 6826 ValueExprMapType::iterator It = 6827 ValueExprMap.find_as(static_cast<Value *>(I)); 6828 if (It != ValueExprMap.end()) { 6829 eraseValueFromMap(It->first); 6830 forgetMemoizedResults(It->second); 6831 if (PHINode *PN = dyn_cast<PHINode>(I)) 6832 ConstantEvolutionLoopExitValue.erase(PN); 6833 } 6834 6835 PushDefUseChildren(I, Worklist); 6836 } 6837 6838 LoopPropertiesCache.erase(CurrL); 6839 // Forget all contained loops too, to avoid dangling entries in the 6840 // ValuesAtScopes map. 6841 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6842 } 6843 } 6844 6845 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6846 while (Loop *Parent = L->getParentLoop()) 6847 L = Parent; 6848 forgetLoop(L); 6849 } 6850 6851 void ScalarEvolution::forgetValue(Value *V) { 6852 Instruction *I = dyn_cast<Instruction>(V); 6853 if (!I) return; 6854 6855 // Drop information about expressions based on loop-header PHIs. 6856 SmallVector<Instruction *, 16> Worklist; 6857 Worklist.push_back(I); 6858 6859 SmallPtrSet<Instruction *, 8> Visited; 6860 while (!Worklist.empty()) { 6861 I = Worklist.pop_back_val(); 6862 if (!Visited.insert(I).second) 6863 continue; 6864 6865 ValueExprMapType::iterator It = 6866 ValueExprMap.find_as(static_cast<Value *>(I)); 6867 if (It != ValueExprMap.end()) { 6868 eraseValueFromMap(It->first); 6869 forgetMemoizedResults(It->second); 6870 if (PHINode *PN = dyn_cast<PHINode>(I)) 6871 ConstantEvolutionLoopExitValue.erase(PN); 6872 } 6873 6874 PushDefUseChildren(I, Worklist); 6875 } 6876 } 6877 6878 /// Get the exact loop backedge taken count considering all loop exits. A 6879 /// computable result can only be returned for loops with all exiting blocks 6880 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6881 /// is never skipped. This is a valid assumption as long as the loop exits via 6882 /// that test. For precise results, it is the caller's responsibility to specify 6883 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6884 const SCEV * 6885 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6886 SCEVUnionPredicate *Preds) const { 6887 // If any exits were not computable, the loop is not computable. 6888 if (!isComplete() || ExitNotTaken.empty()) 6889 return SE->getCouldNotCompute(); 6890 6891 const BasicBlock *Latch = L->getLoopLatch(); 6892 // All exiting blocks we have collected must dominate the only backedge. 6893 if (!Latch) 6894 return SE->getCouldNotCompute(); 6895 6896 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6897 // count is simply a minimum out of all these calculated exit counts. 6898 SmallVector<const SCEV *, 2> Ops; 6899 for (auto &ENT : ExitNotTaken) { 6900 const SCEV *BECount = ENT.ExactNotTaken; 6901 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6902 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6903 "We should only have known counts for exiting blocks that dominate " 6904 "latch!"); 6905 6906 Ops.push_back(BECount); 6907 6908 if (Preds && !ENT.hasAlwaysTruePredicate()) 6909 Preds->add(ENT.Predicate.get()); 6910 6911 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6912 "Predicate should be always true!"); 6913 } 6914 6915 return SE->getUMinFromMismatchedTypes(Ops); 6916 } 6917 6918 /// Get the exact not taken count for this loop exit. 6919 const SCEV * 6920 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6921 ScalarEvolution *SE) const { 6922 for (auto &ENT : ExitNotTaken) 6923 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6924 return ENT.ExactNotTaken; 6925 6926 return SE->getCouldNotCompute(); 6927 } 6928 6929 /// getMax - Get the max backedge taken count for the loop. 6930 const SCEV * 6931 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6932 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6933 return !ENT.hasAlwaysTruePredicate(); 6934 }; 6935 6936 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6937 return SE->getCouldNotCompute(); 6938 6939 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6940 "No point in having a non-constant max backedge taken count!"); 6941 return getMax(); 6942 } 6943 6944 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6945 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6946 return !ENT.hasAlwaysTruePredicate(); 6947 }; 6948 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6949 } 6950 6951 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6952 ScalarEvolution *SE) const { 6953 if (getMax() && getMax() != SE->getCouldNotCompute() && 6954 SE->hasOperand(getMax(), S)) 6955 return true; 6956 6957 for (auto &ENT : ExitNotTaken) 6958 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6959 SE->hasOperand(ENT.ExactNotTaken, S)) 6960 return true; 6961 6962 return false; 6963 } 6964 6965 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6966 : ExactNotTaken(E), MaxNotTaken(E) { 6967 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6968 isa<SCEVConstant>(MaxNotTaken)) && 6969 "No point in having a non-constant max backedge taken count!"); 6970 } 6971 6972 ScalarEvolution::ExitLimit::ExitLimit( 6973 const SCEV *E, const SCEV *M, bool MaxOrZero, 6974 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6975 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6976 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6977 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6978 "Exact is not allowed to be less precise than Max"); 6979 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6980 isa<SCEVConstant>(MaxNotTaken)) && 6981 "No point in having a non-constant max backedge taken count!"); 6982 for (auto *PredSet : PredSetList) 6983 for (auto *P : *PredSet) 6984 addPredicate(P); 6985 } 6986 6987 ScalarEvolution::ExitLimit::ExitLimit( 6988 const SCEV *E, const SCEV *M, bool MaxOrZero, 6989 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6990 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6991 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6992 isa<SCEVConstant>(MaxNotTaken)) && 6993 "No point in having a non-constant max backedge taken count!"); 6994 } 6995 6996 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6997 bool MaxOrZero) 6998 : ExitLimit(E, M, MaxOrZero, None) { 6999 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7000 isa<SCEVConstant>(MaxNotTaken)) && 7001 "No point in having a non-constant max backedge taken count!"); 7002 } 7003 7004 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7005 /// computable exit into a persistent ExitNotTakenInfo array. 7006 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7007 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7008 ExitCounts, 7009 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7010 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7011 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7012 7013 ExitNotTaken.reserve(ExitCounts.size()); 7014 std::transform( 7015 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7016 [&](const EdgeExitInfo &EEI) { 7017 BasicBlock *ExitBB = EEI.first; 7018 const ExitLimit &EL = EEI.second; 7019 if (EL.Predicates.empty()) 7020 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 7021 7022 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7023 for (auto *Pred : EL.Predicates) 7024 Predicate->add(Pred); 7025 7026 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 7027 }); 7028 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7029 "No point in having a non-constant max backedge taken count!"); 7030 } 7031 7032 /// Invalidate this result and free the ExitNotTakenInfo array. 7033 void ScalarEvolution::BackedgeTakenInfo::clear() { 7034 ExitNotTaken.clear(); 7035 } 7036 7037 /// Compute the number of times the backedge of the specified loop will execute. 7038 ScalarEvolution::BackedgeTakenInfo 7039 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7040 bool AllowPredicates) { 7041 SmallVector<BasicBlock *, 8> ExitingBlocks; 7042 L->getExitingBlocks(ExitingBlocks); 7043 7044 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7045 7046 SmallVector<EdgeExitInfo, 4> ExitCounts; 7047 bool CouldComputeBECount = true; 7048 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7049 const SCEV *MustExitMaxBECount = nullptr; 7050 const SCEV *MayExitMaxBECount = nullptr; 7051 bool MustExitMaxOrZero = false; 7052 7053 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7054 // and compute maxBECount. 7055 // Do a union of all the predicates here. 7056 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7057 BasicBlock *ExitBB = ExitingBlocks[i]; 7058 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7059 7060 assert((AllowPredicates || EL.Predicates.empty()) && 7061 "Predicated exit limit when predicates are not allowed!"); 7062 7063 // 1. For each exit that can be computed, add an entry to ExitCounts. 7064 // CouldComputeBECount is true only if all exits can be computed. 7065 if (EL.ExactNotTaken == getCouldNotCompute()) 7066 // We couldn't compute an exact value for this exit, so 7067 // we won't be able to compute an exact value for the loop. 7068 CouldComputeBECount = false; 7069 else 7070 ExitCounts.emplace_back(ExitBB, EL); 7071 7072 // 2. Derive the loop's MaxBECount from each exit's max number of 7073 // non-exiting iterations. Partition the loop exits into two kinds: 7074 // LoopMustExits and LoopMayExits. 7075 // 7076 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7077 // is a LoopMayExit. If any computable LoopMustExit is found, then 7078 // MaxBECount is the minimum EL.MaxNotTaken of computable 7079 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7080 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7081 // computable EL.MaxNotTaken. 7082 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7083 DT.dominates(ExitBB, Latch)) { 7084 if (!MustExitMaxBECount) { 7085 MustExitMaxBECount = EL.MaxNotTaken; 7086 MustExitMaxOrZero = EL.MaxOrZero; 7087 } else { 7088 MustExitMaxBECount = 7089 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7090 } 7091 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7092 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7093 MayExitMaxBECount = EL.MaxNotTaken; 7094 else { 7095 MayExitMaxBECount = 7096 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7097 } 7098 } 7099 } 7100 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7101 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7102 // The loop backedge will be taken the maximum or zero times if there's 7103 // a single exit that must be taken the maximum or zero times. 7104 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7105 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7106 MaxBECount, MaxOrZero); 7107 } 7108 7109 ScalarEvolution::ExitLimit 7110 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7111 bool AllowPredicates) { 7112 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7113 // If our exiting block does not dominate the latch, then its connection with 7114 // loop's exit limit may be far from trivial. 7115 const BasicBlock *Latch = L->getLoopLatch(); 7116 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7117 return getCouldNotCompute(); 7118 7119 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7120 Instruction *Term = ExitingBlock->getTerminator(); 7121 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7122 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7123 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7124 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7125 "It should have one successor in loop and one exit block!"); 7126 // Proceed to the next level to examine the exit condition expression. 7127 return computeExitLimitFromCond( 7128 L, BI->getCondition(), ExitIfTrue, 7129 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7130 } 7131 7132 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7133 // For switch, make sure that there is a single exit from the loop. 7134 BasicBlock *Exit = nullptr; 7135 for (auto *SBB : successors(ExitingBlock)) 7136 if (!L->contains(SBB)) { 7137 if (Exit) // Multiple exit successors. 7138 return getCouldNotCompute(); 7139 Exit = SBB; 7140 } 7141 assert(Exit && "Exiting block must have at least one exit"); 7142 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7143 /*ControlsExit=*/IsOnlyExit); 7144 } 7145 7146 return getCouldNotCompute(); 7147 } 7148 7149 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7150 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7151 bool ControlsExit, bool AllowPredicates) { 7152 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7153 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7154 ControlsExit, AllowPredicates); 7155 } 7156 7157 Optional<ScalarEvolution::ExitLimit> 7158 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7159 bool ExitIfTrue, bool ControlsExit, 7160 bool AllowPredicates) { 7161 (void)this->L; 7162 (void)this->ExitIfTrue; 7163 (void)this->AllowPredicates; 7164 7165 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7166 this->AllowPredicates == AllowPredicates && 7167 "Variance in assumed invariant key components!"); 7168 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7169 if (Itr == TripCountMap.end()) 7170 return None; 7171 return Itr->second; 7172 } 7173 7174 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7175 bool ExitIfTrue, 7176 bool ControlsExit, 7177 bool AllowPredicates, 7178 const ExitLimit &EL) { 7179 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7180 this->AllowPredicates == AllowPredicates && 7181 "Variance in assumed invariant key components!"); 7182 7183 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7184 assert(InsertResult.second && "Expected successful insertion!"); 7185 (void)InsertResult; 7186 (void)ExitIfTrue; 7187 } 7188 7189 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7190 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7191 bool ControlsExit, bool AllowPredicates) { 7192 7193 if (auto MaybeEL = 7194 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7195 return *MaybeEL; 7196 7197 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7198 ControlsExit, AllowPredicates); 7199 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7200 return EL; 7201 } 7202 7203 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7204 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7205 bool ControlsExit, bool AllowPredicates) { 7206 // Check if the controlling expression for this loop is an And or Or. 7207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7208 if (BO->getOpcode() == Instruction::And) { 7209 // Recurse on the operands of the and. 7210 bool EitherMayExit = !ExitIfTrue; 7211 ExitLimit EL0 = computeExitLimitFromCondCached( 7212 Cache, L, BO->getOperand(0), ExitIfTrue, 7213 ControlsExit && !EitherMayExit, AllowPredicates); 7214 ExitLimit EL1 = computeExitLimitFromCondCached( 7215 Cache, L, BO->getOperand(1), ExitIfTrue, 7216 ControlsExit && !EitherMayExit, AllowPredicates); 7217 const SCEV *BECount = getCouldNotCompute(); 7218 const SCEV *MaxBECount = getCouldNotCompute(); 7219 if (EitherMayExit) { 7220 // Both conditions must be true for the loop to continue executing. 7221 // Choose the less conservative count. 7222 if (EL0.ExactNotTaken == getCouldNotCompute() || 7223 EL1.ExactNotTaken == getCouldNotCompute()) 7224 BECount = getCouldNotCompute(); 7225 else 7226 BECount = 7227 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7228 if (EL0.MaxNotTaken == getCouldNotCompute()) 7229 MaxBECount = EL1.MaxNotTaken; 7230 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7231 MaxBECount = EL0.MaxNotTaken; 7232 else 7233 MaxBECount = 7234 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7235 } else { 7236 // Both conditions must be true at the same time for the loop to exit. 7237 // For now, be conservative. 7238 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7239 MaxBECount = EL0.MaxNotTaken; 7240 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7241 BECount = EL0.ExactNotTaken; 7242 } 7243 7244 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7245 // to be more aggressive when computing BECount than when computing 7246 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7247 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7248 // to not. 7249 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7250 !isa<SCEVCouldNotCompute>(BECount)) 7251 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7252 7253 return ExitLimit(BECount, MaxBECount, false, 7254 {&EL0.Predicates, &EL1.Predicates}); 7255 } 7256 if (BO->getOpcode() == Instruction::Or) { 7257 // Recurse on the operands of the or. 7258 bool EitherMayExit = ExitIfTrue; 7259 ExitLimit EL0 = computeExitLimitFromCondCached( 7260 Cache, L, BO->getOperand(0), ExitIfTrue, 7261 ControlsExit && !EitherMayExit, AllowPredicates); 7262 ExitLimit EL1 = computeExitLimitFromCondCached( 7263 Cache, L, BO->getOperand(1), ExitIfTrue, 7264 ControlsExit && !EitherMayExit, AllowPredicates); 7265 const SCEV *BECount = getCouldNotCompute(); 7266 const SCEV *MaxBECount = getCouldNotCompute(); 7267 if (EitherMayExit) { 7268 // Both conditions must be false for the loop to continue executing. 7269 // Choose the less conservative count. 7270 if (EL0.ExactNotTaken == getCouldNotCompute() || 7271 EL1.ExactNotTaken == getCouldNotCompute()) 7272 BECount = getCouldNotCompute(); 7273 else 7274 BECount = 7275 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7276 if (EL0.MaxNotTaken == getCouldNotCompute()) 7277 MaxBECount = EL1.MaxNotTaken; 7278 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7279 MaxBECount = EL0.MaxNotTaken; 7280 else 7281 MaxBECount = 7282 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7283 } else { 7284 // Both conditions must be false at the same time for the loop to exit. 7285 // For now, be conservative. 7286 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7287 MaxBECount = EL0.MaxNotTaken; 7288 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7289 BECount = EL0.ExactNotTaken; 7290 } 7291 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7292 // to be more aggressive when computing BECount than when computing 7293 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7294 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7295 // to not. 7296 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7297 !isa<SCEVCouldNotCompute>(BECount)) 7298 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7299 7300 return ExitLimit(BECount, MaxBECount, false, 7301 {&EL0.Predicates, &EL1.Predicates}); 7302 } 7303 } 7304 7305 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7306 // Proceed to the next level to examine the icmp. 7307 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7308 ExitLimit EL = 7309 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7310 if (EL.hasFullInfo() || !AllowPredicates) 7311 return EL; 7312 7313 // Try again, but use SCEV predicates this time. 7314 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7315 /*AllowPredicates=*/true); 7316 } 7317 7318 // Check for a constant condition. These are normally stripped out by 7319 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7320 // preserve the CFG and is temporarily leaving constant conditions 7321 // in place. 7322 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7323 if (ExitIfTrue == !CI->getZExtValue()) 7324 // The backedge is always taken. 7325 return getCouldNotCompute(); 7326 else 7327 // The backedge is never taken. 7328 return getZero(CI->getType()); 7329 } 7330 7331 // If it's not an integer or pointer comparison then compute it the hard way. 7332 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7333 } 7334 7335 ScalarEvolution::ExitLimit 7336 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7337 ICmpInst *ExitCond, 7338 bool ExitIfTrue, 7339 bool ControlsExit, 7340 bool AllowPredicates) { 7341 // If the condition was exit on true, convert the condition to exit on false 7342 ICmpInst::Predicate Pred; 7343 if (!ExitIfTrue) 7344 Pred = ExitCond->getPredicate(); 7345 else 7346 Pred = ExitCond->getInversePredicate(); 7347 const ICmpInst::Predicate OriginalPred = Pred; 7348 7349 // Handle common loops like: for (X = "string"; *X; ++X) 7350 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7351 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7352 ExitLimit ItCnt = 7353 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7354 if (ItCnt.hasAnyInfo()) 7355 return ItCnt; 7356 } 7357 7358 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7359 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7360 7361 // Try to evaluate any dependencies out of the loop. 7362 LHS = getSCEVAtScope(LHS, L); 7363 RHS = getSCEVAtScope(RHS, L); 7364 7365 // At this point, we would like to compute how many iterations of the 7366 // loop the predicate will return true for these inputs. 7367 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7368 // If there is a loop-invariant, force it into the RHS. 7369 std::swap(LHS, RHS); 7370 Pred = ICmpInst::getSwappedPredicate(Pred); 7371 } 7372 7373 // Simplify the operands before analyzing them. 7374 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7375 7376 // If we have a comparison of a chrec against a constant, try to use value 7377 // ranges to answer this query. 7378 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7379 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7380 if (AddRec->getLoop() == L) { 7381 // Form the constant range. 7382 ConstantRange CompRange = 7383 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7384 7385 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7386 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7387 } 7388 7389 switch (Pred) { 7390 case ICmpInst::ICMP_NE: { // while (X != Y) 7391 // Convert to: while (X-Y != 0) 7392 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7393 AllowPredicates); 7394 if (EL.hasAnyInfo()) return EL; 7395 break; 7396 } 7397 case ICmpInst::ICMP_EQ: { // while (X == Y) 7398 // Convert to: while (X-Y == 0) 7399 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7400 if (EL.hasAnyInfo()) return EL; 7401 break; 7402 } 7403 case ICmpInst::ICMP_SLT: 7404 case ICmpInst::ICMP_ULT: { // while (X < Y) 7405 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7406 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7407 AllowPredicates); 7408 if (EL.hasAnyInfo()) return EL; 7409 break; 7410 } 7411 case ICmpInst::ICMP_SGT: 7412 case ICmpInst::ICMP_UGT: { // while (X > Y) 7413 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7414 ExitLimit EL = 7415 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7416 AllowPredicates); 7417 if (EL.hasAnyInfo()) return EL; 7418 break; 7419 } 7420 default: 7421 break; 7422 } 7423 7424 auto *ExhaustiveCount = 7425 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7426 7427 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7428 return ExhaustiveCount; 7429 7430 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7431 ExitCond->getOperand(1), L, OriginalPred); 7432 } 7433 7434 ScalarEvolution::ExitLimit 7435 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7436 SwitchInst *Switch, 7437 BasicBlock *ExitingBlock, 7438 bool ControlsExit) { 7439 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7440 7441 // Give up if the exit is the default dest of a switch. 7442 if (Switch->getDefaultDest() == ExitingBlock) 7443 return getCouldNotCompute(); 7444 7445 assert(L->contains(Switch->getDefaultDest()) && 7446 "Default case must not exit the loop!"); 7447 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7448 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7449 7450 // while (X != Y) --> while (X-Y != 0) 7451 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7452 if (EL.hasAnyInfo()) 7453 return EL; 7454 7455 return getCouldNotCompute(); 7456 } 7457 7458 static ConstantInt * 7459 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7460 ScalarEvolution &SE) { 7461 const SCEV *InVal = SE.getConstant(C); 7462 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7463 assert(isa<SCEVConstant>(Val) && 7464 "Evaluation of SCEV at constant didn't fold correctly?"); 7465 return cast<SCEVConstant>(Val)->getValue(); 7466 } 7467 7468 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7469 /// compute the backedge execution count. 7470 ScalarEvolution::ExitLimit 7471 ScalarEvolution::computeLoadConstantCompareExitLimit( 7472 LoadInst *LI, 7473 Constant *RHS, 7474 const Loop *L, 7475 ICmpInst::Predicate predicate) { 7476 if (LI->isVolatile()) return getCouldNotCompute(); 7477 7478 // Check to see if the loaded pointer is a getelementptr of a global. 7479 // TODO: Use SCEV instead of manually grubbing with GEPs. 7480 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7481 if (!GEP) return getCouldNotCompute(); 7482 7483 // Make sure that it is really a constant global we are gepping, with an 7484 // initializer, and make sure the first IDX is really 0. 7485 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7486 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7487 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7488 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7489 return getCouldNotCompute(); 7490 7491 // Okay, we allow one non-constant index into the GEP instruction. 7492 Value *VarIdx = nullptr; 7493 std::vector<Constant*> Indexes; 7494 unsigned VarIdxNum = 0; 7495 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7496 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7497 Indexes.push_back(CI); 7498 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7499 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7500 VarIdx = GEP->getOperand(i); 7501 VarIdxNum = i-2; 7502 Indexes.push_back(nullptr); 7503 } 7504 7505 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7506 if (!VarIdx) 7507 return getCouldNotCompute(); 7508 7509 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7510 // Check to see if X is a loop variant variable value now. 7511 const SCEV *Idx = getSCEV(VarIdx); 7512 Idx = getSCEVAtScope(Idx, L); 7513 7514 // We can only recognize very limited forms of loop index expressions, in 7515 // particular, only affine AddRec's like {C1,+,C2}. 7516 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7517 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7518 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7519 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7520 return getCouldNotCompute(); 7521 7522 unsigned MaxSteps = MaxBruteForceIterations; 7523 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7524 ConstantInt *ItCst = ConstantInt::get( 7525 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7526 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7527 7528 // Form the GEP offset. 7529 Indexes[VarIdxNum] = Val; 7530 7531 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7532 Indexes); 7533 if (!Result) break; // Cannot compute! 7534 7535 // Evaluate the condition for this iteration. 7536 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7537 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7538 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7539 ++NumArrayLenItCounts; 7540 return getConstant(ItCst); // Found terminating iteration! 7541 } 7542 } 7543 return getCouldNotCompute(); 7544 } 7545 7546 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7547 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7548 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7549 if (!RHS) 7550 return getCouldNotCompute(); 7551 7552 const BasicBlock *Latch = L->getLoopLatch(); 7553 if (!Latch) 7554 return getCouldNotCompute(); 7555 7556 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7557 if (!Predecessor) 7558 return getCouldNotCompute(); 7559 7560 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7561 // Return LHS in OutLHS and shift_opt in OutOpCode. 7562 auto MatchPositiveShift = 7563 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7564 7565 using namespace PatternMatch; 7566 7567 ConstantInt *ShiftAmt; 7568 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7569 OutOpCode = Instruction::LShr; 7570 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7571 OutOpCode = Instruction::AShr; 7572 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7573 OutOpCode = Instruction::Shl; 7574 else 7575 return false; 7576 7577 return ShiftAmt->getValue().isStrictlyPositive(); 7578 }; 7579 7580 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7581 // 7582 // loop: 7583 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7584 // %iv.shifted = lshr i32 %iv, <positive constant> 7585 // 7586 // Return true on a successful match. Return the corresponding PHI node (%iv 7587 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7588 auto MatchShiftRecurrence = 7589 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7590 Optional<Instruction::BinaryOps> PostShiftOpCode; 7591 7592 { 7593 Instruction::BinaryOps OpC; 7594 Value *V; 7595 7596 // If we encounter a shift instruction, "peel off" the shift operation, 7597 // and remember that we did so. Later when we inspect %iv's backedge 7598 // value, we will make sure that the backedge value uses the same 7599 // operation. 7600 // 7601 // Note: the peeled shift operation does not have to be the same 7602 // instruction as the one feeding into the PHI's backedge value. We only 7603 // really care about it being the same *kind* of shift instruction -- 7604 // that's all that is required for our later inferences to hold. 7605 if (MatchPositiveShift(LHS, V, OpC)) { 7606 PostShiftOpCode = OpC; 7607 LHS = V; 7608 } 7609 } 7610 7611 PNOut = dyn_cast<PHINode>(LHS); 7612 if (!PNOut || PNOut->getParent() != L->getHeader()) 7613 return false; 7614 7615 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7616 Value *OpLHS; 7617 7618 return 7619 // The backedge value for the PHI node must be a shift by a positive 7620 // amount 7621 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7622 7623 // of the PHI node itself 7624 OpLHS == PNOut && 7625 7626 // and the kind of shift should be match the kind of shift we peeled 7627 // off, if any. 7628 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7629 }; 7630 7631 PHINode *PN; 7632 Instruction::BinaryOps OpCode; 7633 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7634 return getCouldNotCompute(); 7635 7636 const DataLayout &DL = getDataLayout(); 7637 7638 // The key rationale for this optimization is that for some kinds of shift 7639 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7640 // within a finite number of iterations. If the condition guarding the 7641 // backedge (in the sense that the backedge is taken if the condition is true) 7642 // is false for the value the shift recurrence stabilizes to, then we know 7643 // that the backedge is taken only a finite number of times. 7644 7645 ConstantInt *StableValue = nullptr; 7646 switch (OpCode) { 7647 default: 7648 llvm_unreachable("Impossible case!"); 7649 7650 case Instruction::AShr: { 7651 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7652 // bitwidth(K) iterations. 7653 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7654 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7655 Predecessor->getTerminator(), &DT); 7656 auto *Ty = cast<IntegerType>(RHS->getType()); 7657 if (Known.isNonNegative()) 7658 StableValue = ConstantInt::get(Ty, 0); 7659 else if (Known.isNegative()) 7660 StableValue = ConstantInt::get(Ty, -1, true); 7661 else 7662 return getCouldNotCompute(); 7663 7664 break; 7665 } 7666 case Instruction::LShr: 7667 case Instruction::Shl: 7668 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7669 // stabilize to 0 in at most bitwidth(K) iterations. 7670 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7671 break; 7672 } 7673 7674 auto *Result = 7675 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7676 assert(Result->getType()->isIntegerTy(1) && 7677 "Otherwise cannot be an operand to a branch instruction"); 7678 7679 if (Result->isZeroValue()) { 7680 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7681 const SCEV *UpperBound = 7682 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7683 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7684 } 7685 7686 return getCouldNotCompute(); 7687 } 7688 7689 /// Return true if we can constant fold an instruction of the specified type, 7690 /// assuming that all operands were constants. 7691 static bool CanConstantFold(const Instruction *I) { 7692 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7693 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7694 isa<LoadInst>(I)) 7695 return true; 7696 7697 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7698 if (const Function *F = CI->getCalledFunction()) 7699 return canConstantFoldCallTo(CI, F); 7700 return false; 7701 } 7702 7703 /// Determine whether this instruction can constant evolve within this loop 7704 /// assuming its operands can all constant evolve. 7705 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7706 // An instruction outside of the loop can't be derived from a loop PHI. 7707 if (!L->contains(I)) return false; 7708 7709 if (isa<PHINode>(I)) { 7710 // We don't currently keep track of the control flow needed to evaluate 7711 // PHIs, so we cannot handle PHIs inside of loops. 7712 return L->getHeader() == I->getParent(); 7713 } 7714 7715 // If we won't be able to constant fold this expression even if the operands 7716 // are constants, bail early. 7717 return CanConstantFold(I); 7718 } 7719 7720 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7721 /// recursing through each instruction operand until reaching a loop header phi. 7722 static PHINode * 7723 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7724 DenseMap<Instruction *, PHINode *> &PHIMap, 7725 unsigned Depth) { 7726 if (Depth > MaxConstantEvolvingDepth) 7727 return nullptr; 7728 7729 // Otherwise, we can evaluate this instruction if all of its operands are 7730 // constant or derived from a PHI node themselves. 7731 PHINode *PHI = nullptr; 7732 for (Value *Op : UseInst->operands()) { 7733 if (isa<Constant>(Op)) continue; 7734 7735 Instruction *OpInst = dyn_cast<Instruction>(Op); 7736 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7737 7738 PHINode *P = dyn_cast<PHINode>(OpInst); 7739 if (!P) 7740 // If this operand is already visited, reuse the prior result. 7741 // We may have P != PHI if this is the deepest point at which the 7742 // inconsistent paths meet. 7743 P = PHIMap.lookup(OpInst); 7744 if (!P) { 7745 // Recurse and memoize the results, whether a phi is found or not. 7746 // This recursive call invalidates pointers into PHIMap. 7747 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7748 PHIMap[OpInst] = P; 7749 } 7750 if (!P) 7751 return nullptr; // Not evolving from PHI 7752 if (PHI && PHI != P) 7753 return nullptr; // Evolving from multiple different PHIs. 7754 PHI = P; 7755 } 7756 // This is a expression evolving from a constant PHI! 7757 return PHI; 7758 } 7759 7760 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7761 /// in the loop that V is derived from. We allow arbitrary operations along the 7762 /// way, but the operands of an operation must either be constants or a value 7763 /// derived from a constant PHI. If this expression does not fit with these 7764 /// constraints, return null. 7765 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7766 Instruction *I = dyn_cast<Instruction>(V); 7767 if (!I || !canConstantEvolve(I, L)) return nullptr; 7768 7769 if (PHINode *PN = dyn_cast<PHINode>(I)) 7770 return PN; 7771 7772 // Record non-constant instructions contained by the loop. 7773 DenseMap<Instruction *, PHINode *> PHIMap; 7774 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7775 } 7776 7777 /// EvaluateExpression - Given an expression that passes the 7778 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7779 /// in the loop has the value PHIVal. If we can't fold this expression for some 7780 /// reason, return null. 7781 static Constant *EvaluateExpression(Value *V, const Loop *L, 7782 DenseMap<Instruction *, Constant *> &Vals, 7783 const DataLayout &DL, 7784 const TargetLibraryInfo *TLI) { 7785 // Convenient constant check, but redundant for recursive calls. 7786 if (Constant *C = dyn_cast<Constant>(V)) return C; 7787 Instruction *I = dyn_cast<Instruction>(V); 7788 if (!I) return nullptr; 7789 7790 if (Constant *C = Vals.lookup(I)) return C; 7791 7792 // An instruction inside the loop depends on a value outside the loop that we 7793 // weren't given a mapping for, or a value such as a call inside the loop. 7794 if (!canConstantEvolve(I, L)) return nullptr; 7795 7796 // An unmapped PHI can be due to a branch or another loop inside this loop, 7797 // or due to this not being the initial iteration through a loop where we 7798 // couldn't compute the evolution of this particular PHI last time. 7799 if (isa<PHINode>(I)) return nullptr; 7800 7801 std::vector<Constant*> Operands(I->getNumOperands()); 7802 7803 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7804 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7805 if (!Operand) { 7806 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7807 if (!Operands[i]) return nullptr; 7808 continue; 7809 } 7810 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7811 Vals[Operand] = C; 7812 if (!C) return nullptr; 7813 Operands[i] = C; 7814 } 7815 7816 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7817 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7818 Operands[1], DL, TLI); 7819 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7820 if (!LI->isVolatile()) 7821 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7822 } 7823 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7824 } 7825 7826 7827 // If every incoming value to PN except the one for BB is a specific Constant, 7828 // return that, else return nullptr. 7829 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7830 Constant *IncomingVal = nullptr; 7831 7832 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7833 if (PN->getIncomingBlock(i) == BB) 7834 continue; 7835 7836 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7837 if (!CurrentVal) 7838 return nullptr; 7839 7840 if (IncomingVal != CurrentVal) { 7841 if (IncomingVal) 7842 return nullptr; 7843 IncomingVal = CurrentVal; 7844 } 7845 } 7846 7847 return IncomingVal; 7848 } 7849 7850 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7851 /// in the header of its containing loop, we know the loop executes a 7852 /// constant number of times, and the PHI node is just a recurrence 7853 /// involving constants, fold it. 7854 Constant * 7855 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7856 const APInt &BEs, 7857 const Loop *L) { 7858 auto I = ConstantEvolutionLoopExitValue.find(PN); 7859 if (I != ConstantEvolutionLoopExitValue.end()) 7860 return I->second; 7861 7862 if (BEs.ugt(MaxBruteForceIterations)) 7863 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7864 7865 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7866 7867 DenseMap<Instruction *, Constant *> CurrentIterVals; 7868 BasicBlock *Header = L->getHeader(); 7869 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7870 7871 BasicBlock *Latch = L->getLoopLatch(); 7872 if (!Latch) 7873 return nullptr; 7874 7875 for (PHINode &PHI : Header->phis()) { 7876 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7877 CurrentIterVals[&PHI] = StartCST; 7878 } 7879 if (!CurrentIterVals.count(PN)) 7880 return RetVal = nullptr; 7881 7882 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7883 7884 // Execute the loop symbolically to determine the exit value. 7885 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7886 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7887 7888 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7889 unsigned IterationNum = 0; 7890 const DataLayout &DL = getDataLayout(); 7891 for (; ; ++IterationNum) { 7892 if (IterationNum == NumIterations) 7893 return RetVal = CurrentIterVals[PN]; // Got exit value! 7894 7895 // Compute the value of the PHIs for the next iteration. 7896 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7897 DenseMap<Instruction *, Constant *> NextIterVals; 7898 Constant *NextPHI = 7899 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7900 if (!NextPHI) 7901 return nullptr; // Couldn't evaluate! 7902 NextIterVals[PN] = NextPHI; 7903 7904 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7905 7906 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7907 // cease to be able to evaluate one of them or if they stop evolving, 7908 // because that doesn't necessarily prevent us from computing PN. 7909 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7910 for (const auto &I : CurrentIterVals) { 7911 PHINode *PHI = dyn_cast<PHINode>(I.first); 7912 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7913 PHIsToCompute.emplace_back(PHI, I.second); 7914 } 7915 // We use two distinct loops because EvaluateExpression may invalidate any 7916 // iterators into CurrentIterVals. 7917 for (const auto &I : PHIsToCompute) { 7918 PHINode *PHI = I.first; 7919 Constant *&NextPHI = NextIterVals[PHI]; 7920 if (!NextPHI) { // Not already computed. 7921 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7922 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7923 } 7924 if (NextPHI != I.second) 7925 StoppedEvolving = false; 7926 } 7927 7928 // If all entries in CurrentIterVals == NextIterVals then we can stop 7929 // iterating, the loop can't continue to change. 7930 if (StoppedEvolving) 7931 return RetVal = CurrentIterVals[PN]; 7932 7933 CurrentIterVals.swap(NextIterVals); 7934 } 7935 } 7936 7937 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7938 Value *Cond, 7939 bool ExitWhen) { 7940 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7941 if (!PN) return getCouldNotCompute(); 7942 7943 // If the loop is canonicalized, the PHI will have exactly two entries. 7944 // That's the only form we support here. 7945 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7946 7947 DenseMap<Instruction *, Constant *> CurrentIterVals; 7948 BasicBlock *Header = L->getHeader(); 7949 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7950 7951 BasicBlock *Latch = L->getLoopLatch(); 7952 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7953 7954 for (PHINode &PHI : Header->phis()) { 7955 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7956 CurrentIterVals[&PHI] = StartCST; 7957 } 7958 if (!CurrentIterVals.count(PN)) 7959 return getCouldNotCompute(); 7960 7961 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7962 // the loop symbolically to determine when the condition gets a value of 7963 // "ExitWhen". 7964 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7965 const DataLayout &DL = getDataLayout(); 7966 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7967 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7968 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7969 7970 // Couldn't symbolically evaluate. 7971 if (!CondVal) return getCouldNotCompute(); 7972 7973 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7974 ++NumBruteForceTripCountsComputed; 7975 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7976 } 7977 7978 // Update all the PHI nodes for the next iteration. 7979 DenseMap<Instruction *, Constant *> NextIterVals; 7980 7981 // Create a list of which PHIs we need to compute. We want to do this before 7982 // calling EvaluateExpression on them because that may invalidate iterators 7983 // into CurrentIterVals. 7984 SmallVector<PHINode *, 8> PHIsToCompute; 7985 for (const auto &I : CurrentIterVals) { 7986 PHINode *PHI = dyn_cast<PHINode>(I.first); 7987 if (!PHI || PHI->getParent() != Header) continue; 7988 PHIsToCompute.push_back(PHI); 7989 } 7990 for (PHINode *PHI : PHIsToCompute) { 7991 Constant *&NextPHI = NextIterVals[PHI]; 7992 if (NextPHI) continue; // Already computed! 7993 7994 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7995 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7996 } 7997 CurrentIterVals.swap(NextIterVals); 7998 } 7999 8000 // Too many iterations were needed to evaluate. 8001 return getCouldNotCompute(); 8002 } 8003 8004 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8005 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8006 ValuesAtScopes[V]; 8007 // Check to see if we've folded this expression at this loop before. 8008 for (auto &LS : Values) 8009 if (LS.first == L) 8010 return LS.second ? LS.second : V; 8011 8012 Values.emplace_back(L, nullptr); 8013 8014 // Otherwise compute it. 8015 const SCEV *C = computeSCEVAtScope(V, L); 8016 for (auto &LS : reverse(ValuesAtScopes[V])) 8017 if (LS.first == L) { 8018 LS.second = C; 8019 break; 8020 } 8021 return C; 8022 } 8023 8024 /// This builds up a Constant using the ConstantExpr interface. That way, we 8025 /// will return Constants for objects which aren't represented by a 8026 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8027 /// Returns NULL if the SCEV isn't representable as a Constant. 8028 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8029 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8030 case scCouldNotCompute: 8031 case scAddRecExpr: 8032 break; 8033 case scConstant: 8034 return cast<SCEVConstant>(V)->getValue(); 8035 case scUnknown: 8036 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8037 case scSignExtend: { 8038 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8039 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8040 return ConstantExpr::getSExt(CastOp, SS->getType()); 8041 break; 8042 } 8043 case scZeroExtend: { 8044 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8045 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8046 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8047 break; 8048 } 8049 case scTruncate: { 8050 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8051 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8052 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8053 break; 8054 } 8055 case scAddExpr: { 8056 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8057 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8058 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8059 unsigned AS = PTy->getAddressSpace(); 8060 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8061 C = ConstantExpr::getBitCast(C, DestPtrTy); 8062 } 8063 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8064 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8065 if (!C2) return nullptr; 8066 8067 // First pointer! 8068 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8069 unsigned AS = C2->getType()->getPointerAddressSpace(); 8070 std::swap(C, C2); 8071 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8072 // The offsets have been converted to bytes. We can add bytes to an 8073 // i8* by GEP with the byte count in the first index. 8074 C = ConstantExpr::getBitCast(C, DestPtrTy); 8075 } 8076 8077 // Don't bother trying to sum two pointers. We probably can't 8078 // statically compute a load that results from it anyway. 8079 if (C2->getType()->isPointerTy()) 8080 return nullptr; 8081 8082 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8083 if (PTy->getElementType()->isStructTy()) 8084 C2 = ConstantExpr::getIntegerCast( 8085 C2, Type::getInt32Ty(C->getContext()), true); 8086 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8087 } else 8088 C = ConstantExpr::getAdd(C, C2); 8089 } 8090 return C; 8091 } 8092 break; 8093 } 8094 case scMulExpr: { 8095 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8096 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8097 // Don't bother with pointers at all. 8098 if (C->getType()->isPointerTy()) return nullptr; 8099 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8100 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8101 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8102 C = ConstantExpr::getMul(C, C2); 8103 } 8104 return C; 8105 } 8106 break; 8107 } 8108 case scUDivExpr: { 8109 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8110 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8111 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8112 if (LHS->getType() == RHS->getType()) 8113 return ConstantExpr::getUDiv(LHS, RHS); 8114 break; 8115 } 8116 case scSMaxExpr: 8117 case scUMaxExpr: 8118 break; // TODO: smax, umax. 8119 } 8120 return nullptr; 8121 } 8122 8123 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8124 if (isa<SCEVConstant>(V)) return V; 8125 8126 // If this instruction is evolved from a constant-evolving PHI, compute the 8127 // exit value from the loop without using SCEVs. 8128 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8129 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8130 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8131 const Loop *LI = this->LI[I->getParent()]; 8132 // Looking for loop exit value. 8133 if (LI && LI->getParentLoop() == L && 8134 PN->getParent() == LI->getHeader()) { 8135 // Okay, there is no closed form solution for the PHI node. Check 8136 // to see if the loop that contains it has a known backedge-taken 8137 // count. If so, we may be able to force computation of the exit 8138 // value. 8139 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8140 if (const SCEVConstant *BTCC = 8141 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8142 8143 // This trivial case can show up in some degenerate cases where 8144 // the incoming IR has not yet been fully simplified. 8145 if (BTCC->getValue()->isZero()) { 8146 Value *InitValue = nullptr; 8147 bool MultipleInitValues = false; 8148 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8149 if (!LI->contains(PN->getIncomingBlock(i))) { 8150 if (!InitValue) 8151 InitValue = PN->getIncomingValue(i); 8152 else if (InitValue != PN->getIncomingValue(i)) { 8153 MultipleInitValues = true; 8154 break; 8155 } 8156 } 8157 if (!MultipleInitValues && InitValue) 8158 return getSCEV(InitValue); 8159 } 8160 } 8161 // Okay, we know how many times the containing loop executes. If 8162 // this is a constant evolving PHI node, get the final value at 8163 // the specified iteration number. 8164 Constant *RV = 8165 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8166 if (RV) return getSCEV(RV); 8167 } 8168 } 8169 } 8170 8171 // Okay, this is an expression that we cannot symbolically evaluate 8172 // into a SCEV. Check to see if it's possible to symbolically evaluate 8173 // the arguments into constants, and if so, try to constant propagate the 8174 // result. This is particularly useful for computing loop exit values. 8175 if (CanConstantFold(I)) { 8176 SmallVector<Constant *, 4> Operands; 8177 bool MadeImprovement = false; 8178 for (Value *Op : I->operands()) { 8179 if (Constant *C = dyn_cast<Constant>(Op)) { 8180 Operands.push_back(C); 8181 continue; 8182 } 8183 8184 // If any of the operands is non-constant and if they are 8185 // non-integer and non-pointer, don't even try to analyze them 8186 // with scev techniques. 8187 if (!isSCEVable(Op->getType())) 8188 return V; 8189 8190 const SCEV *OrigV = getSCEV(Op); 8191 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8192 MadeImprovement |= OrigV != OpV; 8193 8194 Constant *C = BuildConstantFromSCEV(OpV); 8195 if (!C) return V; 8196 if (C->getType() != Op->getType()) 8197 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8198 Op->getType(), 8199 false), 8200 C, Op->getType()); 8201 Operands.push_back(C); 8202 } 8203 8204 // Check to see if getSCEVAtScope actually made an improvement. 8205 if (MadeImprovement) { 8206 Constant *C = nullptr; 8207 const DataLayout &DL = getDataLayout(); 8208 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8209 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8210 Operands[1], DL, &TLI); 8211 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8212 if (!LI->isVolatile()) 8213 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8214 } else 8215 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8216 if (!C) return V; 8217 return getSCEV(C); 8218 } 8219 } 8220 } 8221 8222 // This is some other type of SCEVUnknown, just return it. 8223 return V; 8224 } 8225 8226 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8227 // Avoid performing the look-up in the common case where the specified 8228 // expression has no loop-variant portions. 8229 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8230 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8231 if (OpAtScope != Comm->getOperand(i)) { 8232 // Okay, at least one of these operands is loop variant but might be 8233 // foldable. Build a new instance of the folded commutative expression. 8234 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8235 Comm->op_begin()+i); 8236 NewOps.push_back(OpAtScope); 8237 8238 for (++i; i != e; ++i) { 8239 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8240 NewOps.push_back(OpAtScope); 8241 } 8242 if (isa<SCEVAddExpr>(Comm)) 8243 return getAddExpr(NewOps); 8244 if (isa<SCEVMulExpr>(Comm)) 8245 return getMulExpr(NewOps); 8246 if (isa<SCEVSMaxExpr>(Comm)) 8247 return getSMaxExpr(NewOps); 8248 if (isa<SCEVUMaxExpr>(Comm)) 8249 return getUMaxExpr(NewOps); 8250 llvm_unreachable("Unknown commutative SCEV type!"); 8251 } 8252 } 8253 // If we got here, all operands are loop invariant. 8254 return Comm; 8255 } 8256 8257 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8258 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8259 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8260 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8261 return Div; // must be loop invariant 8262 return getUDivExpr(LHS, RHS); 8263 } 8264 8265 // If this is a loop recurrence for a loop that does not contain L, then we 8266 // are dealing with the final value computed by the loop. 8267 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8268 // First, attempt to evaluate each operand. 8269 // Avoid performing the look-up in the common case where the specified 8270 // expression has no loop-variant portions. 8271 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8272 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8273 if (OpAtScope == AddRec->getOperand(i)) 8274 continue; 8275 8276 // Okay, at least one of these operands is loop variant but might be 8277 // foldable. Build a new instance of the folded commutative expression. 8278 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8279 AddRec->op_begin()+i); 8280 NewOps.push_back(OpAtScope); 8281 for (++i; i != e; ++i) 8282 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8283 8284 const SCEV *FoldedRec = 8285 getAddRecExpr(NewOps, AddRec->getLoop(), 8286 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8287 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8288 // The addrec may be folded to a nonrecurrence, for example, if the 8289 // induction variable is multiplied by zero after constant folding. Go 8290 // ahead and return the folded value. 8291 if (!AddRec) 8292 return FoldedRec; 8293 break; 8294 } 8295 8296 // If the scope is outside the addrec's loop, evaluate it by using the 8297 // loop exit value of the addrec. 8298 if (!AddRec->getLoop()->contains(L)) { 8299 // To evaluate this recurrence, we need to know how many times the AddRec 8300 // loop iterates. Compute this now. 8301 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8302 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8303 8304 // Then, evaluate the AddRec. 8305 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8306 } 8307 8308 return AddRec; 8309 } 8310 8311 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8312 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8313 if (Op == Cast->getOperand()) 8314 return Cast; // must be loop invariant 8315 return getZeroExtendExpr(Op, Cast->getType()); 8316 } 8317 8318 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8319 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8320 if (Op == Cast->getOperand()) 8321 return Cast; // must be loop invariant 8322 return getSignExtendExpr(Op, Cast->getType()); 8323 } 8324 8325 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8326 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8327 if (Op == Cast->getOperand()) 8328 return Cast; // must be loop invariant 8329 return getTruncateExpr(Op, Cast->getType()); 8330 } 8331 8332 llvm_unreachable("Unknown SCEV type!"); 8333 } 8334 8335 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8336 return getSCEVAtScope(getSCEV(V), L); 8337 } 8338 8339 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8340 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8341 return stripInjectiveFunctions(ZExt->getOperand()); 8342 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8343 return stripInjectiveFunctions(SExt->getOperand()); 8344 return S; 8345 } 8346 8347 /// Finds the minimum unsigned root of the following equation: 8348 /// 8349 /// A * X = B (mod N) 8350 /// 8351 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8352 /// A and B isn't important. 8353 /// 8354 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8355 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8356 ScalarEvolution &SE) { 8357 uint32_t BW = A.getBitWidth(); 8358 assert(BW == SE.getTypeSizeInBits(B->getType())); 8359 assert(A != 0 && "A must be non-zero."); 8360 8361 // 1. D = gcd(A, N) 8362 // 8363 // The gcd of A and N may have only one prime factor: 2. The number of 8364 // trailing zeros in A is its multiplicity 8365 uint32_t Mult2 = A.countTrailingZeros(); 8366 // D = 2^Mult2 8367 8368 // 2. Check if B is divisible by D. 8369 // 8370 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8371 // is not less than multiplicity of this prime factor for D. 8372 if (SE.GetMinTrailingZeros(B) < Mult2) 8373 return SE.getCouldNotCompute(); 8374 8375 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8376 // modulo (N / D). 8377 // 8378 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8379 // (N / D) in general. The inverse itself always fits into BW bits, though, 8380 // so we immediately truncate it. 8381 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8382 APInt Mod(BW + 1, 0); 8383 Mod.setBit(BW - Mult2); // Mod = N / D 8384 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8385 8386 // 4. Compute the minimum unsigned root of the equation: 8387 // I * (B / D) mod (N / D) 8388 // To simplify the computation, we factor out the divide by D: 8389 // (I * B mod N) / D 8390 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8391 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8392 } 8393 8394 /// For a given quadratic addrec, generate coefficients of the corresponding 8395 /// quadratic equation, multiplied by a common value to ensure that they are 8396 /// integers. 8397 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8398 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8399 /// were multiplied by, and BitWidth is the bit width of the original addrec 8400 /// coefficients. 8401 /// This function returns None if the addrec coefficients are not compile- 8402 /// time constants. 8403 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8404 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8405 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8406 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8407 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8408 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8409 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8410 << *AddRec << '\n'); 8411 8412 // We currently can only solve this if the coefficients are constants. 8413 if (!LC || !MC || !NC) { 8414 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8415 return None; 8416 } 8417 8418 APInt L = LC->getAPInt(); 8419 APInt M = MC->getAPInt(); 8420 APInt N = NC->getAPInt(); 8421 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8422 8423 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8424 unsigned NewWidth = BitWidth + 1; 8425 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8426 << BitWidth << '\n'); 8427 // The sign-extension (as opposed to a zero-extension) here matches the 8428 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8429 N = N.sext(NewWidth); 8430 M = M.sext(NewWidth); 8431 L = L.sext(NewWidth); 8432 8433 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8434 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8435 // L+M, L+2M+N, L+3M+3N, ... 8436 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8437 // 8438 // The equation Acc = 0 is then 8439 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8440 // In a quadratic form it becomes: 8441 // N n^2 + (2M-N) n + 2L = 0. 8442 8443 APInt A = N; 8444 APInt B = 2 * M - A; 8445 APInt C = 2 * L; 8446 APInt T = APInt(NewWidth, 2); 8447 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8448 << "x + " << C << ", coeff bw: " << NewWidth 8449 << ", multiplied by " << T << '\n'); 8450 return std::make_tuple(A, B, C, T, BitWidth); 8451 } 8452 8453 /// Helper function to compare optional APInts: 8454 /// (a) if X and Y both exist, return min(X, Y), 8455 /// (b) if neither X nor Y exist, return None, 8456 /// (c) if exactly one of X and Y exists, return that value. 8457 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8458 if (X.hasValue() && Y.hasValue()) { 8459 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8460 APInt XW = X->sextOrSelf(W); 8461 APInt YW = Y->sextOrSelf(W); 8462 return XW.slt(YW) ? *X : *Y; 8463 } 8464 if (!X.hasValue() && !Y.hasValue()) 8465 return None; 8466 return X.hasValue() ? *X : *Y; 8467 } 8468 8469 /// Helper function to truncate an optional APInt to a given BitWidth. 8470 /// When solving addrec-related equations, it is preferable to return a value 8471 /// that has the same bit width as the original addrec's coefficients. If the 8472 /// solution fits in the original bit width, truncate it (except for i1). 8473 /// Returning a value of a different bit width may inhibit some optimizations. 8474 /// 8475 /// In general, a solution to a quadratic equation generated from an addrec 8476 /// may require BW+1 bits, where BW is the bit width of the addrec's 8477 /// coefficients. The reason is that the coefficients of the quadratic 8478 /// equation are BW+1 bits wide (to avoid truncation when converting from 8479 /// the addrec to the equation). 8480 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8481 if (!X.hasValue()) 8482 return None; 8483 unsigned W = X->getBitWidth(); 8484 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8485 return X->trunc(BitWidth); 8486 return X; 8487 } 8488 8489 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8490 /// iterations. The values L, M, N are assumed to be signed, and they 8491 /// should all have the same bit widths. 8492 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8493 /// where BW is the bit width of the addrec's coefficients. 8494 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8495 /// returned as such, otherwise the bit width of the returned value may 8496 /// be greater than BW. 8497 /// 8498 /// This function returns None if 8499 /// (a) the addrec coefficients are not constant, or 8500 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8501 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8502 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8503 static Optional<APInt> 8504 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8505 APInt A, B, C, M; 8506 unsigned BitWidth; 8507 auto T = GetQuadraticEquation(AddRec); 8508 if (!T.hasValue()) 8509 return None; 8510 8511 std::tie(A, B, C, M, BitWidth) = *T; 8512 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8513 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8514 if (!X.hasValue()) 8515 return None; 8516 8517 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8518 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8519 if (!V->isZero()) 8520 return None; 8521 8522 return TruncIfPossible(X, BitWidth); 8523 } 8524 8525 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8526 /// iterations. The values M, N are assumed to be signed, and they 8527 /// should all have the same bit widths. 8528 /// Find the least n such that c(n) does not belong to the given range, 8529 /// while c(n-1) does. 8530 /// 8531 /// This function returns None if 8532 /// (a) the addrec coefficients are not constant, or 8533 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8534 /// bounds of the range. 8535 static Optional<APInt> 8536 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8537 const ConstantRange &Range, ScalarEvolution &SE) { 8538 assert(AddRec->getOperand(0)->isZero() && 8539 "Starting value of addrec should be 0"); 8540 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8541 << Range << ", addrec " << *AddRec << '\n'); 8542 // This case is handled in getNumIterationsInRange. Here we can assume that 8543 // we start in the range. 8544 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8545 "Addrec's initial value should be in range"); 8546 8547 APInt A, B, C, M; 8548 unsigned BitWidth; 8549 auto T = GetQuadraticEquation(AddRec); 8550 if (!T.hasValue()) 8551 return None; 8552 8553 // Be careful about the return value: there can be two reasons for not 8554 // returning an actual number. First, if no solutions to the equations 8555 // were found, and second, if the solutions don't leave the given range. 8556 // The first case means that the actual solution is "unknown", the second 8557 // means that it's known, but not valid. If the solution is unknown, we 8558 // cannot make any conclusions. 8559 // Return a pair: the optional solution and a flag indicating if the 8560 // solution was found. 8561 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8562 // Solve for signed overflow and unsigned overflow, pick the lower 8563 // solution. 8564 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8565 << Bound << " (before multiplying by " << M << ")\n"); 8566 Bound *= M; // The quadratic equation multiplier. 8567 8568 Optional<APInt> SO = None; 8569 if (BitWidth > 1) { 8570 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8571 "signed overflow\n"); 8572 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8573 } 8574 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8575 "unsigned overflow\n"); 8576 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8577 BitWidth+1); 8578 8579 auto LeavesRange = [&] (const APInt &X) { 8580 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8581 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8582 if (Range.contains(V0->getValue())) 8583 return false; 8584 // X should be at least 1, so X-1 is non-negative. 8585 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8586 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8587 if (Range.contains(V1->getValue())) 8588 return true; 8589 return false; 8590 }; 8591 8592 // If SolveQuadraticEquationWrap returns None, it means that there can 8593 // be a solution, but the function failed to find it. We cannot treat it 8594 // as "no solution". 8595 if (!SO.hasValue() || !UO.hasValue()) 8596 return { None, false }; 8597 8598 // Check the smaller value first to see if it leaves the range. 8599 // At this point, both SO and UO must have values. 8600 Optional<APInt> Min = MinOptional(SO, UO); 8601 if (LeavesRange(*Min)) 8602 return { Min, true }; 8603 Optional<APInt> Max = Min == SO ? UO : SO; 8604 if (LeavesRange(*Max)) 8605 return { Max, true }; 8606 8607 // Solutions were found, but were eliminated, hence the "true". 8608 return { None, true }; 8609 }; 8610 8611 std::tie(A, B, C, M, BitWidth) = *T; 8612 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8613 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8614 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8615 auto SL = SolveForBoundary(Lower); 8616 auto SU = SolveForBoundary(Upper); 8617 // If any of the solutions was unknown, no meaninigful conclusions can 8618 // be made. 8619 if (!SL.second || !SU.second) 8620 return None; 8621 8622 // Claim: The correct solution is not some value between Min and Max. 8623 // 8624 // Justification: Assuming that Min and Max are different values, one of 8625 // them is when the first signed overflow happens, the other is when the 8626 // first unsigned overflow happens. Crossing the range boundary is only 8627 // possible via an overflow (treating 0 as a special case of it, modeling 8628 // an overflow as crossing k*2^W for some k). 8629 // 8630 // The interesting case here is when Min was eliminated as an invalid 8631 // solution, but Max was not. The argument is that if there was another 8632 // overflow between Min and Max, it would also have been eliminated if 8633 // it was considered. 8634 // 8635 // For a given boundary, it is possible to have two overflows of the same 8636 // type (signed/unsigned) without having the other type in between: this 8637 // can happen when the vertex of the parabola is between the iterations 8638 // corresponding to the overflows. This is only possible when the two 8639 // overflows cross k*2^W for the same k. In such case, if the second one 8640 // left the range (and was the first one to do so), the first overflow 8641 // would have to enter the range, which would mean that either we had left 8642 // the range before or that we started outside of it. Both of these cases 8643 // are contradictions. 8644 // 8645 // Claim: In the case where SolveForBoundary returns None, the correct 8646 // solution is not some value between the Max for this boundary and the 8647 // Min of the other boundary. 8648 // 8649 // Justification: Assume that we had such Max_A and Min_B corresponding 8650 // to range boundaries A and B and such that Max_A < Min_B. If there was 8651 // a solution between Max_A and Min_B, it would have to be caused by an 8652 // overflow corresponding to either A or B. It cannot correspond to B, 8653 // since Min_B is the first occurrence of such an overflow. If it 8654 // corresponded to A, it would have to be either a signed or an unsigned 8655 // overflow that is larger than both eliminated overflows for A. But 8656 // between the eliminated overflows and this overflow, the values would 8657 // cover the entire value space, thus crossing the other boundary, which 8658 // is a contradiction. 8659 8660 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8661 } 8662 8663 ScalarEvolution::ExitLimit 8664 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8665 bool AllowPredicates) { 8666 8667 // This is only used for loops with a "x != y" exit test. The exit condition 8668 // is now expressed as a single expression, V = x-y. So the exit test is 8669 // effectively V != 0. We know and take advantage of the fact that this 8670 // expression only being used in a comparison by zero context. 8671 8672 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8673 // If the value is a constant 8674 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8675 // If the value is already zero, the branch will execute zero times. 8676 if (C->getValue()->isZero()) return C; 8677 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8678 } 8679 8680 const SCEVAddRecExpr *AddRec = 8681 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8682 8683 if (!AddRec && AllowPredicates) 8684 // Try to make this an AddRec using runtime tests, in the first X 8685 // iterations of this loop, where X is the SCEV expression found by the 8686 // algorithm below. 8687 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8688 8689 if (!AddRec || AddRec->getLoop() != L) 8690 return getCouldNotCompute(); 8691 8692 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8693 // the quadratic equation to solve it. 8694 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8695 // We can only use this value if the chrec ends up with an exact zero 8696 // value at this index. When solving for "X*X != 5", for example, we 8697 // should not accept a root of 2. 8698 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8699 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8700 return ExitLimit(R, R, false, Predicates); 8701 } 8702 return getCouldNotCompute(); 8703 } 8704 8705 // Otherwise we can only handle this if it is affine. 8706 if (!AddRec->isAffine()) 8707 return getCouldNotCompute(); 8708 8709 // If this is an affine expression, the execution count of this branch is 8710 // the minimum unsigned root of the following equation: 8711 // 8712 // Start + Step*N = 0 (mod 2^BW) 8713 // 8714 // equivalent to: 8715 // 8716 // Step*N = -Start (mod 2^BW) 8717 // 8718 // where BW is the common bit width of Start and Step. 8719 8720 // Get the initial value for the loop. 8721 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8722 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8723 8724 // For now we handle only constant steps. 8725 // 8726 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8727 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8728 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8729 // We have not yet seen any such cases. 8730 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8731 if (!StepC || StepC->getValue()->isZero()) 8732 return getCouldNotCompute(); 8733 8734 // For positive steps (counting up until unsigned overflow): 8735 // N = -Start/Step (as unsigned) 8736 // For negative steps (counting down to zero): 8737 // N = Start/-Step 8738 // First compute the unsigned distance from zero in the direction of Step. 8739 bool CountDown = StepC->getAPInt().isNegative(); 8740 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8741 8742 // Handle unitary steps, which cannot wraparound. 8743 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8744 // N = Distance (as unsigned) 8745 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8746 APInt MaxBECount = getUnsignedRangeMax(Distance); 8747 8748 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8749 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8750 // case, and see if we can improve the bound. 8751 // 8752 // Explicitly handling this here is necessary because getUnsignedRange 8753 // isn't context-sensitive; it doesn't know that we only care about the 8754 // range inside the loop. 8755 const SCEV *Zero = getZero(Distance->getType()); 8756 const SCEV *One = getOne(Distance->getType()); 8757 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8758 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8759 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8760 // as "unsigned_max(Distance + 1) - 1". 8761 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8762 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8763 } 8764 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8765 } 8766 8767 // If the condition controls loop exit (the loop exits only if the expression 8768 // is true) and the addition is no-wrap we can use unsigned divide to 8769 // compute the backedge count. In this case, the step may not divide the 8770 // distance, but we don't care because if the condition is "missed" the loop 8771 // will have undefined behavior due to wrapping. 8772 if (ControlsExit && AddRec->hasNoSelfWrap() && 8773 loopHasNoAbnormalExits(AddRec->getLoop())) { 8774 const SCEV *Exact = 8775 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8776 const SCEV *Max = 8777 Exact == getCouldNotCompute() 8778 ? Exact 8779 : getConstant(getUnsignedRangeMax(Exact)); 8780 return ExitLimit(Exact, Max, false, Predicates); 8781 } 8782 8783 // Solve the general equation. 8784 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8785 getNegativeSCEV(Start), *this); 8786 const SCEV *M = E == getCouldNotCompute() 8787 ? E 8788 : getConstant(getUnsignedRangeMax(E)); 8789 return ExitLimit(E, M, false, Predicates); 8790 } 8791 8792 ScalarEvolution::ExitLimit 8793 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8794 // Loops that look like: while (X == 0) are very strange indeed. We don't 8795 // handle them yet except for the trivial case. This could be expanded in the 8796 // future as needed. 8797 8798 // If the value is a constant, check to see if it is known to be non-zero 8799 // already. If so, the backedge will execute zero times. 8800 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8801 if (!C->getValue()->isZero()) 8802 return getZero(C->getType()); 8803 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8804 } 8805 8806 // We could implement others, but I really doubt anyone writes loops like 8807 // this, and if they did, they would already be constant folded. 8808 return getCouldNotCompute(); 8809 } 8810 8811 std::pair<BasicBlock *, BasicBlock *> 8812 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8813 // If the block has a unique predecessor, then there is no path from the 8814 // predecessor to the block that does not go through the direct edge 8815 // from the predecessor to the block. 8816 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8817 return {Pred, BB}; 8818 8819 // A loop's header is defined to be a block that dominates the loop. 8820 // If the header has a unique predecessor outside the loop, it must be 8821 // a block that has exactly one successor that can reach the loop. 8822 if (Loop *L = LI.getLoopFor(BB)) 8823 return {L->getLoopPredecessor(), L->getHeader()}; 8824 8825 return {nullptr, nullptr}; 8826 } 8827 8828 /// SCEV structural equivalence is usually sufficient for testing whether two 8829 /// expressions are equal, however for the purposes of looking for a condition 8830 /// guarding a loop, it can be useful to be a little more general, since a 8831 /// front-end may have replicated the controlling expression. 8832 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8833 // Quick check to see if they are the same SCEV. 8834 if (A == B) return true; 8835 8836 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8837 // Not all instructions that are "identical" compute the same value. For 8838 // instance, two distinct alloca instructions allocating the same type are 8839 // identical and do not read memory; but compute distinct values. 8840 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8841 }; 8842 8843 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8844 // two different instructions with the same value. Check for this case. 8845 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8846 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8847 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8848 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8849 if (ComputesEqualValues(AI, BI)) 8850 return true; 8851 8852 // Otherwise assume they may have a different value. 8853 return false; 8854 } 8855 8856 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8857 const SCEV *&LHS, const SCEV *&RHS, 8858 unsigned Depth) { 8859 bool Changed = false; 8860 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8861 // '0 != 0'. 8862 auto TrivialCase = [&](bool TriviallyTrue) { 8863 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8864 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8865 return true; 8866 }; 8867 // If we hit the max recursion limit bail out. 8868 if (Depth >= 3) 8869 return false; 8870 8871 // Canonicalize a constant to the right side. 8872 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8873 // Check for both operands constant. 8874 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8875 if (ConstantExpr::getICmp(Pred, 8876 LHSC->getValue(), 8877 RHSC->getValue())->isNullValue()) 8878 return TrivialCase(false); 8879 else 8880 return TrivialCase(true); 8881 } 8882 // Otherwise swap the operands to put the constant on the right. 8883 std::swap(LHS, RHS); 8884 Pred = ICmpInst::getSwappedPredicate(Pred); 8885 Changed = true; 8886 } 8887 8888 // If we're comparing an addrec with a value which is loop-invariant in the 8889 // addrec's loop, put the addrec on the left. Also make a dominance check, 8890 // as both operands could be addrecs loop-invariant in each other's loop. 8891 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8892 const Loop *L = AR->getLoop(); 8893 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8894 std::swap(LHS, RHS); 8895 Pred = ICmpInst::getSwappedPredicate(Pred); 8896 Changed = true; 8897 } 8898 } 8899 8900 // If there's a constant operand, canonicalize comparisons with boundary 8901 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8902 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8903 const APInt &RA = RC->getAPInt(); 8904 8905 bool SimplifiedByConstantRange = false; 8906 8907 if (!ICmpInst::isEquality(Pred)) { 8908 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8909 if (ExactCR.isFullSet()) 8910 return TrivialCase(true); 8911 else if (ExactCR.isEmptySet()) 8912 return TrivialCase(false); 8913 8914 APInt NewRHS; 8915 CmpInst::Predicate NewPred; 8916 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8917 ICmpInst::isEquality(NewPred)) { 8918 // We were able to convert an inequality to an equality. 8919 Pred = NewPred; 8920 RHS = getConstant(NewRHS); 8921 Changed = SimplifiedByConstantRange = true; 8922 } 8923 } 8924 8925 if (!SimplifiedByConstantRange) { 8926 switch (Pred) { 8927 default: 8928 break; 8929 case ICmpInst::ICMP_EQ: 8930 case ICmpInst::ICMP_NE: 8931 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8932 if (!RA) 8933 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8934 if (const SCEVMulExpr *ME = 8935 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8936 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8937 ME->getOperand(0)->isAllOnesValue()) { 8938 RHS = AE->getOperand(1); 8939 LHS = ME->getOperand(1); 8940 Changed = true; 8941 } 8942 break; 8943 8944 8945 // The "Should have been caught earlier!" messages refer to the fact 8946 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8947 // should have fired on the corresponding cases, and canonicalized the 8948 // check to trivial case. 8949 8950 case ICmpInst::ICMP_UGE: 8951 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8952 Pred = ICmpInst::ICMP_UGT; 8953 RHS = getConstant(RA - 1); 8954 Changed = true; 8955 break; 8956 case ICmpInst::ICMP_ULE: 8957 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8958 Pred = ICmpInst::ICMP_ULT; 8959 RHS = getConstant(RA + 1); 8960 Changed = true; 8961 break; 8962 case ICmpInst::ICMP_SGE: 8963 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8964 Pred = ICmpInst::ICMP_SGT; 8965 RHS = getConstant(RA - 1); 8966 Changed = true; 8967 break; 8968 case ICmpInst::ICMP_SLE: 8969 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8970 Pred = ICmpInst::ICMP_SLT; 8971 RHS = getConstant(RA + 1); 8972 Changed = true; 8973 break; 8974 } 8975 } 8976 } 8977 8978 // Check for obvious equality. 8979 if (HasSameValue(LHS, RHS)) { 8980 if (ICmpInst::isTrueWhenEqual(Pred)) 8981 return TrivialCase(true); 8982 if (ICmpInst::isFalseWhenEqual(Pred)) 8983 return TrivialCase(false); 8984 } 8985 8986 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8987 // adding or subtracting 1 from one of the operands. 8988 switch (Pred) { 8989 case ICmpInst::ICMP_SLE: 8990 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8991 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8992 SCEV::FlagNSW); 8993 Pred = ICmpInst::ICMP_SLT; 8994 Changed = true; 8995 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8996 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8997 SCEV::FlagNSW); 8998 Pred = ICmpInst::ICMP_SLT; 8999 Changed = true; 9000 } 9001 break; 9002 case ICmpInst::ICMP_SGE: 9003 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9004 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9005 SCEV::FlagNSW); 9006 Pred = ICmpInst::ICMP_SGT; 9007 Changed = true; 9008 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9009 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9010 SCEV::FlagNSW); 9011 Pred = ICmpInst::ICMP_SGT; 9012 Changed = true; 9013 } 9014 break; 9015 case ICmpInst::ICMP_ULE: 9016 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9017 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9018 SCEV::FlagNUW); 9019 Pred = ICmpInst::ICMP_ULT; 9020 Changed = true; 9021 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9022 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9023 Pred = ICmpInst::ICMP_ULT; 9024 Changed = true; 9025 } 9026 break; 9027 case ICmpInst::ICMP_UGE: 9028 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9029 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9030 Pred = ICmpInst::ICMP_UGT; 9031 Changed = true; 9032 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9033 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9034 SCEV::FlagNUW); 9035 Pred = ICmpInst::ICMP_UGT; 9036 Changed = true; 9037 } 9038 break; 9039 default: 9040 break; 9041 } 9042 9043 // TODO: More simplifications are possible here. 9044 9045 // Recursively simplify until we either hit a recursion limit or nothing 9046 // changes. 9047 if (Changed) 9048 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9049 9050 return Changed; 9051 } 9052 9053 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9054 return getSignedRangeMax(S).isNegative(); 9055 } 9056 9057 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9058 return getSignedRangeMin(S).isStrictlyPositive(); 9059 } 9060 9061 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9062 return !getSignedRangeMin(S).isNegative(); 9063 } 9064 9065 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9066 return !getSignedRangeMax(S).isStrictlyPositive(); 9067 } 9068 9069 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9070 return isKnownNegative(S) || isKnownPositive(S); 9071 } 9072 9073 std::pair<const SCEV *, const SCEV *> 9074 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9075 // Compute SCEV on entry of loop L. 9076 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9077 if (Start == getCouldNotCompute()) 9078 return { Start, Start }; 9079 // Compute post increment SCEV for loop L. 9080 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9081 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9082 return { Start, PostInc }; 9083 } 9084 9085 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9086 const SCEV *LHS, const SCEV *RHS) { 9087 // First collect all loops. 9088 SmallPtrSet<const Loop *, 8> LoopsUsed; 9089 getUsedLoops(LHS, LoopsUsed); 9090 getUsedLoops(RHS, LoopsUsed); 9091 9092 if (LoopsUsed.empty()) 9093 return false; 9094 9095 // Domination relationship must be a linear order on collected loops. 9096 #ifndef NDEBUG 9097 for (auto *L1 : LoopsUsed) 9098 for (auto *L2 : LoopsUsed) 9099 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9100 DT.dominates(L2->getHeader(), L1->getHeader())) && 9101 "Domination relationship is not a linear order"); 9102 #endif 9103 9104 const Loop *MDL = 9105 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9106 [&](const Loop *L1, const Loop *L2) { 9107 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9108 }); 9109 9110 // Get init and post increment value for LHS. 9111 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9112 // if LHS contains unknown non-invariant SCEV then bail out. 9113 if (SplitLHS.first == getCouldNotCompute()) 9114 return false; 9115 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9116 // Get init and post increment value for RHS. 9117 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9118 // if RHS contains unknown non-invariant SCEV then bail out. 9119 if (SplitRHS.first == getCouldNotCompute()) 9120 return false; 9121 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9122 // It is possible that init SCEV contains an invariant load but it does 9123 // not dominate MDL and is not available at MDL loop entry, so we should 9124 // check it here. 9125 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9126 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9127 return false; 9128 9129 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9130 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9131 SplitRHS.second); 9132 } 9133 9134 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9135 const SCEV *LHS, const SCEV *RHS) { 9136 // Canonicalize the inputs first. 9137 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9138 9139 if (isKnownViaInduction(Pred, LHS, RHS)) 9140 return true; 9141 9142 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9143 return true; 9144 9145 // Otherwise see what can be done with some simple reasoning. 9146 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9147 } 9148 9149 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9150 const SCEVAddRecExpr *LHS, 9151 const SCEV *RHS) { 9152 const Loop *L = LHS->getLoop(); 9153 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9154 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9155 } 9156 9157 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9158 ICmpInst::Predicate Pred, 9159 bool &Increasing) { 9160 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9161 9162 #ifndef NDEBUG 9163 // Verify an invariant: inverting the predicate should turn a monotonically 9164 // increasing change to a monotonically decreasing one, and vice versa. 9165 bool IncreasingSwapped; 9166 bool ResultSwapped = isMonotonicPredicateImpl( 9167 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9168 9169 assert(Result == ResultSwapped && "should be able to analyze both!"); 9170 if (ResultSwapped) 9171 assert(Increasing == !IncreasingSwapped && 9172 "monotonicity should flip as we flip the predicate"); 9173 #endif 9174 9175 return Result; 9176 } 9177 9178 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9179 ICmpInst::Predicate Pred, 9180 bool &Increasing) { 9181 9182 // A zero step value for LHS means the induction variable is essentially a 9183 // loop invariant value. We don't really depend on the predicate actually 9184 // flipping from false to true (for increasing predicates, and the other way 9185 // around for decreasing predicates), all we care about is that *if* the 9186 // predicate changes then it only changes from false to true. 9187 // 9188 // A zero step value in itself is not very useful, but there may be places 9189 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9190 // as general as possible. 9191 9192 switch (Pred) { 9193 default: 9194 return false; // Conservative answer 9195 9196 case ICmpInst::ICMP_UGT: 9197 case ICmpInst::ICMP_UGE: 9198 case ICmpInst::ICMP_ULT: 9199 case ICmpInst::ICMP_ULE: 9200 if (!LHS->hasNoUnsignedWrap()) 9201 return false; 9202 9203 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9204 return true; 9205 9206 case ICmpInst::ICMP_SGT: 9207 case ICmpInst::ICMP_SGE: 9208 case ICmpInst::ICMP_SLT: 9209 case ICmpInst::ICMP_SLE: { 9210 if (!LHS->hasNoSignedWrap()) 9211 return false; 9212 9213 const SCEV *Step = LHS->getStepRecurrence(*this); 9214 9215 if (isKnownNonNegative(Step)) { 9216 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9217 return true; 9218 } 9219 9220 if (isKnownNonPositive(Step)) { 9221 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9222 return true; 9223 } 9224 9225 return false; 9226 } 9227 9228 } 9229 9230 llvm_unreachable("switch has default clause!"); 9231 } 9232 9233 bool ScalarEvolution::isLoopInvariantPredicate( 9234 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9235 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9236 const SCEV *&InvariantRHS) { 9237 9238 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9239 if (!isLoopInvariant(RHS, L)) { 9240 if (!isLoopInvariant(LHS, L)) 9241 return false; 9242 9243 std::swap(LHS, RHS); 9244 Pred = ICmpInst::getSwappedPredicate(Pred); 9245 } 9246 9247 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9248 if (!ArLHS || ArLHS->getLoop() != L) 9249 return false; 9250 9251 bool Increasing; 9252 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9253 return false; 9254 9255 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9256 // true as the loop iterates, and the backedge is control dependent on 9257 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9258 // 9259 // * if the predicate was false in the first iteration then the predicate 9260 // is never evaluated again, since the loop exits without taking the 9261 // backedge. 9262 // * if the predicate was true in the first iteration then it will 9263 // continue to be true for all future iterations since it is 9264 // monotonically increasing. 9265 // 9266 // For both the above possibilities, we can replace the loop varying 9267 // predicate with its value on the first iteration of the loop (which is 9268 // loop invariant). 9269 // 9270 // A similar reasoning applies for a monotonically decreasing predicate, by 9271 // replacing true with false and false with true in the above two bullets. 9272 9273 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9274 9275 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9276 return false; 9277 9278 InvariantPred = Pred; 9279 InvariantLHS = ArLHS->getStart(); 9280 InvariantRHS = RHS; 9281 return true; 9282 } 9283 9284 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9285 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9286 if (HasSameValue(LHS, RHS)) 9287 return ICmpInst::isTrueWhenEqual(Pred); 9288 9289 // This code is split out from isKnownPredicate because it is called from 9290 // within isLoopEntryGuardedByCond. 9291 9292 auto CheckRanges = 9293 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9294 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9295 .contains(RangeLHS); 9296 }; 9297 9298 // The check at the top of the function catches the case where the values are 9299 // known to be equal. 9300 if (Pred == CmpInst::ICMP_EQ) 9301 return false; 9302 9303 if (Pred == CmpInst::ICMP_NE) 9304 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9305 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9306 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9307 9308 if (CmpInst::isSigned(Pred)) 9309 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9310 9311 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9312 } 9313 9314 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9315 const SCEV *LHS, 9316 const SCEV *RHS) { 9317 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9318 // Return Y via OutY. 9319 auto MatchBinaryAddToConst = 9320 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9321 SCEV::NoWrapFlags ExpectedFlags) { 9322 const SCEV *NonConstOp, *ConstOp; 9323 SCEV::NoWrapFlags FlagsPresent; 9324 9325 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9326 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9327 return false; 9328 9329 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9330 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9331 }; 9332 9333 APInt C; 9334 9335 switch (Pred) { 9336 default: 9337 break; 9338 9339 case ICmpInst::ICMP_SGE: 9340 std::swap(LHS, RHS); 9341 LLVM_FALLTHROUGH; 9342 case ICmpInst::ICMP_SLE: 9343 // X s<= (X + C)<nsw> if C >= 0 9344 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9345 return true; 9346 9347 // (X + C)<nsw> s<= X if C <= 0 9348 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9349 !C.isStrictlyPositive()) 9350 return true; 9351 break; 9352 9353 case ICmpInst::ICMP_SGT: 9354 std::swap(LHS, RHS); 9355 LLVM_FALLTHROUGH; 9356 case ICmpInst::ICMP_SLT: 9357 // X s< (X + C)<nsw> if C > 0 9358 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9359 C.isStrictlyPositive()) 9360 return true; 9361 9362 // (X + C)<nsw> s< X if C < 0 9363 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9364 return true; 9365 break; 9366 } 9367 9368 return false; 9369 } 9370 9371 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9372 const SCEV *LHS, 9373 const SCEV *RHS) { 9374 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9375 return false; 9376 9377 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9378 // the stack can result in exponential time complexity. 9379 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9380 9381 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9382 // 9383 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9384 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9385 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9386 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9387 // use isKnownPredicate later if needed. 9388 return isKnownNonNegative(RHS) && 9389 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9390 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9391 } 9392 9393 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9394 ICmpInst::Predicate Pred, 9395 const SCEV *LHS, const SCEV *RHS) { 9396 // No need to even try if we know the module has no guards. 9397 if (!HasGuards) 9398 return false; 9399 9400 return any_of(*BB, [&](Instruction &I) { 9401 using namespace llvm::PatternMatch; 9402 9403 Value *Condition; 9404 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9405 m_Value(Condition))) && 9406 isImpliedCond(Pred, LHS, RHS, Condition, false); 9407 }); 9408 } 9409 9410 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9411 /// protected by a conditional between LHS and RHS. This is used to 9412 /// to eliminate casts. 9413 bool 9414 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9415 ICmpInst::Predicate Pred, 9416 const SCEV *LHS, const SCEV *RHS) { 9417 // Interpret a null as meaning no loop, where there is obviously no guard 9418 // (interprocedural conditions notwithstanding). 9419 if (!L) return true; 9420 9421 if (VerifyIR) 9422 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9423 "This cannot be done on broken IR!"); 9424 9425 9426 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9427 return true; 9428 9429 BasicBlock *Latch = L->getLoopLatch(); 9430 if (!Latch) 9431 return false; 9432 9433 BranchInst *LoopContinuePredicate = 9434 dyn_cast<BranchInst>(Latch->getTerminator()); 9435 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9436 isImpliedCond(Pred, LHS, RHS, 9437 LoopContinuePredicate->getCondition(), 9438 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9439 return true; 9440 9441 // We don't want more than one activation of the following loops on the stack 9442 // -- that can lead to O(n!) time complexity. 9443 if (WalkingBEDominatingConds) 9444 return false; 9445 9446 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9447 9448 // See if we can exploit a trip count to prove the predicate. 9449 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9450 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9451 if (LatchBECount != getCouldNotCompute()) { 9452 // We know that Latch branches back to the loop header exactly 9453 // LatchBECount times. This means the backdege condition at Latch is 9454 // equivalent to "{0,+,1} u< LatchBECount". 9455 Type *Ty = LatchBECount->getType(); 9456 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9457 const SCEV *LoopCounter = 9458 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9459 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9460 LatchBECount)) 9461 return true; 9462 } 9463 9464 // Check conditions due to any @llvm.assume intrinsics. 9465 for (auto &AssumeVH : AC.assumptions()) { 9466 if (!AssumeVH) 9467 continue; 9468 auto *CI = cast<CallInst>(AssumeVH); 9469 if (!DT.dominates(CI, Latch->getTerminator())) 9470 continue; 9471 9472 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9473 return true; 9474 } 9475 9476 // If the loop is not reachable from the entry block, we risk running into an 9477 // infinite loop as we walk up into the dom tree. These loops do not matter 9478 // anyway, so we just return a conservative answer when we see them. 9479 if (!DT.isReachableFromEntry(L->getHeader())) 9480 return false; 9481 9482 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9483 return true; 9484 9485 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9486 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9487 assert(DTN && "should reach the loop header before reaching the root!"); 9488 9489 BasicBlock *BB = DTN->getBlock(); 9490 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9491 return true; 9492 9493 BasicBlock *PBB = BB->getSinglePredecessor(); 9494 if (!PBB) 9495 continue; 9496 9497 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9498 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9499 continue; 9500 9501 Value *Condition = ContinuePredicate->getCondition(); 9502 9503 // If we have an edge `E` within the loop body that dominates the only 9504 // latch, the condition guarding `E` also guards the backedge. This 9505 // reasoning works only for loops with a single latch. 9506 9507 BasicBlockEdge DominatingEdge(PBB, BB); 9508 if (DominatingEdge.isSingleEdge()) { 9509 // We're constructively (and conservatively) enumerating edges within the 9510 // loop body that dominate the latch. The dominator tree better agree 9511 // with us on this: 9512 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9513 9514 if (isImpliedCond(Pred, LHS, RHS, Condition, 9515 BB != ContinuePredicate->getSuccessor(0))) 9516 return true; 9517 } 9518 } 9519 9520 return false; 9521 } 9522 9523 bool 9524 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9525 ICmpInst::Predicate Pred, 9526 const SCEV *LHS, const SCEV *RHS) { 9527 // Interpret a null as meaning no loop, where there is obviously no guard 9528 // (interprocedural conditions notwithstanding). 9529 if (!L) return false; 9530 9531 if (VerifyIR) 9532 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9533 "This cannot be done on broken IR!"); 9534 9535 // Both LHS and RHS must be available at loop entry. 9536 assert(isAvailableAtLoopEntry(LHS, L) && 9537 "LHS is not available at Loop Entry"); 9538 assert(isAvailableAtLoopEntry(RHS, L) && 9539 "RHS is not available at Loop Entry"); 9540 9541 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9542 return true; 9543 9544 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9545 // the facts (a >= b && a != b) separately. A typical situation is when the 9546 // non-strict comparison is known from ranges and non-equality is known from 9547 // dominating predicates. If we are proving strict comparison, we always try 9548 // to prove non-equality and non-strict comparison separately. 9549 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9550 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9551 bool ProvedNonStrictComparison = false; 9552 bool ProvedNonEquality = false; 9553 9554 if (ProvingStrictComparison) { 9555 ProvedNonStrictComparison = 9556 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9557 ProvedNonEquality = 9558 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9559 if (ProvedNonStrictComparison && ProvedNonEquality) 9560 return true; 9561 } 9562 9563 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9564 auto ProveViaGuard = [&](BasicBlock *Block) { 9565 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9566 return true; 9567 if (ProvingStrictComparison) { 9568 if (!ProvedNonStrictComparison) 9569 ProvedNonStrictComparison = 9570 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9571 if (!ProvedNonEquality) 9572 ProvedNonEquality = 9573 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9574 if (ProvedNonStrictComparison && ProvedNonEquality) 9575 return true; 9576 } 9577 return false; 9578 }; 9579 9580 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9581 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9582 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9583 return true; 9584 if (ProvingStrictComparison) { 9585 if (!ProvedNonStrictComparison) 9586 ProvedNonStrictComparison = 9587 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9588 if (!ProvedNonEquality) 9589 ProvedNonEquality = 9590 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9591 if (ProvedNonStrictComparison && ProvedNonEquality) 9592 return true; 9593 } 9594 return false; 9595 }; 9596 9597 // Starting at the loop predecessor, climb up the predecessor chain, as long 9598 // as there are predecessors that can be found that have unique successors 9599 // leading to the original header. 9600 for (std::pair<BasicBlock *, BasicBlock *> 9601 Pair(L->getLoopPredecessor(), L->getHeader()); 9602 Pair.first; 9603 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9604 9605 if (ProveViaGuard(Pair.first)) 9606 return true; 9607 9608 BranchInst *LoopEntryPredicate = 9609 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9610 if (!LoopEntryPredicate || 9611 LoopEntryPredicate->isUnconditional()) 9612 continue; 9613 9614 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9615 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9616 return true; 9617 } 9618 9619 // Check conditions due to any @llvm.assume intrinsics. 9620 for (auto &AssumeVH : AC.assumptions()) { 9621 if (!AssumeVH) 9622 continue; 9623 auto *CI = cast<CallInst>(AssumeVH); 9624 if (!DT.dominates(CI, L->getHeader())) 9625 continue; 9626 9627 if (ProveViaCond(CI->getArgOperand(0), false)) 9628 return true; 9629 } 9630 9631 return false; 9632 } 9633 9634 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9635 const SCEV *LHS, const SCEV *RHS, 9636 Value *FoundCondValue, 9637 bool Inverse) { 9638 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9639 return false; 9640 9641 auto ClearOnExit = 9642 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9643 9644 // Recursively handle And and Or conditions. 9645 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9646 if (BO->getOpcode() == Instruction::And) { 9647 if (!Inverse) 9648 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9649 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9650 } else if (BO->getOpcode() == Instruction::Or) { 9651 if (Inverse) 9652 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9653 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9654 } 9655 } 9656 9657 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9658 if (!ICI) return false; 9659 9660 // Now that we found a conditional branch that dominates the loop or controls 9661 // the loop latch. Check to see if it is the comparison we are looking for. 9662 ICmpInst::Predicate FoundPred; 9663 if (Inverse) 9664 FoundPred = ICI->getInversePredicate(); 9665 else 9666 FoundPred = ICI->getPredicate(); 9667 9668 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9669 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9670 9671 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9672 } 9673 9674 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9675 const SCEV *RHS, 9676 ICmpInst::Predicate FoundPred, 9677 const SCEV *FoundLHS, 9678 const SCEV *FoundRHS) { 9679 // Balance the types. 9680 if (getTypeSizeInBits(LHS->getType()) < 9681 getTypeSizeInBits(FoundLHS->getType())) { 9682 if (CmpInst::isSigned(Pred)) { 9683 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9684 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9685 } else { 9686 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9687 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9688 } 9689 } else if (getTypeSizeInBits(LHS->getType()) > 9690 getTypeSizeInBits(FoundLHS->getType())) { 9691 if (CmpInst::isSigned(FoundPred)) { 9692 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9693 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9694 } else { 9695 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9696 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9697 } 9698 } 9699 9700 // Canonicalize the query to match the way instcombine will have 9701 // canonicalized the comparison. 9702 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9703 if (LHS == RHS) 9704 return CmpInst::isTrueWhenEqual(Pred); 9705 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9706 if (FoundLHS == FoundRHS) 9707 return CmpInst::isFalseWhenEqual(FoundPred); 9708 9709 // Check to see if we can make the LHS or RHS match. 9710 if (LHS == FoundRHS || RHS == FoundLHS) { 9711 if (isa<SCEVConstant>(RHS)) { 9712 std::swap(FoundLHS, FoundRHS); 9713 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9714 } else { 9715 std::swap(LHS, RHS); 9716 Pred = ICmpInst::getSwappedPredicate(Pred); 9717 } 9718 } 9719 9720 // Check whether the found predicate is the same as the desired predicate. 9721 if (FoundPred == Pred) 9722 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9723 9724 // Check whether swapping the found predicate makes it the same as the 9725 // desired predicate. 9726 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9727 if (isa<SCEVConstant>(RHS)) 9728 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9729 else 9730 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9731 RHS, LHS, FoundLHS, FoundRHS); 9732 } 9733 9734 // Unsigned comparison is the same as signed comparison when both the operands 9735 // are non-negative. 9736 if (CmpInst::isUnsigned(FoundPred) && 9737 CmpInst::getSignedPredicate(FoundPred) == Pred && 9738 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9739 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9740 9741 // Check if we can make progress by sharpening ranges. 9742 if (FoundPred == ICmpInst::ICMP_NE && 9743 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9744 9745 const SCEVConstant *C = nullptr; 9746 const SCEV *V = nullptr; 9747 9748 if (isa<SCEVConstant>(FoundLHS)) { 9749 C = cast<SCEVConstant>(FoundLHS); 9750 V = FoundRHS; 9751 } else { 9752 C = cast<SCEVConstant>(FoundRHS); 9753 V = FoundLHS; 9754 } 9755 9756 // The guarding predicate tells us that C != V. If the known range 9757 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9758 // range we consider has to correspond to same signedness as the 9759 // predicate we're interested in folding. 9760 9761 APInt Min = ICmpInst::isSigned(Pred) ? 9762 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9763 9764 if (Min == C->getAPInt()) { 9765 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9766 // This is true even if (Min + 1) wraps around -- in case of 9767 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9768 9769 APInt SharperMin = Min + 1; 9770 9771 switch (Pred) { 9772 case ICmpInst::ICMP_SGE: 9773 case ICmpInst::ICMP_UGE: 9774 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9775 // RHS, we're done. 9776 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9777 getConstant(SharperMin))) 9778 return true; 9779 LLVM_FALLTHROUGH; 9780 9781 case ICmpInst::ICMP_SGT: 9782 case ICmpInst::ICMP_UGT: 9783 // We know from the range information that (V `Pred` Min || 9784 // V == Min). We know from the guarding condition that !(V 9785 // == Min). This gives us 9786 // 9787 // V `Pred` Min || V == Min && !(V == Min) 9788 // => V `Pred` Min 9789 // 9790 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9791 9792 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9793 return true; 9794 LLVM_FALLTHROUGH; 9795 9796 default: 9797 // No change 9798 break; 9799 } 9800 } 9801 } 9802 9803 // Check whether the actual condition is beyond sufficient. 9804 if (FoundPred == ICmpInst::ICMP_EQ) 9805 if (ICmpInst::isTrueWhenEqual(Pred)) 9806 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9807 return true; 9808 if (Pred == ICmpInst::ICMP_NE) 9809 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9810 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9811 return true; 9812 9813 // Otherwise assume the worst. 9814 return false; 9815 } 9816 9817 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9818 const SCEV *&L, const SCEV *&R, 9819 SCEV::NoWrapFlags &Flags) { 9820 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9821 if (!AE || AE->getNumOperands() != 2) 9822 return false; 9823 9824 L = AE->getOperand(0); 9825 R = AE->getOperand(1); 9826 Flags = AE->getNoWrapFlags(); 9827 return true; 9828 } 9829 9830 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9831 const SCEV *Less) { 9832 // We avoid subtracting expressions here because this function is usually 9833 // fairly deep in the call stack (i.e. is called many times). 9834 9835 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9836 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9837 const auto *MAR = cast<SCEVAddRecExpr>(More); 9838 9839 if (LAR->getLoop() != MAR->getLoop()) 9840 return None; 9841 9842 // We look at affine expressions only; not for correctness but to keep 9843 // getStepRecurrence cheap. 9844 if (!LAR->isAffine() || !MAR->isAffine()) 9845 return None; 9846 9847 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9848 return None; 9849 9850 Less = LAR->getStart(); 9851 More = MAR->getStart(); 9852 9853 // fall through 9854 } 9855 9856 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9857 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9858 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9859 return M - L; 9860 } 9861 9862 SCEV::NoWrapFlags Flags; 9863 const SCEV *LLess = nullptr, *RLess = nullptr; 9864 const SCEV *LMore = nullptr, *RMore = nullptr; 9865 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9866 // Compare (X + C1) vs X. 9867 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9868 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9869 if (RLess == More) 9870 return -(C1->getAPInt()); 9871 9872 // Compare X vs (X + C2). 9873 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9874 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9875 if (RMore == Less) 9876 return C2->getAPInt(); 9877 9878 // Compare (X + C1) vs (X + C2). 9879 if (C1 && C2 && RLess == RMore) 9880 return C2->getAPInt() - C1->getAPInt(); 9881 9882 return None; 9883 } 9884 9885 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9886 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9887 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9888 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9889 return false; 9890 9891 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9892 if (!AddRecLHS) 9893 return false; 9894 9895 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9896 if (!AddRecFoundLHS) 9897 return false; 9898 9899 // We'd like to let SCEV reason about control dependencies, so we constrain 9900 // both the inequalities to be about add recurrences on the same loop. This 9901 // way we can use isLoopEntryGuardedByCond later. 9902 9903 const Loop *L = AddRecFoundLHS->getLoop(); 9904 if (L != AddRecLHS->getLoop()) 9905 return false; 9906 9907 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9908 // 9909 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9910 // ... (2) 9911 // 9912 // Informal proof for (2), assuming (1) [*]: 9913 // 9914 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9915 // 9916 // Then 9917 // 9918 // FoundLHS s< FoundRHS s< INT_MIN - C 9919 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9920 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9921 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9922 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9923 // <=> FoundLHS + C s< FoundRHS + C 9924 // 9925 // [*]: (1) can be proved by ruling out overflow. 9926 // 9927 // [**]: This can be proved by analyzing all the four possibilities: 9928 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9929 // (A s>= 0, B s>= 0). 9930 // 9931 // Note: 9932 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9933 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9934 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9935 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9936 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9937 // C)". 9938 9939 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9940 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9941 if (!LDiff || !RDiff || *LDiff != *RDiff) 9942 return false; 9943 9944 if (LDiff->isMinValue()) 9945 return true; 9946 9947 APInt FoundRHSLimit; 9948 9949 if (Pred == CmpInst::ICMP_ULT) { 9950 FoundRHSLimit = -(*RDiff); 9951 } else { 9952 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9953 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9954 } 9955 9956 // Try to prove (1) or (2), as needed. 9957 return isAvailableAtLoopEntry(FoundRHS, L) && 9958 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9959 getConstant(FoundRHSLimit)); 9960 } 9961 9962 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9963 const SCEV *LHS, const SCEV *RHS, 9964 const SCEV *FoundLHS, 9965 const SCEV *FoundRHS, unsigned Depth) { 9966 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9967 9968 auto ClearOnExit = make_scope_exit([&]() { 9969 if (LPhi) { 9970 bool Erased = PendingMerges.erase(LPhi); 9971 assert(Erased && "Failed to erase LPhi!"); 9972 (void)Erased; 9973 } 9974 if (RPhi) { 9975 bool Erased = PendingMerges.erase(RPhi); 9976 assert(Erased && "Failed to erase RPhi!"); 9977 (void)Erased; 9978 } 9979 }); 9980 9981 // Find respective Phis and check that they are not being pending. 9982 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 9983 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 9984 if (!PendingMerges.insert(Phi).second) 9985 return false; 9986 LPhi = Phi; 9987 } 9988 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 9989 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 9990 // If we detect a loop of Phi nodes being processed by this method, for 9991 // example: 9992 // 9993 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 9994 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 9995 // 9996 // we don't want to deal with a case that complex, so return conservative 9997 // answer false. 9998 if (!PendingMerges.insert(Phi).second) 9999 return false; 10000 RPhi = Phi; 10001 } 10002 10003 // If none of LHS, RHS is a Phi, nothing to do here. 10004 if (!LPhi && !RPhi) 10005 return false; 10006 10007 // If there is a SCEVUnknown Phi we are interested in, make it left. 10008 if (!LPhi) { 10009 std::swap(LHS, RHS); 10010 std::swap(FoundLHS, FoundRHS); 10011 std::swap(LPhi, RPhi); 10012 Pred = ICmpInst::getSwappedPredicate(Pred); 10013 } 10014 10015 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10016 const BasicBlock *LBB = LPhi->getParent(); 10017 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10018 10019 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10020 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10021 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10022 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10023 }; 10024 10025 if (RPhi && RPhi->getParent() == LBB) { 10026 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10027 // If we compare two Phis from the same block, and for each entry block 10028 // the predicate is true for incoming values from this block, then the 10029 // predicate is also true for the Phis. 10030 for (const BasicBlock *IncBB : predecessors(LBB)) { 10031 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10032 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10033 if (!ProvedEasily(L, R)) 10034 return false; 10035 } 10036 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10037 // Case two: RHS is also a Phi from the same basic block, and it is an 10038 // AddRec. It means that there is a loop which has both AddRec and Unknown 10039 // PHIs, for it we can compare incoming values of AddRec from above the loop 10040 // and latch with their respective incoming values of LPhi. 10041 // TODO: Generalize to handle loops with many inputs in a header. 10042 if (LPhi->getNumIncomingValues() != 2) return false; 10043 10044 auto *RLoop = RAR->getLoop(); 10045 auto *Predecessor = RLoop->getLoopPredecessor(); 10046 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10047 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10048 if (!ProvedEasily(L1, RAR->getStart())) 10049 return false; 10050 auto *Latch = RLoop->getLoopLatch(); 10051 assert(Latch && "Loop with AddRec with no latch?"); 10052 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10053 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10054 return false; 10055 } else { 10056 // In all other cases go over inputs of LHS and compare each of them to RHS, 10057 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10058 // At this point RHS is either a non-Phi, or it is a Phi from some block 10059 // different from LBB. 10060 for (const BasicBlock *IncBB : predecessors(LBB)) { 10061 // Check that RHS is available in this block. 10062 if (!dominates(RHS, IncBB)) 10063 return false; 10064 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10065 if (!ProvedEasily(L, RHS)) 10066 return false; 10067 } 10068 } 10069 return true; 10070 } 10071 10072 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10073 const SCEV *LHS, const SCEV *RHS, 10074 const SCEV *FoundLHS, 10075 const SCEV *FoundRHS) { 10076 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10077 return true; 10078 10079 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10080 return true; 10081 10082 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10083 FoundLHS, FoundRHS) || 10084 // ~x < ~y --> x > y 10085 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10086 getNotSCEV(FoundRHS), 10087 getNotSCEV(FoundLHS)); 10088 } 10089 10090 /// If Expr computes ~A, return A else return nullptr 10091 static const SCEV *MatchNotExpr(const SCEV *Expr) { 10092 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 10093 if (!Add || Add->getNumOperands() != 2 || 10094 !Add->getOperand(0)->isAllOnesValue()) 10095 return nullptr; 10096 10097 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 10098 if (!AddRHS || AddRHS->getNumOperands() != 2 || 10099 !AddRHS->getOperand(0)->isAllOnesValue()) 10100 return nullptr; 10101 10102 return AddRHS->getOperand(1); 10103 } 10104 10105 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 10106 template<typename MaxExprType> 10107 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 10108 const SCEV *Candidate) { 10109 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 10110 if (!MaxExpr) return false; 10111 10112 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 10113 } 10114 10115 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 10116 template<typename MaxExprType> 10117 static bool IsMinConsistingOf(ScalarEvolution &SE, 10118 const SCEV *MaybeMinExpr, 10119 const SCEV *Candidate) { 10120 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 10121 if (!MaybeMaxExpr) 10122 return false; 10123 10124 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 10125 } 10126 10127 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10128 ICmpInst::Predicate Pred, 10129 const SCEV *LHS, const SCEV *RHS) { 10130 // If both sides are affine addrecs for the same loop, with equal 10131 // steps, and we know the recurrences don't wrap, then we only 10132 // need to check the predicate on the starting values. 10133 10134 if (!ICmpInst::isRelational(Pred)) 10135 return false; 10136 10137 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10138 if (!LAR) 10139 return false; 10140 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10141 if (!RAR) 10142 return false; 10143 if (LAR->getLoop() != RAR->getLoop()) 10144 return false; 10145 if (!LAR->isAffine() || !RAR->isAffine()) 10146 return false; 10147 10148 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10149 return false; 10150 10151 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10152 SCEV::FlagNSW : SCEV::FlagNUW; 10153 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10154 return false; 10155 10156 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10157 } 10158 10159 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10160 /// expression? 10161 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10162 ICmpInst::Predicate Pred, 10163 const SCEV *LHS, const SCEV *RHS) { 10164 switch (Pred) { 10165 default: 10166 return false; 10167 10168 case ICmpInst::ICMP_SGE: 10169 std::swap(LHS, RHS); 10170 LLVM_FALLTHROUGH; 10171 case ICmpInst::ICMP_SLE: 10172 return 10173 // min(A, ...) <= A 10174 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 10175 // A <= max(A, ...) 10176 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10177 10178 case ICmpInst::ICMP_UGE: 10179 std::swap(LHS, RHS); 10180 LLVM_FALLTHROUGH; 10181 case ICmpInst::ICMP_ULE: 10182 return 10183 // min(A, ...) <= A 10184 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 10185 // A <= max(A, ...) 10186 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10187 } 10188 10189 llvm_unreachable("covered switch fell through?!"); 10190 } 10191 10192 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10193 const SCEV *LHS, const SCEV *RHS, 10194 const SCEV *FoundLHS, 10195 const SCEV *FoundRHS, 10196 unsigned Depth) { 10197 assert(getTypeSizeInBits(LHS->getType()) == 10198 getTypeSizeInBits(RHS->getType()) && 10199 "LHS and RHS have different sizes?"); 10200 assert(getTypeSizeInBits(FoundLHS->getType()) == 10201 getTypeSizeInBits(FoundRHS->getType()) && 10202 "FoundLHS and FoundRHS have different sizes?"); 10203 // We want to avoid hurting the compile time with analysis of too big trees. 10204 if (Depth > MaxSCEVOperationsImplicationDepth) 10205 return false; 10206 // We only want to work with ICMP_SGT comparison so far. 10207 // TODO: Extend to ICMP_UGT? 10208 if (Pred == ICmpInst::ICMP_SLT) { 10209 Pred = ICmpInst::ICMP_SGT; 10210 std::swap(LHS, RHS); 10211 std::swap(FoundLHS, FoundRHS); 10212 } 10213 if (Pred != ICmpInst::ICMP_SGT) 10214 return false; 10215 10216 auto GetOpFromSExt = [&](const SCEV *S) { 10217 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10218 return Ext->getOperand(); 10219 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10220 // the constant in some cases. 10221 return S; 10222 }; 10223 10224 // Acquire values from extensions. 10225 auto *OrigLHS = LHS; 10226 auto *OrigFoundLHS = FoundLHS; 10227 LHS = GetOpFromSExt(LHS); 10228 FoundLHS = GetOpFromSExt(FoundLHS); 10229 10230 // Is the SGT predicate can be proved trivially or using the found context. 10231 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10232 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10233 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10234 FoundRHS, Depth + 1); 10235 }; 10236 10237 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10238 // We want to avoid creation of any new non-constant SCEV. Since we are 10239 // going to compare the operands to RHS, we should be certain that we don't 10240 // need any size extensions for this. So let's decline all cases when the 10241 // sizes of types of LHS and RHS do not match. 10242 // TODO: Maybe try to get RHS from sext to catch more cases? 10243 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10244 return false; 10245 10246 // Should not overflow. 10247 if (!LHSAddExpr->hasNoSignedWrap()) 10248 return false; 10249 10250 auto *LL = LHSAddExpr->getOperand(0); 10251 auto *LR = LHSAddExpr->getOperand(1); 10252 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10253 10254 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10255 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10256 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10257 }; 10258 // Try to prove the following rule: 10259 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10260 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10261 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10262 return true; 10263 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10264 Value *LL, *LR; 10265 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10266 10267 using namespace llvm::PatternMatch; 10268 10269 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10270 // Rules for division. 10271 // We are going to perform some comparisons with Denominator and its 10272 // derivative expressions. In general case, creating a SCEV for it may 10273 // lead to a complex analysis of the entire graph, and in particular it 10274 // can request trip count recalculation for the same loop. This would 10275 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10276 // this, we only want to create SCEVs that are constants in this section. 10277 // So we bail if Denominator is not a constant. 10278 if (!isa<ConstantInt>(LR)) 10279 return false; 10280 10281 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10282 10283 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10284 // then a SCEV for the numerator already exists and matches with FoundLHS. 10285 auto *Numerator = getExistingSCEV(LL); 10286 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10287 return false; 10288 10289 // Make sure that the numerator matches with FoundLHS and the denominator 10290 // is positive. 10291 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10292 return false; 10293 10294 auto *DTy = Denominator->getType(); 10295 auto *FRHSTy = FoundRHS->getType(); 10296 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10297 // One of types is a pointer and another one is not. We cannot extend 10298 // them properly to a wider type, so let us just reject this case. 10299 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10300 // to avoid this check. 10301 return false; 10302 10303 // Given that: 10304 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10305 auto *WTy = getWiderType(DTy, FRHSTy); 10306 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10307 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10308 10309 // Try to prove the following rule: 10310 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10311 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10312 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10313 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10314 if (isKnownNonPositive(RHS) && 10315 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10316 return true; 10317 10318 // Try to prove the following rule: 10319 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10320 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10321 // If we divide it by Denominator > 2, then: 10322 // 1. If FoundLHS is negative, then the result is 0. 10323 // 2. If FoundLHS is non-negative, then the result is non-negative. 10324 // Anyways, the result is non-negative. 10325 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10326 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10327 if (isKnownNegative(RHS) && 10328 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10329 return true; 10330 } 10331 } 10332 10333 // If our expression contained SCEVUnknown Phis, and we split it down and now 10334 // need to prove something for them, try to prove the predicate for every 10335 // possible incoming values of those Phis. 10336 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10337 return true; 10338 10339 return false; 10340 } 10341 10342 bool 10343 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10344 const SCEV *LHS, const SCEV *RHS) { 10345 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10346 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10347 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10348 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10349 } 10350 10351 bool 10352 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10353 const SCEV *LHS, const SCEV *RHS, 10354 const SCEV *FoundLHS, 10355 const SCEV *FoundRHS) { 10356 switch (Pred) { 10357 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10358 case ICmpInst::ICMP_EQ: 10359 case ICmpInst::ICMP_NE: 10360 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10361 return true; 10362 break; 10363 case ICmpInst::ICMP_SLT: 10364 case ICmpInst::ICMP_SLE: 10365 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10366 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10367 return true; 10368 break; 10369 case ICmpInst::ICMP_SGT: 10370 case ICmpInst::ICMP_SGE: 10371 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10372 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10373 return true; 10374 break; 10375 case ICmpInst::ICMP_ULT: 10376 case ICmpInst::ICMP_ULE: 10377 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10378 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10379 return true; 10380 break; 10381 case ICmpInst::ICMP_UGT: 10382 case ICmpInst::ICMP_UGE: 10383 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10384 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10385 return true; 10386 break; 10387 } 10388 10389 // Maybe it can be proved via operations? 10390 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10391 return true; 10392 10393 return false; 10394 } 10395 10396 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10397 const SCEV *LHS, 10398 const SCEV *RHS, 10399 const SCEV *FoundLHS, 10400 const SCEV *FoundRHS) { 10401 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10402 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10403 // reduce the compile time impact of this optimization. 10404 return false; 10405 10406 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10407 if (!Addend) 10408 return false; 10409 10410 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10411 10412 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10413 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10414 ConstantRange FoundLHSRange = 10415 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10416 10417 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10418 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10419 10420 // We can also compute the range of values for `LHS` that satisfy the 10421 // consequent, "`LHS` `Pred` `RHS`": 10422 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10423 ConstantRange SatisfyingLHSRange = 10424 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10425 10426 // The antecedent implies the consequent if every value of `LHS` that 10427 // satisfies the antecedent also satisfies the consequent. 10428 return SatisfyingLHSRange.contains(LHSRange); 10429 } 10430 10431 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10432 bool IsSigned, bool NoWrap) { 10433 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10434 10435 if (NoWrap) return false; 10436 10437 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10438 const SCEV *One = getOne(Stride->getType()); 10439 10440 if (IsSigned) { 10441 APInt MaxRHS = getSignedRangeMax(RHS); 10442 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10443 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10444 10445 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10446 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10447 } 10448 10449 APInt MaxRHS = getUnsignedRangeMax(RHS); 10450 APInt MaxValue = APInt::getMaxValue(BitWidth); 10451 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10452 10453 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10454 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10455 } 10456 10457 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10458 bool IsSigned, bool NoWrap) { 10459 if (NoWrap) return false; 10460 10461 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10462 const SCEV *One = getOne(Stride->getType()); 10463 10464 if (IsSigned) { 10465 APInt MinRHS = getSignedRangeMin(RHS); 10466 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10467 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10468 10469 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10470 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10471 } 10472 10473 APInt MinRHS = getUnsignedRangeMin(RHS); 10474 APInt MinValue = APInt::getMinValue(BitWidth); 10475 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10476 10477 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10478 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10479 } 10480 10481 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10482 bool Equality) { 10483 const SCEV *One = getOne(Step->getType()); 10484 Delta = Equality ? getAddExpr(Delta, Step) 10485 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10486 return getUDivExpr(Delta, Step); 10487 } 10488 10489 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10490 const SCEV *Stride, 10491 const SCEV *End, 10492 unsigned BitWidth, 10493 bool IsSigned) { 10494 10495 assert(!isKnownNonPositive(Stride) && 10496 "Stride is expected strictly positive!"); 10497 // Calculate the maximum backedge count based on the range of values 10498 // permitted by Start, End, and Stride. 10499 const SCEV *MaxBECount; 10500 APInt MinStart = 10501 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10502 10503 APInt StrideForMaxBECount = 10504 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10505 10506 // We already know that the stride is positive, so we paper over conservatism 10507 // in our range computation by forcing StrideForMaxBECount to be at least one. 10508 // In theory this is unnecessary, but we expect MaxBECount to be a 10509 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10510 // is nothing to constant fold it to). 10511 APInt One(BitWidth, 1, IsSigned); 10512 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10513 10514 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10515 : APInt::getMaxValue(BitWidth); 10516 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10517 10518 // Although End can be a MAX expression we estimate MaxEnd considering only 10519 // the case End = RHS of the loop termination condition. This is safe because 10520 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10521 // taken count. 10522 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10523 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10524 10525 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10526 getConstant(StrideForMaxBECount) /* Step */, 10527 false /* Equality */); 10528 10529 return MaxBECount; 10530 } 10531 10532 ScalarEvolution::ExitLimit 10533 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10534 const Loop *L, bool IsSigned, 10535 bool ControlsExit, bool AllowPredicates) { 10536 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10537 10538 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10539 bool PredicatedIV = false; 10540 10541 if (!IV && AllowPredicates) { 10542 // Try to make this an AddRec using runtime tests, in the first X 10543 // iterations of this loop, where X is the SCEV expression found by the 10544 // algorithm below. 10545 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10546 PredicatedIV = true; 10547 } 10548 10549 // Avoid weird loops 10550 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10551 return getCouldNotCompute(); 10552 10553 bool NoWrap = ControlsExit && 10554 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10555 10556 const SCEV *Stride = IV->getStepRecurrence(*this); 10557 10558 bool PositiveStride = isKnownPositive(Stride); 10559 10560 // Avoid negative or zero stride values. 10561 if (!PositiveStride) { 10562 // We can compute the correct backedge taken count for loops with unknown 10563 // strides if we can prove that the loop is not an infinite loop with side 10564 // effects. Here's the loop structure we are trying to handle - 10565 // 10566 // i = start 10567 // do { 10568 // A[i] = i; 10569 // i += s; 10570 // } while (i < end); 10571 // 10572 // The backedge taken count for such loops is evaluated as - 10573 // (max(end, start + stride) - start - 1) /u stride 10574 // 10575 // The additional preconditions that we need to check to prove correctness 10576 // of the above formula is as follows - 10577 // 10578 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10579 // NoWrap flag). 10580 // b) loop is single exit with no side effects. 10581 // 10582 // 10583 // Precondition a) implies that if the stride is negative, this is a single 10584 // trip loop. The backedge taken count formula reduces to zero in this case. 10585 // 10586 // Precondition b) implies that the unknown stride cannot be zero otherwise 10587 // we have UB. 10588 // 10589 // The positive stride case is the same as isKnownPositive(Stride) returning 10590 // true (original behavior of the function). 10591 // 10592 // We want to make sure that the stride is truly unknown as there are edge 10593 // cases where ScalarEvolution propagates no wrap flags to the 10594 // post-increment/decrement IV even though the increment/decrement operation 10595 // itself is wrapping. The computed backedge taken count may be wrong in 10596 // such cases. This is prevented by checking that the stride is not known to 10597 // be either positive or non-positive. For example, no wrap flags are 10598 // propagated to the post-increment IV of this loop with a trip count of 2 - 10599 // 10600 // unsigned char i; 10601 // for(i=127; i<128; i+=129) 10602 // A[i] = i; 10603 // 10604 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10605 !loopHasNoSideEffects(L)) 10606 return getCouldNotCompute(); 10607 } else if (!Stride->isOne() && 10608 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10609 // Avoid proven overflow cases: this will ensure that the backedge taken 10610 // count will not generate any unsigned overflow. Relaxed no-overflow 10611 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10612 // undefined behaviors like the case of C language. 10613 return getCouldNotCompute(); 10614 10615 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10616 : ICmpInst::ICMP_ULT; 10617 const SCEV *Start = IV->getStart(); 10618 const SCEV *End = RHS; 10619 // When the RHS is not invariant, we do not know the end bound of the loop and 10620 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10621 // calculate the MaxBECount, given the start, stride and max value for the end 10622 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10623 // checked above). 10624 if (!isLoopInvariant(RHS, L)) { 10625 const SCEV *MaxBECount = computeMaxBECountForLT( 10626 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10627 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10628 false /*MaxOrZero*/, Predicates); 10629 } 10630 // If the backedge is taken at least once, then it will be taken 10631 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10632 // is the LHS value of the less-than comparison the first time it is evaluated 10633 // and End is the RHS. 10634 const SCEV *BECountIfBackedgeTaken = 10635 computeBECount(getMinusSCEV(End, Start), Stride, false); 10636 // If the loop entry is guarded by the result of the backedge test of the 10637 // first loop iteration, then we know the backedge will be taken at least 10638 // once and so the backedge taken count is as above. If not then we use the 10639 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10640 // as if the backedge is taken at least once max(End,Start) is End and so the 10641 // result is as above, and if not max(End,Start) is Start so we get a backedge 10642 // count of zero. 10643 const SCEV *BECount; 10644 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10645 BECount = BECountIfBackedgeTaken; 10646 else { 10647 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10648 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10649 } 10650 10651 const SCEV *MaxBECount; 10652 bool MaxOrZero = false; 10653 if (isa<SCEVConstant>(BECount)) 10654 MaxBECount = BECount; 10655 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10656 // If we know exactly how many times the backedge will be taken if it's 10657 // taken at least once, then the backedge count will either be that or 10658 // zero. 10659 MaxBECount = BECountIfBackedgeTaken; 10660 MaxOrZero = true; 10661 } else { 10662 MaxBECount = computeMaxBECountForLT( 10663 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10664 } 10665 10666 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10667 !isa<SCEVCouldNotCompute>(BECount)) 10668 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10669 10670 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10671 } 10672 10673 ScalarEvolution::ExitLimit 10674 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10675 const Loop *L, bool IsSigned, 10676 bool ControlsExit, bool AllowPredicates) { 10677 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10678 // We handle only IV > Invariant 10679 if (!isLoopInvariant(RHS, L)) 10680 return getCouldNotCompute(); 10681 10682 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10683 if (!IV && AllowPredicates) 10684 // Try to make this an AddRec using runtime tests, in the first X 10685 // iterations of this loop, where X is the SCEV expression found by the 10686 // algorithm below. 10687 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10688 10689 // Avoid weird loops 10690 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10691 return getCouldNotCompute(); 10692 10693 bool NoWrap = ControlsExit && 10694 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10695 10696 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10697 10698 // Avoid negative or zero stride values 10699 if (!isKnownPositive(Stride)) 10700 return getCouldNotCompute(); 10701 10702 // Avoid proven overflow cases: this will ensure that the backedge taken count 10703 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10704 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10705 // behaviors like the case of C language. 10706 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10707 return getCouldNotCompute(); 10708 10709 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10710 : ICmpInst::ICMP_UGT; 10711 10712 const SCEV *Start = IV->getStart(); 10713 const SCEV *End = RHS; 10714 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10715 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10716 10717 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10718 10719 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10720 : getUnsignedRangeMax(Start); 10721 10722 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10723 : getUnsignedRangeMin(Stride); 10724 10725 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10726 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10727 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10728 10729 // Although End can be a MIN expression we estimate MinEnd considering only 10730 // the case End = RHS. This is safe because in the other case (Start - End) 10731 // is zero, leading to a zero maximum backedge taken count. 10732 APInt MinEnd = 10733 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10734 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10735 10736 10737 const SCEV *MaxBECount = getCouldNotCompute(); 10738 if (isa<SCEVConstant>(BECount)) 10739 MaxBECount = BECount; 10740 else 10741 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10742 getConstant(MinStride), false); 10743 10744 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10745 MaxBECount = BECount; 10746 10747 return ExitLimit(BECount, MaxBECount, false, Predicates); 10748 } 10749 10750 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10751 ScalarEvolution &SE) const { 10752 if (Range.isFullSet()) // Infinite loop. 10753 return SE.getCouldNotCompute(); 10754 10755 // If the start is a non-zero constant, shift the range to simplify things. 10756 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10757 if (!SC->getValue()->isZero()) { 10758 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10759 Operands[0] = SE.getZero(SC->getType()); 10760 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10761 getNoWrapFlags(FlagNW)); 10762 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10763 return ShiftedAddRec->getNumIterationsInRange( 10764 Range.subtract(SC->getAPInt()), SE); 10765 // This is strange and shouldn't happen. 10766 return SE.getCouldNotCompute(); 10767 } 10768 10769 // The only time we can solve this is when we have all constant indices. 10770 // Otherwise, we cannot determine the overflow conditions. 10771 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10772 return SE.getCouldNotCompute(); 10773 10774 // Okay at this point we know that all elements of the chrec are constants and 10775 // that the start element is zero. 10776 10777 // First check to see if the range contains zero. If not, the first 10778 // iteration exits. 10779 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10780 if (!Range.contains(APInt(BitWidth, 0))) 10781 return SE.getZero(getType()); 10782 10783 if (isAffine()) { 10784 // If this is an affine expression then we have this situation: 10785 // Solve {0,+,A} in Range === Ax in Range 10786 10787 // We know that zero is in the range. If A is positive then we know that 10788 // the upper value of the range must be the first possible exit value. 10789 // If A is negative then the lower of the range is the last possible loop 10790 // value. Also note that we already checked for a full range. 10791 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10792 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10793 10794 // The exit value should be (End+A)/A. 10795 APInt ExitVal = (End + A).udiv(A); 10796 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10797 10798 // Evaluate at the exit value. If we really did fall out of the valid 10799 // range, then we computed our trip count, otherwise wrap around or other 10800 // things must have happened. 10801 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10802 if (Range.contains(Val->getValue())) 10803 return SE.getCouldNotCompute(); // Something strange happened 10804 10805 // Ensure that the previous value is in the range. This is a sanity check. 10806 assert(Range.contains( 10807 EvaluateConstantChrecAtConstant(this, 10808 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10809 "Linear scev computation is off in a bad way!"); 10810 return SE.getConstant(ExitValue); 10811 } 10812 10813 if (isQuadratic()) { 10814 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10815 return SE.getConstant(S.getValue()); 10816 } 10817 10818 return SE.getCouldNotCompute(); 10819 } 10820 10821 const SCEVAddRecExpr * 10822 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10823 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10824 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10825 // but in this case we cannot guarantee that the value returned will be an 10826 // AddRec because SCEV does not have a fixed point where it stops 10827 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10828 // may happen if we reach arithmetic depth limit while simplifying. So we 10829 // construct the returned value explicitly. 10830 SmallVector<const SCEV *, 3> Ops; 10831 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10832 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10833 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10834 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10835 // We know that the last operand is not a constant zero (otherwise it would 10836 // have been popped out earlier). This guarantees us that if the result has 10837 // the same last operand, then it will also not be popped out, meaning that 10838 // the returned value will be an AddRec. 10839 const SCEV *Last = getOperand(getNumOperands() - 1); 10840 assert(!Last->isZero() && "Recurrency with zero step?"); 10841 Ops.push_back(Last); 10842 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10843 SCEV::FlagAnyWrap)); 10844 } 10845 10846 // Return true when S contains at least an undef value. 10847 static inline bool containsUndefs(const SCEV *S) { 10848 return SCEVExprContains(S, [](const SCEV *S) { 10849 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10850 return isa<UndefValue>(SU->getValue()); 10851 return false; 10852 }); 10853 } 10854 10855 namespace { 10856 10857 // Collect all steps of SCEV expressions. 10858 struct SCEVCollectStrides { 10859 ScalarEvolution &SE; 10860 SmallVectorImpl<const SCEV *> &Strides; 10861 10862 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10863 : SE(SE), Strides(S) {} 10864 10865 bool follow(const SCEV *S) { 10866 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10867 Strides.push_back(AR->getStepRecurrence(SE)); 10868 return true; 10869 } 10870 10871 bool isDone() const { return false; } 10872 }; 10873 10874 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10875 struct SCEVCollectTerms { 10876 SmallVectorImpl<const SCEV *> &Terms; 10877 10878 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10879 10880 bool follow(const SCEV *S) { 10881 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10882 isa<SCEVSignExtendExpr>(S)) { 10883 if (!containsUndefs(S)) 10884 Terms.push_back(S); 10885 10886 // Stop recursion: once we collected a term, do not walk its operands. 10887 return false; 10888 } 10889 10890 // Keep looking. 10891 return true; 10892 } 10893 10894 bool isDone() const { return false; } 10895 }; 10896 10897 // Check if a SCEV contains an AddRecExpr. 10898 struct SCEVHasAddRec { 10899 bool &ContainsAddRec; 10900 10901 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10902 ContainsAddRec = false; 10903 } 10904 10905 bool follow(const SCEV *S) { 10906 if (isa<SCEVAddRecExpr>(S)) { 10907 ContainsAddRec = true; 10908 10909 // Stop recursion: once we collected a term, do not walk its operands. 10910 return false; 10911 } 10912 10913 // Keep looking. 10914 return true; 10915 } 10916 10917 bool isDone() const { return false; } 10918 }; 10919 10920 // Find factors that are multiplied with an expression that (possibly as a 10921 // subexpression) contains an AddRecExpr. In the expression: 10922 // 10923 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10924 // 10925 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10926 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10927 // parameters as they form a product with an induction variable. 10928 // 10929 // This collector expects all array size parameters to be in the same MulExpr. 10930 // It might be necessary to later add support for collecting parameters that are 10931 // spread over different nested MulExpr. 10932 struct SCEVCollectAddRecMultiplies { 10933 SmallVectorImpl<const SCEV *> &Terms; 10934 ScalarEvolution &SE; 10935 10936 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10937 : Terms(T), SE(SE) {} 10938 10939 bool follow(const SCEV *S) { 10940 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10941 bool HasAddRec = false; 10942 SmallVector<const SCEV *, 0> Operands; 10943 for (auto Op : Mul->operands()) { 10944 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10945 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10946 Operands.push_back(Op); 10947 } else if (Unknown) { 10948 HasAddRec = true; 10949 } else { 10950 bool ContainsAddRec; 10951 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10952 visitAll(Op, ContiansAddRec); 10953 HasAddRec |= ContainsAddRec; 10954 } 10955 } 10956 if (Operands.size() == 0) 10957 return true; 10958 10959 if (!HasAddRec) 10960 return false; 10961 10962 Terms.push_back(SE.getMulExpr(Operands)); 10963 // Stop recursion: once we collected a term, do not walk its operands. 10964 return false; 10965 } 10966 10967 // Keep looking. 10968 return true; 10969 } 10970 10971 bool isDone() const { return false; } 10972 }; 10973 10974 } // end anonymous namespace 10975 10976 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10977 /// two places: 10978 /// 1) The strides of AddRec expressions. 10979 /// 2) Unknowns that are multiplied with AddRec expressions. 10980 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10981 SmallVectorImpl<const SCEV *> &Terms) { 10982 SmallVector<const SCEV *, 4> Strides; 10983 SCEVCollectStrides StrideCollector(*this, Strides); 10984 visitAll(Expr, StrideCollector); 10985 10986 LLVM_DEBUG({ 10987 dbgs() << "Strides:\n"; 10988 for (const SCEV *S : Strides) 10989 dbgs() << *S << "\n"; 10990 }); 10991 10992 for (const SCEV *S : Strides) { 10993 SCEVCollectTerms TermCollector(Terms); 10994 visitAll(S, TermCollector); 10995 } 10996 10997 LLVM_DEBUG({ 10998 dbgs() << "Terms:\n"; 10999 for (const SCEV *T : Terms) 11000 dbgs() << *T << "\n"; 11001 }); 11002 11003 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11004 visitAll(Expr, MulCollector); 11005 } 11006 11007 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11008 SmallVectorImpl<const SCEV *> &Terms, 11009 SmallVectorImpl<const SCEV *> &Sizes) { 11010 int Last = Terms.size() - 1; 11011 const SCEV *Step = Terms[Last]; 11012 11013 // End of recursion. 11014 if (Last == 0) { 11015 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11016 SmallVector<const SCEV *, 2> Qs; 11017 for (const SCEV *Op : M->operands()) 11018 if (!isa<SCEVConstant>(Op)) 11019 Qs.push_back(Op); 11020 11021 Step = SE.getMulExpr(Qs); 11022 } 11023 11024 Sizes.push_back(Step); 11025 return true; 11026 } 11027 11028 for (const SCEV *&Term : Terms) { 11029 // Normalize the terms before the next call to findArrayDimensionsRec. 11030 const SCEV *Q, *R; 11031 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11032 11033 // Bail out when GCD does not evenly divide one of the terms. 11034 if (!R->isZero()) 11035 return false; 11036 11037 Term = Q; 11038 } 11039 11040 // Remove all SCEVConstants. 11041 Terms.erase( 11042 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11043 Terms.end()); 11044 11045 if (Terms.size() > 0) 11046 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11047 return false; 11048 11049 Sizes.push_back(Step); 11050 return true; 11051 } 11052 11053 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11054 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11055 for (const SCEV *T : Terms) 11056 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11057 return true; 11058 return false; 11059 } 11060 11061 // Return the number of product terms in S. 11062 static inline int numberOfTerms(const SCEV *S) { 11063 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11064 return Expr->getNumOperands(); 11065 return 1; 11066 } 11067 11068 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11069 if (isa<SCEVConstant>(T)) 11070 return nullptr; 11071 11072 if (isa<SCEVUnknown>(T)) 11073 return T; 11074 11075 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11076 SmallVector<const SCEV *, 2> Factors; 11077 for (const SCEV *Op : M->operands()) 11078 if (!isa<SCEVConstant>(Op)) 11079 Factors.push_back(Op); 11080 11081 return SE.getMulExpr(Factors); 11082 } 11083 11084 return T; 11085 } 11086 11087 /// Return the size of an element read or written by Inst. 11088 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11089 Type *Ty; 11090 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11091 Ty = Store->getValueOperand()->getType(); 11092 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11093 Ty = Load->getType(); 11094 else 11095 return nullptr; 11096 11097 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11098 return getSizeOfExpr(ETy, Ty); 11099 } 11100 11101 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11102 SmallVectorImpl<const SCEV *> &Sizes, 11103 const SCEV *ElementSize) { 11104 if (Terms.size() < 1 || !ElementSize) 11105 return; 11106 11107 // Early return when Terms do not contain parameters: we do not delinearize 11108 // non parametric SCEVs. 11109 if (!containsParameters(Terms)) 11110 return; 11111 11112 LLVM_DEBUG({ 11113 dbgs() << "Terms:\n"; 11114 for (const SCEV *T : Terms) 11115 dbgs() << *T << "\n"; 11116 }); 11117 11118 // Remove duplicates. 11119 array_pod_sort(Terms.begin(), Terms.end()); 11120 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11121 11122 // Put larger terms first. 11123 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11124 return numberOfTerms(LHS) > numberOfTerms(RHS); 11125 }); 11126 11127 // Try to divide all terms by the element size. If term is not divisible by 11128 // element size, proceed with the original term. 11129 for (const SCEV *&Term : Terms) { 11130 const SCEV *Q, *R; 11131 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11132 if (!Q->isZero()) 11133 Term = Q; 11134 } 11135 11136 SmallVector<const SCEV *, 4> NewTerms; 11137 11138 // Remove constant factors. 11139 for (const SCEV *T : Terms) 11140 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11141 NewTerms.push_back(NewT); 11142 11143 LLVM_DEBUG({ 11144 dbgs() << "Terms after sorting:\n"; 11145 for (const SCEV *T : NewTerms) 11146 dbgs() << *T << "\n"; 11147 }); 11148 11149 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11150 Sizes.clear(); 11151 return; 11152 } 11153 11154 // The last element to be pushed into Sizes is the size of an element. 11155 Sizes.push_back(ElementSize); 11156 11157 LLVM_DEBUG({ 11158 dbgs() << "Sizes:\n"; 11159 for (const SCEV *S : Sizes) 11160 dbgs() << *S << "\n"; 11161 }); 11162 } 11163 11164 void ScalarEvolution::computeAccessFunctions( 11165 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11166 SmallVectorImpl<const SCEV *> &Sizes) { 11167 // Early exit in case this SCEV is not an affine multivariate function. 11168 if (Sizes.empty()) 11169 return; 11170 11171 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11172 if (!AR->isAffine()) 11173 return; 11174 11175 const SCEV *Res = Expr; 11176 int Last = Sizes.size() - 1; 11177 for (int i = Last; i >= 0; i--) { 11178 const SCEV *Q, *R; 11179 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11180 11181 LLVM_DEBUG({ 11182 dbgs() << "Res: " << *Res << "\n"; 11183 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11184 dbgs() << "Res divided by Sizes[i]:\n"; 11185 dbgs() << "Quotient: " << *Q << "\n"; 11186 dbgs() << "Remainder: " << *R << "\n"; 11187 }); 11188 11189 Res = Q; 11190 11191 // Do not record the last subscript corresponding to the size of elements in 11192 // the array. 11193 if (i == Last) { 11194 11195 // Bail out if the remainder is too complex. 11196 if (isa<SCEVAddRecExpr>(R)) { 11197 Subscripts.clear(); 11198 Sizes.clear(); 11199 return; 11200 } 11201 11202 continue; 11203 } 11204 11205 // Record the access function for the current subscript. 11206 Subscripts.push_back(R); 11207 } 11208 11209 // Also push in last position the remainder of the last division: it will be 11210 // the access function of the innermost dimension. 11211 Subscripts.push_back(Res); 11212 11213 std::reverse(Subscripts.begin(), Subscripts.end()); 11214 11215 LLVM_DEBUG({ 11216 dbgs() << "Subscripts:\n"; 11217 for (const SCEV *S : Subscripts) 11218 dbgs() << *S << "\n"; 11219 }); 11220 } 11221 11222 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11223 /// sizes of an array access. Returns the remainder of the delinearization that 11224 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11225 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11226 /// expressions in the stride and base of a SCEV corresponding to the 11227 /// computation of a GCD (greatest common divisor) of base and stride. When 11228 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11229 /// 11230 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11231 /// 11232 /// void foo(long n, long m, long o, double A[n][m][o]) { 11233 /// 11234 /// for (long i = 0; i < n; i++) 11235 /// for (long j = 0; j < m; j++) 11236 /// for (long k = 0; k < o; k++) 11237 /// A[i][j][k] = 1.0; 11238 /// } 11239 /// 11240 /// the delinearization input is the following AddRec SCEV: 11241 /// 11242 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11243 /// 11244 /// From this SCEV, we are able to say that the base offset of the access is %A 11245 /// because it appears as an offset that does not divide any of the strides in 11246 /// the loops: 11247 /// 11248 /// CHECK: Base offset: %A 11249 /// 11250 /// and then SCEV->delinearize determines the size of some of the dimensions of 11251 /// the array as these are the multiples by which the strides are happening: 11252 /// 11253 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11254 /// 11255 /// Note that the outermost dimension remains of UnknownSize because there are 11256 /// no strides that would help identifying the size of the last dimension: when 11257 /// the array has been statically allocated, one could compute the size of that 11258 /// dimension by dividing the overall size of the array by the size of the known 11259 /// dimensions: %m * %o * 8. 11260 /// 11261 /// Finally delinearize provides the access functions for the array reference 11262 /// that does correspond to A[i][j][k] of the above C testcase: 11263 /// 11264 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11265 /// 11266 /// The testcases are checking the output of a function pass: 11267 /// DelinearizationPass that walks through all loads and stores of a function 11268 /// asking for the SCEV of the memory access with respect to all enclosing 11269 /// loops, calling SCEV->delinearize on that and printing the results. 11270 void ScalarEvolution::delinearize(const SCEV *Expr, 11271 SmallVectorImpl<const SCEV *> &Subscripts, 11272 SmallVectorImpl<const SCEV *> &Sizes, 11273 const SCEV *ElementSize) { 11274 // First step: collect parametric terms. 11275 SmallVector<const SCEV *, 4> Terms; 11276 collectParametricTerms(Expr, Terms); 11277 11278 if (Terms.empty()) 11279 return; 11280 11281 // Second step: find subscript sizes. 11282 findArrayDimensions(Terms, Sizes, ElementSize); 11283 11284 if (Sizes.empty()) 11285 return; 11286 11287 // Third step: compute the access functions for each subscript. 11288 computeAccessFunctions(Expr, Subscripts, Sizes); 11289 11290 if (Subscripts.empty()) 11291 return; 11292 11293 LLVM_DEBUG({ 11294 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11295 dbgs() << "ArrayDecl[UnknownSize]"; 11296 for (const SCEV *S : Sizes) 11297 dbgs() << "[" << *S << "]"; 11298 11299 dbgs() << "\nArrayRef"; 11300 for (const SCEV *S : Subscripts) 11301 dbgs() << "[" << *S << "]"; 11302 dbgs() << "\n"; 11303 }); 11304 } 11305 11306 //===----------------------------------------------------------------------===// 11307 // SCEVCallbackVH Class Implementation 11308 //===----------------------------------------------------------------------===// 11309 11310 void ScalarEvolution::SCEVCallbackVH::deleted() { 11311 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11312 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11313 SE->ConstantEvolutionLoopExitValue.erase(PN); 11314 SE->eraseValueFromMap(getValPtr()); 11315 // this now dangles! 11316 } 11317 11318 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11319 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11320 11321 // Forget all the expressions associated with users of the old value, 11322 // so that future queries will recompute the expressions using the new 11323 // value. 11324 Value *Old = getValPtr(); 11325 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11326 SmallPtrSet<User *, 8> Visited; 11327 while (!Worklist.empty()) { 11328 User *U = Worklist.pop_back_val(); 11329 // Deleting the Old value will cause this to dangle. Postpone 11330 // that until everything else is done. 11331 if (U == Old) 11332 continue; 11333 if (!Visited.insert(U).second) 11334 continue; 11335 if (PHINode *PN = dyn_cast<PHINode>(U)) 11336 SE->ConstantEvolutionLoopExitValue.erase(PN); 11337 SE->eraseValueFromMap(U); 11338 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11339 } 11340 // Delete the Old value. 11341 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11342 SE->ConstantEvolutionLoopExitValue.erase(PN); 11343 SE->eraseValueFromMap(Old); 11344 // this now dangles! 11345 } 11346 11347 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11348 : CallbackVH(V), SE(se) {} 11349 11350 //===----------------------------------------------------------------------===// 11351 // ScalarEvolution Class Implementation 11352 //===----------------------------------------------------------------------===// 11353 11354 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11355 AssumptionCache &AC, DominatorTree &DT, 11356 LoopInfo &LI) 11357 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11358 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11359 LoopDispositions(64), BlockDispositions(64) { 11360 // To use guards for proving predicates, we need to scan every instruction in 11361 // relevant basic blocks, and not just terminators. Doing this is a waste of 11362 // time if the IR does not actually contain any calls to 11363 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11364 // 11365 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11366 // to _add_ guards to the module when there weren't any before, and wants 11367 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11368 // efficient in lieu of being smart in that rather obscure case. 11369 11370 auto *GuardDecl = F.getParent()->getFunction( 11371 Intrinsic::getName(Intrinsic::experimental_guard)); 11372 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11373 } 11374 11375 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11376 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11377 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11378 ValueExprMap(std::move(Arg.ValueExprMap)), 11379 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11380 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11381 PendingMerges(std::move(Arg.PendingMerges)), 11382 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11383 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11384 PredicatedBackedgeTakenCounts( 11385 std::move(Arg.PredicatedBackedgeTakenCounts)), 11386 ConstantEvolutionLoopExitValue( 11387 std::move(Arg.ConstantEvolutionLoopExitValue)), 11388 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11389 LoopDispositions(std::move(Arg.LoopDispositions)), 11390 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11391 BlockDispositions(std::move(Arg.BlockDispositions)), 11392 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11393 SignedRanges(std::move(Arg.SignedRanges)), 11394 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11395 UniquePreds(std::move(Arg.UniquePreds)), 11396 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11397 LoopUsers(std::move(Arg.LoopUsers)), 11398 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11399 FirstUnknown(Arg.FirstUnknown) { 11400 Arg.FirstUnknown = nullptr; 11401 } 11402 11403 ScalarEvolution::~ScalarEvolution() { 11404 // Iterate through all the SCEVUnknown instances and call their 11405 // destructors, so that they release their references to their values. 11406 for (SCEVUnknown *U = FirstUnknown; U;) { 11407 SCEVUnknown *Tmp = U; 11408 U = U->Next; 11409 Tmp->~SCEVUnknown(); 11410 } 11411 FirstUnknown = nullptr; 11412 11413 ExprValueMap.clear(); 11414 ValueExprMap.clear(); 11415 HasRecMap.clear(); 11416 11417 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11418 // that a loop had multiple computable exits. 11419 for (auto &BTCI : BackedgeTakenCounts) 11420 BTCI.second.clear(); 11421 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11422 BTCI.second.clear(); 11423 11424 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11425 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11426 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11427 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11428 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11429 } 11430 11431 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11432 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11433 } 11434 11435 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11436 const Loop *L) { 11437 // Print all inner loops first 11438 for (Loop *I : *L) 11439 PrintLoopInfo(OS, SE, I); 11440 11441 OS << "Loop "; 11442 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11443 OS << ": "; 11444 11445 SmallVector<BasicBlock *, 8> ExitBlocks; 11446 L->getExitBlocks(ExitBlocks); 11447 if (ExitBlocks.size() != 1) 11448 OS << "<multiple exits> "; 11449 11450 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11451 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 11452 } else { 11453 OS << "Unpredictable backedge-taken count. "; 11454 } 11455 11456 OS << "\n" 11457 "Loop "; 11458 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11459 OS << ": "; 11460 11461 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 11462 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 11463 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11464 OS << ", actual taken count either this or zero."; 11465 } else { 11466 OS << "Unpredictable max backedge-taken count. "; 11467 } 11468 11469 OS << "\n" 11470 "Loop "; 11471 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11472 OS << ": "; 11473 11474 SCEVUnionPredicate Pred; 11475 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11476 if (!isa<SCEVCouldNotCompute>(PBT)) { 11477 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11478 OS << " Predicates:\n"; 11479 Pred.print(OS, 4); 11480 } else { 11481 OS << "Unpredictable predicated backedge-taken count. "; 11482 } 11483 OS << "\n"; 11484 11485 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11486 OS << "Loop "; 11487 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11488 OS << ": "; 11489 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11490 } 11491 } 11492 11493 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11494 switch (LD) { 11495 case ScalarEvolution::LoopVariant: 11496 return "Variant"; 11497 case ScalarEvolution::LoopInvariant: 11498 return "Invariant"; 11499 case ScalarEvolution::LoopComputable: 11500 return "Computable"; 11501 } 11502 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11503 } 11504 11505 void ScalarEvolution::print(raw_ostream &OS) const { 11506 // ScalarEvolution's implementation of the print method is to print 11507 // out SCEV values of all instructions that are interesting. Doing 11508 // this potentially causes it to create new SCEV objects though, 11509 // which technically conflicts with the const qualifier. This isn't 11510 // observable from outside the class though, so casting away the 11511 // const isn't dangerous. 11512 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11513 11514 OS << "Classifying expressions for: "; 11515 F.printAsOperand(OS, /*PrintType=*/false); 11516 OS << "\n"; 11517 for (Instruction &I : instructions(F)) 11518 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11519 OS << I << '\n'; 11520 OS << " --> "; 11521 const SCEV *SV = SE.getSCEV(&I); 11522 SV->print(OS); 11523 if (!isa<SCEVCouldNotCompute>(SV)) { 11524 OS << " U: "; 11525 SE.getUnsignedRange(SV).print(OS); 11526 OS << " S: "; 11527 SE.getSignedRange(SV).print(OS); 11528 } 11529 11530 const Loop *L = LI.getLoopFor(I.getParent()); 11531 11532 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11533 if (AtUse != SV) { 11534 OS << " --> "; 11535 AtUse->print(OS); 11536 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11537 OS << " U: "; 11538 SE.getUnsignedRange(AtUse).print(OS); 11539 OS << " S: "; 11540 SE.getSignedRange(AtUse).print(OS); 11541 } 11542 } 11543 11544 if (L) { 11545 OS << "\t\t" "Exits: "; 11546 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11547 if (!SE.isLoopInvariant(ExitValue, L)) { 11548 OS << "<<Unknown>>"; 11549 } else { 11550 OS << *ExitValue; 11551 } 11552 11553 bool First = true; 11554 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11555 if (First) { 11556 OS << "\t\t" "LoopDispositions: { "; 11557 First = false; 11558 } else { 11559 OS << ", "; 11560 } 11561 11562 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11563 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11564 } 11565 11566 for (auto *InnerL : depth_first(L)) { 11567 if (InnerL == L) 11568 continue; 11569 if (First) { 11570 OS << "\t\t" "LoopDispositions: { "; 11571 First = false; 11572 } else { 11573 OS << ", "; 11574 } 11575 11576 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11577 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11578 } 11579 11580 OS << " }"; 11581 } 11582 11583 OS << "\n"; 11584 } 11585 11586 OS << "Determining loop execution counts for: "; 11587 F.printAsOperand(OS, /*PrintType=*/false); 11588 OS << "\n"; 11589 for (Loop *I : LI) 11590 PrintLoopInfo(OS, &SE, I); 11591 } 11592 11593 ScalarEvolution::LoopDisposition 11594 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11595 auto &Values = LoopDispositions[S]; 11596 for (auto &V : Values) { 11597 if (V.getPointer() == L) 11598 return V.getInt(); 11599 } 11600 Values.emplace_back(L, LoopVariant); 11601 LoopDisposition D = computeLoopDisposition(S, L); 11602 auto &Values2 = LoopDispositions[S]; 11603 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11604 if (V.getPointer() == L) { 11605 V.setInt(D); 11606 break; 11607 } 11608 } 11609 return D; 11610 } 11611 11612 ScalarEvolution::LoopDisposition 11613 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11614 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11615 case scConstant: 11616 return LoopInvariant; 11617 case scTruncate: 11618 case scZeroExtend: 11619 case scSignExtend: 11620 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11621 case scAddRecExpr: { 11622 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11623 11624 // If L is the addrec's loop, it's computable. 11625 if (AR->getLoop() == L) 11626 return LoopComputable; 11627 11628 // Add recurrences are never invariant in the function-body (null loop). 11629 if (!L) 11630 return LoopVariant; 11631 11632 // Everything that is not defined at loop entry is variant. 11633 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11634 return LoopVariant; 11635 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11636 " dominate the contained loop's header?"); 11637 11638 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11639 if (AR->getLoop()->contains(L)) 11640 return LoopInvariant; 11641 11642 // This recurrence is variant w.r.t. L if any of its operands 11643 // are variant. 11644 for (auto *Op : AR->operands()) 11645 if (!isLoopInvariant(Op, L)) 11646 return LoopVariant; 11647 11648 // Otherwise it's loop-invariant. 11649 return LoopInvariant; 11650 } 11651 case scAddExpr: 11652 case scMulExpr: 11653 case scUMaxExpr: 11654 case scSMaxExpr: { 11655 bool HasVarying = false; 11656 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11657 LoopDisposition D = getLoopDisposition(Op, L); 11658 if (D == LoopVariant) 11659 return LoopVariant; 11660 if (D == LoopComputable) 11661 HasVarying = true; 11662 } 11663 return HasVarying ? LoopComputable : LoopInvariant; 11664 } 11665 case scUDivExpr: { 11666 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11667 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11668 if (LD == LoopVariant) 11669 return LoopVariant; 11670 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11671 if (RD == LoopVariant) 11672 return LoopVariant; 11673 return (LD == LoopInvariant && RD == LoopInvariant) ? 11674 LoopInvariant : LoopComputable; 11675 } 11676 case scUnknown: 11677 // All non-instruction values are loop invariant. All instructions are loop 11678 // invariant if they are not contained in the specified loop. 11679 // Instructions are never considered invariant in the function body 11680 // (null loop) because they are defined within the "loop". 11681 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11682 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11683 return LoopInvariant; 11684 case scCouldNotCompute: 11685 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11686 } 11687 llvm_unreachable("Unknown SCEV kind!"); 11688 } 11689 11690 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11691 return getLoopDisposition(S, L) == LoopInvariant; 11692 } 11693 11694 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11695 return getLoopDisposition(S, L) == LoopComputable; 11696 } 11697 11698 ScalarEvolution::BlockDisposition 11699 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11700 auto &Values = BlockDispositions[S]; 11701 for (auto &V : Values) { 11702 if (V.getPointer() == BB) 11703 return V.getInt(); 11704 } 11705 Values.emplace_back(BB, DoesNotDominateBlock); 11706 BlockDisposition D = computeBlockDisposition(S, BB); 11707 auto &Values2 = BlockDispositions[S]; 11708 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11709 if (V.getPointer() == BB) { 11710 V.setInt(D); 11711 break; 11712 } 11713 } 11714 return D; 11715 } 11716 11717 ScalarEvolution::BlockDisposition 11718 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11719 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11720 case scConstant: 11721 return ProperlyDominatesBlock; 11722 case scTruncate: 11723 case scZeroExtend: 11724 case scSignExtend: 11725 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11726 case scAddRecExpr: { 11727 // This uses a "dominates" query instead of "properly dominates" query 11728 // to test for proper dominance too, because the instruction which 11729 // produces the addrec's value is a PHI, and a PHI effectively properly 11730 // dominates its entire containing block. 11731 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11732 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11733 return DoesNotDominateBlock; 11734 11735 // Fall through into SCEVNAryExpr handling. 11736 LLVM_FALLTHROUGH; 11737 } 11738 case scAddExpr: 11739 case scMulExpr: 11740 case scUMaxExpr: 11741 case scSMaxExpr: { 11742 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11743 bool Proper = true; 11744 for (const SCEV *NAryOp : NAry->operands()) { 11745 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11746 if (D == DoesNotDominateBlock) 11747 return DoesNotDominateBlock; 11748 if (D == DominatesBlock) 11749 Proper = false; 11750 } 11751 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11752 } 11753 case scUDivExpr: { 11754 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11755 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11756 BlockDisposition LD = getBlockDisposition(LHS, BB); 11757 if (LD == DoesNotDominateBlock) 11758 return DoesNotDominateBlock; 11759 BlockDisposition RD = getBlockDisposition(RHS, BB); 11760 if (RD == DoesNotDominateBlock) 11761 return DoesNotDominateBlock; 11762 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11763 ProperlyDominatesBlock : DominatesBlock; 11764 } 11765 case scUnknown: 11766 if (Instruction *I = 11767 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11768 if (I->getParent() == BB) 11769 return DominatesBlock; 11770 if (DT.properlyDominates(I->getParent(), BB)) 11771 return ProperlyDominatesBlock; 11772 return DoesNotDominateBlock; 11773 } 11774 return ProperlyDominatesBlock; 11775 case scCouldNotCompute: 11776 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11777 } 11778 llvm_unreachable("Unknown SCEV kind!"); 11779 } 11780 11781 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11782 return getBlockDisposition(S, BB) >= DominatesBlock; 11783 } 11784 11785 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11786 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11787 } 11788 11789 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11790 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11791 } 11792 11793 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11794 auto IsS = [&](const SCEV *X) { return S == X; }; 11795 auto ContainsS = [&](const SCEV *X) { 11796 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11797 }; 11798 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11799 } 11800 11801 void 11802 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11803 ValuesAtScopes.erase(S); 11804 LoopDispositions.erase(S); 11805 BlockDispositions.erase(S); 11806 UnsignedRanges.erase(S); 11807 SignedRanges.erase(S); 11808 ExprValueMap.erase(S); 11809 HasRecMap.erase(S); 11810 MinTrailingZerosCache.erase(S); 11811 11812 for (auto I = PredicatedSCEVRewrites.begin(); 11813 I != PredicatedSCEVRewrites.end();) { 11814 std::pair<const SCEV *, const Loop *> Entry = I->first; 11815 if (Entry.first == S) 11816 PredicatedSCEVRewrites.erase(I++); 11817 else 11818 ++I; 11819 } 11820 11821 auto RemoveSCEVFromBackedgeMap = 11822 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11823 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11824 BackedgeTakenInfo &BEInfo = I->second; 11825 if (BEInfo.hasOperand(S, this)) { 11826 BEInfo.clear(); 11827 Map.erase(I++); 11828 } else 11829 ++I; 11830 } 11831 }; 11832 11833 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11834 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11835 } 11836 11837 void 11838 ScalarEvolution::getUsedLoops(const SCEV *S, 11839 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11840 struct FindUsedLoops { 11841 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11842 : LoopsUsed(LoopsUsed) {} 11843 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11844 bool follow(const SCEV *S) { 11845 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11846 LoopsUsed.insert(AR->getLoop()); 11847 return true; 11848 } 11849 11850 bool isDone() const { return false; } 11851 }; 11852 11853 FindUsedLoops F(LoopsUsed); 11854 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11855 } 11856 11857 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11858 SmallPtrSet<const Loop *, 8> LoopsUsed; 11859 getUsedLoops(S, LoopsUsed); 11860 for (auto *L : LoopsUsed) 11861 LoopUsers[L].push_back(S); 11862 } 11863 11864 void ScalarEvolution::verify() const { 11865 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11866 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11867 11868 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11869 11870 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11871 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11872 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11873 11874 const SCEV *visitConstant(const SCEVConstant *Constant) { 11875 return SE.getConstant(Constant->getAPInt()); 11876 } 11877 11878 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11879 return SE.getUnknown(Expr->getValue()); 11880 } 11881 11882 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11883 return SE.getCouldNotCompute(); 11884 } 11885 }; 11886 11887 SCEVMapper SCM(SE2); 11888 11889 while (!LoopStack.empty()) { 11890 auto *L = LoopStack.pop_back_val(); 11891 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11892 11893 auto *CurBECount = SCM.visit( 11894 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11895 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11896 11897 if (CurBECount == SE2.getCouldNotCompute() || 11898 NewBECount == SE2.getCouldNotCompute()) { 11899 // NB! This situation is legal, but is very suspicious -- whatever pass 11900 // change the loop to make a trip count go from could not compute to 11901 // computable or vice-versa *should have* invalidated SCEV. However, we 11902 // choose not to assert here (for now) since we don't want false 11903 // positives. 11904 continue; 11905 } 11906 11907 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11908 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11909 // not propagate undef aggressively). This means we can (and do) fail 11910 // verification in cases where a transform makes the trip count of a loop 11911 // go from "undef" to "undef+1" (say). The transform is fine, since in 11912 // both cases the loop iterates "undef" times, but SCEV thinks we 11913 // increased the trip count of the loop by 1 incorrectly. 11914 continue; 11915 } 11916 11917 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11918 SE.getTypeSizeInBits(NewBECount->getType())) 11919 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11920 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11921 SE.getTypeSizeInBits(NewBECount->getType())) 11922 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11923 11924 auto *ConstantDelta = 11925 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11926 11927 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11928 dbgs() << "Trip Count Changed!\n"; 11929 dbgs() << "Old: " << *CurBECount << "\n"; 11930 dbgs() << "New: " << *NewBECount << "\n"; 11931 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11932 std::abort(); 11933 } 11934 } 11935 } 11936 11937 bool ScalarEvolution::invalidate( 11938 Function &F, const PreservedAnalyses &PA, 11939 FunctionAnalysisManager::Invalidator &Inv) { 11940 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11941 // of its dependencies is invalidated. 11942 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11943 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11944 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11945 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11946 Inv.invalidate<LoopAnalysis>(F, PA); 11947 } 11948 11949 AnalysisKey ScalarEvolutionAnalysis::Key; 11950 11951 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11952 FunctionAnalysisManager &AM) { 11953 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11954 AM.getResult<AssumptionAnalysis>(F), 11955 AM.getResult<DominatorTreeAnalysis>(F), 11956 AM.getResult<LoopAnalysis>(F)); 11957 } 11958 11959 PreservedAnalyses 11960 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11961 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11962 return PreservedAnalyses::all(); 11963 } 11964 11965 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11966 "Scalar Evolution Analysis", false, true) 11967 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11968 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11969 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11970 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11971 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11972 "Scalar Evolution Analysis", false, true) 11973 11974 char ScalarEvolutionWrapperPass::ID = 0; 11975 11976 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11977 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11978 } 11979 11980 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11981 SE.reset(new ScalarEvolution( 11982 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11983 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11984 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11985 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11986 return false; 11987 } 11988 11989 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11990 11991 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11992 SE->print(OS); 11993 } 11994 11995 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11996 if (!VerifySCEV) 11997 return; 11998 11999 SE->verify(); 12000 } 12001 12002 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12003 AU.setPreservesAll(); 12004 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12005 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12006 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12007 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12008 } 12009 12010 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12011 const SCEV *RHS) { 12012 FoldingSetNodeID ID; 12013 assert(LHS->getType() == RHS->getType() && 12014 "Type mismatch between LHS and RHS"); 12015 // Unique this node based on the arguments 12016 ID.AddInteger(SCEVPredicate::P_Equal); 12017 ID.AddPointer(LHS); 12018 ID.AddPointer(RHS); 12019 void *IP = nullptr; 12020 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12021 return S; 12022 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12023 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12024 UniquePreds.InsertNode(Eq, IP); 12025 return Eq; 12026 } 12027 12028 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12029 const SCEVAddRecExpr *AR, 12030 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12031 FoldingSetNodeID ID; 12032 // Unique this node based on the arguments 12033 ID.AddInteger(SCEVPredicate::P_Wrap); 12034 ID.AddPointer(AR); 12035 ID.AddInteger(AddedFlags); 12036 void *IP = nullptr; 12037 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12038 return S; 12039 auto *OF = new (SCEVAllocator) 12040 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12041 UniquePreds.InsertNode(OF, IP); 12042 return OF; 12043 } 12044 12045 namespace { 12046 12047 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12048 public: 12049 12050 /// Rewrites \p S in the context of a loop L and the SCEV predication 12051 /// infrastructure. 12052 /// 12053 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12054 /// equivalences present in \p Pred. 12055 /// 12056 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12057 /// \p NewPreds such that the result will be an AddRecExpr. 12058 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12059 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12060 SCEVUnionPredicate *Pred) { 12061 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12062 return Rewriter.visit(S); 12063 } 12064 12065 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12066 if (Pred) { 12067 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12068 for (auto *Pred : ExprPreds) 12069 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12070 if (IPred->getLHS() == Expr) 12071 return IPred->getRHS(); 12072 } 12073 return convertToAddRecWithPreds(Expr); 12074 } 12075 12076 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12077 const SCEV *Operand = visit(Expr->getOperand()); 12078 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12079 if (AR && AR->getLoop() == L && AR->isAffine()) { 12080 // This couldn't be folded because the operand didn't have the nuw 12081 // flag. Add the nusw flag as an assumption that we could make. 12082 const SCEV *Step = AR->getStepRecurrence(SE); 12083 Type *Ty = Expr->getType(); 12084 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12085 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12086 SE.getSignExtendExpr(Step, Ty), L, 12087 AR->getNoWrapFlags()); 12088 } 12089 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12090 } 12091 12092 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12093 const SCEV *Operand = visit(Expr->getOperand()); 12094 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12095 if (AR && AR->getLoop() == L && AR->isAffine()) { 12096 // This couldn't be folded because the operand didn't have the nsw 12097 // flag. Add the nssw flag as an assumption that we could make. 12098 const SCEV *Step = AR->getStepRecurrence(SE); 12099 Type *Ty = Expr->getType(); 12100 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12101 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12102 SE.getSignExtendExpr(Step, Ty), L, 12103 AR->getNoWrapFlags()); 12104 } 12105 return SE.getSignExtendExpr(Operand, Expr->getType()); 12106 } 12107 12108 private: 12109 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12110 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12111 SCEVUnionPredicate *Pred) 12112 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12113 12114 bool addOverflowAssumption(const SCEVPredicate *P) { 12115 if (!NewPreds) { 12116 // Check if we've already made this assumption. 12117 return Pred && Pred->implies(P); 12118 } 12119 NewPreds->insert(P); 12120 return true; 12121 } 12122 12123 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12124 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12125 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12126 return addOverflowAssumption(A); 12127 } 12128 12129 // If \p Expr represents a PHINode, we try to see if it can be represented 12130 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12131 // to add this predicate as a runtime overflow check, we return the AddRec. 12132 // If \p Expr does not meet these conditions (is not a PHI node, or we 12133 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12134 // return \p Expr. 12135 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12136 if (!isa<PHINode>(Expr->getValue())) 12137 return Expr; 12138 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12139 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12140 if (!PredicatedRewrite) 12141 return Expr; 12142 for (auto *P : PredicatedRewrite->second){ 12143 // Wrap predicates from outer loops are not supported. 12144 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12145 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12146 if (L != AR->getLoop()) 12147 return Expr; 12148 } 12149 if (!addOverflowAssumption(P)) 12150 return Expr; 12151 } 12152 return PredicatedRewrite->first; 12153 } 12154 12155 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12156 SCEVUnionPredicate *Pred; 12157 const Loop *L; 12158 }; 12159 12160 } // end anonymous namespace 12161 12162 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12163 SCEVUnionPredicate &Preds) { 12164 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12165 } 12166 12167 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12168 const SCEV *S, const Loop *L, 12169 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12170 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12171 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12172 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12173 12174 if (!AddRec) 12175 return nullptr; 12176 12177 // Since the transformation was successful, we can now transfer the SCEV 12178 // predicates. 12179 for (auto *P : TransformPreds) 12180 Preds.insert(P); 12181 12182 return AddRec; 12183 } 12184 12185 /// SCEV predicates 12186 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12187 SCEVPredicateKind Kind) 12188 : FastID(ID), Kind(Kind) {} 12189 12190 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12191 const SCEV *LHS, const SCEV *RHS) 12192 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12193 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12194 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12195 } 12196 12197 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12198 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12199 12200 if (!Op) 12201 return false; 12202 12203 return Op->LHS == LHS && Op->RHS == RHS; 12204 } 12205 12206 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12207 12208 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12209 12210 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12211 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12212 } 12213 12214 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12215 const SCEVAddRecExpr *AR, 12216 IncrementWrapFlags Flags) 12217 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12218 12219 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12220 12221 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12222 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12223 12224 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12225 } 12226 12227 bool SCEVWrapPredicate::isAlwaysTrue() const { 12228 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12229 IncrementWrapFlags IFlags = Flags; 12230 12231 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12232 IFlags = clearFlags(IFlags, IncrementNSSW); 12233 12234 return IFlags == IncrementAnyWrap; 12235 } 12236 12237 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12238 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12239 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12240 OS << "<nusw>"; 12241 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12242 OS << "<nssw>"; 12243 OS << "\n"; 12244 } 12245 12246 SCEVWrapPredicate::IncrementWrapFlags 12247 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12248 ScalarEvolution &SE) { 12249 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12250 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12251 12252 // We can safely transfer the NSW flag as NSSW. 12253 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12254 ImpliedFlags = IncrementNSSW; 12255 12256 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12257 // If the increment is positive, the SCEV NUW flag will also imply the 12258 // WrapPredicate NUSW flag. 12259 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12260 if (Step->getValue()->getValue().isNonNegative()) 12261 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12262 } 12263 12264 return ImpliedFlags; 12265 } 12266 12267 /// Union predicates don't get cached so create a dummy set ID for it. 12268 SCEVUnionPredicate::SCEVUnionPredicate() 12269 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12270 12271 bool SCEVUnionPredicate::isAlwaysTrue() const { 12272 return all_of(Preds, 12273 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12274 } 12275 12276 ArrayRef<const SCEVPredicate *> 12277 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12278 auto I = SCEVToPreds.find(Expr); 12279 if (I == SCEVToPreds.end()) 12280 return ArrayRef<const SCEVPredicate *>(); 12281 return I->second; 12282 } 12283 12284 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12285 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12286 return all_of(Set->Preds, 12287 [this](const SCEVPredicate *I) { return this->implies(I); }); 12288 12289 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12290 if (ScevPredsIt == SCEVToPreds.end()) 12291 return false; 12292 auto &SCEVPreds = ScevPredsIt->second; 12293 12294 return any_of(SCEVPreds, 12295 [N](const SCEVPredicate *I) { return I->implies(N); }); 12296 } 12297 12298 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12299 12300 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12301 for (auto Pred : Preds) 12302 Pred->print(OS, Depth); 12303 } 12304 12305 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12306 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12307 for (auto Pred : Set->Preds) 12308 add(Pred); 12309 return; 12310 } 12311 12312 if (implies(N)) 12313 return; 12314 12315 const SCEV *Key = N->getExpr(); 12316 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12317 " associated expression!"); 12318 12319 SCEVToPreds[Key].push_back(N); 12320 Preds.push_back(N); 12321 } 12322 12323 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12324 Loop &L) 12325 : SE(SE), L(L) {} 12326 12327 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12328 const SCEV *Expr = SE.getSCEV(V); 12329 RewriteEntry &Entry = RewriteMap[Expr]; 12330 12331 // If we already have an entry and the version matches, return it. 12332 if (Entry.second && Generation == Entry.first) 12333 return Entry.second; 12334 12335 // We found an entry but it's stale. Rewrite the stale entry 12336 // according to the current predicate. 12337 if (Entry.second) 12338 Expr = Entry.second; 12339 12340 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12341 Entry = {Generation, NewSCEV}; 12342 12343 return NewSCEV; 12344 } 12345 12346 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12347 if (!BackedgeCount) { 12348 SCEVUnionPredicate BackedgePred; 12349 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12350 addPredicate(BackedgePred); 12351 } 12352 return BackedgeCount; 12353 } 12354 12355 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12356 if (Preds.implies(&Pred)) 12357 return; 12358 Preds.add(&Pred); 12359 updateGeneration(); 12360 } 12361 12362 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12363 return Preds; 12364 } 12365 12366 void PredicatedScalarEvolution::updateGeneration() { 12367 // If the generation number wrapped recompute everything. 12368 if (++Generation == 0) { 12369 for (auto &II : RewriteMap) { 12370 const SCEV *Rewritten = II.second.second; 12371 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12372 } 12373 } 12374 } 12375 12376 void PredicatedScalarEvolution::setNoOverflow( 12377 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12378 const SCEV *Expr = getSCEV(V); 12379 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12380 12381 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12382 12383 // Clear the statically implied flags. 12384 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12385 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12386 12387 auto II = FlagsMap.insert({V, Flags}); 12388 if (!II.second) 12389 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12390 } 12391 12392 bool PredicatedScalarEvolution::hasNoOverflow( 12393 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12394 const SCEV *Expr = getSCEV(V); 12395 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12396 12397 Flags = SCEVWrapPredicate::clearFlags( 12398 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12399 12400 auto II = FlagsMap.find(V); 12401 12402 if (II != FlagsMap.end()) 12403 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12404 12405 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12406 } 12407 12408 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12409 const SCEV *Expr = this->getSCEV(V); 12410 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12411 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12412 12413 if (!New) 12414 return nullptr; 12415 12416 for (auto *P : NewPreds) 12417 Preds.add(P); 12418 12419 updateGeneration(); 12420 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12421 return New; 12422 } 12423 12424 PredicatedScalarEvolution::PredicatedScalarEvolution( 12425 const PredicatedScalarEvolution &Init) 12426 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12427 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12428 for (const auto &I : Init.FlagsMap) 12429 FlagsMap.insert(I); 12430 } 12431 12432 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12433 // For each block. 12434 for (auto *BB : L.getBlocks()) 12435 for (auto &I : *BB) { 12436 if (!SE.isSCEVable(I.getType())) 12437 continue; 12438 12439 auto *Expr = SE.getSCEV(&I); 12440 auto II = RewriteMap.find(Expr); 12441 12442 if (II == RewriteMap.end()) 12443 continue; 12444 12445 // Don't print things that are not interesting. 12446 if (II->second.second == Expr) 12447 continue; 12448 12449 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12450 OS.indent(Depth + 2) << *Expr << "\n"; 12451 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12452 } 12453 } 12454 12455 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12456 // arbitrary expressions. 12457 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12458 // 4, A / B becomes X / 8). 12459 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12460 const SCEV *&RHS) { 12461 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12462 if (Add == nullptr || Add->getNumOperands() != 2) 12463 return false; 12464 12465 const SCEV *A = Add->getOperand(1); 12466 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12467 12468 if (Mul == nullptr) 12469 return false; 12470 12471 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12472 // (SomeExpr + (-(SomeExpr / B) * B)). 12473 if (Expr == getURemExpr(A, B)) { 12474 LHS = A; 12475 RHS = B; 12476 return true; 12477 } 12478 return false; 12479 }; 12480 12481 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12482 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12483 return MatchURemWithDivisor(Mul->getOperand(1)) || 12484 MatchURemWithDivisor(Mul->getOperand(2)); 12485 12486 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12487 if (Mul->getNumOperands() == 2) 12488 return MatchURemWithDivisor(Mul->getOperand(1)) || 12489 MatchURemWithDivisor(Mul->getOperand(0)) || 12490 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12491 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12492 return false; 12493 } 12494