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