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/ScalarEvolution.h" 187 #include "llvm/Analysis/ScalarEvolutionExpander.h" 188 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 189 #include "llvm/IR/Function.h" 190 #include "llvm/IR/GlobalValue.h" 191 #include "llvm/IR/IntrinsicInst.h" 192 #include "llvm/IR/Module.h" 193 #include "llvm/IR/PatternMatch.h" 194 #include "llvm/Pass.h" 195 #include "llvm/Support/Debug.h" 196 #include "llvm/Transforms/Scalar.h" 197 #include "llvm/Transforms/Utils/Local.h" 198 #include "llvm/Transforms/Utils/LoopUtils.h" 199 200 #define DEBUG_TYPE "loop-predication" 201 202 STATISTIC(TotalConsidered, "Number of guards considered"); 203 STATISTIC(TotalWidened, "Number of checks widened"); 204 205 using namespace llvm; 206 207 static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation", 208 cl::Hidden, cl::init(true)); 209 210 static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop", 211 cl::Hidden, cl::init(true)); 212 213 static cl::opt<bool> 214 SkipProfitabilityChecks("loop-predication-skip-profitability-checks", 215 cl::Hidden, cl::init(false)); 216 217 // This is the scale factor for the latch probability. We use this during 218 // profitability analysis to find other exiting blocks that have a much higher 219 // probability of exiting the loop instead of loop exiting via latch. 220 // This value should be greater than 1 for a sane profitability check. 221 static cl::opt<float> LatchExitProbabilityScale( 222 "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0), 223 cl::desc("scale factor for the latch probability. Value should be greater " 224 "than 1. Lower values are ignored")); 225 226 static cl::opt<bool> PredicateWidenableBranchGuards( 227 "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden, 228 cl::desc("Whether or not we should predicate guards " 229 "expressed as widenable branches to deoptimize blocks"), 230 cl::init(true)); 231 232 namespace { 233 /// Represents an induction variable check: 234 /// icmp Pred, <induction variable>, <loop invariant limit> 235 struct LoopICmp { 236 ICmpInst::Predicate Pred; 237 const SCEVAddRecExpr *IV; 238 const SCEV *Limit; 239 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV, 240 const SCEV *Limit) 241 : Pred(Pred), IV(IV), Limit(Limit) {} 242 LoopICmp() {} 243 void dump() { 244 dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV 245 << ", Limit = " << *Limit << "\n"; 246 } 247 }; 248 249 class LoopPredication { 250 AliasAnalysis *AA; 251 ScalarEvolution *SE; 252 BranchProbabilityInfo *BPI; 253 254 Loop *L; 255 const DataLayout *DL; 256 BasicBlock *Preheader; 257 LoopICmp LatchCheck; 258 259 bool isSupportedStep(const SCEV* Step); 260 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) { 261 return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0), 262 ICI->getOperand(1)); 263 } 264 Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS, 265 Value *RHS); 266 267 Optional<LoopICmp> parseLoopLatchICmp(); 268 269 /// Return an insertion point suitable for inserting a safe to speculate 270 /// instruction whose only user will be 'User' which has operands 'Ops'. A 271 /// trivial result would be the at the User itself, but we try to return a 272 /// loop invariant location if possible. 273 Instruction *findInsertPt(Instruction *User, ArrayRef<Value*> Ops); 274 /// Same as above, *except* that this uses the SCEV definition of invariant 275 /// which is that an expression *can be made* invariant via SCEVExpander. 276 /// Thus, this version is only suitable for finding an insert point to be be 277 /// passed to SCEVExpander! 278 Instruction *findInsertPt(Instruction *User, ArrayRef<const SCEV*> Ops); 279 280 /// Return true if the value is known to produce a single fixed value across 281 /// all iterations on which it executes. Note that this does not imply 282 /// speculation safety. That must be established seperately. 283 bool isLoopInvariantValue(const SCEV* S); 284 285 Value *expandCheck(SCEVExpander &Expander, Instruction *Guard, 286 ICmpInst::Predicate Pred, const SCEV *LHS, 287 const SCEV *RHS); 288 289 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, 290 Instruction *Guard); 291 Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck, 292 LoopICmp RangeCheck, 293 SCEVExpander &Expander, 294 Instruction *Guard); 295 Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck, 296 LoopICmp RangeCheck, 297 SCEVExpander &Expander, 298 Instruction *Guard); 299 unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition, 300 SCEVExpander &Expander, Instruction *Guard); 301 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander); 302 bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander); 303 // If the loop always exits through another block in the loop, we should not 304 // predicate based on the latch check. For example, the latch check can be a 305 // very coarse grained check and there can be more fine grained exit checks 306 // within the loop. We identify such unprofitable loops through BPI. 307 bool isLoopProfitableToPredicate(); 308 309 // When the IV type is wider than the range operand type, we can still do loop 310 // predication, by generating SCEVs for the range and latch that are of the 311 // same type. We achieve this by generating a SCEV truncate expression for the 312 // latch IV. This is done iff truncation of the IV is a safe operation, 313 // without loss of information. 314 // Another way to achieve this is by generating a wider type SCEV for the 315 // range check operand, however, this needs a more involved check that 316 // operands do not overflow. This can lead to loss of information when the 317 // range operand is of the form: add i32 %offset, %iv. We need to prove that 318 // sext(x + y) is same as sext(x) + sext(y). 319 // This function returns true if we can safely represent the IV type in 320 // the RangeCheckType without loss of information. 321 bool isSafeToTruncateWideIVType(Type *RangeCheckType); 322 // Return the loopLatchCheck corresponding to the RangeCheckType if safe to do 323 // so. 324 Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType); 325 326 public: 327 LoopPredication(AliasAnalysis *AA, ScalarEvolution *SE, 328 BranchProbabilityInfo *BPI) 329 : AA(AA), SE(SE), BPI(BPI){}; 330 bool runOnLoop(Loop *L); 331 }; 332 333 class LoopPredicationLegacyPass : public LoopPass { 334 public: 335 static char ID; 336 LoopPredicationLegacyPass() : LoopPass(ID) { 337 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry()); 338 } 339 340 void getAnalysisUsage(AnalysisUsage &AU) const override { 341 AU.addRequired<BranchProbabilityInfoWrapperPass>(); 342 getLoopAnalysisUsage(AU); 343 } 344 345 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 346 if (skipLoop(L)) 347 return false; 348 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 349 BranchProbabilityInfo &BPI = 350 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); 351 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 352 LoopPredication LP(AA, SE, &BPI); 353 return LP.runOnLoop(L); 354 } 355 }; 356 357 char LoopPredicationLegacyPass::ID = 0; 358 } // end namespace llvm 359 360 INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", 361 "Loop predication", false, false) 362 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 363 INITIALIZE_PASS_DEPENDENCY(LoopPass) 364 INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication", 365 "Loop predication", false, false) 366 367 Pass *llvm::createLoopPredicationPass() { 368 return new LoopPredicationLegacyPass(); 369 } 370 371 PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM, 372 LoopStandardAnalysisResults &AR, 373 LPMUpdater &U) { 374 const auto &FAM = 375 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); 376 Function *F = L.getHeader()->getParent(); 377 auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F); 378 LoopPredication LP(&AR.AA, &AR.SE, BPI); 379 if (!LP.runOnLoop(&L)) 380 return PreservedAnalyses::all(); 381 382 return getLoopPassPreservedAnalyses(); 383 } 384 385 Optional<LoopICmp> 386 LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS, 387 Value *RHS) { 388 const SCEV *LHSS = SE->getSCEV(LHS); 389 if (isa<SCEVCouldNotCompute>(LHSS)) 390 return None; 391 const SCEV *RHSS = SE->getSCEV(RHS); 392 if (isa<SCEVCouldNotCompute>(RHSS)) 393 return None; 394 395 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV 396 if (SE->isLoopInvariant(LHSS, L)) { 397 std::swap(LHS, RHS); 398 std::swap(LHSS, RHSS); 399 Pred = ICmpInst::getSwappedPredicate(Pred); 400 } 401 402 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS); 403 if (!AR || AR->getLoop() != L) 404 return None; 405 406 return LoopICmp(Pred, AR, RHSS); 407 } 408 409 Value *LoopPredication::expandCheck(SCEVExpander &Expander, 410 Instruction *Guard, 411 ICmpInst::Predicate Pred, const SCEV *LHS, 412 const SCEV *RHS) { 413 Type *Ty = LHS->getType(); 414 assert(Ty == RHS->getType() && "expandCheck operands have different types?"); 415 416 if (SE->isLoopInvariant(LHS, L) && SE->isLoopInvariant(RHS, L)) { 417 IRBuilder<> Builder(Guard); 418 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS)) 419 return Builder.getTrue(); 420 if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred), 421 LHS, RHS)) 422 return Builder.getFalse(); 423 } 424 425 Value *LHSV = Expander.expandCodeFor(LHS, Ty, findInsertPt(Guard, {LHS})); 426 Value *RHSV = Expander.expandCodeFor(RHS, Ty, findInsertPt(Guard, {RHS})); 427 IRBuilder<> Builder(findInsertPt(Guard, {LHSV, RHSV})); 428 return Builder.CreateICmp(Pred, LHSV, RHSV); 429 } 430 431 Optional<LoopICmp> 432 LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) { 433 434 auto *LatchType = LatchCheck.IV->getType(); 435 if (RangeCheckType == LatchType) 436 return LatchCheck; 437 // For now, bail out if latch type is narrower than range type. 438 if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType)) 439 return None; 440 if (!isSafeToTruncateWideIVType(RangeCheckType)) 441 return None; 442 // We can now safely identify the truncated version of the IV and limit for 443 // RangeCheckType. 444 LoopICmp NewLatchCheck; 445 NewLatchCheck.Pred = LatchCheck.Pred; 446 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>( 447 SE->getTruncateExpr(LatchCheck.IV, RangeCheckType)); 448 if (!NewLatchCheck.IV) 449 return None; 450 NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType); 451 LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType 452 << "can be represented as range check type:" 453 << *RangeCheckType << "\n"); 454 LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n"); 455 LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n"); 456 return NewLatchCheck; 457 } 458 459 bool LoopPredication::isSupportedStep(const SCEV* Step) { 460 return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop); 461 } 462 463 Instruction *LoopPredication::findInsertPt(Instruction *Use, 464 ArrayRef<Value*> Ops) { 465 for (Value *Op : Ops) 466 if (!L->isLoopInvariant(Op)) 467 return Use; 468 return Preheader->getTerminator(); 469 } 470 471 Instruction *LoopPredication::findInsertPt(Instruction *Use, 472 ArrayRef<const SCEV*> Ops) { 473 // Subtlety: SCEV considers things to be invariant if the value produced is 474 // the same across iterations. This is not the same as being able to 475 // evaluate outside the loop, which is what we actually need here. 476 for (const SCEV *Op : Ops) 477 if (!SE->isLoopInvariant(Op, L) || 478 !isSafeToExpandAt(Op, Preheader->getTerminator(), *SE)) 479 return Use; 480 return Preheader->getTerminator(); 481 } 482 483 bool LoopPredication::isLoopInvariantValue(const SCEV* S) { 484 // Handling expressions which produce invariant results, but *haven't* yet 485 // been removed from the loop serves two important purposes. 486 // 1) Most importantly, it resolves a pass ordering cycle which would 487 // otherwise need us to iteration licm, loop-predication, and either 488 // loop-unswitch or loop-peeling to make progress on examples with lots of 489 // predicable range checks in a row. (Since, in the general case, we can't 490 // hoist the length checks until the dominating checks have been discharged 491 // as we can't prove doing so is safe.) 492 // 2) As a nice side effect, this exposes the value of peeling or unswitching 493 // much more obviously in the IR. Otherwise, the cost modeling for other 494 // transforms would end up needing to duplicate all of this logic to model a 495 // check which becomes predictable based on a modeled peel or unswitch. 496 // 497 // The cost of doing so in the worst case is an extra fill from the stack in 498 // the loop to materialize the loop invariant test value instead of checking 499 // against the original IV which is presumable in a register inside the loop. 500 // Such cases are presumably rare, and hint at missing oppurtunities for 501 // other passes. 502 503 if (SE->isLoopInvariant(S, L)) 504 // Note: This the SCEV variant, so the original Value* may be within the 505 // loop even though SCEV has proven it is loop invariant. 506 return true; 507 508 // Handle a particular important case which SCEV doesn't yet know about which 509 // shows up in range checks on arrays with immutable lengths. 510 // TODO: This should be sunk inside SCEV. 511 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) 512 if (const auto *LI = dyn_cast<LoadInst>(U->getValue())) 513 if (LI->isUnordered() && L->hasLoopInvariantOperands(LI)) 514 if (AA->pointsToConstantMemory(LI->getOperand(0)) || 515 LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr) 516 return true; 517 return false; 518 } 519 520 Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop( 521 LoopICmp LatchCheck, LoopICmp RangeCheck, 522 SCEVExpander &Expander, Instruction *Guard) { 523 auto *Ty = RangeCheck.IV->getType(); 524 // Generate the widened condition for the forward loop: 525 // guardStart u< guardLimit && 526 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart 527 // where <pred> depends on the latch condition predicate. See the file 528 // header comment for the reasoning. 529 // guardLimit - guardStart + latchStart - 1 530 const SCEV *GuardStart = RangeCheck.IV->getStart(); 531 const SCEV *GuardLimit = RangeCheck.Limit; 532 const SCEV *LatchStart = LatchCheck.IV->getStart(); 533 const SCEV *LatchLimit = LatchCheck.Limit; 534 // Subtlety: We need all the values to be *invariant* across all iterations, 535 // but we only need to check expansion safety for those which *aren't* 536 // already guaranteed to dominate the guard. 537 if (!isLoopInvariantValue(GuardStart) || 538 !isLoopInvariantValue(GuardLimit) || 539 !isLoopInvariantValue(LatchStart) || 540 !isLoopInvariantValue(LatchLimit)) { 541 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 542 return None; 543 } 544 if (!isSafeToExpandAt(LatchStart, Guard, *SE) || 545 !isSafeToExpandAt(LatchLimit, Guard, *SE)) { 546 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 547 return None; 548 } 549 550 // guardLimit - guardStart + latchStart - 1 551 const SCEV *RHS = 552 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart), 553 SE->getMinusSCEV(LatchStart, SE->getOne(Ty))); 554 auto LimitCheckPred = 555 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); 556 557 LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n"); 558 LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n"); 559 LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n"); 560 561 auto *LimitCheck = 562 expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, RHS); 563 auto *FirstIterationCheck = expandCheck(Expander, Guard, RangeCheck.Pred, 564 GuardStart, GuardLimit); 565 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck})); 566 return Builder.CreateAnd(FirstIterationCheck, LimitCheck); 567 } 568 569 Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop( 570 LoopICmp LatchCheck, LoopICmp RangeCheck, 571 SCEVExpander &Expander, Instruction *Guard) { 572 auto *Ty = RangeCheck.IV->getType(); 573 const SCEV *GuardStart = RangeCheck.IV->getStart(); 574 const SCEV *GuardLimit = RangeCheck.Limit; 575 const SCEV *LatchStart = LatchCheck.IV->getStart(); 576 const SCEV *LatchLimit = LatchCheck.Limit; 577 // Subtlety: We need all the values to be *invariant* across all iterations, 578 // but we only need to check expansion safety for those which *aren't* 579 // already guaranteed to dominate the guard. 580 if (!isLoopInvariantValue(GuardStart) || 581 !isLoopInvariantValue(GuardLimit) || 582 !isLoopInvariantValue(LatchStart) || 583 !isLoopInvariantValue(LatchLimit)) { 584 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 585 return None; 586 } 587 if (!isSafeToExpandAt(LatchStart, Guard, *SE) || 588 !isSafeToExpandAt(LatchLimit, Guard, *SE)) { 589 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 590 return None; 591 } 592 // The decrement of the latch check IV should be the same as the 593 // rangeCheckIV. 594 auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE); 595 if (RangeCheck.IV != PostDecLatchCheckIV) { 596 LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: " 597 << *PostDecLatchCheckIV 598 << " and RangeCheckIV: " << *RangeCheck.IV << "\n"); 599 return None; 600 } 601 602 // Generate the widened condition for CountDownLoop: 603 // guardStart u< guardLimit && 604 // latchLimit <pred> 1. 605 // See the header comment for reasoning of the checks. 606 auto LimitCheckPred = 607 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); 608 auto *FirstIterationCheck = expandCheck(Expander, Guard, 609 ICmpInst::ICMP_ULT, 610 GuardStart, GuardLimit); 611 auto *LimitCheck = expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, 612 SE->getOne(Ty)); 613 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck})); 614 return Builder.CreateAnd(FirstIterationCheck, LimitCheck); 615 } 616 617 static void normalizePredicate(ScalarEvolution *SE, Loop *L, 618 LoopICmp& RC) { 619 // LFTR canonicalizes checks to the ICMP_NE form instead of an ULT/SLT form. 620 // Normalize back to the ULT/SLT form for ease of handling. 621 if (RC.Pred == ICmpInst::ICMP_NE && 622 RC.IV->getStepRecurrence(*SE)->isOne() && 623 SE->isKnownPredicate(ICmpInst::ICMP_ULE, RC.IV->getStart(), RC.Limit)) 624 RC.Pred = ICmpInst::ICMP_ULT; 625 } 626 627 628 /// If ICI can be widened to a loop invariant condition emits the loop 629 /// invariant condition in the loop preheader and return it, otherwise 630 /// returns None. 631 Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, 632 SCEVExpander &Expander, 633 Instruction *Guard) { 634 LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n"); 635 LLVM_DEBUG(ICI->dump()); 636 637 // parseLoopStructure guarantees that the latch condition is: 638 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=. 639 // We are looking for the range checks of the form: 640 // i u< guardLimit 641 auto RangeCheck = parseLoopICmp(ICI); 642 if (!RangeCheck) { 643 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 644 return None; 645 } 646 LLVM_DEBUG(dbgs() << "Guard check:\n"); 647 LLVM_DEBUG(RangeCheck->dump()); 648 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) { 649 LLVM_DEBUG(dbgs() << "Unsupported range check predicate(" 650 << RangeCheck->Pred << ")!\n"); 651 return None; 652 } 653 auto *RangeCheckIV = RangeCheck->IV; 654 if (!RangeCheckIV->isAffine()) { 655 LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n"); 656 return None; 657 } 658 auto *Step = RangeCheckIV->getStepRecurrence(*SE); 659 // We cannot just compare with latch IV step because the latch and range IVs 660 // may have different types. 661 if (!isSupportedStep(Step)) { 662 LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n"); 663 return None; 664 } 665 auto *Ty = RangeCheckIV->getType(); 666 auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty); 667 if (!CurrLatchCheckOpt) { 668 LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check " 669 "corresponding to range type: " 670 << *Ty << "\n"); 671 return None; 672 } 673 674 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt; 675 // At this point, the range and latch step should have the same type, but need 676 // not have the same value (we support both 1 and -1 steps). 677 assert(Step->getType() == 678 CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() && 679 "Range and latch steps should be of same type!"); 680 if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) { 681 LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n"); 682 return None; 683 } 684 685 if (Step->isOne()) 686 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck, 687 Expander, Guard); 688 else { 689 assert(Step->isAllOnesValue() && "Step should be -1!"); 690 return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck, 691 Expander, Guard); 692 } 693 } 694 695 unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks, 696 Value *Condition, 697 SCEVExpander &Expander, 698 Instruction *Guard) { 699 unsigned NumWidened = 0; 700 // The guard condition is expected to be in form of: 701 // cond1 && cond2 && cond3 ... 702 // Iterate over subconditions looking for icmp conditions which can be 703 // widened across loop iterations. Widening these conditions remember the 704 // resulting list of subconditions in Checks vector. 705 SmallVector<Value *, 4> Worklist(1, Condition); 706 SmallPtrSet<Value *, 4> Visited; 707 Value *WideableCond = nullptr; 708 do { 709 Value *Condition = Worklist.pop_back_val(); 710 if (!Visited.insert(Condition).second) 711 continue; 712 713 Value *LHS, *RHS; 714 using namespace llvm::PatternMatch; 715 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) { 716 Worklist.push_back(LHS); 717 Worklist.push_back(RHS); 718 continue; 719 } 720 721 if (match(Condition, 722 m_Intrinsic<Intrinsic::experimental_widenable_condition>())) { 723 // Pick any, we don't care which 724 WideableCond = Condition; 725 continue; 726 } 727 728 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) { 729 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, 730 Guard)) { 731 Checks.push_back(NewRangeCheck.getValue()); 732 NumWidened++; 733 continue; 734 } 735 } 736 737 // Save the condition as is if we can't widen it 738 Checks.push_back(Condition); 739 } while (!Worklist.empty()); 740 // At the moment, our matching logic for wideable conditions implicitly 741 // assumes we preserve the form: (br (and Cond, WC())). FIXME 742 // Note that if there were multiple calls to wideable condition in the 743 // traversal, we only need to keep one, and which one is arbitrary. 744 if (WideableCond) 745 Checks.push_back(WideableCond); 746 return NumWidened; 747 } 748 749 bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard, 750 SCEVExpander &Expander) { 751 LLVM_DEBUG(dbgs() << "Processing guard:\n"); 752 LLVM_DEBUG(Guard->dump()); 753 754 TotalConsidered++; 755 SmallVector<Value *, 4> Checks; 756 unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander, 757 Guard); 758 if (NumWidened == 0) 759 return false; 760 761 TotalWidened += NumWidened; 762 763 // Emit the new guard condition 764 IRBuilder<> Builder(findInsertPt(Guard, Checks)); 765 Value *LastCheck = nullptr; 766 for (auto *Check : Checks) 767 if (!LastCheck) 768 LastCheck = Check; 769 else 770 LastCheck = Builder.CreateAnd(LastCheck, Check); 771 auto *OldCond = Guard->getOperand(0); 772 Guard->setOperand(0, LastCheck); 773 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 774 775 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 776 return true; 777 } 778 779 bool LoopPredication::widenWidenableBranchGuardConditions( 780 BranchInst *BI, SCEVExpander &Expander) { 781 assert(isGuardAsWidenableBranch(BI) && "Must be!"); 782 LLVM_DEBUG(dbgs() << "Processing guard:\n"); 783 LLVM_DEBUG(BI->dump()); 784 785 TotalConsidered++; 786 SmallVector<Value *, 4> Checks; 787 unsigned NumWidened = collectChecks(Checks, BI->getCondition(), 788 Expander, BI); 789 if (NumWidened == 0) 790 return false; 791 792 TotalWidened += NumWidened; 793 794 // Emit the new guard condition 795 IRBuilder<> Builder(findInsertPt(BI, Checks)); 796 Value *LastCheck = nullptr; 797 for (auto *Check : Checks) 798 if (!LastCheck) 799 LastCheck = Check; 800 else 801 LastCheck = Builder.CreateAnd(LastCheck, Check); 802 auto *OldCond = BI->getCondition(); 803 BI->setCondition(LastCheck); 804 assert(isGuardAsWidenableBranch(BI) && 805 "Stopped being a guard after transform?"); 806 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 807 808 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 809 return true; 810 } 811 812 Optional<LoopICmp> LoopPredication::parseLoopLatchICmp() { 813 using namespace PatternMatch; 814 815 BasicBlock *LoopLatch = L->getLoopLatch(); 816 if (!LoopLatch) { 817 LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n"); 818 return None; 819 } 820 821 ICmpInst::Predicate Pred; 822 Value *LHS, *RHS; 823 BasicBlock *TrueDest, *FalseDest; 824 825 if (!match(LoopLatch->getTerminator(), 826 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest, 827 FalseDest))) { 828 LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n"); 829 return None; 830 } 831 assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) && 832 "One of the latch's destinations must be the header"); 833 if (TrueDest != L->getHeader()) 834 Pred = ICmpInst::getInversePredicate(Pred); 835 836 auto Result = parseLoopICmp(Pred, LHS, RHS); 837 if (!Result) { 838 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 839 return None; 840 } 841 842 // Check affine first, so if it's not we don't try to compute the step 843 // recurrence. 844 if (!Result->IV->isAffine()) { 845 LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n"); 846 return None; 847 } 848 849 auto *Step = Result->IV->getStepRecurrence(*SE); 850 if (!isSupportedStep(Step)) { 851 LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n"); 852 return None; 853 } 854 855 auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) { 856 if (Step->isOne()) { 857 return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT && 858 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE; 859 } else { 860 assert(Step->isAllOnesValue() && "Step should be -1!"); 861 return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT && 862 Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE; 863 } 864 }; 865 866 normalizePredicate(SE, L, *Result); 867 if (IsUnsupportedPredicate(Step, Result->Pred)) { 868 LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred 869 << ")!\n"); 870 return None; 871 } 872 return Result; 873 } 874 875 // Returns true if its safe to truncate the IV to RangeCheckType. 876 bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) { 877 if (!EnableIVTruncation) 878 return false; 879 assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) > 880 DL->getTypeSizeInBits(RangeCheckType) && 881 "Expected latch check IV type to be larger than range check operand " 882 "type!"); 883 // The start and end values of the IV should be known. This is to guarantee 884 // that truncating the wide type will not lose information. 885 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit); 886 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart()); 887 if (!Limit || !Start) 888 return false; 889 // This check makes sure that the IV does not change sign during loop 890 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE, 891 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the 892 // IV wraps around, and the truncation of the IV would lose the range of 893 // iterations between 2^32 and 2^64. 894 bool Increasing; 895 if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing)) 896 return false; 897 // The active bits should be less than the bits in the RangeCheckType. This 898 // guarantees that truncating the latch check to RangeCheckType is a safe 899 // operation. 900 auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType); 901 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize && 902 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize; 903 } 904 905 bool LoopPredication::isLoopProfitableToPredicate() { 906 if (SkipProfitabilityChecks || !BPI) 907 return true; 908 909 SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 8> ExitEdges; 910 L->getExitEdges(ExitEdges); 911 // If there is only one exiting edge in the loop, it is always profitable to 912 // predicate the loop. 913 if (ExitEdges.size() == 1) 914 return true; 915 916 // Calculate the exiting probabilities of all exiting edges from the loop, 917 // starting with the LatchExitProbability. 918 // Heuristic for profitability: If any of the exiting blocks' probability of 919 // exiting the loop is larger than exiting through the latch block, it's not 920 // profitable to predicate the loop. 921 auto *LatchBlock = L->getLoopLatch(); 922 assert(LatchBlock && "Should have a single latch at this point!"); 923 auto *LatchTerm = LatchBlock->getTerminator(); 924 assert(LatchTerm->getNumSuccessors() == 2 && 925 "expected to be an exiting block with 2 succs!"); 926 unsigned LatchBrExitIdx = 927 LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0; 928 BranchProbability LatchExitProbability = 929 BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx); 930 931 // Protect against degenerate inputs provided by the user. Providing a value 932 // less than one, can invert the definition of profitable loop predication. 933 float ScaleFactor = LatchExitProbabilityScale; 934 if (ScaleFactor < 1) { 935 LLVM_DEBUG( 936 dbgs() 937 << "Ignored user setting for loop-predication-latch-probability-scale: " 938 << LatchExitProbabilityScale << "\n"); 939 LLVM_DEBUG(dbgs() << "The value is set to 1.0\n"); 940 ScaleFactor = 1.0; 941 } 942 const auto LatchProbabilityThreshold = 943 LatchExitProbability * ScaleFactor; 944 945 for (const auto &ExitEdge : ExitEdges) { 946 BranchProbability ExitingBlockProbability = 947 BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second); 948 // Some exiting edge has higher probability than the latch exiting edge. 949 // No longer profitable to predicate. 950 if (ExitingBlockProbability > LatchProbabilityThreshold) 951 return false; 952 } 953 // Using BPI, we have concluded that the most probable way to exit from the 954 // loop is through the latch (or there's no profile information and all 955 // exits are equally likely). 956 return true; 957 } 958 959 bool LoopPredication::runOnLoop(Loop *Loop) { 960 L = Loop; 961 962 LLVM_DEBUG(dbgs() << "Analyzing "); 963 LLVM_DEBUG(L->dump()); 964 965 Module *M = L->getHeader()->getModule(); 966 967 // There is nothing to do if the module doesn't use guards 968 auto *GuardDecl = 969 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard)); 970 bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty(); 971 auto *WCDecl = M->getFunction( 972 Intrinsic::getName(Intrinsic::experimental_widenable_condition)); 973 bool HasWidenableConditions = 974 PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty(); 975 if (!HasIntrinsicGuards && !HasWidenableConditions) 976 return false; 977 978 DL = &M->getDataLayout(); 979 980 Preheader = L->getLoopPreheader(); 981 if (!Preheader) 982 return false; 983 984 auto LatchCheckOpt = parseLoopLatchICmp(); 985 if (!LatchCheckOpt) 986 return false; 987 LatchCheck = *LatchCheckOpt; 988 989 LLVM_DEBUG(dbgs() << "Latch check:\n"); 990 LLVM_DEBUG(LatchCheck.dump()); 991 992 if (!isLoopProfitableToPredicate()) { 993 LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n"); 994 return false; 995 } 996 // Collect all the guards into a vector and process later, so as not 997 // to invalidate the instruction iterator. 998 SmallVector<IntrinsicInst *, 4> Guards; 999 SmallVector<BranchInst *, 4> GuardsAsWidenableBranches; 1000 for (const auto BB : L->blocks()) { 1001 for (auto &I : *BB) 1002 if (isGuard(&I)) 1003 Guards.push_back(cast<IntrinsicInst>(&I)); 1004 if (PredicateWidenableBranchGuards && 1005 isGuardAsWidenableBranch(BB->getTerminator())) 1006 GuardsAsWidenableBranches.push_back( 1007 cast<BranchInst>(BB->getTerminator())); 1008 } 1009 1010 if (Guards.empty() && GuardsAsWidenableBranches.empty()) 1011 return false; 1012 1013 SCEVExpander Expander(*SE, *DL, "loop-predication"); 1014 1015 bool Changed = false; 1016 for (auto *Guard : Guards) 1017 Changed |= widenGuardConditions(Guard, Expander); 1018 for (auto *Guard : GuardsAsWidenableBranches) 1019 Changed |= widenWidenableBranchGuardConditions(Guard, Expander); 1020 1021 return Changed; 1022 } 1023