57 #define DEBUG_TYPE "gvn-hoist"
59 STATISTIC(NumHoisted,
"Number of instructions hoisted");
60 STATISTIC(NumRemoved,
"Number of instructions removed");
61 STATISTIC(NumLoadsHoisted,
"Number of loads hoisted");
62 STATISTIC(NumLoadsRemoved,
"Number of loads removed");
63 STATISTIC(NumStoresHoisted,
"Number of stores hoisted");
64 STATISTIC(NumStoresRemoved,
"Number of stores removed");
65 STATISTIC(NumCallsHoisted,
"Number of calls hoisted");
66 STATISTIC(NumCallsRemoved,
"Number of calls removed");
70 cl::desc(
"Max number of instructions to hoist "
71 "(default unlimited = -1)"));
74 cl::desc(
"Max number of basic blocks on the path between "
75 "hoisting locations (default = 4, unlimited = -1)"));
79 cl::desc(
"Hoist instructions from the beginning of the BB up to the "
80 "maximum specified depth (default = 100, unlimited = -1)"));
84 cl::desc(
"Maximum length of dependent chains to hoist "
85 "(default = 10, unlimited = -1)"));
103 ADFS = DFSNumber.
lookup(A);
104 BDFS = DFSNumber.
lookup(B);
106 ADFS = DFSNumber.
lookup(BA);
107 BDFS = DFSNumber.
lookup(BB);
130 VNtoScalars[{V,
InvalidVN}].push_back(I);
145 VNtoLoads[{V,
InvalidVN}].push_back(Load);
184 auto Entry = std::make_pair(V,
InvalidVN);
187 VNtoCallsScalars[Entry].push_back(Call);
189 VNtoCallsLoads[Entry].push_back(Call);
191 VNtoCallsStores[Entry].push_back(Call);
206 static const unsigned KnownIDs[] = {
221 : DT(DT), AA(AA), MD(MD), MSSA(MSSA),
235 DFSNumber[BB] = ++BBI;
237 for (
auto &Inst : *BB)
238 DFSNumber[&Inst] = ++
I;
248 auto HoistStat = hoistExpressions(F);
249 if (HoistStat.first + HoistStat.second == 0)
252 if (HoistStat.second > 0)
270 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
271 const bool HoistingGeps;
277 enum InsKind { Unknown, Scalar, Load, Store };
281 auto It = BBSideEffects.
find(BB);
282 if (It != BBSideEffects.
end())
286 BBSideEffects[BB] =
true;
291 BBSideEffects[BB] =
true;
295 BBSideEffects[BB] =
false;
310 bool hoistingFromAllPaths(
const BasicBlock *HoistBB,
320 if (WorkList.empty())
324 if (WorkList.erase(BB)) {
336 if (successorDominate(BB, HoistBB))
349 unsigned I1DFS = DFSNumber.
lookup(I1);
350 unsigned I2DFS = DFSNumber.
lookup(I2);
352 return I1DFS < I2DFS;
365 bool ReachedNewPt =
false;
368 if (
const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {
372 if (BB == OldBB && firstInBB(OldPt, Insn))
378 if (firstInBB(Insn, NewPt))
398 int &NBBsOnAllPaths) {
403 "def does not dominate new hoisting point");
418 if (NBBsOnAllPaths == 0)
428 if ((BB != OldBB) && HoistBarrier.count(BB))
432 if (hasMemoryUse(NewPt, Def, BB))
436 if (NBBsOnAllPaths != -1)
450 int &NBBsOnAllPaths) {
467 if (NBBsOnAllPaths == 0)
477 if ((BB != SrcBB) && HoistBarrier.count(BB))
481 if (NBBsOnAllPaths != -1)
511 if (
auto *UD = dyn_cast<MemoryUseOrDef>(D))
512 if (firstInBB(NewPt, UD->getMemoryInst()))
518 if (hasEHOrLoadsOnPath(NewPt, dyn_cast<MemoryDef>(U), NBBsOnAllPaths))
520 }
else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
536 bool safeToHoistScalar(
const BasicBlock *HoistBB,
538 int &NBBsOnAllPaths) {
540 if (!hoistingFromAllPaths(HoistBB, WL))
544 if (hasEHOnPath(HoistBB, BB, NBBsOnAllPaths))
552 typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo;
560 HoistingPointList &HPL, InsKind K) {
562 if (InstructionsToHoist.
size() > 2) {
577 for (++II; II != InstructionsToHoist.
end(); ++II) {
584 NewHoistBB = HoistBB;
585 NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt;
590 if (NewHoistBB == BB)
592 else if (NewHoistBB == HoistBB)
593 NewHoistPt = HoistPt;
603 if (safeToHoistScalar(NewHoistBB, WL, NumBBsOnAllPaths)) {
605 HoistPt = NewHoistPt;
606 HoistBB = NewHoistBB;
616 if ((HoistBB == NewHoistBB || BB == NewHoistBB ||
617 hoistingFromAllPaths(NewHoistBB, WL)) &&
620 safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NumBBsOnAllPaths) &&
622 K, NumBBsOnAllPaths)) {
624 HoistPt = NewHoistPt;
625 HoistBB = NewHoistBB;
632 if (std::distance(Start, II) > 1)
645 if (std::distance(Start, II) > 1)
650 void computeInsertionPoints(
const VNtoInsns &Map, HoistingPointList &HPL,
652 for (
const auto &Entry : Map) {
665 if (!hasEH(
I->getParent()))
668 if (!InstructionsToHoist.
empty())
669 partitionCandidates(InstructionsToHoist, HPL, K);
680 if (
const auto *Inst = dyn_cast<Instruction>(&
Op))
681 if (!DT->
dominates(Inst->getParent(), HoistPt))
691 if (
const auto *Inst = dyn_cast<Instruction>(&
Op))
692 if (!DT->
dominates(Inst->getParent(), HoistPt)) {
694 dyn_cast<GetElementPtrInst>(Inst)) {
695 if (!allGepOperandsAvailable(GepOp, HoistPt))
711 assert(allGepOperandsAvailable(Gep, HoistPt) &&
712 "GEP operands not available");
725 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
737 for (
const Instruction *OtherInst : InstructionsToHoist) {
739 if (
auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
740 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
742 OtherGep = cast<GetElementPtrInst>(
759 if (
auto *Ld = dyn_cast<LoadInst>(Repl)) {
761 }
else if (
auto *St = dyn_cast<StoreInst>(Repl)) {
766 if (isa<GetElementPtrInst>(Val)) {
768 if (!allGepOperandsAvailable(Val, HoistPt))
770 }
else if (!DT->
dominates(Val->getParent(), HoistPt))
776 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
779 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
781 if (Val && isa<GetElementPtrInst>(Val))
782 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
787 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) {
788 unsigned NI = 0, NL = 0, NS = 0,
NC = 0, NR = 0;
789 for (
const HoistingPointInfo &HP : HPL) {
800 if (!Repl || firstInBB(I, Repl))
805 bool MoveAccess =
true;
808 assert(allOperandsAvailable(Repl, HoistPt) &&
809 "instruction depends on operands that are not available");
814 Repl = InstructionsToHoist.front();
819 if (!allOperandsAvailable(Repl, HoistPt)) {
827 if (!makeGepOperandsAvailable(Repl, HoistPt, InstructionsToHoist))
836 DFSNumber[Repl] = DFSNumber[Last]++;
843 dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) {
848 MSSAUpdater->createMemoryAccessInBB(Repl, Def, HoistPt,
MemorySSA::End);
849 OldMemAcc->replaceAllUsesWith(NewMemAcc);
850 MSSAUpdater->removeMemoryAccess(OldMemAcc);
854 if (isa<LoadInst>(Repl))
856 else if (isa<StoreInst>(Repl))
858 else if (isa<CallInst>(Repl))
867 if (
auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
868 ReplacementLoad->setAlignment(
869 std::min(ReplacementLoad->getAlignment(),
872 }
else if (
auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
873 ReplacementStore->setAlignment(
874 std::min(ReplacementStore->getAlignment(),
877 }
else if (
auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
878 ReplacementAlloca->setAlignment(
879 std::max(ReplacementAlloca->getAlignment(),
881 }
else if (isa<CallInst>(Repl)) {
889 MSSAUpdater->removeMemoryAccess(OldMA);
904 if (
MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
907 for (
auto *Phi : UsePhis) {
908 auto In = Phi->incoming_values();
909 if (
all_of(
In, [&](
Use &U) {
return U == NewMemAcc; })) {
910 Phi->replaceAllUsesWith(NewMemAcc);
911 MSSAUpdater->removeMemoryAccess(Phi);
917 NumHoisted += NL + NS +
NC + NI;
919 NumLoadsHoisted += NL;
920 NumStoresHoisted += NS;
921 NumCallsHoisted +=
NC;
922 return {NI, NL +
NC + NS};
927 std::pair<unsigned, unsigned> hoistExpressions(
Function &
F) {
933 int InstructionNb = 0;
938 HoistBarrier.insert(BB);
947 if (isa<TerminatorInst>(&I1))
950 if (
auto *Load = dyn_cast<LoadInst>(&I1))
952 else if (
auto *Store = dyn_cast<StoreInst>(&I1))
954 else if (
auto *Call = dyn_cast<CallInst>(&I1)) {
955 if (
auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
956 if (isa<DbgInfoIntrinsic>(Intr) ||
957 Intr->getIntrinsicID() == Intrinsic::assume)
960 if (
Call->mayHaveSideEffects())
963 if (
Call->isConvergent())
967 }
else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
976 HoistingPointList HPL;
998 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
999 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1000 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1001 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1037 "Early GVN Hoisting of Expressions",
false,
false)
Legacy wrapper pass to provide the GlobalsAAResult object.
const VNtoInsns & getVNTable() const
void setDomTree(DominatorTree *D)
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
static cl::opt< int > MaxDepthInBB("gvn-hoist-max-depth", cl::Hidden, cl::init(100), cl::desc("Hoist instructions from the beginning of the BB up to the ""maximum specified depth (default = 100, unlimited = -1)"))
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Provides a lazy, caching interface for making common memory aliasing information queries, backed by LLVM's alias analysis passes.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
SmallVectorImpl< Instruction * > SmallVecImplInsn
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const VNtoInsns & getStoreVNTable() const
gvn Early GVN Hoisting of false
STATISTIC(NumFunctions,"Total number of functions")
This is the interface for a simple mod/ref and alias analysis over globals.
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
bool operator()(const Instruction *A, const Instruction *B) const
Implements a dense probed hash-table based set.
unsigned getNumOperands() const
const VNtoInsns & getVNTable() const
This class represents a function call, abstracting a target machine's calling convention.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
void setAliasAnalysis(AliasAnalysis *A)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
bool isEHPad() const
Return true if this basic block is an exception handling block.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
Analysis pass which computes a DominatorTree.
FunctionPass * createGVNHoistPass()
An instruction for reading from memory.
const VNtoInsns & getScalarVNTable() const
static void combineKnownMetadata(Instruction *ReplInst, Instruction *I)
gvn Early GVN Hoisting of Expressions
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Represents read-only accesses to memory.
bool onlyReadsMemory() const
Determine if the call does not access or only reads memory.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
static uint32_t getAlignment(const MCSectionCOFF &Sec)
Legacy analysis pass which computes MemorySSA.
static Value * getPointerOperand(Instruction &Inst)
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
void clear()
Remove all entries from the ValueTable.
DenseMap< const BasicBlock *, bool > BBSideEffectsSet
A Use represents the edge between a Value definition and its users.
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.
MemoryUseOrDef * getMemoryAccess(const Instruction *) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
void insert(Instruction *I, GVN::ValueTable &VN)
An analysis that produces MemoryDependenceResults for a function.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
LLVM_NODISCARD bool empty() const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
BasicBlock * getBlock() const
SmallVector< Instruction *, 4 > SmallVecInsn
void insert(LoadInst *Load, GVN::ValueTable &VN)
The core GVN pass object.
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
const VNtoInsns & getLoadVNTable() const
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
idf_iterator< T > idf_begin(const T &G)
iterator find(const_arg_type_t< KeyT > Val)
idf_iterator< T > idf_end(const T &G)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
void insert(CallInst *Call, GVN::ValueTable &VN)
initializer< Ty > init(const Ty &Val)
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
A set of analyses that are preserved following a run of a transformation pass.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const VNtoInsns & getVNTable() const
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
LLVM Basic Block Representation.
This class holds the mapping between values and value numbers.
df_iterator< T > df_end(const T &G)
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
A manager for alias analyses.
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.
bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
Analysis pass providing a never-invalidated alias analysis result.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
bool doesNotAccessMemory() const
Determine if the call does not access memory.
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
Value * getPointerOperand()
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
static cl::opt< int > MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1), cl::desc("Max number of instructions to hoist ""(default unlimited = -1)"))
INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass,"gvn-hoist","Early GVN Hoisting of Expressions", false, false) INITIALIZE_PASS_END(GVNHoistLegacyPass
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static cl::opt< int > MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10), cl::desc("Maximum length of dependent chains to hoist ""(default = 10, unlimited = -1)"))
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance...
An intrusive list with ownership and callbacks specified/controlled by ilist_traits, only with API safe for polymorphic types.
DenseMap< std::pair< unsigned, unsigned >, SmallVector< Instruction *, 4 > > VNtoInsns
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, AliasAnalysis &AA)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
GVNHoist(DominatorTree *DT, AliasAnalysis *AA, MemoryDependenceResults *MD, MemorySSA *MSSA)
An analysis that produces MemorySSA for a function.
static cl::opt< int > MaxNumberOfBBSInPath("gvn-hoist-max-bbs", cl::Hidden, cl::init(4), cl::desc("Max number of basic blocks on the path between ""hoisting locations (default = 4, unlimited = -1)"))
const BasicBlock & getEntryBlock() const
gvn hoist
When an instruction is found to only use loop invariant operands that is safe to hoist, this instruction is called to do the dirty work.
df_iterator< T > df_begin(const T &G)
Class that has the common methods + fields of memory uses/defs.
typename SuperClass::iterator iterator
iterator_range< user_iterator > users()
void insert(StoreInst *Store, GVN::ValueTable &VN)
bool mayThrow() const
Return true if this instruction may throw an exception.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void initializeGVNHoistLegacyPassPass(PassRegistry &)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
void setMemDep(MemoryDependenceResults *M)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void preserve()
Mark an analysis as preserved.
uint32_t lookupOrAdd(Value *V)
lookup_or_add - Returns the value number for the specified value, assigning it a new number if it did...
iterator_range< df_iterator< T > > depth_first(const T &G)
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
SortByDFSIn(DenseMap< const Value *, unsigned > &D)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
void removeInstruction(Instruction *InstToRemove)
Removes an instruction from the dependence analysis, updating the dependence of instructions that pre...
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
Represents phi nodes for memory accesses.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
const AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
Value * getPointerOperand()
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs)
Combine the metadata of two instructions so that K can replace J.
const BasicBlock * getParent() const
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.