DxilModule.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilModule.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. ///////////////////////////////////////////////////////////////////////////////
  9. #include "dxc/Support/Global.h"
  10. #include "dxc/HLSL/DxilOperations.h"
  11. #include "dxc/HLSL/DxilModule.h"
  12. #include "dxc/HLSL/DxilShaderModel.h"
  13. #include "dxc/HLSL/DxilSignatureElement.h"
  14. #include "dxc/HLSL/DxilContainer.h"
  15. #include "dxc/HLSL/DxilRootSignature.h"
  16. #include "llvm/IR/Constants.h"
  17. #include "llvm/IR/Function.h"
  18. #include "llvm/IR/Instructions.h"
  19. #include "llvm/IR/LLVMContext.h"
  20. #include "llvm/IR/Metadata.h"
  21. #include "llvm/IR/Module.h"
  22. #include "llvm/IR/DebugInfo.h"
  23. #include "llvm/IR/DiagnosticInfo.h"
  24. #include "llvm/IR/DiagnosticPrinter.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include <unordered_set>
  27. using namespace llvm;
  28. using std::string;
  29. using std::vector;
  30. using std::unique_ptr;
  31. namespace {
  32. class DxilErrorDiagnosticInfo : public DiagnosticInfo {
  33. private:
  34. const char *m_message;
  35. public:
  36. DxilErrorDiagnosticInfo(const char *str)
  37. : DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
  38. m_message(str) { }
  39. __override void print(DiagnosticPrinter &DP) const {
  40. DP << m_message;
  41. }
  42. };
  43. } // anon namespace
  44. namespace hlsl {
  45. //------------------------------------------------------------------------------
  46. //
  47. // DxilModule methods.
  48. //
  49. DxilModule::DxilModule(Module *pModule)
  50. : m_Ctx(pModule->getContext())
  51. , m_pModule(pModule)
  52. , m_pOP(std::make_unique<OP>(pModule->getContext(), pModule))
  53. , m_pTypeSystem(std::make_unique<DxilTypeSystem>(pModule))
  54. , m_pMDHelper(std::make_unique<DxilMDHelper>(pModule, std::make_unique<DxilExtraPropertyHelper>(pModule)))
  55. , m_pDebugInfoFinder(nullptr)
  56. , m_pEntryFunc(nullptr)
  57. , m_EntryName("")
  58. , m_pPatchConstantFunc(nullptr)
  59. , m_pSM(nullptr)
  60. , m_DxilMajor(DXIL::kDxilMajor)
  61. , m_DxilMinor(DXIL::kDxilMinor)
  62. , m_InputPrimitive(DXIL::InputPrimitive::Undefined)
  63. , m_MaxVertexCount(0)
  64. , m_StreamPrimitiveTopology(DXIL::PrimitiveTopology::Undefined)
  65. , m_ActiveStreamMask(0)
  66. , m_NumGSInstances(1)
  67. , m_InputControlPointCount(0)
  68. , m_TessellatorDomain(DXIL::TessellatorDomain::Undefined)
  69. , m_OutputControlPointCount(0)
  70. , m_TessellatorPartitioning(DXIL::TessellatorPartitioning::Undefined)
  71. , m_TessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive::Undefined)
  72. , m_MaxTessellationFactor(0.f)
  73. , m_RootSignature(nullptr) {
  74. DXASSERT_NOMSG(m_pModule != nullptr);
  75. m_NumThreads[0] = m_NumThreads[1] = m_NumThreads[2] = 0;
  76. #if defined(_DEBUG) || defined(DBG)
  77. // Pin LLVM dump methods.
  78. void (__thiscall Module::*pfnModuleDump)() const = &Module::dump;
  79. void (__thiscall Type::*pfnTypeDump)() const = &Type::dump;
  80. void (__thiscall Function::*pfnViewCFGOnly)() const = &Function::viewCFGOnly;
  81. m_pUnused = (char *)&pfnModuleDump - (char *)&pfnTypeDump;
  82. m_pUnused -= (size_t)&pfnViewCFGOnly;
  83. #endif
  84. }
  85. DxilModule::~DxilModule() {
  86. }
  87. DxilModule::ShaderFlags::ShaderFlags():
  88. m_bDisableOptimizations(false)
  89. , m_bDisableMathRefactoring(false)
  90. , m_bEnableDoublePrecision(false)
  91. , m_bForceEarlyDepthStencil(false)
  92. , m_bEnableRawAndStructuredBuffers(false)
  93. , m_bEnableMinPrecision(false)
  94. , m_bEnableDoubleExtensions(false)
  95. , m_bEnableMSAD(false)
  96. , m_bAllResourcesBound(false)
  97. , m_bViewportAndRTArrayIndex(false)
  98. , m_bInnerCoverage(false)
  99. , m_bStencilRef(false)
  100. , m_bTiledResources(false)
  101. , m_bUAVLoadAdditionalFormats(false)
  102. , m_bLevel9ComparisonFiltering(false)
  103. , m_bCSRawAndStructuredViaShader4X(false)
  104. , m_b64UAVs(false)
  105. , m_UAVsAtEveryStage(false)
  106. , m_bROVS(false)
  107. , m_bWaveOps(false)
  108. , m_bInt64Ops(false)
  109. , m_align0(0)
  110. , m_align1(0)
  111. {}
  112. LLVMContext &DxilModule::GetCtx() const { return m_Ctx; }
  113. Module *DxilModule::GetModule() const { return m_pModule; }
  114. OP *DxilModule::GetOP() const { return m_pOP.get(); }
  115. void DxilModule::SetShaderModel(const ShaderModel *pSM) {
  116. DXASSERT(m_pSM == nullptr || (pSM != nullptr && *m_pSM == *pSM), "shader model must not change for the module");
  117. m_pSM = pSM;
  118. m_pMDHelper->SetShaderModel(m_pSM);
  119. DXIL::ShaderKind shaderKind = pSM->GetKind();
  120. m_InputSignature.reset(new DxilSignature(shaderKind, DXIL::SignatureKind::Input));
  121. m_OutputSignature.reset(new DxilSignature(shaderKind, DXIL::SignatureKind::Output));
  122. m_PatchConstantSignature.reset(new DxilSignature(shaderKind, DXIL::SignatureKind::PatchConstant));
  123. m_RootSignature.reset(new RootSignatureHandle());
  124. }
  125. const ShaderModel *DxilModule::GetShaderModel() const {
  126. return m_pSM;
  127. }
  128. Function *DxilModule::GetEntryFunction() {
  129. return m_pEntryFunc;
  130. }
  131. const Function *DxilModule::GetEntryFunction() const {
  132. return m_pEntryFunc;
  133. }
  134. void DxilModule::SetEntryFunction(Function *pEntryFunc) {
  135. m_pEntryFunc = pEntryFunc;
  136. }
  137. const string &DxilModule::GetEntryFunctionName() const {
  138. return m_EntryName;
  139. }
  140. void DxilModule::SetEntryFunctionName(const string &name) {
  141. m_EntryName = name;
  142. }
  143. llvm::Function *DxilModule::GetPatchConstantFunction() {
  144. return m_pPatchConstantFunc;
  145. }
  146. const llvm::Function *DxilModule::GetPatchConstantFunction() const {
  147. return m_pPatchConstantFunc;
  148. }
  149. void DxilModule::SetPatchConstantFunction(llvm::Function *pFunc) {
  150. m_pPatchConstantFunc = pFunc;
  151. }
  152. unsigned DxilModule::ShaderFlags::GetGlobalFlags() const {
  153. unsigned Flags = 0;
  154. Flags |= m_bDisableOptimizations ? DXIL::kDisableOptimizations : 0;
  155. Flags |= m_bDisableMathRefactoring ? DXIL::kDisableMathRefactoring : 0;
  156. Flags |= m_bEnableDoublePrecision ? DXIL::kEnableDoublePrecision : 0;
  157. Flags |= m_bForceEarlyDepthStencil ? DXIL::kForceEarlyDepthStencil : 0;
  158. Flags |= m_bEnableRawAndStructuredBuffers ? DXIL::kEnableRawAndStructuredBuffers : 0;
  159. Flags |= m_bEnableMinPrecision ? DXIL::kEnableMinPrecision : 0;
  160. Flags |= m_bEnableDoubleExtensions ? DXIL::kEnableDoubleExtensions : 0;
  161. Flags |= m_bEnableMSAD ? DXIL::kEnableMSAD : 0;
  162. Flags |= m_bAllResourcesBound ? DXIL::kAllResourcesBound : 0;
  163. return Flags;
  164. }
  165. uint64_t DxilModule::ShaderFlags::GetFeatureInfo() const {
  166. uint64_t Flags = 0;
  167. Flags |= m_bEnableDoublePrecision ? hlsl::ShaderFeatureInfo_Doubles : 0;
  168. Flags |= m_bEnableMinPrecision ? hlsl::ShaderFeatureInfo_MininumPrecision : 0;
  169. Flags |= m_bEnableDoubleExtensions ? hlsl::ShaderFeatureInfo_11_1_DoubleExtensions : 0;
  170. Flags |= m_bWaveOps ? hlsl::ShaderFeatureInfo_WaveOps : 0;
  171. Flags |= m_bInt64Ops ? hlsl::ShaderFeatureInfo_Int64Ops : 0;
  172. Flags |= m_bROVS ? hlsl::ShaderFeatureInfo_ROVs : 0;
  173. Flags |= m_bViewportAndRTArrayIndex ? hlsl::ShaderFeatureInfo_ViewportAndRTArrayIndexFromAnyShaderFeedingRasterizer : 0;
  174. Flags |= m_bInnerCoverage ? hlsl::ShaderFeatureInfo_InnerCoverage : 0;
  175. Flags |= m_bStencilRef ? hlsl::ShaderFeatureInfo_StencilRef : 0;
  176. Flags |= m_bTiledResources ? hlsl::ShaderFeatureInfo_TiledResources : 0;
  177. Flags |= m_bEnableMSAD ? hlsl::ShaderFeatureInfo_11_1_ShaderExtensions : 0;
  178. Flags |= m_bCSRawAndStructuredViaShader4X ? hlsl::ShaderFeatureInfo_ComputeShadersPlusRawAndStructuredBuffersViaShader4X : 0;
  179. Flags |= m_UAVsAtEveryStage ? hlsl::ShaderFeatureInfo_UAVsAtEveryStage : 0;
  180. Flags |= m_b64UAVs ? hlsl::ShaderFeatureInfo_64UAVs : 0;
  181. Flags |= m_bLevel9ComparisonFiltering ? hlsl::ShaderFeatureInfo_LEVEL9ComparisonFiltering : 0;
  182. Flags |= m_bUAVLoadAdditionalFormats ? hlsl::ShaderFeatureInfo_TypedUAVLoadAdditionalFormats : 0;
  183. return Flags;
  184. }
  185. uint64_t DxilModule::ShaderFlags::GetShaderFlagsRaw() const {
  186. union Cast {
  187. Cast(const DxilModule::ShaderFlags &flags) {
  188. shaderFlags = flags;
  189. }
  190. DxilModule::ShaderFlags shaderFlags;
  191. uint64_t rawData;
  192. };
  193. static_assert(sizeof(uint64_t) == sizeof(DxilModule::ShaderFlags),
  194. "size must match to make sure no undefined bits when cast");
  195. Cast rawCast(*this);
  196. return rawCast.rawData;
  197. }
  198. void DxilModule::ShaderFlags::SetShaderFlagsRaw(uint64_t data) {
  199. union Cast {
  200. Cast(uint64_t data) {
  201. rawData = data;
  202. }
  203. DxilModule::ShaderFlags shaderFlags;
  204. uint64_t rawData;
  205. };
  206. Cast rawCast(data);
  207. *this = rawCast.shaderFlags;
  208. }
  209. unsigned DxilModule::GetGlobalFlags() const {
  210. unsigned Flags = m_ShaderFlags.GetGlobalFlags();
  211. return Flags;
  212. }
  213. void DxilModule::CollectShaderFlags(ShaderFlags &Flags) {
  214. bool hasDouble = false;
  215. // ddiv dfma drcp d2i d2u i2d u2d.
  216. // fma has dxil op. Others should check IR instruction div/cast.
  217. bool hasDoubleExtension = false;
  218. bool has64Int = false;
  219. bool has16FloatInt = false;
  220. bool hasWaveOps = false;
  221. bool hasCheckAccessFully = false;
  222. bool hasMSAD = false;
  223. bool hasMulticomponentUAVLoads = false;
  224. bool hasInnerCoverage = false;
  225. Type *int16Ty = Type::getInt16Ty(GetCtx());
  226. Type *int64Ty = Type::getInt64Ty(GetCtx());
  227. for (Function &F : GetModule()->functions()) {
  228. for (BasicBlock &BB : F.getBasicBlockList()) {
  229. for (Instruction &I : BB.getInstList()) {
  230. // Skip none dxil function call.
  231. if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  232. if (!OP::IsDxilOpFunc(CI->getCalledFunction()))
  233. continue;
  234. }
  235. Type *Ty = I.getType();
  236. bool isDouble = Ty->isDoubleTy();
  237. bool isHalf = Ty->isHalfTy();
  238. bool isInt16 = Ty == int16Ty;
  239. bool isInt64 = Ty == int64Ty;
  240. if (isa<ExtractElementInst>(&I) ||
  241. isa<InsertElementInst>(&I))
  242. continue;
  243. for (Value *operand : I.operands()) {
  244. Type *Ty = operand->getType();
  245. isDouble |= Ty->isDoubleTy();
  246. isHalf |= Ty->isHalfTy();
  247. isInt16 |= Ty == int16Ty;
  248. isInt64 |= Ty == int64Ty;
  249. }
  250. if (isDouble) {
  251. hasDouble = true;
  252. switch (I.getOpcode()) {
  253. case Instruction::FDiv:
  254. case Instruction::UIToFP:
  255. case Instruction::SIToFP:
  256. case Instruction::FPToUI:
  257. case Instruction::FPToSI:
  258. hasDoubleExtension = true;
  259. break;
  260. }
  261. }
  262. has16FloatInt |= isHalf;
  263. has16FloatInt |= isInt16;
  264. has64Int |= isInt64;
  265. if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  266. if (!OP::IsDxilOpFunc(CI->getCalledFunction()))
  267. continue;
  268. Value *opcodeArg = CI->getArgOperand(DXIL::OperandIndex::kOpcodeIdx);
  269. ConstantInt *opcodeConst = dyn_cast<ConstantInt>(opcodeArg);
  270. DXASSERT(opcodeConst, "DXIL opcode arg must be immediate");
  271. unsigned opcode = opcodeConst->getLimitedValue();
  272. DXASSERT(opcode < static_cast<unsigned>(DXIL::OpCode::NumOpCodes),
  273. "invalid DXIL opcode");
  274. DXIL::OpCode dxilOp = static_cast<DXIL::OpCode>(opcode);
  275. if (hlsl::OP::IsDxilOpWave(dxilOp))
  276. hasWaveOps = true;
  277. switch (dxilOp) {
  278. case DXIL::OpCode::CheckAccessFullyMapped:
  279. hasCheckAccessFully = true;
  280. break;
  281. case DXIL::OpCode::Msad:
  282. hasMSAD = true;
  283. break;
  284. case DXIL::OpCode::BufferLoad:
  285. case DXIL::OpCode::TextureLoad: {
  286. Value *resHandle = CI->getArgOperand(DXIL::OperandIndex::kBufferStoreHandleOpIdx);
  287. CallInst *handleCall = cast<CallInst>(resHandle);
  288. if (ConstantInt *resClassArg =
  289. dyn_cast<ConstantInt>(handleCall->getArgOperand(
  290. DXIL::OperandIndex::kCreateHandleResClassOpIdx))) {
  291. DXIL::ResourceClass resClass = static_cast<DXIL::ResourceClass>(
  292. resClassArg->getLimitedValue());
  293. if (resClass == DXIL::ResourceClass::UAV) {
  294. // For DXIL, all uav load is multi component load.
  295. hasMulticomponentUAVLoads = true;
  296. }
  297. } else if (PHINode *resClassPhi = dyn_cast<
  298. PHINode>(handleCall->getArgOperand(
  299. DXIL::OperandIndex::kCreateHandleResClassOpIdx))) {
  300. unsigned numOperands = resClassPhi->getNumOperands();
  301. for (unsigned i = 0; i < numOperands; i++) {
  302. if (ConstantInt *resClassArg = dyn_cast<ConstantInt>(
  303. resClassPhi->getIncomingValue(i))) {
  304. DXIL::ResourceClass resClass =
  305. static_cast<DXIL::ResourceClass>(
  306. resClassArg->getLimitedValue());
  307. if (resClass == DXIL::ResourceClass::UAV) {
  308. // For DXIL, all uav load is multi component load.
  309. hasMulticomponentUAVLoads = true;
  310. break;
  311. }
  312. }
  313. }
  314. }
  315. } break;
  316. case DXIL::OpCode::Fma:
  317. hasDoubleExtension |= isDouble;
  318. break;
  319. case DXIL::OpCode::InnerCoverage:
  320. hasInnerCoverage = true;
  321. break;
  322. default:
  323. // Normal opcodes.
  324. break;
  325. }
  326. }
  327. }
  328. }
  329. }
  330. Flags.SetEnableDoublePrecision(hasDouble);
  331. Flags.SetInt64Ops(has64Int);
  332. Flags.SetEnableMinPrecision(has16FloatInt);
  333. Flags.SetEnableDoubleExtensions(hasDoubleExtension);
  334. Flags.SetWaveOps(hasWaveOps);
  335. Flags.SetTiledResources(hasCheckAccessFully);
  336. Flags.SetEnableMSAD(hasMSAD);
  337. Flags.SetUAVLoadAdditionalFormats(hasMulticomponentUAVLoads);
  338. const ShaderModel *SM = GetShaderModel();
  339. if (SM->IsPS()) {
  340. bool hasStencilRef = false;
  341. DxilSignature &outS = GetOutputSignature();
  342. for (auto &&E : outS.GetElements()) {
  343. if (E->GetKind() == Semantic::Kind::StencilRef) {
  344. hasStencilRef = true;
  345. } else if (E->GetKind() == Semantic::Kind::InnerCoverage) {
  346. hasInnerCoverage = true;
  347. }
  348. }
  349. Flags.SetStencilRef(hasStencilRef);
  350. Flags.SetInnerCoverage(hasInnerCoverage);
  351. }
  352. bool checkInputRTArrayIndex =
  353. SM->IsGS() || SM->IsDS() || SM->IsHS() || SM->IsPS();
  354. if (checkInputRTArrayIndex) {
  355. bool hasViewportArrayIndex = false;
  356. bool hasRenderTargetArrayIndex = false;
  357. DxilSignature &inS = GetInputSignature();
  358. for (auto &E : inS.GetElements()) {
  359. if (E->GetKind() == Semantic::Kind::ViewPortArrayIndex) {
  360. hasViewportArrayIndex = true;
  361. } else if (E->GetKind() == Semantic::Kind::RenderTargetArrayIndex) {
  362. hasRenderTargetArrayIndex = true;
  363. }
  364. }
  365. Flags.SetViewportAndRTArrayIndex(hasViewportArrayIndex |
  366. hasRenderTargetArrayIndex);
  367. }
  368. bool checkOutputRTArrayIndex =
  369. SM->IsVS() || SM->IsDS() || SM->IsHS() || SM->IsPS();
  370. if (checkOutputRTArrayIndex) {
  371. bool hasViewportArrayIndex = false;
  372. bool hasRenderTargetArrayIndex = false;
  373. DxilSignature &outS = GetOutputSignature();
  374. for (auto &E : outS.GetElements()) {
  375. if (E->GetKind() == Semantic::Kind::ViewPortArrayIndex) {
  376. hasViewportArrayIndex = true;
  377. } else if (E->GetKind() == Semantic::Kind::RenderTargetArrayIndex) {
  378. hasRenderTargetArrayIndex = true;
  379. }
  380. }
  381. Flags.SetViewportAndRTArrayIndex(hasViewportArrayIndex |
  382. hasRenderTargetArrayIndex);
  383. }
  384. unsigned NumUAVs = m_UAVs.size();
  385. const unsigned kSmallUAVCount = 8;
  386. if (NumUAVs > kSmallUAVCount)
  387. Flags.Set64UAVs(true);
  388. if (NumUAVs && !(SM->IsCS() || SM->IsPS()))
  389. Flags.SetUAVsAtEveryStage(true);
  390. bool hasRawAndStructuredBuffer = false;
  391. for (auto &UAV : m_UAVs) {
  392. if (UAV->IsROV())
  393. Flags.SetROVs(true);
  394. switch (UAV->GetKind()) {
  395. case DXIL::ResourceKind::RawBuffer:
  396. case DXIL::ResourceKind::StructuredBuffer:
  397. hasRawAndStructuredBuffer = true;
  398. break;
  399. default:
  400. // Not raw/structured.
  401. break;
  402. }
  403. }
  404. for (auto &SRV : m_SRVs) {
  405. switch (SRV->GetKind()) {
  406. case DXIL::ResourceKind::RawBuffer:
  407. case DXIL::ResourceKind::StructuredBuffer:
  408. hasRawAndStructuredBuffer = true;
  409. break;
  410. default:
  411. // Not raw/structured.
  412. break;
  413. }
  414. }
  415. Flags.SetEnableRawAndStructuredBuffers(hasRawAndStructuredBuffer);
  416. bool hasCSRawAndStructuredViaShader4X =
  417. hasRawAndStructuredBuffer && m_pSM->GetMajor() == 4 && m_pSM->IsCS();
  418. Flags.SetCSRawAndStructuredViaShader4X(hasCSRawAndStructuredViaShader4X);
  419. }
  420. void DxilModule::CollectShaderFlags() {
  421. CollectShaderFlags(m_ShaderFlags);
  422. }
  423. uint64_t DxilModule::ShaderFlags::GetShaderFlagsRawForCollection() {
  424. // This should be all the flags that can be set by DxilModule::CollectShaderFlags.
  425. ShaderFlags Flags;
  426. Flags.SetEnableDoublePrecision(true);
  427. Flags.SetInt64Ops(true);
  428. Flags.SetEnableMinPrecision(true);
  429. Flags.SetEnableDoubleExtensions(true);
  430. Flags.SetWaveOps(true);
  431. Flags.SetTiledResources(true);
  432. Flags.SetEnableMSAD(true);
  433. Flags.SetUAVLoadAdditionalFormats(true);
  434. Flags.SetStencilRef(true);
  435. Flags.SetInnerCoverage(true);
  436. Flags.SetViewportAndRTArrayIndex(true);
  437. Flags.Set64UAVs(true);
  438. Flags.SetUAVsAtEveryStage(true);
  439. Flags.SetEnableRawAndStructuredBuffers(true);
  440. Flags.SetCSRawAndStructuredViaShader4X(true);
  441. return Flags.GetShaderFlagsRaw();
  442. }
  443. DXIL::InputPrimitive DxilModule::GetInputPrimitive() const {
  444. return m_InputPrimitive;
  445. }
  446. void DxilModule::SetInputPrimitive(DXIL::InputPrimitive IP) {
  447. DXASSERT_NOMSG(m_InputPrimitive == DXIL::InputPrimitive::Undefined);
  448. DXASSERT_NOMSG(DXIL::InputPrimitive::Undefined < IP && IP < DXIL::InputPrimitive::LastEntry);
  449. m_InputPrimitive = IP;
  450. }
  451. unsigned DxilModule::GetMaxVertexCount() const {
  452. DXASSERT_NOMSG(m_MaxVertexCount != 0);
  453. return m_MaxVertexCount;
  454. }
  455. void DxilModule::SetMaxVertexCount(unsigned Count) {
  456. DXASSERT_NOMSG(m_MaxVertexCount == 0);
  457. m_MaxVertexCount = Count;
  458. }
  459. DXIL::PrimitiveTopology DxilModule::GetStreamPrimitiveTopology() const {
  460. return m_StreamPrimitiveTopology;
  461. }
  462. void DxilModule::SetStreamPrimitiveTopology(DXIL::PrimitiveTopology Topology) {
  463. m_StreamPrimitiveTopology = Topology;
  464. }
  465. bool DxilModule::HasMultipleOutputStreams() const {
  466. if (!m_pSM->IsGS()) {
  467. return false;
  468. } else {
  469. unsigned NumStreams = (m_ActiveStreamMask & 0x1) +
  470. ((m_ActiveStreamMask & 0x2) >> 1) +
  471. ((m_ActiveStreamMask & 0x4) >> 2) +
  472. ((m_ActiveStreamMask & 0x8) >> 3);
  473. DXASSERT_NOMSG(NumStreams <= DXIL::kNumOutputStreams);
  474. return NumStreams > 1;
  475. }
  476. }
  477. unsigned DxilModule::GetOutputStream() const {
  478. if (!m_pSM->IsGS()) {
  479. return 0;
  480. } else {
  481. DXASSERT_NOMSG(!HasMultipleOutputStreams());
  482. switch (m_ActiveStreamMask) {
  483. case 0x1: return 0;
  484. case 0x2: return 1;
  485. case 0x4: return 2;
  486. case 0x8: return 3;
  487. default: DXASSERT_NOMSG(false);
  488. }
  489. return (unsigned)(-1);
  490. }
  491. }
  492. unsigned DxilModule::GetGSInstanceCount() const {
  493. return m_NumGSInstances;
  494. }
  495. void DxilModule::SetGSInstanceCount(unsigned Count) {
  496. m_NumGSInstances = Count;
  497. }
  498. bool DxilModule::IsStreamActive(unsigned Stream) const {
  499. return (m_ActiveStreamMask & (1<<Stream)) != 0;
  500. }
  501. void DxilModule::SetStreamActive(unsigned Stream, bool bActive) {
  502. if (bActive) {
  503. m_ActiveStreamMask |= (1<<Stream);
  504. } else {
  505. m_ActiveStreamMask &= ~(1<<Stream);
  506. }
  507. }
  508. void DxilModule::SetActiveStreamMask(unsigned Mask) {
  509. m_ActiveStreamMask = Mask;
  510. }
  511. unsigned DxilModule::GetActiveStreamMask() const {
  512. return m_ActiveStreamMask;
  513. }
  514. unsigned DxilModule::GetInputControlPointCount() const {
  515. return m_InputControlPointCount;
  516. }
  517. void DxilModule::SetInputControlPointCount(unsigned NumICPs) {
  518. m_InputControlPointCount = NumICPs;
  519. }
  520. DXIL::TessellatorDomain DxilModule::GetTessellatorDomain() const {
  521. return m_TessellatorDomain;
  522. }
  523. void DxilModule::SetTessellatorDomain(DXIL::TessellatorDomain TessDomain) {
  524. m_TessellatorDomain = TessDomain;
  525. }
  526. unsigned DxilModule::GetOutputControlPointCount() const {
  527. return m_OutputControlPointCount;
  528. }
  529. void DxilModule::SetOutputControlPointCount(unsigned NumOCPs) {
  530. m_OutputControlPointCount = NumOCPs;
  531. }
  532. DXIL::TessellatorPartitioning DxilModule::GetTessellatorPartitioning() const {
  533. return m_TessellatorPartitioning;
  534. }
  535. void DxilModule::SetTessellatorPartitioning(DXIL::TessellatorPartitioning TessPartitioning) {
  536. m_TessellatorPartitioning = TessPartitioning;
  537. }
  538. DXIL::TessellatorOutputPrimitive DxilModule::GetTessellatorOutputPrimitive() const {
  539. return m_TessellatorOutputPrimitive;
  540. }
  541. void DxilModule::SetTessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive TessOutputPrimitive) {
  542. m_TessellatorOutputPrimitive = TessOutputPrimitive;
  543. }
  544. float DxilModule::GetMaxTessellationFactor() const {
  545. return m_MaxTessellationFactor;
  546. }
  547. void DxilModule::SetMaxTessellationFactor(float MaxTessellationFactor) {
  548. m_MaxTessellationFactor = MaxTessellationFactor;
  549. }
  550. template<typename T> unsigned
  551. DxilModule::AddResource(vector<unique_ptr<T> > &Vec, unique_ptr<T> pRes) {
  552. DXASSERT_NOMSG((unsigned)Vec.size() < UINT_MAX);
  553. unsigned Id = (unsigned)Vec.size();
  554. Vec.emplace_back(std::move(pRes));
  555. return Id;
  556. }
  557. unsigned DxilModule::AddCBuffer(unique_ptr<DxilCBuffer> pCB) {
  558. return AddResource<DxilCBuffer>(m_CBuffers, std::move(pCB));
  559. }
  560. DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) {
  561. return *m_CBuffers[idx];
  562. }
  563. const DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) const {
  564. return *m_CBuffers[idx];
  565. }
  566. const vector<unique_ptr<DxilCBuffer> > &DxilModule::GetCBuffers() const {
  567. return m_CBuffers;
  568. }
  569. unsigned DxilModule::AddSampler(unique_ptr<DxilSampler> pSampler) {
  570. return AddResource<DxilSampler>(m_Samplers, std::move(pSampler));
  571. }
  572. DxilSampler &DxilModule::GetSampler(unsigned idx) {
  573. return *m_Samplers[idx];
  574. }
  575. const DxilSampler &DxilModule::GetSampler(unsigned idx) const {
  576. return *m_Samplers[idx];
  577. }
  578. const vector<unique_ptr<DxilSampler> > &DxilModule::GetSamplers() const {
  579. return m_Samplers;
  580. }
  581. unsigned DxilModule::AddSRV(unique_ptr<DxilResource> pSRV) {
  582. return AddResource<DxilResource>(m_SRVs, std::move(pSRV));
  583. }
  584. DxilResource &DxilModule::GetSRV(unsigned idx) {
  585. return *m_SRVs[idx];
  586. }
  587. const DxilResource &DxilModule::GetSRV(unsigned idx) const {
  588. return *m_SRVs[idx];
  589. }
  590. const vector<unique_ptr<DxilResource> > &DxilModule::GetSRVs() const {
  591. return m_SRVs;
  592. }
  593. unsigned DxilModule::AddUAV(unique_ptr<DxilResource> pUAV) {
  594. return AddResource<DxilResource>(m_UAVs, std::move(pUAV));
  595. }
  596. DxilResource &DxilModule::GetUAV(unsigned idx) {
  597. return *m_UAVs[idx];
  598. }
  599. const DxilResource &DxilModule::GetUAV(unsigned idx) const {
  600. return *m_UAVs[idx];
  601. }
  602. const vector<unique_ptr<DxilResource> > &DxilModule::GetUAVs() const {
  603. return m_UAVs;
  604. }
  605. void DxilModule::LoadDxilResourceBaseFromMDNode(MDNode *MD, DxilResourceBase &R) {
  606. return m_pMDHelper->LoadDxilResourceBaseFromMDNode(MD, R);
  607. }
  608. void DxilModule::LoadDxilResourceFromMDNode(llvm::MDNode *MD, DxilResource &R) {
  609. return m_pMDHelper->LoadDxilResourceFromMDNode(MD, R);
  610. }
  611. void DxilModule::LoadDxilSamplerFromMDNode(llvm::MDNode *MD, DxilSampler &S) {
  612. return m_pMDHelper->LoadDxilSamplerFromMDNode(MD, S);
  613. }
  614. template <typename TResource>
  615. static void RemoveResources(std::vector<std::unique_ptr<TResource>> &vec,
  616. std::unordered_set<unsigned> &immResID) {
  617. for (std::vector<std::unique_ptr<TResource>>::iterator p = vec.begin(); p != vec.end();) {
  618. std::vector<std::unique_ptr<TResource>>::iterator c = p++;
  619. if (immResID.count((*c)->GetID()) == 0) {
  620. p = vec.erase(c);
  621. }
  622. }
  623. }
  624. static void CollectUsedResource(Value *resID,
  625. std::unordered_set<Value *> &usedResID) {
  626. if (usedResID.count(resID) > 0)
  627. return;
  628. usedResID.insert(resID);
  629. if (ConstantInt *cResID = dyn_cast<ConstantInt>(resID)) {
  630. // Do nothing
  631. } else if (ZExtInst *ZEI = dyn_cast<ZExtInst>(resID)) {
  632. if (ZEI->getSrcTy()->isIntegerTy()) {
  633. IntegerType *ITy = cast<IntegerType>(ZEI->getSrcTy());
  634. if (ITy->getBitWidth() == 1) {
  635. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 0));
  636. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 1));
  637. }
  638. }
  639. } else if (SelectInst *SI = dyn_cast<SelectInst>(resID)) {
  640. CollectUsedResource(SI->getTrueValue(), usedResID);
  641. CollectUsedResource(SI->getFalseValue(), usedResID);
  642. } else {
  643. PHINode *Phi = cast<PHINode>(resID);
  644. for (Use &U : Phi->incoming_values()) {
  645. CollectUsedResource(U.get(), usedResID);
  646. }
  647. }
  648. }
  649. static void ConvertUsedResource(std::unordered_set<unsigned> &immResID,
  650. std::unordered_set<Value *> &usedResID) {
  651. for (Value *V : usedResID) {
  652. if (ConstantInt *cResID = dyn_cast<ConstantInt>(V)) {
  653. immResID.insert(cResID->getLimitedValue());
  654. }
  655. }
  656. }
  657. void DxilModule::RemoveFunction(llvm::Function *F) {
  658. DXASSERT_NOMSG(F != nullptr);
  659. if (m_pTypeSystem.get()->GetFunctionAnnotation(F))
  660. m_pTypeSystem.get()->EraseFunctionAnnotation(F);
  661. m_pOP->RemoveFunction(F);
  662. }
  663. void DxilModule::RemoveUnusedResources() {
  664. hlsl::OP *hlslOP = GetOP();
  665. Function *createHandleFunc = hlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(GetCtx()));
  666. if (createHandleFunc->user_empty()) {
  667. m_CBuffers.clear();
  668. m_UAVs.clear();
  669. m_SRVs.clear();
  670. m_Samplers.clear();
  671. createHandleFunc->eraseFromParent();
  672. return;
  673. }
  674. std::unordered_set<Value *> usedUAVID;
  675. std::unordered_set<Value *> usedSRVID;
  676. std::unordered_set<Value *> usedSamplerID;
  677. std::unordered_set<Value *> usedCBufID;
  678. // Collect used ID.
  679. for (User *U : createHandleFunc->users()) {
  680. CallInst *CI = cast<CallInst>(U);
  681. Value *vResClass =
  682. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
  683. ConstantInt *cResClass = cast<ConstantInt>(vResClass);
  684. DXIL::ResourceClass resClass =
  685. static_cast<DXIL::ResourceClass>(cResClass->getLimitedValue());
  686. // Skip unused resource handle.
  687. if (CI->user_empty())
  688. continue;
  689. Value *resID =
  690. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
  691. switch (resClass) {
  692. case DXIL::ResourceClass::CBuffer:
  693. CollectUsedResource(resID, usedCBufID);
  694. break;
  695. case DXIL::ResourceClass::Sampler:
  696. CollectUsedResource(resID, usedSamplerID);
  697. break;
  698. case DXIL::ResourceClass::SRV:
  699. CollectUsedResource(resID, usedSRVID);
  700. break;
  701. case DXIL::ResourceClass::UAV:
  702. CollectUsedResource(resID, usedUAVID);
  703. break;
  704. default:
  705. DXASSERT(0, "invalid res class");
  706. break;
  707. }
  708. }
  709. std::unordered_set<unsigned> immUAVID;
  710. std::unordered_set<unsigned> immSRVID;
  711. std::unordered_set<unsigned> immSamplerID;
  712. std::unordered_set<unsigned> immCBufID;
  713. ConvertUsedResource(immUAVID, usedUAVID);
  714. RemoveResources(m_UAVs, immUAVID);
  715. ConvertUsedResource(immSRVID, usedSRVID);
  716. ConvertUsedResource(immSamplerID, usedSamplerID);
  717. ConvertUsedResource(immCBufID, usedCBufID);
  718. RemoveResources(m_SRVs, immSRVID);
  719. RemoveResources(m_Samplers, immSamplerID);
  720. RemoveResources(m_CBuffers, immCBufID);
  721. }
  722. DxilSignature &DxilModule::GetInputSignature() {
  723. return *m_InputSignature;
  724. }
  725. const DxilSignature &DxilModule::GetInputSignature() const {
  726. return *m_InputSignature;
  727. }
  728. DxilSignature &DxilModule::GetOutputSignature() {
  729. return *m_OutputSignature;
  730. }
  731. const DxilSignature &DxilModule::GetOutputSignature() const {
  732. return *m_OutputSignature;
  733. }
  734. DxilSignature &DxilModule::GetPatchConstantSignature() {
  735. return *m_PatchConstantSignature;
  736. }
  737. const DxilSignature &DxilModule::GetPatchConstantSignature() const {
  738. return *m_PatchConstantSignature;
  739. }
  740. const RootSignatureHandle &DxilModule::GetRootSignature() const {
  741. return *m_RootSignature;
  742. }
  743. void DxilModule::StripRootSignatureFromMetadata() {
  744. NamedMDNode *pRootSignatureNamedMD = GetModule()->getNamedMetadata(DxilMDHelper::kDxilRootSignatureMDName);
  745. if (pRootSignatureNamedMD) {
  746. GetModule()->eraseNamedMetadata(pRootSignatureNamedMD);
  747. }
  748. }
  749. void DxilModule::ResetInputSignature(DxilSignature *pValue) {
  750. m_InputSignature.reset(pValue);
  751. }
  752. void DxilModule::ResetOutputSignature(DxilSignature *pValue) {
  753. m_OutputSignature.reset(pValue);
  754. }
  755. void DxilModule::ResetPatchConstantSignature(DxilSignature *pValue) {
  756. m_PatchConstantSignature.reset(pValue);
  757. }
  758. void DxilModule::ResetRootSignature(RootSignatureHandle *pValue) {
  759. m_RootSignature.reset(pValue);
  760. }
  761. DxilTypeSystem &DxilModule::GetTypeSystem() {
  762. return *m_pTypeSystem;
  763. }
  764. void DxilModule::ResetTypeSystem(DxilTypeSystem *pValue) {
  765. m_pTypeSystem.reset(pValue);
  766. }
  767. void DxilModule::ResetOP(hlsl::OP *hlslOP) {
  768. m_pOP.reset(hlslOP);
  769. }
  770. void DxilModule::EmitLLVMUsed() {
  771. if (m_LLVMUsed.empty())
  772. return;
  773. vector<llvm::Constant*> GVs;
  774. Type *pI8PtrType = Type::getInt8PtrTy(m_Ctx, DXIL::kDefaultAddrSpace);
  775. GVs.resize(m_LLVMUsed.size());
  776. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  777. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  778. PointerType * pPtrType = dyn_cast<PointerType>(pConst->getType());
  779. if (pPtrType->getPointerAddressSpace() != DXIL::kDefaultAddrSpace) {
  780. // Cast pointer to addrspace 0, as LLVMUsed elements must have the same type.
  781. GVs[i] = ConstantExpr::getAddrSpaceCast(pConst, pI8PtrType);
  782. } else {
  783. GVs[i] = ConstantExpr::getPointerCast(pConst, pI8PtrType);
  784. }
  785. }
  786. ArrayType *pATy = ArrayType::get(pI8PtrType, GVs.size());
  787. StringRef llvmUsedName = "llvm.used";
  788. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  789. oldGV->eraseFromParent();
  790. }
  791. GlobalVariable *pGV = new GlobalVariable(*m_pModule, pATy, false,
  792. GlobalValue::AppendingLinkage,
  793. ConstantArray::get(pATy, GVs),
  794. llvmUsedName);
  795. pGV->setSection("llvm.metadata");
  796. }
  797. vector<GlobalVariable* > &DxilModule::GetLLVMUsed() {
  798. return m_LLVMUsed;
  799. }
  800. // DXIL metadata serialization/deserialization.
  801. void DxilModule::EmitDxilMetadata() {
  802. m_pSM->GetDxilVersion(m_DxilMajor, m_DxilMinor);
  803. m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
  804. m_pMDHelper->EmitDxilShaderModel(m_pSM);
  805. MDTuple *pMDSignatures = m_pMDHelper->EmitDxilSignatures(*m_InputSignature,
  806. *m_OutputSignature,
  807. *m_PatchConstantSignature);
  808. MDTuple *pMDResources = EmitDxilResources();
  809. MDTuple *pMDProperties = EmitDxilShaderProperties();
  810. m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
  811. EmitLLVMUsed();
  812. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources, pMDProperties);
  813. vector<MDNode *> Entries;
  814. Entries.emplace_back(pEntry);
  815. m_pMDHelper->EmitDxilEntryPoints(Entries);
  816. if (!m_RootSignature->IsEmpty()) {
  817. m_pMDHelper->EmitRootSignature(*m_RootSignature.get());
  818. }
  819. }
  820. bool DxilModule::IsKnownNamedMetaData(llvm::NamedMDNode &Node) {
  821. return DxilMDHelper::IsKnownNamedMetaData(Node);
  822. }
  823. void DxilModule::LoadDxilMetadata() {
  824. m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
  825. const ShaderModel *loadedModule;
  826. m_pMDHelper->LoadDxilShaderModel(loadedModule);
  827. SetShaderModel(loadedModule);
  828. DXASSERT(m_InputSignature != nullptr, "else SetShaderModel didn't create input signature");
  829. const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
  830. IFTBOOL(pEntries->getNumOperands() == 1, DXC_E_INCORRECT_DXIL_METADATA);
  831. Function *pEntryFunc;
  832. string EntryName;
  833. const llvm::MDOperand *pSignatures, *pResources, *pProperties;
  834. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0), pEntryFunc, EntryName, pSignatures, pResources, pProperties);
  835. SetEntryFunction(pEntryFunc);
  836. SetEntryFunctionName(EntryName);
  837. m_pMDHelper->LoadDxilSignatures(*pSignatures, *m_InputSignature,
  838. *m_OutputSignature, *m_PatchConstantSignature);
  839. LoadDxilResources(*pResources);
  840. LoadDxilShaderProperties(*pProperties);
  841. m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
  842. m_pMDHelper->LoadRootSignature(*m_RootSignature.get());
  843. }
  844. MDTuple *DxilModule::EmitDxilResources() {
  845. // Emit SRV records.
  846. MDTuple *pTupleSRVs = nullptr;
  847. if (!m_SRVs.empty()) {
  848. vector<Metadata *> MDVals;
  849. for (size_t i = 0; i < m_SRVs.size(); i++) {
  850. MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
  851. }
  852. pTupleSRVs = MDNode::get(m_Ctx, MDVals);
  853. }
  854. // Emit UAV records.
  855. MDTuple *pTupleUAVs = nullptr;
  856. if (!m_UAVs.empty()) {
  857. vector<Metadata *> MDVals;
  858. for (size_t i = 0; i < m_UAVs.size(); i++) {
  859. MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
  860. }
  861. pTupleUAVs = MDNode::get(m_Ctx, MDVals);
  862. }
  863. // Emit CBuffer records.
  864. MDTuple *pTupleCBuffers = nullptr;
  865. if (!m_CBuffers.empty()) {
  866. vector<Metadata *> MDVals;
  867. for (size_t i = 0; i < m_CBuffers.size(); i++) {
  868. MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
  869. }
  870. pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
  871. }
  872. // Emit Sampler records.
  873. MDTuple *pTupleSamplers = nullptr;
  874. if (!m_Samplers.empty()) {
  875. vector<Metadata *> MDVals;
  876. for (size_t i = 0; i < m_Samplers.size(); i++) {
  877. MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
  878. }
  879. pTupleSamplers = MDNode::get(m_Ctx, MDVals);
  880. }
  881. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr || pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  882. return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs, pTupleCBuffers, pTupleSamplers);
  883. } else {
  884. return nullptr;
  885. }
  886. }
  887. void DxilModule::LoadDxilResources(const llvm::MDOperand &MDO) {
  888. if (MDO.get() == nullptr)
  889. return;
  890. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  891. m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
  892. // Load SRV records.
  893. if (pSRVs != nullptr) {
  894. for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
  895. unique_ptr<DxilResource> pSRV(new DxilResource);
  896. m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
  897. AddSRV(std::move(pSRV));
  898. }
  899. }
  900. // Load UAV records.
  901. if (pUAVs != nullptr) {
  902. for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
  903. unique_ptr<DxilResource> pUAV(new DxilResource);
  904. m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
  905. AddUAV(std::move(pUAV));
  906. }
  907. }
  908. // Load CBuffer records.
  909. if (pCBuffers != nullptr) {
  910. for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
  911. unique_ptr<DxilCBuffer> pCB(new DxilCBuffer);
  912. m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
  913. AddCBuffer(std::move(pCB));
  914. }
  915. }
  916. // Load Sampler records.
  917. if (pSamplers != nullptr) {
  918. for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
  919. unique_ptr<DxilSampler> pSampler(new DxilSampler);
  920. m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
  921. AddSampler(std::move(pSampler));
  922. }
  923. }
  924. }
  925. MDTuple *DxilModule::EmitDxilShaderProperties() {
  926. vector<Metadata *> MDVals;
  927. // DXIL shader flags.
  928. uint64_t Flags = m_ShaderFlags.GetShaderFlagsRaw();
  929. if (Flags != 0) {
  930. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilShaderFlagsTag));
  931. MDVals.emplace_back(m_pMDHelper->Uint64ToConstMD(Flags));
  932. }
  933. // Compute shader.
  934. if (m_pSM->IsCS()) {
  935. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilNumThreadsTag));
  936. vector<Metadata *> NumThreadVals;
  937. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[0]));
  938. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[1]));
  939. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[2]));
  940. MDVals.emplace_back(MDNode::get(m_Ctx, NumThreadVals));
  941. }
  942. // Geometry shader.
  943. if (m_pSM->IsGS()) {
  944. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilGSStateTag));
  945. MDTuple *pMDTuple = m_pMDHelper->EmitDxilGSState(m_InputPrimitive,
  946. m_MaxVertexCount,
  947. GetActiveStreamMask(),
  948. m_StreamPrimitiveTopology,
  949. m_NumGSInstances);
  950. MDVals.emplace_back(pMDTuple);
  951. }
  952. // Domain shader.
  953. if (m_pSM->IsDS()) {
  954. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilDSStateTag));
  955. MDTuple *pMDTuple = m_pMDHelper->EmitDxilDSState(m_TessellatorDomain,
  956. m_InputControlPointCount);
  957. MDVals.emplace_back(pMDTuple);
  958. }
  959. // Hull shader.
  960. if (m_pSM->IsHS()) {
  961. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilHSStateTag));
  962. MDTuple *pMDTuple = m_pMDHelper->EmitDxilHSState(m_pPatchConstantFunc,
  963. m_InputControlPointCount,
  964. m_OutputControlPointCount,
  965. m_TessellatorDomain,
  966. m_TessellatorPartitioning,
  967. m_TessellatorOutputPrimitive,
  968. m_MaxTessellationFactor);
  969. MDVals.emplace_back(pMDTuple);
  970. }
  971. if (!MDVals.empty())
  972. return MDNode::get(m_Ctx, MDVals);
  973. else
  974. return nullptr;
  975. }
  976. void DxilModule::LoadDxilShaderProperties(const MDOperand &MDO) {
  977. if (MDO.get() == nullptr)
  978. return;
  979. const MDTuple *pTupleMD = dyn_cast<MDTuple>(MDO.get());
  980. IFTBOOL(pTupleMD != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  981. IFTBOOL((pTupleMD->getNumOperands() & 0x1) == 0, DXC_E_INCORRECT_DXIL_METADATA);
  982. for (unsigned iNode = 0; iNode < pTupleMD->getNumOperands(); iNode += 2) {
  983. unsigned Tag = DxilMDHelper::ConstMDToUint32(pTupleMD->getOperand(iNode));
  984. const MDOperand &MDO = pTupleMD->getOperand(iNode + 1);
  985. IFTBOOL(MDO.get() != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  986. switch (Tag) {
  987. case DxilMDHelper::kDxilShaderFlagsTag:
  988. m_ShaderFlags.SetShaderFlagsRaw(DxilMDHelper::ConstMDToUint64(MDO));
  989. break;
  990. case DxilMDHelper::kDxilNumThreadsTag: {
  991. MDNode *pNode = cast<MDNode>(MDO.get());
  992. m_NumThreads[0] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(0));
  993. m_NumThreads[1] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(1));
  994. m_NumThreads[2] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(2));
  995. break;
  996. }
  997. case DxilMDHelper::kDxilGSStateTag: {
  998. m_pMDHelper->LoadDxilGSState(MDO, m_InputPrimitive, m_MaxVertexCount, m_ActiveStreamMask,
  999. m_StreamPrimitiveTopology, m_NumGSInstances);
  1000. break;
  1001. }
  1002. case DxilMDHelper::kDxilDSStateTag:
  1003. m_pMDHelper->LoadDxilDSState(MDO, m_TessellatorDomain, m_InputControlPointCount);
  1004. break;
  1005. case DxilMDHelper::kDxilHSStateTag:
  1006. m_pMDHelper->LoadDxilHSState(MDO,
  1007. m_pPatchConstantFunc,
  1008. m_InputControlPointCount,
  1009. m_OutputControlPointCount,
  1010. m_TessellatorDomain,
  1011. m_TessellatorPartitioning,
  1012. m_TessellatorOutputPrimitive,
  1013. m_MaxTessellationFactor);
  1014. break;
  1015. default:
  1016. DXASSERT(false, "Unknown extended shader properties tag");
  1017. break;
  1018. }
  1019. }
  1020. }
  1021. void DxilModule::StripDebugRelatedCode() {
  1022. // Remove all users of global resources.
  1023. for (GlobalVariable &GV : m_pModule->globals()) {
  1024. if (GV.hasInternalLinkage())
  1025. continue;
  1026. if (GV.getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace)
  1027. continue;
  1028. for (auto git = GV.user_begin(); git != GV.user_end();) {
  1029. User *U = *(git++);
  1030. // Try to remove load of GV.
  1031. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1032. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1033. Instruction *LIUser = cast<Instruction>(*(it++));
  1034. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1035. Value *Ptr = SI->getPointerOperand();
  1036. SI->eraseFromParent();
  1037. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1038. if (Ptr->user_empty())
  1039. PtrInst->eraseFromParent();
  1040. }
  1041. }
  1042. }
  1043. if (LI->user_empty())
  1044. LI->eraseFromParent();
  1045. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  1046. for (auto GEPIt = GEP->user_begin(); GEPIt != GEP->user_end();) {
  1047. User *GEPU = *(GEPIt++);
  1048. // Try to remove load of GEP.
  1049. if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
  1050. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1051. Instruction *LIUser = cast<Instruction>(*(it++));
  1052. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1053. Value *Ptr = SI->getPointerOperand();
  1054. SI->eraseFromParent();
  1055. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1056. if (Ptr->user_empty())
  1057. PtrInst->eraseFromParent();
  1058. }
  1059. }
  1060. if (LI->user_empty())
  1061. LI->eraseFromParent();
  1062. }
  1063. }
  1064. }
  1065. if (GEP->user_empty())
  1066. GEP->eraseFromParent();
  1067. }
  1068. }
  1069. }
  1070. }
  1071. DebugInfoFinder &DxilModule::GetOrCreateDebugInfoFinder() {
  1072. if (m_pDebugInfoFinder == nullptr) {
  1073. m_pDebugInfoFinder = std::make_unique<llvm::DebugInfoFinder>();
  1074. m_pDebugInfoFinder->processModule(*m_pModule);
  1075. }
  1076. return *m_pDebugInfoFinder;
  1077. }
  1078. hlsl::DxilModule *hlsl::DxilModule::TryGetDxilModule(llvm::Module *pModule) {
  1079. LLVMContext &Ctx = pModule->getContext();
  1080. std::string diagStr;
  1081. raw_string_ostream diagStream(diagStr);
  1082. hlsl::DxilModule *pDxilModule = nullptr;
  1083. // TODO: add detail error in DxilMDHelper.
  1084. try {
  1085. pDxilModule = &pModule->GetOrCreateDxilModule();
  1086. } catch (const ::hlsl::Exception &hlslException) {
  1087. diagStream << "load dxil metadata failed -";
  1088. try {
  1089. const char *msg = hlslException.what();
  1090. if (msg == nullptr || *msg == '\0')
  1091. diagStream << " error code " << hlslException.hr << "\n";
  1092. else
  1093. diagStream << msg;
  1094. } catch (...) {
  1095. diagStream << " unable to retrieve error message.\n";
  1096. }
  1097. Ctx.diagnose(DxilErrorDiagnosticInfo(diagStream.str().c_str()));
  1098. } catch (...) {
  1099. Ctx.diagnose(DxilErrorDiagnosticInfo("load dxil metadata failed - unknown error.\n"));
  1100. }
  1101. return pDxilModule;
  1102. }
  1103. } // namespace hlsl
  1104. namespace llvm {
  1105. hlsl::DxilModule &Module::GetOrCreateDxilModule(bool skipInit) {
  1106. std::unique_ptr<hlsl::DxilModule> M;
  1107. if (!HasDxilModule()) {
  1108. M = std::make_unique<hlsl::DxilModule>(this);
  1109. if (!skipInit) {
  1110. M->LoadDxilMetadata();
  1111. }
  1112. SetDxilModule(M.release());
  1113. }
  1114. return GetDxilModule();
  1115. }
  1116. void Module::ResetDxilModule() {
  1117. if (HasDxilModule()) {
  1118. delete TheDxilModule;
  1119. TheDxilModule = nullptr;
  1120. }
  1121. }
  1122. }