62 #define DEBUG_TYPE "amdgpu-promote-alloca" 69 "disable-promote-alloca-to-vector",
70 cl::desc(
"Disable promote alloca to vector"),
85 bool IsAMDGCN =
false;
86 bool IsAMDHSA =
false;
88 std::pair<Value *, Value *> getLocalSizeYZ(
IRBuilder<> &Builder);
93 bool collectUsesWithPtrTypes(
Value *BaseAlloca,
95 std::vector<Value*> &WorkList)
const;
101 bool binaryOpIsDerivedFromSameAlloca(
Value *Alloca,
Value *Val,
103 int OpIdx0,
int OpIdx1)
const;
106 bool hasSufficientLocalMem(
const Function &
F);
113 bool doInitialization(
Module &M)
override;
116 StringRef getPassName()
const override {
return "AMDGPU Promote Alloca"; }
118 bool handleAlloca(
AllocaInst &
I,
bool SufficientLDS);
131 "AMDGPU promote alloca to vector or LDS",
false,
false)
135 bool AMDGPUPromoteAlloca::doInitialization(
Module &M) {
137 DL = &
Mod->getDataLayout();
146 if (
auto *TPC = getAnalysisIfAvailable<TargetPassConfig>())
151 const Triple &TT =
TM->getTargetTriple();
161 bool SufficientLDS = hasSufficientLocalMem(F);
162 bool Changed =
false;
164 for (
auto I = EntryBB.
begin(),
E = EntryBB.
end();
I !=
E; ) {
169 Changed |= handleAlloca(*AI, SufficientLDS);
175 std::pair<Value *, Value *>
176 AMDGPUPromoteAlloca::getLocalSizeYZ(
IRBuilder<> &Builder) {
192 return std::make_pair(LocalSizeY, LocalSizeZ);
260 return std::make_pair(Y, LoadZU);
270 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_x
271 : Intrinsic::r600_read_tidig_x;
274 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_y
275 : Intrinsic::r600_read_tidig_y;
279 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_z
280 : Intrinsic::r600_read_tidig_z;
300 const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
303 auto I = GEPIdx.find(GEP);
304 return I == GEPIdx.end() ? nullptr : I->second;
328 LoadInst *LI = cast<LoadInst>(Inst);
331 case Instruction::BitCast:
347 if (DisablePromoteAllocaToVector) {
348 LLVM_DEBUG(
dbgs() <<
" Promotion alloca to vector is disabled\n");
368 std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
369 std::vector<Value*> WorkList;
370 for (
User *AllocaUser : Alloca->
users()) {
376 WorkList.push_back(AllocaUser);
385 LLVM_DEBUG(
dbgs() <<
" Cannot compute vector index for GEP " << *GEP
391 for (
User *GEPUser : AllocaUser->
users()) {
395 WorkList.push_back(GEPUser);
401 LLVM_DEBUG(
dbgs() <<
" Converting alloca to vector " << *AllocaTy <<
" -> " 402 << *VectorTy <<
'\n');
404 for (
Value *V : WorkList) {
413 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
414 Value *VecValue = Builder.CreateLoad(BitCast);
415 Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
426 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
427 Value *VecValue = Builder.CreateLoad(BitCast);
428 Value *NewVecValue = Builder.CreateInsertElement(VecValue,
431 Builder.CreateStore(NewVecValue, BitCast);
435 case Instruction::BitCast:
436 case Instruction::AddrSpaceCast:
452 case Intrinsic::memcpy:
453 case Intrinsic::memmove:
454 case Intrinsic::memset:
455 case Intrinsic::lifetime_start:
456 case Intrinsic::lifetime_end:
457 case Intrinsic::invariant_start:
458 case Intrinsic::invariant_end:
459 case Intrinsic::launder_invariant_group:
460 case Intrinsic::strip_invariant_group:
461 case Intrinsic::objectsize:
468 bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(
Value *BaseAlloca,
478 if (isa<ConstantPointerNull>(OtherOp))
482 if (!isa<AllocaInst>(OtherObj))
491 if (OtherObj != BaseAlloca) {
493 dbgs() <<
"Found a binary instruction with another alloca object\n");
500 bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
503 std::vector<Value*> &WorkList)
const {
513 WorkList.push_back(
User);
518 if (UseInst->
getOpcode() == Instruction::PtrToInt)
521 if (
LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
522 if (LI->isVolatile())
528 if (
StoreInst *
SI = dyn_cast<StoreInst>(UseInst)) {
529 if (
SI->isVolatile())
533 if (
SI->getPointerOperand() != Val)
535 }
else if (
AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
536 if (RMW->isVolatile())
539 if (CAS->isVolatile())
545 if (
ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
546 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
550 WorkList.push_back(ICmp);
553 if (UseInst->
getOpcode() == Instruction::AddrSpaceCast) {
558 WorkList.push_back(
User);
568 if (!
GEP->isInBounds())
575 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val,
SI, 1, 2))
580 if (
PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
583 switch (Phi->getNumIncomingValues()) {
587 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
595 WorkList.push_back(
User);
596 if (!collectUsesWithPtrTypes(BaseAlloca,
User, WorkList))
603 bool AMDGPUPromoteAlloca::hasSufficientLocalMem(
const Function &F) {
615 LLVM_DEBUG(
dbgs() <<
"Function has local memory argument. Promoting to " 616 "local memory disabled.\n");
622 if (LocalMemLimit == 0)
628 CurrentLocalMemUsage = 0;
639 unsigned Align = GV.getAlignment();
648 CurrentLocalMemUsage =
alignTo(CurrentLocalMemUsage, Align);
649 CurrentLocalMemUsage += AllocSize;
664 if (OccupancyHint == 0)
672 MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
676 unsigned MaxSizeWithWaveCount
680 if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
683 LocalMemLimit = MaxSizeWithWaveCount;
687 <<
" Rounding size to " << MaxSizeWithWaveCount
688 <<
" with a maximum occupancy of " << MaxOccupancy <<
'\n' 689 <<
" and " << (LocalMemLimit - CurrentLocalMemUsage)
690 <<
" available for promotion\n");
696 bool AMDGPUPromoteAlloca::handleAlloca(
AllocaInst &
I,
bool SufficientLDS) {
725 <<
" promote alloca to LDS not supported with calling convention.\n");
750 NewSize += AllocSize;
752 if (NewSize > LocalMemLimit) {
754 <<
" bytes of local memory not available to promote\n");
758 CurrentLocalMemUsage = NewSize;
760 std::vector<Value*> WorkList;
762 if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
782 Value *TCntY, *TCntZ;
784 std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
785 Value *TIdX = getWorkitemID(Builder, 0);
786 Value *TIdY = getWorkitemID(Builder, 1);
787 Value *TIdZ = getWorkitemID(Builder, 2);
805 for (
Value *V : WorkList) {
808 if (
ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
809 Value *Src0 = CI->getOperand(0);
813 if (isa<ConstantPointerNull>(CI->getOperand(0)))
816 if (isa<ConstantPointerNull>(CI->getOperand(1)))
824 if (isa<AddrSpaceCastInst>(V))
832 V->mutateType(NewTy);
836 if (isa<ConstantPointerNull>(
SI->getOperand(1)))
839 if (isa<ConstantPointerNull>(
SI->getOperand(2)))
841 }
else if (
PHINode *Phi = dyn_cast<PHINode>(V)) {
842 for (
unsigned I = 0,
E = Phi->getNumIncomingValues(); I !=
E; ++
I) {
843 if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
854 case Intrinsic::lifetime_start:
855 case Intrinsic::lifetime_end:
859 case Intrinsic::memcpy: {
867 case Intrinsic::memmove: {
875 case Intrinsic::memset: {
883 case Intrinsic::invariant_start:
884 case Intrinsic::invariant_end:
885 case Intrinsic::launder_invariant_group:
886 case Intrinsic::strip_invariant_group:
892 case Intrinsic::objectsize: {
896 Intrinsic::objectsize,
915 return new AMDGPUPromoteAlloca();
bool makeLIDRangeMetadata(Instruction *I) const
Creates value range metadata on an workitemid.* inrinsic call or load.
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
unsigned getMaxWavesPerEU(unsigned FlatWorkGroupSize) const
Value * getPointerOperand(Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
AMDGPU specific subclass of TargetSubtarget.
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
Compute iterated dominance frontiers using a linear time algorithm.
A Module instance is used to store all the information related to an LLVM module. ...
unsigned getOccupancyWithLocalMemSize(uint32_t Bytes, const Function &) const
Inverse of getMaxLocalMemWithWaveCount.
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
OSType getOS() const
getOS - Get the parsed operating system type of this triple.
bool isPromoteAllocaEnabled() const
This class represents a function call, abstracting a target machine's calling convention.
AMDGPUAS getAMDGPUAS(const Module &M)
unsigned getSourceAlignment() const
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
The two locations do not alias at all.
This class wraps the llvm.memset intrinsic.
FunctionPass * createAMDGPUPromoteAlloca()
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memset to the specified pointer and the specified value.
An instruction for reading from memory.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Address space for local memory.
Value * getLength() const
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
static const AMDGPUSubtarget & get(const MachineFunction &MF)
Address space for constant memory (VTX2)
This class represents the LLVM 'select' instruction.
Type * getPointerElementType() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
OpenCL uses address spaces to differentiate between various memory regions on the hardware...
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
This class wraps the llvm.memmove intrinsic.
int getLocalMemorySize() const
A Use represents the edge between a Value definition and its users.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This file contains the simple types necessary to represent the attributes associated with functions a...
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
CallInst * CreateMemMove(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memmove between the specified pointers.
unsigned getDestAlignment() const
uint64_t getNumElements() const
This file implements a class to represent arbitrary precision integral constant values and operations...
SPIR_KERNEL - Calling convention for SPIR kernel functions.
Class to represent function types.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Type * getType() const
All values are typed, get the type of this value.
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
BasicBlock * GetInsertBlock() const
Class to represent array types.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Value * getOperand(unsigned i) const
Class to represent pointers.
Value * getOperand(unsigned i_nocapture) const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
std::pair< unsigned, unsigned > getWavesPerEU(const Function &F) const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
ArrayRef< Type * > params() const
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
FunctionPass class - This class is used to implement most global optimizations.
Value * getPointerOperand()
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Triple - Helper class for working with autoconf configuration names.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
unsigned getNumOperands() const
This is the shared class of boolean and integer constants.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Module.h This file contains the declarations for the Module class.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
CallInst * CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memcpy between the specified pointers.
This class wraps the llvm.memcpy intrinsic.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Value * getRawSource() const
Return the arguments to the instruction.
Value * CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name="")
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
The access may modify the value stored in memory.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Class to represent vector types.
iterator_range< user_iterator > users()
Calling convention for AMDGPU code object kernels.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
void setUnnamedAddr(UnnamedAddr Val)
static IntegerType * getInt32Ty(LLVMContext &C)
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 isZero() const
This is just a convenience method to make client code smaller for a common code.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Rename collisions when linking (static functions).
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void addDereferenceableAttr(unsigned i, uint64_t Bytes)
adds the dereferenceable attribute to the list of attributes.
LoadInst * CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name)
Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' correctly, instead of converting the strin...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Primary interface to the complete machine description for the target machine.
Type * getElementType() const
char & AMDGPUPromoteAllocaID
StringRef - Represent a constant reference to a string, i.e.
unsigned getMaxLocalMemSizeWithWaveCount(unsigned WaveCount, const Function &) const
Return the amount of LDS that can be used that will not restrict the occupancy lower than WaveCount...
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
std::pair< unsigned, unsigned > getFlatWorkGroupSizes(const Function &F) const
Value * getPointerOperand()
Value * getRawDest() const
unsigned PRIVATE_ADDRESS
Address space for private memory.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.