64 #include <forward_list> 71 #define LLE_OPTION "loop-load-elim" 72 #define DEBUG_TYPE LLE_OPTION 75 "runtime-check-per-loop-load-elim",
cl::Hidden,
76 cl::desc(
"Max number of memchecks allowed per eliminated load on average"),
81 cl::desc(
"The maximum number of SCEV checks allowed for Loop " 84 STATISTIC(NumLoopLoadEliminted,
"Number of loads eliminated by LLE");
89 struct StoreToLoadForwardingCandidate {
94 : Load(Load), Store(Store) {}
108 "Should be a known dependence");
120 auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.
getSCEV(LoadPtr));
121 auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.
getSCEV(StorePtr));
125 auto *Dist = cast<SCEVConstant>(
127 const APInt &Val = Dist->getAPInt();
128 return Val == TypeByteSize;
135 const StoreToLoadForwardingCandidate &Cand) {
136 OS << *Cand.Store <<
" -->\n";
137 OS.
indent(2) << *Cand.Load <<
"\n";
164 class LoadEliminationForLoop {
169 : L(L), LI(LI), LAI(LAI), DT(DT),
BFI(BFI), PSI(PSI), PSE(LAI.
getPSE()) {}
176 std::forward_list<StoreToLoadForwardingCandidate>
178 std::forward_list<StoreToLoadForwardingCandidate> Candidates;
190 for (
const auto &Dep : *Deps) {
192 Instruction *Destination = Dep.getDestination(LAI);
195 if (isa<LoadInst>(Source))
196 LoadsWithUnknownDepedence.
insert(Source);
197 if (isa<LoadInst>(Destination))
198 LoadsWithUnknownDepedence.
insert(Destination);
202 if (Dep.isBackward())
208 assert(Dep.isForward() &&
"Needs to be a forward dependence");
221 Candidates.emplace_front(Load, Store);
224 if (!LoadsWithUnknownDepedence.
empty())
225 Candidates.remove_if([&](
const StoreToLoadForwardingCandidate &
C) {
226 return LoadsWithUnknownDepedence.count(C.Load);
234 auto I = InstOrder.find(Inst);
235 assert(
I != InstOrder.end() &&
"No index for instruction");
258 void removeDependencesFromMultipleStores(
259 std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
262 using LoadToSingleCandT =
264 LoadToSingleCandT LoadToSingleCand;
266 for (
const auto &Cand : Candidates) {
268 LoadToSingleCandT::iterator Iter;
270 std::tie(Iter, NewElt) =
271 LoadToSingleCand.
insert(std::make_pair(Cand.Load, &Cand));
273 const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
275 if (OtherCand ==
nullptr)
281 if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
282 Cand.isDependenceDistanceOfOne(PSE, L) &&
283 OtherCand->isDependenceDistanceOfOne(PSE, L)) {
285 if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
292 Candidates.remove_if([&](
const StoreToLoadForwardingCandidate &Cand) {
293 if (LoadToSingleCand[Cand.Load] != &Cand) {
295 dbgs() <<
"Removing from candidates: \n" 297 <<
" The load may have multiple stores forwarding to " 310 bool needsChecking(
unsigned PtrIdx1,
unsigned PtrIdx2,
312 const std::set<Value *> &CandLoadPtrs) {
317 return ((PtrsWrittenOnFwdingPath.
count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
318 (PtrsWrittenOnFwdingPath.
count(Ptr2) && CandLoadPtrs.count(Ptr1)));
345 std::max_element(Candidates.
begin(), Candidates.
end(),
346 [&](
const StoreToLoadForwardingCandidate &A,
347 const StoreToLoadForwardingCandidate &
B) {
348 return getInstrIndex(A.Load) < getInstrIndex(
B.Load);
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);
366 if (
auto *S = dyn_cast<StoreInst>(
I))
367 PtrsWrittenOnFwdingPath.
insert(S->getPointerOperand());
370 std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
371 MemInstrs.end(), InsertStorePtr);
372 std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
375 return PtrsWrittenOnFwdingPath;
384 findPointersWrittenOnForwardingPath(Candidates);
388 std::set<Value *> CandLoadPtrs;
390 std::inserter(CandLoadPtrs, CandLoadPtrs.begin()),
391 std::mem_fn(&StoreToLoadForwardingCandidate::getLoadPtr));
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,
415 propagateStoredValueToLoadUsers(
const StoreToLoadForwardingCandidate &Cand,
432 Value *Ptr = Cand.Load->getPointerOperand();
433 auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.
getSCEV(Ptr));
436 PH->getTerminator());
438 Cand.Load->getType(), InitialPtr,
"load_initial",
440 PH->getTerminator());
445 PHI->addIncoming(Cand.Store->getOperand(0), L->
getLoopLatch());
447 Cand.Load->replaceAllUsesWith(PHI);
454 <<
"\" checking " << *L <<
"\n");
475 auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
476 if (StoreToLoadDependences.empty())
485 removeDependencesFromMultipleStores(StoreToLoadDependences);
486 if (StoreToLoadDependences.empty())
491 unsigned NumForwarding = 0;
492 for (
const StoreToLoadForwardingCandidate &Cand : StoreToLoadDependences) {
508 if (!Cand.isDependenceDistanceOfOne(PSE, L))
515 <<
". Valid store-to-load forwarding across the loop backedge\n");
518 if (Candidates.
empty())
524 collectMemchecks(Candidates);
541 "convergent calls\n");
546 auto *
F = HeaderBB->getParent();
547 bool OptForSize =
F->hasOptSize() ||
552 dbgs() <<
"Versioning is needed but not allowed when optimizing " 575 for (
const auto &Cand : Candidates)
576 propagateStoredValueToLoadUsers(Cand, SEE);
577 NumLoopLoadEliminted += NumForwarding;
611 for (
Loop *TopLevelLoop : LI)
618 bool Changed =
false;
619 for (
Loop *L : Worklist) {
621 LoadEliminationForLoop LEL(L, &LI, GetLAI(*L), &DT, BFI, PSI);
622 Changed |= LEL.processLoop();
643 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
644 auto &LAA = getAnalysis<LoopAccessLegacyAnalysis>();
645 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
646 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
648 &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
675 static const char LLE_name[] =
"Loop Load Elimination";
688 return new LoopLoadElimination();
Legacy wrapper pass to provide the GlobalsAAResult object.
static bool Check(DecodeStatus &Out, DecodeStatus In)
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.
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.
This class represents lattice values for constants.
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...
void push_back(const T &Elt)
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.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
An efficient, type-erasing, non-owning reference to a callable.
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...
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.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
Type * getPointerElementType() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
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...
Encapsulates MemorySSA, including all data associated with memory accesses.
static const char LLE_name[]
void getLoopLatches(SmallVectorImpl< BlockT *> &LoopLatches) const
Return all loop latch blocks of this loop.
Analysis pass that exposes the LoopInfo for a function.
This file implements a class to represent arbitrary precision integral constant values and operations...
BlockT * getHeader() const
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.
This header provides classes for managing per-loop analyses.
void initializeLoopLoadEliminationPass(PassRegistry &)
An instruction for storing to memory.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
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)
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.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
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
const Instruction & front() const
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...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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.
Value * getPointerOperand()
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.
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.
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.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
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...
AnalysisUsage & addRequiredID(const void *ID)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
const PointerInfo & getPointerInfo(unsigned PtrIdx) const
Return PointerInfo for pointer at index PtrIdx.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
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)
An analysis that produces MemorySSA for a function.
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't ove...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class for arbitrary precision integers.
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...
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...
This analysis provides dependence information for the memory accesses of a loop.
Type * getPointerOperandType() const
cl::opt< bool > EnableMSSALoopDependency
Enables memory ssa as a dependency for loop passes.
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
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)
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
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...
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...
LLVM Value Representation.
This class implements an extremely fast bulk output stream that can only output to a stream...
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
The legacy pass manager's analysis pass to compute loop information.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
UnaryPredicate for_each(R &&Range, UnaryPredicate P)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly...
This header defines various interfaces for pass management in LLVM.
const SmallVector< PointerCheck, 4 > & getChecks() const
Returns the checks that generateChecks created.
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()
const BasicBlock * getParent() const
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...