LLVM 19.0.0git
LoopLoadElimination.cpp
Go to the documentation of this file.
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
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/Statistic.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/Dominators.h"
45#include "llvm/IR/Module.h"
46#include "llvm/IR/PassManager.h"
47#include "llvm/IR/Type.h"
48#include "llvm/IR/Value.h"
51#include "llvm/Support/Debug.h"
58#include <algorithm>
59#include <cassert>
60#include <forward_list>
61#include <tuple>
62#include <utility>
63
64using namespace llvm;
65
66#define LLE_OPTION "loop-load-elim"
67#define DEBUG_TYPE LLE_OPTION
68
70 "runtime-check-per-loop-load-elim", cl::Hidden,
71 cl::desc("Max number of memchecks allowed per eliminated load on average"),
72 cl::init(1));
73
75 "loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden,
76 cl::desc("The maximum number of SCEV checks allowed for Loop "
77 "Load Elimination"));
78
79STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");
80
81namespace {
82
83/// Represent a store-to-forwarding candidate.
84struct StoreToLoadForwardingCandidate {
85 LoadInst *Load;
86 StoreInst *Store;
87
88 StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)
89 : Load(Load), Store(Store) {}
90
91 /// Return true if the dependence from the store to the load has an
92 /// absolute distance of one.
93 /// E.g. A[i+1] = A[i] (or A[i-1] = A[i] for descending loop)
94 bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,
95 Loop *L) const {
96 Value *LoadPtr = Load->getPointerOperand();
97 Value *StorePtr = Store->getPointerOperand();
98 Type *LoadType = getLoadStoreType(Load);
99 auto &DL = Load->getParent()->getModule()->getDataLayout();
100
101 assert(LoadPtr->getType()->getPointerAddressSpace() ==
102 StorePtr->getType()->getPointerAddressSpace() &&
103 DL.getTypeSizeInBits(LoadType) ==
104 DL.getTypeSizeInBits(getLoadStoreType(Store)) &&
105 "Should be a known dependence");
106
107 int64_t StrideLoad = getPtrStride(PSE, LoadType, LoadPtr, L).value_or(0);
108 int64_t StrideStore = getPtrStride(PSE, LoadType, StorePtr, L).value_or(0);
109 if (!StrideLoad || !StrideStore || StrideLoad != StrideStore)
110 return false;
111
112 // TODO: This check for stride values other than 1 and -1 can be eliminated.
113 // However, doing so may cause the LoopAccessAnalysis to overcompensate,
114 // generating numerous non-wrap runtime checks that may undermine the
115 // benefits of load elimination. To safely implement support for non-unit
116 // strides, we would need to ensure either that the processed case does not
117 // require these additional checks, or improve the LAA to handle them more
118 // efficiently, or potentially both.
119 if (std::abs(StrideLoad) != 1)
120 return false;
121
122 unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));
123
124 auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr));
125 auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr));
126
127 // We don't need to check non-wrapping here because forward/backward
128 // dependence wouldn't be valid if these weren't monotonic accesses.
129 auto *Dist = dyn_cast<SCEVConstant>(
130 PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));
131 if (!Dist)
132 return false;
133 const APInt &Val = Dist->getAPInt();
134 return Val == TypeByteSize * StrideLoad;
135 }
136
137 Value *getLoadPtr() const { return Load->getPointerOperand(); }
138
139#ifndef NDEBUG
141 const StoreToLoadForwardingCandidate &Cand) {
142 OS << *Cand.Store << " -->\n";
143 OS.indent(2) << *Cand.Load << "\n";
144 return OS;
145 }
146#endif
147};
148
149} // end anonymous namespace
150
151/// Check if the store dominates all latches, so as long as there is no
152/// intervening store this value will be loaded in the next iteration.
153static bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L,
154 DominatorTree *DT) {
156 L->getLoopLatches(Latches);
157 return llvm::all_of(Latches, [&](const BasicBlock *Latch) {
158 return DT->dominates(StoreBlock, Latch);
159 });
160}
161
162/// Return true if the load is not executed on all paths in the loop.
163static bool isLoadConditional(LoadInst *Load, Loop *L) {
164 return Load->getParent() != L->getHeader();
165}
166
167namespace {
168
169/// The per-loop class that does most of the work.
170class LoadEliminationForLoop {
171public:
172 LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,
175 : L(L), LI(LI), LAI(LAI), DT(DT), BFI(BFI), PSI(PSI), PSE(LAI.getPSE()) {}
176
177 /// Look through the loop-carried and loop-independent dependences in
178 /// this loop and find store->load dependences.
179 ///
180 /// Note that no candidate is returned if LAA has failed to analyze the loop
181 /// (e.g. if it's not bottom-tested, contains volatile memops, etc.)
182 std::forward_list<StoreToLoadForwardingCandidate>
183 findStoreToLoadDependences(const LoopAccessInfo &LAI) {
184 std::forward_list<StoreToLoadForwardingCandidate> Candidates;
185
186 const auto *Deps = LAI.getDepChecker().getDependences();
187 if (!Deps)
188 return Candidates;
189
190 // Find store->load dependences (consequently true dep). Both lexically
191 // forward and backward dependences qualify. Disqualify loads that have
192 // other unknown dependences.
193
194 SmallPtrSet<Instruction *, 4> LoadsWithUnknownDepedence;
195
196 for (const auto &Dep : *Deps) {
197 Instruction *Source = Dep.getSource(LAI);
198 Instruction *Destination = Dep.getDestination(LAI);
199
202 if (isa<LoadInst>(Source))
203 LoadsWithUnknownDepedence.insert(Source);
204 if (isa<LoadInst>(Destination))
205 LoadsWithUnknownDepedence.insert(Destination);
206 continue;
207 }
208
209 if (Dep.isBackward())
210 // Note that the designations source and destination follow the program
211 // order, i.e. source is always first. (The direction is given by the
212 // DepType.)
213 std::swap(Source, Destination);
214 else
215 assert(Dep.isForward() && "Needs to be a forward dependence");
216
217 auto *Store = dyn_cast<StoreInst>(Source);
218 if (!Store)
219 continue;
220 auto *Load = dyn_cast<LoadInst>(Destination);
221 if (!Load)
222 continue;
223
224 // Only propagate if the stored values are bit/pointer castable.
227 Store->getParent()->getModule()->getDataLayout()))
228 continue;
229
230 Candidates.emplace_front(Load, Store);
231 }
232
233 if (!LoadsWithUnknownDepedence.empty())
234 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
235 return LoadsWithUnknownDepedence.count(C.Load);
236 });
237
238 return Candidates;
239 }
240
241 /// Return the index of the instruction according to program order.
242 unsigned getInstrIndex(Instruction *Inst) {
243 auto I = InstOrder.find(Inst);
244 assert(I != InstOrder.end() && "No index for instruction");
245 return I->second;
246 }
247
248 /// If a load has multiple candidates associated (i.e. different
249 /// stores), it means that it could be forwarding from multiple stores
250 /// depending on control flow. Remove these candidates.
251 ///
252 /// Here, we rely on LAA to include the relevant loop-independent dependences.
253 /// LAA is known to omit these in the very simple case when the read and the
254 /// write within an alias set always takes place using the *same* pointer.
255 ///
256 /// However, we know that this is not the case here, i.e. we can rely on LAA
257 /// to provide us with loop-independent dependences for the cases we're
258 /// interested. Consider the case for example where a loop-independent
259 /// dependece S1->S2 invalidates the forwarding S3->S2.
260 ///
261 /// A[i] = ... (S1)
262 /// ... = A[i] (S2)
263 /// A[i+1] = ... (S3)
264 ///
265 /// LAA will perform dependence analysis here because there are two
266 /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).
267 void removeDependencesFromMultipleStores(
268 std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
269 // If Store is nullptr it means that we have multiple stores forwarding to
270 // this store.
271 using LoadToSingleCandT =
273 LoadToSingleCandT LoadToSingleCand;
274
275 for (const auto &Cand : Candidates) {
276 bool NewElt;
277 LoadToSingleCandT::iterator Iter;
278
279 std::tie(Iter, NewElt) =
280 LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
281 if (!NewElt) {
282 const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
283 // Already multiple stores forward to this load.
284 if (OtherCand == nullptr)
285 continue;
286
287 // Handle the very basic case when the two stores are in the same block
288 // so deciding which one forwards is easy. The later one forwards as
289 // long as they both have a dependence distance of one to the load.
290 if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
291 Cand.isDependenceDistanceOfOne(PSE, L) &&
292 OtherCand->isDependenceDistanceOfOne(PSE, L)) {
293 // They are in the same block, the later one will forward to the load.
294 if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
295 OtherCand = &Cand;
296 } else
297 OtherCand = nullptr;
298 }
299 }
300
301 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
302 if (LoadToSingleCand[Cand.Load] != &Cand) {
303 LLVM_DEBUG(
304 dbgs() << "Removing from candidates: \n"
305 << Cand
306 << " The load may have multiple stores forwarding to "
307 << "it\n");
308 return true;
309 }
310 return false;
311 });
312 }
313
314 /// Given two pointers operations by their RuntimePointerChecking
315 /// indices, return true if they require an alias check.
316 ///
317 /// We need a check if one is a pointer for a candidate load and the other is
318 /// a pointer for a possibly intervening store.
319 bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
320 const SmallPtrSetImpl<Value *> &PtrsWrittenOnFwdingPath,
321 const SmallPtrSetImpl<Value *> &CandLoadPtrs) {
322 Value *Ptr1 =
324 Value *Ptr2 =
326 return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
327 (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
328 }
329
330 /// Return pointers that are possibly written to on the path from a
331 /// forwarding store to a load.
332 ///
333 /// These pointers need to be alias-checked against the forwarding candidates.
334 SmallPtrSet<Value *, 4> findPointersWrittenOnForwardingPath(
336 // From FirstStore to LastLoad neither of the elimination candidate loads
337 // should overlap with any of the stores.
338 //
339 // E.g.:
340 //
341 // st1 C[i]
342 // ld1 B[i] <-------,
343 // ld0 A[i] <----, | * LastLoad
344 // ... | |
345 // st2 E[i] | |
346 // st3 B[i+1] -- | -' * FirstStore
347 // st0 A[i+1] ---'
348 // st4 D[i]
349 //
350 // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
351 // ld0.
352
353 LoadInst *LastLoad =
354 llvm::max_element(Candidates,
355 [&](const StoreToLoadForwardingCandidate &A,
356 const StoreToLoadForwardingCandidate &B) {
357 return getInstrIndex(A.Load) <
358 getInstrIndex(B.Load);
359 })
360 ->Load;
361 StoreInst *FirstStore =
362 llvm::min_element(Candidates,
363 [&](const StoreToLoadForwardingCandidate &A,
364 const StoreToLoadForwardingCandidate &B) {
365 return getInstrIndex(A.Store) <
366 getInstrIndex(B.Store);
367 })
368 ->Store;
369
370 // We're looking for stores after the first forwarding store until the end
371 // of the loop, then from the beginning of the loop until the last
372 // forwarded-to load. Collect the pointer for the stores.
373 SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath;
374
375 auto InsertStorePtr = [&](Instruction *I) {
376 if (auto *S = dyn_cast<StoreInst>(I))
377 PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
378 };
379 const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
380 std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
381 MemInstrs.end(), InsertStorePtr);
382 std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
383 InsertStorePtr);
384
385 return PtrsWrittenOnFwdingPath;
386 }
387
388 /// Determine the pointer alias checks to prove that there are no
389 /// intervening stores.
392
393 SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath =
394 findPointersWrittenOnForwardingPath(Candidates);
395
396 // Collect the pointers of the candidate loads.
397 SmallPtrSet<Value *, 4> CandLoadPtrs;
398 for (const auto &Candidate : Candidates)
399 CandLoadPtrs.insert(Candidate.getLoadPtr());
400
401 const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
403
404 copy_if(AllChecks, std::back_inserter(Checks),
405 [&](const RuntimePointerCheck &Check) {
406 for (auto PtrIdx1 : Check.first->Members)
407 for (auto PtrIdx2 : Check.second->Members)
408 if (needsChecking(PtrIdx1, PtrIdx2, PtrsWrittenOnFwdingPath,
409 CandLoadPtrs))
410 return true;
411 return false;
412 });
413
414 LLVM_DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size()
415 << "):\n");
417
418 return Checks;
419 }
420
421 /// Perform the transformation for a candidate.
422 void
423 propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
424 SCEVExpander &SEE) {
425 // loop:
426 // %x = load %gep_i
427 // = ... %x
428 // store %y, %gep_i_plus_1
429 //
430 // =>
431 //
432 // ph:
433 // %x.initial = load %gep_0
434 // loop:
435 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
436 // %x = load %gep_i <---- now dead
437 // = ... %x.storeforward
438 // store %y, %gep_i_plus_1
439
440 Value *Ptr = Cand.Load->getPointerOperand();
441 auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
442 auto *PH = L->getLoopPreheader();
443 assert(PH && "Preheader should exist!");
444 Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
445 PH->getTerminator());
446 Value *Initial =
447 new LoadInst(Cand.Load->getType(), InitialPtr, "load_initial",
448 /* isVolatile */ false, Cand.Load->getAlign(),
449 PH->getTerminator()->getIterator());
450
451 PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded");
452 PHI->insertBefore(L->getHeader()->begin());
453 PHI->addIncoming(Initial, PH);
454
455 Type *LoadType = Initial->getType();
456 Type *StoreType = Cand.Store->getValueOperand()->getType();
457 auto &DL = Cand.Load->getParent()->getModule()->getDataLayout();
458 (void)DL;
459
460 assert(DL.getTypeSizeInBits(LoadType) == DL.getTypeSizeInBits(StoreType) &&
461 "The type sizes should match!");
462
463 Value *StoreValue = Cand.Store->getValueOperand();
464 if (LoadType != StoreType)
465 StoreValue = CastInst::CreateBitOrPointerCast(StoreValue, LoadType,
466 "store_forward_cast",
467 Cand.Store->getIterator());
468
469 PHI->addIncoming(StoreValue, L->getLoopLatch());
470
471 Cand.Load->replaceAllUsesWith(PHI);
472 }
473
474 /// Top-level driver for each loop: find store->load forwarding
475 /// candidates, add run-time checks and perform transformation.
476 bool processLoop() {
477 LLVM_DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
478 << "\" checking " << *L << "\n");
479
480 // Look for store-to-load forwarding cases across the
481 // backedge. E.g.:
482 //
483 // loop:
484 // %x = load %gep_i
485 // = ... %x
486 // store %y, %gep_i_plus_1
487 //
488 // =>
489 //
490 // ph:
491 // %x.initial = load %gep_0
492 // loop:
493 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
494 // %x = load %gep_i <---- now dead
495 // = ... %x.storeforward
496 // store %y, %gep_i_plus_1
497
498 // First start with store->load dependences.
499 auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
500 if (StoreToLoadDependences.empty())
501 return false;
502
503 // Generate an index for each load and store according to the original
504 // program order. This will be used later.
505 InstOrder = LAI.getDepChecker().generateInstructionOrderMap();
506
507 // To keep things simple for now, remove those where the load is potentially
508 // fed by multiple stores.
509 removeDependencesFromMultipleStores(StoreToLoadDependences);
510 if (StoreToLoadDependences.empty())
511 return false;
512
513 // Filter the candidates further.
515 for (const StoreToLoadForwardingCandidate &Cand : StoreToLoadDependences) {
516 LLVM_DEBUG(dbgs() << "Candidate " << Cand);
517
518 // Make sure that the stored values is available everywhere in the loop in
519 // the next iteration.
520 if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
521 continue;
522
523 // If the load is conditional we can't hoist its 0-iteration instance to
524 // the preheader because that would make it unconditional. Thus we would
525 // access a memory location that the original loop did not access.
526 if (isLoadConditional(Cand.Load, L))
527 continue;
528
529 // Check whether the SCEV difference is the same as the induction step,
530 // thus we load the value in the next iteration.
531 if (!Cand.isDependenceDistanceOfOne(PSE, L))
532 continue;
533
534 assert(isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Load->getPointerOperand())) &&
535 "Loading from something other than indvar?");
536 assert(
537 isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Store->getPointerOperand())) &&
538 "Storing to something other than indvar?");
539
540 Candidates.push_back(Cand);
542 dbgs()
543 << Candidates.size()
544 << ". Valid store-to-load forwarding across the loop backedge\n");
545 }
546 if (Candidates.empty())
547 return false;
548
549 // Check intervening may-alias stores. These need runtime checks for alias
550 // disambiguation.
551 SmallVector<RuntimePointerCheck, 4> Checks = collectMemchecks(Candidates);
552
553 // Too many checks are likely to outweigh the benefits of forwarding.
554 if (Checks.size() > Candidates.size() * CheckPerElim) {
555 LLVM_DEBUG(dbgs() << "Too many run-time checks needed.\n");
556 return false;
557 }
558
559 if (LAI.getPSE().getPredicate().getComplexity() >
561 LLVM_DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
562 return false;
563 }
564
565 if (!L->isLoopSimplifyForm()) {
566 LLVM_DEBUG(dbgs() << "Loop is not is loop-simplify form");
567 return false;
568 }
569
570 if (!Checks.empty() || !LAI.getPSE().getPredicate().isAlwaysTrue()) {
571 if (LAI.hasConvergentOp()) {
572 LLVM_DEBUG(dbgs() << "Versioning is needed but not allowed with "
573 "convergent calls\n");
574 return false;
575 }
576
577 auto *HeaderBB = L->getHeader();
578 auto *F = HeaderBB->getParent();
579 bool OptForSize = F->hasOptSize() ||
580 llvm::shouldOptimizeForSize(HeaderBB, PSI, BFI,
581 PGSOQueryType::IRPass);
582 if (OptForSize) {
584 dbgs() << "Versioning is needed but not allowed when optimizing "
585 "for size.\n");
586 return false;
587 }
588
589 // Point of no-return, start the transformation. First, version the loop
590 // if necessary.
591
592 LoopVersioning LV(LAI, Checks, L, LI, DT, PSE.getSE());
593 LV.versionLoop();
594
595 // After versioning, some of the candidates' pointers could stop being
596 // SCEVAddRecs. We need to filter them out.
597 auto NoLongerGoodCandidate = [this](
598 const StoreToLoadForwardingCandidate &Cand) {
599 return !isa<SCEVAddRecExpr>(
600 PSE.getSCEV(Cand.Load->getPointerOperand())) ||
601 !isa<SCEVAddRecExpr>(
602 PSE.getSCEV(Cand.Store->getPointerOperand()));
603 };
604 llvm::erase_if(Candidates, NoLongerGoodCandidate);
605 }
606
607 // Next, propagate the value stored by the store to the users of the load.
608 // Also for the first iteration, generate the initial value of the load.
609 SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(),
610 "storeforward");
611 for (const auto &Cand : Candidates)
612 propagateStoredValueToLoadUsers(Cand, SEE);
613 NumLoopLoadEliminted += Candidates.size();
614
615 return true;
616 }
617
618private:
619 Loop *L;
620
621 /// Maps the load/store instructions to their index according to
622 /// program order.
624
625 // Analyses used.
626 LoopInfo *LI;
627 const LoopAccessInfo &LAI;
628 DominatorTree *DT;
632};
633
634} // end anonymous namespace
635
637 DominatorTree &DT,
641 LoopAccessInfoManager &LAIs) {
642 // Build up a worklist of inner-loops to transform to avoid iterator
643 // invalidation.
644 // FIXME: This logic comes from other passes that actually change the loop
645 // nest structure. It isn't clear this is necessary (or useful) for a pass
646 // which merely optimizes the use of loads in a loop.
647 SmallVector<Loop *, 8> Worklist;
648
649 bool Changed = false;
650
651 for (Loop *TopLevelLoop : LI)
652 for (Loop *L : depth_first(TopLevelLoop)) {
653 Changed |= simplifyLoop(L, &DT, &LI, SE, AC, /*MSSAU*/ nullptr, false);
654 // We only handle inner-most loops.
655 if (L->isInnermost())
656 Worklist.push_back(L);
657 }
658
659 // Now walk the identified inner loops.
660 for (Loop *L : Worklist) {
661 // Match historical behavior
662 if (!L->isRotatedForm() || !L->getExitingBlock())
663 continue;
664 // The actual work is performed by LoadEliminationForLoop.
665 LoadEliminationForLoop LEL(L, &LI, LAIs.getInfo(*L), &DT, BFI, PSI);
666 Changed |= LEL.processLoop();
667 if (Changed)
668 LAIs.clear();
669 }
670 return Changed;
671}
672
675 auto &LI = AM.getResult<LoopAnalysis>(F);
676 // There are no loops in the function. Return before computing other expensive
677 // analyses.
678 if (LI.empty())
679 return PreservedAnalyses::all();
680 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
681 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
682 auto &AC = AM.getResult<AssumptionAnalysis>(F);
683 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
684 auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
685 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
686 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
688
689 bool Changed = eliminateLoadsAcrossLoops(F, LI, DT, BFI, PSI, &SE, &AC, LAIs);
690
691 if (!Changed)
692 return PreservedAnalyses::all();
693
697 return PA;
698}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
#define Check(C,...)
This is the interface for a simple mod/ref and alias analysis over globals.
This header provides classes for managing per-loop analyses.
static bool eliminateLoadsAcrossLoops(Function &F, LoopInfo &LI, DominatorTree &DT, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, ScalarEvolution *SE, AssumptionCache *AC, LoopAccessInfoManager &LAIs)
static cl::opt< unsigned > LoadElimSCEVCheckThreshold("loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed for Loop " "Load Elimination"))
static bool isLoadConditional(LoadInst *Load, Loop *L)
Return true if the load is not executed on all paths in the loop.
static bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L, DominatorTree *DT)
Check if the store dominates all latches, so as long as there is no intervening store this value will...
static cl::opt< unsigned > CheckPerElim("runtime-check-per-loop-load-elim", cl::Hidden, cl::desc("Max number of memchecks allowed per eliminated load on average"), cl::init(1))
This header defines the LoopLoadEliminationPass object.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
if(VerifyEach)
This header defines various interfaces for pass management in LLVM.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This pass exposes codegen information to IR-level passes.
Class for arbitrary precision integers.
Definition: APInt.h:76
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:473
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
An instruction for reading from memory.
Definition: Instructions.h:184
This analysis provides dependence information for the memory accesses of a loop.
const LoopAccessInfo & getInfo(Loop &L)
Drive the analysis of memory accesses in the loop.
const MemoryDepChecker & getDepChecker() const
the Memory Dependence Checker which can determine the loop-independent and loop-carried dependences b...
const RuntimePointerChecking * getRuntimePointerChecking() const
const PredicatedScalarEvolution & getPSE() const
Used to add runtime SCEV checks.
bool hasConvergentOp() const
Return true if there is a convergent operation in the loop.
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:566
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:44
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
const SmallVectorImpl< Instruction * > & getMemoryInstructions() const
The vector of memory access instructions.
const SmallVectorImpl< Dependence > * getDependences() const
Returns the memory dependences.
DenseMap< Instruction *, unsigned > generateInstructionOrderMap() const
Generate a mapping between the memory instructions and their indices according to program order.
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
Definition: PassManager.h:756
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr, BasicBlock::iterator InsertBefore)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
const SCEVPredicate & getPredicate() const
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:129
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
void printChecks(raw_ostream &OS, const SmallVectorImpl< RuntimePointerCheck > &Checks, unsigned Depth=0) const
Print Checks.
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
const PointerInfo & getPointerInfo(unsigned PtrIdx) const
Return PointerInfo for pointer at index PtrIdx.
This class uses information about analyze scalars to rewrite expressions in canonical form.
virtual unsigned getComplexity() const
Returns the estimated complexity of this predicate.
virtual bool isAlwaysTrue() const =0
Returns true if the predicate is always true.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:321
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:360
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:317
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
auto min_element(R &&Range)
Definition: STLExtras.h:1978
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
std::pair< const RuntimeCheckingPtrGroup *, const RuntimeCheckingPtrGroup * > RuntimePointerCheck
A memcheck which made up of a pair of grouped pointers.
bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1768
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
std::optional< int64_t > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DenseMap< Value *, const SCEV * > &StridesMap=DenseMap< Value *, const SCEV * >(), bool Assume=false, bool ShouldCheckWrap=true)
If the pointer has a constant stride return it in units of the access type size.
auto max_element(R &&Range)
Definition: STLExtras.h:1986
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:293
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition: STLExtras.h:2051
iterator_range< df_iterator< T > > depth_first(const T &G)
Type * getLoadStoreType(Value *I)
A helper function that returns the type of a load or store instruction.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#define SEE(c)
Definition: regcomp.c:254
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
TrackingVH< Value > PointerValue
Holds the pointer value that we need to check.