1//===- DXILResourceImplicitBinding.cpp -----------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "DirectX.h"
10#include "llvm/ADT/APInt.h"
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/Analysis/DXILResource.h"
13#include "llvm/IR/Analysis.h"
14#include "llvm/IR/Constants.h"
15#include "llvm/IR/DiagnosticInfo.h"
16#include "llvm/IR/Function.h"
17#include "llvm/IR/IRBuilder.h"
18#include "llvm/IR/Instructions.h"
19#include "llvm/IR/IntrinsicsDirectX.h"
20#include "llvm/IR/Module.h"
21#include "llvm/InitializePasses.h"
22#include <cstdint>
23
24#define DEBUG_TYPE "dxil-resource-implicit-binding"
25
26using namespace llvm;
27using namespace llvm::dxil;
28
29namespace {
30
31static void diagnoseImplicitBindingNotFound(CallInst *ImplBindingCall) {
32 Function *F = ImplBindingCall->getFunction();
33 LLVMContext &Context = F->getParent()->getContext();
34 // FIXME: include the name of the resource in the error message
35 // (llvm/llvm-project#137868)
36 Context.diagnose(
37 DI: DiagnosticInfoGenericWithLoc("resource cannot be allocated", *F,
38 ImplBindingCall->getDebugLoc(), DS_Error));
39}
40
41static bool assignBindings(Module &M, DXILResourceBindingInfo &DRBI,
42 DXILResourceTypeMap &DRTM) {
43 struct ImplicitBindingCall {
44 int OrderID;
45 CallInst *Call;
46 ImplicitBindingCall(int OrderID, CallInst *Call)
47 : OrderID(OrderID), Call(Call) {}
48 };
49 SmallVector<ImplicitBindingCall> Calls;
50 SmallVector<Function *> FunctionsToMaybeRemove;
51
52 // collect all of the llvm.dx.resource.handlefromImplicitbinding calls
53 for (Function &F : M.functions()) {
54 if (!F.isDeclaration())
55 continue;
56
57 if (F.getIntrinsicID() != Intrinsic::dx_resource_handlefromimplicitbinding)
58 continue;
59
60 for (User *U : F.users()) {
61 if (CallInst *CI = dyn_cast<CallInst>(Val: U)) {
62 int OrderID = cast<ConstantInt>(Val: CI->getArgOperand(i: 0))->getZExtValue();
63 Calls.emplace_back(Args&: OrderID, Args&: CI);
64 }
65 }
66 FunctionsToMaybeRemove.emplace_back(Args: &F);
67 }
68
69 // sort all the collected implicit bindings by OrderID
70 llvm::stable_sort(
71 Range&: Calls, C: [](auto &LHS, auto &RHS) { return LHS.OrderID < RHS.OrderID; });
72
73 // iterate over sorted calls, find binding for each new OrderID and replace
74 // each call with dx_resource_handlefrombinding using the new binding
75 int LastOrderID = -1;
76 llvm::TargetExtType *HandleTy = nullptr;
77 ConstantInt *RegSlotOp = nullptr;
78 bool AllBindingsAssigned = true;
79 bool Changed = false;
80
81 for (ImplicitBindingCall &IB : Calls) {
82 IRBuilder<> Builder(IB.Call);
83
84 if (IB.OrderID != LastOrderID) {
85 LastOrderID = IB.OrderID;
86 HandleTy = cast<TargetExtType>(Val: IB.Call->getType());
87 ResourceTypeInfo &RTI = DRTM[HandleTy];
88
89 uint32_t Space =
90 cast<ConstantInt>(Val: IB.Call->getArgOperand(i: 1))->getZExtValue();
91 int32_t Size =
92 cast<ConstantInt>(Val: IB.Call->getArgOperand(i: 2))->getZExtValue();
93
94 std::optional<uint32_t> RegSlot =
95 DRBI.findAvailableBinding(RC: RTI.getResourceClass(), Space, Size);
96 if (!RegSlot) {
97 diagnoseImplicitBindingNotFound(ImplBindingCall: IB.Call);
98 AllBindingsAssigned = false;
99 continue;
100 }
101 RegSlotOp = ConstantInt::get(Ty: Builder.getInt32Ty(), V: RegSlot.value());
102 }
103
104 if (!RegSlotOp)
105 continue;
106
107 auto *NewCall = Builder.CreateIntrinsic(
108 RetTy: HandleTy, ID: Intrinsic::dx_resource_handlefrombinding,
109 Args: {IB.Call->getOperand(i_nocapture: 1), /* space */
110 RegSlotOp, /* register slot */
111 IB.Call->getOperand(i_nocapture: 2), /* size */
112 IB.Call->getOperand(i_nocapture: 3), /* index */
113 IB.Call->getOperand(i_nocapture: 4)}); /* name */
114 IB.Call->replaceAllUsesWith(V: NewCall);
115 IB.Call->eraseFromParent();
116 Changed = true;
117 }
118
119 for (Function *F : FunctionsToMaybeRemove) {
120 if (F->user_empty()) {
121 F->eraseFromParent();
122 Changed = true;
123 }
124 }
125
126 DRBI.setHasImplicitBinding(!AllBindingsAssigned);
127 return Changed;
128}
129
130} // end anonymous namespace
131
132PreservedAnalyses
133DXILResourceImplicitBindingPass::run(Module &M, ModuleAnalysisManager &AM) {
134
135 DXILResourceBindingInfo &DRBI = AM.getResult<DXILResourceBindingAnalysis>(IR&: M);
136 DXILResourceTypeMap &DRTM = AM.getResult<DXILResourceTypeAnalysis>(IR&: M);
137
138 if (!DRBI.hasImplicitBinding())
139 return PreservedAnalyses::all();
140
141 if (!assignBindings(M, DRBI, DRTM))
142 return PreservedAnalyses::all();
143
144 PreservedAnalyses PA;
145 PA.preserve<DXILResourceBindingAnalysis>();
146 PA.preserve<DXILResourceTypeAnalysis>();
147 return PA;
148}
149
150namespace {
151
152class DXILResourceImplicitBindingLegacy : public ModulePass {
153public:
154 DXILResourceImplicitBindingLegacy() : ModulePass(ID) {}
155
156 bool runOnModule(Module &M) override {
157 DXILResourceTypeMap &DRTM =
158 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
159 DXILResourceBindingInfo &DRBI =
160 getAnalysis<DXILResourceBindingWrapperPass>().getBindingInfo();
161
162 if (DRBI.hasImplicitBinding())
163 return assignBindings(M, DRBI, DRTM);
164 return false;
165 }
166
167 static char ID; // Pass identification.
168 void getAnalysisUsage(llvm::AnalysisUsage &AU) const override {
169 AU.addRequired<DXILResourceTypeWrapperPass>();
170 AU.addRequired<DXILResourceBindingWrapperPass>();
171 AU.addPreserved<DXILResourceTypeWrapperPass>();
172 AU.addPreserved<DXILResourceBindingWrapperPass>();
173 }
174};
175
176char DXILResourceImplicitBindingLegacy::ID = 0;
177} // end anonymous namespace
178
179INITIALIZE_PASS_BEGIN(DXILResourceImplicitBindingLegacy, DEBUG_TYPE,
180 "DXIL Resource Implicit Binding", false, false)
181INITIALIZE_PASS_DEPENDENCY(DXILResourceTypeWrapperPass)
182INITIALIZE_PASS_DEPENDENCY(DXILResourceBindingWrapperPass)
183INITIALIZE_PASS_END(DXILResourceImplicitBindingLegacy, DEBUG_TYPE,
184 "DXIL Resource Implicit Binding", false, false)
185
186ModulePass *llvm::createDXILResourceImplicitBindingLegacyPass() {
187 return new DXILResourceImplicitBindingLegacy();
188}
189