27#include "llvm/IR/IntrinsicsSPIRV.h"
35class SPIRVLegalizeResourceBindingImpl {
37 bool runOnModule(
Module &M);
40 void collectBindingInfo(
Module &M);
41 uint32_t getAndReserveFirstUnusedBinding(uint32_t DescSet);
42 bool replaceImplicitBindingCalls(
Module &M);
43 bool replaceHeapBindingCalls(
Module &M);
46 std::vector<BitVector> UsedBindings;
51 bool MayHaveImplicitBindings =
false;
52 bool MayHaveHeapBindings =
false;
55class SPIRVLegalizeResourceBindingLegacy :
public ModulePass {
58 SPIRVLegalizeResourceBindingLegacy() : ModulePass(ID) {}
59 StringRef getPassName()
const override {
60 return "SPIRV Legalize Resource Binding";
62 bool runOnModule(
Module &M)
override {
63 return SPIRVLegalizeResourceBindingImpl().runOnModule(M);
70 case Intrinsic::spv_resource_handlefromimplicitbinding_mdname:
73 case Intrinsic::spv_resource_counterhandlefromimplicitbinding:
85void SPIRVLegalizeResourceBindingImpl::collectBindingInfo(
Module &M) {
87 auto addBinding = [&](uint32_t DescSet, uint32_t
Binding) {
88 if (UsedBindings.size() <= DescSet) {
89 UsedBindings.resize(DescSet + 1);
90 UsedBindings[DescSet].resize(64);
93 UsedBindings[DescSet].resize(2 *
Binding + 1);
95 UsedBindings[DescSet].set(
Binding);
98 auto collectBinding = [&](
Function &
F, uint32_t ArgDescSetIdx,
99 uint32_t ArgBindingIdx) {
100 for (User *U :
F.users()) {
102 const uint32_t DescSet =
112 if (!
F.isDeclaration())
115 switch (
F.getIntrinsicID()) {
116 case Intrinsic::spv_resource_handlefrombinding_mdname:
117 collectBinding(
F, 0, 1);
119 case Intrinsic::spv_resource_counterhandlefrombinding:
120 collectBinding(
F, 1, 2);
122 case Intrinsic::spv_resource_handlefromimplicitbinding_mdname:
123 case Intrinsic::spv_resource_counterhandlefromimplicitbinding:
124 MayHaveImplicitBindings =
true;
126 case Intrinsic::spv_resource_handlefromheap:
127 case Intrinsic::spv_resource_counterhandlefromheap:
128 MayHaveHeapBindings =
true;
136uint32_t SPIRVLegalizeResourceBindingImpl::getAndReserveFirstUnusedBinding(
138 if (UsedBindings.size() <= DescSet) {
139 UsedBindings.resize(DescSet + 1);
140 UsedBindings[DescSet].resize(64);
143 int NewBinding = UsedBindings[DescSet].find_first_unset();
144 if (NewBinding == -1) {
145 NewBinding = UsedBindings[DescSet].size();
146 UsedBindings[DescSet].resize(2 * NewBinding + 1);
149 UsedBindings[DescSet].set(NewBinding);
154static void replaceWithHandleFromBinding(
Module &M, CallInst *CI,
155 uint32_t DescSet, uint32_t
Binding,
159 Intrinsic::spv_resource_handlefromimplicitbinding_mdname ||
160 CI->
getIntrinsicID() == Intrinsic::spv_resource_handlefromheap) &&
161 "unexpected binding intrinsic");
163 Value *DescSetOp = Builder.getInt32(DescSet);
166 &M, Intrinsic::spv_resource_handlefrombinding_mdname, {CI->
getType()});
167 CallInst *NewCI = Builder.CreateCall(
168 NewFunc, {DescSetOp, BindingOp, RangeOp, IndexOp,
Name});
176static void replaceWithCounterHandleFromBinding(
Module &M, CallInst *CI,
181 Intrinsic::spv_resource_counterhandlefromimplicitbinding ||
182 CI->
getIntrinsicID() == Intrinsic::spv_resource_counterhandlefromheap) &&
183 "unexpected binding intrinsic");
185 Value *DescSetOp = Builder.getInt32(DescSet);
190 &M, Intrinsic::spv_resource_counterhandlefrombinding, OverloadTys);
192 Builder.CreateCall(NewFunc, {MainHandle, DescSetOp, BindingOp});
198bool SPIRVLegalizeResourceBindingImpl::replaceImplicitBindingCalls(
Module &M) {
203 if (!
F.isDeclaration())
207 if (
F.getIntrinsicID() ==
208 Intrinsic::spv_resource_handlefromimplicitbinding_mdname)
210 else if (
F.getIntrinsicID() ==
211 Intrinsic::spv_resource_counterhandlefromimplicitbinding)
216 for (User *U :
F.users()) {
233 uint32_t LastOrderId = -1;
234 uint32_t LastBinding = -1;
235 uint32_t LastDescSet = -1;
236 for (
auto &[OrderId, CI] : IBCalls) {
238 uint32_t DescSet = getDescSet(CI);
239 if (OrderId == LastOrderId) {
240 if (DescSet != LastDescSet)
242 "have the same descriptor set");
245 Binding = getAndReserveFirstUnusedBinding(DescSet);
250 Intrinsic::spv_resource_handlefromimplicitbinding_mdname)
251 replaceWithHandleFromBinding(M, CI, DescSet,
Binding,
255 replaceWithCounterHandleFromBinding(M, CI, DescSet,
Binding);
258 LastOrderId = OrderId;
260 LastDescSet = DescSet;
265static Value *createHeapNameMetadata(LLVMContext &Ctx, StringRef Name,
267 std::string HeapName = (Twine(
".") +
Name +
"." + Twine(ID)).str();
292bool SPIRVLegalizeResourceBindingImpl::replaceHeapBindingCalls(
Module &M) {
301 if (!
F.isDeclaration() ||
F.user_empty())
304 if (
F.getIntrinsicID() == Intrinsic::spv_resource_handlefromheap) {
306 if (ResType->
getName() ==
"spirv.Sampler")
310 }
else if (
F.getIntrinsicID() ==
311 Intrinsic::spv_resource_counterhandlefromheap) {
322 constexpr uint32_t DescSet = 0;
326 if (!CbvSrvUavs.
empty()) {
330 uint32_t
Binding = getAndReserveFirstUnusedBinding(DescSet);
333 Value *HeapName = createHeapNameMetadata(
334 M.getContext(),
"ResourceDescriptorHeap", HeapID++);
339 replaceWithHandleFromBinding(M, CI, DescSet,
Binding,
Zero, HeapIdx,
344 F->eraseFromParent();
348 if (!Samplers.
empty()) {
349 uint32_t
Binding = getAndReserveFirstUnusedBinding(DescSet);
352 [[maybe_unused]] TargetExtType *SamplerHandleType =
356 createHeapNameMetadata(
M.getContext(),
"SamplerDescriptorHeap", 0);
358 assert(
F->getReturnType() == SamplerHandleType &&
359 "sampler handle type mismatch");
363 replaceWithHandleFromBinding(M, CI, DescSet,
Binding,
Zero, HeapIdx,
368 F->eraseFromParent();
373 uint32_t
Binding = getAndReserveFirstUnusedBinding(DescSet);
374 [[maybe_unused]]
Type *CounterHandleTy =
Counters.front()->getReturnType();
378 assert(
F->getReturnType() == CounterHandleTy &&
379 "counter handle type mismatch");
382 replaceWithCounterHandleFromBinding(M, CI, DescSet,
Binding);
386 F->eraseFromParent();
393bool SPIRVLegalizeResourceBindingImpl::runOnModule(
Module &M) {
394 collectBindingInfo(M);
397 if (MayHaveImplicitBindings)
398 Changed |= replaceImplicitBindingCalls(M);
399 if (MayHaveHeapBindings)
400 Changed |= replaceHeapBindingCalls(M);
408 return SPIRVLegalizeResourceBindingImpl().runOnModule(M)
413char SPIRVLegalizeResourceBindingLegacy::ID = 0;
416 "legalize-spirv-resource-binding",
417 "Legalize SPIR-V resource bindings",
false,
false)
420 return new SPIRVLegalizeResourceBindingLegacy();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements the BitVector class.
DXIL Resource Implicit Binding
Module.h This file contains the declarations for the Module class.
Machine Check Debug Module
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file defines the SmallVector class.
void setCallingConv(CallingConv::ID CC)
CallingConv::ID getCallingConv() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
This class represents a function call, abstracting a target machine's calling convention.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
void setCallingConv(CallingConv::ID CC)
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
A Module instance is used to store all the information related to an LLVM module.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
reference emplace_back(ArgTypes &&... Args)
StringRef getName() const
Return the name for this target extension type.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
void sort(IteratorTy Start, IteratorTy End)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
ModulePass * createSPIRVLegalizeResourceBindingPass()
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.