40 #include "llvm/IR/IntrinsicsAMDGPU.h" 41 #include "llvm/IR/IntrinsicsR600.h" 63 #define DEBUG_TYPE "amdgpu-promote-alloca" 70 "disable-promote-alloca-to-vector",
71 cl::desc(
"Disable promote alloca to vector"),
75 "disable-promote-alloca-to-lds",
76 cl::desc(
"Disable promote alloca to LDS"),
90 bool IsAMDGCN =
false;
91 bool IsAMDHSA =
false;
93 std::pair<Value *, Value *> getLocalSizeYZ(
IRBuilder<> &Builder);
98 bool collectUsesWithPtrTypes(
Value *BaseAlloca,
100 std::vector<Value*> &WorkList)
const;
106 bool binaryOpIsDerivedFromSameAlloca(
Value *Alloca,
Value *Val,
108 int OpIdx0,
int OpIdx1)
const;
111 bool hasSufficientLocalMem(
const Function &
F);
118 bool doInitialization(
Module &M)
override;
121 StringRef getPassName()
const override {
return "AMDGPU Promote Alloca"; }
123 bool handleAlloca(
AllocaInst &
I,
bool SufficientLDS);
136 "AMDGPU promote alloca to vector or LDS",
false,
false)
140 bool AMDGPUPromoteAlloca::doInitialization(
Module &M) {
142 DL = &
Mod->getDataLayout();
151 if (
auto *TPC = getAnalysisIfAvailable<TargetPassConfig>())
164 bool SufficientLDS = hasSufficientLocalMem(F);
165 bool Changed =
false;
175 if (handleAlloca(*AI, SufficientLDS))
182 std::pair<Value *, Value *>
183 AMDGPUPromoteAlloca::getLocalSizeYZ(
IRBuilder<> &Builder) {
199 return std::make_pair(LocalSizeY, LocalSizeZ);
260 LoadXY->
setMetadata(LLVMContext::MD_invariant_load, MD);
261 LoadZU->
setMetadata(LLVMContext::MD_invariant_load, MD);
267 return std::make_pair(Y, LoadZU);
277 IntrID = IsAMDGCN ? (
Intrinsic::ID)Intrinsic::amdgcn_workitem_id_x
281 IntrID = IsAMDGCN ? (
Intrinsic::ID)Intrinsic::amdgcn_workitem_id_y
286 IntrID = IsAMDGCN ? (
Intrinsic::ID)Intrinsic::amdgcn_workitem_id_z
307 const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
310 auto I = GEPIdx.find(GEP);
311 return I == GEPIdx.end() ? nullptr : I->second;
335 LoadInst *LI = cast<LoadInst>(Inst);
336 if (isa<AllocaInst>(User) &&
338 isa<VectorType>(LI->
getType()))
342 case Instruction::BitCast:
349 if (isa<AllocaInst>(User) &&
362 if (DisablePromoteAllocaToVector) {
363 LLVM_DEBUG(
dbgs() <<
" Promotion alloca to vector is disabled\n");
384 std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
385 std::vector<Value*> WorkList;
386 for (
User *AllocaUser : Alloca->
users()) {
392 WorkList.push_back(AllocaUser);
401 LLVM_DEBUG(
dbgs() <<
" Cannot compute vector index for GEP " << *GEP
407 for (
User *GEPUser : AllocaUser->
users()) {
411 WorkList.push_back(GEPUser);
419 LLVM_DEBUG(
dbgs() <<
" Converting alloca to vector " << *AllocaTy <<
" -> " 420 << *VectorTy <<
'\n');
422 for (
Value *V : WorkList) {
434 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
435 Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
436 Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
449 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
450 Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
451 Value *NewVecValue = Builder.CreateInsertElement(VecValue,
454 Builder.CreateStore(NewVecValue, BitCast);
458 case Instruction::BitCast:
459 case Instruction::AddrSpaceCast:
475 case Intrinsic::memcpy:
476 case Intrinsic::memmove:
477 case Intrinsic::memset:
478 case Intrinsic::lifetime_start:
479 case Intrinsic::lifetime_end:
480 case Intrinsic::invariant_start:
481 case Intrinsic::invariant_end:
482 case Intrinsic::launder_invariant_group:
483 case Intrinsic::strip_invariant_group:
484 case Intrinsic::objectsize:
491 bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(
Value *BaseAlloca,
501 if (isa<ConstantPointerNull>(OtherOp))
505 if (!isa<AllocaInst>(OtherObj))
514 if (OtherObj != BaseAlloca) {
516 dbgs() <<
"Found a binary instruction with another alloca object\n");
523 bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
526 std::vector<Value*> &WorkList)
const {
536 WorkList.push_back(
User);
541 if (UseInst->
getOpcode() == Instruction::PtrToInt)
544 if (
LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
545 if (LI->isVolatile())
551 if (
StoreInst *
SI = dyn_cast<StoreInst>(UseInst)) {
552 if (
SI->isVolatile())
556 if (
SI->getPointerOperand() != Val)
558 }
else if (
AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
559 if (RMW->isVolatile())
562 if (CAS->isVolatile())
568 if (
ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
569 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
573 WorkList.push_back(ICmp);
576 if (UseInst->
getOpcode() == Instruction::AddrSpaceCast) {
581 WorkList.push_back(
User);
591 if (!
GEP->isInBounds())
598 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val,
SI, 1, 2))
603 if (
PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
606 switch (Phi->getNumIncomingValues()) {
610 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
618 WorkList.push_back(
User);
619 if (!collectUsesWithPtrTypes(BaseAlloca,
User, WorkList))
626 bool AMDGPUPromoteAlloca::hasSufficientLocalMem(
const Function &F) {
638 LLVM_DEBUG(
dbgs() <<
"Function has local memory argument. Promoting to " 639 "local memory disabled.\n");
645 if (LocalMemLimit == 0)
651 CurrentLocalMemUsage = 0;
662 unsigned Align = GV.getAlignment();
671 CurrentLocalMemUsage =
alignTo(CurrentLocalMemUsage, Align);
672 CurrentLocalMemUsage += AllocSize;
687 if (OccupancyHint == 0)
695 MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
699 unsigned MaxSizeWithWaveCount
703 if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
706 LocalMemLimit = MaxSizeWithWaveCount;
710 <<
" Rounding size to " << MaxSizeWithWaveCount
711 <<
" with a maximum occupancy of " << MaxOccupancy <<
'\n' 712 <<
" and " << (LocalMemLimit - CurrentLocalMemUsage)
713 <<
" available for promotion\n");
719 bool AMDGPUPromoteAlloca::handleAlloca(
AllocaInst &
I,
bool SufficientLDS) {
735 if (DisablePromoteAllocaToLDS)
751 <<
" promote alloca to LDS not supported with calling convention.\n");
776 NewSize += AllocSize;
778 if (NewSize > LocalMemLimit) {
780 <<
" bytes of local memory not available to promote\n");
784 CurrentLocalMemUsage = NewSize;
786 std::vector<Value*> WorkList;
788 if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
808 Value *TCntY, *TCntZ;
810 std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
811 Value *TIdX = getWorkitemID(Builder, 0);
812 Value *TIdY = getWorkitemID(Builder, 1);
813 Value *TIdZ = getWorkitemID(Builder, 2);
831 for (
Value *V : WorkList) {
834 if (
ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
835 Value *Src0 = CI->getOperand(0);
839 if (isa<ConstantPointerNull>(CI->getOperand(0)))
842 if (isa<ConstantPointerNull>(CI->getOperand(1)))
850 if (isa<AddrSpaceCastInst>(V))
858 V->mutateType(NewTy);
862 if (isa<ConstantPointerNull>(
SI->getOperand(1)))
865 if (isa<ConstantPointerNull>(
SI->getOperand(2)))
867 }
else if (
PHINode *Phi = dyn_cast<PHINode>(V)) {
868 for (
unsigned I = 0,
E = Phi->getNumIncomingValues(); I !=
E; ++
I) {
869 if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
880 case Intrinsic::lifetime_start:
881 case Intrinsic::lifetime_end:
885 case Intrinsic::memcpy: {
893 case Intrinsic::memmove: {
901 case Intrinsic::memset: {
909 case Intrinsic::invariant_start:
910 case Intrinsic::invariant_end:
911 case Intrinsic::launder_invariant_group:
912 case Intrinsic::strip_invariant_group:
918 case Intrinsic::objectsize: {
922 Intrinsic::objectsize,
942 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. ...
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AMDGPU specific subclass of TargetSubtarget.
This class represents lattice values for constants.
A Module instance is used to store all the information related to an LLVM module. ...
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, unsigned Align, const char *Name)
Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' correctly, instead of converting the strin...
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
void push_back(const T &Elt)
MaybeAlign getDestAlign() const
This class represents a function call, abstracting a target machine's calling convention.
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()
Type * getPointerOperandType() const
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.
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
Value * getLength() const
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
static const AMDGPUSubtarget & get(const MachineFunction &MF)
SPIR_KERNEL - Calling convention for SPIR kernel functions.
This class represents the LLVM 'select' instruction.
Type * getPointerElementType() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
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 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)
unsigned getDestAlignment() const
FIXME: Remove this function once transition to Align is over.
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
This file implements a class to represent arbitrary precision integral constant values and operations...
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.
CallInst * CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
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.
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...
Value * CreateConstInBoundsGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, const Twine &Name="")
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.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
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.
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)
This struct is a compact representation of a valid (non-zero power of two) alignment.
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.
This is the superclass of the array and vector type classes.
unsigned getNumOperands() const
This is the shared class of boolean and integer constants.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Address space for local memory.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
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.
MaybeAlign getSourceAlign() const
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.
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()
void addDereferenceableAttr(unsigned i, uint64_t Bytes)
adds the dereferenceable attribute to the list of attributes.
CallInst * CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
void setUnnamedAddr(UnnamedAddr Val)
Type * getPointerOperandType() const
static IntegerType * getInt32Ty(LLVMContext &C)
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
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).
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Address space for private memory.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
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())
LLVM Value Representation.
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
virtual unsigned getMaxWavesPerEU(unsigned FlatWorkGroupSize) const =0
Calling convention for AMDGPU code object kernels.
Value * getPointerOperand()
Value * getRawDest() const
Address space for constant memory (VTX2).
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, MaybeAlign 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.
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures, unsigned MaxUsesToExplore=DefaultMaxUsesToExplore)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.