1//===- DXILPrepare.cpp - Prepare LLVM Module for DXIL encoding ------------===//
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/// \file This file contains passes and utilities to convert a modern LLVM
10/// module into a module compatible with the LLVM 3.7-based DirectX Intermediate
11/// Language (DXIL).
12//===----------------------------------------------------------------------===//
13
14#include "DXILRootSignature.h"
15#include "DXILShaderFlags.h"
16#include "DirectX.h"
17#include "DirectXIRPasses/DXILAttributes.h"
18#include "DirectXIRPasses/PointerTypeAnalysis.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/StringSet.h"
21#include "llvm/Analysis/DXILMetadataAnalysis.h"
22#include "llvm/Analysis/DXILResource.h"
23#include "llvm/CodeGen/Passes.h"
24#include "llvm/IR/AttributeMask.h"
25#include "llvm/IR/IRBuilder.h"
26#include "llvm/IR/Instruction.h"
27#include "llvm/IR/Module.h"
28#include "llvm/InitializePasses.h"
29#include "llvm/Pass.h"
30#include "llvm/Support/VersionTuple.h"
31
32#define DEBUG_TYPE "dxil-prepare"
33
34using namespace llvm;
35using namespace llvm::dxil;
36
37namespace {
38
39static void collectDeadStringAttrs(AttributeMask &DeadAttrs, AttributeSet &&AS,
40 const StringSet<> &LiveKeys,
41 bool AllowExperimental) {
42 for (auto &Attr : AS) {
43 if (!Attr.isStringAttribute())
44 continue;
45 StringRef Key = Attr.getKindAsString();
46 if (LiveKeys.contains(key: Key))
47 continue;
48 if (AllowExperimental && Key.starts_with(Prefix: "exp-"))
49 continue;
50 DeadAttrs.addAttribute(A: Key);
51 }
52}
53
54static void removeStringFunctionAttributes(Function &F,
55 bool AllowExperimental) {
56 AttributeList Attrs = F.getAttributes();
57 const StringSet<> LiveKeys = {"waveops-include-helper-lanes",
58 "fp32-denorm-mode"};
59 // Collect DeadKeys in FnAttrs.
60 AttributeMask DeadAttrs;
61 collectDeadStringAttrs(DeadAttrs, AS: Attrs.getFnAttrs(), LiveKeys,
62 AllowExperimental);
63 collectDeadStringAttrs(DeadAttrs, AS: Attrs.getRetAttrs(), LiveKeys,
64 AllowExperimental);
65
66 F.removeFnAttrs(Attrs: DeadAttrs);
67 F.removeRetAttrs(Attrs: DeadAttrs);
68}
69
70class DXILPrepareModule : public ModulePass {
71
72 static Value *maybeGenerateBitcast(IRBuilder<> &Builder,
73 PointerTypeMap &PointerTypes,
74 Instruction &Inst, Value *Operand,
75 Type *Ty) {
76 // Omit bitcasts if the incoming value matches the instruction type.
77 auto It = PointerTypes.find(Val: Operand);
78 if (It != PointerTypes.end()) {
79 auto *OpTy = cast<TypedPointerType>(Val: It->second)->getElementType();
80 if (OpTy == Ty)
81 return nullptr;
82 }
83
84 Type *ValTy = Operand->getType();
85 // Also omit the bitcast for matching global array types
86 if (auto *GlobalVar = dyn_cast<GlobalVariable>(Val: Operand))
87 ValTy = GlobalVar->getValueType();
88
89 if (auto *AI = dyn_cast<AllocaInst>(Val: Operand))
90 ValTy = AI->getAllocatedType();
91
92 if (auto *ArrTy = dyn_cast<ArrayType>(Val: ValTy)) {
93 Type *ElTy = ArrTy->getElementType();
94 if (ElTy == Ty)
95 return nullptr;
96 }
97
98 // finally, drill down GEP instructions until we get the array
99 // that is being accessed, and compare element types
100 if (ConstantExpr *GEPInstr = dyn_cast<ConstantExpr>(Val: Operand)) {
101 while (GEPInstr->getOpcode() == Instruction::GetElementPtr) {
102 Value *OpArg = GEPInstr->getOperand(i_nocapture: 0);
103 if (ConstantExpr *NewGEPInstr = dyn_cast<ConstantExpr>(Val: OpArg)) {
104 GEPInstr = NewGEPInstr;
105 continue;
106 }
107
108 if (auto *GlobalVar = dyn_cast<GlobalVariable>(Val: OpArg))
109 ValTy = GlobalVar->getValueType();
110 if (auto *AI = dyn_cast<AllocaInst>(Val: Operand))
111 ValTy = AI->getAllocatedType();
112 if (auto *ArrTy = dyn_cast<ArrayType>(Val: ValTy)) {
113 Type *ElTy = ArrTy->getElementType();
114 if (ElTy == Ty)
115 return nullptr;
116 }
117 break;
118 }
119 }
120
121 // Insert bitcasts where we are removing the instruction.
122 Builder.SetInsertPoint(&Inst);
123 // This code only gets hit in opaque-pointer mode, so the type of the
124 // pointer doesn't matter.
125 PointerType *PtrTy = cast<PointerType>(Val: Operand->getType());
126 return Builder.Insert(
127 I: CastInst::Create(Instruction::BitCast, S: Operand,
128 Ty: Builder.getPtrTy(AddrSpace: PtrTy->getAddressSpace())));
129 }
130
131public:
132 bool runOnModule(Module &M) override {
133 PointerTypeMap PointerTypes = PointerTypeAnalysis::run(M);
134 const AttributeMask &AttrMask = getNonDXILAttributeMask();
135
136 const dxil::ModuleMetadataInfo MetadataInfo =
137 getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata();
138 VersionTuple ValVer = MetadataInfo.ValidatorVersion;
139 bool AllowExperimental = ValVer.getMajor() == 0 && ValVer.getMinor() == 0;
140
141 for (auto &F : M.functions()) {
142 F.removeFnAttrs(Attrs: AttrMask);
143 F.removeRetAttrs(Attrs: AttrMask);
144 // Only remove string attributes if we are not skipping validation.
145 // This will reserve the experimental attributes when validation version
146 // is 0.0 for experiment mode.
147 removeStringFunctionAttributes(F, AllowExperimental);
148 for (size_t Idx = 0, End = F.arg_size(); Idx < End; ++Idx)
149 F.removeParamAttrs(ArgNo: Idx, Attrs: AttrMask);
150
151 for (auto &BB : F) {
152 IRBuilder<> Builder(&BB);
153 for (auto &I : make_early_inc_range(Range&: BB)) {
154
155 if (auto *CB = dyn_cast<CallBase>(Val: &I)) {
156 CB->removeFnAttrs(AttrsToRemove: AttrMask);
157 CB->removeRetAttrs(AttrsToRemove: AttrMask);
158 for (size_t Idx = 0, End = CB->arg_size(); Idx < End; ++Idx)
159 CB->removeParamAttrs(ArgNo: Idx, AttrsToRemove: AttrMask);
160 continue;
161 }
162
163 // Emtting NoOp bitcast instructions allows the ValueEnumerator to be
164 // unmodified as it reserves instruction IDs during contruction.
165 if (auto *LI = dyn_cast<LoadInst>(Val: &I)) {
166 if (Value *NoOpBitcast = maybeGenerateBitcast(
167 Builder, PointerTypes, Inst&: I, Operand: LI->getPointerOperand(),
168 Ty: LI->getType())) {
169 LI->replaceAllUsesWith(
170 V: Builder.CreateLoad(Ty: LI->getType(), Ptr: NoOpBitcast));
171 LI->eraseFromParent();
172 }
173 continue;
174 }
175 if (auto *SI = dyn_cast<StoreInst>(Val: &I)) {
176 if (Value *NoOpBitcast = maybeGenerateBitcast(
177 Builder, PointerTypes, Inst&: I, Operand: SI->getPointerOperand(),
178 Ty: SI->getValueOperand()->getType())) {
179
180 SI->replaceAllUsesWith(
181 V: Builder.CreateStore(Val: SI->getValueOperand(), Ptr: NoOpBitcast));
182 SI->eraseFromParent();
183 }
184 continue;
185 }
186 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: &I)) {
187 if (Value *NoOpBitcast = maybeGenerateBitcast(
188 Builder, PointerTypes, Inst&: I, Operand: GEP->getPointerOperand(),
189 Ty: GEP->getSourceElementType()))
190 GEP->setOperand(i_nocapture: 0, Val_nocapture: NoOpBitcast);
191 continue;
192 }
193 }
194 }
195 }
196
197 return true;
198 }
199
200 DXILPrepareModule() : ModulePass(ID) {}
201 void getAnalysisUsage(AnalysisUsage &AU) const override {
202 AU.addRequired<DXILMetadataAnalysisWrapperPass>();
203
204 AU.addPreserved<DXILMetadataAnalysisWrapperPass>();
205 AU.addPreserved<DXILResourceWrapperPass>();
206 AU.addPreserved<RootSignatureAnalysisWrapper>();
207 AU.addPreserved<ShaderFlagsAnalysisWrapper>();
208 }
209 static char ID; // Pass identification.
210};
211char DXILPrepareModule::ID = 0;
212
213} // end anonymous namespace
214
215INITIALIZE_PASS_BEGIN(DXILPrepareModule, DEBUG_TYPE, "DXIL Prepare Module",
216 false, false)
217INITIALIZE_PASS_DEPENDENCY(DXILMetadataAnalysisWrapperPass)
218INITIALIZE_PASS_END(DXILPrepareModule, DEBUG_TYPE, "DXIL Prepare Module", false,
219 false)
220
221ModulePass *llvm::createDXILPrepareModulePass() {
222 return new DXILPrepareModule();
223}
224