DxilModule.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024
  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.clear();
  1162. m_SerializedRootSignature.reserve(Value.size());
  1163. m_SerializedRootSignature.assign(Value.begin(), Value.end());
  1164. }
  1165. DxilTypeSystem &DxilModule::GetTypeSystem() {
  1166. return *m_pTypeSystem;
  1167. }
  1168. const DxilTypeSystem &DxilModule::GetTypeSystem() const {
  1169. return *m_pTypeSystem;
  1170. }
  1171. std::vector<unsigned> &DxilModule::GetSerializedViewIdState() {
  1172. return m_SerializedState;
  1173. }
  1174. const std::vector<unsigned> &DxilModule::GetSerializedViewIdState() const {
  1175. return m_SerializedState;
  1176. }
  1177. void DxilModule::ResetTypeSystem(DxilTypeSystem *pValue) {
  1178. m_pTypeSystem.reset(pValue);
  1179. }
  1180. void DxilModule::ResetOP(hlsl::OP *hlslOP) { m_pOP.reset(hlslOP); }
  1181. void DxilModule::ResetEntryPropsMap(DxilEntryPropsMap &&PropMap) {
  1182. m_DxilEntryPropsMap.clear();
  1183. std::move(PropMap.begin(), PropMap.end(),
  1184. inserter(m_DxilEntryPropsMap, m_DxilEntryPropsMap.begin()));
  1185. }
  1186. static const StringRef llvmUsedName = "llvm.used";
  1187. void DxilModule::EmitLLVMUsed() {
  1188. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  1189. oldGV->eraseFromParent();
  1190. }
  1191. if (m_LLVMUsed.empty())
  1192. return;
  1193. vector<llvm::Constant *> GVs;
  1194. Type *pI8PtrType = Type::getInt8PtrTy(m_Ctx, DXIL::kDefaultAddrSpace);
  1195. GVs.resize(m_LLVMUsed.size());
  1196. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  1197. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  1198. PointerType *pPtrType = dyn_cast<PointerType>(pConst->getType());
  1199. if (pPtrType->getPointerAddressSpace() != DXIL::kDefaultAddrSpace) {
  1200. // Cast pointer to addrspace 0, as LLVMUsed elements must have the same
  1201. // type.
  1202. GVs[i] = ConstantExpr::getAddrSpaceCast(pConst, pI8PtrType);
  1203. } else {
  1204. GVs[i] = ConstantExpr::getPointerCast(pConst, pI8PtrType);
  1205. }
  1206. }
  1207. ArrayType *pATy = ArrayType::get(pI8PtrType, GVs.size());
  1208. GlobalVariable *pGV =
  1209. new GlobalVariable(*m_pModule, pATy, false, GlobalValue::AppendingLinkage,
  1210. ConstantArray::get(pATy, GVs), llvmUsedName);
  1211. pGV->setSection("llvm.metadata");
  1212. }
  1213. void DxilModule::ClearLLVMUsed() {
  1214. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  1215. oldGV->eraseFromParent();
  1216. }
  1217. if (m_LLVMUsed.empty())
  1218. return;
  1219. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  1220. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  1221. pConst->removeDeadConstantUsers();
  1222. }
  1223. m_LLVMUsed.clear();
  1224. }
  1225. vector<GlobalVariable* > &DxilModule::GetLLVMUsed() {
  1226. return m_LLVMUsed;
  1227. }
  1228. // DXIL metadata serialization/deserialization.
  1229. void DxilModule::ClearDxilMetadata(Module &M) {
  1230. // Delete: DXIL version, validator version, DXIL shader model,
  1231. // entry point tuples (shader properties, signatures, resources)
  1232. // type system, view ID state, LLVM used, entry point tuples,
  1233. // root signature, function properties.
  1234. // Other cases for libs pending.
  1235. // LLVM used is a global variable - handle separately.
  1236. SmallVector<NamedMDNode*, 8> nodes;
  1237. for (NamedMDNode &b : M.named_metadata()) {
  1238. StringRef name = b.getName();
  1239. if (name == DxilMDHelper::kDxilVersionMDName ||
  1240. name == DxilMDHelper::kDxilValidatorVersionMDName ||
  1241. name == DxilMDHelper::kDxilShaderModelMDName ||
  1242. name == DxilMDHelper::kDxilEntryPointsMDName ||
  1243. name == DxilMDHelper::kDxilRootSignatureMDName ||
  1244. name == DxilMDHelper::kDxilIntermediateOptionsMDName ||
  1245. name == DxilMDHelper::kDxilResourcesMDName ||
  1246. name == DxilMDHelper::kDxilTypeSystemMDName ||
  1247. name == DxilMDHelper::kDxilViewIdStateMDName ||
  1248. name == DxilMDHelper::kDxilSubobjectsMDName ||
  1249. name == DxilMDHelper::kDxilCountersMDName ||
  1250. name.startswith(DxilMDHelper::kDxilTypeSystemHelperVariablePrefix)) {
  1251. nodes.push_back(&b);
  1252. }
  1253. }
  1254. for (size_t i = 0; i < nodes.size(); ++i) {
  1255. M.eraseNamedMetadata(nodes[i]);
  1256. }
  1257. }
  1258. void DxilModule::EmitDxilMetadata() {
  1259. m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
  1260. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  1261. m_pMDHelper->EmitDxilShaderModel(m_pSM);
  1262. m_pMDHelper->EmitDxilIntermediateOptions(m_IntermediateFlags);
  1263. MDTuple *pMDProperties = nullptr;
  1264. uint64_t flag = m_ShaderFlags.GetShaderFlagsRaw();
  1265. if (m_pSM->IsLib()) {
  1266. DxilFunctionProps props;
  1267. props.shaderKind = DXIL::ShaderKind::Library;
  1268. pMDProperties = m_pMDHelper->EmitDxilEntryProperties(flag, props,
  1269. GetAutoBindingSpace());
  1270. } else {
  1271. pMDProperties = m_pMDHelper->EmitDxilEntryProperties(
  1272. flag, m_DxilEntryPropsMap.begin()->second->props,
  1273. GetAutoBindingSpace());
  1274. }
  1275. MDTuple *pMDSignatures = nullptr;
  1276. if (!m_pSM->IsLib()) {
  1277. pMDSignatures = m_pMDHelper->EmitDxilSignatures(
  1278. m_DxilEntryPropsMap.begin()->second->sig);
  1279. }
  1280. MDTuple *pMDResources = EmitDxilResources();
  1281. if (pMDResources)
  1282. m_pMDHelper->EmitDxilResources(pMDResources);
  1283. m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
  1284. if (!m_pSM->IsLib() && !m_pSM->IsCS() &&
  1285. ((m_ValMajor == 0 && m_ValMinor == 0) ||
  1286. (m_ValMajor > 1 || (m_ValMajor == 1 && m_ValMinor >= 1)))) {
  1287. m_pMDHelper->EmitDxilViewIdState(m_SerializedState);
  1288. }
  1289. // Emit the DXR Payload Annotations only for library Dxil 1.6 and above.
  1290. if (m_pSM->IsLib()) {
  1291. if (DXIL::CompareVersions(m_DxilMajor, m_DxilMinor, 1, 6) >= 0) {
  1292. m_pMDHelper->EmitDxrPayloadAnnotations(GetTypeSystem());
  1293. }
  1294. }
  1295. EmitLLVMUsed();
  1296. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources, pMDProperties);
  1297. vector<MDNode *> Entries;
  1298. Entries.emplace_back(pEntry);
  1299. if (m_pSM->IsLib()) {
  1300. // Sort functions by name to keep metadata deterministic
  1301. vector<const Function *> funcOrder;
  1302. funcOrder.reserve(m_DxilEntryPropsMap.size());
  1303. std::transform( m_DxilEntryPropsMap.begin(),
  1304. m_DxilEntryPropsMap.end(),
  1305. std::back_inserter(funcOrder),
  1306. [](const std::pair<const llvm::Function * const, std::unique_ptr<DxilEntryProps>> &p) -> const Function* { return p.first; } );
  1307. std::sort(funcOrder.begin(), funcOrder.end(), [](const Function *F1, const Function *F2) {
  1308. return F1->getName() < F2->getName();
  1309. });
  1310. for (auto F : funcOrder) {
  1311. auto &entryProps = m_DxilEntryPropsMap[F];
  1312. MDTuple *pProps = m_pMDHelper->EmitDxilEntryProperties(0, entryProps->props, 0);
  1313. MDTuple *pSig = m_pMDHelper->EmitDxilSignatures(entryProps->sig);
  1314. MDTuple *pSubEntry = m_pMDHelper->EmitDxilEntryPointTuple(
  1315. const_cast<Function *>(F), F->getName(), pSig, nullptr, pProps);
  1316. Entries.emplace_back(pSubEntry);
  1317. }
  1318. funcOrder.clear();
  1319. // Save Subobjects
  1320. if (GetSubobjects()) {
  1321. m_pMDHelper->EmitSubobjects(*GetSubobjects());
  1322. }
  1323. }
  1324. m_pMDHelper->EmitDxilEntryPoints(Entries);
  1325. if (!m_SerializedRootSignature.empty()) {
  1326. m_pMDHelper->EmitRootSignature(m_SerializedRootSignature);
  1327. }
  1328. }
  1329. bool DxilModule::IsKnownNamedMetaData(llvm::NamedMDNode &Node) {
  1330. return DxilMDHelper::IsKnownNamedMetaData(Node);
  1331. }
  1332. bool DxilModule::HasMetadataErrors() {
  1333. return m_bMetadataErrors;
  1334. }
  1335. void DxilModule::LoadDxilMetadata() {
  1336. m_bMetadataErrors = false;
  1337. m_pMDHelper->LoadValidatorVersion(m_ValMajor, m_ValMinor);
  1338. const ShaderModel *loadedSM;
  1339. m_pMDHelper->LoadDxilShaderModel(loadedSM);
  1340. m_pMDHelper->LoadDxilIntermediateOptions(m_IntermediateFlags);
  1341. // This must be set before LoadDxilEntryProperties
  1342. m_pMDHelper->SetShaderModel(loadedSM);
  1343. // Setting module shader model requires UseMinPrecision flag,
  1344. // which requires loading m_ShaderFlags,
  1345. // which requires global entry properties,
  1346. // so load entry properties first, then set the shader model
  1347. const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
  1348. if (!loadedSM->IsLib()) {
  1349. IFTBOOL(pEntries->getNumOperands() == 1, DXC_E_INCORRECT_DXIL_METADATA);
  1350. }
  1351. Function *pEntryFunc;
  1352. string EntryName;
  1353. const llvm::MDOperand *pEntrySignatures, *pEntryResources, *pEntryProperties;
  1354. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0),
  1355. pEntryFunc, EntryName,
  1356. pEntrySignatures, pEntryResources,
  1357. pEntryProperties);
  1358. uint64_t rawShaderFlags = 0;
  1359. DxilFunctionProps entryFuncProps;
  1360. entryFuncProps.shaderKind = loadedSM->GetKind();
  1361. m_pMDHelper->LoadDxilEntryProperties(*pEntryProperties, rawShaderFlags,
  1362. entryFuncProps, m_AutoBindingSpace);
  1363. m_bUseMinPrecision = true;
  1364. if (rawShaderFlags) {
  1365. m_ShaderFlags.SetShaderFlagsRaw(rawShaderFlags);
  1366. m_bUseMinPrecision = !m_ShaderFlags.GetUseNativeLowPrecision();
  1367. m_bDisableOptimizations = m_ShaderFlags.GetDisableOptimizations();
  1368. m_bAllResourcesBound = m_ShaderFlags.GetAllResourcesBound();
  1369. }
  1370. // Now that we have the UseMinPrecision flag, set shader model:
  1371. SetShaderModel(loadedSM, m_bUseMinPrecision);
  1372. // SetShaderModel will initialize m_DxilMajor/m_DxilMinor to min for SM,
  1373. // so, load here after shader model so it matches the metadata.
  1374. m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
  1375. if (loadedSM->IsLib()) {
  1376. for (unsigned i = 1; i < pEntries->getNumOperands(); i++) {
  1377. Function *pFunc;
  1378. string Name;
  1379. const llvm::MDOperand *pSignatures, *pResources, *pProperties;
  1380. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(i), pFunc, Name,
  1381. pSignatures, pResources, pProperties);
  1382. DxilFunctionProps props;
  1383. uint64_t rawShaderFlags = 0;
  1384. unsigned autoBindingSpace = 0;
  1385. m_pMDHelper->LoadDxilEntryProperties(
  1386. *pProperties, rawShaderFlags, props, autoBindingSpace);
  1387. if (props.IsHS() && props.ShaderProps.HS.patchConstantFunc) {
  1388. // Add patch constant function to m_PatchConstantFunctions
  1389. m_PatchConstantFunctions.insert(props.ShaderProps.HS.patchConstantFunc);
  1390. }
  1391. std::unique_ptr<DxilEntryProps> pEntryProps =
  1392. llvm::make_unique<DxilEntryProps>(props, m_bUseMinPrecision);
  1393. m_pMDHelper->LoadDxilSignatures(*pSignatures, pEntryProps->sig);
  1394. m_DxilEntryPropsMap[pFunc] = std::move(pEntryProps);
  1395. }
  1396. // Load Subobjects
  1397. std::unique_ptr<DxilSubobjects> pSubobjects(new DxilSubobjects());
  1398. m_pMDHelper->LoadSubobjects(*pSubobjects);
  1399. if (pSubobjects->GetSubobjects().size()) {
  1400. ResetSubobjects(pSubobjects.release());
  1401. }
  1402. } else {
  1403. std::unique_ptr<DxilEntryProps> pEntryProps =
  1404. llvm::make_unique<DxilEntryProps>(entryFuncProps, m_bUseMinPrecision);
  1405. DxilFunctionProps *pFuncProps = &pEntryProps->props;
  1406. m_pMDHelper->LoadDxilSignatures(*pEntrySignatures, pEntryProps->sig);
  1407. m_DxilEntryPropsMap.clear();
  1408. m_DxilEntryPropsMap[pEntryFunc] = std::move(pEntryProps);
  1409. SetEntryFunction(pEntryFunc);
  1410. SetEntryFunctionName(EntryName);
  1411. SetShaderProperties(pFuncProps);
  1412. }
  1413. LoadDxilResources(*pEntryResources);
  1414. // Type system is not required for consumption of dxil.
  1415. try {
  1416. m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
  1417. } catch (hlsl::Exception &) {
  1418. m_bMetadataErrors = true;
  1419. #ifdef DBG
  1420. throw;
  1421. #endif
  1422. m_pTypeSystem->GetStructAnnotationMap().clear();
  1423. m_pTypeSystem->GetFunctionAnnotationMap().clear();
  1424. }
  1425. // Payload annotations not required for consumption of dxil.
  1426. try {
  1427. m_pMDHelper->LoadDxrPayloadAnnotations(*m_pTypeSystem.get());
  1428. } catch (hlsl::Exception &) {
  1429. m_bMetadataErrors = true;
  1430. #ifdef DBG
  1431. throw;
  1432. #endif
  1433. m_pTypeSystem->GetPayloadAnnotationMap().clear();
  1434. }
  1435. m_pMDHelper->LoadRootSignature(m_SerializedRootSignature);
  1436. m_pMDHelper->LoadDxilViewIdState(m_SerializedState);
  1437. m_bMetadataErrors |= m_pMDHelper->HasExtraMetadata();
  1438. }
  1439. MDTuple *DxilModule::EmitDxilResources() {
  1440. // Emit SRV records.
  1441. MDTuple *pTupleSRVs = nullptr;
  1442. if (!m_SRVs.empty()) {
  1443. vector<Metadata *> MDVals;
  1444. for (size_t i = 0; i < m_SRVs.size(); i++) {
  1445. MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
  1446. }
  1447. pTupleSRVs = MDNode::get(m_Ctx, MDVals);
  1448. }
  1449. // Emit UAV records.
  1450. MDTuple *pTupleUAVs = nullptr;
  1451. if (!m_UAVs.empty()) {
  1452. vector<Metadata *> MDVals;
  1453. for (size_t i = 0; i < m_UAVs.size(); i++) {
  1454. MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
  1455. }
  1456. pTupleUAVs = MDNode::get(m_Ctx, MDVals);
  1457. }
  1458. // Emit CBuffer records.
  1459. MDTuple *pTupleCBuffers = nullptr;
  1460. if (!m_CBuffers.empty()) {
  1461. vector<Metadata *> MDVals;
  1462. for (size_t i = 0; i < m_CBuffers.size(); i++) {
  1463. MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
  1464. }
  1465. pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
  1466. }
  1467. // Emit Sampler records.
  1468. MDTuple *pTupleSamplers = nullptr;
  1469. if (!m_Samplers.empty()) {
  1470. vector<Metadata *> MDVals;
  1471. for (size_t i = 0; i < m_Samplers.size(); i++) {
  1472. MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
  1473. }
  1474. pTupleSamplers = MDNode::get(m_Ctx, MDVals);
  1475. }
  1476. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr || pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  1477. return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs, pTupleCBuffers, pTupleSamplers);
  1478. } else {
  1479. return nullptr;
  1480. }
  1481. }
  1482. void DxilModule::ReEmitDxilResources() {
  1483. ClearDxilMetadata(*m_pModule);
  1484. EmitDxilMetadata();
  1485. }
  1486. void DxilModule::EmitDxilCounters() {
  1487. DxilCounters counters = {};
  1488. hlsl::CountInstructions(*m_pModule, counters);
  1489. m_pMDHelper->EmitDxilCounters(counters);
  1490. }
  1491. void DxilModule::LoadDxilCounters(DxilCounters &counters) const {
  1492. m_pMDHelper->LoadDxilCounters(counters);
  1493. }
  1494. template <typename TResource>
  1495. static bool
  1496. StripResourcesReflection(std::vector<std::unique_ptr<TResource>> &vec) {
  1497. bool bChanged = false;
  1498. for (auto &p : vec) {
  1499. p->SetGlobalName("");
  1500. // Cannot remove global symbol which used by validation.
  1501. bChanged = true;
  1502. }
  1503. return bChanged;
  1504. }
  1505. // Return true if any members or components of struct <Ty> contain
  1506. // scalars of less than 32 bits or are matrices, in which case translation is required
  1507. typedef llvm::SmallSetVector<const StructType*, 4> SmallStructSetVector;
  1508. static bool ResourceTypeRequiresTranslation(const StructType * Ty, SmallStructSetVector & containedStructs) {
  1509. if (Ty->getName().startswith("class.matrix."))
  1510. return true;
  1511. bool bResult = false;
  1512. containedStructs.insert(Ty);
  1513. for (auto eTy : Ty->elements()) {
  1514. // Skip past all levels of sequential types to test their elements
  1515. SequentialType *seqTy;
  1516. while ((seqTy = dyn_cast<SequentialType>(eTy))) {
  1517. eTy = seqTy->getElementType();
  1518. }
  1519. // Recursively call this function again to process internal structs
  1520. if (StructType *structTy = dyn_cast<StructType>(eTy)) {
  1521. if (ResourceTypeRequiresTranslation(structTy, containedStructs))
  1522. bResult = true;
  1523. } else if (eTy->getScalarSizeInBits() < 32) { // test scalar sizes
  1524. bResult = true;
  1525. }
  1526. }
  1527. return bResult;
  1528. }
  1529. bool DxilModule::StripReflection() {
  1530. bool bChanged = false;
  1531. bool bIsLib = GetShaderModel()->IsLib();
  1532. // Remove names.
  1533. for (Function &F : m_pModule->functions()) {
  1534. for (BasicBlock &BB : F) {
  1535. if (BB.hasName()) {
  1536. BB.setName("");
  1537. bChanged = true;
  1538. }
  1539. for (Instruction &I : BB) {
  1540. if (I.hasName()) {
  1541. I.setName("");
  1542. bChanged = true;
  1543. }
  1544. }
  1545. }
  1546. }
  1547. if (bIsLib && GetUseMinPrecision())
  1548. {
  1549. // We must preserve struct annotations for resources containing min-precision types,
  1550. // since they have not yet been converted for legacy layout.
  1551. // Keep all structs contained in any we must keep.
  1552. SmallStructSetVector structsToKeep;
  1553. SmallStructSetVector structsToRemove;
  1554. for (auto &item : m_pTypeSystem->GetStructAnnotationMap()) {
  1555. SmallStructSetVector containedStructs;
  1556. if (!ResourceTypeRequiresTranslation(item.first, containedStructs))
  1557. structsToRemove.insert(item.first);
  1558. else
  1559. structsToKeep.insert(containedStructs.begin(), containedStructs.end());
  1560. }
  1561. for (auto Ty : structsToKeep)
  1562. structsToRemove.remove(Ty);
  1563. for (auto Ty : structsToRemove) {
  1564. m_pTypeSystem->GetStructAnnotationMap().erase(Ty);
  1565. }
  1566. } else {
  1567. // Remove struct annotations.
  1568. if (!m_pTypeSystem->GetStructAnnotationMap().empty()) {
  1569. m_pTypeSystem->GetStructAnnotationMap().clear();
  1570. bChanged = true;
  1571. }
  1572. if (DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 5) >= 0) {
  1573. // Remove function annotations.
  1574. if (!m_pTypeSystem->GetFunctionAnnotationMap().empty()) {
  1575. m_pTypeSystem->GetFunctionAnnotationMap().clear();
  1576. bChanged = true;
  1577. }
  1578. }
  1579. }
  1580. // Resource
  1581. if (!bIsLib) {
  1582. bChanged |= StripResourcesReflection(m_CBuffers);
  1583. bChanged |= StripResourcesReflection(m_UAVs);
  1584. bChanged |= StripResourcesReflection(m_SRVs);
  1585. bChanged |= StripResourcesReflection(m_Samplers);
  1586. }
  1587. // Unused global.
  1588. SmallVector<GlobalVariable *,2> UnusedGlobals;
  1589. for (GlobalVariable &GV : m_pModule->globals()) {
  1590. if (GV.use_empty()) {
  1591. // Need to preserve this global, otherwise we drop constructors
  1592. // for static globals.
  1593. if (!bIsLib || GV.getName().compare("llvm.global_ctors") != 0)
  1594. UnusedGlobals.emplace_back(&GV);
  1595. }
  1596. }
  1597. bChanged |= !UnusedGlobals.empty();
  1598. for (GlobalVariable *GV : UnusedGlobals) {
  1599. GV->eraseFromParent();
  1600. }
  1601. // ReEmit meta.
  1602. if (bChanged)
  1603. ReEmitDxilResources();
  1604. return bChanged;
  1605. }
  1606. void DxilModule::LoadDxilResources(const llvm::MDOperand &MDO) {
  1607. if (MDO.get() == nullptr)
  1608. return;
  1609. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  1610. m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
  1611. // Load SRV records.
  1612. if (pSRVs != nullptr) {
  1613. for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
  1614. unique_ptr<DxilResource> pSRV(new DxilResource);
  1615. m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
  1616. AddSRV(std::move(pSRV));
  1617. }
  1618. }
  1619. // Load UAV records.
  1620. if (pUAVs != nullptr) {
  1621. for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
  1622. unique_ptr<DxilResource> pUAV(new DxilResource);
  1623. m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
  1624. AddUAV(std::move(pUAV));
  1625. }
  1626. }
  1627. // Load CBuffer records.
  1628. if (pCBuffers != nullptr) {
  1629. for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
  1630. unique_ptr<DxilCBuffer> pCB(new DxilCBuffer);
  1631. m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
  1632. AddCBuffer(std::move(pCB));
  1633. }
  1634. }
  1635. // Load Sampler records.
  1636. if (pSamplers != nullptr) {
  1637. for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
  1638. unique_ptr<DxilSampler> pSampler(new DxilSampler);
  1639. m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
  1640. AddSampler(std::move(pSampler));
  1641. }
  1642. }
  1643. }
  1644. void DxilModule::StripShaderSourcesAndCompileOptions(bool bReplaceWithDummyData) {
  1645. // Remove dx.source metadata.
  1646. if (NamedMDNode *contents = m_pModule->getNamedMetadata(
  1647. DxilMDHelper::kDxilSourceContentsMDName)) {
  1648. contents->eraseFromParent();
  1649. if (bReplaceWithDummyData) {
  1650. // Insert an empty source and content
  1651. llvm::LLVMContext &context = m_pModule->getContext();
  1652. llvm::NamedMDNode *newNamedMD = m_pModule->getOrInsertNamedMetadata(DxilMDHelper::kDxilSourceContentsMDName);
  1653. llvm::Metadata *operands[2] = { llvm::MDString::get(context, ""), llvm::MDString::get(context, "") };
  1654. newNamedMD->addOperand(llvm::MDTuple::get(context, operands));
  1655. }
  1656. }
  1657. if (NamedMDNode *defines =
  1658. m_pModule->getNamedMetadata(DxilMDHelper::kDxilSourceDefinesMDName)) {
  1659. defines->eraseFromParent();
  1660. if (bReplaceWithDummyData) {
  1661. llvm::LLVMContext &context = m_pModule->getContext();
  1662. llvm::NamedMDNode *newNamedMD = m_pModule->getOrInsertNamedMetadata(DxilMDHelper::kDxilSourceDefinesMDName);
  1663. newNamedMD->addOperand(llvm::MDTuple::get(context, llvm::ArrayRef<llvm::Metadata *>()));
  1664. }
  1665. }
  1666. if (NamedMDNode *mainFileName = m_pModule->getNamedMetadata(
  1667. DxilMDHelper::kDxilSourceMainFileNameMDName)) {
  1668. mainFileName->eraseFromParent();
  1669. if (bReplaceWithDummyData) {
  1670. // Insert an empty file name
  1671. llvm::LLVMContext &context = m_pModule->getContext();
  1672. llvm::NamedMDNode *newNamedMD = m_pModule->getOrInsertNamedMetadata(DxilMDHelper::kDxilSourceMainFileNameMDName);
  1673. llvm::Metadata *operands[1] = { llvm::MDString::get(context, "") };
  1674. newNamedMD->addOperand(llvm::MDTuple::get(context, operands));
  1675. }
  1676. }
  1677. if (NamedMDNode *arguments =
  1678. m_pModule->getNamedMetadata(DxilMDHelper::kDxilSourceArgsMDName)) {
  1679. arguments->eraseFromParent();
  1680. if (bReplaceWithDummyData) {
  1681. llvm::LLVMContext &context = m_pModule->getContext();
  1682. llvm::NamedMDNode *newNamedMD = m_pModule->getOrInsertNamedMetadata(DxilMDHelper::kDxilSourceArgsMDName);
  1683. newNamedMD->addOperand(llvm::MDTuple::get(context, llvm::ArrayRef<llvm::Metadata *>()));
  1684. }
  1685. }
  1686. }
  1687. void DxilModule::StripDebugRelatedCode() {
  1688. StripShaderSourcesAndCompileOptions();
  1689. if (NamedMDNode *flags = m_pModule->getModuleFlagsMetadata()) {
  1690. SmallVector<llvm::Module::ModuleFlagEntry, 4> flagEntries;
  1691. m_pModule->getModuleFlagsMetadata(flagEntries);
  1692. flags->eraseFromParent();
  1693. for (unsigned i = 0; i < flagEntries.size(); i++) {
  1694. llvm::Module::ModuleFlagEntry &entry = flagEntries[i];
  1695. if (entry.Key->getString() == "Dwarf Version" || entry.Key->getString() == "Debug Info Version") {
  1696. continue;
  1697. }
  1698. m_pModule->addModuleFlag(
  1699. entry.Behavior, entry.Key->getString(),
  1700. cast<ConstantAsMetadata>(entry.Val)->getValue());
  1701. }
  1702. }
  1703. }
  1704. DebugInfoFinder &DxilModule::GetOrCreateDebugInfoFinder() {
  1705. if (m_pDebugInfoFinder == nullptr) {
  1706. m_pDebugInfoFinder = llvm::make_unique<llvm::DebugInfoFinder>();
  1707. m_pDebugInfoFinder->processModule(*m_pModule);
  1708. }
  1709. return *m_pDebugInfoFinder;
  1710. }
  1711. hlsl::DxilModule *hlsl::DxilModule::TryGetDxilModule(llvm::Module *pModule) {
  1712. LLVMContext &Ctx = pModule->getContext();
  1713. std::string diagStr;
  1714. raw_string_ostream diagStream(diagStr);
  1715. hlsl::DxilModule *pDxilModule = nullptr;
  1716. // TODO: add detail error in DxilMDHelper.
  1717. try {
  1718. pDxilModule = &pModule->GetOrCreateDxilModule();
  1719. } catch (const ::hlsl::Exception &hlslException) {
  1720. diagStream << "load dxil metadata failed -";
  1721. try {
  1722. const char *msg = hlslException.what();
  1723. if (msg == nullptr || *msg == '\0')
  1724. diagStream << " error code " << hlslException.hr << "\n";
  1725. else
  1726. diagStream << msg;
  1727. } catch (...) {
  1728. diagStream << " unable to retrieve error message.\n";
  1729. }
  1730. Ctx.diagnose(DxilErrorDiagnosticInfo(diagStream.str().c_str()));
  1731. } catch (...) {
  1732. Ctx.diagnose(DxilErrorDiagnosticInfo("load dxil metadata failed - unknown error.\n"));
  1733. }
  1734. return pDxilModule;
  1735. }
  1736. // Check if the instruction has fast math flags configured to indicate
  1737. // the instruction is precise.
  1738. // Precise fast math flags means none of the fast math flags are set.
  1739. bool DxilModule::HasPreciseFastMathFlags(const Instruction *inst) {
  1740. return isa<FPMathOperator>(inst) && !inst->getFastMathFlags().any();
  1741. }
  1742. // Set fast math flags configured to indicate the instruction is precise.
  1743. void DxilModule::SetPreciseFastMathFlags(llvm::Instruction *inst) {
  1744. assert(isa<FPMathOperator>(inst));
  1745. inst->copyFastMathFlags(FastMathFlags());
  1746. }
  1747. // True if fast math flags are preserved across serialization/deserialization
  1748. // of the dxil module.
  1749. //
  1750. // We need to check for this when querying fast math flags for preciseness
  1751. // otherwise we will be overly conservative by reporting instructions precise
  1752. // because their fast math flags were not preserved.
  1753. //
  1754. // Currently we restrict it to the instruction types that have fast math
  1755. // preserved in the bitcode. We can expand this by converting fast math
  1756. // flags to dx.precise metadata during serialization and back to fast
  1757. // math flags during deserialization.
  1758. bool DxilModule::PreservesFastMathFlags(const llvm::Instruction *inst) {
  1759. return
  1760. isa<FPMathOperator>(inst) && (isa<BinaryOperator>(inst) || isa<FCmpInst>(inst));
  1761. }
  1762. bool DxilModule::IsPrecise(const Instruction *inst) const {
  1763. if (m_ShaderFlags.GetDisableMathRefactoring())
  1764. return true;
  1765. else if (DxilMDHelper::IsMarkedPrecise(inst))
  1766. return true;
  1767. else if (PreservesFastMathFlags(inst))
  1768. return HasPreciseFastMathFlags(inst);
  1769. else
  1770. return false;
  1771. }
  1772. } // namespace hlsl
  1773. namespace llvm {
  1774. hlsl::DxilModule &Module::GetOrCreateDxilModule(bool skipInit) {
  1775. std::unique_ptr<hlsl::DxilModule> M;
  1776. if (!HasDxilModule()) {
  1777. M = llvm::make_unique<hlsl::DxilModule>(this);
  1778. if (!skipInit) {
  1779. M->LoadDxilMetadata();
  1780. }
  1781. SetDxilModule(M.release());
  1782. }
  1783. return GetDxilModule();
  1784. }
  1785. }