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/BranchProbabilityInfo.h" 182 #include "llvm/Analysis/GuardUtils.h" 183 #include "llvm/Analysis/LoopInfo.h" 184 #include "llvm/Analysis/LoopPass.h" 185 #include "llvm/Analysis/ScalarEvolution.h" 186 #include "llvm/Analysis/ScalarEvolutionExpander.h" 187 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 188 #include "llvm/IR/Function.h" 189 #include "llvm/IR/GlobalValue.h" 190 #include "llvm/IR/IntrinsicInst.h" 191 #include "llvm/IR/Module.h" 192 #include "llvm/IR/PatternMatch.h" 193 #include "llvm/Pass.h" 194 #include "llvm/Support/Debug.h" 195 #include "llvm/Transforms/Scalar.h" 196 #include "llvm/Transforms/Utils/LoopUtils.h" 197 198 #define DEBUG_TYPE "loop-predication" 199 200 STATISTIC(TotalConsidered, "Number of guards considered"); 201 STATISTIC(TotalWidened, "Number of checks widened"); 202 203 using namespace llvm; 204 205 static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation", 206 cl::Hidden, cl::init(true)); 207 208 static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop", 209 cl::Hidden, cl::init(true)); 210 211 static cl::opt<bool> 212 SkipProfitabilityChecks("loop-predication-skip-profitability-checks", 213 cl::Hidden, cl::init(false)); 214 215 // This is the scale factor for the latch probability. We use this during 216 // profitability analysis to find other exiting blocks that have a much higher 217 // probability of exiting the loop instead of loop exiting via latch. 218 // This value should be greater than 1 for a sane profitability check. 219 static cl::opt<float> LatchExitProbabilityScale( 220 "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0), 221 cl::desc("scale factor for the latch probability. Value should be greater " 222 "than 1. Lower values are ignored")); 223 224 static cl::opt<bool> PredicateWidenableBranchGuards( 225 "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden, 226 cl::desc("Whether or not we should predicate guards " 227 "expressed as widenable branches to deoptimize blocks"), 228 cl::init(true)); 229 230 namespace { 231 class LoopPredication { 232 /// Represents an induction variable check: 233 /// icmp Pred, <induction variable>, <loop invariant limit> 234 struct LoopICmp { 235 ICmpInst::Predicate Pred; 236 const SCEVAddRecExpr *IV; 237 const SCEV *Limit; 238 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV, 239 const SCEV *Limit) 240 : Pred(Pred), IV(IV), Limit(Limit) {} 241 LoopICmp() {} 242 void dump() { 243 dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV 244 << ", Limit = " << *Limit << "\n"; 245 } 246 }; 247 248 ScalarEvolution *SE; 249 BranchProbabilityInfo *BPI; 250 251 Loop *L; 252 const DataLayout *DL; 253 BasicBlock *Preheader; 254 LoopICmp LatchCheck; 255 256 bool isSupportedStep(const SCEV* Step); 257 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) { 258 return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0), 259 ICI->getOperand(1)); 260 } 261 Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS, 262 Value *RHS); 263 264 Optional<LoopICmp> parseLoopLatchICmp(); 265 266 bool CanExpand(const SCEV* S); 267 Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder, 268 ICmpInst::Predicate Pred, const SCEV *LHS, 269 const SCEV *RHS); 270 271 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, 272 IRBuilder<> &Builder); 273 Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck, 274 LoopICmp RangeCheck, 275 SCEVExpander &Expander, 276 IRBuilder<> &Builder); 277 Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck, 278 LoopICmp RangeCheck, 279 SCEVExpander &Expander, 280 IRBuilder<> &Builder); 281 unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition, 282 SCEVExpander &Expander, IRBuilder<> &Builder); 283 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander); 284 bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander); 285 // If the loop always exits through another block in the loop, we should not 286 // predicate based on the latch check. For example, the latch check can be a 287 // very coarse grained check and there can be more fine grained exit checks 288 // within the loop. We identify such unprofitable loops through BPI. 289 bool isLoopProfitableToPredicate(); 290 291 // When the IV type is wider than the range operand type, we can still do loop 292 // predication, by generating SCEVs for the range and latch that are of the 293 // same type. We achieve this by generating a SCEV truncate expression for the 294 // latch IV. This is done iff truncation of the IV is a safe operation, 295 // without loss of information. 296 // Another way to achieve this is by generating a wider type SCEV for the 297 // range check operand, however, this needs a more involved check that 298 // operands do not overflow. This can lead to loss of information when the 299 // range operand is of the form: add i32 %offset, %iv. We need to prove that 300 // sext(x + y) is same as sext(x) + sext(y). 301 // This function returns true if we can safely represent the IV type in 302 // the RangeCheckType without loss of information. 303 bool isSafeToTruncateWideIVType(Type *RangeCheckType); 304 // Return the loopLatchCheck corresponding to the RangeCheckType if safe to do 305 // so. 306 Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType); 307 308 public: 309 LoopPredication(ScalarEvolution *SE, BranchProbabilityInfo *BPI) 310 : SE(SE), BPI(BPI){}; 311 bool runOnLoop(Loop *L); 312 }; 313 314 class LoopPredicationLegacyPass : public LoopPass { 315 public: 316 static char ID; 317 LoopPredicationLegacyPass() : LoopPass(ID) { 318 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry()); 319 } 320 321 void getAnalysisUsage(AnalysisUsage &AU) const override { 322 AU.addRequired<BranchProbabilityInfoWrapperPass>(); 323 getLoopAnalysisUsage(AU); 324 } 325 326 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 327 if (skipLoop(L)) 328 return false; 329 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 330 BranchProbabilityInfo &BPI = 331 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); 332 LoopPredication LP(SE, &BPI); 333 return LP.runOnLoop(L); 334 } 335 }; 336 337 char LoopPredicationLegacyPass::ID = 0; 338 } // end namespace llvm 339 340 INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", 341 "Loop predication", false, false) 342 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 343 INITIALIZE_PASS_DEPENDENCY(LoopPass) 344 INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication", 345 "Loop predication", false, false) 346 347 Pass *llvm::createLoopPredicationPass() { 348 return new LoopPredicationLegacyPass(); 349 } 350 351 PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM, 352 LoopStandardAnalysisResults &AR, 353 LPMUpdater &U) { 354 const auto &FAM = 355 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); 356 Function *F = L.getHeader()->getParent(); 357 auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F); 358 LoopPredication LP(&AR.SE, BPI); 359 if (!LP.runOnLoop(&L)) 360 return PreservedAnalyses::all(); 361 362 return getLoopPassPreservedAnalyses(); 363 } 364 365 Optional<LoopPredication::LoopICmp> 366 LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS, 367 Value *RHS) { 368 const SCEV *LHSS = SE->getSCEV(LHS); 369 if (isa<SCEVCouldNotCompute>(LHSS)) 370 return None; 371 const SCEV *RHSS = SE->getSCEV(RHS); 372 if (isa<SCEVCouldNotCompute>(RHSS)) 373 return None; 374 375 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV 376 if (SE->isLoopInvariant(LHSS, L)) { 377 std::swap(LHS, RHS); 378 std::swap(LHSS, RHSS); 379 Pred = ICmpInst::getSwappedPredicate(Pred); 380 } 381 382 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS); 383 if (!AR || AR->getLoop() != L) 384 return None; 385 386 return LoopICmp(Pred, AR, RHSS); 387 } 388 389 Value *LoopPredication::expandCheck(SCEVExpander &Expander, 390 IRBuilder<> &Builder, 391 ICmpInst::Predicate Pred, const SCEV *LHS, 392 const SCEV *RHS) { 393 Type *Ty = LHS->getType(); 394 assert(Ty == RHS->getType() && "expandCheck operands have different types?"); 395 396 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS)) 397 return Builder.getTrue(); 398 399 Instruction *InsertAt = &*Builder.GetInsertPoint(); 400 Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt); 401 Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt); 402 return Builder.CreateICmp(Pred, LHSV, RHSV); 403 } 404 405 Optional<LoopPredication::LoopICmp> 406 LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) { 407 408 auto *LatchType = LatchCheck.IV->getType(); 409 if (RangeCheckType == LatchType) 410 return LatchCheck; 411 // For now, bail out if latch type is narrower than range type. 412 if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType)) 413 return None; 414 if (!isSafeToTruncateWideIVType(RangeCheckType)) 415 return None; 416 // We can now safely identify the truncated version of the IV and limit for 417 // RangeCheckType. 418 LoopICmp NewLatchCheck; 419 NewLatchCheck.Pred = LatchCheck.Pred; 420 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>( 421 SE->getTruncateExpr(LatchCheck.IV, RangeCheckType)); 422 if (!NewLatchCheck.IV) 423 return None; 424 NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType); 425 LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType 426 << "can be represented as range check type:" 427 << *RangeCheckType << "\n"); 428 LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n"); 429 LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n"); 430 return NewLatchCheck; 431 } 432 433 bool LoopPredication::isSupportedStep(const SCEV* Step) { 434 return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop); 435 } 436 437 bool LoopPredication::CanExpand(const SCEV* S) { 438 return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE); 439 } 440 441 Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop( 442 LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck, 443 SCEVExpander &Expander, IRBuilder<> &Builder) { 444 auto *Ty = RangeCheck.IV->getType(); 445 // Generate the widened condition for the forward loop: 446 // guardStart u< guardLimit && 447 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart 448 // where <pred> depends on the latch condition predicate. See the file 449 // header comment for the reasoning. 450 // guardLimit - guardStart + latchStart - 1 451 const SCEV *GuardStart = RangeCheck.IV->getStart(); 452 const SCEV *GuardLimit = RangeCheck.Limit; 453 const SCEV *LatchStart = LatchCheck.IV->getStart(); 454 const SCEV *LatchLimit = LatchCheck.Limit; 455 456 // guardLimit - guardStart + latchStart - 1 457 const SCEV *RHS = 458 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart), 459 SE->getMinusSCEV(LatchStart, SE->getOne(Ty))); 460 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) || 461 !CanExpand(LatchLimit) || !CanExpand(RHS)) { 462 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 463 return None; 464 } 465 auto LimitCheckPred = 466 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); 467 468 LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n"); 469 LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n"); 470 LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n"); 471 472 auto *LimitCheck = 473 expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS); 474 auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck.Pred, 475 GuardStart, GuardLimit); 476 return Builder.CreateAnd(FirstIterationCheck, LimitCheck); 477 } 478 479 Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop( 480 LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck, 481 SCEVExpander &Expander, IRBuilder<> &Builder) { 482 auto *Ty = RangeCheck.IV->getType(); 483 const SCEV *GuardStart = RangeCheck.IV->getStart(); 484 const SCEV *GuardLimit = RangeCheck.Limit; 485 const SCEV *LatchLimit = LatchCheck.Limit; 486 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) || 487 !CanExpand(LatchLimit)) { 488 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 489 return None; 490 } 491 // The decrement of the latch check IV should be the same as the 492 // rangeCheckIV. 493 auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE); 494 if (RangeCheck.IV != PostDecLatchCheckIV) { 495 LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: " 496 << *PostDecLatchCheckIV 497 << " and RangeCheckIV: " << *RangeCheck.IV << "\n"); 498 return None; 499 } 500 501 // Generate the widened condition for CountDownLoop: 502 // guardStart u< guardLimit && 503 // latchLimit <pred> 1. 504 // See the header comment for reasoning of the checks. 505 auto LimitCheckPred = 506 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); 507 auto *FirstIterationCheck = expandCheck(Expander, Builder, ICmpInst::ICMP_ULT, 508 GuardStart, GuardLimit); 509 auto *LimitCheck = expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, 510 SE->getOne(Ty)); 511 return Builder.CreateAnd(FirstIterationCheck, LimitCheck); 512 } 513 514 /// If ICI can be widened to a loop invariant condition emits the loop 515 /// invariant condition in the loop preheader and return it, otherwise 516 /// returns None. 517 Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, 518 SCEVExpander &Expander, 519 IRBuilder<> &Builder) { 520 LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n"); 521 LLVM_DEBUG(ICI->dump()); 522 523 // parseLoopStructure guarantees that the latch condition is: 524 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=. 525 // We are looking for the range checks of the form: 526 // i u< guardLimit 527 auto RangeCheck = parseLoopICmp(ICI); 528 if (!RangeCheck) { 529 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 530 return None; 531 } 532 LLVM_DEBUG(dbgs() << "Guard check:\n"); 533 LLVM_DEBUG(RangeCheck->dump()); 534 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) { 535 LLVM_DEBUG(dbgs() << "Unsupported range check predicate(" 536 << RangeCheck->Pred << ")!\n"); 537 return None; 538 } 539 auto *RangeCheckIV = RangeCheck->IV; 540 if (!RangeCheckIV->isAffine()) { 541 LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n"); 542 return None; 543 } 544 auto *Step = RangeCheckIV->getStepRecurrence(*SE); 545 // We cannot just compare with latch IV step because the latch and range IVs 546 // may have different types. 547 if (!isSupportedStep(Step)) { 548 LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n"); 549 return None; 550 } 551 auto *Ty = RangeCheckIV->getType(); 552 auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty); 553 if (!CurrLatchCheckOpt) { 554 LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check " 555 "corresponding to range type: " 556 << *Ty << "\n"); 557 return None; 558 } 559 560 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt; 561 // At this point, the range and latch step should have the same type, but need 562 // not have the same value (we support both 1 and -1 steps). 563 assert(Step->getType() == 564 CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() && 565 "Range and latch steps should be of same type!"); 566 if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) { 567 LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n"); 568 return None; 569 } 570 571 if (Step->isOne()) 572 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck, 573 Expander, Builder); 574 else { 575 assert(Step->isAllOnesValue() && "Step should be -1!"); 576 return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck, 577 Expander, Builder); 578 } 579 } 580 581 unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks, 582 Value *Condition, 583 SCEVExpander &Expander, 584 IRBuilder<> &Builder) { 585 unsigned NumWidened = 0; 586 // The guard condition is expected to be in form of: 587 // cond1 && cond2 && cond3 ... 588 // Iterate over subconditions looking for icmp conditions which can be 589 // widened across loop iterations. Widening these conditions remember the 590 // resulting list of subconditions in Checks vector. 591 SmallVector<Value *, 4> Worklist(1, Condition); 592 SmallPtrSet<Value *, 4> Visited; 593 do { 594 Value *Condition = Worklist.pop_back_val(); 595 if (!Visited.insert(Condition).second) 596 continue; 597 598 Value *LHS, *RHS; 599 using namespace llvm::PatternMatch; 600 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) { 601 Worklist.push_back(LHS); 602 Worklist.push_back(RHS); 603 continue; 604 } 605 606 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) { 607 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, 608 Builder)) { 609 Checks.push_back(NewRangeCheck.getValue()); 610 NumWidened++; 611 continue; 612 } 613 } 614 615 // Save the condition as is if we can't widen it 616 Checks.push_back(Condition); 617 } while (!Worklist.empty()); 618 return NumWidened; 619 } 620 621 bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard, 622 SCEVExpander &Expander) { 623 LLVM_DEBUG(dbgs() << "Processing guard:\n"); 624 LLVM_DEBUG(Guard->dump()); 625 626 TotalConsidered++; 627 SmallVector<Value *, 4> Checks; 628 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator())); 629 unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander, 630 Builder); 631 if (NumWidened == 0) 632 return false; 633 634 TotalWidened += NumWidened; 635 636 // Emit the new guard condition 637 Builder.SetInsertPoint(Guard); 638 Value *LastCheck = nullptr; 639 for (auto *Check : Checks) 640 if (!LastCheck) 641 LastCheck = Check; 642 else 643 LastCheck = Builder.CreateAnd(LastCheck, Check); 644 Guard->setOperand(0, LastCheck); 645 646 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 647 return true; 648 } 649 650 bool LoopPredication::widenWidenableBranchGuardConditions( 651 BranchInst *Guard, SCEVExpander &Expander) { 652 assert(isGuardAsWidenableBranch(Guard) && "Must be!"); 653 LLVM_DEBUG(dbgs() << "Processing guard:\n"); 654 LLVM_DEBUG(Guard->dump()); 655 656 TotalConsidered++; 657 SmallVector<Value *, 4> Checks; 658 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator())); 659 Value *Condition = nullptr, *WidenableCondition = nullptr; 660 BasicBlock *GBB = nullptr, *DBB = nullptr; 661 parseWidenableBranch(Guard, Condition, WidenableCondition, GBB, DBB); 662 unsigned NumWidened = collectChecks(Checks, Condition, Expander, Builder); 663 if (NumWidened == 0) 664 return false; 665 666 TotalWidened += NumWidened; 667 668 // Emit the new guard condition 669 Builder.SetInsertPoint(Guard); 670 Value *LastCheck = nullptr; 671 for (auto *Check : Checks) 672 if (!LastCheck) 673 LastCheck = Check; 674 else 675 LastCheck = Builder.CreateAnd(LastCheck, Check); 676 // Make sure that the check contains widenable condition and therefore can be 677 // further widened. 678 LastCheck = Builder.CreateAnd(LastCheck, WidenableCondition); 679 Guard->setOperand(0, LastCheck); 680 assert(isGuardAsWidenableBranch(Guard) && 681 "Stopped being a guard after transform?"); 682 683 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 684 return true; 685 } 686 687 Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() { 688 using namespace PatternMatch; 689 690 BasicBlock *LoopLatch = L->getLoopLatch(); 691 if (!LoopLatch) { 692 LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n"); 693 return None; 694 } 695 696 ICmpInst::Predicate Pred; 697 Value *LHS, *RHS; 698 BasicBlock *TrueDest, *FalseDest; 699 700 if (!match(LoopLatch->getTerminator(), 701 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest, 702 FalseDest))) { 703 LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n"); 704 return None; 705 } 706 assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) && 707 "One of the latch's destinations must be the header"); 708 if (TrueDest != L->getHeader()) 709 Pred = ICmpInst::getInversePredicate(Pred); 710 711 auto Result = parseLoopICmp(Pred, LHS, RHS); 712 if (!Result) { 713 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 714 return None; 715 } 716 717 // Check affine first, so if it's not we don't try to compute the step 718 // recurrence. 719 if (!Result->IV->isAffine()) { 720 LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n"); 721 return None; 722 } 723 724 auto *Step = Result->IV->getStepRecurrence(*SE); 725 if (!isSupportedStep(Step)) { 726 LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n"); 727 return None; 728 } 729 730 auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) { 731 if (Step->isOne()) { 732 return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT && 733 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE; 734 } else { 735 assert(Step->isAllOnesValue() && "Step should be -1!"); 736 return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT && 737 Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE; 738 } 739 }; 740 741 if (IsUnsupportedPredicate(Step, Result->Pred)) { 742 LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred 743 << ")!\n"); 744 return None; 745 } 746 return Result; 747 } 748 749 // Returns true if its safe to truncate the IV to RangeCheckType. 750 bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) { 751 if (!EnableIVTruncation) 752 return false; 753 assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) > 754 DL->getTypeSizeInBits(RangeCheckType) && 755 "Expected latch check IV type to be larger than range check operand " 756 "type!"); 757 // The start and end values of the IV should be known. This is to guarantee 758 // that truncating the wide type will not lose information. 759 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit); 760 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart()); 761 if (!Limit || !Start) 762 return false; 763 // This check makes sure that the IV does not change sign during loop 764 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE, 765 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the 766 // IV wraps around, and the truncation of the IV would lose the range of 767 // iterations between 2^32 and 2^64. 768 bool Increasing; 769 if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing)) 770 return false; 771 // The active bits should be less than the bits in the RangeCheckType. This 772 // guarantees that truncating the latch check to RangeCheckType is a safe 773 // operation. 774 auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType); 775 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize && 776 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize; 777 } 778 779 bool LoopPredication::isLoopProfitableToPredicate() { 780 if (SkipProfitabilityChecks || !BPI) 781 return true; 782 783 SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 8> ExitEdges; 784 L->getExitEdges(ExitEdges); 785 // If there is only one exiting edge in the loop, it is always profitable to 786 // predicate the loop. 787 if (ExitEdges.size() == 1) 788 return true; 789 790 // Calculate the exiting probabilities of all exiting edges from the loop, 791 // starting with the LatchExitProbability. 792 // Heuristic for profitability: If any of the exiting blocks' probability of 793 // exiting the loop is larger than exiting through the latch block, it's not 794 // profitable to predicate the loop. 795 auto *LatchBlock = L->getLoopLatch(); 796 assert(LatchBlock && "Should have a single latch at this point!"); 797 auto *LatchTerm = LatchBlock->getTerminator(); 798 assert(LatchTerm->getNumSuccessors() == 2 && 799 "expected to be an exiting block with 2 succs!"); 800 unsigned LatchBrExitIdx = 801 LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0; 802 BranchProbability LatchExitProbability = 803 BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx); 804 805 // Protect against degenerate inputs provided by the user. Providing a value 806 // less than one, can invert the definition of profitable loop predication. 807 float ScaleFactor = LatchExitProbabilityScale; 808 if (ScaleFactor < 1) { 809 LLVM_DEBUG( 810 dbgs() 811 << "Ignored user setting for loop-predication-latch-probability-scale: " 812 << LatchExitProbabilityScale << "\n"); 813 LLVM_DEBUG(dbgs() << "The value is set to 1.0\n"); 814 ScaleFactor = 1.0; 815 } 816 const auto LatchProbabilityThreshold = 817 LatchExitProbability * ScaleFactor; 818 819 for (const auto &ExitEdge : ExitEdges) { 820 BranchProbability ExitingBlockProbability = 821 BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second); 822 // Some exiting edge has higher probability than the latch exiting edge. 823 // No longer profitable to predicate. 824 if (ExitingBlockProbability > LatchProbabilityThreshold) 825 return false; 826 } 827 // Using BPI, we have concluded that the most probable way to exit from the 828 // loop is through the latch (or there's no profile information and all 829 // exits are equally likely). 830 return true; 831 } 832 833 bool LoopPredication::runOnLoop(Loop *Loop) { 834 L = Loop; 835 836 LLVM_DEBUG(dbgs() << "Analyzing "); 837 LLVM_DEBUG(L->dump()); 838 839 Module *M = L->getHeader()->getModule(); 840 841 // There is nothing to do if the module doesn't use guards 842 auto *GuardDecl = 843 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard)); 844 bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty(); 845 auto *WCDecl = M->getFunction( 846 Intrinsic::getName(Intrinsic::experimental_widenable_condition)); 847 bool HasWidenableConditions = 848 PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty(); 849 if (!HasIntrinsicGuards && !HasWidenableConditions) 850 return false; 851 852 DL = &M->getDataLayout(); 853 854 Preheader = L->getLoopPreheader(); 855 if (!Preheader) 856 return false; 857 858 auto LatchCheckOpt = parseLoopLatchICmp(); 859 if (!LatchCheckOpt) 860 return false; 861 LatchCheck = *LatchCheckOpt; 862 863 LLVM_DEBUG(dbgs() << "Latch check:\n"); 864 LLVM_DEBUG(LatchCheck.dump()); 865 866 if (!isLoopProfitableToPredicate()) { 867 LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n"); 868 return false; 869 } 870 // Collect all the guards into a vector and process later, so as not 871 // to invalidate the instruction iterator. 872 SmallVector<IntrinsicInst *, 4> Guards; 873 SmallVector<BranchInst *, 4> GuardsAsWidenableBranches; 874 for (const auto BB : L->blocks()) { 875 for (auto &I : *BB) 876 if (isGuard(&I)) 877 Guards.push_back(cast<IntrinsicInst>(&I)); 878 if (PredicateWidenableBranchGuards && 879 isGuardAsWidenableBranch(BB->getTerminator())) 880 GuardsAsWidenableBranches.push_back( 881 cast<BranchInst>(BB->getTerminator())); 882 } 883 884 if (Guards.empty() && GuardsAsWidenableBranches.empty()) 885 return false; 886 887 SCEVExpander Expander(*SE, *DL, "loop-predication"); 888 889 bool Changed = false; 890 for (auto *Guard : Guards) 891 Changed |= widenGuardConditions(Guard, Expander); 892 for (auto *Guard : GuardsAsWidenableBranches) 893 Changed |= widenWidenableBranchGuardConditions(Guard, Expander); 894 895 return Changed; 896 } 897