DxilModule.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491
  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 "dxc/HLSL/DxilFunctionProps.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/LLVMContext.h"
  21. #include "llvm/IR/Metadata.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/IR/Operator.h"
  24. #include "llvm/IR/DebugInfo.h"
  25. #include "llvm/IR/DiagnosticInfo.h"
  26. #include "llvm/IR/DiagnosticPrinter.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <unordered_set>
  29. using namespace llvm;
  30. using std::string;
  31. using std::vector;
  32. using std::unique_ptr;
  33. namespace {
  34. class DxilErrorDiagnosticInfo : public DiagnosticInfo {
  35. private:
  36. const char *m_message;
  37. public:
  38. DxilErrorDiagnosticInfo(const char *str)
  39. : DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
  40. m_message(str) { }
  41. __override void print(DiagnosticPrinter &DP) const {
  42. DP << m_message;
  43. }
  44. };
  45. } // anon namespace
  46. namespace hlsl {
  47. //------------------------------------------------------------------------------
  48. //
  49. // DxilModule methods.
  50. //
  51. DxilModule::DxilModule(Module *pModule)
  52. : m_Ctx(pModule->getContext())
  53. , m_pModule(pModule)
  54. , m_pOP(std::make_unique<OP>(pModule->getContext(), pModule))
  55. , m_pTypeSystem(std::make_unique<DxilTypeSystem>(pModule))
  56. , m_pViewIdState(std::make_unique<DxilViewIdState>(this))
  57. , m_pMDHelper(std::make_unique<DxilMDHelper>(pModule, std::make_unique<DxilExtraPropertyHelper>(pModule)))
  58. , m_pDebugInfoFinder(nullptr)
  59. , m_pEntryFunc(nullptr)
  60. , m_EntryName("")
  61. , m_pPatchConstantFunc(nullptr)
  62. , m_pSM(nullptr)
  63. , m_DxilMajor(DXIL::kDxilMajor)
  64. , m_DxilMinor(DXIL::kDxilMinor)
  65. , m_ValMajor(1)
  66. , m_ValMinor(0)
  67. , m_InputPrimitive(DXIL::InputPrimitive::Undefined)
  68. , m_MaxVertexCount(0)
  69. , m_StreamPrimitiveTopology(DXIL::PrimitiveTopology::Undefined)
  70. , m_ActiveStreamMask(0)
  71. , m_NumGSInstances(1)
  72. , m_InputControlPointCount(0)
  73. , m_TessellatorDomain(DXIL::TessellatorDomain::Undefined)
  74. , m_OutputControlPointCount(0)
  75. , m_TessellatorPartitioning(DXIL::TessellatorPartitioning::Undefined)
  76. , m_TessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive::Undefined)
  77. , m_MaxTessellationFactor(0.f)
  78. , m_RootSignature(nullptr)
  79. , m_bUseMinPrecision(true) // use min precision by default
  80. , m_bDisableOptimizations(false)
  81. , m_bAllResourcesBound(false) {
  82. DXASSERT_NOMSG(m_pModule != nullptr);
  83. m_NumThreads[0] = m_NumThreads[1] = m_NumThreads[2] = 0;
  84. #if defined(_DEBUG) || defined(DBG)
  85. // Pin LLVM dump methods.
  86. void (__thiscall Module::*pfnModuleDump)() const = &Module::dump;
  87. void (__thiscall Type::*pfnTypeDump)() const = &Type::dump;
  88. void (__thiscall Function::*pfnViewCFGOnly)() const = &Function::viewCFGOnly;
  89. m_pUnused = (char *)&pfnModuleDump - (char *)&pfnTypeDump;
  90. m_pUnused -= (size_t)&pfnViewCFGOnly;
  91. #endif
  92. }
  93. DxilModule::~DxilModule() {
  94. }
  95. LLVMContext &DxilModule::GetCtx() const { return m_Ctx; }
  96. Module *DxilModule::GetModule() const { return m_pModule; }
  97. OP *DxilModule::GetOP() const { return m_pOP.get(); }
  98. void DxilModule::SetShaderModel(const ShaderModel *pSM) {
  99. DXASSERT(m_pSM == nullptr || (pSM != nullptr && *m_pSM == *pSM), "shader model must not change for the module");
  100. DXASSERT(pSM != nullptr && pSM->IsValidForDxil(), "shader model must be valid");
  101. DXASSERT(pSM->IsValidForModule(), "shader model must be valid for top-level module use");
  102. m_pSM = pSM;
  103. m_pSM->GetDxilVersion(m_DxilMajor, m_DxilMinor);
  104. m_pMDHelper->SetShaderModel(m_pSM);
  105. DXIL::ShaderKind shaderKind = pSM->GetKind();
  106. m_EntrySignature = llvm::make_unique<DxilEntrySignature>(shaderKind, GetUseMinPrecision());
  107. m_RootSignature.reset(new RootSignatureHandle());
  108. }
  109. const ShaderModel *DxilModule::GetShaderModel() const {
  110. return m_pSM;
  111. }
  112. void DxilModule::GetDxilVersion(unsigned &DxilMajor, unsigned &DxilMinor) const {
  113. DxilMajor = m_DxilMajor;
  114. DxilMinor = m_DxilMinor;
  115. }
  116. void DxilModule::SetValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
  117. m_ValMajor = ValMajor;
  118. m_ValMinor = ValMinor;
  119. }
  120. bool DxilModule::UpgradeValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
  121. // Don't upgrade if validation was disabled.
  122. if (m_ValMajor == 0 && m_ValMinor == 0) {
  123. return false;
  124. }
  125. if (ValMajor > m_ValMajor || (ValMajor == m_ValMajor && ValMinor > m_ValMinor)) {
  126. // Module requires higher validator version than previously set
  127. SetValidatorVersion(ValMajor, ValMinor);
  128. return true;
  129. }
  130. return false;
  131. }
  132. void DxilModule::GetValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const {
  133. ValMajor = m_ValMajor;
  134. ValMinor = m_ValMinor;
  135. }
  136. bool DxilModule::GetMinValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const {
  137. if (!m_pSM)
  138. return false;
  139. m_pSM->GetMinValidatorVersion(ValMajor, ValMinor);
  140. if (ValMajor == 1 && ValMinor == 0 && (m_ShaderFlags.GetFeatureInfo() & hlsl::ShaderFeatureInfo_ViewID))
  141. ValMinor = 1;
  142. return true;
  143. }
  144. bool DxilModule::UpgradeToMinValidatorVersion() {
  145. unsigned ValMajor = 1, ValMinor = 0;
  146. if (GetMinValidatorVersion(ValMajor, ValMinor)) {
  147. return UpgradeValidatorVersion(ValMajor, ValMinor);
  148. }
  149. return false;
  150. }
  151. Function *DxilModule::GetEntryFunction() {
  152. return m_pEntryFunc;
  153. }
  154. const Function *DxilModule::GetEntryFunction() const {
  155. return m_pEntryFunc;
  156. }
  157. void DxilModule::SetEntryFunction(Function *pEntryFunc) {
  158. m_pEntryFunc = pEntryFunc;
  159. }
  160. const string &DxilModule::GetEntryFunctionName() const {
  161. return m_EntryName;
  162. }
  163. void DxilModule::SetEntryFunctionName(const string &name) {
  164. m_EntryName = name;
  165. }
  166. llvm::Function *DxilModule::GetPatchConstantFunction() {
  167. return m_pPatchConstantFunc;
  168. }
  169. const llvm::Function *DxilModule::GetPatchConstantFunction() const {
  170. return m_pPatchConstantFunc;
  171. }
  172. void DxilModule::SetPatchConstantFunction(llvm::Function *pFunc) {
  173. m_pPatchConstantFunc = pFunc;
  174. }
  175. unsigned DxilModule::GetGlobalFlags() const {
  176. unsigned Flags = m_ShaderFlags.GetGlobalFlags();
  177. return Flags;
  178. }
  179. void DxilModule::CollectShaderFlagsForModule(ShaderFlags &Flags) {
  180. for (Function &F : GetModule()->functions()) {
  181. ShaderFlags funcFlags = ShaderFlags::CollectShaderFlags(&F, this);
  182. Flags.CombineShaderFlags(funcFlags);
  183. };
  184. const ShaderModel *SM = GetShaderModel();
  185. if (SM->IsPS()) {
  186. bool hasStencilRef = false;
  187. DxilSignature &outS = GetOutputSignature();
  188. for (auto &&E : outS.GetElements()) {
  189. if (E->GetKind() == Semantic::Kind::StencilRef) {
  190. hasStencilRef = true;
  191. } else if (E->GetKind() == Semantic::Kind::InnerCoverage) {
  192. Flags.SetInnerCoverage(true);
  193. }
  194. }
  195. Flags.SetStencilRef(hasStencilRef);
  196. }
  197. bool checkInputRTArrayIndex =
  198. SM->IsGS() || SM->IsDS() || SM->IsHS() || SM->IsPS();
  199. if (checkInputRTArrayIndex) {
  200. bool hasViewportArrayIndex = false;
  201. bool hasRenderTargetArrayIndex = false;
  202. DxilSignature &inS = GetInputSignature();
  203. for (auto &E : inS.GetElements()) {
  204. if (E->GetKind() == Semantic::Kind::ViewPortArrayIndex) {
  205. hasViewportArrayIndex = true;
  206. } else if (E->GetKind() == Semantic::Kind::RenderTargetArrayIndex) {
  207. hasRenderTargetArrayIndex = true;
  208. }
  209. }
  210. Flags.SetViewportAndRTArrayIndex(hasViewportArrayIndex |
  211. hasRenderTargetArrayIndex);
  212. }
  213. bool checkOutputRTArrayIndex =
  214. SM->IsVS() || SM->IsDS() || SM->IsHS() || SM->IsPS();
  215. if (checkOutputRTArrayIndex) {
  216. bool hasViewportArrayIndex = false;
  217. bool hasRenderTargetArrayIndex = false;
  218. DxilSignature &outS = GetOutputSignature();
  219. for (auto &E : outS.GetElements()) {
  220. if (E->GetKind() == Semantic::Kind::ViewPortArrayIndex) {
  221. hasViewportArrayIndex = true;
  222. } else if (E->GetKind() == Semantic::Kind::RenderTargetArrayIndex) {
  223. hasRenderTargetArrayIndex = true;
  224. }
  225. }
  226. Flags.SetViewportAndRTArrayIndex(hasViewportArrayIndex |
  227. hasRenderTargetArrayIndex);
  228. }
  229. unsigned NumUAVs = m_UAVs.size();
  230. const unsigned kSmallUAVCount = 8;
  231. if (NumUAVs > kSmallUAVCount)
  232. Flags.Set64UAVs(true);
  233. if (NumUAVs && !(SM->IsCS() || SM->IsPS()))
  234. Flags.SetUAVsAtEveryStage(true);
  235. bool hasRawAndStructuredBuffer = false;
  236. for (auto &UAV : m_UAVs) {
  237. if (UAV->IsROV())
  238. Flags.SetROVs(true);
  239. switch (UAV->GetKind()) {
  240. case DXIL::ResourceKind::RawBuffer:
  241. case DXIL::ResourceKind::StructuredBuffer:
  242. hasRawAndStructuredBuffer = true;
  243. break;
  244. default:
  245. // Not raw/structured.
  246. break;
  247. }
  248. }
  249. for (auto &SRV : m_SRVs) {
  250. switch (SRV->GetKind()) {
  251. case DXIL::ResourceKind::RawBuffer:
  252. case DXIL::ResourceKind::StructuredBuffer:
  253. hasRawAndStructuredBuffer = true;
  254. break;
  255. default:
  256. // Not raw/structured.
  257. break;
  258. }
  259. }
  260. Flags.SetEnableRawAndStructuredBuffers(hasRawAndStructuredBuffer);
  261. bool hasCSRawAndStructuredViaShader4X =
  262. hasRawAndStructuredBuffer && m_pSM->GetMajor() == 4 && m_pSM->IsCS();
  263. Flags.SetCSRawAndStructuredViaShader4X(hasCSRawAndStructuredViaShader4X);
  264. }
  265. void DxilModule::CollectShaderFlagsForModule() {
  266. CollectShaderFlagsForModule(m_ShaderFlags);
  267. }
  268. DXIL::InputPrimitive DxilModule::GetInputPrimitive() const {
  269. return m_InputPrimitive;
  270. }
  271. void DxilModule::SetInputPrimitive(DXIL::InputPrimitive IP) {
  272. DXASSERT_NOMSG(m_InputPrimitive == DXIL::InputPrimitive::Undefined);
  273. DXASSERT_NOMSG(DXIL::InputPrimitive::Undefined < IP && IP < DXIL::InputPrimitive::LastEntry);
  274. m_InputPrimitive = IP;
  275. }
  276. unsigned DxilModule::GetMaxVertexCount() const {
  277. DXASSERT_NOMSG(m_MaxVertexCount != 0);
  278. return m_MaxVertexCount;
  279. }
  280. void DxilModule::SetMaxVertexCount(unsigned Count) {
  281. DXASSERT_NOMSG(m_MaxVertexCount == 0);
  282. m_MaxVertexCount = Count;
  283. }
  284. DXIL::PrimitiveTopology DxilModule::GetStreamPrimitiveTopology() const {
  285. return m_StreamPrimitiveTopology;
  286. }
  287. void DxilModule::SetStreamPrimitiveTopology(DXIL::PrimitiveTopology Topology) {
  288. m_StreamPrimitiveTopology = Topology;
  289. }
  290. bool DxilModule::HasMultipleOutputStreams() const {
  291. if (!m_pSM->IsGS()) {
  292. return false;
  293. } else {
  294. unsigned NumStreams = (m_ActiveStreamMask & 0x1) +
  295. ((m_ActiveStreamMask & 0x2) >> 1) +
  296. ((m_ActiveStreamMask & 0x4) >> 2) +
  297. ((m_ActiveStreamMask & 0x8) >> 3);
  298. DXASSERT_NOMSG(NumStreams <= DXIL::kNumOutputStreams);
  299. return NumStreams > 1;
  300. }
  301. }
  302. unsigned DxilModule::GetOutputStream() const {
  303. if (!m_pSM->IsGS()) {
  304. return 0;
  305. } else {
  306. DXASSERT_NOMSG(!HasMultipleOutputStreams());
  307. switch (m_ActiveStreamMask) {
  308. case 0x1: return 0;
  309. case 0x2: return 1;
  310. case 0x4: return 2;
  311. case 0x8: return 3;
  312. default: DXASSERT_NOMSG(false);
  313. }
  314. return (unsigned)(-1);
  315. }
  316. }
  317. unsigned DxilModule::GetGSInstanceCount() const {
  318. return m_NumGSInstances;
  319. }
  320. void DxilModule::SetGSInstanceCount(unsigned Count) {
  321. m_NumGSInstances = Count;
  322. }
  323. bool DxilModule::IsStreamActive(unsigned Stream) const {
  324. return (m_ActiveStreamMask & (1<<Stream)) != 0;
  325. }
  326. void DxilModule::SetStreamActive(unsigned Stream, bool bActive) {
  327. if (bActive) {
  328. m_ActiveStreamMask |= (1<<Stream);
  329. } else {
  330. m_ActiveStreamMask &= ~(1<<Stream);
  331. }
  332. }
  333. void DxilModule::SetActiveStreamMask(unsigned Mask) {
  334. m_ActiveStreamMask = Mask;
  335. }
  336. unsigned DxilModule::GetActiveStreamMask() const {
  337. return m_ActiveStreamMask;
  338. }
  339. void DxilModule::SetUseMinPrecision(bool UseMinPrecision) {
  340. m_bUseMinPrecision = UseMinPrecision;
  341. }
  342. bool DxilModule::GetUseMinPrecision() const {
  343. return m_bUseMinPrecision;
  344. }
  345. void DxilModule::SetDisableOptimization(bool DisableOptimization) {
  346. m_bDisableOptimizations = DisableOptimization;
  347. }
  348. bool DxilModule::GetDisableOptimization() const {
  349. return m_bDisableOptimizations;
  350. }
  351. void DxilModule::SetAllResourcesBound(bool ResourcesBound) {
  352. m_bAllResourcesBound = ResourcesBound;
  353. }
  354. bool DxilModule::GetAllResourcesBound() const {
  355. return m_bAllResourcesBound;
  356. }
  357. unsigned DxilModule::GetInputControlPointCount() const {
  358. return m_InputControlPointCount;
  359. }
  360. void DxilModule::SetInputControlPointCount(unsigned NumICPs) {
  361. m_InputControlPointCount = NumICPs;
  362. }
  363. DXIL::TessellatorDomain DxilModule::GetTessellatorDomain() const {
  364. return m_TessellatorDomain;
  365. }
  366. void DxilModule::SetTessellatorDomain(DXIL::TessellatorDomain TessDomain) {
  367. m_TessellatorDomain = TessDomain;
  368. }
  369. unsigned DxilModule::GetOutputControlPointCount() const {
  370. return m_OutputControlPointCount;
  371. }
  372. void DxilModule::SetOutputControlPointCount(unsigned NumOCPs) {
  373. m_OutputControlPointCount = NumOCPs;
  374. }
  375. DXIL::TessellatorPartitioning DxilModule::GetTessellatorPartitioning() const {
  376. return m_TessellatorPartitioning;
  377. }
  378. void DxilModule::SetTessellatorPartitioning(DXIL::TessellatorPartitioning TessPartitioning) {
  379. m_TessellatorPartitioning = TessPartitioning;
  380. }
  381. DXIL::TessellatorOutputPrimitive DxilModule::GetTessellatorOutputPrimitive() const {
  382. return m_TessellatorOutputPrimitive;
  383. }
  384. void DxilModule::SetTessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive TessOutputPrimitive) {
  385. m_TessellatorOutputPrimitive = TessOutputPrimitive;
  386. }
  387. float DxilModule::GetMaxTessellationFactor() const {
  388. return m_MaxTessellationFactor;
  389. }
  390. void DxilModule::SetMaxTessellationFactor(float MaxTessellationFactor) {
  391. m_MaxTessellationFactor = MaxTessellationFactor;
  392. }
  393. void DxilModule::SetShaderProperties(DxilFunctionProps *props) {
  394. if (!props)
  395. return;
  396. switch (props->shaderKind) {
  397. case DXIL::ShaderKind::Pixel: {
  398. auto &PS = props->ShaderProps.PS;
  399. m_ShaderFlags.SetForceEarlyDepthStencil(PS.EarlyDepthStencil);
  400. } break;
  401. case DXIL::ShaderKind::Compute: {
  402. auto &CS = props->ShaderProps.CS;
  403. for (size_t i = 0; i < _countof(m_NumThreads); ++i)
  404. m_NumThreads[i] = CS.numThreads[i];
  405. } break;
  406. case DXIL::ShaderKind::Domain: {
  407. auto &DS = props->ShaderProps.DS;
  408. SetTessellatorDomain(DS.domain);
  409. SetInputControlPointCount(DS.inputControlPoints);
  410. } break;
  411. case DXIL::ShaderKind::Hull: {
  412. auto &HS = props->ShaderProps.HS;
  413. SetPatchConstantFunction(HS.patchConstantFunc);
  414. SetTessellatorDomain(HS.domain);
  415. SetTessellatorPartitioning(HS.partition);
  416. SetTessellatorOutputPrimitive(HS.outputPrimitive);
  417. SetInputControlPointCount(HS.inputControlPoints);
  418. SetOutputControlPointCount(HS.outputControlPoints);
  419. SetMaxTessellationFactor(HS.maxTessFactor);
  420. } break;
  421. case DXIL::ShaderKind::Vertex:
  422. break;
  423. default: {
  424. DXASSERT(props->shaderKind == DXIL::ShaderKind::Geometry,
  425. "else invalid shader kind");
  426. auto &GS = props->ShaderProps.GS;
  427. SetInputPrimitive(GS.inputPrimitive);
  428. SetMaxVertexCount(GS.maxVertexCount);
  429. for (size_t i = 0; i < _countof(GS.streamPrimitiveTopologies); ++i) {
  430. if (GS.streamPrimitiveTopologies[i] !=
  431. DXIL::PrimitiveTopology::Undefined) {
  432. SetStreamActive(i, true);
  433. DXASSERT_NOMSG(GetStreamPrimitiveTopology() ==
  434. DXIL::PrimitiveTopology::Undefined ||
  435. GetStreamPrimitiveTopology() ==
  436. GS.streamPrimitiveTopologies[i]);
  437. SetStreamPrimitiveTopology(GS.streamPrimitiveTopologies[i]);
  438. }
  439. }
  440. SetGSInstanceCount(GS.instanceCount);
  441. } break;
  442. }
  443. }
  444. template<typename T> unsigned
  445. DxilModule::AddResource(vector<unique_ptr<T> > &Vec, unique_ptr<T> pRes) {
  446. DXASSERT_NOMSG((unsigned)Vec.size() < UINT_MAX);
  447. unsigned Id = (unsigned)Vec.size();
  448. Vec.emplace_back(std::move(pRes));
  449. return Id;
  450. }
  451. unsigned DxilModule::AddCBuffer(unique_ptr<DxilCBuffer> pCB) {
  452. return AddResource<DxilCBuffer>(m_CBuffers, std::move(pCB));
  453. }
  454. DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) {
  455. return *m_CBuffers[idx];
  456. }
  457. const DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) const {
  458. return *m_CBuffers[idx];
  459. }
  460. const vector<unique_ptr<DxilCBuffer> > &DxilModule::GetCBuffers() const {
  461. return m_CBuffers;
  462. }
  463. unsigned DxilModule::AddSampler(unique_ptr<DxilSampler> pSampler) {
  464. return AddResource<DxilSampler>(m_Samplers, std::move(pSampler));
  465. }
  466. DxilSampler &DxilModule::GetSampler(unsigned idx) {
  467. return *m_Samplers[idx];
  468. }
  469. const DxilSampler &DxilModule::GetSampler(unsigned idx) const {
  470. return *m_Samplers[idx];
  471. }
  472. const vector<unique_ptr<DxilSampler> > &DxilModule::GetSamplers() const {
  473. return m_Samplers;
  474. }
  475. unsigned DxilModule::AddSRV(unique_ptr<DxilResource> pSRV) {
  476. return AddResource<DxilResource>(m_SRVs, std::move(pSRV));
  477. }
  478. DxilResource &DxilModule::GetSRV(unsigned idx) {
  479. return *m_SRVs[idx];
  480. }
  481. const DxilResource &DxilModule::GetSRV(unsigned idx) const {
  482. return *m_SRVs[idx];
  483. }
  484. const vector<unique_ptr<DxilResource> > &DxilModule::GetSRVs() const {
  485. return m_SRVs;
  486. }
  487. unsigned DxilModule::AddUAV(unique_ptr<DxilResource> pUAV) {
  488. return AddResource<DxilResource>(m_UAVs, std::move(pUAV));
  489. }
  490. DxilResource &DxilModule::GetUAV(unsigned idx) {
  491. return *m_UAVs[idx];
  492. }
  493. const DxilResource &DxilModule::GetUAV(unsigned idx) const {
  494. return *m_UAVs[idx];
  495. }
  496. const vector<unique_ptr<DxilResource> > &DxilModule::GetUAVs() const {
  497. return m_UAVs;
  498. }
  499. void DxilModule::LoadDxilResourceBaseFromMDNode(MDNode *MD, DxilResourceBase &R) {
  500. return m_pMDHelper->LoadDxilResourceBaseFromMDNode(MD, R);
  501. }
  502. void DxilModule::LoadDxilResourceFromMDNode(llvm::MDNode *MD, DxilResource &R) {
  503. return m_pMDHelper->LoadDxilResourceFromMDNode(MD, R);
  504. }
  505. void DxilModule::LoadDxilSamplerFromMDNode(llvm::MDNode *MD, DxilSampler &S) {
  506. return m_pMDHelper->LoadDxilSamplerFromMDNode(MD, S);
  507. }
  508. template <typename TResource>
  509. static void RemoveResources(std::vector<std::unique_ptr<TResource>> &vec,
  510. std::unordered_set<unsigned> &immResID) {
  511. for (std::vector<std::unique_ptr<TResource>>::iterator p = vec.begin(); p != vec.end();) {
  512. std::vector<std::unique_ptr<TResource>>::iterator c = p++;
  513. if (immResID.count((*c)->GetID()) == 0) {
  514. p = vec.erase(c);
  515. }
  516. }
  517. }
  518. static void CollectUsedResource(Value *resID,
  519. std::unordered_set<Value *> &usedResID) {
  520. if (usedResID.count(resID) > 0)
  521. return;
  522. usedResID.insert(resID);
  523. if (ConstantInt *cResID = dyn_cast<ConstantInt>(resID)) {
  524. // Do nothing
  525. } else if (ZExtInst *ZEI = dyn_cast<ZExtInst>(resID)) {
  526. if (ZEI->getSrcTy()->isIntegerTy()) {
  527. IntegerType *ITy = cast<IntegerType>(ZEI->getSrcTy());
  528. if (ITy->getBitWidth() == 1) {
  529. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 0));
  530. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 1));
  531. }
  532. }
  533. } else if (SelectInst *SI = dyn_cast<SelectInst>(resID)) {
  534. CollectUsedResource(SI->getTrueValue(), usedResID);
  535. CollectUsedResource(SI->getFalseValue(), usedResID);
  536. } else if (PHINode *Phi = dyn_cast<PHINode>(resID)) {
  537. for (Use &U : Phi->incoming_values()) {
  538. CollectUsedResource(U.get(), usedResID);
  539. }
  540. }
  541. // TODO: resID could be other types of instructions depending on the compiler optimization.
  542. }
  543. static void ConvertUsedResource(std::unordered_set<unsigned> &immResID,
  544. std::unordered_set<Value *> &usedResID) {
  545. for (Value *V : usedResID) {
  546. if (ConstantInt *cResID = dyn_cast<ConstantInt>(V)) {
  547. immResID.insert(cResID->getLimitedValue());
  548. }
  549. }
  550. }
  551. void DxilModule::RemoveFunction(llvm::Function *F) {
  552. DXASSERT_NOMSG(F != nullptr);
  553. m_DxilFunctionPropsMap.erase(F);
  554. m_DxilEntrySignatureMap.erase(F);
  555. if (m_pTypeSystem.get()->GetFunctionAnnotation(F))
  556. m_pTypeSystem.get()->EraseFunctionAnnotation(F);
  557. m_pOP->RemoveFunction(F);
  558. }
  559. void DxilModule::RemoveUnusedResources() {
  560. DXASSERT(!m_pSM->IsLib(), "this function not work on library");
  561. hlsl::OP *hlslOP = GetOP();
  562. Function *createHandleFunc = hlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(GetCtx()));
  563. if (createHandleFunc->user_empty()) {
  564. m_CBuffers.clear();
  565. m_UAVs.clear();
  566. m_SRVs.clear();
  567. m_Samplers.clear();
  568. createHandleFunc->eraseFromParent();
  569. return;
  570. }
  571. std::unordered_set<Value *> usedUAVID;
  572. std::unordered_set<Value *> usedSRVID;
  573. std::unordered_set<Value *> usedSamplerID;
  574. std::unordered_set<Value *> usedCBufID;
  575. // Collect used ID.
  576. for (User *U : createHandleFunc->users()) {
  577. CallInst *CI = cast<CallInst>(U);
  578. Value *vResClass =
  579. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
  580. ConstantInt *cResClass = cast<ConstantInt>(vResClass);
  581. DXIL::ResourceClass resClass =
  582. static_cast<DXIL::ResourceClass>(cResClass->getLimitedValue());
  583. // Skip unused resource handle.
  584. if (CI->user_empty())
  585. continue;
  586. Value *resID =
  587. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
  588. switch (resClass) {
  589. case DXIL::ResourceClass::CBuffer:
  590. CollectUsedResource(resID, usedCBufID);
  591. break;
  592. case DXIL::ResourceClass::Sampler:
  593. CollectUsedResource(resID, usedSamplerID);
  594. break;
  595. case DXIL::ResourceClass::SRV:
  596. CollectUsedResource(resID, usedSRVID);
  597. break;
  598. case DXIL::ResourceClass::UAV:
  599. CollectUsedResource(resID, usedUAVID);
  600. break;
  601. default:
  602. DXASSERT(0, "invalid res class");
  603. break;
  604. }
  605. }
  606. std::unordered_set<unsigned> immUAVID;
  607. std::unordered_set<unsigned> immSRVID;
  608. std::unordered_set<unsigned> immSamplerID;
  609. std::unordered_set<unsigned> immCBufID;
  610. ConvertUsedResource(immUAVID, usedUAVID);
  611. RemoveResources(m_UAVs, immUAVID);
  612. ConvertUsedResource(immSRVID, usedSRVID);
  613. ConvertUsedResource(immSamplerID, usedSamplerID);
  614. ConvertUsedResource(immCBufID, usedCBufID);
  615. RemoveResources(m_SRVs, immSRVID);
  616. RemoveResources(m_Samplers, immSamplerID);
  617. RemoveResources(m_CBuffers, immCBufID);
  618. }
  619. namespace {
  620. template <typename TResource>
  621. static void RemoveResourceSymbols(std::vector<std::unique_ptr<TResource>> &vec) {
  622. unsigned resID = 0;
  623. for (std::vector<std::unique_ptr<TResource>>::iterator p = vec.begin(); p != vec.end();) {
  624. std::vector<std::unique_ptr<TResource>>::iterator c = p++;
  625. GlobalVariable *GV = cast<GlobalVariable>((*c)->GetGlobalSymbol());
  626. GV->removeDeadConstantUsers();
  627. if (GV->user_empty()) {
  628. p = vec.erase(c);
  629. GV->eraseFromParent();
  630. continue;
  631. }
  632. if ((*c)->GetID() != resID) {
  633. (*c)->SetID(resID);
  634. }
  635. resID++;
  636. }
  637. }
  638. }
  639. void DxilModule::RemoveUnusedResourceSymbols() {
  640. RemoveResourceSymbols(m_SRVs);
  641. RemoveResourceSymbols(m_UAVs);
  642. RemoveResourceSymbols(m_CBuffers);
  643. RemoveResourceSymbols(m_Samplers);
  644. }
  645. DxilSignature &DxilModule::GetInputSignature() {
  646. return m_EntrySignature->InputSignature;
  647. }
  648. const DxilSignature &DxilModule::GetInputSignature() const {
  649. return m_EntrySignature->InputSignature;
  650. }
  651. DxilSignature &DxilModule::GetOutputSignature() {
  652. return m_EntrySignature->OutputSignature;
  653. }
  654. const DxilSignature &DxilModule::GetOutputSignature() const {
  655. return m_EntrySignature->OutputSignature;
  656. }
  657. DxilSignature &DxilModule::GetPatchConstantSignature() {
  658. return m_EntrySignature->PatchConstantSignature;
  659. }
  660. const DxilSignature &DxilModule::GetPatchConstantSignature() const {
  661. return m_EntrySignature->PatchConstantSignature;
  662. }
  663. const RootSignatureHandle &DxilModule::GetRootSignature() const {
  664. return *m_RootSignature;
  665. }
  666. bool DxilModule::HasDxilEntrySignature(const llvm::Function *F) const {
  667. return m_DxilEntrySignatureMap.find(F) != m_DxilEntrySignatureMap.end();
  668. }
  669. DxilEntrySignature &DxilModule::GetDxilEntrySignature(const llvm::Function *F) {
  670. DXASSERT(m_DxilEntrySignatureMap.count(F) != 0, "cannot find F in map");
  671. return *m_DxilEntrySignatureMap[F];
  672. }
  673. void DxilModule::ReplaceDxilEntrySignature(llvm::Function *F,
  674. llvm::Function *NewF) {
  675. DXASSERT(m_DxilEntrySignatureMap.count(F) != 0, "cannot find F in map");
  676. std::unique_ptr<DxilEntrySignature> Sig =
  677. std::move(m_DxilEntrySignatureMap[F]);
  678. m_DxilEntrySignatureMap.erase(F);
  679. m_DxilEntrySignatureMap[NewF] = std::move(Sig);
  680. }
  681. bool DxilModule::HasDxilFunctionProps(const llvm::Function *F) const {
  682. return m_DxilFunctionPropsMap.find(F) != m_DxilFunctionPropsMap.end();
  683. }
  684. DxilFunctionProps &DxilModule::GetDxilFunctionProps(const llvm::Function *F) {
  685. return const_cast<DxilFunctionProps &>(
  686. static_cast<const DxilModule *>(this)->GetDxilFunctionProps(F));
  687. }
  688. const DxilFunctionProps &
  689. DxilModule::GetDxilFunctionProps(const llvm::Function *F) const {
  690. DXASSERT(m_DxilFunctionPropsMap.count(F) != 0, "cannot find F in map");
  691. return *(m_DxilFunctionPropsMap.find(F))->second.get();
  692. }
  693. void DxilModule::AddDxilFunctionProps(
  694. const llvm::Function *F, std::unique_ptr<DxilFunctionProps> &info) {
  695. DXASSERT(m_DxilFunctionPropsMap.count(F) == 0,
  696. "F already in map, info will be overwritten");
  697. DXASSERT_NOMSG(info->shaderKind != DXIL::ShaderKind::Invalid);
  698. m_DxilFunctionPropsMap[F] = std::move(info);
  699. }
  700. void DxilModule::ReplaceDxilFunctionProps(llvm::Function *F,
  701. llvm::Function *NewF) {
  702. DXASSERT(m_DxilFunctionPropsMap.count(F) != 0, "cannot find F in map");
  703. std::unique_ptr<DxilFunctionProps> props =
  704. std::move(m_DxilFunctionPropsMap[F]);
  705. m_DxilFunctionPropsMap.erase(F);
  706. m_DxilFunctionPropsMap[NewF] = std::move(props);
  707. }
  708. void DxilModule::SetPatchConstantFunctionForHS(llvm::Function *hullShaderFunc, llvm::Function *patchConstantFunc) {
  709. auto propIter = m_DxilFunctionPropsMap.find(hullShaderFunc);
  710. DXASSERT(propIter != m_DxilFunctionPropsMap.end(), "Hull shader must already have function props!");
  711. DxilFunctionProps &props = *(propIter->second);
  712. DXASSERT(props.IsHS(), "else hullShaderFunc is not a Hull Shader");
  713. if (props.ShaderProps.HS.patchConstantFunc)
  714. m_PatchConstantFunctions.erase(props.ShaderProps.HS.patchConstantFunc);
  715. props.ShaderProps.HS.patchConstantFunc = patchConstantFunc;
  716. if (patchConstantFunc)
  717. m_PatchConstantFunctions.insert(patchConstantFunc);
  718. }
  719. bool DxilModule::IsGraphicsShader(const llvm::Function *F) const {
  720. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsGraphics();
  721. }
  722. bool DxilModule::IsPatchConstantShader(const llvm::Function *F) const {
  723. return m_PatchConstantFunctions.count(F) != 0;
  724. }
  725. bool DxilModule::IsComputeShader(const llvm::Function *F) const {
  726. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsCS();
  727. }
  728. bool DxilModule::IsEntryThatUsesSignatures(const llvm::Function *F) const {
  729. auto propIter = m_DxilFunctionPropsMap.find(F);
  730. if (propIter != m_DxilFunctionPropsMap.end()) {
  731. DxilFunctionProps &props = *(propIter->second);
  732. return props.IsGraphics() || props.IsCS();
  733. }
  734. // Otherwise, return true if patch constant function
  735. return IsPatchConstantShader(F);
  736. }
  737. void DxilModule::StripRootSignatureFromMetadata() {
  738. NamedMDNode *pRootSignatureNamedMD = GetModule()->getNamedMetadata(DxilMDHelper::kDxilRootSignatureMDName);
  739. if (pRootSignatureNamedMD) {
  740. GetModule()->eraseNamedMetadata(pRootSignatureNamedMD);
  741. }
  742. }
  743. void DxilModule::UpdateValidatorVersionMetadata() {
  744. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  745. }
  746. void DxilModule::ResetEntrySignature(DxilEntrySignature *pValue) {
  747. m_EntrySignature.reset(pValue);
  748. }
  749. void DxilModule::ResetRootSignature(RootSignatureHandle *pValue) {
  750. m_RootSignature.reset(pValue);
  751. }
  752. DxilTypeSystem &DxilModule::GetTypeSystem() {
  753. return *m_pTypeSystem;
  754. }
  755. DxilViewIdState &DxilModule::GetViewIdState() {
  756. return *m_pViewIdState;
  757. }
  758. const DxilViewIdState &DxilModule::GetViewIdState() const {
  759. return *m_pViewIdState;
  760. }
  761. void DxilModule::ResetTypeSystem(DxilTypeSystem *pValue) {
  762. m_pTypeSystem.reset(pValue);
  763. }
  764. void DxilModule::ResetOP(hlsl::OP *hlslOP) { m_pOP.reset(hlslOP); }
  765. void DxilModule::ResetFunctionPropsMap(DxilFunctionPropsMap &&propsMap) {
  766. m_DxilFunctionPropsMap = std::move(propsMap);
  767. }
  768. void DxilModule::ResetEntrySignatureMap(DxilEntrySignatureMap &&SigMap) {
  769. m_DxilEntrySignatureMap = std::move(SigMap);
  770. }
  771. static const StringRef llvmUsedName = "llvm.used";
  772. void DxilModule::EmitLLVMUsed() {
  773. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  774. oldGV->eraseFromParent();
  775. }
  776. if (m_LLVMUsed.empty())
  777. return;
  778. vector<llvm::Constant *> GVs;
  779. Type *pI8PtrType = Type::getInt8PtrTy(m_Ctx, DXIL::kDefaultAddrSpace);
  780. GVs.resize(m_LLVMUsed.size());
  781. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  782. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  783. PointerType *pPtrType = dyn_cast<PointerType>(pConst->getType());
  784. if (pPtrType->getPointerAddressSpace() != DXIL::kDefaultAddrSpace) {
  785. // Cast pointer to addrspace 0, as LLVMUsed elements must have the same
  786. // type.
  787. GVs[i] = ConstantExpr::getAddrSpaceCast(pConst, pI8PtrType);
  788. } else {
  789. GVs[i] = ConstantExpr::getPointerCast(pConst, pI8PtrType);
  790. }
  791. }
  792. ArrayType *pATy = ArrayType::get(pI8PtrType, GVs.size());
  793. GlobalVariable *pGV =
  794. new GlobalVariable(*m_pModule, pATy, false, GlobalValue::AppendingLinkage,
  795. ConstantArray::get(pATy, GVs), llvmUsedName);
  796. pGV->setSection("llvm.metadata");
  797. }
  798. void DxilModule::ClearLLVMUsed() {
  799. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  800. oldGV->eraseFromParent();
  801. }
  802. if (m_LLVMUsed.empty())
  803. return;
  804. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  805. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  806. pConst->removeDeadConstantUsers();
  807. }
  808. m_LLVMUsed.clear();
  809. }
  810. vector<GlobalVariable* > &DxilModule::GetLLVMUsed() {
  811. return m_LLVMUsed;
  812. }
  813. // DXIL metadata serialization/deserialization.
  814. void DxilModule::ClearDxilMetadata(Module &M) {
  815. // Delete: DXIL version, validator version, DXIL shader model,
  816. // entry point tuples (shader properties, signatures, resources)
  817. // type system, view ID state, LLVM used, entry point tuples,
  818. // root signature, function properties.
  819. // Other cases for libs pending.
  820. // LLVM used is a global variable - handle separately.
  821. Module::named_metadata_iterator
  822. b = M.named_metadata_begin(),
  823. e = M.named_metadata_end();
  824. SmallVector<NamedMDNode*, 8> nodes;
  825. for (; b != e; ++b) {
  826. StringRef name = b->getName();
  827. if (name == DxilMDHelper::kDxilVersionMDName ||
  828. name == DxilMDHelper::kDxilValidatorVersionMDName ||
  829. name == DxilMDHelper::kDxilShaderModelMDName ||
  830. name == DxilMDHelper::kDxilEntryPointsMDName ||
  831. name == DxilMDHelper::kDxilRootSignatureMDName ||
  832. name == DxilMDHelper::kDxilResourcesMDName ||
  833. name == DxilMDHelper::kDxilTypeSystemMDName ||
  834. name == DxilMDHelper::kDxilViewIdStateMDName ||
  835. name == DxilMDHelper::kDxilFunctionPropertiesMDName || // used in libraries
  836. name == DxilMDHelper::kDxilEntrySignaturesMDName || // used in libraries
  837. name == DxilMDHelper::kDxilResourcesLinkInfoMDName || // used in libraries
  838. name.startswith(DxilMDHelper::kDxilTypeSystemHelperVariablePrefix)) {
  839. nodes.push_back(b);
  840. }
  841. }
  842. for (size_t i = 0; i < nodes.size(); ++i) {
  843. M.eraseNamedMetadata(nodes[i]);
  844. }
  845. }
  846. void DxilModule::EmitDxilMetadata() {
  847. m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
  848. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  849. m_pMDHelper->EmitDxilShaderModel(m_pSM);
  850. MDTuple *pMDProperties = EmitDxilShaderProperties();
  851. MDTuple *pMDSignatures = m_pMDHelper->EmitDxilSignatures(*m_EntrySignature);
  852. MDTuple *pMDResources = EmitDxilResources();
  853. if (pMDResources)
  854. m_pMDHelper->EmitDxilResources(pMDResources);
  855. m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
  856. if (!m_pSM->IsLib() && !m_pSM->IsCS() &&
  857. ((m_ValMajor == 0 && m_ValMinor == 0) ||
  858. (m_ValMajor > 1 || (m_ValMajor == 1 && m_ValMinor >= 1)))) {
  859. m_pMDHelper->EmitDxilViewIdState(GetViewIdState());
  860. }
  861. EmitLLVMUsed();
  862. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources, pMDProperties);
  863. vector<MDNode *> Entries;
  864. Entries.emplace_back(pEntry);
  865. m_pMDHelper->EmitDxilEntryPoints(Entries);
  866. if (!m_RootSignature->IsEmpty()) {
  867. m_pMDHelper->EmitRootSignature(*m_RootSignature.get());
  868. }
  869. if (m_pSM->IsLib()) {
  870. NamedMDNode *fnProps = m_pModule->getOrInsertNamedMetadata(
  871. DxilMDHelper::kDxilFunctionPropertiesMDName);
  872. // Sort functions by name to keep metadata deterministic
  873. vector<const Function *> funcOrder;
  874. funcOrder.reserve(std::max(m_DxilFunctionPropsMap.size(),
  875. m_DxilEntrySignatureMap.size()));
  876. std::transform( m_DxilFunctionPropsMap.begin(),
  877. m_DxilFunctionPropsMap.end(),
  878. std::back_inserter(funcOrder),
  879. [](auto &p) -> const Function* { return p.first; } );
  880. std::sort(funcOrder.begin(), funcOrder.end(), [](const Function *F1, const Function *F2) {
  881. return F1->getName() < F2->getName();
  882. });
  883. for (auto F : funcOrder) {
  884. MDTuple *pProps = m_pMDHelper->EmitDxilFunctionProps(&GetDxilFunctionProps(F), F);
  885. fnProps->addOperand(pProps);
  886. }
  887. funcOrder.clear();
  888. NamedMDNode *entrySigs = m_pModule->getOrInsertNamedMetadata(
  889. DxilMDHelper::kDxilEntrySignaturesMDName);
  890. // Sort functions by name to keep metadata deterministic
  891. std::transform( m_DxilEntrySignatureMap.begin(),
  892. m_DxilEntrySignatureMap.end(),
  893. std::back_inserter(funcOrder),
  894. [](auto &p) -> const Function* { return p.first; } );
  895. std::sort(funcOrder.begin(), funcOrder.end(), [](const Function *F1, const Function *F2) {
  896. return F1->getName() < F2->getName();
  897. });
  898. for (auto F : funcOrder) {
  899. DxilEntrySignature *Sig = &GetDxilEntrySignature(F);
  900. MDTuple *pSig = m_pMDHelper->EmitDxilSignatures(*Sig);
  901. entrySigs->addOperand(
  902. MDTuple::get(m_Ctx, {ValueAsMetadata::get(const_cast<Function*>(F)), pSig}));
  903. }
  904. }
  905. }
  906. bool DxilModule::IsKnownNamedMetaData(llvm::NamedMDNode &Node) {
  907. return DxilMDHelper::IsKnownNamedMetaData(Node);
  908. }
  909. void DxilModule::LoadDxilMetadata() {
  910. m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
  911. m_pMDHelper->LoadValidatorVersion(m_ValMajor, m_ValMinor);
  912. const ShaderModel *loadedModule;
  913. m_pMDHelper->LoadDxilShaderModel(loadedModule);
  914. SetShaderModel(loadedModule);
  915. DXASSERT(m_EntrySignature != nullptr, "else SetShaderModel didn't create entry signature");
  916. const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
  917. IFTBOOL(pEntries->getNumOperands() == 1, DXC_E_INCORRECT_DXIL_METADATA);
  918. Function *pEntryFunc;
  919. string EntryName;
  920. const llvm::MDOperand *pSignatures, *pResources, *pProperties;
  921. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0), pEntryFunc, EntryName, pSignatures, pResources, pProperties);
  922. SetEntryFunction(pEntryFunc);
  923. SetEntryFunctionName(EntryName);
  924. LoadDxilShaderProperties(*pProperties);
  925. m_pMDHelper->LoadDxilSignatures(*pSignatures, *m_EntrySignature);
  926. LoadDxilResources(*pResources);
  927. m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
  928. m_pMDHelper->LoadRootSignature(*m_RootSignature.get());
  929. m_pMDHelper->LoadDxilViewIdState(*m_pViewIdState.get());
  930. if (loadedModule->IsLib()) {
  931. NamedMDNode *fnProps = m_pModule->getNamedMetadata(
  932. DxilMDHelper::kDxilFunctionPropertiesMDName);
  933. size_t propIdx = 0;
  934. while (propIdx < fnProps->getNumOperands()) {
  935. MDTuple *pProps = dyn_cast<MDTuple>(fnProps->getOperand(propIdx++));
  936. std::unique_ptr<hlsl::DxilFunctionProps> props =
  937. llvm::make_unique<hlsl::DxilFunctionProps>();
  938. Function *F = m_pMDHelper->LoadDxilFunctionProps(pProps, props.get());
  939. if (props->IsHS() && props->ShaderProps.HS.patchConstantFunc) {
  940. // Add patch constant function to m_PatchConstantFunctions
  941. m_PatchConstantFunctions.insert(props->ShaderProps.HS.patchConstantFunc);
  942. }
  943. m_DxilFunctionPropsMap[F] = std::move(props);
  944. }
  945. NamedMDNode *entrySigs = m_pModule->getOrInsertNamedMetadata(
  946. DxilMDHelper::kDxilEntrySignaturesMDName);
  947. size_t sigIdx = 0;
  948. while (sigIdx < entrySigs->getNumOperands()) {
  949. MDTuple *pSig = dyn_cast<MDTuple>(entrySigs->getOperand(sigIdx++));
  950. unsigned idx = 0;
  951. Function *F = dyn_cast<Function>(
  952. dyn_cast<ValueAsMetadata>(pSig->getOperand(idx++))->getValue());
  953. // Entry must have props.
  954. IFTBOOL(m_DxilFunctionPropsMap.count(F), DXC_E_INCORRECT_DXIL_METADATA);
  955. DXIL::ShaderKind shaderKind = m_DxilFunctionPropsMap[F]->shaderKind;
  956. std::unique_ptr<hlsl::DxilEntrySignature> Sig =
  957. llvm::make_unique<hlsl::DxilEntrySignature>(shaderKind, GetUseMinPrecision());
  958. m_pMDHelper->LoadDxilSignatures(pSig->getOperand(idx), *Sig);
  959. m_DxilEntrySignatureMap[F] = std::move(Sig);
  960. }
  961. }
  962. }
  963. MDTuple *DxilModule::EmitDxilResources() {
  964. // Emit SRV records.
  965. MDTuple *pTupleSRVs = nullptr;
  966. if (!m_SRVs.empty()) {
  967. vector<Metadata *> MDVals;
  968. for (size_t i = 0; i < m_SRVs.size(); i++) {
  969. MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
  970. }
  971. pTupleSRVs = MDNode::get(m_Ctx, MDVals);
  972. }
  973. // Emit UAV records.
  974. MDTuple *pTupleUAVs = nullptr;
  975. if (!m_UAVs.empty()) {
  976. vector<Metadata *> MDVals;
  977. for (size_t i = 0; i < m_UAVs.size(); i++) {
  978. MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
  979. }
  980. pTupleUAVs = MDNode::get(m_Ctx, MDVals);
  981. }
  982. // Emit CBuffer records.
  983. MDTuple *pTupleCBuffers = nullptr;
  984. if (!m_CBuffers.empty()) {
  985. vector<Metadata *> MDVals;
  986. for (size_t i = 0; i < m_CBuffers.size(); i++) {
  987. MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
  988. }
  989. pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
  990. }
  991. // Emit Sampler records.
  992. MDTuple *pTupleSamplers = nullptr;
  993. if (!m_Samplers.empty()) {
  994. vector<Metadata *> MDVals;
  995. for (size_t i = 0; i < m_Samplers.size(); i++) {
  996. MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
  997. }
  998. pTupleSamplers = MDNode::get(m_Ctx, MDVals);
  999. }
  1000. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr || pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  1001. return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs, pTupleCBuffers, pTupleSamplers);
  1002. } else {
  1003. return nullptr;
  1004. }
  1005. }
  1006. void DxilModule::ReEmitDxilResources() {
  1007. ClearDxilMetadata(*m_pModule);
  1008. if (!m_pSM->IsCS() && !m_pSM->IsLib())
  1009. m_pViewIdState->Compute();
  1010. EmitDxilMetadata();
  1011. }
  1012. void DxilModule::LoadDxilResources(const llvm::MDOperand &MDO) {
  1013. if (MDO.get() == nullptr)
  1014. return;
  1015. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  1016. m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
  1017. // Load SRV records.
  1018. if (pSRVs != nullptr) {
  1019. for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
  1020. unique_ptr<DxilResource> pSRV(new DxilResource);
  1021. m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
  1022. AddSRV(std::move(pSRV));
  1023. }
  1024. }
  1025. // Load UAV records.
  1026. if (pUAVs != nullptr) {
  1027. for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
  1028. unique_ptr<DxilResource> pUAV(new DxilResource);
  1029. m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
  1030. AddUAV(std::move(pUAV));
  1031. }
  1032. }
  1033. // Load CBuffer records.
  1034. if (pCBuffers != nullptr) {
  1035. for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
  1036. unique_ptr<DxilCBuffer> pCB(new DxilCBuffer);
  1037. m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
  1038. AddCBuffer(std::move(pCB));
  1039. }
  1040. }
  1041. // Load Sampler records.
  1042. if (pSamplers != nullptr) {
  1043. for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
  1044. unique_ptr<DxilSampler> pSampler(new DxilSampler);
  1045. m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
  1046. AddSampler(std::move(pSampler));
  1047. }
  1048. }
  1049. }
  1050. MDTuple *DxilModule::EmitDxilShaderProperties() {
  1051. vector<Metadata *> MDVals;
  1052. // DXIL shader flags.
  1053. uint64_t flag = m_ShaderFlags.GetShaderFlagsRaw();
  1054. if (flag != 0) {
  1055. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilShaderFlagsTag));
  1056. MDVals.emplace_back(m_pMDHelper->Uint64ToConstMD(flag));
  1057. }
  1058. // Compute shader.
  1059. if (m_pSM->IsCS()) {
  1060. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilNumThreadsTag));
  1061. vector<Metadata *> NumThreadVals;
  1062. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[0]));
  1063. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[1]));
  1064. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[2]));
  1065. MDVals.emplace_back(MDNode::get(m_Ctx, NumThreadVals));
  1066. }
  1067. // Geometry shader.
  1068. if (m_pSM->IsGS()) {
  1069. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilGSStateTag));
  1070. MDTuple *pMDTuple = m_pMDHelper->EmitDxilGSState(m_InputPrimitive,
  1071. m_MaxVertexCount,
  1072. GetActiveStreamMask(),
  1073. m_StreamPrimitiveTopology,
  1074. m_NumGSInstances);
  1075. MDVals.emplace_back(pMDTuple);
  1076. }
  1077. // Domain shader.
  1078. if (m_pSM->IsDS()) {
  1079. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilDSStateTag));
  1080. MDTuple *pMDTuple = m_pMDHelper->EmitDxilDSState(m_TessellatorDomain,
  1081. m_InputControlPointCount);
  1082. MDVals.emplace_back(pMDTuple);
  1083. }
  1084. // Hull shader.
  1085. if (m_pSM->IsHS()) {
  1086. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilHSStateTag));
  1087. MDTuple *pMDTuple = m_pMDHelper->EmitDxilHSState(m_pPatchConstantFunc,
  1088. m_InputControlPointCount,
  1089. m_OutputControlPointCount,
  1090. m_TessellatorDomain,
  1091. m_TessellatorPartitioning,
  1092. m_TessellatorOutputPrimitive,
  1093. m_MaxTessellationFactor);
  1094. MDVals.emplace_back(pMDTuple);
  1095. }
  1096. if (!MDVals.empty())
  1097. return MDNode::get(m_Ctx, MDVals);
  1098. else
  1099. return nullptr;
  1100. }
  1101. void DxilModule::LoadDxilShaderProperties(const MDOperand &MDO) {
  1102. if (MDO.get() == nullptr)
  1103. return;
  1104. const MDTuple *pTupleMD = dyn_cast<MDTuple>(MDO.get());
  1105. IFTBOOL(pTupleMD != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  1106. IFTBOOL((pTupleMD->getNumOperands() & 0x1) == 0, DXC_E_INCORRECT_DXIL_METADATA);
  1107. for (unsigned iNode = 0; iNode < pTupleMD->getNumOperands(); iNode += 2) {
  1108. unsigned Tag = DxilMDHelper::ConstMDToUint32(pTupleMD->getOperand(iNode));
  1109. const MDOperand &MDO = pTupleMD->getOperand(iNode + 1);
  1110. IFTBOOL(MDO.get() != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  1111. switch (Tag) {
  1112. case DxilMDHelper::kDxilShaderFlagsTag:
  1113. m_ShaderFlags.SetShaderFlagsRaw(DxilMDHelper::ConstMDToUint64(MDO));
  1114. m_bUseMinPrecision = !m_ShaderFlags.GetUseNativeLowPrecision();
  1115. m_bDisableOptimizations = m_ShaderFlags.GetDisableOptimizations();
  1116. m_bAllResourcesBound = m_ShaderFlags.GetAllResourcesBound();
  1117. break;
  1118. case DxilMDHelper::kDxilNumThreadsTag: {
  1119. MDNode *pNode = cast<MDNode>(MDO.get());
  1120. m_NumThreads[0] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(0));
  1121. m_NumThreads[1] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(1));
  1122. m_NumThreads[2] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(2));
  1123. break;
  1124. }
  1125. case DxilMDHelper::kDxilGSStateTag: {
  1126. m_pMDHelper->LoadDxilGSState(MDO, m_InputPrimitive, m_MaxVertexCount, m_ActiveStreamMask,
  1127. m_StreamPrimitiveTopology, m_NumGSInstances);
  1128. break;
  1129. }
  1130. case DxilMDHelper::kDxilDSStateTag:
  1131. m_pMDHelper->LoadDxilDSState(MDO, m_TessellatorDomain, m_InputControlPointCount);
  1132. break;
  1133. case DxilMDHelper::kDxilHSStateTag:
  1134. m_pMDHelper->LoadDxilHSState(MDO,
  1135. m_pPatchConstantFunc,
  1136. m_InputControlPointCount,
  1137. m_OutputControlPointCount,
  1138. m_TessellatorDomain,
  1139. m_TessellatorPartitioning,
  1140. m_TessellatorOutputPrimitive,
  1141. m_MaxTessellationFactor);
  1142. break;
  1143. default:
  1144. DXASSERT(false, "Unknown extended shader properties tag");
  1145. break;
  1146. }
  1147. }
  1148. }
  1149. void DxilModule::StripDebugRelatedCode() {
  1150. // Remove all users of global resources.
  1151. for (GlobalVariable &GV : m_pModule->globals()) {
  1152. if (GV.hasInternalLinkage())
  1153. continue;
  1154. if (GV.getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace)
  1155. continue;
  1156. for (auto git = GV.user_begin(); git != GV.user_end();) {
  1157. User *U = *(git++);
  1158. // Try to remove load of GV.
  1159. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1160. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1161. Instruction *LIUser = cast<Instruction>(*(it++));
  1162. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1163. Value *Ptr = SI->getPointerOperand();
  1164. SI->eraseFromParent();
  1165. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1166. if (Ptr->user_empty())
  1167. PtrInst->eraseFromParent();
  1168. }
  1169. }
  1170. }
  1171. if (LI->user_empty())
  1172. LI->eraseFromParent();
  1173. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  1174. for (auto GEPIt = GEP->user_begin(); GEPIt != GEP->user_end();) {
  1175. User *GEPU = *(GEPIt++);
  1176. // Try to remove load of GEP.
  1177. if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
  1178. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1179. Instruction *LIUser = cast<Instruction>(*(it++));
  1180. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1181. Value *Ptr = SI->getPointerOperand();
  1182. SI->eraseFromParent();
  1183. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1184. if (Ptr->user_empty())
  1185. PtrInst->eraseFromParent();
  1186. }
  1187. }
  1188. if (LI->user_empty())
  1189. LI->eraseFromParent();
  1190. }
  1191. }
  1192. }
  1193. if (GEP->user_empty())
  1194. GEP->eraseFromParent();
  1195. }
  1196. }
  1197. }
  1198. }
  1199. DebugInfoFinder &DxilModule::GetOrCreateDebugInfoFinder() {
  1200. if (m_pDebugInfoFinder == nullptr) {
  1201. m_pDebugInfoFinder = std::make_unique<llvm::DebugInfoFinder>();
  1202. m_pDebugInfoFinder->processModule(*m_pModule);
  1203. }
  1204. return *m_pDebugInfoFinder;
  1205. }
  1206. hlsl::DxilModule *hlsl::DxilModule::TryGetDxilModule(llvm::Module *pModule) {
  1207. LLVMContext &Ctx = pModule->getContext();
  1208. std::string diagStr;
  1209. raw_string_ostream diagStream(diagStr);
  1210. hlsl::DxilModule *pDxilModule = nullptr;
  1211. // TODO: add detail error in DxilMDHelper.
  1212. try {
  1213. pDxilModule = &pModule->GetOrCreateDxilModule();
  1214. } catch (const ::hlsl::Exception &hlslException) {
  1215. diagStream << "load dxil metadata failed -";
  1216. try {
  1217. const char *msg = hlslException.what();
  1218. if (msg == nullptr || *msg == '\0')
  1219. diagStream << " error code " << hlslException.hr << "\n";
  1220. else
  1221. diagStream << msg;
  1222. } catch (...) {
  1223. diagStream << " unable to retrieve error message.\n";
  1224. }
  1225. Ctx.diagnose(DxilErrorDiagnosticInfo(diagStream.str().c_str()));
  1226. } catch (...) {
  1227. Ctx.diagnose(DxilErrorDiagnosticInfo("load dxil metadata failed - unknown error.\n"));
  1228. }
  1229. return pDxilModule;
  1230. }
  1231. // Check if the instruction has fast math flags configured to indicate
  1232. // the instruction is precise.
  1233. // Precise fast math flags means none of the fast math flags are set.
  1234. bool DxilModule::HasPreciseFastMathFlags(const Instruction *inst) {
  1235. return isa<FPMathOperator>(inst) && !inst->getFastMathFlags().any();
  1236. }
  1237. // Set fast math flags configured to indicate the instruction is precise.
  1238. void DxilModule::SetPreciseFastMathFlags(llvm::Instruction *inst) {
  1239. assert(isa<FPMathOperator>(inst));
  1240. inst->copyFastMathFlags(FastMathFlags());
  1241. }
  1242. // True if fast math flags are preserved across serialization/deserialization
  1243. // of the dxil module.
  1244. //
  1245. // We need to check for this when querying fast math flags for preciseness
  1246. // otherwise we will be overly conservative by reporting instructions precise
  1247. // because their fast math flags were not preserved.
  1248. //
  1249. // Currently we restrict it to the instruction types that have fast math
  1250. // preserved in the bitcode. We can expand this by converting fast math
  1251. // flags to dx.precise metadata during serialization and back to fast
  1252. // math flags during deserialization.
  1253. bool DxilModule::PreservesFastMathFlags(const llvm::Instruction *inst) {
  1254. return
  1255. isa<FPMathOperator>(inst) && (isa<BinaryOperator>(inst) || isa<FCmpInst>(inst));
  1256. }
  1257. bool DxilModule::IsPrecise(const Instruction *inst) const {
  1258. if (m_ShaderFlags.GetDisableMathRefactoring())
  1259. return true;
  1260. else if (DxilMDHelper::IsMarkedPrecise(inst))
  1261. return true;
  1262. else if (PreservesFastMathFlags(inst))
  1263. return HasPreciseFastMathFlags(inst);
  1264. else
  1265. return false;
  1266. }
  1267. } // namespace hlsl
  1268. namespace llvm {
  1269. hlsl::DxilModule &Module::GetOrCreateDxilModule(bool skipInit) {
  1270. std::unique_ptr<hlsl::DxilModule> M;
  1271. if (!HasDxilModule()) {
  1272. M = std::make_unique<hlsl::DxilModule>(this);
  1273. if (!skipInit) {
  1274. M->LoadDxilMetadata();
  1275. }
  1276. SetDxilModule(M.release());
  1277. }
  1278. return GetDxilModule();
  1279. }
  1280. void Module::ResetDxilModule() {
  1281. if (HasDxilModule()) {
  1282. delete TheDxilModule;
  1283. TheDxilModule = nullptr;
  1284. }
  1285. }
  1286. }