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 //===----------------------------------------------------------------------===// 38 39 #include "llvm/Transforms/Scalar/LoopPredication.h" 40 #include "llvm/Pass.h" 41 #include "llvm/Analysis/LoopInfo.h" 42 #include "llvm/Analysis/LoopPass.h" 43 #include "llvm/Analysis/ScalarEvolution.h" 44 #include "llvm/Analysis/ScalarEvolutionExpander.h" 45 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 46 #include "llvm/IR/Function.h" 47 #include "llvm/IR/GlobalValue.h" 48 #include "llvm/IR/IntrinsicInst.h" 49 #include "llvm/IR/Module.h" 50 #include "llvm/IR/PatternMatch.h" 51 #include "llvm/Support/Debug.h" 52 #include "llvm/Transforms/Scalar.h" 53 #include "llvm/Transforms/Utils/LoopUtils.h" 54 55 #define DEBUG_TYPE "loop-predication" 56 57 using namespace llvm; 58 59 namespace { 60 class LoopPredication { 61 ScalarEvolution *SE; 62 63 Loop *L; 64 const DataLayout *DL; 65 BasicBlock *Preheader; 66 67 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, 68 IRBuilder<> &Builder); 69 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander); 70 71 public: 72 LoopPredication(ScalarEvolution *SE) : SE(SE){}; 73 bool runOnLoop(Loop *L); 74 }; 75 76 class LoopPredicationLegacyPass : public LoopPass { 77 public: 78 static char ID; 79 LoopPredicationLegacyPass() : LoopPass(ID) { 80 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry()); 81 } 82 83 void getAnalysisUsage(AnalysisUsage &AU) const override { 84 getLoopAnalysisUsage(AU); 85 } 86 87 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 88 if (skipLoop(L)) 89 return false; 90 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 91 LoopPredication LP(SE); 92 return LP.runOnLoop(L); 93 } 94 }; 95 96 char LoopPredicationLegacyPass::ID = 0; 97 } // end namespace llvm 98 99 INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", 100 "Loop predication", false, false) 101 INITIALIZE_PASS_DEPENDENCY(LoopPass) 102 INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication", 103 "Loop predication", false, false) 104 105 Pass *llvm::createLoopPredicationPass() { 106 return new LoopPredicationLegacyPass(); 107 } 108 109 PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM, 110 LoopStandardAnalysisResults &AR, 111 LPMUpdater &U) { 112 LoopPredication LP(&AR.SE); 113 if (!LP.runOnLoop(&L)) 114 return PreservedAnalyses::all(); 115 116 return getLoopPassPreservedAnalyses(); 117 } 118 119 /// If ICI can be widened to a loop invariant condition emits the loop 120 /// invariant condition in the loop preheader and return it, otherwise 121 /// returns None. 122 Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, 123 SCEVExpander &Expander, 124 IRBuilder<> &Builder) { 125 DEBUG(dbgs() << "Analyzing ICmpInst condition:\n"); 126 DEBUG(ICI->dump()); 127 128 ICmpInst::Predicate Pred = ICI->getPredicate(); 129 Value *LHS = ICI->getOperand(0); 130 Value *RHS = ICI->getOperand(1); 131 const SCEV *LHSS = SE->getSCEV(LHS); 132 if (isa<SCEVCouldNotCompute>(LHSS)) 133 return None; 134 const SCEV *RHSS = SE->getSCEV(RHS); 135 if (isa<SCEVCouldNotCompute>(RHSS)) 136 return None; 137 138 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable index 139 if (SE->isLoopInvariant(LHSS, L)) { 140 std::swap(LHS, RHS); 141 std::swap(LHSS, RHSS); 142 Pred = ICmpInst::getSwappedPredicate(Pred); 143 } 144 145 auto CanExpand = [this](const SCEV *S) { 146 return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE); 147 }; 148 if (!CanExpand(RHSS)) 149 return None; 150 151 const SCEVAddRecExpr *IndexAR = dyn_cast<SCEVAddRecExpr>(LHSS); 152 if (!IndexAR || IndexAR->getLoop() != L) 153 return None; 154 155 DEBUG(dbgs() << "IndexAR: "); 156 DEBUG(IndexAR->dump()); 157 158 bool IsIncreasing = false; 159 if (!SE->isMonotonicPredicate(IndexAR, Pred, IsIncreasing)) 160 return None; 161 162 // If the predicate is increasing the condition can change from false to true 163 // as the loop progresses, in this case take the value on the first iteration 164 // for the widened check. Otherwise the condition can change from true to 165 // false as the loop progresses, so take the value on the last iteration. 166 const SCEV *NewLHSS = IsIncreasing 167 ? IndexAR->getStart() 168 : SE->getSCEVAtScope(IndexAR, L->getParentLoop()); 169 if (NewLHSS == IndexAR) { 170 DEBUG(dbgs() << "Can't compute NewLHSS!\n"); 171 return None; 172 } 173 174 DEBUG(dbgs() << "NewLHSS: "); 175 DEBUG(NewLHSS->dump()); 176 177 if (!CanExpand(NewLHSS)) 178 return None; 179 180 DEBUG(dbgs() << "NewLHSS is loop invariant and safe to expand. Expand!\n"); 181 182 Type *Ty = LHS->getType(); 183 Instruction *InsertAt = Preheader->getTerminator(); 184 assert(Ty == RHS->getType() && "icmp operands have different types?"); 185 Value *NewLHS = Expander.expandCodeFor(NewLHSS, Ty, InsertAt); 186 Value *NewRHS = Expander.expandCodeFor(RHSS, Ty, InsertAt); 187 return Builder.CreateICmp(Pred, NewLHS, NewRHS); 188 } 189 190 bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard, 191 SCEVExpander &Expander) { 192 DEBUG(dbgs() << "Processing guard:\n"); 193 DEBUG(Guard->dump()); 194 195 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator())); 196 197 // The guard condition is expected to be in form of: 198 // cond1 && cond2 && cond3 ... 199 // Iterate over subconditions looking for for icmp conditions which can be 200 // widened across loop iterations. Widening these conditions remember the 201 // resulting list of subconditions in Checks vector. 202 SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0)); 203 SmallPtrSet<Value *, 4> Visited; 204 205 SmallVector<Value *, 4> Checks; 206 207 unsigned NumWidened = 0; 208 do { 209 Value *Condition = Worklist.pop_back_val(); 210 if (!Visited.insert(Condition).second) 211 continue; 212 213 Value *LHS, *RHS; 214 using namespace llvm::PatternMatch; 215 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) { 216 Worklist.push_back(LHS); 217 Worklist.push_back(RHS); 218 continue; 219 } 220 221 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) { 222 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) { 223 Checks.push_back(NewRangeCheck.getValue()); 224 NumWidened++; 225 continue; 226 } 227 } 228 229 // Save the condition as is if we can't widen it 230 Checks.push_back(Condition); 231 } while (Worklist.size() != 0); 232 233 if (NumWidened == 0) 234 return false; 235 236 // Emit the new guard condition 237 Builder.SetInsertPoint(Guard); 238 Value *LastCheck = nullptr; 239 for (auto *Check : Checks) 240 if (!LastCheck) 241 LastCheck = Check; 242 else 243 LastCheck = Builder.CreateAnd(LastCheck, Check); 244 Guard->setOperand(0, LastCheck); 245 246 DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 247 return true; 248 } 249 250 bool LoopPredication::runOnLoop(Loop *Loop) { 251 L = Loop; 252 253 DEBUG(dbgs() << "Analyzing "); 254 DEBUG(L->dump()); 255 256 Module *M = L->getHeader()->getModule(); 257 258 // There is nothing to do if the module doesn't use guards 259 auto *GuardDecl = 260 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard)); 261 if (!GuardDecl || GuardDecl->use_empty()) 262 return false; 263 264 DL = &M->getDataLayout(); 265 266 Preheader = L->getLoopPreheader(); 267 if (!Preheader) 268 return false; 269 270 // Collect all the guards into a vector and process later, so as not 271 // to invalidate the instruction iterator. 272 SmallVector<IntrinsicInst *, 4> Guards; 273 for (const auto BB : L->blocks()) 274 for (auto &I : *BB) 275 if (auto *II = dyn_cast<IntrinsicInst>(&I)) 276 if (II->getIntrinsicID() == Intrinsic::experimental_guard) 277 Guards.push_back(II); 278 279 if (Guards.empty()) 280 return false; 281 282 SCEVExpander Expander(*SE, *DL, "loop-predication"); 283 284 bool Changed = false; 285 for (auto *Guard : Guards) 286 Changed |= widenGuardConditions(Guard, Expander); 287 288 return Changed; 289 } 290