LLVM  10.0.0
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"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Analysis/LoopInfo.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/Dominators.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/IR/PassManager.h"
50 #include "llvm/IR/Type.h"
51 #include "llvm/IR/Value.h"
52 #include "llvm/InitializePasses.h"
53 #include "llvm/Pass.h"
54 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/Debug.h"
58 #include "llvm/Transforms/Scalar.h"
59 #include "llvm/Transforms/Utils.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 
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 
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;
92 
93  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]
98  bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,
99  Loop *L) const {
100  Value *LoadPtr = Load->getPointerOperand();
101  Value *StorePtr = Store->getPointerOperand();
102  Type *LoadPtrType = LoadPtr->getType();
103  Type *LoadType = LoadPtrType->getPointerElementType();
104 
105  assert(LoadPtrType->getPointerAddressSpace() ==
106  StorePtr->getType()->getPointerAddressSpace() &&
107  LoadType == StorePtr->getType()->getPointerElementType() &&
108  "Should be a known dependence");
109 
110  // Currently we only support accesses with unit stride. FIXME: we should be
111  // able to handle non unit stirde as well as long as the stride is equal to
112  // the dependence distance.
113  if (getPtrStride(PSE, LoadPtr, L) != 1 ||
114  getPtrStride(PSE, StorePtr, L) != 1)
115  return false;
116 
117  auto &DL = Load->getParent()->getModule()->getDataLayout();
118  unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));
119 
120  auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr));
121  auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr));
122 
123  // We don't need to check non-wrapping here because forward/backward
124  // dependence wouldn't be valid if these weren't monotonic accesses.
125  auto *Dist = cast<SCEVConstant>(
126  PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));
127  const APInt &Val = Dist->getAPInt();
128  return Val == TypeByteSize;
129  }
130 
131  Value *getLoadPtr() const { return Load->getPointerOperand(); }
132 
133 #ifndef NDEBUG
134  friend raw_ostream &operator<<(raw_ostream &OS,
135  const StoreToLoadForwardingCandidate &Cand) {
136  OS << *Cand.Store << " -->\n";
137  OS.indent(2) << *Cand.Load << "\n";
138  return OS;
139  }
140 #endif
141 };
142 
143 } // end anonymous namespace
144 
145 /// Check if the store dominates all latches, so as long as there is no
146 /// intervening store this value will be loaded in the next iteration.
147 static bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L,
148  DominatorTree *DT) {
150  L->getLoopLatches(Latches);
151  return llvm::all_of(Latches, [&](const BasicBlock *Latch) {
152  return DT->dominates(StoreBlock, Latch);
153  });
154 }
155 
156 /// Return true if the load is not executed on all paths in the loop.
157 static bool isLoadConditional(LoadInst *Load, Loop *L) {
158  return Load->getParent() != L->getHeader();
159 }
160 
161 namespace {
162 
163 /// The per-loop class that does most of the work.
164 class LoadEliminationForLoop {
165 public:
166  LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,
168  ProfileSummaryInfo* PSI)
169  : L(L), LI(LI), LAI(LAI), DT(DT), BFI(BFI), PSI(PSI), PSE(LAI.getPSE()) {}
170 
171  /// Look through the loop-carried and loop-independent dependences in
172  /// this loop and find store->load dependences.
173  ///
174  /// Note that no candidate is returned if LAA has failed to analyze the loop
175  /// (e.g. if it's not bottom-tested, contains volatile memops, etc.)
176  std::forward_list<StoreToLoadForwardingCandidate>
177  findStoreToLoadDependences(const LoopAccessInfo &LAI) {
178  std::forward_list<StoreToLoadForwardingCandidate> Candidates;
179 
180  const auto *Deps = LAI.getDepChecker().getDependences();
181  if (!Deps)
182  return Candidates;
183 
184  // Find store->load dependences (consequently true dep). Both lexically
185  // forward and backward dependences qualify. Disqualify loads that have
186  // other unknown dependences.
187 
188  SmallPtrSet<Instruction *, 4> LoadsWithUnknownDepedence;
189 
190  for (const auto &Dep : *Deps) {
191  Instruction *Source = Dep.getSource(LAI);
192  Instruction *Destination = Dep.getDestination(LAI);
193 
194  if (Dep.Type == MemoryDepChecker::Dependence::Unknown) {
195  if (isa<LoadInst>(Source))
196  LoadsWithUnknownDepedence.insert(Source);
197  if (isa<LoadInst>(Destination))
198  LoadsWithUnknownDepedence.insert(Destination);
199  continue;
200  }
201 
202  if (Dep.isBackward())
203  // Note that the designations source and destination follow the program
204  // order, i.e. source is always first. (The direction is given by the
205  // DepType.)
206  std::swap(Source, Destination);
207  else
208  assert(Dep.isForward() && "Needs to be a forward dependence");
209 
210  auto *Store = dyn_cast<StoreInst>(Source);
211  if (!Store)
212  continue;
213  auto *Load = dyn_cast<LoadInst>(Destination);
214  if (!Load)
215  continue;
216 
217  // Only progagate the value if they are of the same type.
218  if (Store->getPointerOperandType() != Load->getPointerOperandType())
219  continue;
220 
221  Candidates.emplace_front(Load, Store);
222  }
223 
224  if (!LoadsWithUnknownDepedence.empty())
225  Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
226  return LoadsWithUnknownDepedence.count(C.Load);
227  });
228 
229  return Candidates;
230  }
231 
232  /// Return the index of the instruction according to program order.
233  unsigned getInstrIndex(Instruction *Inst) {
234  auto I = InstOrder.find(Inst);
235  assert(I != InstOrder.end() && "No index for instruction");
236  return I->second;
237  }
238 
239  /// If a load has multiple candidates associated (i.e. different
240  /// stores), it means that it could be forwarding from multiple stores
241  /// depending on control flow. Remove these candidates.
242  ///
243  /// Here, we rely on LAA to include the relevant loop-independent dependences.
244  /// LAA is known to omit these in the very simple case when the read and the
245  /// write within an alias set always takes place using the *same* pointer.
246  ///
247  /// However, we know that this is not the case here, i.e. we can rely on LAA
248  /// to provide us with loop-independent dependences for the cases we're
249  /// interested. Consider the case for example where a loop-independent
250  /// dependece S1->S2 invalidates the forwarding S3->S2.
251  ///
252  /// A[i] = ... (S1)
253  /// ... = A[i] (S2)
254  /// A[i+1] = ... (S3)
255  ///
256  /// LAA will perform dependence analysis here because there are two
257  /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).
258  void removeDependencesFromMultipleStores(
259  std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
260  // If Store is nullptr it means that we have multiple stores forwarding to
261  // this store.
262  using LoadToSingleCandT =
264  LoadToSingleCandT LoadToSingleCand;
265 
266  for (const auto &Cand : Candidates) {
267  bool NewElt;
268  LoadToSingleCandT::iterator Iter;
269 
270  std::tie(Iter, NewElt) =
271  LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
272  if (!NewElt) {
273  const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
274  // Already multiple stores forward to this load.
275  if (OtherCand == nullptr)
276  continue;
277 
278  // Handle the very basic case when the two stores are in the same block
279  // so deciding which one forwards is easy. The later one forwards as
280  // long as they both have a dependence distance of one to the load.
281  if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
282  Cand.isDependenceDistanceOfOne(PSE, L) &&
283  OtherCand->isDependenceDistanceOfOne(PSE, L)) {
284  // They are in the same block, the later one will forward to the load.
285  if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
286  OtherCand = &Cand;
287  } else
288  OtherCand = nullptr;
289  }
290  }
291 
292  Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
293  if (LoadToSingleCand[Cand.Load] != &Cand) {
294  LLVM_DEBUG(
295  dbgs() << "Removing from candidates: \n"
296  << Cand
297  << " The load may have multiple stores forwarding to "
298  << "it\n");
299  return true;
300  }
301  return false;
302  });
303  }
304 
305  /// Given two pointers operations by their RuntimePointerChecking
306  /// indices, return true if they require an alias check.
307  ///
308  /// We need a check if one is a pointer for a candidate load and the other is
309  /// a pointer for a possibly intervening store.
310  bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
311  const SmallPtrSet<Value *, 4> &PtrsWrittenOnFwdingPath,
312  const std::set<Value *> &CandLoadPtrs) {
313  Value *Ptr1 =
315  Value *Ptr2 =
317  return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
318  (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
319  }
320 
321  /// Return pointers that are possibly written to on the path from a
322  /// forwarding store to a load.
323  ///
324  /// These pointers need to be alias-checked against the forwarding candidates.
325  SmallPtrSet<Value *, 4> findPointersWrittenOnForwardingPath(
327  // From FirstStore to LastLoad neither of the elimination candidate loads
328  // should overlap with any of the stores.
329  //
330  // E.g.:
331  //
332  // st1 C[i]
333  // ld1 B[i] <-------,
334  // ld0 A[i] <----, | * LastLoad
335  // ... | |
336  // st2 E[i] | |
337  // st3 B[i+1] -- | -' * FirstStore
338  // st0 A[i+1] ---'
339  // st4 D[i]
340  //
341  // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
342  // ld0.
343 
344  LoadInst *LastLoad =
345  std::max_element(Candidates.begin(), Candidates.end(),
346  [&](const StoreToLoadForwardingCandidate &A,
347  const StoreToLoadForwardingCandidate &B) {
348  return getInstrIndex(A.Load) < getInstrIndex(B.Load);
349  })
350  ->Load;
351  StoreInst *FirstStore =
352  std::min_element(Candidates.begin(), Candidates.end(),
353  [&](const StoreToLoadForwardingCandidate &A,
354  const StoreToLoadForwardingCandidate &B) {
355  return getInstrIndex(A.Store) <
356  getInstrIndex(B.Store);
357  })
358  ->Store;
359 
360  // We're looking for stores after the first forwarding store until the end
361  // of the loop, then from the beginning of the loop until the last
362  // forwarded-to load. Collect the pointer for the stores.
363  SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath;
364 
365  auto InsertStorePtr = [&](Instruction *I) {
366  if (auto *S = dyn_cast<StoreInst>(I))
367  PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
368  };
369  const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
370  std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
371  MemInstrs.end(), InsertStorePtr);
372  std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
373  InsertStorePtr);
374 
375  return PtrsWrittenOnFwdingPath;
376  }
377 
378  /// Determine the pointer alias checks to prove that there are no
379  /// intervening stores.
382 
383  SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath =
384  findPointersWrittenOnForwardingPath(Candidates);
385 
386  // Collect the pointers of the candidate loads.
387  // FIXME: SmallPtrSet does not work with std::inserter.
388  std::set<Value *> CandLoadPtrs;
389  transform(Candidates,
390  std::inserter(CandLoadPtrs, CandLoadPtrs.begin()),
391  std::mem_fn(&StoreToLoadForwardingCandidate::getLoadPtr));
392 
393  const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
395 
396  copy_if(AllChecks, std::back_inserter(Checks),
398  for (auto PtrIdx1 : Check.first->Members)
399  for (auto PtrIdx2 : Check.second->Members)
400  if (needsChecking(PtrIdx1, PtrIdx2, PtrsWrittenOnFwdingPath,
401  CandLoadPtrs))
402  return true;
403  return false;
404  });
405 
406  LLVM_DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size()
407  << "):\n");
409 
410  return Checks;
411  }
412 
413  /// Perform the transformation for a candidate.
414  void
415  propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
416  SCEVExpander &SEE) {
417  // loop:
418  // %x = load %gep_i
419  // = ... %x
420  // store %y, %gep_i_plus_1
421  //
422  // =>
423  //
424  // ph:
425  // %x.initial = load %gep_0
426  // loop:
427  // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
428  // %x = load %gep_i <---- now dead
429  // = ... %x.storeforward
430  // store %y, %gep_i_plus_1
431 
432  Value *Ptr = Cand.Load->getPointerOperand();
433  auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
434  auto *PH = L->getLoopPreheader();
435  Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
436  PH->getTerminator());
437  Value *Initial = new LoadInst(
438  Cand.Load->getType(), InitialPtr, "load_initial",
439  /* isVolatile */ false, MaybeAlign(Cand.Load->getAlignment()),
440  PH->getTerminator());
441 
442  PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded",
443  &L->getHeader()->front());
444  PHI->addIncoming(Initial, PH);
445  PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch());
446 
447  Cand.Load->replaceAllUsesWith(PHI);
448  }
449 
450  /// Top-level driver for each loop: find store->load forwarding
451  /// candidates, add run-time checks and perform transformation.
452  bool processLoop() {
453  LLVM_DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
454  << "\" checking " << *L << "\n");
455 
456  // Look for store-to-load forwarding cases across the
457  // backedge. E.g.:
458  //
459  // loop:
460  // %x = load %gep_i
461  // = ... %x
462  // store %y, %gep_i_plus_1
463  //
464  // =>
465  //
466  // ph:
467  // %x.initial = load %gep_0
468  // loop:
469  // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
470  // %x = load %gep_i <---- now dead
471  // = ... %x.storeforward
472  // store %y, %gep_i_plus_1
473 
474  // First start with store->load dependences.
475  auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
476  if (StoreToLoadDependences.empty())
477  return false;
478 
479  // Generate an index for each load and store according to the original
480  // program order. This will be used later.
481  InstOrder = LAI.getDepChecker().generateInstructionOrderMap();
482 
483  // To keep things simple for now, remove those where the load is potentially
484  // fed by multiple stores.
485  removeDependencesFromMultipleStores(StoreToLoadDependences);
486  if (StoreToLoadDependences.empty())
487  return false;
488 
489  // Filter the candidates further.
491  unsigned NumForwarding = 0;
492  for (const StoreToLoadForwardingCandidate &Cand : StoreToLoadDependences) {
493  LLVM_DEBUG(dbgs() << "Candidate " << Cand);
494 
495  // Make sure that the stored values is available everywhere in the loop in
496  // the next iteration.
497  if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
498  continue;
499 
500  // If the load is conditional we can't hoist its 0-iteration instance to
501  // the preheader because that would make it unconditional. Thus we would
502  // access a memory location that the original loop did not access.
503  if (isLoadConditional(Cand.Load, L))
504  continue;
505 
506  // Check whether the SCEV difference is the same as the induction step,
507  // thus we load the value in the next iteration.
508  if (!Cand.isDependenceDistanceOfOne(PSE, L))
509  continue;
510 
511  ++NumForwarding;
512  LLVM_DEBUG(
513  dbgs()
514  << NumForwarding
515  << ". Valid store-to-load forwarding across the loop backedge\n");
516  Candidates.push_back(Cand);
517  }
518  if (Candidates.empty())
519  return false;
520 
521  // Check intervening may-alias stores. These need runtime checks for alias
522  // disambiguation.
524  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() >
534  LLVM_DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
535  return false;
536  }
537 
538  if (!Checks.empty() || !LAI.getPSE().getUnionPredicate().isAlwaysTrue()) {
539  if (LAI.hasConvergentOp()) {
540  LLVM_DEBUG(dbgs() << "Versioning is needed but not allowed with "
541  "convergent calls\n");
542  return false;
543  }
544 
545  auto *HeaderBB = L->getHeader();
546  auto *F = HeaderBB->getParent();
547  bool OptForSize = F->hasOptSize() ||
548  llvm::shouldOptimizeForSize(HeaderBB, PSI, BFI,
550  if (OptForSize) {
551  LLVM_DEBUG(
552  dbgs() << "Versioning is needed but not allowed when optimizing "
553  "for size.\n");
554  return false;
555  }
556 
557  if (!L->isLoopSimplifyForm()) {
558  LLVM_DEBUG(dbgs() << "Loop is not is loop-simplify form");
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, L, LI, DT, PSE.getSE(), false);
566  LV.setAliasChecks(std::move(Checks));
567  LV.setSCEVChecks(LAI.getPSE().getUnionPredicate());
568  LV.versionLoop();
569  }
570 
571  // Next, propagate the value stored by the store to the users of the load.
572  // Also for the first iteration, generate the initial value of the load.
574  "storeforward");
575  for (const auto &Cand : Candidates)
576  propagateStoredValueToLoadUsers(Cand, SEE);
577  NumLoopLoadEliminted += NumForwarding;
578 
579  return true;
580  }
581 
582 private:
583  Loop *L;
584 
585  /// Maps the load/store instructions to their index according to
586  /// program order.
588 
589  // Analyses used.
590  LoopInfo *LI;
591  const LoopAccessInfo &LAI;
592  DominatorTree *DT;
594  ProfileSummaryInfo *PSI;
596 };
597 
598 } // end anonymous namespace
599 
600 static bool
603  function_ref<const LoopAccessInfo &(Loop &)> GetLAI) {
604  // Build up a worklist of inner-loops to transform to avoid iterator
605  // invalidation.
606  // FIXME: This logic comes from other passes that actually change the loop
607  // nest structure. It isn't clear this is necessary (or useful) for a pass
608  // which merely optimizes the use of loads in a loop.
609  SmallVector<Loop *, 8> Worklist;
610 
611  for (Loop *TopLevelLoop : LI)
612  for (Loop *L : depth_first(TopLevelLoop))
613  // We only handle inner-most loops.
614  if (L->empty())
615  Worklist.push_back(L);
616 
617  // Now walk the identified inner loops.
618  bool Changed = false;
619  for (Loop *L : Worklist) {
620  // The actual work is performed by LoadEliminationForLoop.
621  LoadEliminationForLoop LEL(L, &LI, GetLAI(*L), &DT, BFI, PSI);
622  Changed |= LEL.processLoop();
623  }
624  return Changed;
625 }
626 
627 namespace {
628 
629 /// The pass. Most of the work is delegated to the per-loop
630 /// LoadEliminationForLoop class.
631 class LoopLoadElimination : public FunctionPass {
632 public:
633  static char ID;
634 
635  LoopLoadElimination() : FunctionPass(ID) {
637  }
638 
639  bool runOnFunction(Function &F) override {
640  if (skipFunction(F))
641  return false;
642 
643  auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
644  auto &LAA = getAnalysis<LoopAccessLegacyAnalysis>();
645  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
646  auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
647  auto *BFI = (PSI && PSI->hasProfileSummary()) ?
648  &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
649  nullptr;
650 
651  // Process each loop nest in the function.
653  F, LI, DT, BFI, PSI,
654  [&LAA](Loop &L) -> const LoopAccessInfo & { return LAA.getInfo(&L); });
655  }
656 
657  void getAnalysisUsage(AnalysisUsage &AU) const override {
668  }
669 };
670 
671 } // end anonymous namespace
672 
674 
675 static const char LLE_name[] = "Loop Load Elimination";
676 
677 INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
682 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
685 INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
686 
688  return new LoopLoadElimination();
689 }
690 
693  auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
694  auto &LI = AM.getResult<LoopAnalysis>(F);
695  auto &TTI = AM.getResult<TargetIRAnalysis>(F);
696  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
697  auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
698  auto &AA = AM.getResult<AAManager>(F);
699  auto &AC = AM.getResult<AssumptionAnalysis>(F);
700  auto &MAM = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
701  auto *PSI = MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
702  auto *BFI = (PSI && PSI->hasProfileSummary()) ?
703  &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
705  ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
706  : nullptr;
707 
708  auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
709  bool Changed = eliminateLoadsAcrossLoops(
710  F, LI, DT, BFI, PSI, [&](Loop &L) -> const LoopAccessInfo & {
711  LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI, MSSA};
712  return LAM.getResult<LoopAccessAnalysis>(L, AR);
713  });
714 
715  if (!Changed)
716  return PreservedAnalyses::all();
717 
719  return PA;
720 }
Legacy wrapper pass to provide the GlobalsAAResult object.
static bool Check(DecodeStatus &Out, DecodeStatus In)
uint64_t CallInst * C
TrackingVH< Value > PointerValue
Holds the pointer value that we need to check.
void printChecks(raw_ostream &OS, const SmallVectorImpl< PointerCheck > &Checks, unsigned Depth=0) const
Print Checks.
const MemoryDepChecker & getDepChecker() const
the Memory Dependence Checker which can determine the loop-independent and loop-carried dependences b...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:209
DenseMap< Instruction *, unsigned > generateInstructionOrderMap() const
Generate a mapping between the memory instructions and their indices according to program order...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This is an alternative analysis pass to BlockFrequencyInfoWrapperPass.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:777
This class represents lattice values for constants.
Definition: AllocatorList.h:23
This is the interface for a simple mod/ref and alias analysis over globals.
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:1229
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"))
const RuntimePointerChecking * getRuntimePointerChecking() const
Analysis providing profile information.
int64_t getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr, const Loop *Lp, const ValueToValueMap &StridesMap=ValueToValueMap(), bool Assume=false, bool ShouldCheckWrap=true)
If the pointer has a constant stride return it in units of its element size.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:160
raw_ostream & indent(unsigned NumSpaces)
indent - Insert &#39;NumSpaces&#39; spaces.
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:99
Analysis pass providing the TargetTransformInfo.
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:1182
STATISTIC(NumFunctions, "Total number of functions")
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:230
F(f)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:635
An instruction for reading from memory.
Definition: Instructions.h:169
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:195
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:140
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
Type * getPointerElementType() const
Definition: Type.h:381
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
static bool isLoadConditional(LoadInst *Load, Loop *L)
Return true if the load is not executed on all paths in the loop.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition: MemorySSA.h:704
static const char LLE_name[]
void getLoopLatches(SmallVectorImpl< BlockT *> &LoopLatches) const
Return all loop latch blocks of this loop.
Definition: LoopInfo.h:314
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:1194
This file implements a class to represent arbitrary precision integral constant values and operations...
BlockT * getHeader() const
Definition: LoopInfo.h:105
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
const SmallVectorImpl< Instruction * > & getMemoryInstructions() const
The vector of memory access instructions.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
This header provides classes for managing per-loop analyses.
void initializeLoopLoadEliminationPass(PassRegistry &)
An instruction for storing to memory.
Definition: Instructions.h:331
#define LLE_OPTION
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
bool hasProfileSummary()
Returns true if profile summary is available.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
This analysis provides dependence information for the memory accesses of a loop.
LLVM_NODISCARD bool empty() const
Definition: SmallPtrSet.h:91
const Instruction & front() const
Definition: BasicBlock.h:285
A manager for alias analyses.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:486
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:370
Represent the analysis usage information of a pass.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:282
Value * getPointerOperand()
Definition: Instructions.h:295
const PredicatedScalarEvolution & getPSE() const
Used to add runtime SCEV checks.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
void setAliasChecks(SmallVector< RuntimePointerChecking::PointerCheck, 4 > Checks)
Sets the runtime alias checks for versioning the loop.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
std::pair< const CheckingPtrGroup *, const CheckingPtrGroup * > PointerCheck
A memcheck which made up of a pair of grouped pointers.
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
size_t size() const
Definition: SmallVector.h:52
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
char & LoopSimplifyID
A function analysis which provides an AssumptionCache.
const SmallVectorImpl< Dependence > * getDependences() const
Returns the memory dependences.
This header defines the LoopLoadEliminationPass object.
Analysis pass which computes BlockFrequencyInfo.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
const SCEVUnionPredicate & getUnionPredicate() const
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
Definition: PassManager.h:1161
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:269
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
Definition: Alignment.h:117
const PointerInfo & getPointerInfo(unsigned PtrIdx) const
Return PointerInfo for pointer at index PtrIdx.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:249
Module.h This file contains the declarations for the Module class.
FunctionPass * createLoopLoadEliminationPass()
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:47
An analysis that produces MemorySSA for a function.
Definition: MemorySSA.h:925
Drive the analysis of memory accesses in the loop.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
This class emits a version of the loop where run-time checks ensure that may-alias pointers can&#39;t ove...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
Class for arbitrary precision integers.
Definition: APInt.h:69
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...
#define SEE(c)
Definition: regcomp.c:254
This class uses information about analyze scalars to rewrite expressions in canonical form...
static bool eliminateLoadsAcrossLoops(Function &F, LoopInfo &LI, DominatorTree &DT, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, function_ref< const LoopAccessInfo &(Loop &)> GetLAI)
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
Analysis pass that exposes the ScalarEvolution for a function.
unsigned getComplexity() const override
We estimate the complexity of a union predicate as the size number of predicates in the union...
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
Definition: LoopInfo.cpp:465
This analysis provides dependence information for the memory accesses of a loop.
Type * getPointerOperandType() const
Definition: Instructions.h:298
cl::opt< bool > EnableMSSALoopDependency
Enables memory ssa as a dependency for loop passes.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:509
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
#define I(x, y, z)
Definition: MD5.cpp:58
bool hasConvergentOp() const
Return true if there is a convergent operation in the loop.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
Definition: APInt.h:2096
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
Definition: STLExtras.h:1264
bool empty() const
Definition: LoopInfo.h:151
Analysis pass providing the TargetLibraryInfo.
iterator_range< df_iterator< T > > depth_first(const T &G)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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))
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
LLVM Value Representation.
Definition: Value.h:74
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
The legacy pass manager&#39;s analysis pass to compute loop information.
Definition: LoopInfo.h:1219
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:259
This pass exposes codegen information to IR-level passes.
UnaryPredicate for_each(R &&Range, UnaryPredicate P)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1175
This header defines various interfaces for pass management in LLVM.
const SmallVector< PointerCheck, 4 > & getChecks() const
Returns the checks that generateChecks created.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
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...
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
Value * getPointerOperand()
Definition: Instructions.h:429
const BasicBlock * getParent() const
Definition: Instruction.h:66
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:1045