1 //===- LoopLoadElimination.cpp - Loop Load Elimination Pass ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implement a loop-aware load elimination pass.
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.
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
21 //===----------------------------------------------------------------------===//
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>
34 #define LLE_OPTION "loop-load-elim"
35 #define DEBUG_TYPE LLE_OPTION
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"),
44 STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");
48 /// \brief Represent a store-to-forwarding candidate.
49 struct StoreToLoadForwardingCandidate {
53 StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)
54 : Load(Load), Store(Store) {}
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();
64 assert(LoadPtrType->getPointerAddressSpace() ==
65 StorePtr->getType()->getPointerAddressSpace() &&
66 LoadType == StorePtr->getType()->getPointerElementType() &&
67 "Should be a known dependence");
69 auto &DL = Load->getParent()->getModule()->getDataLayout();
70 unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));
72 auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
73 auto *StorePtrSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
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.
78 cast<SCEVConstant>(SE->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));
79 const APInt &Val = Dist->getValue()->getValue();
80 return Val.abs() == TypeByteSize;
83 Value *getLoadPtr() const { return Load->getPointerOperand(); }
86 friend raw_ostream &operator<<(raw_ostream &OS,
87 const StoreToLoadForwardingCandidate &Cand) {
88 OS << *Cand.Store << " -->\n";
89 OS.indent(2) << *Cand.Load << "\n";
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,
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);
107 /// \brief The per-loop class that does most of the work.
108 class LoadEliminationForLoop {
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) {}
114 /// \brief Look through the loop-carried and loop-independent dependences in
115 /// this loop and find store->load dependences.
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;
123 const auto *Deps = LAI.getDepChecker().getDependences();
127 // Find store->load dependences (consequently true dep). Both lexically
128 // forward and backward dependences qualify. Disqualify loads that have
129 // other unknown dependences.
131 SmallSet<Instruction *, 4> LoadsWithUnknownDepedence;
133 for (const auto &Dep : *Deps) {
134 Instruction *Source = Dep.getSource(LAI);
135 Instruction *Destination = Dep.getDestination(LAI);
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);
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
149 std::swap(Source, Destination);
151 assert(Dep.isForward() && "Needs to be a forward dependence");
153 auto *Store = dyn_cast<StoreInst>(Source);
156 auto *Load = dyn_cast<LoadInst>(Destination);
159 Candidates.emplace_front(Load, Store);
162 if (!LoadsWithUnknownDepedence.empty())
163 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
164 return LoadsWithUnknownDepedence.count(C.Load);
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");
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.
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.
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.
192 /// A[i+1] = ... (S3)
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
200 typedef DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>
202 LoadToSingleCandT LoadToSingleCand;
204 for (const auto &Cand : Candidates) {
206 LoadToSingleCandT::iterator Iter;
208 std::tie(Iter, NewElt) =
209 LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
211 const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
212 // Already multiple stores forward to this load.
213 if (OtherCand == nullptr)
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))
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 "
241 /// \brief Given two pointers operations by their RuntimePointerChecking
242 /// indices, return true if they require an alias check.
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) {
250 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;
252 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;
253 return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
254 (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
257 /// \brief Return pointers that are possibly written to on the path from a
258 /// forwarding store to a load.
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.
269 // ld1 B[i] <-------,
270 // ld0 A[i] <----, | * LastLoad
273 // st3 B[i+1] -- | -' * FirstStore
277 // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
281 std::max_element(Candidates.begin(), Candidates.end(),
282 [&](const StoreToLoadForwardingCandidate &A,
283 const StoreToLoadForwardingCandidate &B) {
284 return getInstrIndex(A.Load) < getInstrIndex(B.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);
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;
301 auto InsertStorePtr = [&](Instruction *I) {
302 if (auto *S = dyn_cast<StoreInst>(I))
303 PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
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)],
311 return PtrsWrittenOnFwdingPath;
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) {
319 SmallSet<Value *, 4> PtrsWrittenOnFwdingPath =
320 findPointersWrittenOnForwardingPath(Candidates);
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));
329 const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
330 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks;
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))
342 DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size() << "):\n");
343 DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));
348 /// \brief Perform the transformation for a candidate.
350 propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
356 // store %y, %gep_i_plus_1
361 // %x.initial = load %gep_0
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
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());
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());
380 Cand.Load->replaceAllUsesWith(PHI);
383 /// \brief Top-level driver for each loop: find store->load forwarding
384 /// candidates, add run-time checks and perform transformation.
386 DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
387 << "\" checking " << *L << "\n");
388 // Look for store-to-load forwarding cases across the
394 // store %y, %gep_i_plus_1
399 // %x.initial = load %gep_0
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
406 // First start with store->load dependences.
407 auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
408 if (StoreToLoadDependences.empty())
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();
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())
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))
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))
439 << ". Valid store-to-load forwarding across the loop backedge\n");
440 Candidates.push_back(Cand);
442 if (Candidates.empty())
445 // Check intervening may-alias stores. These need runtime checks for alias
447 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks =
448 collectMemchecks(Candidates);
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");
456 // Point of no-return, start the transformation. First, version the loop if
458 if (!Checks.empty()) {
459 LoopVersioning LV(std::move(Checks), LAI, L, LI, DT);
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(),
467 for (const auto &Cand : Candidates)
468 propagateStoredValueToLoadUsers(Cand, SEE);
469 NumLoopLoadEliminted += NumForwarding;
477 /// \brief Maps the load/store instructions to their index according to
479 DenseMap<Instruction *, unsigned> InstOrder;
483 const LoopAccessInfo &LAI;
488 /// \brief The pass. Most of the work is delegated to the per-loop
489 /// LoadEliminationForLoop class.
490 class LoopLoadElimination : public FunctionPass {
492 LoopLoadElimination() : FunctionPass(ID) {
493 initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry());
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();
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
505 SmallVector<Loop *, 8> Worklist;
507 for (Loop *TopLevelLoop : *LI)
508 for (Loop *L : depth_first(TopLevelLoop))
509 // We only handle inner-most loops.
511 Worklist.push_back(L);
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();
522 // Process each loop nest in the function.
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>();
539 char LoopLoadElimination::ID;
540 static const char LLE_name[] = "Loop Load Elimination";
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)
550 FunctionPass *createLoopLoadEliminationPass() {
551 return new LoopLoadElimination();