1 //===- LoopLoadElimination.cpp - Loop Load Elimination 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 // This file implement a loop-aware load elimination pass. 11 // 12 // It uses LoopAccessAnalysis to identify loop-carried dependences with a 13 // distance of one between stores and loads. These form the candidates for the 14 // transformation. The source value of each store then propagated to the user 15 // of the corresponding load. This makes the load dead. 16 // 17 // The pass can also version the loop and add memchecks in order to prove that 18 // may-aliasing stores can't change the value in memory before it's read by the 19 // load. 20 // 21 //===----------------------------------------------------------------------===// 22 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/LoopAccessAnalysis.h" 25 #include "llvm/Analysis/LoopInfo.h" 26 #include "llvm/Analysis/ScalarEvolutionExpander.h" 27 #include "llvm/IR/Dominators.h" 28 #include "llvm/IR/Module.h" 29 #include "llvm/Pass.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Transforms/Utils/LoopVersioning.h" 32 #include <forward_list> 33 34 #define LLE_OPTION "loop-load-elim" 35 #define DEBUG_TYPE LLE_OPTION 36 37 using namespace llvm; 38 39 static cl::opt<unsigned> CheckPerElim( 40 "runtime-check-per-loop-load-elim", cl::Hidden, 41 cl::desc("Max number of memchecks allowed per eliminated load on average"), 42 cl::init(1)); 43 44 STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE"); 45 46 namespace { 47 48 /// \brief Represent a store-to-forwarding candidate. 49 struct StoreToLoadForwardingCandidate { 50 LoadInst *Load; 51 StoreInst *Store; 52 53 StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store) 54 : Load(Load), Store(Store) {} 55 56 /// \brief Return true if the dependence from the store to the load has a 57 /// distance of one. E.g. A[i+1] = A[i] 58 bool isDependenceDistanceOfOne(ScalarEvolution *SE) const { 59 Value *LoadPtr = Load->getPointerOperand(); 60 Value *StorePtr = Store->getPointerOperand(); 61 Type *LoadPtrType = LoadPtr->getType(); 62 Type *LoadType = LoadPtrType->getPointerElementType(); 63 64 assert(LoadPtrType->getPointerAddressSpace() == 65 StorePtr->getType()->getPointerAddressSpace() && 66 LoadType == StorePtr->getType()->getPointerElementType() && 67 "Should be a known dependence"); 68 69 auto &DL = Load->getParent()->getModule()->getDataLayout(); 70 unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType)); 71 72 auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr)); 73 auto *StorePtrSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 74 75 // We don't need to check non-wrapping here because forward/backward 76 // dependence wouldn't be valid if these weren't monotonic accesses. 77 auto *Dist = 78 cast<SCEVConstant>(SE->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV)); 79 const APInt &Val = Dist->getValue()->getValue(); 80 return Val.abs() == TypeByteSize; 81 } 82 83 Value *getLoadPtr() const { return Load->getPointerOperand(); } 84 85 #ifndef NDEBUG 86 friend raw_ostream &operator<<(raw_ostream &OS, 87 const StoreToLoadForwardingCandidate &Cand) { 88 OS << *Cand.Store << " -->\n"; 89 OS.indent(2) << *Cand.Load << "\n"; 90 return OS; 91 } 92 #endif 93 }; 94 95 /// \brief Check if the store dominates all latches, so as long as there is no 96 /// intervening store this value will be loaded in the next iteration. 97 bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L, 98 DominatorTree *DT) { 99 SmallVector<BasicBlock *, 8> Latches; 100 L->getLoopLatches(Latches); 101 return std::all_of(Latches.begin(), Latches.end(), 102 [&](const BasicBlock *Latch) { 103 return DT->dominates(StoreBlock, Latch); 104 }); 105 } 106 107 /// \brief The per-loop class that does most of the work. 108 class LoadEliminationForLoop { 109 public: 110 LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI, 111 DominatorTree *DT, ScalarEvolution *SE) 112 : L(L), LI(LI), LAI(LAI), DT(DT), SE(SE) {} 113 114 /// \brief Look through the loop-carried and loop-independent dependences in 115 /// this loop and find store->load dependences. 116 /// 117 /// Note that no candidate is returned if LAA has failed to analyze the loop 118 /// (e.g. if it's not bottom-tested, contains volatile memops, etc.) 119 std::forward_list<StoreToLoadForwardingCandidate> 120 findStoreToLoadDependences(const LoopAccessInfo &LAI) { 121 std::forward_list<StoreToLoadForwardingCandidate> Candidates; 122 123 const auto *Deps = LAI.getDepChecker().getDependences(); 124 if (!Deps) 125 return Candidates; 126 127 // Find store->load dependences (consequently true dep). Both lexically 128 // forward and backward dependences qualify. Disqualify loads that have 129 // other unknown dependences. 130 131 SmallSet<Instruction *, 4> LoadsWithUnknownDepedence; 132 133 for (const auto &Dep : *Deps) { 134 Instruction *Source = Dep.getSource(LAI); 135 Instruction *Destination = Dep.getDestination(LAI); 136 137 if (Dep.Type == MemoryDepChecker::Dependence::Unknown) { 138 if (isa<LoadInst>(Source)) 139 LoadsWithUnknownDepedence.insert(Source); 140 if (isa<LoadInst>(Destination)) 141 LoadsWithUnknownDepedence.insert(Destination); 142 continue; 143 } 144 145 if (Dep.isBackward()) 146 // Note that the designations source and destination follow the program 147 // order, i.e. source is always first. (The direction is given by the 148 // DepType.) 149 std::swap(Source, Destination); 150 else 151 assert(Dep.isForward() && "Needs to be a forward dependence"); 152 153 auto *Store = dyn_cast<StoreInst>(Source); 154 if (!Store) 155 continue; 156 auto *Load = dyn_cast<LoadInst>(Destination); 157 if (!Load) 158 continue; 159 Candidates.emplace_front(Load, Store); 160 } 161 162 if (!LoadsWithUnknownDepedence.empty()) 163 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) { 164 return LoadsWithUnknownDepedence.count(C.Load); 165 }); 166 167 return Candidates; 168 } 169 170 /// \brief Return the index of the instruction according to program order. 171 unsigned getInstrIndex(Instruction *Inst) { 172 auto I = InstOrder.find(Inst); 173 assert(I != InstOrder.end() && "No index for instruction"); 174 return I->second; 175 } 176 177 /// \brief If a load has multiple candidates associated (i.e. different 178 /// stores), it means that it could be forwarding from multiple stores 179 /// depending on control flow. Remove these candidates. 180 /// 181 /// Here, we rely on LAA to include the relevant loop-independent dependences. 182 /// LAA is known to omit these in the very simple case when the read and the 183 /// write within an alias set always takes place using the *same* pointer. 184 /// 185 /// However, we know that this is not the case here, i.e. we can rely on LAA 186 /// to provide us with loop-independent dependences for the cases we're 187 /// interested. Consider the case for example where a loop-independent 188 /// dependece S1->S2 invalidates the forwarding S3->S2. 189 /// 190 /// A[i] = ... (S1) 191 /// ... = A[i] (S2) 192 /// A[i+1] = ... (S3) 193 /// 194 /// LAA will perform dependence analysis here because there are two 195 /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]). 196 void removeDependencesFromMultipleStores( 197 std::forward_list<StoreToLoadForwardingCandidate> &Candidates) { 198 // If Store is nullptr it means that we have multiple stores forwarding to 199 // this store. 200 typedef DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *> 201 LoadToSingleCandT; 202 LoadToSingleCandT LoadToSingleCand; 203 204 for (const auto &Cand : Candidates) { 205 bool NewElt; 206 LoadToSingleCandT::iterator Iter; 207 208 std::tie(Iter, NewElt) = 209 LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand)); 210 if (!NewElt) { 211 const StoreToLoadForwardingCandidate *&OtherCand = Iter->second; 212 // Already multiple stores forward to this load. 213 if (OtherCand == nullptr) 214 continue; 215 216 // Handle the very basic of case when the two stores are in the same 217 // block so deciding which one forwards is easy. The later one forwards 218 // as long as they both have a dependence distance of one to the load. 219 if (Cand.Store->getParent() == OtherCand->Store->getParent() && 220 Cand.isDependenceDistanceOfOne(SE) && 221 OtherCand->isDependenceDistanceOfOne(SE)) { 222 // They are in the same block, the later one will forward to the load. 223 if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store)) 224 OtherCand = &Cand; 225 } else 226 OtherCand = nullptr; 227 } 228 } 229 230 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) { 231 if (LoadToSingleCand[Cand.Load] != &Cand) { 232 DEBUG(dbgs() << "Removing from candidates: \n" << Cand 233 << " The load may have multiple stores forwarding to " 234 << "it\n"); 235 return true; 236 } 237 return false; 238 }); 239 } 240 241 /// \brief Given two pointers operations by their RuntimePointerChecking 242 /// indices, return true if they require an alias check. 243 /// 244 /// We need a check if one is a pointer for a candidate load and the other is 245 /// a pointer for a possibly intervening store. 246 bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2, 247 const SmallSet<Value *, 4> &PtrsWrittenOnFwdingPath, 248 const std::set<Value *> &CandLoadPtrs) { 249 Value *Ptr1 = 250 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue; 251 Value *Ptr2 = 252 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue; 253 return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) || 254 (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1))); 255 } 256 257 /// \brief Return pointers that are possibly written to on the path from a 258 /// forwarding store to a load. 259 /// 260 /// These pointers need to be alias-checked against the forwarding candidates. 261 SmallSet<Value *, 4> findPointersWrittenOnForwardingPath( 262 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) { 263 // From FirstStore to LastLoad neither of the elimination candidate loads 264 // should overlap with any of the stores. 265 // 266 // E.g.: 267 // 268 // st1 C[i] 269 // ld1 B[i] <-------, 270 // ld0 A[i] <----, | * LastLoad 271 // ... | | 272 // st2 E[i] | | 273 // st3 B[i+1] -- | -' * FirstStore 274 // st0 A[i+1] ---' 275 // st4 D[i] 276 // 277 // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with 278 // ld0. 279 280 LoadInst *LastLoad = 281 std::max_element(Candidates.begin(), Candidates.end(), 282 [&](const StoreToLoadForwardingCandidate &A, 283 const StoreToLoadForwardingCandidate &B) { 284 return getInstrIndex(A.Load) < getInstrIndex(B.Load); 285 }) 286 ->Load; 287 StoreInst *FirstStore = 288 std::min_element(Candidates.begin(), Candidates.end(), 289 [&](const StoreToLoadForwardingCandidate &A, 290 const StoreToLoadForwardingCandidate &B) { 291 return getInstrIndex(A.Store) < 292 getInstrIndex(B.Store); 293 }) 294 ->Store; 295 296 // We're looking for stores after the first forwarding store until the end 297 // of the loop, then from the beginning of the loop until the last 298 // forwarded-to load. Collect the pointer for the stores. 299 SmallSet<Value *, 4> PtrsWrittenOnFwdingPath; 300 301 auto InsertStorePtr = [&](Instruction *I) { 302 if (auto *S = dyn_cast<StoreInst>(I)) 303 PtrsWrittenOnFwdingPath.insert(S->getPointerOperand()); 304 }; 305 const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions(); 306 std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1, 307 MemInstrs.end(), InsertStorePtr); 308 std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)], 309 InsertStorePtr); 310 311 return PtrsWrittenOnFwdingPath; 312 } 313 314 /// \brief Determine the pointer alias checks to prove that there are no 315 /// intervening stores. 316 SmallVector<RuntimePointerChecking::PointerCheck, 4> collectMemchecks( 317 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) { 318 319 SmallSet<Value *, 4> PtrsWrittenOnFwdingPath = 320 findPointersWrittenOnForwardingPath(Candidates); 321 322 // Collect the pointers of the candidate loads. 323 // FIXME: SmallSet does not work with std::inserter. 324 std::set<Value *> CandLoadPtrs; 325 std::transform(Candidates.begin(), Candidates.end(), 326 std::inserter(CandLoadPtrs, CandLoadPtrs.begin()), 327 std::mem_fn(&StoreToLoadForwardingCandidate::getLoadPtr)); 328 329 const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks(); 330 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks; 331 332 std::copy_if(AllChecks.begin(), AllChecks.end(), std::back_inserter(Checks), 333 [&](const RuntimePointerChecking::PointerCheck &Check) { 334 for (auto PtrIdx1 : Check.first->Members) 335 for (auto PtrIdx2 : Check.second->Members) 336 if (needsChecking(PtrIdx1, PtrIdx2, 337 PtrsWrittenOnFwdingPath, CandLoadPtrs)) 338 return true; 339 return false; 340 }); 341 342 DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size() << "):\n"); 343 DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks)); 344 345 return Checks; 346 } 347 348 /// \brief Perform the transformation for a candidate. 349 void 350 propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand, 351 SCEVExpander &SEE) { 352 // 353 // loop: 354 // %x = load %gep_i 355 // = ... %x 356 // store %y, %gep_i_plus_1 357 // 358 // => 359 // 360 // ph: 361 // %x.initial = load %gep_0 362 // loop: 363 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop] 364 // %x = load %gep_i <---- now dead 365 // = ... %x.storeforward 366 // store %y, %gep_i_plus_1 367 368 Value *Ptr = Cand.Load->getPointerOperand(); 369 auto *PtrSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(Ptr)); 370 auto *PH = L->getLoopPreheader(); 371 Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(), 372 PH->getTerminator()); 373 Value *Initial = 374 new LoadInst(InitialPtr, "load_initial", PH->getTerminator()); 375 PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded", 376 L->getHeader()->begin()); 377 PHI->addIncoming(Initial, PH); 378 PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch()); 379 380 Cand.Load->replaceAllUsesWith(PHI); 381 } 382 383 /// \brief Top-level driver for each loop: find store->load forwarding 384 /// candidates, add run-time checks and perform transformation. 385 bool processLoop() { 386 DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName() 387 << "\" checking " << *L << "\n"); 388 // Look for store-to-load forwarding cases across the 389 // backedge. E.g.: 390 // 391 // loop: 392 // %x = load %gep_i 393 // = ... %x 394 // store %y, %gep_i_plus_1 395 // 396 // => 397 // 398 // ph: 399 // %x.initial = load %gep_0 400 // loop: 401 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop] 402 // %x = load %gep_i <---- now dead 403 // = ... %x.storeforward 404 // store %y, %gep_i_plus_1 405 406 // First start with store->load dependences. 407 auto StoreToLoadDependences = findStoreToLoadDependences(LAI); 408 if (StoreToLoadDependences.empty()) 409 return false; 410 411 // Generate an index for each load and store according to the original 412 // program order. This will be used later. 413 InstOrder = LAI.getDepChecker().generateInstructionOrderMap(); 414 415 // To keep things simple for now, remove those where the load is potentially 416 // fed by multiple stores. 417 removeDependencesFromMultipleStores(StoreToLoadDependences); 418 if (StoreToLoadDependences.empty()) 419 return false; 420 421 // Filter the candidates further. 422 SmallVector<StoreToLoadForwardingCandidate, 4> Candidates; 423 unsigned NumForwarding = 0; 424 for (const StoreToLoadForwardingCandidate Cand : StoreToLoadDependences) { 425 DEBUG(dbgs() << "Candidate " << Cand); 426 // Make sure that the stored values is available everywhere in the loop in 427 // the next iteration. 428 if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT)) 429 continue; 430 431 // Check whether the SCEV difference is the same as the induction step, 432 // thus we load the value in the next iteration. 433 if (!Cand.isDependenceDistanceOfOne(SE)) 434 continue; 435 436 ++NumForwarding; 437 DEBUG(dbgs() 438 << NumForwarding 439 << ". Valid store-to-load forwarding across the loop backedge\n"); 440 Candidates.push_back(Cand); 441 } 442 if (Candidates.empty()) 443 return false; 444 445 // Check intervening may-alias stores. These need runtime checks for alias 446 // disambiguation. 447 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks = 448 collectMemchecks(Candidates); 449 450 // Too many checks are likely to outweigh the benefits of forwarding. 451 if (Checks.size() > Candidates.size() * CheckPerElim) { 452 DEBUG(dbgs() << "Too many run-time checks needed.\n"); 453 return false; 454 } 455 456 // Point of no-return, start the transformation. First, version the loop if 457 // necessary. 458 if (!Checks.empty()) { 459 LoopVersioning LV(std::move(Checks), LAI, L, LI, DT); 460 LV.versionLoop(); 461 } 462 463 // Next, propagate the value stored by the store to the users of the load. 464 // Also for the first iteration, generate the initial value of the load. 465 SCEVExpander SEE(*SE, L->getHeader()->getModule()->getDataLayout(), 466 "storeforward"); 467 for (const auto &Cand : Candidates) 468 propagateStoredValueToLoadUsers(Cand, SEE); 469 NumLoopLoadEliminted += NumForwarding; 470 471 return true; 472 } 473 474 private: 475 Loop *L; 476 477 /// \brief Maps the load/store instructions to their index according to 478 /// program order. 479 DenseMap<Instruction *, unsigned> InstOrder; 480 481 // Analyses used. 482 LoopInfo *LI; 483 const LoopAccessInfo &LAI; 484 DominatorTree *DT; 485 ScalarEvolution *SE; 486 }; 487 488 /// \brief The pass. Most of the work is delegated to the per-loop 489 /// LoadEliminationForLoop class. 490 class LoopLoadElimination : public FunctionPass { 491 public: 492 LoopLoadElimination() : FunctionPass(ID) { 493 initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry()); 494 } 495 496 bool runOnFunction(Function &F) override { 497 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 498 auto *LAA = &getAnalysis<LoopAccessAnalysis>(); 499 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 500 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 501 502 // Build up a worklist of inner-loops to vectorize. This is necessary as the 503 // act of distributing a loop creates new loops and can invalidate iterators 504 // across the loops. 505 SmallVector<Loop *, 8> Worklist; 506 507 for (Loop *TopLevelLoop : *LI) 508 for (Loop *L : depth_first(TopLevelLoop)) 509 // We only handle inner-most loops. 510 if (L->empty()) 511 Worklist.push_back(L); 512 513 // Now walk the identified inner loops. 514 bool Changed = false; 515 for (Loop *L : Worklist) { 516 const LoopAccessInfo &LAI = LAA->getInfo(L, ValueToValueMap()); 517 // The actual work is performed by LoadEliminationForLoop. 518 LoadEliminationForLoop LEL(L, LI, LAI, DT, SE); 519 Changed |= LEL.processLoop(); 520 } 521 522 // Process each loop nest in the function. 523 return Changed; 524 } 525 526 void getAnalysisUsage(AnalysisUsage &AU) const override { 527 AU.addRequired<LoopInfoWrapperPass>(); 528 AU.addPreserved<LoopInfoWrapperPass>(); 529 AU.addRequired<LoopAccessAnalysis>(); 530 AU.addRequired<ScalarEvolutionWrapperPass>(); 531 AU.addRequired<DominatorTreeWrapperPass>(); 532 AU.addPreserved<DominatorTreeWrapperPass>(); 533 } 534 535 static char ID; 536 }; 537 } 538 539 char LoopLoadElimination::ID; 540 static const char LLE_name[] = "Loop Load Elimination"; 541 542 INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false) 543 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 544 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis) 545 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 546 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 547 INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false) 548 549 namespace llvm { 550 FunctionPass *createLoopLoadEliminationPass() { 551 return new LoopLoadElimination(); 552 } 553 } 554