DxilModule.cpp 54 KB

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