1 //===-- LoopPredication.cpp - Guard based loop predication pass -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // The LoopPredication pass tries to convert loop variant range checks to loop 11 // invariant by widening checks across loop iterations. For example, it will 12 // convert 13 // 14 // for (i = 0; i < n; i++) { 15 // guard(i < len); 16 // ... 17 // } 18 // 19 // to 20 // 21 // for (i = 0; i < n; i++) { 22 // guard(n - 1 < len); 23 // ... 24 // } 25 // 26 // After this transformation the condition of the guard is loop invariant, so 27 // loop-unswitch can later unswitch the loop by this condition which basically 28 // predicates the loop by the widened condition: 29 // 30 // if (n - 1 < len) 31 // for (i = 0; i < n; i++) { 32 // ... 33 // } 34 // else 35 // deoptimize 36 // 37 // It's tempting to rely on SCEV here, but it has proven to be problematic. 38 // Generally the facts SCEV provides about the increment step of add 39 // recurrences are true if the backedge of the loop is taken, which implicitly 40 // assumes that the guard doesn't fail. Using these facts to optimize the 41 // guard results in a circular logic where the guard is optimized under the 42 // assumption that it never fails. 43 // 44 // For example, in the loop below the induction variable will be marked as nuw 45 // basing on the guard. Basing on nuw the guard predicate will be considered 46 // monotonic. Given a monotonic condition it's tempting to replace the induction 47 // variable in the condition with its value on the last iteration. But this 48 // transformation is not correct, e.g. e = 4, b = 5 breaks the loop. 49 // 50 // for (int i = b; i != e; i++) 51 // guard(i u< len) 52 // 53 // One of the ways to reason about this problem is to use an inductive proof 54 // approach. Given the loop: 55 // 56 // if (B(Start)) { 57 // do { 58 // I = PHI(Start, I.INC) 59 // I.INC = I + Step 60 // guard(G(I)); 61 // } while (B(I.INC)); 62 // } 63 // 64 // where B(x) and G(x) are predicates that map integers to booleans, we want a 65 // loop invariant expression M such the following program has the same semantics 66 // as the above: 67 // 68 // if (B(Start)) { 69 // do { 70 // I = PHI(Start, I.INC) 71 // I.INC = I + Step 72 // guard(G(Start) && M); 73 // } while (B(I.INC)); 74 // } 75 // 76 // One solution for M is M = forall X . (G(X) && B(X + Step)) => G(X + Step) 77 // 78 // Informal proof that the transformation above is correct: 79 // 80 // By the definition of guards we can rewrite the guard condition to: 81 // G(I) && G(Start) && M 82 // 83 // Let's prove that for each iteration of the loop: 84 // G(Start) && M => G(I) 85 // And the condition above can be simplified to G(Start) && M. 86 // 87 // Induction base. 88 // G(Start) && M => G(Start) 89 // 90 // Induction step. Assuming G(Start) && M => G(I) on the subsequent 91 // iteration: 92 // 93 // B(I + Step) is true because it's the backedge condition. 94 // G(I) is true because the backedge is guarded by this condition. 95 // 96 // So M = forall X . (G(X) && B(X + Step)) => G(X + Step) implies 97 // G(I + Step). 98 // 99 // Note that we can use anything stronger than M, i.e. any condition which 100 // implies M. 101 // 102 // For now the transformation is limited to the following case: 103 // * The loop has a single latch with either ult or slt icmp condition. 104 // * The step of the IV used in the latch condition is 1. 105 // * The IV of the latch condition is the same as the post increment IV of the 106 // guard condition. 107 // * The guard condition is ult. 108 // 109 // In this case the latch is of the from: 110 // ++i u< latchLimit or ++i s< latchLimit 111 // and the guard is of the form: 112 // i u< guardLimit 113 // 114 // For the unsigned latch comparison case M is: 115 // forall X . X u< guardLimit && (X + 1) u< latchLimit => 116 // (X + 1) u< guardLimit 117 // 118 // This is true if latchLimit u<= guardLimit since then 119 // (X + 1) u< latchLimit u<= guardLimit == (X + 1) u< guardLimit. 120 // 121 // So the widened condition is: 122 // i.start u< guardLimit && latchLimit u<= guardLimit 123 // 124 // For the signed latch comparison case M is: 125 // forall X . X u< guardLimit && (X + 1) s< latchLimit => 126 // (X + 1) u< guardLimit 127 // 128 // The only way the antecedent can be true and the consequent can be false is 129 // if 130 // X == guardLimit - 1 131 // (and guardLimit is non-zero, but we won't use this latter fact). 132 // If X == guardLimit - 1 then the second half of the antecedent is 133 // guardLimit s< latchLimit 134 // and its negation is 135 // latchLimit s<= guardLimit. 136 // 137 // In other words, if latchLimit s<= guardLimit then: 138 // (the ranges below are written in ConstantRange notation, where [A, B) is the 139 // set for (I = A; I != B; I++ /*maywrap*/) yield(I);) 140 // 141 // forall X . X u< guardLimit && (X + 1) s< latchLimit => (X + 1) u< guardLimit 142 // == forall X . X u< guardLimit && (X + 1) s< guardLimit => (X + 1) u< guardLimit 143 // == forall X . X in [0, guardLimit) && (X + 1) in [INT_MIN, guardLimit) => (X + 1) in [0, guardLimit) 144 // == forall X . X in [0, guardLimit) && X in [INT_MAX, guardLimit-1) => X in [-1, guardLimit-1) 145 // == forall X . X in [0, guardLimit-1) => X in [-1, guardLimit-1) 146 // == true 147 // 148 // So the widened condition is: 149 // i.start u< guardLimit && latchLimit s<= guardLimit 150 // 151 //===----------------------------------------------------------------------===// 152 153 #include "llvm/Transforms/Scalar/LoopPredication.h" 154 #include "llvm/Analysis/LoopInfo.h" 155 #include "llvm/Analysis/LoopPass.h" 156 #include "llvm/Analysis/ScalarEvolution.h" 157 #include "llvm/Analysis/ScalarEvolutionExpander.h" 158 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 159 #include "llvm/IR/Function.h" 160 #include "llvm/IR/GlobalValue.h" 161 #include "llvm/IR/IntrinsicInst.h" 162 #include "llvm/IR/Module.h" 163 #include "llvm/IR/PatternMatch.h" 164 #include "llvm/Pass.h" 165 #include "llvm/Support/Debug.h" 166 #include "llvm/Transforms/Scalar.h" 167 #include "llvm/Transforms/Utils/LoopUtils.h" 168 169 #define DEBUG_TYPE "loop-predication" 170 171 using namespace llvm; 172 173 namespace { 174 class LoopPredication { 175 /// Represents an induction variable check: 176 /// icmp Pred, <induction variable>, <loop invariant limit> 177 struct LoopICmp { 178 ICmpInst::Predicate Pred; 179 const SCEVAddRecExpr *IV; 180 const SCEV *Limit; 181 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV, 182 const SCEV *Limit) 183 : Pred(Pred), IV(IV), Limit(Limit) {} 184 LoopICmp() {} 185 }; 186 187 ScalarEvolution *SE; 188 189 Loop *L; 190 const DataLayout *DL; 191 BasicBlock *Preheader; 192 LoopICmp LatchCheck; 193 194 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) { 195 return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0), 196 ICI->getOperand(1)); 197 } 198 Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS, 199 Value *RHS); 200 201 Optional<LoopICmp> parseLoopLatchICmp(); 202 203 Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder, 204 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 205 Instruction *InsertAt); 206 207 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, 208 IRBuilder<> &Builder); 209 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander); 210 211 public: 212 LoopPredication(ScalarEvolution *SE) : SE(SE){}; 213 bool runOnLoop(Loop *L); 214 }; 215 216 class LoopPredicationLegacyPass : public LoopPass { 217 public: 218 static char ID; 219 LoopPredicationLegacyPass() : LoopPass(ID) { 220 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry()); 221 } 222 223 void getAnalysisUsage(AnalysisUsage &AU) const override { 224 getLoopAnalysisUsage(AU); 225 } 226 227 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 228 if (skipLoop(L)) 229 return false; 230 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 231 LoopPredication LP(SE); 232 return LP.runOnLoop(L); 233 } 234 }; 235 236 char LoopPredicationLegacyPass::ID = 0; 237 } // end namespace llvm 238 239 INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", 240 "Loop predication", false, false) 241 INITIALIZE_PASS_DEPENDENCY(LoopPass) 242 INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication", 243 "Loop predication", false, false) 244 245 Pass *llvm::createLoopPredicationPass() { 246 return new LoopPredicationLegacyPass(); 247 } 248 249 PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM, 250 LoopStandardAnalysisResults &AR, 251 LPMUpdater &U) { 252 LoopPredication LP(&AR.SE); 253 if (!LP.runOnLoop(&L)) 254 return PreservedAnalyses::all(); 255 256 return getLoopPassPreservedAnalyses(); 257 } 258 259 Optional<LoopPredication::LoopICmp> 260 LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS, 261 Value *RHS) { 262 const SCEV *LHSS = SE->getSCEV(LHS); 263 if (isa<SCEVCouldNotCompute>(LHSS)) 264 return None; 265 const SCEV *RHSS = SE->getSCEV(RHS); 266 if (isa<SCEVCouldNotCompute>(RHSS)) 267 return None; 268 269 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV 270 if (SE->isLoopInvariant(LHSS, L)) { 271 std::swap(LHS, RHS); 272 std::swap(LHSS, RHSS); 273 Pred = ICmpInst::getSwappedPredicate(Pred); 274 } 275 276 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS); 277 if (!AR || AR->getLoop() != L) 278 return None; 279 280 return LoopICmp(Pred, AR, RHSS); 281 } 282 283 Value *LoopPredication::expandCheck(SCEVExpander &Expander, 284 IRBuilder<> &Builder, 285 ICmpInst::Predicate Pred, const SCEV *LHS, 286 const SCEV *RHS, Instruction *InsertAt) { 287 // TODO: we can check isLoopEntryGuardedByCond before emitting the check 288 289 Type *Ty = LHS->getType(); 290 assert(Ty == RHS->getType() && "expandCheck operands have different types?"); 291 Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt); 292 Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt); 293 return Builder.CreateICmp(Pred, LHSV, RHSV); 294 } 295 296 /// If ICI can be widened to a loop invariant condition emits the loop 297 /// invariant condition in the loop preheader and return it, otherwise 298 /// returns None. 299 Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, 300 SCEVExpander &Expander, 301 IRBuilder<> &Builder) { 302 DEBUG(dbgs() << "Analyzing ICmpInst condition:\n"); 303 DEBUG(ICI->dump()); 304 305 // parseLoopStructure guarantees that the latch condition is: 306 // ++i u< latchLimit or ++i s< latchLimit 307 // We are looking for the range checks of the form: 308 // i u< guardLimit 309 auto RangeCheck = parseLoopICmp(ICI); 310 if (!RangeCheck) { 311 DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 312 return None; 313 } 314 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) { 315 DEBUG(dbgs() << "Unsupported range check predicate(" << RangeCheck->Pred 316 << ")!\n"); 317 return None; 318 } 319 auto *RangeCheckIV = RangeCheck->IV; 320 auto *PostIncRangeCheckIV = RangeCheckIV->getPostIncExpr(*SE); 321 if (LatchCheck.IV != PostIncRangeCheckIV) { 322 DEBUG(dbgs() << "Post increment range check IV (" << *PostIncRangeCheckIV 323 << ") is not the same as latch IV (" << *LatchCheck.IV 324 << ")!\n"); 325 return None; 326 } 327 assert(RangeCheckIV->getStepRecurrence(*SE)->isOne() && "must be one"); 328 const SCEV *Start = RangeCheckIV->getStart(); 329 330 // Generate the widened condition. See the file header comment for reasoning. 331 // If the latch condition is unsigned: 332 // i.start u< guardLimit && latchLimit u<= guardLimit 333 // If the latch condition is signed: 334 // i.start u< guardLimit && latchLimit s<= guardLimit 335 336 auto LimitCheckPred = ICmpInst::isSigned(LatchCheck.Pred) 337 ? ICmpInst::ICMP_SLE 338 : ICmpInst::ICMP_ULE; 339 340 auto CanExpand = [this](const SCEV *S) { 341 return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE); 342 }; 343 if (!CanExpand(Start) || !CanExpand(LatchCheck.Limit) || 344 !CanExpand(RangeCheck->Limit)) 345 return None; 346 347 Instruction *InsertAt = Preheader->getTerminator(); 348 auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck->Pred, 349 Start, RangeCheck->Limit, InsertAt); 350 auto *LimitCheck = expandCheck(Expander, Builder, LimitCheckPred, 351 LatchCheck.Limit, RangeCheck->Limit, InsertAt); 352 return Builder.CreateAnd(FirstIterationCheck, LimitCheck); 353 } 354 355 bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard, 356 SCEVExpander &Expander) { 357 DEBUG(dbgs() << "Processing guard:\n"); 358 DEBUG(Guard->dump()); 359 360 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator())); 361 362 // The guard condition is expected to be in form of: 363 // cond1 && cond2 && cond3 ... 364 // Iterate over subconditions looking for for icmp conditions which can be 365 // widened across loop iterations. Widening these conditions remember the 366 // resulting list of subconditions in Checks vector. 367 SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0)); 368 SmallPtrSet<Value *, 4> Visited; 369 370 SmallVector<Value *, 4> Checks; 371 372 unsigned NumWidened = 0; 373 do { 374 Value *Condition = Worklist.pop_back_val(); 375 if (!Visited.insert(Condition).second) 376 continue; 377 378 Value *LHS, *RHS; 379 using namespace llvm::PatternMatch; 380 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) { 381 Worklist.push_back(LHS); 382 Worklist.push_back(RHS); 383 continue; 384 } 385 386 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) { 387 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) { 388 Checks.push_back(NewRangeCheck.getValue()); 389 NumWidened++; 390 continue; 391 } 392 } 393 394 // Save the condition as is if we can't widen it 395 Checks.push_back(Condition); 396 } while (Worklist.size() != 0); 397 398 if (NumWidened == 0) 399 return false; 400 401 // Emit the new guard condition 402 Builder.SetInsertPoint(Guard); 403 Value *LastCheck = nullptr; 404 for (auto *Check : Checks) 405 if (!LastCheck) 406 LastCheck = Check; 407 else 408 LastCheck = Builder.CreateAnd(LastCheck, Check); 409 Guard->setOperand(0, LastCheck); 410 411 DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 412 return true; 413 } 414 415 Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() { 416 using namespace PatternMatch; 417 418 BasicBlock *LoopLatch = L->getLoopLatch(); 419 if (!LoopLatch) { 420 DEBUG(dbgs() << "The loop doesn't have a single latch!\n"); 421 return None; 422 } 423 424 ICmpInst::Predicate Pred; 425 Value *LHS, *RHS; 426 BasicBlock *TrueDest, *FalseDest; 427 428 if (!match(LoopLatch->getTerminator(), 429 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest, 430 FalseDest))) { 431 DEBUG(dbgs() << "Failed to match the latch terminator!\n"); 432 return None; 433 } 434 assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) && 435 "One of the latch's destinations must be the header"); 436 if (TrueDest != L->getHeader()) 437 Pred = ICmpInst::getInversePredicate(Pred); 438 439 auto Result = parseLoopICmp(Pred, LHS, RHS); 440 if (!Result) { 441 DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 442 return None; 443 } 444 445 if (Result->Pred != ICmpInst::ICMP_ULT && 446 Result->Pred != ICmpInst::ICMP_SLT) { 447 DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred 448 << ")!\n"); 449 return None; 450 } 451 452 // Check affine first, so if it's not we don't try to compute the step 453 // recurrence. 454 if (!Result->IV->isAffine()) { 455 DEBUG(dbgs() << "The induction variable is not affine!\n"); 456 return None; 457 } 458 459 auto *Step = Result->IV->getStepRecurrence(*SE); 460 if (!Step->isOne()) { 461 DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n"); 462 return None; 463 } 464 465 return Result; 466 } 467 468 bool LoopPredication::runOnLoop(Loop *Loop) { 469 L = Loop; 470 471 DEBUG(dbgs() << "Analyzing "); 472 DEBUG(L->dump()); 473 474 Module *M = L->getHeader()->getModule(); 475 476 // There is nothing to do if the module doesn't use guards 477 auto *GuardDecl = 478 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard)); 479 if (!GuardDecl || GuardDecl->use_empty()) 480 return false; 481 482 DL = &M->getDataLayout(); 483 484 Preheader = L->getLoopPreheader(); 485 if (!Preheader) 486 return false; 487 488 auto LatchCheckOpt = parseLoopLatchICmp(); 489 if (!LatchCheckOpt) 490 return false; 491 LatchCheck = *LatchCheckOpt; 492 493 // Collect all the guards into a vector and process later, so as not 494 // to invalidate the instruction iterator. 495 SmallVector<IntrinsicInst *, 4> Guards; 496 for (const auto BB : L->blocks()) 497 for (auto &I : *BB) 498 if (auto *II = dyn_cast<IntrinsicInst>(&I)) 499 if (II->getIntrinsicID() == Intrinsic::experimental_guard) 500 Guards.push_back(II); 501 502 if (Guards.empty()) 503 return false; 504 505 SCEVExpander Expander(*SE, *DL, "loop-predication"); 506 507 bool Changed = false; 508 for (auto *Guard : Guards) 509 Changed |= widenGuardConditions(Guard, Expander); 510 511 return Changed; 512 } 513