1 //===- LoopLoadElimination.cpp - Loop Load Elimination Pass ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implement a loop-aware load elimination pass.
10 //
11 // It uses LoopAccessAnalysis to identify loop-carried dependences with a
12 // distance of one between stores and loads. These form the candidates for the
13 // transformation. The source value of each store then propagated to the user
14 // of the corresponding load. This makes the load dead.
15 //
16 // The pass can also version the loop and add memchecks in order to prove that
17 // may-aliasing stores can't change the value in memory before it's read by the
18 // load.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/DepthFirstIterator.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Analysis/AssumptionCache.h"
31 #include "llvm/Analysis/BlockFrequencyInfo.h"
32 #include "llvm/Analysis/GlobalsModRef.h"
33 #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
34 #include "llvm/Analysis/LoopAccessAnalysis.h"
35 #include "llvm/Analysis/LoopAnalysisManager.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/MemorySSA.h"
38 #include "llvm/Analysis/ProfileSummaryInfo.h"
39 #include "llvm/Analysis/ScalarEvolution.h"
40 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
41 #include "llvm/Analysis/TargetLibraryInfo.h"
42 #include "llvm/Analysis/TargetTransformInfo.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/Dominators.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/IR/PassManager.h"
48 #include "llvm/IR/Type.h"
49 #include "llvm/IR/Value.h"
50 #include "llvm/InitializePasses.h"
51 #include "llvm/Pass.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Scalar.h"
57 #include "llvm/Transforms/Utils.h"
58 #include "llvm/Transforms/Utils/LoopSimplify.h"
59 #include "llvm/Transforms/Utils/LoopVersioning.h"
60 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
61 #include "llvm/Transforms/Utils/SizeOpts.h"
62 #include <algorithm>
63 #include <cassert>
64 #include <forward_list>
65 #include <set>
66 #include <tuple>
67 #include <utility>
68
69 using namespace llvm;
70
71 #define LLE_OPTION "loop-load-elim"
72 #define DEBUG_TYPE LLE_OPTION
73
74 static cl::opt<unsigned> CheckPerElim(
75 "runtime-check-per-loop-load-elim", cl::Hidden,
76 cl::desc("Max number of memchecks allowed per eliminated load on average"),
77 cl::init(1));
78
79 static cl::opt<unsigned> LoadElimSCEVCheckThreshold(
80 "loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden,
81 cl::desc("The maximum number of SCEV checks allowed for Loop "
82 "Load Elimination"));
83
84 STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");
85
86 namespace {
87
88 /// Represent a store-to-forwarding candidate.
89 struct StoreToLoadForwardingCandidate {
90 LoadInst *Load;
91 StoreInst *Store;
92
StoreToLoadForwardingCandidate__anonb343eb5a0111::StoreToLoadForwardingCandidate93 StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)
94 : Load(Load), Store(Store) {}
95
96 /// Return true if the dependence from the store to the load has a
97 /// distance of one. E.g. A[i+1] = A[i]
isDependenceDistanceOfOne__anonb343eb5a0111::StoreToLoadForwardingCandidate98 bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,
99 Loop *L) const {
100 Value *LoadPtr = Load->getPointerOperand();
101 Value *StorePtr = Store->getPointerOperand();
102 Type *LoadType = getLoadStoreType(Load);
103
104 assert(LoadPtr->getType()->getPointerAddressSpace() ==
105 StorePtr->getType()->getPointerAddressSpace() &&
106 LoadType == getLoadStoreType(Store) &&
107 "Should be a known dependence");
108
109 // Currently we only support accesses with unit stride. FIXME: we should be
110 // able to handle non unit stirde as well as long as the stride is equal to
111 // the dependence distance.
112 if (getPtrStride(PSE, LoadPtr, L) != 1 ||
113 getPtrStride(PSE, StorePtr, L) != 1)
114 return false;
115
116 auto &DL = Load->getParent()->getModule()->getDataLayout();
117 unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));
118
119 auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr));
120 auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr));
121
122 // We don't need to check non-wrapping here because forward/backward
123 // dependence wouldn't be valid if these weren't monotonic accesses.
124 auto *Dist = cast<SCEVConstant>(
125 PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));
126 const APInt &Val = Dist->getAPInt();
127 return Val == TypeByteSize;
128 }
129
getLoadPtr__anonb343eb5a0111::StoreToLoadForwardingCandidate130 Value *getLoadPtr() const { return Load->getPointerOperand(); }
131
132 #ifndef NDEBUG
operator <<(raw_ostream & OS,const StoreToLoadForwardingCandidate & Cand)133 friend raw_ostream &operator<<(raw_ostream &OS,
134 const StoreToLoadForwardingCandidate &Cand) {
135 OS << *Cand.Store << " -->\n";
136 OS.indent(2) << *Cand.Load << "\n";
137 return OS;
138 }
139 #endif
140 };
141
142 } // end anonymous namespace
143
144 /// Check if the store dominates all latches, so as long as there is no
145 /// intervening store this value will be loaded in the next iteration.
doesStoreDominatesAllLatches(BasicBlock * StoreBlock,Loop * L,DominatorTree * DT)146 static bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L,
147 DominatorTree *DT) {
148 SmallVector<BasicBlock *, 8> Latches;
149 L->getLoopLatches(Latches);
150 return llvm::all_of(Latches, [&](const BasicBlock *Latch) {
151 return DT->dominates(StoreBlock, Latch);
152 });
153 }
154
155 /// Return true if the load is not executed on all paths in the loop.
isLoadConditional(LoadInst * Load,Loop * L)156 static bool isLoadConditional(LoadInst *Load, Loop *L) {
157 return Load->getParent() != L->getHeader();
158 }
159
160 namespace {
161
162 /// The per-loop class that does most of the work.
163 class LoadEliminationForLoop {
164 public:
LoadEliminationForLoop(Loop * L,LoopInfo * LI,const LoopAccessInfo & LAI,DominatorTree * DT,BlockFrequencyInfo * BFI,ProfileSummaryInfo * PSI)165 LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,
166 DominatorTree *DT, BlockFrequencyInfo *BFI,
167 ProfileSummaryInfo* PSI)
168 : L(L), LI(LI), LAI(LAI), DT(DT), BFI(BFI), PSI(PSI), PSE(LAI.getPSE()) {}
169
170 /// Look through the loop-carried and loop-independent dependences in
171 /// this loop and find store->load dependences.
172 ///
173 /// Note that no candidate is returned if LAA has failed to analyze the loop
174 /// (e.g. if it's not bottom-tested, contains volatile memops, etc.)
175 std::forward_list<StoreToLoadForwardingCandidate>
findStoreToLoadDependences(const LoopAccessInfo & LAI)176 findStoreToLoadDependences(const LoopAccessInfo &LAI) {
177 std::forward_list<StoreToLoadForwardingCandidate> Candidates;
178
179 const auto *Deps = LAI.getDepChecker().getDependences();
180 if (!Deps)
181 return Candidates;
182
183 // Find store->load dependences (consequently true dep). Both lexically
184 // forward and backward dependences qualify. Disqualify loads that have
185 // other unknown dependences.
186
187 SmallPtrSet<Instruction *, 4> LoadsWithUnknownDepedence;
188
189 for (const auto &Dep : *Deps) {
190 Instruction *Source = Dep.getSource(LAI);
191 Instruction *Destination = Dep.getDestination(LAI);
192
193 if (Dep.Type == MemoryDepChecker::Dependence::Unknown) {
194 if (isa<LoadInst>(Source))
195 LoadsWithUnknownDepedence.insert(Source);
196 if (isa<LoadInst>(Destination))
197 LoadsWithUnknownDepedence.insert(Destination);
198 continue;
199 }
200
201 if (Dep.isBackward())
202 // Note that the designations source and destination follow the program
203 // order, i.e. source is always first. (The direction is given by the
204 // DepType.)
205 std::swap(Source, Destination);
206 else
207 assert(Dep.isForward() && "Needs to be a forward dependence");
208
209 auto *Store = dyn_cast<StoreInst>(Source);
210 if (!Store)
211 continue;
212 auto *Load = dyn_cast<LoadInst>(Destination);
213 if (!Load)
214 continue;
215
216 // Only progagate the value if they are of the same type.
217 if (Store->getPointerOperandType() != Load->getPointerOperandType())
218 continue;
219
220 Candidates.emplace_front(Load, Store);
221 }
222
223 if (!LoadsWithUnknownDepedence.empty())
224 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
225 return LoadsWithUnknownDepedence.count(C.Load);
226 });
227
228 return Candidates;
229 }
230
231 /// Return the index of the instruction according to program order.
getInstrIndex(Instruction * Inst)232 unsigned getInstrIndex(Instruction *Inst) {
233 auto I = InstOrder.find(Inst);
234 assert(I != InstOrder.end() && "No index for instruction");
235 return I->second;
236 }
237
238 /// If a load has multiple candidates associated (i.e. different
239 /// stores), it means that it could be forwarding from multiple stores
240 /// depending on control flow. Remove these candidates.
241 ///
242 /// Here, we rely on LAA to include the relevant loop-independent dependences.
243 /// LAA is known to omit these in the very simple case when the read and the
244 /// write within an alias set always takes place using the *same* pointer.
245 ///
246 /// However, we know that this is not the case here, i.e. we can rely on LAA
247 /// to provide us with loop-independent dependences for the cases we're
248 /// interested. Consider the case for example where a loop-independent
249 /// dependece S1->S2 invalidates the forwarding S3->S2.
250 ///
251 /// A[i] = ... (S1)
252 /// ... = A[i] (S2)
253 /// A[i+1] = ... (S3)
254 ///
255 /// LAA will perform dependence analysis here because there are two
256 /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).
removeDependencesFromMultipleStores(std::forward_list<StoreToLoadForwardingCandidate> & Candidates)257 void removeDependencesFromMultipleStores(
258 std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
259 // If Store is nullptr it means that we have multiple stores forwarding to
260 // this store.
261 using LoadToSingleCandT =
262 DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>;
263 LoadToSingleCandT LoadToSingleCand;
264
265 for (const auto &Cand : Candidates) {
266 bool NewElt;
267 LoadToSingleCandT::iterator Iter;
268
269 std::tie(Iter, NewElt) =
270 LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
271 if (!NewElt) {
272 const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
273 // Already multiple stores forward to this load.
274 if (OtherCand == nullptr)
275 continue;
276
277 // Handle the very basic case when the two stores are in the same block
278 // so deciding which one forwards is easy. The later one forwards as
279 // long as they both have a dependence distance of one to the load.
280 if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
281 Cand.isDependenceDistanceOfOne(PSE, L) &&
282 OtherCand->isDependenceDistanceOfOne(PSE, L)) {
283 // They are in the same block, the later one will forward to the load.
284 if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
285 OtherCand = &Cand;
286 } else
287 OtherCand = nullptr;
288 }
289 }
290
291 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
292 if (LoadToSingleCand[Cand.Load] != &Cand) {
293 LLVM_DEBUG(
294 dbgs() << "Removing from candidates: \n"
295 << Cand
296 << " The load may have multiple stores forwarding to "
297 << "it\n");
298 return true;
299 }
300 return false;
301 });
302 }
303
304 /// Given two pointers operations by their RuntimePointerChecking
305 /// indices, return true if they require an alias check.
306 ///
307 /// We need a check if one is a pointer for a candidate load and the other is
308 /// a pointer for a possibly intervening store.
needsChecking(unsigned PtrIdx1,unsigned PtrIdx2,const SmallPtrSetImpl<Value * > & PtrsWrittenOnFwdingPath,const SmallPtrSetImpl<Value * > & CandLoadPtrs)309 bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
310 const SmallPtrSetImpl<Value *> &PtrsWrittenOnFwdingPath,
311 const SmallPtrSetImpl<Value *> &CandLoadPtrs) {
312 Value *Ptr1 =
313 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;
314 Value *Ptr2 =
315 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;
316 return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
317 (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
318 }
319
320 /// Return pointers that are possibly written to on the path from a
321 /// forwarding store to a load.
322 ///
323 /// These pointers need to be alias-checked against the forwarding candidates.
findPointersWrittenOnForwardingPath(const SmallVectorImpl<StoreToLoadForwardingCandidate> & Candidates)324 SmallPtrSet<Value *, 4> findPointersWrittenOnForwardingPath(
325 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
326 // From FirstStore to LastLoad neither of the elimination candidate loads
327 // should overlap with any of the stores.
328 //
329 // E.g.:
330 //
331 // st1 C[i]
332 // ld1 B[i] <-------,
333 // ld0 A[i] <----, | * LastLoad
334 // ... | |
335 // st2 E[i] | |
336 // st3 B[i+1] -- | -' * FirstStore
337 // st0 A[i+1] ---'
338 // st4 D[i]
339 //
340 // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
341 // ld0.
342
343 LoadInst *LastLoad =
344 std::max_element(Candidates.begin(), Candidates.end(),
345 [&](const StoreToLoadForwardingCandidate &A,
346 const StoreToLoadForwardingCandidate &B) {
347 return getInstrIndex(A.Load) < getInstrIndex(B.Load);
348 })
349 ->Load;
350 StoreInst *FirstStore =
351 std::min_element(Candidates.begin(), Candidates.end(),
352 [&](const StoreToLoadForwardingCandidate &A,
353 const StoreToLoadForwardingCandidate &B) {
354 return getInstrIndex(A.Store) <
355 getInstrIndex(B.Store);
356 })
357 ->Store;
358
359 // We're looking for stores after the first forwarding store until the end
360 // of the loop, then from the beginning of the loop until the last
361 // forwarded-to load. Collect the pointer for the stores.
362 SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath;
363
364 auto InsertStorePtr = [&](Instruction *I) {
365 if (auto *S = dyn_cast<StoreInst>(I))
366 PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
367 };
368 const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
369 std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
370 MemInstrs.end(), InsertStorePtr);
371 std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
372 InsertStorePtr);
373
374 return PtrsWrittenOnFwdingPath;
375 }
376
377 /// Determine the pointer alias checks to prove that there are no
378 /// intervening stores.
collectMemchecks(const SmallVectorImpl<StoreToLoadForwardingCandidate> & Candidates)379 SmallVector<RuntimePointerCheck, 4> collectMemchecks(
380 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
381
382 SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath =
383 findPointersWrittenOnForwardingPath(Candidates);
384
385 // Collect the pointers of the candidate loads.
386 SmallPtrSet<Value *, 4> CandLoadPtrs;
387 for (const auto &Candidate : Candidates)
388 CandLoadPtrs.insert(Candidate.getLoadPtr());
389
390 const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
391 SmallVector<RuntimePointerCheck, 4> Checks;
392
393 copy_if(AllChecks, std::back_inserter(Checks),
394 [&](const RuntimePointerCheck &Check) {
395 for (auto PtrIdx1 : Check.first->Members)
396 for (auto PtrIdx2 : Check.second->Members)
397 if (needsChecking(PtrIdx1, PtrIdx2, PtrsWrittenOnFwdingPath,
398 CandLoadPtrs))
399 return true;
400 return false;
401 });
402
403 LLVM_DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size()
404 << "):\n");
405 LLVM_DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));
406
407 return Checks;
408 }
409
410 /// Perform the transformation for a candidate.
411 void
propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate & Cand,SCEVExpander & SEE)412 propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
413 SCEVExpander &SEE) {
414 // loop:
415 // %x = load %gep_i
416 // = ... %x
417 // store %y, %gep_i_plus_1
418 //
419 // =>
420 //
421 // ph:
422 // %x.initial = load %gep_0
423 // loop:
424 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
425 // %x = load %gep_i <---- now dead
426 // = ... %x.storeforward
427 // store %y, %gep_i_plus_1
428
429 Value *Ptr = Cand.Load->getPointerOperand();
430 auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
431 auto *PH = L->getLoopPreheader();
432 assert(PH && "Preheader should exist!");
433 Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
434 PH->getTerminator());
435 Value *Initial = new LoadInst(
436 Cand.Load->getType(), InitialPtr, "load_initial",
437 /* isVolatile */ false, Cand.Load->getAlign(), PH->getTerminator());
438
439 PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded",
440 &L->getHeader()->front());
441 PHI->addIncoming(Initial, PH);
442 PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch());
443
444 Cand.Load->replaceAllUsesWith(PHI);
445 }
446
447 /// Top-level driver for each loop: find store->load forwarding
448 /// candidates, add run-time checks and perform transformation.
processLoop()449 bool processLoop() {
450 LLVM_DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
451 << "\" checking " << *L << "\n");
452
453 // Look for store-to-load forwarding cases across the
454 // backedge. E.g.:
455 //
456 // loop:
457 // %x = load %gep_i
458 // = ... %x
459 // store %y, %gep_i_plus_1
460 //
461 // =>
462 //
463 // ph:
464 // %x.initial = load %gep_0
465 // loop:
466 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
467 // %x = load %gep_i <---- now dead
468 // = ... %x.storeforward
469 // store %y, %gep_i_plus_1
470
471 // First start with store->load dependences.
472 auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
473 if (StoreToLoadDependences.empty())
474 return false;
475
476 // Generate an index for each load and store according to the original
477 // program order. This will be used later.
478 InstOrder = LAI.getDepChecker().generateInstructionOrderMap();
479
480 // To keep things simple for now, remove those where the load is potentially
481 // fed by multiple stores.
482 removeDependencesFromMultipleStores(StoreToLoadDependences);
483 if (StoreToLoadDependences.empty())
484 return false;
485
486 // Filter the candidates further.
487 SmallVector<StoreToLoadForwardingCandidate, 4> Candidates;
488 for (const StoreToLoadForwardingCandidate &Cand : StoreToLoadDependences) {
489 LLVM_DEBUG(dbgs() << "Candidate " << Cand);
490
491 // Make sure that the stored values is available everywhere in the loop in
492 // the next iteration.
493 if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
494 continue;
495
496 // If the load is conditional we can't hoist its 0-iteration instance to
497 // the preheader because that would make it unconditional. Thus we would
498 // access a memory location that the original loop did not access.
499 if (isLoadConditional(Cand.Load, L))
500 continue;
501
502 // Check whether the SCEV difference is the same as the induction step,
503 // thus we load the value in the next iteration.
504 if (!Cand.isDependenceDistanceOfOne(PSE, L))
505 continue;
506
507 assert(isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Load->getPointerOperand())) &&
508 "Loading from something other than indvar?");
509 assert(
510 isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Store->getPointerOperand())) &&
511 "Storing to something other than indvar?");
512
513 Candidates.push_back(Cand);
514 LLVM_DEBUG(
515 dbgs()
516 << Candidates.size()
517 << ". Valid store-to-load forwarding across the loop backedge\n");
518 }
519 if (Candidates.empty())
520 return false;
521
522 // Check intervening may-alias stores. These need runtime checks for alias
523 // disambiguation.
524 SmallVector<RuntimePointerCheck, 4> Checks = collectMemchecks(Candidates);
525
526 // Too many checks are likely to outweigh the benefits of forwarding.
527 if (Checks.size() > Candidates.size() * CheckPerElim) {
528 LLVM_DEBUG(dbgs() << "Too many run-time checks needed.\n");
529 return false;
530 }
531
532 if (LAI.getPSE().getUnionPredicate().getComplexity() >
533 LoadElimSCEVCheckThreshold) {
534 LLVM_DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
535 return false;
536 }
537
538 if (!L->isLoopSimplifyForm()) {
539 LLVM_DEBUG(dbgs() << "Loop is not is loop-simplify form");
540 return false;
541 }
542
543 if (!Checks.empty() || !LAI.getPSE().getUnionPredicate().isAlwaysTrue()) {
544 if (LAI.hasConvergentOp()) {
545 LLVM_DEBUG(dbgs() << "Versioning is needed but not allowed with "
546 "convergent calls\n");
547 return false;
548 }
549
550 auto *HeaderBB = L->getHeader();
551 auto *F = HeaderBB->getParent();
552 bool OptForSize = F->hasOptSize() ||
553 llvm::shouldOptimizeForSize(HeaderBB, PSI, BFI,
554 PGSOQueryType::IRPass);
555 if (OptForSize) {
556 LLVM_DEBUG(
557 dbgs() << "Versioning is needed but not allowed when optimizing "
558 "for size.\n");
559 return false;
560 }
561
562 // Point of no-return, start the transformation. First, version the loop
563 // if necessary.
564
565 LoopVersioning LV(LAI, Checks, L, LI, DT, PSE.getSE());
566 LV.versionLoop();
567
568 // After versioning, some of the candidates' pointers could stop being
569 // SCEVAddRecs. We need to filter them out.
570 auto NoLongerGoodCandidate = [this](
571 const StoreToLoadForwardingCandidate &Cand) {
572 return !isa<SCEVAddRecExpr>(
573 PSE.getSCEV(Cand.Load->getPointerOperand())) ||
574 !isa<SCEVAddRecExpr>(
575 PSE.getSCEV(Cand.Store->getPointerOperand()));
576 };
577 llvm::erase_if(Candidates, NoLongerGoodCandidate);
578 }
579
580 // Next, propagate the value stored by the store to the users of the load.
581 // Also for the first iteration, generate the initial value of the load.
582 SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(),
583 "storeforward");
584 for (const auto &Cand : Candidates)
585 propagateStoredValueToLoadUsers(Cand, SEE);
586 NumLoopLoadEliminted += Candidates.size();
587
588 return true;
589 }
590
591 private:
592 Loop *L;
593
594 /// Maps the load/store instructions to their index according to
595 /// program order.
596 DenseMap<Instruction *, unsigned> InstOrder;
597
598 // Analyses used.
599 LoopInfo *LI;
600 const LoopAccessInfo &LAI;
601 DominatorTree *DT;
602 BlockFrequencyInfo *BFI;
603 ProfileSummaryInfo *PSI;
604 PredicatedScalarEvolution PSE;
605 };
606
607 } // end anonymous namespace
608
609 static bool
eliminateLoadsAcrossLoops(Function & F,LoopInfo & LI,DominatorTree & DT,BlockFrequencyInfo * BFI,ProfileSummaryInfo * PSI,ScalarEvolution * SE,AssumptionCache * AC,function_ref<const LoopAccessInfo & (Loop &)> GetLAI)610 eliminateLoadsAcrossLoops(Function &F, LoopInfo &LI, DominatorTree &DT,
611 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
612 ScalarEvolution *SE, AssumptionCache *AC,
613 function_ref<const LoopAccessInfo &(Loop &)> GetLAI) {
614 // Build up a worklist of inner-loops to transform to avoid iterator
615 // invalidation.
616 // FIXME: This logic comes from other passes that actually change the loop
617 // nest structure. It isn't clear this is necessary (or useful) for a pass
618 // which merely optimizes the use of loads in a loop.
619 SmallVector<Loop *, 8> Worklist;
620
621 bool Changed = false;
622
623 for (Loop *TopLevelLoop : LI)
624 for (Loop *L : depth_first(TopLevelLoop)) {
625 Changed |= simplifyLoop(L, &DT, &LI, SE, AC, /*MSSAU*/ nullptr, false);
626 // We only handle inner-most loops.
627 if (L->isInnermost())
628 Worklist.push_back(L);
629 }
630
631 // Now walk the identified inner loops.
632 for (Loop *L : Worklist) {
633 // Match historical behavior
634 if (!L->isRotatedForm() || !L->getExitingBlock())
635 continue;
636 // The actual work is performed by LoadEliminationForLoop.
637 LoadEliminationForLoop LEL(L, &LI, GetLAI(*L), &DT, BFI, PSI);
638 Changed |= LEL.processLoop();
639 }
640 return Changed;
641 }
642
643 namespace {
644
645 /// The pass. Most of the work is delegated to the per-loop
646 /// LoadEliminationForLoop class.
647 class LoopLoadElimination : public FunctionPass {
648 public:
649 static char ID;
650
LoopLoadElimination()651 LoopLoadElimination() : FunctionPass(ID) {
652 initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry());
653 }
654
runOnFunction(Function & F)655 bool runOnFunction(Function &F) override {
656 if (skipFunction(F))
657 return false;
658
659 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
660 auto &LAA = getAnalysis<LoopAccessLegacyAnalysis>();
661 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
662 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
663 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
664 &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
665 nullptr;
666 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
667
668 // Process each loop nest in the function.
669 return eliminateLoadsAcrossLoops(
670 F, LI, DT, BFI, PSI, SE, /*AC*/ nullptr,
671 [&LAA](Loop &L) -> const LoopAccessInfo & { return LAA.getInfo(&L); });
672 }
673
getAnalysisUsage(AnalysisUsage & AU) const674 void getAnalysisUsage(AnalysisUsage &AU) const override {
675 AU.addRequiredID(LoopSimplifyID);
676 AU.addRequired<LoopInfoWrapperPass>();
677 AU.addPreserved<LoopInfoWrapperPass>();
678 AU.addRequired<LoopAccessLegacyAnalysis>();
679 AU.addRequired<ScalarEvolutionWrapperPass>();
680 AU.addRequired<DominatorTreeWrapperPass>();
681 AU.addPreserved<DominatorTreeWrapperPass>();
682 AU.addPreserved<GlobalsAAWrapperPass>();
683 AU.addRequired<ProfileSummaryInfoWrapperPass>();
684 LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
685 }
686 };
687
688 } // end anonymous namespace
689
690 char LoopLoadElimination::ID;
691
692 static const char LLE_name[] = "Loop Load Elimination";
693
INITIALIZE_PASS_BEGIN(LoopLoadElimination,LLE_OPTION,LLE_name,false,false)694 INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
695 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
696 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
697 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
698 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
699 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
700 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
701 INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
702 INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
703
704 FunctionPass *llvm::createLoopLoadEliminationPass() {
705 return new LoopLoadElimination();
706 }
707
run(Function & F,FunctionAnalysisManager & AM)708 PreservedAnalyses LoopLoadEliminationPass::run(Function &F,
709 FunctionAnalysisManager &AM) {
710 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
711 auto &LI = AM.getResult<LoopAnalysis>(F);
712 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
713 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
714 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
715 auto &AA = AM.getResult<AAManager>(F);
716 auto &AC = AM.getResult<AssumptionAnalysis>(F);
717 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
718 auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
719 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
720 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
721 MemorySSA *MSSA = EnableMSSALoopDependency
722 ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
723 : nullptr;
724
725 auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
726 bool Changed = eliminateLoadsAcrossLoops(
727 F, LI, DT, BFI, PSI, &SE, &AC, [&](Loop &L) -> const LoopAccessInfo & {
728 LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE,
729 TLI, TTI, nullptr, MSSA};
730 return LAM.getResult<LoopAccessAnalysis>(L, AR);
731 });
732
733 if (!Changed)
734 return PreservedAnalyses::all();
735
736 PreservedAnalyses PA;
737 return PA;
738 }
739