1 //===-- LoopPredication.cpp - Guard based loop predication pass -----------===// 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 // The LoopPredication pass tries to convert loop variant range checks to loop 10 // invariant by widening checks across loop iterations. For example, it will 11 // convert 12 // 13 // for (i = 0; i < n; i++) { 14 // guard(i < len); 15 // ... 16 // } 17 // 18 // to 19 // 20 // for (i = 0; i < n; i++) { 21 // guard(n - 1 < len); 22 // ... 23 // } 24 // 25 // After this transformation the condition of the guard is loop invariant, so 26 // loop-unswitch can later unswitch the loop by this condition which basically 27 // predicates the loop by the widened condition: 28 // 29 // if (n - 1 < len) 30 // for (i = 0; i < n; i++) { 31 // ... 32 // } 33 // else 34 // deoptimize 35 // 36 // It's tempting to rely on SCEV here, but it has proven to be problematic. 37 // Generally the facts SCEV provides about the increment step of add 38 // recurrences are true if the backedge of the loop is taken, which implicitly 39 // assumes that the guard doesn't fail. Using these facts to optimize the 40 // guard results in a circular logic where the guard is optimized under the 41 // assumption that it never fails. 42 // 43 // For example, in the loop below the induction variable will be marked as nuw 44 // basing on the guard. Basing on nuw the guard predicate will be considered 45 // monotonic. Given a monotonic condition it's tempting to replace the induction 46 // variable in the condition with its value on the last iteration. But this 47 // transformation is not correct, e.g. e = 4, b = 5 breaks the loop. 48 // 49 // for (int i = b; i != e; i++) 50 // guard(i u< len) 51 // 52 // One of the ways to reason about this problem is to use an inductive proof 53 // approach. Given the loop: 54 // 55 // if (B(0)) { 56 // do { 57 // I = PHI(0, I.INC) 58 // I.INC = I + Step 59 // guard(G(I)); 60 // } while (B(I)); 61 // } 62 // 63 // where B(x) and G(x) are predicates that map integers to booleans, we want a 64 // loop invariant expression M such the following program has the same semantics 65 // as the above: 66 // 67 // if (B(0)) { 68 // do { 69 // I = PHI(0, I.INC) 70 // I.INC = I + Step 71 // guard(G(0) && M); 72 // } while (B(I)); 73 // } 74 // 75 // One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step) 76 // 77 // Informal proof that the transformation above is correct: 78 // 79 // By the definition of guards we can rewrite the guard condition to: 80 // G(I) && G(0) && M 81 // 82 // Let's prove that for each iteration of the loop: 83 // G(0) && M => G(I) 84 // And the condition above can be simplified to G(Start) && M. 85 // 86 // Induction base. 87 // G(0) && M => G(0) 88 // 89 // Induction step. Assuming G(0) && M => G(I) on the subsequent 90 // iteration: 91 // 92 // B(I) is true because it's the backedge condition. 93 // G(I) is true because the backedge is guarded by this condition. 94 // 95 // So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step). 96 // 97 // Note that we can use anything stronger than M, i.e. any condition which 98 // implies M. 99 // 100 // When S = 1 (i.e. forward iterating loop), the transformation is supported 101 // when: 102 // * The loop has a single latch with the condition of the form: 103 // B(X) = latchStart + X <pred> latchLimit, 104 // where <pred> is u<, u<=, s<, or s<=. 105 // * The guard condition is of the form 106 // G(X) = guardStart + X u< guardLimit 107 // 108 // For the ult latch comparison case M is: 109 // forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit => 110 // guardStart + X + 1 u< guardLimit 111 // 112 // The only way the antecedent can be true and the consequent can be false is 113 // if 114 // X == guardLimit - 1 - guardStart 115 // (and guardLimit is non-zero, but we won't use this latter fact). 116 // If X == guardLimit - 1 - guardStart then the second half of the antecedent is 117 // latchStart + guardLimit - 1 - guardStart u< latchLimit 118 // and its negation is 119 // latchStart + guardLimit - 1 - guardStart u>= latchLimit 120 // 121 // In other words, if 122 // latchLimit u<= latchStart + guardLimit - 1 - guardStart 123 // then: 124 // (the ranges below are written in ConstantRange notation, where [A, B) is the 125 // set for (I = A; I != B; I++ /*maywrap*/) yield(I);) 126 // 127 // forall X . guardStart + X u< guardLimit && 128 // latchStart + X u< latchLimit => 129 // guardStart + X + 1 u< guardLimit 130 // == forall X . guardStart + X u< guardLimit && 131 // latchStart + X u< latchStart + guardLimit - 1 - guardStart => 132 // guardStart + X + 1 u< guardLimit 133 // == forall X . (guardStart + X) in [0, guardLimit) && 134 // (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) => 135 // (guardStart + X + 1) in [0, guardLimit) 136 // == forall X . X in [-guardStart, guardLimit - guardStart) && 137 // X in [-latchStart, guardLimit - 1 - guardStart) => 138 // X in [-guardStart - 1, guardLimit - guardStart - 1) 139 // == true 140 // 141 // So the widened condition is: 142 // guardStart u< guardLimit && 143 // latchStart + guardLimit - 1 - guardStart u>= latchLimit 144 // Similarly for ule condition the widened condition is: 145 // guardStart u< guardLimit && 146 // latchStart + guardLimit - 1 - guardStart u> latchLimit 147 // For slt condition the widened condition is: 148 // guardStart u< guardLimit && 149 // latchStart + guardLimit - 1 - guardStart s>= latchLimit 150 // For sle condition the widened condition is: 151 // guardStart u< guardLimit && 152 // latchStart + guardLimit - 1 - guardStart s> latchLimit 153 // 154 // When S = -1 (i.e. reverse iterating loop), the transformation is supported 155 // when: 156 // * The loop has a single latch with the condition of the form: 157 // B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=. 158 // * The guard condition is of the form 159 // G(X) = X - 1 u< guardLimit 160 // 161 // For the ugt latch comparison case M is: 162 // forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit 163 // 164 // The only way the antecedent can be true and the consequent can be false is if 165 // X == 1. 166 // If X == 1 then the second half of the antecedent is 167 // 1 u> latchLimit, and its negation is latchLimit u>= 1. 168 // 169 // So the widened condition is: 170 // guardStart u< guardLimit && latchLimit u>= 1. 171 // Similarly for sgt condition the widened condition is: 172 // guardStart u< guardLimit && latchLimit s>= 1. 173 // For uge condition the widened condition is: 174 // guardStart u< guardLimit && latchLimit u> 1. 175 // For sge condition the widened condition is: 176 // guardStart u< guardLimit && latchLimit s> 1. 177 //===----------------------------------------------------------------------===// 178 179 #include "llvm/Transforms/Scalar/LoopPredication.h" 180 #include "llvm/ADT/Statistic.h" 181 #include "llvm/Analysis/AliasAnalysis.h" 182 #include "llvm/Analysis/BranchProbabilityInfo.h" 183 #include "llvm/Analysis/GuardUtils.h" 184 #include "llvm/Analysis/LoopInfo.h" 185 #include "llvm/Analysis/LoopPass.h" 186 #include "llvm/Analysis/MemorySSA.h" 187 #include "llvm/Analysis/MemorySSAUpdater.h" 188 #include "llvm/Analysis/ScalarEvolution.h" 189 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 190 #include "llvm/IR/Function.h" 191 #include "llvm/IR/IntrinsicInst.h" 192 #include "llvm/IR/Module.h" 193 #include "llvm/IR/PatternMatch.h" 194 #include "llvm/InitializePasses.h" 195 #include "llvm/Pass.h" 196 #include "llvm/Support/CommandLine.h" 197 #include "llvm/Support/Debug.h" 198 #include "llvm/Transforms/Scalar.h" 199 #include "llvm/Transforms/Utils/GuardUtils.h" 200 #include "llvm/Transforms/Utils/Local.h" 201 #include "llvm/Transforms/Utils/LoopUtils.h" 202 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 203 204 #define DEBUG_TYPE "loop-predication" 205 206 STATISTIC(TotalConsidered, "Number of guards considered"); 207 STATISTIC(TotalWidened, "Number of checks widened"); 208 209 using namespace llvm; 210 211 static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation", 212 cl::Hidden, cl::init(true)); 213 214 static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop", 215 cl::Hidden, cl::init(true)); 216 217 static cl::opt<bool> 218 SkipProfitabilityChecks("loop-predication-skip-profitability-checks", 219 cl::Hidden, cl::init(false)); 220 221 // This is the scale factor for the latch probability. We use this during 222 // profitability analysis to find other exiting blocks that have a much higher 223 // probability of exiting the loop instead of loop exiting via latch. 224 // This value should be greater than 1 for a sane profitability check. 225 static cl::opt<float> LatchExitProbabilityScale( 226 "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0), 227 cl::desc("scale factor for the latch probability. Value should be greater " 228 "than 1. Lower values are ignored")); 229 230 static cl::opt<bool> PredicateWidenableBranchGuards( 231 "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden, 232 cl::desc("Whether or not we should predicate guards " 233 "expressed as widenable branches to deoptimize blocks"), 234 cl::init(true)); 235 236 static cl::opt<bool> InsertAssumesOfPredicatedGuardsConditions( 237 "loop-predication-insert-assumes-of-predicated-guards-conditions", 238 cl::Hidden, 239 cl::desc("Whether or not we should insert assumes of conditions of " 240 "predicated guards"), 241 cl::init(true)); 242 243 namespace { 244 /// Represents an induction variable check: 245 /// icmp Pred, <induction variable>, <loop invariant limit> 246 struct LoopICmp { 247 ICmpInst::Predicate Pred; 248 const SCEVAddRecExpr *IV; 249 const SCEV *Limit; 250 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV, 251 const SCEV *Limit) 252 : Pred(Pred), IV(IV), Limit(Limit) {} 253 LoopICmp() = default; 254 void dump() { 255 dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV 256 << ", Limit = " << *Limit << "\n"; 257 } 258 }; 259 260 class LoopPredication { 261 AliasAnalysis *AA; 262 DominatorTree *DT; 263 ScalarEvolution *SE; 264 LoopInfo *LI; 265 MemorySSAUpdater *MSSAU; 266 267 Loop *L; 268 const DataLayout *DL; 269 BasicBlock *Preheader; 270 LoopICmp LatchCheck; 271 272 bool isSupportedStep(const SCEV* Step); 273 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI); 274 Optional<LoopICmp> parseLoopLatchICmp(); 275 276 /// Return an insertion point suitable for inserting a safe to speculate 277 /// instruction whose only user will be 'User' which has operands 'Ops'. A 278 /// trivial result would be the at the User itself, but we try to return a 279 /// loop invariant location if possible. 280 Instruction *findInsertPt(Instruction *User, ArrayRef<Value*> Ops); 281 /// Same as above, *except* that this uses the SCEV definition of invariant 282 /// which is that an expression *can be made* invariant via SCEVExpander. 283 /// Thus, this version is only suitable for finding an insert point to be be 284 /// passed to SCEVExpander! 285 Instruction *findInsertPt(const SCEVExpander &Expander, Instruction *User, 286 ArrayRef<const SCEV *> Ops); 287 288 /// Return true if the value is known to produce a single fixed value across 289 /// all iterations on which it executes. Note that this does not imply 290 /// speculation safety. That must be established separately. 291 bool isLoopInvariantValue(const SCEV* S); 292 293 Value *expandCheck(SCEVExpander &Expander, Instruction *Guard, 294 ICmpInst::Predicate Pred, const SCEV *LHS, 295 const SCEV *RHS); 296 297 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, 298 Instruction *Guard); 299 Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck, 300 LoopICmp RangeCheck, 301 SCEVExpander &Expander, 302 Instruction *Guard); 303 Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck, 304 LoopICmp RangeCheck, 305 SCEVExpander &Expander, 306 Instruction *Guard); 307 unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition, 308 SCEVExpander &Expander, Instruction *Guard); 309 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander); 310 bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander); 311 // If the loop always exits through another block in the loop, we should not 312 // predicate based on the latch check. For example, the latch check can be a 313 // very coarse grained check and there can be more fine grained exit checks 314 // within the loop. 315 bool isLoopProfitableToPredicate(); 316 317 bool predicateLoopExits(Loop *L, SCEVExpander &Rewriter); 318 319 public: 320 LoopPredication(AliasAnalysis *AA, DominatorTree *DT, ScalarEvolution *SE, 321 LoopInfo *LI, MemorySSAUpdater *MSSAU) 322 : AA(AA), DT(DT), SE(SE), LI(LI), MSSAU(MSSAU){}; 323 bool runOnLoop(Loop *L); 324 }; 325 326 class LoopPredicationLegacyPass : public LoopPass { 327 public: 328 static char ID; 329 LoopPredicationLegacyPass() : LoopPass(ID) { 330 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry()); 331 } 332 333 void getAnalysisUsage(AnalysisUsage &AU) const override { 334 AU.addRequired<BranchProbabilityInfoWrapperPass>(); 335 getLoopAnalysisUsage(AU); 336 AU.addPreserved<MemorySSAWrapperPass>(); 337 } 338 339 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 340 if (skipLoop(L)) 341 return false; 342 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 343 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 344 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 345 auto *MSSAWP = getAnalysisIfAvailable<MemorySSAWrapperPass>(); 346 std::unique_ptr<MemorySSAUpdater> MSSAU; 347 if (MSSAWP) 348 MSSAU = std::make_unique<MemorySSAUpdater>(&MSSAWP->getMSSA()); 349 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 350 LoopPredication LP(AA, DT, SE, LI, MSSAU ? MSSAU.get() : nullptr); 351 return LP.runOnLoop(L); 352 } 353 }; 354 355 char LoopPredicationLegacyPass::ID = 0; 356 } // end namespace 357 358 INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", 359 "Loop predication", false, false) 360 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 361 INITIALIZE_PASS_DEPENDENCY(LoopPass) 362 INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication", 363 "Loop predication", false, false) 364 365 Pass *llvm::createLoopPredicationPass() { 366 return new LoopPredicationLegacyPass(); 367 } 368 369 PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM, 370 LoopStandardAnalysisResults &AR, 371 LPMUpdater &U) { 372 std::unique_ptr<MemorySSAUpdater> MSSAU; 373 if (AR.MSSA) 374 MSSAU = std::make_unique<MemorySSAUpdater>(AR.MSSA); 375 LoopPredication LP(&AR.AA, &AR.DT, &AR.SE, &AR.LI, 376 MSSAU ? MSSAU.get() : nullptr); 377 if (!LP.runOnLoop(&L)) 378 return PreservedAnalyses::all(); 379 380 auto PA = getLoopPassPreservedAnalyses(); 381 if (AR.MSSA) 382 PA.preserve<MemorySSAAnalysis>(); 383 return PA; 384 } 385 386 Optional<LoopICmp> 387 LoopPredication::parseLoopICmp(ICmpInst *ICI) { 388 auto Pred = ICI->getPredicate(); 389 auto *LHS = ICI->getOperand(0); 390 auto *RHS = ICI->getOperand(1); 391 392 const SCEV *LHSS = SE->getSCEV(LHS); 393 if (isa<SCEVCouldNotCompute>(LHSS)) 394 return None; 395 const SCEV *RHSS = SE->getSCEV(RHS); 396 if (isa<SCEVCouldNotCompute>(RHSS)) 397 return None; 398 399 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV 400 if (SE->isLoopInvariant(LHSS, L)) { 401 std::swap(LHS, RHS); 402 std::swap(LHSS, RHSS); 403 Pred = ICmpInst::getSwappedPredicate(Pred); 404 } 405 406 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS); 407 if (!AR || AR->getLoop() != L) 408 return None; 409 410 return LoopICmp(Pred, AR, RHSS); 411 } 412 413 Value *LoopPredication::expandCheck(SCEVExpander &Expander, 414 Instruction *Guard, 415 ICmpInst::Predicate Pred, const SCEV *LHS, 416 const SCEV *RHS) { 417 Type *Ty = LHS->getType(); 418 assert(Ty == RHS->getType() && "expandCheck operands have different types?"); 419 420 if (SE->isLoopInvariant(LHS, L) && SE->isLoopInvariant(RHS, L)) { 421 IRBuilder<> Builder(Guard); 422 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS)) 423 return Builder.getTrue(); 424 if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred), 425 LHS, RHS)) 426 return Builder.getFalse(); 427 } 428 429 Value *LHSV = 430 Expander.expandCodeFor(LHS, Ty, findInsertPt(Expander, Guard, {LHS})); 431 Value *RHSV = 432 Expander.expandCodeFor(RHS, Ty, findInsertPt(Expander, Guard, {RHS})); 433 IRBuilder<> Builder(findInsertPt(Guard, {LHSV, RHSV})); 434 return Builder.CreateICmp(Pred, LHSV, RHSV); 435 } 436 437 // Returns true if its safe to truncate the IV to RangeCheckType. 438 // When the IV type is wider than the range operand type, we can still do loop 439 // predication, by generating SCEVs for the range and latch that are of the 440 // same type. We achieve this by generating a SCEV truncate expression for the 441 // latch IV. This is done iff truncation of the IV is a safe operation, 442 // without loss of information. 443 // Another way to achieve this is by generating a wider type SCEV for the 444 // range check operand, however, this needs a more involved check that 445 // operands do not overflow. This can lead to loss of information when the 446 // range operand is of the form: add i32 %offset, %iv. We need to prove that 447 // sext(x + y) is same as sext(x) + sext(y). 448 // This function returns true if we can safely represent the IV type in 449 // the RangeCheckType without loss of information. 450 static bool isSafeToTruncateWideIVType(const DataLayout &DL, 451 ScalarEvolution &SE, 452 const LoopICmp LatchCheck, 453 Type *RangeCheckType) { 454 if (!EnableIVTruncation) 455 return false; 456 assert(DL.getTypeSizeInBits(LatchCheck.IV->getType()).getFixedSize() > 457 DL.getTypeSizeInBits(RangeCheckType).getFixedSize() && 458 "Expected latch check IV type to be larger than range check operand " 459 "type!"); 460 // The start and end values of the IV should be known. This is to guarantee 461 // that truncating the wide type will not lose information. 462 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit); 463 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart()); 464 if (!Limit || !Start) 465 return false; 466 // This check makes sure that the IV does not change sign during loop 467 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE, 468 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the 469 // IV wraps around, and the truncation of the IV would lose the range of 470 // iterations between 2^32 and 2^64. 471 if (!SE.getMonotonicPredicateType(LatchCheck.IV, LatchCheck.Pred)) 472 return false; 473 // The active bits should be less than the bits in the RangeCheckType. This 474 // guarantees that truncating the latch check to RangeCheckType is a safe 475 // operation. 476 auto RangeCheckTypeBitSize = 477 DL.getTypeSizeInBits(RangeCheckType).getFixedSize(); 478 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize && 479 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize; 480 } 481 482 483 // Return an LoopICmp describing a latch check equivlent to LatchCheck but with 484 // the requested type if safe to do so. May involve the use of a new IV. 485 static Optional<LoopICmp> generateLoopLatchCheck(const DataLayout &DL, 486 ScalarEvolution &SE, 487 const LoopICmp LatchCheck, 488 Type *RangeCheckType) { 489 490 auto *LatchType = LatchCheck.IV->getType(); 491 if (RangeCheckType == LatchType) 492 return LatchCheck; 493 // For now, bail out if latch type is narrower than range type. 494 if (DL.getTypeSizeInBits(LatchType).getFixedSize() < 495 DL.getTypeSizeInBits(RangeCheckType).getFixedSize()) 496 return None; 497 if (!isSafeToTruncateWideIVType(DL, SE, LatchCheck, RangeCheckType)) 498 return None; 499 // We can now safely identify the truncated version of the IV and limit for 500 // RangeCheckType. 501 LoopICmp NewLatchCheck; 502 NewLatchCheck.Pred = LatchCheck.Pred; 503 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>( 504 SE.getTruncateExpr(LatchCheck.IV, RangeCheckType)); 505 if (!NewLatchCheck.IV) 506 return None; 507 NewLatchCheck.Limit = SE.getTruncateExpr(LatchCheck.Limit, RangeCheckType); 508 LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType 509 << "can be represented as range check type:" 510 << *RangeCheckType << "\n"); 511 LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n"); 512 LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n"); 513 return NewLatchCheck; 514 } 515 516 bool LoopPredication::isSupportedStep(const SCEV* Step) { 517 return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop); 518 } 519 520 Instruction *LoopPredication::findInsertPt(Instruction *Use, 521 ArrayRef<Value*> Ops) { 522 for (Value *Op : Ops) 523 if (!L->isLoopInvariant(Op)) 524 return Use; 525 return Preheader->getTerminator(); 526 } 527 528 Instruction *LoopPredication::findInsertPt(const SCEVExpander &Expander, 529 Instruction *Use, 530 ArrayRef<const SCEV *> Ops) { 531 // Subtlety: SCEV considers things to be invariant if the value produced is 532 // the same across iterations. This is not the same as being able to 533 // evaluate outside the loop, which is what we actually need here. 534 for (const SCEV *Op : Ops) 535 if (!SE->isLoopInvariant(Op, L) || 536 !Expander.isSafeToExpandAt(Op, Preheader->getTerminator())) 537 return Use; 538 return Preheader->getTerminator(); 539 } 540 541 bool LoopPredication::isLoopInvariantValue(const SCEV* S) { 542 // Handling expressions which produce invariant results, but *haven't* yet 543 // been removed from the loop serves two important purposes. 544 // 1) Most importantly, it resolves a pass ordering cycle which would 545 // otherwise need us to iteration licm, loop-predication, and either 546 // loop-unswitch or loop-peeling to make progress on examples with lots of 547 // predicable range checks in a row. (Since, in the general case, we can't 548 // hoist the length checks until the dominating checks have been discharged 549 // as we can't prove doing so is safe.) 550 // 2) As a nice side effect, this exposes the value of peeling or unswitching 551 // much more obviously in the IR. Otherwise, the cost modeling for other 552 // transforms would end up needing to duplicate all of this logic to model a 553 // check which becomes predictable based on a modeled peel or unswitch. 554 // 555 // The cost of doing so in the worst case is an extra fill from the stack in 556 // the loop to materialize the loop invariant test value instead of checking 557 // against the original IV which is presumable in a register inside the loop. 558 // Such cases are presumably rare, and hint at missing oppurtunities for 559 // other passes. 560 561 if (SE->isLoopInvariant(S, L)) 562 // Note: This the SCEV variant, so the original Value* may be within the 563 // loop even though SCEV has proven it is loop invariant. 564 return true; 565 566 // Handle a particular important case which SCEV doesn't yet know about which 567 // shows up in range checks on arrays with immutable lengths. 568 // TODO: This should be sunk inside SCEV. 569 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) 570 if (const auto *LI = dyn_cast<LoadInst>(U->getValue())) 571 if (LI->isUnordered() && L->hasLoopInvariantOperands(LI)) 572 if (!isModSet(AA->getModRefInfoMask(LI->getOperand(0))) || 573 LI->hasMetadata(LLVMContext::MD_invariant_load)) 574 return true; 575 return false; 576 } 577 578 Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop( 579 LoopICmp LatchCheck, LoopICmp RangeCheck, 580 SCEVExpander &Expander, Instruction *Guard) { 581 auto *Ty = RangeCheck.IV->getType(); 582 // Generate the widened condition for the forward loop: 583 // guardStart u< guardLimit && 584 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart 585 // where <pred> depends on the latch condition predicate. See the file 586 // header comment for the reasoning. 587 // guardLimit - guardStart + latchStart - 1 588 const SCEV *GuardStart = RangeCheck.IV->getStart(); 589 const SCEV *GuardLimit = RangeCheck.Limit; 590 const SCEV *LatchStart = LatchCheck.IV->getStart(); 591 const SCEV *LatchLimit = LatchCheck.Limit; 592 // Subtlety: We need all the values to be *invariant* across all iterations, 593 // but we only need to check expansion safety for those which *aren't* 594 // already guaranteed to dominate the guard. 595 if (!isLoopInvariantValue(GuardStart) || 596 !isLoopInvariantValue(GuardLimit) || 597 !isLoopInvariantValue(LatchStart) || 598 !isLoopInvariantValue(LatchLimit)) { 599 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 600 return None; 601 } 602 if (!Expander.isSafeToExpandAt(LatchStart, Guard) || 603 !Expander.isSafeToExpandAt(LatchLimit, Guard)) { 604 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 605 return None; 606 } 607 608 // guardLimit - guardStart + latchStart - 1 609 const SCEV *RHS = 610 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart), 611 SE->getMinusSCEV(LatchStart, SE->getOne(Ty))); 612 auto LimitCheckPred = 613 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); 614 615 LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n"); 616 LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n"); 617 LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n"); 618 619 auto *LimitCheck = 620 expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, RHS); 621 auto *FirstIterationCheck = expandCheck(Expander, Guard, RangeCheck.Pred, 622 GuardStart, GuardLimit); 623 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck})); 624 return Builder.CreateAnd(FirstIterationCheck, LimitCheck); 625 } 626 627 Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop( 628 LoopICmp LatchCheck, LoopICmp RangeCheck, 629 SCEVExpander &Expander, Instruction *Guard) { 630 auto *Ty = RangeCheck.IV->getType(); 631 const SCEV *GuardStart = RangeCheck.IV->getStart(); 632 const SCEV *GuardLimit = RangeCheck.Limit; 633 const SCEV *LatchStart = LatchCheck.IV->getStart(); 634 const SCEV *LatchLimit = LatchCheck.Limit; 635 // Subtlety: We need all the values to be *invariant* across all iterations, 636 // but we only need to check expansion safety for those which *aren't* 637 // already guaranteed to dominate the guard. 638 if (!isLoopInvariantValue(GuardStart) || 639 !isLoopInvariantValue(GuardLimit) || 640 !isLoopInvariantValue(LatchStart) || 641 !isLoopInvariantValue(LatchLimit)) { 642 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 643 return None; 644 } 645 if (!Expander.isSafeToExpandAt(LatchStart, Guard) || 646 !Expander.isSafeToExpandAt(LatchLimit, Guard)) { 647 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 648 return None; 649 } 650 // The decrement of the latch check IV should be the same as the 651 // rangeCheckIV. 652 auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE); 653 if (RangeCheck.IV != PostDecLatchCheckIV) { 654 LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: " 655 << *PostDecLatchCheckIV 656 << " and RangeCheckIV: " << *RangeCheck.IV << "\n"); 657 return None; 658 } 659 660 // Generate the widened condition for CountDownLoop: 661 // guardStart u< guardLimit && 662 // latchLimit <pred> 1. 663 // See the header comment for reasoning of the checks. 664 auto LimitCheckPred = 665 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); 666 auto *FirstIterationCheck = expandCheck(Expander, Guard, 667 ICmpInst::ICMP_ULT, 668 GuardStart, GuardLimit); 669 auto *LimitCheck = expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, 670 SE->getOne(Ty)); 671 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck})); 672 return Builder.CreateAnd(FirstIterationCheck, LimitCheck); 673 } 674 675 static void normalizePredicate(ScalarEvolution *SE, Loop *L, 676 LoopICmp& RC) { 677 // LFTR canonicalizes checks to the ICMP_NE/EQ form; normalize back to the 678 // ULT/UGE form for ease of handling by our caller. 679 if (ICmpInst::isEquality(RC.Pred) && 680 RC.IV->getStepRecurrence(*SE)->isOne() && 681 SE->isKnownPredicate(ICmpInst::ICMP_ULE, RC.IV->getStart(), RC.Limit)) 682 RC.Pred = RC.Pred == ICmpInst::ICMP_NE ? 683 ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE; 684 } 685 686 687 /// If ICI can be widened to a loop invariant condition emits the loop 688 /// invariant condition in the loop preheader and return it, otherwise 689 /// returns None. 690 Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, 691 SCEVExpander &Expander, 692 Instruction *Guard) { 693 LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n"); 694 LLVM_DEBUG(ICI->dump()); 695 696 // parseLoopStructure guarantees that the latch condition is: 697 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=. 698 // We are looking for the range checks of the form: 699 // i u< guardLimit 700 auto RangeCheck = parseLoopICmp(ICI); 701 if (!RangeCheck) { 702 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 703 return None; 704 } 705 LLVM_DEBUG(dbgs() << "Guard check:\n"); 706 LLVM_DEBUG(RangeCheck->dump()); 707 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) { 708 LLVM_DEBUG(dbgs() << "Unsupported range check predicate(" 709 << RangeCheck->Pred << ")!\n"); 710 return None; 711 } 712 auto *RangeCheckIV = RangeCheck->IV; 713 if (!RangeCheckIV->isAffine()) { 714 LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n"); 715 return None; 716 } 717 auto *Step = RangeCheckIV->getStepRecurrence(*SE); 718 // We cannot just compare with latch IV step because the latch and range IVs 719 // may have different types. 720 if (!isSupportedStep(Step)) { 721 LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n"); 722 return None; 723 } 724 auto *Ty = RangeCheckIV->getType(); 725 auto CurrLatchCheckOpt = generateLoopLatchCheck(*DL, *SE, LatchCheck, Ty); 726 if (!CurrLatchCheckOpt) { 727 LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check " 728 "corresponding to range type: " 729 << *Ty << "\n"); 730 return None; 731 } 732 733 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt; 734 // At this point, the range and latch step should have the same type, but need 735 // not have the same value (we support both 1 and -1 steps). 736 assert(Step->getType() == 737 CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() && 738 "Range and latch steps should be of same type!"); 739 if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) { 740 LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n"); 741 return None; 742 } 743 744 if (Step->isOne()) 745 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck, 746 Expander, Guard); 747 else { 748 assert(Step->isAllOnesValue() && "Step should be -1!"); 749 return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck, 750 Expander, Guard); 751 } 752 } 753 754 unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks, 755 Value *Condition, 756 SCEVExpander &Expander, 757 Instruction *Guard) { 758 unsigned NumWidened = 0; 759 // The guard condition is expected to be in form of: 760 // cond1 && cond2 && cond3 ... 761 // Iterate over subconditions looking for icmp conditions which can be 762 // widened across loop iterations. Widening these conditions remember the 763 // resulting list of subconditions in Checks vector. 764 SmallVector<Value *, 4> Worklist(1, Condition); 765 SmallPtrSet<Value *, 4> Visited; 766 Visited.insert(Condition); 767 Value *WideableCond = nullptr; 768 do { 769 Value *Condition = Worklist.pop_back_val(); 770 Value *LHS, *RHS; 771 using namespace llvm::PatternMatch; 772 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) { 773 if (Visited.insert(LHS).second) 774 Worklist.push_back(LHS); 775 if (Visited.insert(RHS).second) 776 Worklist.push_back(RHS); 777 continue; 778 } 779 780 if (match(Condition, 781 m_Intrinsic<Intrinsic::experimental_widenable_condition>())) { 782 // Pick any, we don't care which 783 WideableCond = Condition; 784 continue; 785 } 786 787 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) { 788 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, 789 Guard)) { 790 Checks.push_back(*NewRangeCheck); 791 NumWidened++; 792 continue; 793 } 794 } 795 796 // Save the condition as is if we can't widen it 797 Checks.push_back(Condition); 798 } while (!Worklist.empty()); 799 // At the moment, our matching logic for wideable conditions implicitly 800 // assumes we preserve the form: (br (and Cond, WC())). FIXME 801 // Note that if there were multiple calls to wideable condition in the 802 // traversal, we only need to keep one, and which one is arbitrary. 803 if (WideableCond) 804 Checks.push_back(WideableCond); 805 return NumWidened; 806 } 807 808 bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard, 809 SCEVExpander &Expander) { 810 LLVM_DEBUG(dbgs() << "Processing guard:\n"); 811 LLVM_DEBUG(Guard->dump()); 812 813 TotalConsidered++; 814 SmallVector<Value *, 4> Checks; 815 unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander, 816 Guard); 817 if (NumWidened == 0) 818 return false; 819 820 TotalWidened += NumWidened; 821 822 // Emit the new guard condition 823 IRBuilder<> Builder(findInsertPt(Guard, Checks)); 824 Value *AllChecks = Builder.CreateAnd(Checks); 825 auto *OldCond = Guard->getOperand(0); 826 Guard->setOperand(0, AllChecks); 827 if (InsertAssumesOfPredicatedGuardsConditions) { 828 Builder.SetInsertPoint(&*++BasicBlock::iterator(Guard)); 829 Builder.CreateAssumption(OldCond); 830 } 831 RecursivelyDeleteTriviallyDeadInstructions(OldCond, nullptr /* TLI */, MSSAU); 832 833 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 834 return true; 835 } 836 837 bool LoopPredication::widenWidenableBranchGuardConditions( 838 BranchInst *BI, SCEVExpander &Expander) { 839 assert(isGuardAsWidenableBranch(BI) && "Must be!"); 840 LLVM_DEBUG(dbgs() << "Processing guard:\n"); 841 LLVM_DEBUG(BI->dump()); 842 843 Value *Cond, *WC; 844 BasicBlock *IfTrueBB, *IfFalseBB; 845 bool Parsed = parseWidenableBranch(BI, Cond, WC, IfTrueBB, IfFalseBB); 846 assert(Parsed && "Must be able to parse widenable branch"); 847 (void)Parsed; 848 849 TotalConsidered++; 850 SmallVector<Value *, 4> Checks; 851 unsigned NumWidened = collectChecks(Checks, BI->getCondition(), 852 Expander, BI); 853 if (NumWidened == 0) 854 return false; 855 856 TotalWidened += NumWidened; 857 858 // Emit the new guard condition 859 IRBuilder<> Builder(findInsertPt(BI, Checks)); 860 Value *AllChecks = Builder.CreateAnd(Checks); 861 auto *OldCond = BI->getCondition(); 862 BI->setCondition(AllChecks); 863 if (InsertAssumesOfPredicatedGuardsConditions) { 864 Builder.SetInsertPoint(IfTrueBB, IfTrueBB->getFirstInsertionPt()); 865 Builder.CreateAssumption(Cond); 866 } 867 RecursivelyDeleteTriviallyDeadInstructions(OldCond, nullptr /* TLI */, MSSAU); 868 assert(isGuardAsWidenableBranch(BI) && 869 "Stopped being a guard after transform?"); 870 871 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 872 return true; 873 } 874 875 Optional<LoopICmp> LoopPredication::parseLoopLatchICmp() { 876 using namespace PatternMatch; 877 878 BasicBlock *LoopLatch = L->getLoopLatch(); 879 if (!LoopLatch) { 880 LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n"); 881 return None; 882 } 883 884 auto *BI = dyn_cast<BranchInst>(LoopLatch->getTerminator()); 885 if (!BI || !BI->isConditional()) { 886 LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n"); 887 return None; 888 } 889 BasicBlock *TrueDest = BI->getSuccessor(0); 890 assert( 891 (TrueDest == L->getHeader() || BI->getSuccessor(1) == L->getHeader()) && 892 "One of the latch's destinations must be the header"); 893 894 auto *ICI = dyn_cast<ICmpInst>(BI->getCondition()); 895 if (!ICI) { 896 LLVM_DEBUG(dbgs() << "Failed to match the latch condition!\n"); 897 return None; 898 } 899 auto Result = parseLoopICmp(ICI); 900 if (!Result) { 901 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 902 return None; 903 } 904 905 if (TrueDest != L->getHeader()) 906 Result->Pred = ICmpInst::getInversePredicate(Result->Pred); 907 908 // Check affine first, so if it's not we don't try to compute the step 909 // recurrence. 910 if (!Result->IV->isAffine()) { 911 LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n"); 912 return None; 913 } 914 915 auto *Step = Result->IV->getStepRecurrence(*SE); 916 if (!isSupportedStep(Step)) { 917 LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n"); 918 return None; 919 } 920 921 auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) { 922 if (Step->isOne()) { 923 return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT && 924 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE; 925 } else { 926 assert(Step->isAllOnesValue() && "Step should be -1!"); 927 return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT && 928 Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE; 929 } 930 }; 931 932 normalizePredicate(SE, L, *Result); 933 if (IsUnsupportedPredicate(Step, Result->Pred)) { 934 LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred 935 << ")!\n"); 936 return None; 937 } 938 939 return Result; 940 } 941 942 943 bool LoopPredication::isLoopProfitableToPredicate() { 944 if (SkipProfitabilityChecks) 945 return true; 946 947 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 8> ExitEdges; 948 L->getExitEdges(ExitEdges); 949 // If there is only one exiting edge in the loop, it is always profitable to 950 // predicate the loop. 951 if (ExitEdges.size() == 1) 952 return true; 953 954 // Calculate the exiting probabilities of all exiting edges from the loop, 955 // starting with the LatchExitProbability. 956 // Heuristic for profitability: If any of the exiting blocks' probability of 957 // exiting the loop is larger than exiting through the latch block, it's not 958 // profitable to predicate the loop. 959 auto *LatchBlock = L->getLoopLatch(); 960 assert(LatchBlock && "Should have a single latch at this point!"); 961 auto *LatchTerm = LatchBlock->getTerminator(); 962 assert(LatchTerm->getNumSuccessors() == 2 && 963 "expected to be an exiting block with 2 succs!"); 964 unsigned LatchBrExitIdx = 965 LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0; 966 // We compute branch probabilities without BPI. We do not rely on BPI since 967 // Loop predication is usually run in an LPM and BPI is only preserved 968 // lossily within loop pass managers, while BPI has an inherent notion of 969 // being complete for an entire function. 970 971 // If the latch exits into a deoptimize or an unreachable block, do not 972 // predicate on that latch check. 973 auto *LatchExitBlock = LatchTerm->getSuccessor(LatchBrExitIdx); 974 if (isa<UnreachableInst>(LatchTerm) || 975 LatchExitBlock->getTerminatingDeoptimizeCall()) 976 return false; 977 978 auto IsValidProfileData = [](MDNode *ProfileData, const Instruction *Term) { 979 if (!ProfileData || !ProfileData->getOperand(0)) 980 return false; 981 if (MDString *MDS = dyn_cast<MDString>(ProfileData->getOperand(0))) 982 if (!MDS->getString().equals("branch_weights")) 983 return false; 984 if (ProfileData->getNumOperands() != 1 + Term->getNumSuccessors()) 985 return false; 986 return true; 987 }; 988 MDNode *LatchProfileData = LatchTerm->getMetadata(LLVMContext::MD_prof); 989 // Latch terminator has no valid profile data, so nothing to check 990 // profitability on. 991 if (!IsValidProfileData(LatchProfileData, LatchTerm)) 992 return true; 993 994 auto ComputeBranchProbability = 995 [&](const BasicBlock *ExitingBlock, 996 const BasicBlock *ExitBlock) -> BranchProbability { 997 auto *Term = ExitingBlock->getTerminator(); 998 MDNode *ProfileData = Term->getMetadata(LLVMContext::MD_prof); 999 unsigned NumSucc = Term->getNumSuccessors(); 1000 if (IsValidProfileData(ProfileData, Term)) { 1001 uint64_t Numerator = 0, Denominator = 0, ProfVal = 0; 1002 for (unsigned i = 0; i < NumSucc; i++) { 1003 ConstantInt *CI = 1004 mdconst::extract<ConstantInt>(ProfileData->getOperand(i + 1)); 1005 ProfVal = CI->getValue().getZExtValue(); 1006 if (Term->getSuccessor(i) == ExitBlock) 1007 Numerator += ProfVal; 1008 Denominator += ProfVal; 1009 } 1010 return BranchProbability::getBranchProbability(Numerator, Denominator); 1011 } else { 1012 assert(LatchBlock != ExitingBlock && 1013 "Latch term should always have profile data!"); 1014 // No profile data, so we choose the weight as 1/num_of_succ(Src) 1015 return BranchProbability::getBranchProbability(1, NumSucc); 1016 } 1017 }; 1018 1019 BranchProbability LatchExitProbability = 1020 ComputeBranchProbability(LatchBlock, LatchExitBlock); 1021 1022 // Protect against degenerate inputs provided by the user. Providing a value 1023 // less than one, can invert the definition of profitable loop predication. 1024 float ScaleFactor = LatchExitProbabilityScale; 1025 if (ScaleFactor < 1) { 1026 LLVM_DEBUG( 1027 dbgs() 1028 << "Ignored user setting for loop-predication-latch-probability-scale: " 1029 << LatchExitProbabilityScale << "\n"); 1030 LLVM_DEBUG(dbgs() << "The value is set to 1.0\n"); 1031 ScaleFactor = 1.0; 1032 } 1033 const auto LatchProbabilityThreshold = LatchExitProbability * ScaleFactor; 1034 1035 for (const auto &ExitEdge : ExitEdges) { 1036 BranchProbability ExitingBlockProbability = 1037 ComputeBranchProbability(ExitEdge.first, ExitEdge.second); 1038 // Some exiting edge has higher probability than the latch exiting edge. 1039 // No longer profitable to predicate. 1040 if (ExitingBlockProbability > LatchProbabilityThreshold) 1041 return false; 1042 } 1043 1044 // We have concluded that the most probable way to exit from the 1045 // loop is through the latch (or there's no profile information and all 1046 // exits are equally likely). 1047 return true; 1048 } 1049 1050 /// If we can (cheaply) find a widenable branch which controls entry into the 1051 /// loop, return it. 1052 static BranchInst *FindWidenableTerminatorAboveLoop(Loop *L, LoopInfo &LI) { 1053 // Walk back through any unconditional executed blocks and see if we can find 1054 // a widenable condition which seems to control execution of this loop. Note 1055 // that we predict that maythrow calls are likely untaken and thus that it's 1056 // profitable to widen a branch before a maythrow call with a condition 1057 // afterwards even though that may cause the slow path to run in a case where 1058 // it wouldn't have otherwise. 1059 BasicBlock *BB = L->getLoopPreheader(); 1060 if (!BB) 1061 return nullptr; 1062 do { 1063 if (BasicBlock *Pred = BB->getSinglePredecessor()) 1064 if (BB == Pred->getSingleSuccessor()) { 1065 BB = Pred; 1066 continue; 1067 } 1068 break; 1069 } while (true); 1070 1071 if (BasicBlock *Pred = BB->getSinglePredecessor()) { 1072 auto *Term = Pred->getTerminator(); 1073 1074 Value *Cond, *WC; 1075 BasicBlock *IfTrueBB, *IfFalseBB; 1076 if (parseWidenableBranch(Term, Cond, WC, IfTrueBB, IfFalseBB) && 1077 IfTrueBB == BB) 1078 return cast<BranchInst>(Term); 1079 } 1080 return nullptr; 1081 } 1082 1083 /// Return the minimum of all analyzeable exit counts. This is an upper bound 1084 /// on the actual exit count. If there are not at least two analyzeable exits, 1085 /// returns SCEVCouldNotCompute. 1086 static const SCEV *getMinAnalyzeableBackedgeTakenCount(ScalarEvolution &SE, 1087 DominatorTree &DT, 1088 Loop *L) { 1089 SmallVector<BasicBlock *, 16> ExitingBlocks; 1090 L->getExitingBlocks(ExitingBlocks); 1091 1092 SmallVector<const SCEV *, 4> ExitCounts; 1093 for (BasicBlock *ExitingBB : ExitingBlocks) { 1094 const SCEV *ExitCount = SE.getExitCount(L, ExitingBB); 1095 if (isa<SCEVCouldNotCompute>(ExitCount)) 1096 continue; 1097 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 1098 "We should only have known counts for exiting blocks that " 1099 "dominate latch!"); 1100 ExitCounts.push_back(ExitCount); 1101 } 1102 if (ExitCounts.size() < 2) 1103 return SE.getCouldNotCompute(); 1104 return SE.getUMinFromMismatchedTypes(ExitCounts); 1105 } 1106 1107 /// This implements an analogous, but entirely distinct transform from the main 1108 /// loop predication transform. This one is phrased in terms of using a 1109 /// widenable branch *outside* the loop to allow us to simplify loop exits in a 1110 /// following loop. This is close in spirit to the IndVarSimplify transform 1111 /// of the same name, but is materially different widening loosens legality 1112 /// sharply. 1113 bool LoopPredication::predicateLoopExits(Loop *L, SCEVExpander &Rewriter) { 1114 // The transformation performed here aims to widen a widenable condition 1115 // above the loop such that all analyzeable exit leading to deopt are dead. 1116 // It assumes that the latch is the dominant exit for profitability and that 1117 // exits branching to deoptimizing blocks are rarely taken. It relies on the 1118 // semantics of widenable expressions for legality. (i.e. being able to fall 1119 // down the widenable path spuriously allows us to ignore exit order, 1120 // unanalyzeable exits, side effects, exceptional exits, and other challenges 1121 // which restrict the applicability of the non-WC based version of this 1122 // transform in IndVarSimplify.) 1123 // 1124 // NOTE ON POISON/UNDEF - We're hoisting an expression above guards which may 1125 // imply flags on the expression being hoisted and inserting new uses (flags 1126 // are only correct for current uses). The result is that we may be 1127 // inserting a branch on the value which can be either poison or undef. In 1128 // this case, the branch can legally go either way; we just need to avoid 1129 // introducing UB. This is achieved through the use of the freeze 1130 // instruction. 1131 1132 SmallVector<BasicBlock *, 16> ExitingBlocks; 1133 L->getExitingBlocks(ExitingBlocks); 1134 1135 if (ExitingBlocks.empty()) 1136 return false; // Nothing to do. 1137 1138 auto *Latch = L->getLoopLatch(); 1139 if (!Latch) 1140 return false; 1141 1142 auto *WidenableBR = FindWidenableTerminatorAboveLoop(L, *LI); 1143 if (!WidenableBR) 1144 return false; 1145 1146 const SCEV *LatchEC = SE->getExitCount(L, Latch); 1147 if (isa<SCEVCouldNotCompute>(LatchEC)) 1148 return false; // profitability - want hot exit in analyzeable set 1149 1150 // At this point, we have found an analyzeable latch, and a widenable 1151 // condition above the loop. If we have a widenable exit within the loop 1152 // (for which we can't compute exit counts), drop the ability to further 1153 // widen so that we gain ability to analyze it's exit count and perform this 1154 // transform. TODO: It'd be nice to know for sure the exit became 1155 // analyzeable after dropping widenability. 1156 bool ChangedLoop = false; 1157 1158 for (auto *ExitingBB : ExitingBlocks) { 1159 if (LI->getLoopFor(ExitingBB) != L) 1160 continue; 1161 1162 auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator()); 1163 if (!BI) 1164 continue; 1165 1166 Use *Cond, *WC; 1167 BasicBlock *IfTrueBB, *IfFalseBB; 1168 if (parseWidenableBranch(BI, Cond, WC, IfTrueBB, IfFalseBB) && 1169 L->contains(IfTrueBB)) { 1170 WC->set(ConstantInt::getTrue(IfTrueBB->getContext())); 1171 ChangedLoop = true; 1172 } 1173 } 1174 if (ChangedLoop) 1175 SE->forgetLoop(L); 1176 1177 // The use of umin(all analyzeable exits) instead of latch is subtle, but 1178 // important for profitability. We may have a loop which hasn't been fully 1179 // canonicalized just yet. If the exit we chose to widen is provably never 1180 // taken, we want the widened form to *also* be provably never taken. We 1181 // can't guarantee this as a current unanalyzeable exit may later become 1182 // analyzeable, but we can at least avoid the obvious cases. 1183 const SCEV *MinEC = getMinAnalyzeableBackedgeTakenCount(*SE, *DT, L); 1184 if (isa<SCEVCouldNotCompute>(MinEC) || MinEC->getType()->isPointerTy() || 1185 !SE->isLoopInvariant(MinEC, L) || 1186 !Rewriter.isSafeToExpandAt(MinEC, WidenableBR)) 1187 return ChangedLoop; 1188 1189 // Subtlety: We need to avoid inserting additional uses of the WC. We know 1190 // that it can only have one transitive use at the moment, and thus moving 1191 // that use to just before the branch and inserting code before it and then 1192 // modifying the operand is legal. 1193 auto *IP = cast<Instruction>(WidenableBR->getCondition()); 1194 // Here we unconditionally modify the IR, so after this point we should return 1195 // only `true`! 1196 IP->moveBefore(WidenableBR); 1197 if (MSSAU) 1198 if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(IP)) 1199 MSSAU->moveToPlace(MUD, WidenableBR->getParent(), 1200 MemorySSA::BeforeTerminator); 1201 Rewriter.setInsertPoint(IP); 1202 IRBuilder<> B(IP); 1203 1204 bool InvalidateLoop = false; 1205 Value *MinECV = nullptr; // lazily generated if needed 1206 for (BasicBlock *ExitingBB : ExitingBlocks) { 1207 // If our exiting block exits multiple loops, we can only rewrite the 1208 // innermost one. Otherwise, we're changing how many times the innermost 1209 // loop runs before it exits. 1210 if (LI->getLoopFor(ExitingBB) != L) 1211 continue; 1212 1213 // Can't rewrite non-branch yet. 1214 auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator()); 1215 if (!BI) 1216 continue; 1217 1218 // If already constant, nothing to do. 1219 if (isa<Constant>(BI->getCondition())) 1220 continue; 1221 1222 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB); 1223 if (isa<SCEVCouldNotCompute>(ExitCount) || 1224 ExitCount->getType()->isPointerTy() || 1225 !Rewriter.isSafeToExpandAt(ExitCount, WidenableBR)) 1226 continue; 1227 1228 const bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB)); 1229 BasicBlock *ExitBB = BI->getSuccessor(ExitIfTrue ? 0 : 1); 1230 if (!ExitBB->getPostdominatingDeoptimizeCall()) 1231 continue; 1232 1233 /// Here we can be fairly sure that executing this exit will most likely 1234 /// lead to executing llvm.experimental.deoptimize. 1235 /// This is a profitability heuristic, not a legality constraint. 1236 1237 // If we found a widenable exit condition, do two things: 1238 // 1) fold the widened exit test into the widenable condition 1239 // 2) fold the branch to untaken - avoids infinite looping 1240 1241 Value *ECV = Rewriter.expandCodeFor(ExitCount); 1242 if (!MinECV) 1243 MinECV = Rewriter.expandCodeFor(MinEC); 1244 Value *RHS = MinECV; 1245 if (ECV->getType() != RHS->getType()) { 1246 Type *WiderTy = SE->getWiderType(ECV->getType(), RHS->getType()); 1247 ECV = B.CreateZExt(ECV, WiderTy); 1248 RHS = B.CreateZExt(RHS, WiderTy); 1249 } 1250 assert(!Latch || DT->dominates(ExitingBB, Latch)); 1251 Value *NewCond = B.CreateICmp(ICmpInst::ICMP_UGT, ECV, RHS); 1252 // Freeze poison or undef to an arbitrary bit pattern to ensure we can 1253 // branch without introducing UB. See NOTE ON POISON/UNDEF above for 1254 // context. 1255 NewCond = B.CreateFreeze(NewCond); 1256 1257 widenWidenableBranch(WidenableBR, NewCond); 1258 1259 Value *OldCond = BI->getCondition(); 1260 BI->setCondition(ConstantInt::get(OldCond->getType(), !ExitIfTrue)); 1261 InvalidateLoop = true; 1262 } 1263 1264 if (InvalidateLoop) 1265 // We just mutated a bunch of loop exits changing there exit counts 1266 // widely. We need to force recomputation of the exit counts given these 1267 // changes. Note that all of the inserted exits are never taken, and 1268 // should be removed next time the CFG is modified. 1269 SE->forgetLoop(L); 1270 1271 // Always return `true` since we have moved the WidenableBR's condition. 1272 return true; 1273 } 1274 1275 bool LoopPredication::runOnLoop(Loop *Loop) { 1276 L = Loop; 1277 1278 LLVM_DEBUG(dbgs() << "Analyzing "); 1279 LLVM_DEBUG(L->dump()); 1280 1281 Module *M = L->getHeader()->getModule(); 1282 1283 // There is nothing to do if the module doesn't use guards 1284 auto *GuardDecl = 1285 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard)); 1286 bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty(); 1287 auto *WCDecl = M->getFunction( 1288 Intrinsic::getName(Intrinsic::experimental_widenable_condition)); 1289 bool HasWidenableConditions = 1290 PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty(); 1291 if (!HasIntrinsicGuards && !HasWidenableConditions) 1292 return false; 1293 1294 DL = &M->getDataLayout(); 1295 1296 Preheader = L->getLoopPreheader(); 1297 if (!Preheader) 1298 return false; 1299 1300 auto LatchCheckOpt = parseLoopLatchICmp(); 1301 if (!LatchCheckOpt) 1302 return false; 1303 LatchCheck = *LatchCheckOpt; 1304 1305 LLVM_DEBUG(dbgs() << "Latch check:\n"); 1306 LLVM_DEBUG(LatchCheck.dump()); 1307 1308 if (!isLoopProfitableToPredicate()) { 1309 LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n"); 1310 return false; 1311 } 1312 // Collect all the guards into a vector and process later, so as not 1313 // to invalidate the instruction iterator. 1314 SmallVector<IntrinsicInst *, 4> Guards; 1315 SmallVector<BranchInst *, 4> GuardsAsWidenableBranches; 1316 for (const auto BB : L->blocks()) { 1317 for (auto &I : *BB) 1318 if (isGuard(&I)) 1319 Guards.push_back(cast<IntrinsicInst>(&I)); 1320 if (PredicateWidenableBranchGuards && 1321 isGuardAsWidenableBranch(BB->getTerminator())) 1322 GuardsAsWidenableBranches.push_back( 1323 cast<BranchInst>(BB->getTerminator())); 1324 } 1325 1326 SCEVExpander Expander(*SE, *DL, "loop-predication"); 1327 bool Changed = false; 1328 for (auto *Guard : Guards) 1329 Changed |= widenGuardConditions(Guard, Expander); 1330 for (auto *Guard : GuardsAsWidenableBranches) 1331 Changed |= widenWidenableBranchGuardConditions(Guard, Expander); 1332 Changed |= predicateLoopExits(L, Expander); 1333 1334 if (MSSAU && VerifyMemorySSA) 1335 MSSAU->getMemorySSA()->verifyMemorySSA(); 1336 return Changed; 1337 } 1338