DxilModule.cpp 70 KB

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