DxilModule.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  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/DXIL/DxilOperations.h"
  11. #include "dxc/DXIL/DxilModule.h"
  12. #include "dxc/DXIL/DxilConstants.h"
  13. #include "dxc/DXIL/DxilShaderModel.h"
  14. #include "dxc/DXIL/DxilSignatureElement.h"
  15. #include "dxc/DXIL/DxilFunctionProps.h"
  16. #include "dxc/Support/WinAdapter.h"
  17. #include "dxc/DXIL/DxilEntryProps.h"
  18. #include "dxc/DXIL/DxilSubobject.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/Function.h"
  21. #include "llvm/IR/Instructions.h"
  22. #include "llvm/IR/LLVMContext.h"
  23. #include "llvm/IR/Metadata.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/IR/Operator.h"
  26. #include "llvm/IR/DebugInfo.h"
  27. #include "llvm/IR/DiagnosticInfo.h"
  28. #include "llvm/IR/DiagnosticPrinter.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/ADT/STLExtras.h"
  31. #include <unordered_set>
  32. using namespace llvm;
  33. using std::string;
  34. using std::vector;
  35. using std::unique_ptr;
  36. namespace {
  37. class DxilErrorDiagnosticInfo : public DiagnosticInfo {
  38. private:
  39. const char *m_message;
  40. public:
  41. DxilErrorDiagnosticInfo(const char *str)
  42. : DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
  43. m_message(str) { }
  44. void print(DiagnosticPrinter &DP) const override {
  45. DP << m_message;
  46. }
  47. };
  48. } // anon namespace
  49. namespace hlsl {
  50. namespace DXIL {
  51. // Define constant variables exposed in DxilConstants.h
  52. // TODO: revisit data layout descriptions for the following:
  53. // - x64 pointers?
  54. // - Keep elf manging(m:e)?
  55. // For legacy data layout, everything less than 32 align to 32.
  56. const char* kLegacyLayoutString = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64";
  57. // New data layout with native low precision types
  58. const char* kNewLayoutString = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64";
  59. // Function Attributes
  60. // TODO: consider generating attributes from hctdb
  61. const char* kFP32DenormKindString = "fp32-denorm-mode";
  62. const char* kFP32DenormValueAnyString = "any";
  63. const char* kFP32DenormValuePreserveString = "preserve";
  64. const char* kFP32DenormValueFtzString = "ftz";
  65. }
  66. // Avoid dependency on DxilModule from llvm::Module using this:
  67. void DxilModule_RemoveGlobal(llvm::Module* M, llvm::GlobalObject* G) {
  68. if (M && G && M->HasDxilModule()) {
  69. if (llvm::Function *F = dyn_cast<llvm::Function>(G))
  70. M->GetDxilModule().RemoveFunction(F);
  71. }
  72. }
  73. void DxilModule_ResetModule(llvm::Module* M) {
  74. if (M && M->HasDxilModule())
  75. delete &M->GetDxilModule();
  76. M->SetDxilModule(nullptr);
  77. }
  78. //------------------------------------------------------------------------------
  79. //
  80. // DxilModule methods.
  81. //
  82. DxilModule::DxilModule(Module *pModule)
  83. : m_StreamPrimitiveTopology(DXIL::PrimitiveTopology::Undefined)
  84. , m_ActiveStreamMask(0)
  85. , m_Ctx(pModule->getContext())
  86. , m_pModule(pModule)
  87. , m_pEntryFunc(nullptr)
  88. , m_EntryName("")
  89. , m_pMDHelper(llvm::make_unique<DxilMDHelper>(pModule, llvm::make_unique<DxilExtraPropertyHelper>(pModule)))
  90. , m_pDebugInfoFinder(nullptr)
  91. , m_pSM(nullptr)
  92. , m_DxilMajor(DXIL::kDxilMajor)
  93. , m_DxilMinor(DXIL::kDxilMinor)
  94. , m_ValMajor(1)
  95. , m_ValMinor(0)
  96. , m_pOP(llvm::make_unique<OP>(pModule->getContext(), pModule))
  97. , m_pTypeSystem(llvm::make_unique<DxilTypeSystem>(pModule))
  98. , m_bDisableOptimizations(false)
  99. , m_bUseMinPrecision(true) // use min precision by default
  100. , m_bAllResourcesBound(false)
  101. , m_IntermediateFlags(0)
  102. , m_AutoBindingSpace(UINT_MAX)
  103. , m_pSubobjects(nullptr)
  104. {
  105. DXASSERT_NOMSG(m_pModule != nullptr);
  106. m_pModule->pfnRemoveGlobal = &DxilModule_RemoveGlobal;
  107. m_pModule->pfnResetDxilModule = &DxilModule_ResetModule;
  108. #if defined(_DEBUG) || defined(DBG)
  109. // Pin LLVM dump methods.
  110. void (__thiscall Module::*pfnModuleDump)() const = &Module::dump;
  111. void (__thiscall Type::*pfnTypeDump)() const = &Type::dump;
  112. void (__thiscall Function::*pfnViewCFGOnly)() const = &Function::viewCFGOnly;
  113. m_pUnused = (char *)&pfnModuleDump - (char *)&pfnTypeDump;
  114. m_pUnused -= (size_t)&pfnViewCFGOnly;
  115. #endif
  116. }
  117. DxilModule::~DxilModule() {
  118. if (m_pModule->pfnRemoveGlobal == &DxilModule_RemoveGlobal)
  119. m_pModule->pfnRemoveGlobal = nullptr;
  120. }
  121. LLVMContext &DxilModule::GetCtx() const { return m_Ctx; }
  122. Module *DxilModule::GetModule() const { return m_pModule; }
  123. OP *DxilModule::GetOP() const { return m_pOP.get(); }
  124. void DxilModule::SetShaderModel(const ShaderModel *pSM, bool bUseMinPrecision) {
  125. DXASSERT(m_pSM == nullptr || (pSM != nullptr && *m_pSM == *pSM), "shader model must not change for the module");
  126. DXASSERT(pSM != nullptr && pSM->IsValidForDxil(), "shader model must be valid");
  127. DXASSERT(pSM->IsValidForModule(), "shader model must be valid for top-level module use");
  128. m_pSM = pSM;
  129. m_pSM->GetDxilVersion(m_DxilMajor, m_DxilMinor);
  130. m_pMDHelper->SetShaderModel(m_pSM);
  131. m_bUseMinPrecision = bUseMinPrecision;
  132. m_pOP->SetMinPrecision(m_bUseMinPrecision);
  133. m_pTypeSystem->SetMinPrecision(m_bUseMinPrecision);
  134. if (!m_pSM->IsLib()) {
  135. // Always have valid entry props for non-lib case from this point on.
  136. DxilFunctionProps props;
  137. props.shaderKind = m_pSM->GetKind();
  138. m_DxilEntryPropsMap[nullptr] =
  139. llvm::make_unique<DxilEntryProps>(props, m_bUseMinPrecision);
  140. }
  141. m_SerializedRootSignature.clear();
  142. }
  143. const ShaderModel *DxilModule::GetShaderModel() const {
  144. return m_pSM;
  145. }
  146. void DxilModule::GetDxilVersion(unsigned &DxilMajor, unsigned &DxilMinor) const {
  147. DxilMajor = m_DxilMajor;
  148. DxilMinor = m_DxilMinor;
  149. }
  150. void DxilModule::SetValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
  151. m_ValMajor = ValMajor;
  152. m_ValMinor = ValMinor;
  153. }
  154. bool DxilModule::UpgradeValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
  155. // Don't upgrade if validation was disabled.
  156. if (m_ValMajor == 0 && m_ValMinor == 0) {
  157. return false;
  158. }
  159. if (ValMajor > m_ValMajor || (ValMajor == m_ValMajor && ValMinor > m_ValMinor)) {
  160. // Module requires higher validator version than previously set
  161. SetValidatorVersion(ValMajor, ValMinor);
  162. return true;
  163. }
  164. return false;
  165. }
  166. void DxilModule::GetValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const {
  167. ValMajor = m_ValMajor;
  168. ValMinor = m_ValMinor;
  169. }
  170. bool DxilModule::GetMinValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const {
  171. if (!m_pSM)
  172. return false;
  173. m_pSM->GetMinValidatorVersion(ValMajor, ValMinor);
  174. if (ValMajor == 1 && ValMinor == 0 &&
  175. (m_ShaderFlags.GetFeatureInfo() & hlsl::DXIL::ShaderFeatureInfo_ViewID))
  176. ValMinor = 1;
  177. return true;
  178. }
  179. bool DxilModule::UpgradeToMinValidatorVersion() {
  180. unsigned ValMajor = 1, ValMinor = 0;
  181. if (GetMinValidatorVersion(ValMajor, ValMinor)) {
  182. return UpgradeValidatorVersion(ValMajor, ValMinor);
  183. }
  184. return false;
  185. }
  186. Function *DxilModule::GetEntryFunction() {
  187. return m_pEntryFunc;
  188. }
  189. const Function *DxilModule::GetEntryFunction() const {
  190. return m_pEntryFunc;
  191. }
  192. void DxilModule::SetEntryFunction(Function *pEntryFunc) {
  193. if (m_pSM->IsLib()) {
  194. DXASSERT(pEntryFunc == nullptr,
  195. "Otherwise, trying to set an entry function on library");
  196. m_pEntryFunc = nullptr;
  197. return;
  198. }
  199. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  200. m_pEntryFunc = pEntryFunc;
  201. // Move entry props to new function in order to preserve them.
  202. std::unique_ptr<DxilEntryProps> Props = std::move(m_DxilEntryPropsMap.begin()->second);
  203. m_DxilEntryPropsMap.clear();
  204. m_DxilEntryPropsMap[m_pEntryFunc] = std::move(Props);
  205. }
  206. const string &DxilModule::GetEntryFunctionName() const {
  207. return m_EntryName;
  208. }
  209. void DxilModule::SetEntryFunctionName(const string &name) {
  210. m_EntryName = name;
  211. }
  212. llvm::Function *DxilModule::GetPatchConstantFunction() {
  213. if (!m_pSM->IsHS())
  214. return nullptr;
  215. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  216. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  217. DXASSERT(props.IsHS(), "Must be HS profile");
  218. return props.ShaderProps.HS.patchConstantFunc;
  219. }
  220. const llvm::Function *DxilModule::GetPatchConstantFunction() const {
  221. if (!m_pSM->IsHS())
  222. return nullptr;
  223. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  224. const DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  225. DXASSERT(props.IsHS(), "Must be HS profile");
  226. return props.ShaderProps.HS.patchConstantFunc;
  227. }
  228. void DxilModule::SetPatchConstantFunction(llvm::Function *patchConstantFunc) {
  229. if (!m_pSM->IsHS())
  230. return;
  231. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  232. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  233. DXASSERT(props.IsHS(), "Must be HS profile");
  234. auto &HS = props.ShaderProps.HS;
  235. if (HS.patchConstantFunc != patchConstantFunc) {
  236. if (HS.patchConstantFunc)
  237. m_PatchConstantFunctions.erase(HS.patchConstantFunc);
  238. HS.patchConstantFunc = patchConstantFunc;
  239. if (patchConstantFunc)
  240. m_PatchConstantFunctions.insert(patchConstantFunc);
  241. }
  242. }
  243. bool DxilModule::IsEntryOrPatchConstantFunction(const llvm::Function* pFunc) const {
  244. return pFunc == GetEntryFunction() || pFunc == GetPatchConstantFunction();
  245. }
  246. unsigned DxilModule::GetGlobalFlags() const {
  247. unsigned Flags = m_ShaderFlags.GetGlobalFlags();
  248. return Flags;
  249. }
  250. void DxilModule::CollectShaderFlagsForModule(ShaderFlags &Flags) {
  251. for (Function &F : GetModule()->functions()) {
  252. ShaderFlags funcFlags = ShaderFlags::CollectShaderFlags(&F, this);
  253. Flags.CombineShaderFlags(funcFlags);
  254. };
  255. const ShaderModel *SM = GetShaderModel();
  256. unsigned NumUAVs = m_UAVs.size();
  257. const unsigned kSmallUAVCount = 8;
  258. if (NumUAVs > kSmallUAVCount)
  259. Flags.Set64UAVs(true);
  260. if (NumUAVs && !(SM->IsCS() || SM->IsPS()))
  261. Flags.SetUAVsAtEveryStage(true);
  262. bool hasRawAndStructuredBuffer = false;
  263. for (auto &UAV : m_UAVs) {
  264. if (UAV->IsROV())
  265. Flags.SetROVs(true);
  266. switch (UAV->GetKind()) {
  267. case DXIL::ResourceKind::RawBuffer:
  268. case DXIL::ResourceKind::StructuredBuffer:
  269. hasRawAndStructuredBuffer = true;
  270. break;
  271. default:
  272. // Not raw/structured.
  273. break;
  274. }
  275. }
  276. for (auto &SRV : m_SRVs) {
  277. switch (SRV->GetKind()) {
  278. case DXIL::ResourceKind::RawBuffer:
  279. case DXIL::ResourceKind::StructuredBuffer:
  280. hasRawAndStructuredBuffer = true;
  281. break;
  282. default:
  283. // Not raw/structured.
  284. break;
  285. }
  286. }
  287. Flags.SetEnableRawAndStructuredBuffers(hasRawAndStructuredBuffer);
  288. bool hasCSRawAndStructuredViaShader4X =
  289. hasRawAndStructuredBuffer && m_pSM->GetMajor() == 4 && m_pSM->IsCS();
  290. Flags.SetCSRawAndStructuredViaShader4X(hasCSRawAndStructuredViaShader4X);
  291. }
  292. void DxilModule::CollectShaderFlagsForModule() {
  293. CollectShaderFlagsForModule(m_ShaderFlags);
  294. }
  295. void DxilModule::SetNumThreads(unsigned x, unsigned y, unsigned z) {
  296. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsCS(),
  297. "only works for CS profile");
  298. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  299. DXASSERT(props.IsCS(), "Must be CS profile");
  300. unsigned *numThreads = props.ShaderProps.CS.numThreads;
  301. numThreads[0] = x;
  302. numThreads[1] = y;
  303. numThreads[2] = z;
  304. }
  305. unsigned DxilModule::GetNumThreads(unsigned idx) const {
  306. DXASSERT(idx < 3, "Thread dimension index must be 0-2");
  307. if (!m_pSM->IsCS())
  308. return 0;
  309. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  310. __analysis_assume(idx < 3);
  311. const DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  312. DXASSERT(props.IsCS(), "Must be CS profile");
  313. return props.ShaderProps.CS.numThreads[idx];
  314. }
  315. DXIL::InputPrimitive DxilModule::GetInputPrimitive() const {
  316. if (!m_pSM->IsGS())
  317. return DXIL::InputPrimitive::Undefined;
  318. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  319. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  320. DXASSERT(props.IsGS(), "Must be GS profile");
  321. return props.ShaderProps.GS.inputPrimitive;
  322. }
  323. void DxilModule::SetInputPrimitive(DXIL::InputPrimitive IP) {
  324. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
  325. "only works for GS profile");
  326. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  327. DXASSERT(props.IsGS(), "Must be GS profile");
  328. auto &GS = props.ShaderProps.GS;
  329. DXASSERT_NOMSG(DXIL::InputPrimitive::Undefined < IP && IP < DXIL::InputPrimitive::LastEntry);
  330. GS.inputPrimitive = IP;
  331. }
  332. unsigned DxilModule::GetMaxVertexCount() const {
  333. if (!m_pSM->IsGS())
  334. return 0;
  335. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  336. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  337. DXASSERT(props.IsGS(), "Must be GS profile");
  338. auto &GS = props.ShaderProps.GS;
  339. DXASSERT_NOMSG(GS.maxVertexCount != 0);
  340. return GS.maxVertexCount;
  341. }
  342. void DxilModule::SetMaxVertexCount(unsigned Count) {
  343. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
  344. "only works for GS profile");
  345. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  346. DXASSERT(props.IsGS(), "Must be GS profile");
  347. auto &GS = props.ShaderProps.GS;
  348. GS.maxVertexCount = Count;
  349. }
  350. DXIL::PrimitiveTopology DxilModule::GetStreamPrimitiveTopology() const {
  351. return m_StreamPrimitiveTopology;
  352. }
  353. void DxilModule::SetStreamPrimitiveTopology(DXIL::PrimitiveTopology Topology) {
  354. m_StreamPrimitiveTopology = Topology;
  355. SetActiveStreamMask(m_ActiveStreamMask); // Update props
  356. }
  357. bool DxilModule::HasMultipleOutputStreams() const {
  358. if (!m_pSM->IsGS()) {
  359. return false;
  360. } else {
  361. unsigned NumStreams = (m_ActiveStreamMask & 0x1) +
  362. ((m_ActiveStreamMask & 0x2) >> 1) +
  363. ((m_ActiveStreamMask & 0x4) >> 2) +
  364. ((m_ActiveStreamMask & 0x8) >> 3);
  365. DXASSERT_NOMSG(NumStreams <= DXIL::kNumOutputStreams);
  366. return NumStreams > 1;
  367. }
  368. }
  369. unsigned DxilModule::GetOutputStream() const {
  370. if (!m_pSM->IsGS()) {
  371. return 0;
  372. } else {
  373. DXASSERT_NOMSG(!HasMultipleOutputStreams());
  374. switch (m_ActiveStreamMask) {
  375. case 0x1: return 0;
  376. case 0x2: return 1;
  377. case 0x4: return 2;
  378. case 0x8: return 3;
  379. default: DXASSERT_NOMSG(false);
  380. }
  381. return (unsigned)(-1);
  382. }
  383. }
  384. unsigned DxilModule::GetGSInstanceCount() const {
  385. if (!m_pSM->IsGS())
  386. return 0;
  387. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  388. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  389. DXASSERT(props.IsGS(), "Must be GS profile");
  390. return props.ShaderProps.GS.instanceCount;
  391. }
  392. void DxilModule::SetGSInstanceCount(unsigned Count) {
  393. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
  394. "only works for GS profile");
  395. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  396. DXASSERT(props.IsGS(), "Must be GS profile");
  397. props.ShaderProps.GS.instanceCount = Count;
  398. }
  399. bool DxilModule::IsStreamActive(unsigned Stream) const {
  400. return (m_ActiveStreamMask & (1<<Stream)) != 0;
  401. }
  402. void DxilModule::SetStreamActive(unsigned Stream, bool bActive) {
  403. if (bActive) {
  404. m_ActiveStreamMask |= (1<<Stream);
  405. } else {
  406. m_ActiveStreamMask &= ~(1<<Stream);
  407. }
  408. SetActiveStreamMask(m_ActiveStreamMask);
  409. }
  410. void DxilModule::SetActiveStreamMask(unsigned Mask) {
  411. m_ActiveStreamMask = Mask;
  412. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
  413. "only works for GS profile");
  414. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  415. DXASSERT(props.IsGS(), "Must be GS profile");
  416. for (unsigned i = 0; i < 4; i++) {
  417. if (IsStreamActive(i))
  418. props.ShaderProps.GS.streamPrimitiveTopologies[i] = m_StreamPrimitiveTopology;
  419. else
  420. props.ShaderProps.GS.streamPrimitiveTopologies[i] = DXIL::PrimitiveTopology::Undefined;
  421. }
  422. }
  423. unsigned DxilModule::GetActiveStreamMask() const {
  424. return m_ActiveStreamMask;
  425. }
  426. bool DxilModule::GetUseMinPrecision() const {
  427. return m_bUseMinPrecision;
  428. }
  429. void DxilModule::SetDisableOptimization(bool DisableOptimization) {
  430. m_bDisableOptimizations = DisableOptimization;
  431. }
  432. bool DxilModule::GetDisableOptimization() const {
  433. return m_bDisableOptimizations;
  434. }
  435. void DxilModule::SetAllResourcesBound(bool ResourcesBound) {
  436. m_bAllResourcesBound = ResourcesBound;
  437. }
  438. bool DxilModule::GetAllResourcesBound() const {
  439. return m_bAllResourcesBound;
  440. }
  441. void DxilModule::SetLegacyResourceReservation(bool legacyResourceReservation) {
  442. m_IntermediateFlags &= ~LegacyResourceReservation;
  443. if (legacyResourceReservation) m_IntermediateFlags |= LegacyResourceReservation;
  444. }
  445. bool DxilModule::GetLegacyResourceReservation() const {
  446. return (m_IntermediateFlags & LegacyResourceReservation) != 0;
  447. }
  448. void DxilModule::ClearIntermediateOptions() {
  449. m_IntermediateFlags = 0;
  450. }
  451. unsigned DxilModule::GetInputControlPointCount() const {
  452. if (!(m_pSM->IsHS() || m_pSM->IsDS()))
  453. return 0;
  454. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  455. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  456. DXASSERT(props.IsHS() || props.IsDS(), "Must be HS or DS profile");
  457. if (props.IsHS())
  458. return props.ShaderProps.HS.inputControlPoints;
  459. else
  460. return props.ShaderProps.DS.inputControlPoints;
  461. }
  462. void DxilModule::SetInputControlPointCount(unsigned NumICPs) {
  463. DXASSERT(m_DxilEntryPropsMap.size() == 1
  464. && (m_pSM->IsHS() || m_pSM->IsDS()),
  465. "only works for non-lib profile");
  466. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  467. DXASSERT(props.IsHS() || props.IsDS(), "Must be HS or DS profile");
  468. if (props.IsHS())
  469. props.ShaderProps.HS.inputControlPoints = NumICPs;
  470. else
  471. props.ShaderProps.DS.inputControlPoints = NumICPs;
  472. }
  473. DXIL::TessellatorDomain DxilModule::GetTessellatorDomain() const {
  474. if (!(m_pSM->IsHS() || m_pSM->IsDS()))
  475. return DXIL::TessellatorDomain::Undefined;
  476. DXASSERT_NOMSG(m_DxilEntryPropsMap.size() == 1);
  477. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  478. if (props.IsHS())
  479. return props.ShaderProps.HS.domain;
  480. else
  481. return props.ShaderProps.DS.domain;
  482. }
  483. void DxilModule::SetTessellatorDomain(DXIL::TessellatorDomain TessDomain) {
  484. DXASSERT(m_DxilEntryPropsMap.size() == 1
  485. && (m_pSM->IsHS() || m_pSM->IsDS()),
  486. "only works for HS or DS profile");
  487. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  488. DXASSERT(props.IsHS() || props.IsDS(), "Must be HS or DS profile");
  489. if (props.IsHS())
  490. props.ShaderProps.HS.domain = TessDomain;
  491. else
  492. props.ShaderProps.DS.domain = TessDomain;
  493. }
  494. unsigned DxilModule::GetOutputControlPointCount() const {
  495. if (!m_pSM->IsHS())
  496. return 0;
  497. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  498. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  499. DXASSERT(props.IsHS(), "Must be HS profile");
  500. return props.ShaderProps.HS.outputControlPoints;
  501. }
  502. void DxilModule::SetOutputControlPointCount(unsigned NumOCPs) {
  503. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
  504. "only works for HS profile");
  505. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  506. DXASSERT(props.IsHS(), "Must be HS profile");
  507. props.ShaderProps.HS.outputControlPoints = NumOCPs;
  508. }
  509. DXIL::TessellatorPartitioning DxilModule::GetTessellatorPartitioning() const {
  510. if (!m_pSM->IsHS())
  511. return DXIL::TessellatorPartitioning::Undefined;
  512. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  513. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  514. DXASSERT(props.IsHS(), "Must be HS profile");
  515. return props.ShaderProps.HS.partition;
  516. }
  517. void DxilModule::SetTessellatorPartitioning(DXIL::TessellatorPartitioning TessPartitioning) {
  518. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
  519. "only works for HS profile");
  520. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  521. DXASSERT(props.IsHS(), "Must be HS profile");
  522. props.ShaderProps.HS.partition = TessPartitioning;
  523. }
  524. DXIL::TessellatorOutputPrimitive DxilModule::GetTessellatorOutputPrimitive() const {
  525. if (!m_pSM->IsHS())
  526. return DXIL::TessellatorOutputPrimitive::Undefined;
  527. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  528. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  529. DXASSERT(props.IsHS(), "Must be HS profile");
  530. return props.ShaderProps.HS.outputPrimitive;
  531. }
  532. void DxilModule::SetTessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive TessOutputPrimitive) {
  533. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
  534. "only works for HS profile");
  535. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  536. DXASSERT(props.IsHS(), "Must be HS profile");
  537. props.ShaderProps.HS.outputPrimitive = TessOutputPrimitive;
  538. }
  539. float DxilModule::GetMaxTessellationFactor() const {
  540. if (!m_pSM->IsHS())
  541. return 0.0F;
  542. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  543. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  544. DXASSERT(props.IsHS(), "Must be HS profile");
  545. return props.ShaderProps.HS.maxTessFactor;
  546. }
  547. void DxilModule::SetMaxTessellationFactor(float MaxTessellationFactor) {
  548. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
  549. "only works for HS profile");
  550. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  551. DXASSERT(props.IsHS(), "Must be HS profile");
  552. props.ShaderProps.HS.maxTessFactor = MaxTessellationFactor;
  553. }
  554. unsigned DxilModule::GetMaxOutputVertices() const {
  555. if (!m_pSM->IsMS())
  556. return 0;
  557. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  558. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  559. DXASSERT(props.IsMS(), "Must be MS profile");
  560. return props.ShaderProps.MS.maxVertexCount;
  561. }
  562. void DxilModule::SetMaxOutputVertices(unsigned NumOVs) {
  563. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsMS(),
  564. "only works for MS profile");
  565. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  566. DXASSERT(props.IsMS(), "Must be MS profile");
  567. props.ShaderProps.MS.maxVertexCount = NumOVs;
  568. }
  569. unsigned DxilModule::GetMaxOutputPrimitives() const {
  570. if (!m_pSM->IsMS())
  571. return 0;
  572. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  573. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  574. DXASSERT(props.IsMS(), "Must be MS profile");
  575. return props.ShaderProps.MS.maxPrimitiveCount;
  576. }
  577. void DxilModule::SetMaxOutputPrimitives(unsigned NumOPs) {
  578. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsMS(),
  579. "only works for MS profile");
  580. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  581. DXASSERT(props.IsMS(), "Must be MS profile");
  582. props.ShaderProps.MS.maxPrimitiveCount = NumOPs;
  583. }
  584. DXIL::MeshOutputTopology DxilModule::GetMeshOutputTopology() const {
  585. if (!m_pSM->IsMS())
  586. return DXIL::MeshOutputTopology::Undefined;
  587. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  588. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  589. DXASSERT(props.IsMS(), "Must be MS profile");
  590. return props.ShaderProps.MS.outputTopology;
  591. }
  592. void DxilModule::SetMeshOutputTopology(DXIL::MeshOutputTopology MeshOutputTopology) {
  593. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsMS(),
  594. "only works for MS profile");
  595. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  596. DXASSERT(props.IsMS(), "Must be MS profile");
  597. props.ShaderProps.MS.outputTopology = MeshOutputTopology;
  598. }
  599. unsigned DxilModule::GetPayloadByteSize() const {
  600. if (!m_pSM->IsMS())
  601. return 0;
  602. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  603. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  604. DXASSERT(props.IsMS(), "Must be MS profile");
  605. return props.ShaderProps.MS.payloadByteSize;
  606. }
  607. void DxilModule::SetPayloadByteSize(unsigned Size) {
  608. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsMS(),
  609. "only works for MS profile");
  610. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  611. DXASSERT(props.IsMS(), "Must be MS profile");
  612. props.ShaderProps.MS.payloadByteSize = Size;
  613. }
  614. void DxilModule::SetAutoBindingSpace(uint32_t Space) {
  615. m_AutoBindingSpace = Space;
  616. }
  617. uint32_t DxilModule::GetAutoBindingSpace() const {
  618. return m_AutoBindingSpace;
  619. }
  620. void DxilModule::SetShaderProperties(DxilFunctionProps *props) {
  621. if (!props)
  622. return;
  623. DxilFunctionProps &ourProps = GetDxilFunctionProps(GetEntryFunction());
  624. if (props != &ourProps) {
  625. ourProps.shaderKind = props->shaderKind;
  626. ourProps.ShaderProps = props->ShaderProps;
  627. }
  628. switch (props->shaderKind) {
  629. case DXIL::ShaderKind::Pixel: {
  630. auto &PS = props->ShaderProps.PS;
  631. m_ShaderFlags.SetForceEarlyDepthStencil(PS.EarlyDepthStencil);
  632. } break;
  633. case DXIL::ShaderKind::Compute:
  634. case DXIL::ShaderKind::Domain:
  635. case DXIL::ShaderKind::Hull:
  636. case DXIL::ShaderKind::Vertex:
  637. case DXIL::ShaderKind::Mesh:
  638. case DXIL::ShaderKind::Amplification:
  639. break;
  640. default: {
  641. DXASSERT(props->shaderKind == DXIL::ShaderKind::Geometry,
  642. "else invalid shader kind");
  643. auto &GS = props->ShaderProps.GS;
  644. m_ActiveStreamMask = 0;
  645. for (size_t i = 0; i < _countof(GS.streamPrimitiveTopologies); ++i) {
  646. if (GS.streamPrimitiveTopologies[i] !=
  647. DXIL::PrimitiveTopology::Undefined) {
  648. m_ActiveStreamMask |= (1 << i);
  649. DXASSERT_NOMSG(m_StreamPrimitiveTopology ==
  650. DXIL::PrimitiveTopology::Undefined ||
  651. m_StreamPrimitiveTopology ==
  652. GS.streamPrimitiveTopologies[i]);
  653. m_StreamPrimitiveTopology = GS.streamPrimitiveTopologies[i];
  654. }
  655. }
  656. // Refresh props:
  657. SetActiveStreamMask(m_ActiveStreamMask);
  658. } break;
  659. }
  660. }
  661. template<typename T> unsigned
  662. DxilModule::AddResource(vector<unique_ptr<T> > &Vec, unique_ptr<T> pRes) {
  663. DXASSERT_NOMSG((unsigned)Vec.size() < UINT_MAX);
  664. unsigned Id = (unsigned)Vec.size();
  665. Vec.emplace_back(std::move(pRes));
  666. return Id;
  667. }
  668. unsigned DxilModule::AddCBuffer(unique_ptr<DxilCBuffer> pCB) {
  669. return AddResource<DxilCBuffer>(m_CBuffers, std::move(pCB));
  670. }
  671. DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) {
  672. return *m_CBuffers[idx];
  673. }
  674. const DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) const {
  675. return *m_CBuffers[idx];
  676. }
  677. const vector<unique_ptr<DxilCBuffer> > &DxilModule::GetCBuffers() const {
  678. return m_CBuffers;
  679. }
  680. unsigned DxilModule::AddSampler(unique_ptr<DxilSampler> pSampler) {
  681. return AddResource<DxilSampler>(m_Samplers, std::move(pSampler));
  682. }
  683. DxilSampler &DxilModule::GetSampler(unsigned idx) {
  684. return *m_Samplers[idx];
  685. }
  686. const DxilSampler &DxilModule::GetSampler(unsigned idx) const {
  687. return *m_Samplers[idx];
  688. }
  689. const vector<unique_ptr<DxilSampler> > &DxilModule::GetSamplers() const {
  690. return m_Samplers;
  691. }
  692. unsigned DxilModule::AddSRV(unique_ptr<DxilResource> pSRV) {
  693. return AddResource<DxilResource>(m_SRVs, std::move(pSRV));
  694. }
  695. DxilResource &DxilModule::GetSRV(unsigned idx) {
  696. return *m_SRVs[idx];
  697. }
  698. const DxilResource &DxilModule::GetSRV(unsigned idx) const {
  699. return *m_SRVs[idx];
  700. }
  701. const vector<unique_ptr<DxilResource> > &DxilModule::GetSRVs() const {
  702. return m_SRVs;
  703. }
  704. unsigned DxilModule::AddUAV(unique_ptr<DxilResource> pUAV) {
  705. return AddResource<DxilResource>(m_UAVs, std::move(pUAV));
  706. }
  707. DxilResource &DxilModule::GetUAV(unsigned idx) {
  708. return *m_UAVs[idx];
  709. }
  710. const DxilResource &DxilModule::GetUAV(unsigned idx) const {
  711. return *m_UAVs[idx];
  712. }
  713. const vector<unique_ptr<DxilResource> > &DxilModule::GetUAVs() const {
  714. return m_UAVs;
  715. }
  716. void DxilModule::LoadDxilResourceBaseFromMDNode(MDNode *MD, DxilResourceBase &R) {
  717. return m_pMDHelper->LoadDxilResourceBaseFromMDNode(MD, R);
  718. }
  719. void DxilModule::LoadDxilResourceFromMDNode(llvm::MDNode *MD, DxilResource &R) {
  720. return m_pMDHelper->LoadDxilResourceFromMDNode(MD, R);
  721. }
  722. void DxilModule::LoadDxilSamplerFromMDNode(llvm::MDNode *MD, DxilSampler &S) {
  723. return m_pMDHelper->LoadDxilSamplerFromMDNode(MD, S);
  724. }
  725. template <typename TResource>
  726. static void RemoveResources(std::vector<std::unique_ptr<TResource>> &vec,
  727. std::unordered_set<unsigned> &immResID) {
  728. for (auto p = vec.begin(); p != vec.end();) {
  729. auto c = p++;
  730. if (immResID.count((*c)->GetID()) == 0) {
  731. p = vec.erase(c);
  732. }
  733. }
  734. }
  735. static void CollectUsedResource(Value *resID,
  736. std::unordered_set<Value *> &usedResID) {
  737. if (usedResID.count(resID) > 0)
  738. return;
  739. usedResID.insert(resID);
  740. if (dyn_cast<ConstantInt>(resID)) {
  741. // Do nothing
  742. } else if (ZExtInst *ZEI = dyn_cast<ZExtInst>(resID)) {
  743. if (ZEI->getSrcTy()->isIntegerTy()) {
  744. IntegerType *ITy = cast<IntegerType>(ZEI->getSrcTy());
  745. if (ITy->getBitWidth() == 1) {
  746. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 0));
  747. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 1));
  748. }
  749. }
  750. } else if (SelectInst *SI = dyn_cast<SelectInst>(resID)) {
  751. CollectUsedResource(SI->getTrueValue(), usedResID);
  752. CollectUsedResource(SI->getFalseValue(), usedResID);
  753. } else if (PHINode *Phi = dyn_cast<PHINode>(resID)) {
  754. for (Use &U : Phi->incoming_values()) {
  755. CollectUsedResource(U.get(), usedResID);
  756. }
  757. }
  758. // TODO: resID could be other types of instructions depending on the compiler optimization.
  759. }
  760. static void ConvertUsedResource(std::unordered_set<unsigned> &immResID,
  761. std::unordered_set<Value *> &usedResID) {
  762. for (Value *V : usedResID) {
  763. if (ConstantInt *cResID = dyn_cast<ConstantInt>(V)) {
  764. immResID.insert(cResID->getLimitedValue());
  765. }
  766. }
  767. }
  768. void DxilModule::RemoveFunction(llvm::Function *F) {
  769. DXASSERT_NOMSG(F != nullptr);
  770. m_DxilEntryPropsMap.erase(F);
  771. if (m_pTypeSystem.get()->GetFunctionAnnotation(F))
  772. m_pTypeSystem.get()->EraseFunctionAnnotation(F);
  773. m_pOP->RemoveFunction(F);
  774. }
  775. void DxilModule::RemoveUnusedResources() {
  776. DXASSERT(!m_pSM->IsLib(), "this function does not work on libraries");
  777. hlsl::OP *hlslOP = GetOP();
  778. Function *createHandleFunc = hlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(GetCtx()));
  779. if (createHandleFunc->user_empty()) {
  780. m_CBuffers.clear();
  781. m_UAVs.clear();
  782. m_SRVs.clear();
  783. m_Samplers.clear();
  784. createHandleFunc->eraseFromParent();
  785. return;
  786. }
  787. std::unordered_set<Value *> usedUAVID;
  788. std::unordered_set<Value *> usedSRVID;
  789. std::unordered_set<Value *> usedSamplerID;
  790. std::unordered_set<Value *> usedCBufID;
  791. // Collect used ID.
  792. for (User *U : createHandleFunc->users()) {
  793. CallInst *CI = cast<CallInst>(U);
  794. Value *vResClass =
  795. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
  796. ConstantInt *cResClass = cast<ConstantInt>(vResClass);
  797. DXIL::ResourceClass resClass =
  798. static_cast<DXIL::ResourceClass>(cResClass->getLimitedValue());
  799. // Skip unused resource handle.
  800. if (CI->user_empty())
  801. continue;
  802. Value *resID =
  803. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
  804. switch (resClass) {
  805. case DXIL::ResourceClass::CBuffer:
  806. CollectUsedResource(resID, usedCBufID);
  807. break;
  808. case DXIL::ResourceClass::Sampler:
  809. CollectUsedResource(resID, usedSamplerID);
  810. break;
  811. case DXIL::ResourceClass::SRV:
  812. CollectUsedResource(resID, usedSRVID);
  813. break;
  814. case DXIL::ResourceClass::UAV:
  815. CollectUsedResource(resID, usedUAVID);
  816. break;
  817. default:
  818. DXASSERT(0, "invalid res class");
  819. break;
  820. }
  821. }
  822. std::unordered_set<unsigned> immUAVID;
  823. std::unordered_set<unsigned> immSRVID;
  824. std::unordered_set<unsigned> immSamplerID;
  825. std::unordered_set<unsigned> immCBufID;
  826. ConvertUsedResource(immUAVID, usedUAVID);
  827. ConvertUsedResource(immSRVID, usedSRVID);
  828. ConvertUsedResource(immSamplerID, usedSamplerID);
  829. ConvertUsedResource(immCBufID, usedCBufID);
  830. RemoveResources(m_UAVs, immUAVID);
  831. RemoveResources(m_SRVs, immSRVID);
  832. RemoveResources(m_Samplers, immSamplerID);
  833. RemoveResources(m_CBuffers, immCBufID);
  834. }
  835. namespace {
  836. template <typename TResource>
  837. static void RemoveResourcesWithUnusedSymbolsHelper(std::vector<std::unique_ptr<TResource>> &vec) {
  838. unsigned resID = 0;
  839. for (auto p = vec.begin(); p != vec.end();) {
  840. auto c = p++;
  841. Constant *symbol = (*c)->GetGlobalSymbol();
  842. symbol->removeDeadConstantUsers();
  843. if (symbol->user_empty()) {
  844. p = vec.erase(c);
  845. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(symbol))
  846. GV->eraseFromParent();
  847. continue;
  848. }
  849. if ((*c)->GetID() != resID) {
  850. (*c)->SetID(resID);
  851. }
  852. resID++;
  853. }
  854. }
  855. }
  856. void DxilModule::RemoveResourcesWithUnusedSymbols() {
  857. RemoveResourcesWithUnusedSymbolsHelper(m_SRVs);
  858. RemoveResourcesWithUnusedSymbolsHelper(m_UAVs);
  859. RemoveResourcesWithUnusedSymbolsHelper(m_CBuffers);
  860. RemoveResourcesWithUnusedSymbolsHelper(m_Samplers);
  861. }
  862. DxilSignature &DxilModule::GetInputSignature() {
  863. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  864. "only works for non-lib profile");
  865. return m_DxilEntryPropsMap.begin()->second->sig.InputSignature;
  866. }
  867. const DxilSignature &DxilModule::GetInputSignature() const {
  868. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  869. "only works for non-lib profile");
  870. return m_DxilEntryPropsMap.begin()->second->sig.InputSignature;
  871. }
  872. DxilSignature &DxilModule::GetOutputSignature() {
  873. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  874. "only works for non-lib profile");
  875. return m_DxilEntryPropsMap.begin()->second->sig.OutputSignature;
  876. }
  877. const DxilSignature &DxilModule::GetOutputSignature() const {
  878. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  879. "only works for non-lib profile");
  880. return m_DxilEntryPropsMap.begin()->second->sig.OutputSignature;
  881. }
  882. DxilSignature &DxilModule::GetPatchConstOrPrimSignature() {
  883. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  884. "only works for non-lib profile");
  885. return m_DxilEntryPropsMap.begin()->second->sig.PatchConstOrPrimSignature;
  886. }
  887. const DxilSignature &DxilModule::GetPatchConstOrPrimSignature() const {
  888. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  889. "only works for non-lib profile");
  890. return m_DxilEntryPropsMap.begin()->second->sig.PatchConstOrPrimSignature;
  891. }
  892. const std::vector<uint8_t> &DxilModule::GetSerializedRootSignature() const {
  893. return m_SerializedRootSignature;
  894. }
  895. std::vector<uint8_t> &DxilModule::GetSerializedRootSignature() {
  896. return m_SerializedRootSignature;
  897. }
  898. // Entry props.
  899. bool DxilModule::HasDxilEntrySignature(const llvm::Function *F) const {
  900. return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
  901. }
  902. DxilEntrySignature &DxilModule::GetDxilEntrySignature(const llvm::Function *F) {
  903. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  904. return m_DxilEntryPropsMap[F].get()->sig;
  905. }
  906. void DxilModule::ReplaceDxilEntryProps(llvm::Function *F,
  907. llvm::Function *NewF) {
  908. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  909. std::unique_ptr<DxilEntryProps> Props = std::move(m_DxilEntryPropsMap[F]);
  910. m_DxilEntryPropsMap.erase(F);
  911. m_DxilEntryPropsMap[NewF] = std::move(Props);
  912. }
  913. void DxilModule::CloneDxilEntryProps(llvm::Function *F, llvm::Function *NewF) {
  914. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  915. std::unique_ptr<DxilEntryProps> Props =
  916. llvm::make_unique<DxilEntryProps>(*m_DxilEntryPropsMap[F]);
  917. m_DxilEntryPropsMap[NewF] = std::move(Props);
  918. }
  919. bool DxilModule::HasDxilEntryProps(const llvm::Function *F) const {
  920. return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
  921. }
  922. DxilEntryProps &DxilModule::GetDxilEntryProps(const llvm::Function *F) {
  923. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  924. return *m_DxilEntryPropsMap.find(F)->second.get();
  925. }
  926. const DxilEntryProps &DxilModule::GetDxilEntryProps(const llvm::Function *F) const {
  927. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  928. return *m_DxilEntryPropsMap.find(F)->second.get();
  929. }
  930. bool DxilModule::HasDxilFunctionProps(const llvm::Function *F) const {
  931. return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
  932. }
  933. DxilFunctionProps &DxilModule::GetDxilFunctionProps(const llvm::Function *F) {
  934. return const_cast<DxilFunctionProps &>(
  935. static_cast<const DxilModule *>(this)->GetDxilFunctionProps(F));
  936. }
  937. const DxilFunctionProps &
  938. DxilModule::GetDxilFunctionProps(const llvm::Function *F) const {
  939. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  940. return m_DxilEntryPropsMap.find(F)->second.get()->props;
  941. }
  942. void DxilModule::SetPatchConstantFunctionForHS(llvm::Function *hullShaderFunc, llvm::Function *patchConstantFunc) {
  943. auto propIter = m_DxilEntryPropsMap.find(hullShaderFunc);
  944. DXASSERT(propIter != m_DxilEntryPropsMap.end(),
  945. "Hull shader must already have function props!");
  946. DxilFunctionProps &props = propIter->second->props;
  947. DXASSERT(props.IsHS(), "else hullShaderFunc is not a Hull Shader");
  948. auto &HS = props.ShaderProps.HS;
  949. if (HS.patchConstantFunc != patchConstantFunc) {
  950. if (HS.patchConstantFunc)
  951. m_PatchConstantFunctions.erase(HS.patchConstantFunc);
  952. HS.patchConstantFunc = patchConstantFunc;
  953. if (patchConstantFunc)
  954. m_PatchConstantFunctions.insert(patchConstantFunc);
  955. }
  956. }
  957. bool DxilModule::IsGraphicsShader(const llvm::Function *F) const {
  958. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsGraphics();
  959. }
  960. bool DxilModule::IsPatchConstantShader(const llvm::Function *F) const {
  961. return m_PatchConstantFunctions.count(F) != 0;
  962. }
  963. bool DxilModule::IsComputeShader(const llvm::Function *F) const {
  964. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsCS();
  965. }
  966. bool DxilModule::IsEntryThatUsesSignatures(const llvm::Function *F) const {
  967. auto propIter = m_DxilEntryPropsMap.find(F);
  968. if (propIter != m_DxilEntryPropsMap.end()) {
  969. DxilFunctionProps &props = propIter->second->props;
  970. return props.IsGraphics() || props.IsCS();
  971. }
  972. // Otherwise, return true if patch constant function
  973. return IsPatchConstantShader(F);
  974. }
  975. bool DxilModule::StripRootSignatureFromMetadata() {
  976. NamedMDNode *pRootSignatureNamedMD = GetModule()->getNamedMetadata(DxilMDHelper::kDxilRootSignatureMDName);
  977. if (pRootSignatureNamedMD) {
  978. GetModule()->eraseNamedMetadata(pRootSignatureNamedMD);
  979. return true;
  980. }
  981. return false;
  982. }
  983. DxilSubobjects *DxilModule::GetSubobjects() {
  984. return m_pSubobjects.get();
  985. }
  986. const DxilSubobjects *DxilModule::GetSubobjects() const {
  987. return m_pSubobjects.get();
  988. }
  989. DxilSubobjects *DxilModule::ReleaseSubobjects() {
  990. return m_pSubobjects.release();
  991. }
  992. void DxilModule::ResetSubobjects(DxilSubobjects *subobjects) {
  993. m_pSubobjects.reset(subobjects);
  994. }
  995. bool DxilModule::StripSubobjectsFromMetadata() {
  996. NamedMDNode *pSubobjectsNamedMD = GetModule()->getNamedMetadata(DxilMDHelper::kDxilSubobjectsMDName);
  997. if (pSubobjectsNamedMD) {
  998. GetModule()->eraseNamedMetadata(pSubobjectsNamedMD);
  999. return true;
  1000. }
  1001. return false;
  1002. }
  1003. void DxilModule::UpdateValidatorVersionMetadata() {
  1004. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  1005. }
  1006. void DxilModule::ResetSerializedRootSignature(std::vector<uint8_t> &Value) {
  1007. m_SerializedRootSignature.clear();
  1008. m_SerializedRootSignature.reserve(Value.size());
  1009. m_SerializedRootSignature.assign(Value.begin(), Value.end());
  1010. }
  1011. DxilTypeSystem &DxilModule::GetTypeSystem() {
  1012. return *m_pTypeSystem;
  1013. }
  1014. std::vector<unsigned> &DxilModule::GetSerializedViewIdState() {
  1015. return m_SerializedState;
  1016. }
  1017. const std::vector<unsigned> &DxilModule::GetSerializedViewIdState() const {
  1018. return m_SerializedState;
  1019. }
  1020. void DxilModule::ResetTypeSystem(DxilTypeSystem *pValue) {
  1021. m_pTypeSystem.reset(pValue);
  1022. }
  1023. void DxilModule::ResetOP(hlsl::OP *hlslOP) { m_pOP.reset(hlslOP); }
  1024. void DxilModule::ResetEntryPropsMap(DxilEntryPropsMap &&PropMap) {
  1025. m_DxilEntryPropsMap.clear();
  1026. std::move(PropMap.begin(), PropMap.end(),
  1027. inserter(m_DxilEntryPropsMap, m_DxilEntryPropsMap.begin()));
  1028. }
  1029. static const StringRef llvmUsedName = "llvm.used";
  1030. void DxilModule::EmitLLVMUsed() {
  1031. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  1032. oldGV->eraseFromParent();
  1033. }
  1034. if (m_LLVMUsed.empty())
  1035. return;
  1036. vector<llvm::Constant *> GVs;
  1037. Type *pI8PtrType = Type::getInt8PtrTy(m_Ctx, DXIL::kDefaultAddrSpace);
  1038. GVs.resize(m_LLVMUsed.size());
  1039. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  1040. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  1041. PointerType *pPtrType = dyn_cast<PointerType>(pConst->getType());
  1042. if (pPtrType->getPointerAddressSpace() != DXIL::kDefaultAddrSpace) {
  1043. // Cast pointer to addrspace 0, as LLVMUsed elements must have the same
  1044. // type.
  1045. GVs[i] = ConstantExpr::getAddrSpaceCast(pConst, pI8PtrType);
  1046. } else {
  1047. GVs[i] = ConstantExpr::getPointerCast(pConst, pI8PtrType);
  1048. }
  1049. }
  1050. ArrayType *pATy = ArrayType::get(pI8PtrType, GVs.size());
  1051. GlobalVariable *pGV =
  1052. new GlobalVariable(*m_pModule, pATy, false, GlobalValue::AppendingLinkage,
  1053. ConstantArray::get(pATy, GVs), llvmUsedName);
  1054. pGV->setSection("llvm.metadata");
  1055. }
  1056. void DxilModule::ClearLLVMUsed() {
  1057. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  1058. oldGV->eraseFromParent();
  1059. }
  1060. if (m_LLVMUsed.empty())
  1061. return;
  1062. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  1063. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  1064. pConst->removeDeadConstantUsers();
  1065. }
  1066. m_LLVMUsed.clear();
  1067. }
  1068. vector<GlobalVariable* > &DxilModule::GetLLVMUsed() {
  1069. return m_LLVMUsed;
  1070. }
  1071. // DXIL metadata serialization/deserialization.
  1072. void DxilModule::ClearDxilMetadata(Module &M) {
  1073. // Delete: DXIL version, validator version, DXIL shader model,
  1074. // entry point tuples (shader properties, signatures, resources)
  1075. // type system, view ID state, LLVM used, entry point tuples,
  1076. // root signature, function properties.
  1077. // Other cases for libs pending.
  1078. // LLVM used is a global variable - handle separately.
  1079. SmallVector<NamedMDNode*, 8> nodes;
  1080. for (NamedMDNode &b : M.named_metadata()) {
  1081. StringRef name = b.getName();
  1082. if (name == DxilMDHelper::kDxilVersionMDName ||
  1083. name == DxilMDHelper::kDxilValidatorVersionMDName ||
  1084. name == DxilMDHelper::kDxilShaderModelMDName ||
  1085. name == DxilMDHelper::kDxilEntryPointsMDName ||
  1086. name == DxilMDHelper::kDxilRootSignatureMDName ||
  1087. name == DxilMDHelper::kDxilIntermediateOptionsMDName ||
  1088. name == DxilMDHelper::kDxilResourcesMDName ||
  1089. name == DxilMDHelper::kDxilTypeSystemMDName ||
  1090. name == DxilMDHelper::kDxilViewIdStateMDName ||
  1091. name == DxilMDHelper::kDxilSubobjectsMDName ||
  1092. name.startswith(DxilMDHelper::kDxilTypeSystemHelperVariablePrefix)) {
  1093. nodes.push_back(&b);
  1094. }
  1095. }
  1096. for (size_t i = 0; i < nodes.size(); ++i) {
  1097. M.eraseNamedMetadata(nodes[i]);
  1098. }
  1099. }
  1100. void DxilModule::EmitDxilMetadata() {
  1101. m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
  1102. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  1103. m_pMDHelper->EmitDxilShaderModel(m_pSM);
  1104. m_pMDHelper->EmitDxilIntermediateOptions(m_IntermediateFlags);
  1105. MDTuple *pMDProperties = nullptr;
  1106. uint64_t flag = m_ShaderFlags.GetShaderFlagsRaw();
  1107. if (m_pSM->IsLib()) {
  1108. DxilFunctionProps props;
  1109. props.shaderKind = DXIL::ShaderKind::Library;
  1110. pMDProperties = m_pMDHelper->EmitDxilEntryProperties(flag, props,
  1111. GetAutoBindingSpace());
  1112. } else {
  1113. pMDProperties = m_pMDHelper->EmitDxilEntryProperties(
  1114. flag, m_DxilEntryPropsMap.begin()->second->props,
  1115. GetAutoBindingSpace());
  1116. }
  1117. MDTuple *pMDSignatures = nullptr;
  1118. if (!m_pSM->IsLib()) {
  1119. pMDSignatures = m_pMDHelper->EmitDxilSignatures(
  1120. m_DxilEntryPropsMap.begin()->second->sig);
  1121. }
  1122. MDTuple *pMDResources = EmitDxilResources();
  1123. if (pMDResources)
  1124. m_pMDHelper->EmitDxilResources(pMDResources);
  1125. m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
  1126. if (!m_pSM->IsLib() && !m_pSM->IsCS() &&
  1127. ((m_ValMajor == 0 && m_ValMinor == 0) ||
  1128. (m_ValMajor > 1 || (m_ValMajor == 1 && m_ValMinor >= 1)))) {
  1129. m_pMDHelper->EmitDxilViewIdState(m_SerializedState);
  1130. }
  1131. EmitLLVMUsed();
  1132. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources, pMDProperties);
  1133. vector<MDNode *> Entries;
  1134. Entries.emplace_back(pEntry);
  1135. if (m_pSM->IsLib()) {
  1136. // Sort functions by name to keep metadata deterministic
  1137. vector<const Function *> funcOrder;
  1138. funcOrder.reserve(m_DxilEntryPropsMap.size());
  1139. std::transform( m_DxilEntryPropsMap.begin(),
  1140. m_DxilEntryPropsMap.end(),
  1141. std::back_inserter(funcOrder),
  1142. [](const std::pair<const llvm::Function * const, std::unique_ptr<DxilEntryProps>> &p) -> const Function* { return p.first; } );
  1143. std::sort(funcOrder.begin(), funcOrder.end(), [](const Function *F1, const Function *F2) {
  1144. return F1->getName() < F2->getName();
  1145. });
  1146. for (auto F : funcOrder) {
  1147. auto &entryProps = m_DxilEntryPropsMap[F];
  1148. MDTuple *pProps = m_pMDHelper->EmitDxilEntryProperties(0, entryProps->props, 0);
  1149. MDTuple *pSig = m_pMDHelper->EmitDxilSignatures(entryProps->sig);
  1150. MDTuple *pSubEntry = m_pMDHelper->EmitDxilEntryPointTuple(
  1151. const_cast<Function *>(F), F->getName(), pSig, nullptr, pProps);
  1152. Entries.emplace_back(pSubEntry);
  1153. }
  1154. funcOrder.clear();
  1155. // Save Subobjects
  1156. if (GetSubobjects()) {
  1157. m_pMDHelper->EmitSubobjects(*GetSubobjects());
  1158. }
  1159. }
  1160. m_pMDHelper->EmitDxilEntryPoints(Entries);
  1161. if (!m_SerializedRootSignature.empty()) {
  1162. m_pMDHelper->EmitRootSignature(m_SerializedRootSignature);
  1163. }
  1164. }
  1165. bool DxilModule::IsKnownNamedMetaData(llvm::NamedMDNode &Node) {
  1166. return DxilMDHelper::IsKnownNamedMetaData(Node);
  1167. }
  1168. void DxilModule::LoadDxilMetadata() {
  1169. m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
  1170. m_pMDHelper->LoadValidatorVersion(m_ValMajor, m_ValMinor);
  1171. const ShaderModel *loadedSM;
  1172. m_pMDHelper->LoadDxilShaderModel(loadedSM);
  1173. m_pMDHelper->LoadDxilIntermediateOptions(m_IntermediateFlags);
  1174. // This must be set before LoadDxilEntryProperties
  1175. m_pMDHelper->SetShaderModel(loadedSM);
  1176. // Setting module shader model requires UseMinPrecision flag,
  1177. // which requires loading m_ShaderFlags,
  1178. // which requires global entry properties,
  1179. // so load entry properties first, then set the shader model
  1180. const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
  1181. if (!loadedSM->IsLib()) {
  1182. IFTBOOL(pEntries->getNumOperands() == 1, DXC_E_INCORRECT_DXIL_METADATA);
  1183. }
  1184. Function *pEntryFunc;
  1185. string EntryName;
  1186. const llvm::MDOperand *pEntrySignatures, *pEntryResources, *pEntryProperties;
  1187. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0),
  1188. pEntryFunc, EntryName,
  1189. pEntrySignatures, pEntryResources,
  1190. pEntryProperties);
  1191. uint64_t rawShaderFlags = 0;
  1192. DxilFunctionProps entryFuncProps;
  1193. entryFuncProps.shaderKind = loadedSM->GetKind();
  1194. m_pMDHelper->LoadDxilEntryProperties(*pEntryProperties, rawShaderFlags,
  1195. entryFuncProps, m_AutoBindingSpace);
  1196. m_bUseMinPrecision = true;
  1197. if (rawShaderFlags) {
  1198. m_ShaderFlags.SetShaderFlagsRaw(rawShaderFlags);
  1199. m_bUseMinPrecision = !m_ShaderFlags.GetUseNativeLowPrecision();
  1200. m_bDisableOptimizations = m_ShaderFlags.GetDisableOptimizations();
  1201. m_bAllResourcesBound = m_ShaderFlags.GetAllResourcesBound();
  1202. }
  1203. // Now that we have the UseMinPrecision flag, set shader model:
  1204. SetShaderModel(loadedSM, m_bUseMinPrecision);
  1205. if (loadedSM->IsLib()) {
  1206. for (unsigned i = 1; i < pEntries->getNumOperands(); i++) {
  1207. Function *pFunc;
  1208. string Name;
  1209. const llvm::MDOperand *pSignatures, *pResources, *pProperties;
  1210. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(i), pFunc, Name,
  1211. pSignatures, pResources, pProperties);
  1212. DxilFunctionProps props;
  1213. uint64_t rawShaderFlags = 0;
  1214. unsigned autoBindingSpace = 0;
  1215. m_pMDHelper->LoadDxilEntryProperties(
  1216. *pProperties, rawShaderFlags, props, autoBindingSpace);
  1217. if (props.IsHS() && props.ShaderProps.HS.patchConstantFunc) {
  1218. // Add patch constant function to m_PatchConstantFunctions
  1219. m_PatchConstantFunctions.insert(props.ShaderProps.HS.patchConstantFunc);
  1220. }
  1221. std::unique_ptr<DxilEntryProps> pEntryProps =
  1222. llvm::make_unique<DxilEntryProps>(props, m_bUseMinPrecision);
  1223. m_pMDHelper->LoadDxilSignatures(*pSignatures, pEntryProps->sig);
  1224. m_DxilEntryPropsMap[pFunc] = std::move(pEntryProps);
  1225. }
  1226. // Load Subobjects
  1227. std::unique_ptr<DxilSubobjects> pSubobjects(new DxilSubobjects());
  1228. m_pMDHelper->LoadSubobjects(*pSubobjects);
  1229. if (pSubobjects->GetSubobjects().size()) {
  1230. ResetSubobjects(pSubobjects.release());
  1231. }
  1232. } else {
  1233. std::unique_ptr<DxilEntryProps> pEntryProps =
  1234. llvm::make_unique<DxilEntryProps>(entryFuncProps, m_bUseMinPrecision);
  1235. DxilFunctionProps *pFuncProps = &pEntryProps->props;
  1236. m_pMDHelper->LoadDxilSignatures(*pEntrySignatures, pEntryProps->sig);
  1237. m_DxilEntryPropsMap.clear();
  1238. m_DxilEntryPropsMap[pEntryFunc] = std::move(pEntryProps);
  1239. SetEntryFunction(pEntryFunc);
  1240. SetEntryFunctionName(EntryName);
  1241. SetShaderProperties(pFuncProps);
  1242. }
  1243. LoadDxilResources(*pEntryResources);
  1244. m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
  1245. m_pMDHelper->LoadRootSignature(m_SerializedRootSignature);
  1246. m_pMDHelper->LoadDxilViewIdState(m_SerializedState);
  1247. }
  1248. MDTuple *DxilModule::EmitDxilResources() {
  1249. // Emit SRV records.
  1250. MDTuple *pTupleSRVs = nullptr;
  1251. if (!m_SRVs.empty()) {
  1252. vector<Metadata *> MDVals;
  1253. for (size_t i = 0; i < m_SRVs.size(); i++) {
  1254. MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
  1255. }
  1256. pTupleSRVs = MDNode::get(m_Ctx, MDVals);
  1257. }
  1258. // Emit UAV records.
  1259. MDTuple *pTupleUAVs = nullptr;
  1260. if (!m_UAVs.empty()) {
  1261. vector<Metadata *> MDVals;
  1262. for (size_t i = 0; i < m_UAVs.size(); i++) {
  1263. MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
  1264. }
  1265. pTupleUAVs = MDNode::get(m_Ctx, MDVals);
  1266. }
  1267. // Emit CBuffer records.
  1268. MDTuple *pTupleCBuffers = nullptr;
  1269. if (!m_CBuffers.empty()) {
  1270. vector<Metadata *> MDVals;
  1271. for (size_t i = 0; i < m_CBuffers.size(); i++) {
  1272. MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
  1273. }
  1274. pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
  1275. }
  1276. // Emit Sampler records.
  1277. MDTuple *pTupleSamplers = nullptr;
  1278. if (!m_Samplers.empty()) {
  1279. vector<Metadata *> MDVals;
  1280. for (size_t i = 0; i < m_Samplers.size(); i++) {
  1281. MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
  1282. }
  1283. pTupleSamplers = MDNode::get(m_Ctx, MDVals);
  1284. }
  1285. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr || pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  1286. return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs, pTupleCBuffers, pTupleSamplers);
  1287. } else {
  1288. return nullptr;
  1289. }
  1290. }
  1291. void DxilModule::ReEmitDxilResources() {
  1292. ClearDxilMetadata(*m_pModule);
  1293. EmitDxilMetadata();
  1294. }
  1295. template <typename TResource>
  1296. static void
  1297. StripResourcesReflection(std::vector<std::unique_ptr<TResource>> &vec) {
  1298. for (auto &p : vec) {
  1299. p->SetGlobalName("");
  1300. // Cannot remove global symbol which used by validation.
  1301. }
  1302. }
  1303. void DxilModule::StripReflection() {
  1304. // Remove names.
  1305. for (Function &F : m_pModule->functions()) {
  1306. for (BasicBlock &BB : F) {
  1307. if (BB.hasName())
  1308. BB.setName("");
  1309. for (Instruction &I : BB) {
  1310. if (I.hasName())
  1311. I.setName("");
  1312. }
  1313. }
  1314. }
  1315. // Remove struct annotation.
  1316. // FunctionAnnotation is used later, so keep it.
  1317. m_pTypeSystem->GetStructAnnotationMap().clear();
  1318. // Resource
  1319. if (!GetShaderModel()->IsLib()) {
  1320. StripResourcesReflection(m_CBuffers);
  1321. StripResourcesReflection(m_UAVs);
  1322. StripResourcesReflection(m_SRVs);
  1323. StripResourcesReflection(m_Samplers);
  1324. }
  1325. // Unused global.
  1326. SmallVector<GlobalVariable *,2> UnusedGlobals;
  1327. for (GlobalVariable &GV : m_pModule->globals()) {
  1328. if (GV.use_empty())
  1329. UnusedGlobals.emplace_back(&GV);
  1330. }
  1331. for (GlobalVariable *GV : UnusedGlobals) {
  1332. GV->eraseFromParent();
  1333. }
  1334. // ReEmit meta.
  1335. ReEmitDxilResources();
  1336. }
  1337. void DxilModule::LoadDxilResources(const llvm::MDOperand &MDO) {
  1338. if (MDO.get() == nullptr)
  1339. return;
  1340. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  1341. m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
  1342. // Load SRV records.
  1343. if (pSRVs != nullptr) {
  1344. for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
  1345. unique_ptr<DxilResource> pSRV(new DxilResource);
  1346. m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
  1347. AddSRV(std::move(pSRV));
  1348. }
  1349. }
  1350. // Load UAV records.
  1351. if (pUAVs != nullptr) {
  1352. for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
  1353. unique_ptr<DxilResource> pUAV(new DxilResource);
  1354. m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
  1355. AddUAV(std::move(pUAV));
  1356. }
  1357. }
  1358. // Load CBuffer records.
  1359. if (pCBuffers != nullptr) {
  1360. for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
  1361. unique_ptr<DxilCBuffer> pCB(new DxilCBuffer);
  1362. m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
  1363. AddCBuffer(std::move(pCB));
  1364. }
  1365. }
  1366. // Load Sampler records.
  1367. if (pSamplers != nullptr) {
  1368. for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
  1369. unique_ptr<DxilSampler> pSampler(new DxilSampler);
  1370. m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
  1371. AddSampler(std::move(pSampler));
  1372. }
  1373. }
  1374. }
  1375. void DxilModule::StripDebugRelatedCode() {
  1376. // Remove dx.source metadata.
  1377. if (NamedMDNode *contents = m_pModule->getNamedMetadata(
  1378. DxilMDHelper::kDxilSourceContentsMDName)) {
  1379. contents->eraseFromParent();
  1380. }
  1381. if (NamedMDNode *defines =
  1382. m_pModule->getNamedMetadata(DxilMDHelper::kDxilSourceDefinesMDName)) {
  1383. defines->eraseFromParent();
  1384. }
  1385. if (NamedMDNode *mainFileName = m_pModule->getNamedMetadata(
  1386. DxilMDHelper::kDxilSourceMainFileNameMDName)) {
  1387. mainFileName->eraseFromParent();
  1388. }
  1389. if (NamedMDNode *arguments =
  1390. m_pModule->getNamedMetadata(DxilMDHelper::kDxilSourceArgsMDName)) {
  1391. arguments->eraseFromParent();
  1392. }
  1393. if (NamedMDNode *flags = m_pModule->getModuleFlagsMetadata()) {
  1394. SmallVector<llvm::Module::ModuleFlagEntry, 4> flagEntries;
  1395. m_pModule->getModuleFlagsMetadata(flagEntries);
  1396. flags->eraseFromParent();
  1397. for (unsigned i = 0; i < flagEntries.size(); i++) {
  1398. llvm::Module::ModuleFlagEntry &entry = flagEntries[i];
  1399. if (entry.Key->getString() == "Dwarf Version" || entry.Key->getString() == "Debug Info Version") {
  1400. continue;
  1401. }
  1402. m_pModule->addModuleFlag(
  1403. entry.Behavior, entry.Key->getString(),
  1404. cast<ConstantAsMetadata>(entry.Val)->getValue());
  1405. }
  1406. }
  1407. }
  1408. DebugInfoFinder &DxilModule::GetOrCreateDebugInfoFinder() {
  1409. if (m_pDebugInfoFinder == nullptr) {
  1410. m_pDebugInfoFinder = llvm::make_unique<llvm::DebugInfoFinder>();
  1411. m_pDebugInfoFinder->processModule(*m_pModule);
  1412. }
  1413. return *m_pDebugInfoFinder;
  1414. }
  1415. hlsl::DxilModule *hlsl::DxilModule::TryGetDxilModule(llvm::Module *pModule) {
  1416. LLVMContext &Ctx = pModule->getContext();
  1417. std::string diagStr;
  1418. raw_string_ostream diagStream(diagStr);
  1419. hlsl::DxilModule *pDxilModule = nullptr;
  1420. // TODO: add detail error in DxilMDHelper.
  1421. try {
  1422. pDxilModule = &pModule->GetOrCreateDxilModule();
  1423. } catch (const ::hlsl::Exception &hlslException) {
  1424. diagStream << "load dxil metadata failed -";
  1425. try {
  1426. const char *msg = hlslException.what();
  1427. if (msg == nullptr || *msg == '\0')
  1428. diagStream << " error code " << hlslException.hr << "\n";
  1429. else
  1430. diagStream << msg;
  1431. } catch (...) {
  1432. diagStream << " unable to retrieve error message.\n";
  1433. }
  1434. Ctx.diagnose(DxilErrorDiagnosticInfo(diagStream.str().c_str()));
  1435. } catch (...) {
  1436. Ctx.diagnose(DxilErrorDiagnosticInfo("load dxil metadata failed - unknown error.\n"));
  1437. }
  1438. return pDxilModule;
  1439. }
  1440. // Check if the instruction has fast math flags configured to indicate
  1441. // the instruction is precise.
  1442. // Precise fast math flags means none of the fast math flags are set.
  1443. bool DxilModule::HasPreciseFastMathFlags(const Instruction *inst) {
  1444. return isa<FPMathOperator>(inst) && !inst->getFastMathFlags().any();
  1445. }
  1446. // Set fast math flags configured to indicate the instruction is precise.
  1447. void DxilModule::SetPreciseFastMathFlags(llvm::Instruction *inst) {
  1448. assert(isa<FPMathOperator>(inst));
  1449. inst->copyFastMathFlags(FastMathFlags());
  1450. }
  1451. // True if fast math flags are preserved across serialization/deserialization
  1452. // of the dxil module.
  1453. //
  1454. // We need to check for this when querying fast math flags for preciseness
  1455. // otherwise we will be overly conservative by reporting instructions precise
  1456. // because their fast math flags were not preserved.
  1457. //
  1458. // Currently we restrict it to the instruction types that have fast math
  1459. // preserved in the bitcode. We can expand this by converting fast math
  1460. // flags to dx.precise metadata during serialization and back to fast
  1461. // math flags during deserialization.
  1462. bool DxilModule::PreservesFastMathFlags(const llvm::Instruction *inst) {
  1463. return
  1464. isa<FPMathOperator>(inst) && (isa<BinaryOperator>(inst) || isa<FCmpInst>(inst));
  1465. }
  1466. bool DxilModule::IsPrecise(const Instruction *inst) const {
  1467. if (m_ShaderFlags.GetDisableMathRefactoring())
  1468. return true;
  1469. else if (DxilMDHelper::IsMarkedPrecise(inst))
  1470. return true;
  1471. else if (PreservesFastMathFlags(inst))
  1472. return HasPreciseFastMathFlags(inst);
  1473. else
  1474. return false;
  1475. }
  1476. } // namespace hlsl
  1477. namespace llvm {
  1478. hlsl::DxilModule &Module::GetOrCreateDxilModule(bool skipInit) {
  1479. std::unique_ptr<hlsl::DxilModule> M;
  1480. if (!HasDxilModule()) {
  1481. M = llvm::make_unique<hlsl::DxilModule>(this);
  1482. if (!skipInit) {
  1483. M->LoadDxilMetadata();
  1484. }
  1485. SetDxilModule(M.release());
  1486. }
  1487. return GetDxilModule();
  1488. }
  1489. }