26#include "llvm/IR/IntrinsicsSPIRV.h"
40 if (MIRBuilder.
getMF()
56 *STI.getRegBankInfo());
70 if (
F.hasFnAttribute(Attribute::AttrKind::NoInline))
71 FuncControl |=
static_cast<uint32_t>(SPIRV::FunctionControl::DontInline);
72 else if (
F.hasFnAttribute(Attribute::AttrKind::AlwaysInline))
73 FuncControl |=
static_cast<uint32_t>(SPIRV::FunctionControl::Inline);
76 FuncControl |=
static_cast<uint32_t>(SPIRV::FunctionControl::Pure);
78 FuncControl |=
static_cast<uint32_t>(SPIRV::FunctionControl::Const);
80 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_optnone) ||
81 ST->canUseExtension(SPIRV::Extension::SPV_EXT_optnone))
82 if (
F.hasFnAttribute(Attribute::OptimizeNone))
83 FuncControl |=
static_cast<uint32_t>(SPIRV::FunctionControl::OptNoneEXT);
106 bool hasArgPtrs =
false;
107 for (
auto &Arg :
F.args()) {
109 if (Arg.getType()->isPointerTy()) {
115 Type *RetTy = FTy->getReturnType();
125 for (
auto SArgTy : SArgTys)
130static SPIRV::AccessQualifier::AccessQualifier
133 return SPIRV::AccessQualifier::ReadWrite;
137 return SPIRV::AccessQualifier::ReadWrite;
139 if (ArgAttribute->
getString() ==
"read_only")
140 return SPIRV::AccessQualifier::ReadOnly;
141 if (ArgAttribute->
getString() ==
"write_only")
142 return SPIRV::AccessQualifier::WriteOnly;
143 return SPIRV::AccessQualifier::ReadWrite;
146static std::vector<SPIRV::Decoration::Decoration>
149 if (ArgAttribute && ArgAttribute->
getString() ==
"volatile")
150 return {SPIRV::Decoration::Volatile};
159 SPIRV::AccessQualifier::AccessQualifier ArgAccessQual =
162 Type *OriginalArgType =
176 VTy->getNumElements(), MIRBuilder,
true);
208 if (
II &&
II->getIntrinsicID() == Intrinsic::spv_assign_type) {
212 assert(BuiltinType->isTargetExtTy() &&
"Expected TargetExtType");
218 if (!
II ||
II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type)
225 ElementTy, MIRBuilder,
233 ArgAccessQual,
true);
236static SPIRV::ExecutionModel::ExecutionModel
239 "Environment must be resolved before lowering entry points.");
242 return SPIRV::ExecutionModel::Kernel;
244 auto attribute =
F.getFnAttribute(
"hlsl.shader");
245 if (!attribute.isValid()) {
247 "This entry point lacks mandatory hlsl.shader attribute.");
250 const auto value = attribute.getValueAsString();
251 if (value ==
"compute")
252 return SPIRV::ExecutionModel::GLCompute;
253 if (value ==
"vertex")
254 return SPIRV::ExecutionModel::Vertex;
255 if (value ==
"pixel")
256 return SPIRV::ExecutionModel::Fragment;
269 assert(GR &&
"Must initialize the SPIRV type registry before lowering args.");
270 GR->setCurrentFunc(MIRBuilder.
getMF());
278 if (VRegs.size() > 0) {
280 for (
const auto &Arg :
F.args()) {
283 if (VRegs[i].
size() > 1)
286 GR->assignSPIRVTypeToVReg(SpirvTy, VRegs[i][0], MIRBuilder.
getMF());
290 buildOpName(VRegs[i][0], Arg.getName(), MIRBuilder);
292 auto DerefBytes =
static_cast<unsigned>(Arg.getDereferenceableBytes());
295 SPIRV::Decoration::MaxByteOffset, {DerefBytes});
297 if (Arg.hasAttribute(Attribute::Alignment) && !ST->isShader()) {
298 auto Alignment =
static_cast<unsigned>(
299 Arg.getAttribute(Attribute::Alignment).getValueAsInt());
303 if (!ST->isShader()) {
304 if (Arg.hasAttribute(Attribute::ReadOnly)) {
306 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoWrite);
308 SPIRV::Decoration::FuncParamAttr, {Attr});
310 if (Arg.hasAttribute(Attribute::ZExt)) {
312 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Zext);
314 SPIRV::Decoration::FuncParamAttr, {Attr});
316 if (Arg.hasAttribute(Attribute::SExt)) {
318 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sext);
320 SPIRV::Decoration::FuncParamAttr, {Attr});
322 if (Arg.hasAttribute(Attribute::NoAlias)) {
324 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoAlias);
326 SPIRV::Decoration::FuncParamAttr, {Attr});
333 if (Arg.hasAttribute(Attribute::ByVal) ||
334 (Arg.hasAttribute(Attribute::ByRef) &&
335 F.getParent()->getTargetTriple().getVendor() ==
338 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::ByVal);
340 SPIRV::Decoration::FuncParamAttr, {Attr});
342 if (Arg.hasAttribute(Attribute::StructRet)) {
344 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sret);
346 SPIRV::Decoration::FuncParamAttr, {Attr});
351 std::vector<SPIRV::Decoration::Decoration> ArgTypeQualDecs =
353 for (SPIRV::Decoration::Decoration Decoration : ArgTypeQualDecs)
357 MDNode *
Node =
F.getMetadata(
"spirv.ParameterDecorations");
358 if (
Node && i < Node->getNumOperands() &&
363 assert(MD2 &&
"Metadata operand is expected");
365 assert(Const &&
"MDOperand should be ConstantInt");
367 static_cast<SPIRV::Decoration::Decoration
>(Const->getZExtValue());
368 std::vector<uint32_t> DecVec;
371 assert(Const &&
"MDOperand should be ConstantInt");
372 DecVec.push_back(
static_cast<uint32_t>(Const->getZExtValue()));
381 auto MRI = MIRBuilder.
getMRI();
383 MRI->setRegClass(FuncVReg, &SPIRV::iIDRegClass);
387 if (
Type *FRetElemTy = GR->findDeducedElementType(&
F)) {
390 GR->addReturnType(&
F, DerivedTy);
395 FRetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
true);
397 SPIRVTypeInst FuncTy = GR->getOrCreateOpTypeFunctionWithArgs(
398 FTy, RetTy, ArgTypeVRegs, MIRBuilder);
404 .
addUse(GR->getSPIRVTypeID(RetTy))
406 .
addUse(GR->getSPIRVTypeID(FuncTy));
408 GR->addGlobalObject(&
F, &MIRBuilder.
getMF(), FuncVReg);
409 if (
F.isDeclaration())
414 for (
const auto &Arg :
F.args()) {
415 assert(VRegs[i].
size() == 1 &&
"Formal arg has multiple vregs");
417 MRI->setRegClass(ArgReg, GR->getRegClass(ArgTypeVRegs[i]));
418 auto MIB = MIRBuilder.
buildInstr(SPIRV::OpFunctionParameter)
420 .
addUse(GR->getSPIRVTypeID(ArgTypeVRegs[i]));
421 if (
F.isDeclaration())
423 GR->addGlobalObject(&Arg, &MIRBuilder.
getMF(), ArgReg);
432 auto MIB = MIRBuilder.
buildInstr(SPIRV::OpEntryPoint)
437 buildOpDecorate(FuncVReg, MIRBuilder, SPIRV::Decoration::LinkageAttributes,
438 {
static_cast<uint32_t>(*LnkTy)},
F.getName());
442 bool hasFunctionPointers =
443 ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
444 if (hasFunctionPointers) {
445 if (
F.hasFnAttribute(
"referenced-indirectly")) {
447 "Unexpected 'referenced-indirectly' attribute of the kernel "
450 SPIRV::Decoration::ReferencedIndirectlyINTEL, {});
465void SPIRVCallLowering::produceIndirectPtrType(
467 const SPIRVCallLowering::SPIRVIndirectCall &IC)
const {
472 IC.RetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
true);
474 for (
size_t i = 0; i < IC.ArgTys.size(); ++i) {
476 IC.ArgTys[i], MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
true);
485 FTy, SpirvRetTy, SpirvArgTypes, MIRBuilder);
487 auto SC = ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)
488 ? SPIRV::StorageClass::CodeSectionINTEL
489 : SPIRV::StorageClass::Function;
500 if (Info.OrigRet.Regs.size() > 1)
503 GR->setCurrentFunc(MF);
505 std::string DemangledName;
506 const Type *OrigRetTy = Info.OrigRet.Ty;
511 if (Info.Callee.isGlobal()) {
512 std::string FuncName = Info.Callee.getGlobal()->getName().str();
522 if (
auto *DerivedRetTy = GR->findReturnType(CF))
523 OrigRetTy = DerivedRetTy;
529 Info.OrigRet.Regs.empty() ?
Register(0) : Info.OrigRet.Regs[0];
533 if (isFunctionDecl && !DemangledName.empty()) {
535 if (!GR->getSPIRVTypeForVReg(ResVReg)) {
536 const Type *RetTy = OrigRetTy;
538 const Value *OrigValue = Info.OrigRet.OrigValue;
542 if (
Type *ElemTy = GR->findDeducedElementType(OrigValue))
547 SPIRV::AccessQualifier::ReadWrite,
true);
551 SPIRV::AccessQualifier::ReadWrite,
true);
554 for (
auto Arg : Info.OrigArgs) {
555 assert(Arg.Regs.size() == 1 &&
"Call arg has multiple VRegs");
560 Type *ArgTy =
nullptr;
568 if (
Type *ElemTy = GR->findDeducedElementType(Arg.OrigValue))
575 SpvType = GR->getOrCreateSPIRVType(
576 ArgTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
true);
577 GR->assignSPIRVTypeToVReg(SpvType, ArgReg, MF);
584 MRI->
setRegClass(ArgReg, SpvType ? GR->getRegClass(SpvType)
585 : &SPIRV::pIDRegClass);
588 SpvType ? GR->getRegType(SpvType)
590 GR->getPointerSize()));
594 DemangledName, ST->getPreferredInstructionSet(), MIRBuilder,
595 ResVReg, OrigRetTy, ArgVRegs, GR, *Info.CB))
599 if (isFunctionDecl && !GR->find(CF, &MF).isValid()) {
603 FirstBlockBuilder.
setMF(MF);
622 if (MIRBuilder.
getMF()
632 if (Info.CB->isIndirectCall()) {
633 if (!ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
635 "extensions does not support it",
638 CallOp = SPIRV::OpFunctionPointerCallINTEL;
640 Register CalleeReg = Info.Callee.getReg();
647 "Function types mismatch");
648 for (
unsigned I = 0;
I != Info.OrigArgs.size(); ++
I) {
649 assert(Info.OrigArgs[
I].Regs.size() == 1 &&
650 "Call arg has multiple VRegs");
658 CallOp = SPIRV::OpFunctionCall;
665 OrigRetTy, ResVReg, MIRBuilder, SPIRV::AccessQualifier::ReadWrite,
true);
670 .
addUse(GR->getSPIRVTypeID(RetType))
673 for (
const auto &Arg : Info.OrigArgs) {
675 if (Arg.Regs.size() > 1)
677 MIB.addUse(Arg.Regs[0]);
680 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing)) {
685 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
686 SPIRV::Decoration::AliasScopeINTEL, MD);
688 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
689 SPIRV::Decoration::NoAliasINTEL, MD);
694 *ST->getRegBankInfo());
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Promote Memory to Register
uint64_t IntrinsicInst * II
static ConstantInt * getConstInt(MDNode *MD, unsigned NumOp)
static SPIRVTypeInst getArgSPIRVType(const Function &F, unsigned ArgIdx, SPIRVGlobalRegistry *GR, MachineIRBuilder &MIRBuilder, const SPIRVSubtarget &ST)
static SPIRV::ExecutionModel::ExecutionModel getExecutionModel(const SPIRVSubtarget &STI, const Function &F)
static uint32_t getFunctionControl(const Function &F, const SPIRVSubtarget *ST)
static SPIRV::AccessQualifier::AccessQualifier getArgAccessQual(const Function &F, unsigned ArgIdx)
static FunctionType * fixFunctionTypeIfPtrArgs(SPIRVGlobalRegistry *GR, const Function &F, FunctionType *FTy, SPIRVTypeInst SRetTy, const SmallVector< SPIRVTypeInst, 4 > &SArgTys)
static std::vector< SPIRV::Decoration::Decoration > getKernelArgTypeQual(const Function &F, unsigned ArgIdx)
#define SPIRV_BACKEND_SERVICE_FUN_NAME
This class represents an incoming formal argument to a Function.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool isValid() const
Return true if the attribute is any kind of attribute.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
CallLowering(const TargetLowering *TLI)
This is the shared class of boolean and integer constants.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Type * getParamType(unsigned i) const
Parameter type accessors.
Type * getReturnType() const
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
iterator_range< arg_iterator > args()
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
Tracking metadata reference owned by Metadata.
LLVM_ABI StringRef getString() const
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineBasicBlock * getBlockNumbered(unsigned N) const
getBlockNumbered - MachineBasicBlocks are automatically numbered when they are inserted into the mach...
Function & getFunction()
Return the LLVM function that this machine code represents.
Helper class to build MachineInstr.
const TargetInstrInfo & getTII()
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineFunction & getMF()
Getter for the function we currently build.
void setMBB(MachineBasicBlock &MBB)
Set the insertion point to the end of MBB.
MachineInstrBuilder buildTrap(bool Debug=false)
Build and insert G_TRAP or G_DEBUGTRAP.
MachineRegisterInfo * getMRI()
Getter for MRI.
const DataLayout & getDataLayout() const
void setMF(MachineFunction &MF)
void constrainAllUses(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
const MachineOperand & getOperand(unsigned i) const
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI void setType(Register VReg, LLT Ty)
Set the low-level type of VReg to Ty.
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
LLVM_ABI Register createGenericVirtualRegister(LLT Ty, StringRef Name="")
Create and return a new generic virtual register with low-level type Ty.
const TargetRegisterClass * getRegClassOrNull(Register Reg) const
Return the register class of Reg, or null if Reg has not been assigned a register class yet.
bool doesNotAccessMemory() const
Whether this function accesses no memory.
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Wrapper class representing virtual and physical registers.
constexpr bool isValid() const
bool lowerCall(MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info) const override
This hook must be implemented to lower the given call instruction, including argument and return valu...
bool lowerReturn(MachineIRBuilder &MIRBuiler, const Value *Val, ArrayRef< Register > VRegs, FunctionLoweringInfo &FLI, Register SwiftErrorVReg) const override
This hook must be implemented to lower outgoing return values, described by Val, into the specified v...
SPIRVCallLowering(const SPIRVTargetLowering &TLI, SPIRVGlobalRegistry *GR)
bool lowerFormalArguments(MachineIRBuilder &MIRBuilder, const Function &F, ArrayRef< ArrayRef< Register > > VRegs, FunctionLoweringInfo &FLI) const override
This hook must be implemented to lower the incoming (formal) arguments, described by VRegs,...
void assignSPIRVTypeToVReg(SPIRVTypeInst Type, Register VReg, const MachineFunction &MF)
SPIRVTypeInst getOrCreateOpTypeFunctionWithArgs(const Type *Ty, SPIRVTypeInst RetType, const SmallVectorImpl< SPIRVTypeInst > &ArgTypes, MachineIRBuilder &MIRBuilder)
SPIRVTypeInst getOrCreateSPIRVVectorType(SPIRVTypeInst BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder, bool EmitIR)
const Type * getTypeForSPIRVType(SPIRVTypeInst Ty) const
SPIRVTypeInst getOrCreateSPIRVPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC)
SPIRVTypeInst getOrCreateSPIRVType(const Type *Type, MachineInstr &I, SPIRV::AccessQualifier::AccessQualifier AQ, bool EmitIR)
SPIRVTypeInst getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
Type * findDeducedElementType(const Value *Val)
SPIRVEnvType getEnv() const
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const TargetRegisterInfo & getRegisterInfo() const
The instances of the Type class are immutable: once they are created, they are never changed.
bool isPointerTy() const
True if this is an instance of PointerType.
A few GPU targets, such as DXIL and SPIR-V, have typed pointers.
static LLVM_ABI TypedPointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
iterator_range< user_iterator > users()
constexpr bool isZero() const
@ SPIR_KERNEL
Used for SPIR kernel functions.
std::optional< bool > lowerBuiltin(const StringRef DemangledCall, SPIRV::InstructionSet::InstructionSet Set, MachineIRBuilder &MIRBuilder, const Register OrigRet, const Type *OrigRetTy, const SmallVectorImpl< Register > &Args, SPIRVGlobalRegistry *GR, const CallBase &CB)
FunctionType * getOriginalFunctionType(const Function &F)
This is an optimization pass for GlobalISel generic memory operations.
void buildOpName(Register Target, const StringRef &Name, MachineIRBuilder &MIRBuilder)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
unsigned getPointerAddressSpace(const Type *T)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Register createVirtualRegister(SPIRVTypeInst SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
MDString * getOCLKernelArgAccessQual(const Function &F, unsigned ArgIdx)
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
bool isTypedPointerTy(const Type *T)
auto dyn_cast_or_null(const Y &Val)
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, const std::vector< uint32_t > &DecArgs, StringRef StrImm)
Type * toTypedPointer(Type *Ty)
bool isPointerTy(const Type *T)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
void setRegClassType(Register Reg, SPIRVTypeInst SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF, bool Force)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
std::optional< SPIRV::LinkageType::LinkageType > getSpirvLinkageTypeFor(const SPIRVSubtarget &ST, const GlobalValue &GV)
bool isEntryPoint(const Function &F)
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
MDString * getOCLKernelArgTypeQual(const Function &F, unsigned ArgIdx)
Type * getPointeeTypeByAttr(Argument *Arg)
bool hasPointeeTypeAttr(Argument *Arg)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
bool isPointerTyOrWrapper(const Type *Ty)
void addStringImm(const StringRef &Str, MCInst &Inst)
bool isUntypedPointerTy(const Type *T)