58 #define DEBUG_TYPE "mem2reg" 60 STATISTIC(NumLocalPromoted,
"Number of alloca's promoted within one block");
61 STATISTIC(NumSingleStore,
"Number of alloca's promoted with a single store");
62 STATISTIC(NumDeadAlloca,
"Number of dead alloca's removed");
63 STATISTIC(NumPHIInsert,
"Number of PHI nodes inserted");
72 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
77 }
else if (
const StoreInst *
SI = dyn_cast<StoreInst>(U)) {
78 if (
SI->getOperand(0) == AI)
84 }
else if (
const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
85 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
86 II->getIntrinsicID() != Intrinsic::lifetime_end)
88 }
else if (
const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
96 if (!GEPI->hasAllZeroIndices())
116 bool OnlyUsedInOneBlock;
118 Value *AllocaPointerVal;
122 DefiningBlocks.
clear();
126 OnlyUsedInOneBlock =
true;
127 AllocaPointerVal =
nullptr;
145 AllocaPointerVal =
SI->getOperand(0);
148 LoadInst *LI = cast<LoadInst>(User);
152 AllocaPointerVal = LI;
155 if (OnlyUsedInOneBlock) {
159 OnlyUsedInOneBlock =
false;
168 struct RenamePassData {
169 using ValVector = std::vector<Value *>;
170 using LocationVector = std::vector<DebugLoc>;
173 : BB(B), Pred(P), Values(std::move(V)), Locations(std::move(L)) {}
178 LocationVector Locations;
186 class LargeBlockInfo {
197 static bool isInterestingInstruction(
const Instruction *
I) {
198 return (isa<LoadInst>(I) && isa<AllocaInst>(I->
getOperand(0))) ||
199 (isa<StoreInst>(
I) && isa<AllocaInst>(I->
getOperand(1)));
203 unsigned getInstructionIndex(
const Instruction *I) {
204 assert(isInterestingInstruction(I) &&
205 "Not a load/store to/from an alloca?");
209 if (It != InstNumbers.
end())
218 if (isInterestingInstruction(&BBI))
219 InstNumbers[&BBI] = InstNo++;
220 It = InstNumbers.
find(I);
222 assert(It != InstNumbers.
end() &&
"Didn't insert instruction?");
231 struct PromoteMem2Reg {
233 std::vector<AllocaInst *> Allocas;
261 std::vector<Value *> PointerAllocaValues;
281 : Allocas(Allocas.
begin(), Allocas.
end()), DT(DT),
289 void RemoveFromAllocasList(
unsigned &AllocaIdx) {
290 Allocas[AllocaIdx] = Allocas.
back();
296 unsigned &NP = BBNumPreds[BB];
306 RenamePassData::ValVector &IncVals,
307 RenamePassData::LocationVector &IncLocs,
308 std::vector<RenamePassData> &Worklist);
320 LoadNotNull->insertAfter(LI);
333 if (isa<LoadInst>(I) || isa<StoreInst>(
I))
362 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->
getOperand(0));
367 Info.UsingBlocks.clear();
371 if (!isa<LoadInst>(UserInst)) {
372 assert(UserInst == OnlyStore &&
"Should only have load/stores");
375 LoadInst *LI = cast<LoadInst>(UserInst);
381 if (!StoringGlobalVal) {
386 if (StoreIndex == -1)
387 StoreIndex = LBI.getInstructionIndex(OnlyStore);
389 if (
unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
391 Info.UsingBlocks.push_back(StoreBB);
399 Info.UsingBlocks.push_back(LI->
getParent());
424 if (!Info.UsingBlocks.empty())
433 LBI.deleteValue(DII);
436 Info.OnlyStore->eraseFromParent();
437 LBI.deleteValue(Info.OnlyStore);
472 StoresByIndexTy StoresByIndex;
476 StoresByIndex.
push_back(std::make_pair(LBI.getInstructionIndex(
SI),
SI));
489 unsigned LoadIdx = LBI.getInstructionIndex(LI);
492 StoresByIndexTy::iterator
I =
494 std::make_pair(LoadIdx,
495 static_cast<StoreInst *>(
nullptr)),
497 if (I == StoresByIndex.begin()) {
498 if (StoresByIndex.empty())
509 Value *ReplVal = std::prev(I)->second->getOperand(0);
544 LBI.deleteValue(DII);
551 void PromoteMem2Reg::run() {
552 Function &
F = *DT.getRoot()->getParent();
554 AllocaDbgDeclares.resize(Allocas.size());
560 for (
unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
565 "All allocas should be in the same function, which is same as DF!");
574 RemoveFromAllocasList(AllocaNum);
581 Info.AnalyzeAlloca(AI);
585 if (Info.DefiningBlocks.size() == 1) {
588 RemoveFromAllocasList(AllocaNum);
596 if (Info.OnlyUsedInOneBlock &&
599 RemoveFromAllocasList(AllocaNum);
605 if (BBNumbers.empty()) {
608 BBNumbers[&BB] = ID++;
612 if (!Info.DbgDeclares.empty())
613 AllocaDbgDeclares[AllocaNum] = Info.DbgDeclares;
616 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
625 DefBlocks.
insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
640 if (PHIBlocks.
size() > 1)
643 return BBNumbers.lookup(A) < BBNumbers.lookup(
B);
648 QueuePhiNode(BB, AllocaNum, CurrentVersion);
659 RenamePassData::ValVector Values(Allocas.size());
660 for (
unsigned i = 0, e = Allocas.size(); i != e; ++i)
665 RenamePassData::LocationVector Locations(Allocas.size());
669 std::vector<RenamePassData> RenamePassWorkList;
670 RenamePassWorkList.emplace_back(&F.
front(),
nullptr, std::move(Values),
671 std::move(Locations));
673 RenamePassData RPD = std::move(RenamePassWorkList.back());
674 RenamePassWorkList.pop_back();
676 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RPD.Locations, RenamePassWorkList);
677 }
while (!RenamePassWorkList.empty());
689 A->eraseFromParent();
693 for (
auto &Declares : AllocaDbgDeclares)
694 for (
auto *DII : Declares)
695 DII->eraseFromParent();
701 bool EliminatedAPHI =
true;
702 while (EliminatedAPHI) {
703 EliminatedAPHI =
false;
710 I = NewPhiNodes.begin(),
711 E = NewPhiNodes.end();
720 EliminatedAPHI =
true;
733 I = NewPhiNodes.begin(),
734 E = NewPhiNodes.end();
740 if (&BB->
front() != SomePHI)
764 "PHI node has entry for a block which is not a predecessor!");
776 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
800 Info.UsingBlocks.end());
805 for (
unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
807 if (!DefBlocks.
count(BB))
814 if (
SI->getOperand(1) != AI)
819 LiveInBlockWorklist[i] = LiveInBlockWorklist.
back();
820 LiveInBlockWorklist.pop_back();
826 if (
LoadInst *LI = dyn_cast<LoadInst>(
I)) {
827 if (LI->getOperand(0) != AI)
839 while (!LiveInBlockWorklist.empty()) {
840 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
844 if (!LiveInBlocks.
insert(BB).second)
856 LiveInBlockWorklist.push_back(
P);
864 bool PromoteMem2Reg::QueuePhiNode(
BasicBlock *BB,
unsigned AllocaNo,
867 PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
875 PN =
PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
879 PhiToAllocaMap[PN] = AllocaNo;
886 bool ApplyMergedLoc) {
899 RenamePassData::ValVector &IncomingVals,
900 RenamePassData::LocationVector &IncomingLocs,
901 std::vector<RenamePassData> &Worklist) {
908 if (PhiToAllocaMap.count(APN)) {
915 unsigned NewPHINumOperands = APN->getNumOperands();
918 assert(NumEdges &&
"Must be at least one edge from Pred to BB!");
923 unsigned AllocaNo = PhiToAllocaMap[APN];
927 APN->getNumIncomingValues() > 0);
930 for (
unsigned i = 0; i != NumEdges; ++i)
931 APN->addIncoming(IncomingVals[AllocaNo], Pred);
934 IncomingVals[AllocaNo] = APN;
946 }
while (APN->getNumOperands() == NewPHINumOperands);
951 if (!Visited.insert(BB).second)
957 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
963 if (AI == AllocaLookup.
end())
966 Value *V = IncomingVals[AI->second];
976 LI->replaceAllUsesWith(V);
978 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(I)) {
986 if (ai == AllocaLookup.
end())
990 unsigned AllocaNo = ai->second;
991 IncomingVals[AllocaNo] =
SI->getOperand(0);
994 IncomingLocs[AllocaNo] =
SI->getDebugLoc();
1016 if (VisitedSuccs.
insert(*I).second)
1017 Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);
1025 if (Allocas.
empty())
1028 PromoteMem2Reg(Allocas, DT, AC).run();
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
const T & back() const
back - Get the last element.
iterator erase(iterator where)
Compute iterated dominance frontiers using a linear time algorithm.
This class represents a function call, abstracting a target machine's calling convention.
A cache of @llvm.assume calls within a function.
STATISTIC(NumFunctions, "Total number of functions")
static CallInst * Create(Value *Func, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
An instruction for reading from memory.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
PointerType * getType() const
Overload to return most specific pointer type.
void setDefiningBlocks(const SmallPtrSetImpl< BasicBlock *> &Blocks)
Give the IDF calculator the set of blocks in which the value is defined.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
static StringRef getName(Value *V)
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Type * getType() const
All values are typed, get the type of this value.
This class represents a no-op cast from one type to another.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
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...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * getOperand(unsigned i) const
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Interval::succ_iterator succ_end(Interval *I)
iterator find(const_arg_type_t< KeyT > Val)
bool isVoidTy() const
Return true if this is 'void'.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
bool erase(const KeyT &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM Basic Block Representation.
static void ComputeLiveInBlocks(const SmallPtrSetImpl< BasicBlock *> &UsingBlocks, const SmallPtrSetImpl< BasicBlock *> &DefBlocks, SmallPtrSetImpl< BasicBlock *> &LiveInBlocks, PredIteratorCache &PredCache)
Given sets of UsingBlocks and DefBlocks, compute the set of LiveInBlocks.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
void ConvertDebugDeclareToDebugValue(DbgInfoIntrinsic *DII, StoreInst *SI, DIBuilder &Builder)
===---------------------------------------------------------------——===// Dbg Intrinsic utilities ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
const Instruction & front() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
const Instruction & back() const
This instruction compares its operands according to the predicate given to the constructor.
Interval::pred_iterator pred_end(Interval *I)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
iterator erase(const_iterator CI)
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
void sort(IteratorTy Start, IteratorTy End)
const InstListType & getInstList() const
Return the underlying instruction list container.
void setLiveInBlocks(const SmallPtrSetImpl< BasicBlock *> &Blocks)
Give the IDF calculator the set of blocks in which the value is live on entry to the block...
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void calculate(SmallVectorImpl< BasicBlock *> &IDFBlocks)
Calculate iterated dominance frontiers.
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.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
This is the common base class for debug info intrinsics.
void applyMergedLocation(const DILocation *LocA, const DILocation *LocB)
Merge 2 debug locations and apply it to the Instruction.
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...
pred_range predecessors(BasicBlock *BB)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
iterator_range< user_iterator > users()
TinyPtrVector< DbgInfoIntrinsic * > FindDbgAddrUses(Value *V)
Finds all intrinsics declaring local variables as living in the memory that 'V' points to...
static void clear(coro::Shape &Shape)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
unsigned pred_size(const BasicBlock *BB)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Determine the iterated dominance frontier, given a set of defining blocks, and optionally, a set of live-in blocks.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
void PromoteMemToReg(ArrayRef< AllocaInst *> Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Return true if the given value is known to be non-zero when defined.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Function object to check whether the first component of a std::pair compares less than the first comp...
bool empty() const
empty - Check if the array is empty.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack