2
0

DxilModule.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilModule.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. ///////////////////////////////////////////////////////////////////////////////
  9. #include "dxc/Support/Global.h"
  10. #include "dxc/HLSL/DxilOperations.h"
  11. #include "dxc/HLSL/DxilModule.h"
  12. #include "dxc/HLSL/DxilShaderModel.h"
  13. #include "dxc/HLSL/DxilSignatureElement.h"
  14. #include "dxc/HLSL/DxilContainer.h"
  15. #include "dxc/HLSL/DxilRootSignature.h"
  16. #include "dxc/HLSL/DxilFunctionProps.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/LLVMContext.h"
  21. #include "llvm/IR/Metadata.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/IR/Operator.h"
  24. #include "llvm/IR/DebugInfo.h"
  25. #include "llvm/IR/DiagnosticInfo.h"
  26. #include "llvm/IR/DiagnosticPrinter.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <unordered_set>
  29. using namespace llvm;
  30. using std::string;
  31. using std::vector;
  32. using std::unique_ptr;
  33. namespace {
  34. class DxilErrorDiagnosticInfo : public DiagnosticInfo {
  35. private:
  36. const char *m_message;
  37. public:
  38. DxilErrorDiagnosticInfo(const char *str)
  39. : DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
  40. m_message(str) { }
  41. __override void print(DiagnosticPrinter &DP) const {
  42. DP << m_message;
  43. }
  44. };
  45. } // anon namespace
  46. namespace hlsl {
  47. //------------------------------------------------------------------------------
  48. //
  49. // DxilModule methods.
  50. //
  51. DxilModule::DxilModule(Module *pModule)
  52. : m_Ctx(pModule->getContext())
  53. , m_pModule(pModule)
  54. , m_pOP(std::make_unique<OP>(pModule->getContext(), pModule))
  55. , m_pTypeSystem(std::make_unique<DxilTypeSystem>(pModule))
  56. , m_pViewIdState(std::make_unique<DxilViewIdState>(this))
  57. , m_pMDHelper(std::make_unique<DxilMDHelper>(pModule, std::make_unique<DxilExtraPropertyHelper>(pModule)))
  58. , m_pDebugInfoFinder(nullptr)
  59. , m_pEntryFunc(nullptr)
  60. , m_EntryName("")
  61. , m_pPatchConstantFunc(nullptr)
  62. , m_pSM(nullptr)
  63. , m_DxilMajor(DXIL::kDxilMajor)
  64. , m_DxilMinor(DXIL::kDxilMinor)
  65. , m_ValMajor(1)
  66. , m_ValMinor(0)
  67. , m_InputPrimitive(DXIL::InputPrimitive::Undefined)
  68. , m_MaxVertexCount(0)
  69. , m_StreamPrimitiveTopology(DXIL::PrimitiveTopology::Undefined)
  70. , m_ActiveStreamMask(0)
  71. , m_NumGSInstances(1)
  72. , m_InputControlPointCount(0)
  73. , m_TessellatorDomain(DXIL::TessellatorDomain::Undefined)
  74. , m_OutputControlPointCount(0)
  75. , m_TessellatorPartitioning(DXIL::TessellatorPartitioning::Undefined)
  76. , m_TessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive::Undefined)
  77. , m_MaxTessellationFactor(0.f)
  78. , m_RootSignature(nullptr) {
  79. DXASSERT_NOMSG(m_pModule != nullptr);
  80. m_NumThreads[0] = m_NumThreads[1] = m_NumThreads[2] = 0;
  81. #if defined(_DEBUG) || defined(DBG)
  82. // Pin LLVM dump methods.
  83. void (__thiscall Module::*pfnModuleDump)() const = &Module::dump;
  84. void (__thiscall Type::*pfnTypeDump)() const = &Type::dump;
  85. void (__thiscall Function::*pfnViewCFGOnly)() const = &Function::viewCFGOnly;
  86. m_pUnused = (char *)&pfnModuleDump - (char *)&pfnTypeDump;
  87. m_pUnused -= (size_t)&pfnViewCFGOnly;
  88. #endif
  89. }
  90. DxilModule::~DxilModule() {
  91. }
  92. DxilModule::ShaderFlags::ShaderFlags():
  93. m_bDisableOptimizations(false)
  94. , m_bDisableMathRefactoring(false)
  95. , m_bEnableDoublePrecision(false)
  96. , m_bForceEarlyDepthStencil(false)
  97. , m_bEnableRawAndStructuredBuffers(false)
  98. , m_bEnableMinPrecision(false)
  99. , m_bEnableDoubleExtensions(false)
  100. , m_bEnableMSAD(false)
  101. , m_bAllResourcesBound(false)
  102. , m_bViewportAndRTArrayIndex(false)
  103. , m_bInnerCoverage(false)
  104. , m_bStencilRef(false)
  105. , m_bTiledResources(false)
  106. , m_bUAVLoadAdditionalFormats(false)
  107. , m_bLevel9ComparisonFiltering(false)
  108. , m_bCSRawAndStructuredViaShader4X(false)
  109. , m_b64UAVs(false)
  110. , m_UAVsAtEveryStage(false)
  111. , m_bROVS(false)
  112. , m_bWaveOps(false)
  113. , m_bInt64Ops(false)
  114. , m_bViewID(false)
  115. , m_bBarycentrics(false)
  116. , m_align0(0)
  117. , m_align1(0)
  118. {}
  119. LLVMContext &DxilModule::GetCtx() const { return m_Ctx; }
  120. Module *DxilModule::GetModule() const { return m_pModule; }
  121. OP *DxilModule::GetOP() const { return m_pOP.get(); }
  122. void DxilModule::SetShaderModel(const ShaderModel *pSM) {
  123. DXASSERT(m_pSM == nullptr || (pSM != nullptr && *m_pSM == *pSM), "shader model must not change for the module");
  124. DXASSERT(pSM != nullptr && pSM->IsValidForDxil(), "shader model must be valid");
  125. m_pSM = pSM;
  126. m_pSM->GetDxilVersion(m_DxilMajor, m_DxilMinor);
  127. m_pMDHelper->SetShaderModel(m_pSM);
  128. DXIL::ShaderKind shaderKind = pSM->GetKind();
  129. m_EntrySignature = llvm::make_unique<DxilEntrySignature>(shaderKind);
  130. m_RootSignature.reset(new RootSignatureHandle());
  131. }
  132. const ShaderModel *DxilModule::GetShaderModel() const {
  133. return m_pSM;
  134. }
  135. void DxilModule::GetDxilVersion(unsigned &DxilMajor, unsigned &DxilMinor) const {
  136. DxilMajor = m_DxilMajor;
  137. DxilMinor = m_DxilMinor;
  138. }
  139. void DxilModule::SetValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
  140. m_ValMajor = ValMajor;
  141. m_ValMinor = ValMinor;
  142. }
  143. bool DxilModule::UpgradeValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
  144. if (ValMajor > m_ValMajor || (ValMajor == m_ValMajor && ValMinor > m_ValMinor)) {
  145. // Module requires higher validator version than previously set
  146. SetValidatorVersion(ValMajor, ValMinor);
  147. return true;
  148. }
  149. return false;
  150. }
  151. void DxilModule::GetValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const {
  152. ValMajor = m_ValMajor;
  153. ValMinor = m_ValMinor;
  154. }
  155. bool DxilModule::GetMinValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const {
  156. if (!m_pSM)
  157. return false;
  158. m_pSM->GetMinValidatorVersion(ValMajor, ValMinor);
  159. if (ValMajor == 1 && ValMinor == 0 && (m_ShaderFlags.GetFeatureInfo() & hlsl::ShaderFeatureInfo_ViewID))
  160. ValMinor = 1;
  161. return true;
  162. }
  163. bool DxilModule::UpgradeToMinValidatorVersion() {
  164. unsigned ValMajor = 1, ValMinor = 0;
  165. if (GetMinValidatorVersion(ValMajor, ValMinor)) {
  166. return UpgradeValidatorVersion(ValMajor, ValMinor);
  167. }
  168. return false;
  169. }
  170. Function *DxilModule::GetEntryFunction() {
  171. return m_pEntryFunc;
  172. }
  173. const Function *DxilModule::GetEntryFunction() const {
  174. return m_pEntryFunc;
  175. }
  176. void DxilModule::SetEntryFunction(Function *pEntryFunc) {
  177. m_pEntryFunc = pEntryFunc;
  178. }
  179. const string &DxilModule::GetEntryFunctionName() const {
  180. return m_EntryName;
  181. }
  182. void DxilModule::SetEntryFunctionName(const string &name) {
  183. m_EntryName = name;
  184. }
  185. llvm::Function *DxilModule::GetPatchConstantFunction() {
  186. return m_pPatchConstantFunc;
  187. }
  188. const llvm::Function *DxilModule::GetPatchConstantFunction() const {
  189. return m_pPatchConstantFunc;
  190. }
  191. void DxilModule::SetPatchConstantFunction(llvm::Function *pFunc) {
  192. m_pPatchConstantFunc = pFunc;
  193. }
  194. unsigned DxilModule::ShaderFlags::GetGlobalFlags() const {
  195. unsigned Flags = 0;
  196. Flags |= m_bDisableOptimizations ? DXIL::kDisableOptimizations : 0;
  197. Flags |= m_bDisableMathRefactoring ? DXIL::kDisableMathRefactoring : 0;
  198. Flags |= m_bEnableDoublePrecision ? DXIL::kEnableDoublePrecision : 0;
  199. Flags |= m_bForceEarlyDepthStencil ? DXIL::kForceEarlyDepthStencil : 0;
  200. Flags |= m_bEnableRawAndStructuredBuffers ? DXIL::kEnableRawAndStructuredBuffers : 0;
  201. Flags |= m_bEnableMinPrecision ? DXIL::kEnableMinPrecision : 0;
  202. Flags |= m_bEnableDoubleExtensions ? DXIL::kEnableDoubleExtensions : 0;
  203. Flags |= m_bEnableMSAD ? DXIL::kEnableMSAD : 0;
  204. Flags |= m_bAllResourcesBound ? DXIL::kAllResourcesBound : 0;
  205. return Flags;
  206. }
  207. uint64_t DxilModule::ShaderFlags::GetFeatureInfo() const {
  208. uint64_t Flags = 0;
  209. Flags |= m_bEnableDoublePrecision ? hlsl::ShaderFeatureInfo_Doubles : 0;
  210. Flags |= m_bEnableMinPrecision ? hlsl::ShaderFeatureInfo_MininumPrecision : 0;
  211. Flags |= m_bEnableDoubleExtensions ? hlsl::ShaderFeatureInfo_11_1_DoubleExtensions : 0;
  212. Flags |= m_bWaveOps ? hlsl::ShaderFeatureInfo_WaveOps : 0;
  213. Flags |= m_bInt64Ops ? hlsl::ShaderFeatureInfo_Int64Ops : 0;
  214. Flags |= m_bROVS ? hlsl::ShaderFeatureInfo_ROVs : 0;
  215. Flags |= m_bViewportAndRTArrayIndex ? hlsl::ShaderFeatureInfo_ViewportAndRTArrayIndexFromAnyShaderFeedingRasterizer : 0;
  216. Flags |= m_bInnerCoverage ? hlsl::ShaderFeatureInfo_InnerCoverage : 0;
  217. Flags |= m_bStencilRef ? hlsl::ShaderFeatureInfo_StencilRef : 0;
  218. Flags |= m_bTiledResources ? hlsl::ShaderFeatureInfo_TiledResources : 0;
  219. Flags |= m_bEnableMSAD ? hlsl::ShaderFeatureInfo_11_1_ShaderExtensions : 0;
  220. Flags |= m_bCSRawAndStructuredViaShader4X ? hlsl::ShaderFeatureInfo_ComputeShadersPlusRawAndStructuredBuffersViaShader4X : 0;
  221. Flags |= m_UAVsAtEveryStage ? hlsl::ShaderFeatureInfo_UAVsAtEveryStage : 0;
  222. Flags |= m_b64UAVs ? hlsl::ShaderFeatureInfo_64UAVs : 0;
  223. Flags |= m_bLevel9ComparisonFiltering ? hlsl::ShaderFeatureInfo_LEVEL9ComparisonFiltering : 0;
  224. Flags |= m_bUAVLoadAdditionalFormats ? hlsl::ShaderFeatureInfo_TypedUAVLoadAdditionalFormats : 0;
  225. Flags |= m_bViewID ? hlsl::ShaderFeatureInfo_ViewID : 0;
  226. Flags |= m_bBarycentrics ? hlsl::ShaderFeatureInfo_Barycentrics : 0;
  227. return Flags;
  228. }
  229. uint64_t DxilModule::ShaderFlags::GetShaderFlagsRaw() const {
  230. union Cast {
  231. Cast(const DxilModule::ShaderFlags &flags) {
  232. shaderFlags = flags;
  233. }
  234. DxilModule::ShaderFlags shaderFlags;
  235. uint64_t rawData;
  236. };
  237. static_assert(sizeof(uint64_t) == sizeof(DxilModule::ShaderFlags),
  238. "size must match to make sure no undefined bits when cast");
  239. Cast rawCast(*this);
  240. return rawCast.rawData;
  241. }
  242. void DxilModule::ShaderFlags::SetShaderFlagsRaw(uint64_t data) {
  243. union Cast {
  244. Cast(uint64_t data) {
  245. rawData = data;
  246. }
  247. DxilModule::ShaderFlags shaderFlags;
  248. uint64_t rawData;
  249. };
  250. Cast rawCast(data);
  251. *this = rawCast.shaderFlags;
  252. }
  253. unsigned DxilModule::GetGlobalFlags() const {
  254. unsigned Flags = m_ShaderFlags.GetGlobalFlags();
  255. return Flags;
  256. }
  257. static bool IsResourceSingleComponent(llvm::Type *Ty) {
  258. if (llvm::ArrayType *arrType = llvm::dyn_cast<llvm::ArrayType>(Ty)) {
  259. if (arrType->getArrayNumElements() > 1) {
  260. return false;
  261. }
  262. return IsResourceSingleComponent(arrType->getArrayElementType());
  263. } else if (llvm::StructType *structType =
  264. llvm::dyn_cast<llvm::StructType>(Ty)) {
  265. if (structType->getStructNumElements() > 1) {
  266. return false;
  267. }
  268. return IsResourceSingleComponent(structType->getStructElementType(0));
  269. } else if (llvm::VectorType *vectorType =
  270. llvm::dyn_cast<llvm::VectorType>(Ty)) {
  271. if (vectorType->getNumElements() > 1) {
  272. return false;
  273. }
  274. return IsResourceSingleComponent(vectorType->getVectorElementType());
  275. }
  276. return true;
  277. }
  278. // Given a CreateHandle call, returns arbitrary ConstantInt rangeID
  279. // Note: HLSL is currently assuming that rangeID is a constant value, but this code is assuming
  280. // that it can be either constant, phi node, or select instruction
  281. static ConstantInt *GetArbitraryConstantRangeID(CallInst *handleCall) {
  282. Value *rangeID =
  283. handleCall->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
  284. ConstantInt *ConstantRangeID = dyn_cast<ConstantInt>(rangeID);
  285. while (ConstantRangeID == nullptr) {
  286. if (ConstantInt *CI = dyn_cast<ConstantInt>(rangeID)) {
  287. ConstantRangeID = CI;
  288. } else if (PHINode *PN = dyn_cast<PHINode>(rangeID)) {
  289. rangeID = PN->getIncomingValue(0);
  290. } else if (SelectInst *SI = dyn_cast<SelectInst>(rangeID)) {
  291. rangeID = SI->getTrueValue();
  292. } else {
  293. return nullptr;
  294. }
  295. }
  296. return ConstantRangeID;
  297. }
  298. void DxilModule::CollectShaderFlags(ShaderFlags &Flags) {
  299. bool hasDouble = false;
  300. // ddiv dfma drcp d2i d2u i2d u2d.
  301. // fma has dxil op. Others should check IR instruction div/cast.
  302. bool hasDoubleExtension = false;
  303. bool has64Int = false;
  304. bool has16FloatInt = false;
  305. bool hasWaveOps = false;
  306. bool hasCheckAccessFully = false;
  307. bool hasMSAD = false;
  308. bool hasInnerCoverage = false;
  309. bool hasViewID = false;
  310. bool hasMulticomponentUAVLoads = false;
  311. bool hasMulticomponentUAVLoadsBackCompat = false;
  312. // Try to maintain compatibility with a v1.0 validator if that's what we have.
  313. {
  314. unsigned valMajor, valMinor;
  315. GetValidatorVersion(valMajor, valMinor);
  316. hasMulticomponentUAVLoadsBackCompat = valMajor <= 1 && valMinor == 0;
  317. }
  318. Type *int16Ty = Type::getInt16Ty(GetCtx());
  319. Type *int64Ty = Type::getInt64Ty(GetCtx());
  320. for (Function &F : GetModule()->functions()) {
  321. for (BasicBlock &BB : F.getBasicBlockList()) {
  322. for (Instruction &I : BB.getInstList()) {
  323. // Skip none dxil function call.
  324. if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  325. if (!OP::IsDxilOpFunc(CI->getCalledFunction()))
  326. continue;
  327. }
  328. Type *Ty = I.getType();
  329. bool isDouble = Ty->isDoubleTy();
  330. bool isHalf = Ty->isHalfTy();
  331. bool isInt16 = Ty == int16Ty;
  332. bool isInt64 = Ty == int64Ty;
  333. if (isa<ExtractElementInst>(&I) ||
  334. isa<InsertElementInst>(&I))
  335. continue;
  336. for (Value *operand : I.operands()) {
  337. Type *Ty = operand->getType();
  338. isDouble |= Ty->isDoubleTy();
  339. isHalf |= Ty->isHalfTy();
  340. isInt16 |= Ty == int16Ty;
  341. isInt64 |= Ty == int64Ty;
  342. }
  343. if (isDouble) {
  344. hasDouble = true;
  345. switch (I.getOpcode()) {
  346. case Instruction::FDiv:
  347. case Instruction::UIToFP:
  348. case Instruction::SIToFP:
  349. case Instruction::FPToUI:
  350. case Instruction::FPToSI:
  351. hasDoubleExtension = true;
  352. break;
  353. }
  354. }
  355. has16FloatInt |= isHalf;
  356. has16FloatInt |= isInt16;
  357. has64Int |= isInt64;
  358. if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  359. if (!OP::IsDxilOpFunc(CI->getCalledFunction()))
  360. continue;
  361. Value *opcodeArg = CI->getArgOperand(DXIL::OperandIndex::kOpcodeIdx);
  362. ConstantInt *opcodeConst = dyn_cast<ConstantInt>(opcodeArg);
  363. DXASSERT(opcodeConst, "DXIL opcode arg must be immediate");
  364. unsigned opcode = opcodeConst->getLimitedValue();
  365. DXASSERT(opcode < static_cast<unsigned>(DXIL::OpCode::NumOpCodes),
  366. "invalid DXIL opcode");
  367. DXIL::OpCode dxilOp = static_cast<DXIL::OpCode>(opcode);
  368. if (hlsl::OP::IsDxilOpWave(dxilOp))
  369. hasWaveOps = true;
  370. switch (dxilOp) {
  371. case DXIL::OpCode::CheckAccessFullyMapped:
  372. hasCheckAccessFully = true;
  373. break;
  374. case DXIL::OpCode::Msad:
  375. hasMSAD = true;
  376. break;
  377. case DXIL::OpCode::BufferLoad:
  378. case DXIL::OpCode::TextureLoad: {
  379. if (hasMulticomponentUAVLoads) continue;
  380. // This is the old-style computation (overestimating requirements).
  381. Value *resHandle = CI->getArgOperand(DXIL::OperandIndex::kBufferStoreHandleOpIdx);
  382. CallInst *handleCall = cast<CallInst>(resHandle);
  383. if (ConstantInt *resClassArg =
  384. dyn_cast<ConstantInt>(handleCall->getArgOperand(
  385. DXIL::OperandIndex::kCreateHandleResClassOpIdx))) {
  386. DXIL::ResourceClass resClass = static_cast<DXIL::ResourceClass>(
  387. resClassArg->getLimitedValue());
  388. if (resClass == DXIL::ResourceClass::UAV) {
  389. // Validator 1.0 assumes that all uav load is multi component load.
  390. if (hasMulticomponentUAVLoadsBackCompat) {
  391. hasMulticomponentUAVLoads = true;
  392. continue;
  393. }
  394. else {
  395. ConstantInt *rangeID = GetArbitraryConstantRangeID(handleCall);
  396. if (rangeID) {
  397. DxilResource resource = GetUAV(rangeID->getLimitedValue());
  398. if ((resource.IsTypedBuffer() ||
  399. resource.IsAnyTexture()) &&
  400. !IsResourceSingleComponent(resource.GetRetType())) {
  401. hasMulticomponentUAVLoads = true;
  402. }
  403. }
  404. }
  405. }
  406. }
  407. else {
  408. DXASSERT(false, "Resource class must be constant.");
  409. }
  410. } break;
  411. case DXIL::OpCode::Fma:
  412. hasDoubleExtension |= isDouble;
  413. break;
  414. case DXIL::OpCode::InnerCoverage:
  415. hasInnerCoverage = true;
  416. break;
  417. case DXIL::OpCode::ViewID:
  418. hasViewID = true;
  419. break;
  420. default:
  421. // Normal opcodes.
  422. break;
  423. }
  424. }
  425. }
  426. }
  427. }
  428. Flags.SetEnableDoublePrecision(hasDouble);
  429. Flags.SetInt64Ops(has64Int);
  430. Flags.SetEnableMinPrecision(has16FloatInt);
  431. Flags.SetEnableDoubleExtensions(hasDoubleExtension);
  432. Flags.SetWaveOps(hasWaveOps);
  433. Flags.SetTiledResources(hasCheckAccessFully);
  434. Flags.SetEnableMSAD(hasMSAD);
  435. Flags.SetUAVLoadAdditionalFormats(hasMulticomponentUAVLoads);
  436. Flags.SetViewID(hasViewID);
  437. const ShaderModel *SM = GetShaderModel();
  438. if (SM->IsPS()) {
  439. bool hasStencilRef = false;
  440. DxilSignature &outS = GetOutputSignature();
  441. for (auto &&E : outS.GetElements()) {
  442. if (E->GetKind() == Semantic::Kind::StencilRef) {
  443. hasStencilRef = true;
  444. } else if (E->GetKind() == Semantic::Kind::InnerCoverage) {
  445. hasInnerCoverage = true;
  446. }
  447. }
  448. Flags.SetStencilRef(hasStencilRef);
  449. Flags.SetInnerCoverage(hasInnerCoverage);
  450. }
  451. bool checkInputRTArrayIndex =
  452. SM->IsGS() || SM->IsDS() || SM->IsHS() || SM->IsPS();
  453. if (checkInputRTArrayIndex) {
  454. bool hasViewportArrayIndex = false;
  455. bool hasRenderTargetArrayIndex = false;
  456. DxilSignature &inS = GetInputSignature();
  457. for (auto &E : inS.GetElements()) {
  458. if (E->GetKind() == Semantic::Kind::ViewPortArrayIndex) {
  459. hasViewportArrayIndex = true;
  460. } else if (E->GetKind() == Semantic::Kind::RenderTargetArrayIndex) {
  461. hasRenderTargetArrayIndex = true;
  462. }
  463. }
  464. Flags.SetViewportAndRTArrayIndex(hasViewportArrayIndex |
  465. hasRenderTargetArrayIndex);
  466. }
  467. bool checkOutputRTArrayIndex =
  468. SM->IsVS() || SM->IsDS() || SM->IsHS() || SM->IsPS();
  469. if (checkOutputRTArrayIndex) {
  470. bool hasViewportArrayIndex = false;
  471. bool hasRenderTargetArrayIndex = false;
  472. DxilSignature &outS = GetOutputSignature();
  473. for (auto &E : outS.GetElements()) {
  474. if (E->GetKind() == Semantic::Kind::ViewPortArrayIndex) {
  475. hasViewportArrayIndex = true;
  476. } else if (E->GetKind() == Semantic::Kind::RenderTargetArrayIndex) {
  477. hasRenderTargetArrayIndex = true;
  478. }
  479. }
  480. Flags.SetViewportAndRTArrayIndex(hasViewportArrayIndex |
  481. hasRenderTargetArrayIndex);
  482. }
  483. unsigned NumUAVs = m_UAVs.size();
  484. const unsigned kSmallUAVCount = 8;
  485. if (NumUAVs > kSmallUAVCount)
  486. Flags.Set64UAVs(true);
  487. if (NumUAVs && !(SM->IsCS() || SM->IsPS()))
  488. Flags.SetUAVsAtEveryStage(true);
  489. bool hasRawAndStructuredBuffer = false;
  490. for (auto &UAV : m_UAVs) {
  491. if (UAV->IsROV())
  492. Flags.SetROVs(true);
  493. switch (UAV->GetKind()) {
  494. case DXIL::ResourceKind::RawBuffer:
  495. case DXIL::ResourceKind::StructuredBuffer:
  496. hasRawAndStructuredBuffer = true;
  497. break;
  498. default:
  499. // Not raw/structured.
  500. break;
  501. }
  502. }
  503. for (auto &SRV : m_SRVs) {
  504. switch (SRV->GetKind()) {
  505. case DXIL::ResourceKind::RawBuffer:
  506. case DXIL::ResourceKind::StructuredBuffer:
  507. hasRawAndStructuredBuffer = true;
  508. break;
  509. default:
  510. // Not raw/structured.
  511. break;
  512. }
  513. }
  514. Flags.SetEnableRawAndStructuredBuffers(hasRawAndStructuredBuffer);
  515. bool hasCSRawAndStructuredViaShader4X =
  516. hasRawAndStructuredBuffer && m_pSM->GetMajor() == 4 && m_pSM->IsCS();
  517. Flags.SetCSRawAndStructuredViaShader4X(hasCSRawAndStructuredViaShader4X);
  518. }
  519. void DxilModule::CollectShaderFlags() {
  520. CollectShaderFlags(m_ShaderFlags);
  521. }
  522. uint64_t DxilModule::ShaderFlags::GetShaderFlagsRawForCollection() {
  523. // This should be all the flags that can be set by DxilModule::CollectShaderFlags.
  524. ShaderFlags Flags;
  525. Flags.SetEnableDoublePrecision(true);
  526. Flags.SetInt64Ops(true);
  527. Flags.SetEnableMinPrecision(true);
  528. Flags.SetEnableDoubleExtensions(true);
  529. Flags.SetWaveOps(true);
  530. Flags.SetTiledResources(true);
  531. Flags.SetEnableMSAD(true);
  532. Flags.SetUAVLoadAdditionalFormats(true);
  533. Flags.SetStencilRef(true);
  534. Flags.SetInnerCoverage(true);
  535. Flags.SetViewportAndRTArrayIndex(true);
  536. Flags.Set64UAVs(true);
  537. Flags.SetUAVsAtEveryStage(true);
  538. Flags.SetEnableRawAndStructuredBuffers(true);
  539. Flags.SetCSRawAndStructuredViaShader4X(true);
  540. Flags.SetViewID(true);
  541. Flags.SetBarycentrics(true);
  542. return Flags.GetShaderFlagsRaw();
  543. }
  544. DXIL::InputPrimitive DxilModule::GetInputPrimitive() const {
  545. return m_InputPrimitive;
  546. }
  547. void DxilModule::SetInputPrimitive(DXIL::InputPrimitive IP) {
  548. DXASSERT_NOMSG(m_InputPrimitive == DXIL::InputPrimitive::Undefined);
  549. DXASSERT_NOMSG(DXIL::InputPrimitive::Undefined < IP && IP < DXIL::InputPrimitive::LastEntry);
  550. m_InputPrimitive = IP;
  551. }
  552. unsigned DxilModule::GetMaxVertexCount() const {
  553. DXASSERT_NOMSG(m_MaxVertexCount != 0);
  554. return m_MaxVertexCount;
  555. }
  556. void DxilModule::SetMaxVertexCount(unsigned Count) {
  557. DXASSERT_NOMSG(m_MaxVertexCount == 0);
  558. m_MaxVertexCount = Count;
  559. }
  560. DXIL::PrimitiveTopology DxilModule::GetStreamPrimitiveTopology() const {
  561. return m_StreamPrimitiveTopology;
  562. }
  563. void DxilModule::SetStreamPrimitiveTopology(DXIL::PrimitiveTopology Topology) {
  564. m_StreamPrimitiveTopology = Topology;
  565. }
  566. bool DxilModule::HasMultipleOutputStreams() const {
  567. if (!m_pSM->IsGS()) {
  568. return false;
  569. } else {
  570. unsigned NumStreams = (m_ActiveStreamMask & 0x1) +
  571. ((m_ActiveStreamMask & 0x2) >> 1) +
  572. ((m_ActiveStreamMask & 0x4) >> 2) +
  573. ((m_ActiveStreamMask & 0x8) >> 3);
  574. DXASSERT_NOMSG(NumStreams <= DXIL::kNumOutputStreams);
  575. return NumStreams > 1;
  576. }
  577. }
  578. unsigned DxilModule::GetOutputStream() const {
  579. if (!m_pSM->IsGS()) {
  580. return 0;
  581. } else {
  582. DXASSERT_NOMSG(!HasMultipleOutputStreams());
  583. switch (m_ActiveStreamMask) {
  584. case 0x1: return 0;
  585. case 0x2: return 1;
  586. case 0x4: return 2;
  587. case 0x8: return 3;
  588. default: DXASSERT_NOMSG(false);
  589. }
  590. return (unsigned)(-1);
  591. }
  592. }
  593. unsigned DxilModule::GetGSInstanceCount() const {
  594. return m_NumGSInstances;
  595. }
  596. void DxilModule::SetGSInstanceCount(unsigned Count) {
  597. m_NumGSInstances = Count;
  598. }
  599. bool DxilModule::IsStreamActive(unsigned Stream) const {
  600. return (m_ActiveStreamMask & (1<<Stream)) != 0;
  601. }
  602. void DxilModule::SetStreamActive(unsigned Stream, bool bActive) {
  603. if (bActive) {
  604. m_ActiveStreamMask |= (1<<Stream);
  605. } else {
  606. m_ActiveStreamMask &= ~(1<<Stream);
  607. }
  608. }
  609. void DxilModule::SetActiveStreamMask(unsigned Mask) {
  610. m_ActiveStreamMask = Mask;
  611. }
  612. unsigned DxilModule::GetActiveStreamMask() const {
  613. return m_ActiveStreamMask;
  614. }
  615. unsigned DxilModule::GetInputControlPointCount() const {
  616. return m_InputControlPointCount;
  617. }
  618. void DxilModule::SetInputControlPointCount(unsigned NumICPs) {
  619. m_InputControlPointCount = NumICPs;
  620. }
  621. DXIL::TessellatorDomain DxilModule::GetTessellatorDomain() const {
  622. return m_TessellatorDomain;
  623. }
  624. void DxilModule::SetTessellatorDomain(DXIL::TessellatorDomain TessDomain) {
  625. m_TessellatorDomain = TessDomain;
  626. }
  627. unsigned DxilModule::GetOutputControlPointCount() const {
  628. return m_OutputControlPointCount;
  629. }
  630. void DxilModule::SetOutputControlPointCount(unsigned NumOCPs) {
  631. m_OutputControlPointCount = NumOCPs;
  632. }
  633. DXIL::TessellatorPartitioning DxilModule::GetTessellatorPartitioning() const {
  634. return m_TessellatorPartitioning;
  635. }
  636. void DxilModule::SetTessellatorPartitioning(DXIL::TessellatorPartitioning TessPartitioning) {
  637. m_TessellatorPartitioning = TessPartitioning;
  638. }
  639. DXIL::TessellatorOutputPrimitive DxilModule::GetTessellatorOutputPrimitive() const {
  640. return m_TessellatorOutputPrimitive;
  641. }
  642. void DxilModule::SetTessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive TessOutputPrimitive) {
  643. m_TessellatorOutputPrimitive = TessOutputPrimitive;
  644. }
  645. float DxilModule::GetMaxTessellationFactor() const {
  646. return m_MaxTessellationFactor;
  647. }
  648. void DxilModule::SetMaxTessellationFactor(float MaxTessellationFactor) {
  649. m_MaxTessellationFactor = MaxTessellationFactor;
  650. }
  651. void DxilModule::SetShaderProperties(DxilFunctionProps *props) {
  652. if (!props)
  653. return;
  654. switch (props->shaderKind) {
  655. case DXIL::ShaderKind::Pixel: {
  656. auto &PS = props->ShaderProps.PS;
  657. m_ShaderFlags.SetForceEarlyDepthStencil(PS.EarlyDepthStencil);
  658. } break;
  659. case DXIL::ShaderKind::Compute: {
  660. auto &CS = props->ShaderProps.CS;
  661. for (size_t i = 0; i < _countof(m_NumThreads); ++i)
  662. m_NumThreads[i] = CS.numThreads[i];
  663. } break;
  664. case DXIL::ShaderKind::Domain: {
  665. auto &DS = props->ShaderProps.DS;
  666. SetTessellatorDomain(DS.domain);
  667. SetInputControlPointCount(DS.inputControlPoints);
  668. } break;
  669. case DXIL::ShaderKind::Hull: {
  670. auto &HS = props->ShaderProps.HS;
  671. SetPatchConstantFunction(HS.patchConstantFunc);
  672. SetTessellatorDomain(HS.domain);
  673. SetTessellatorPartitioning(HS.partition);
  674. SetTessellatorOutputPrimitive(HS.outputPrimitive);
  675. SetInputControlPointCount(HS.inputControlPoints);
  676. SetOutputControlPointCount(HS.outputControlPoints);
  677. SetMaxTessellationFactor(HS.maxTessFactor);
  678. } break;
  679. case DXIL::ShaderKind::Vertex:
  680. break;
  681. default: {
  682. DXASSERT(props->shaderKind == DXIL::ShaderKind::Geometry,
  683. "else invalid shader kind");
  684. auto &GS = props->ShaderProps.GS;
  685. SetInputPrimitive(GS.inputPrimitive);
  686. SetMaxVertexCount(GS.maxVertexCount);
  687. for (size_t i = 0; i < _countof(GS.streamPrimitiveTopologies); ++i) {
  688. if (GS.streamPrimitiveTopologies[i] !=
  689. DXIL::PrimitiveTopology::Undefined) {
  690. SetStreamActive(i, true);
  691. DXASSERT_NOMSG(GetStreamPrimitiveTopology() ==
  692. DXIL::PrimitiveTopology::Undefined ||
  693. GetStreamPrimitiveTopology() ==
  694. GS.streamPrimitiveTopologies[i]);
  695. SetStreamPrimitiveTopology(GS.streamPrimitiveTopologies[i]);
  696. }
  697. }
  698. SetGSInstanceCount(GS.instanceCount);
  699. } break;
  700. }
  701. }
  702. template<typename T> unsigned
  703. DxilModule::AddResource(vector<unique_ptr<T> > &Vec, unique_ptr<T> pRes) {
  704. DXASSERT_NOMSG((unsigned)Vec.size() < UINT_MAX);
  705. unsigned Id = (unsigned)Vec.size();
  706. Vec.emplace_back(std::move(pRes));
  707. return Id;
  708. }
  709. unsigned DxilModule::AddCBuffer(unique_ptr<DxilCBuffer> pCB) {
  710. return AddResource<DxilCBuffer>(m_CBuffers, std::move(pCB));
  711. }
  712. DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) {
  713. return *m_CBuffers[idx];
  714. }
  715. const DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) const {
  716. return *m_CBuffers[idx];
  717. }
  718. const vector<unique_ptr<DxilCBuffer> > &DxilModule::GetCBuffers() const {
  719. return m_CBuffers;
  720. }
  721. unsigned DxilModule::AddSampler(unique_ptr<DxilSampler> pSampler) {
  722. return AddResource<DxilSampler>(m_Samplers, std::move(pSampler));
  723. }
  724. DxilSampler &DxilModule::GetSampler(unsigned idx) {
  725. return *m_Samplers[idx];
  726. }
  727. const DxilSampler &DxilModule::GetSampler(unsigned idx) const {
  728. return *m_Samplers[idx];
  729. }
  730. const vector<unique_ptr<DxilSampler> > &DxilModule::GetSamplers() const {
  731. return m_Samplers;
  732. }
  733. unsigned DxilModule::AddSRV(unique_ptr<DxilResource> pSRV) {
  734. return AddResource<DxilResource>(m_SRVs, std::move(pSRV));
  735. }
  736. DxilResource &DxilModule::GetSRV(unsigned idx) {
  737. return *m_SRVs[idx];
  738. }
  739. const DxilResource &DxilModule::GetSRV(unsigned idx) const {
  740. return *m_SRVs[idx];
  741. }
  742. const vector<unique_ptr<DxilResource> > &DxilModule::GetSRVs() const {
  743. return m_SRVs;
  744. }
  745. unsigned DxilModule::AddUAV(unique_ptr<DxilResource> pUAV) {
  746. return AddResource<DxilResource>(m_UAVs, std::move(pUAV));
  747. }
  748. DxilResource &DxilModule::GetUAV(unsigned idx) {
  749. return *m_UAVs[idx];
  750. }
  751. const DxilResource &DxilModule::GetUAV(unsigned idx) const {
  752. return *m_UAVs[idx];
  753. }
  754. const vector<unique_ptr<DxilResource> > &DxilModule::GetUAVs() const {
  755. return m_UAVs;
  756. }
  757. static void CreateResourceLinkConstant(Module &M, DxilResourceBase *pRes,
  758. std::vector<DxilModule::ResourceLinkInfo> &resLinkInfo) {
  759. Type *i32Ty = Type::getInt32Ty(M.getContext());
  760. const bool IsConstantTrue = true;
  761. Constant *NullInitVal = nullptr;
  762. GlobalVariable *rangeID = new GlobalVariable(
  763. M, i32Ty, IsConstantTrue, llvm::GlobalValue::ExternalLinkage, NullInitVal,
  764. pRes->GetGlobalName() + "_rangeID");
  765. resLinkInfo.emplace_back(DxilModule::ResourceLinkInfo{rangeID});
  766. }
  767. void DxilModule::CreateResourceLinkInfo() {
  768. DXASSERT(GetShaderModel()->IsLib(), "only for library profile");
  769. DXASSERT(m_SRVsLinkInfo.empty() && m_UAVsLinkInfo.empty() &&
  770. m_CBuffersLinkInfo.empty() && m_SamplersLinkInfo.empty(),
  771. "else resource link info was already created");
  772. Module &M = *m_pModule;
  773. for (auto &SRV : m_SRVs) {
  774. CreateResourceLinkConstant(M, SRV.get(), m_SRVsLinkInfo);
  775. }
  776. for (auto &UAV : m_UAVs) {
  777. CreateResourceLinkConstant(M, UAV.get(), m_UAVsLinkInfo);
  778. }
  779. for (auto &CBuffer : m_CBuffers) {
  780. CreateResourceLinkConstant(M, CBuffer.get(), m_CBuffersLinkInfo);
  781. }
  782. for (auto &Sampler : m_Samplers) {
  783. CreateResourceLinkConstant(M, Sampler.get(), m_SamplersLinkInfo);
  784. }
  785. }
  786. const DxilModule::ResourceLinkInfo &
  787. DxilModule::GetResourceLinkInfo(DXIL::ResourceClass resClass,
  788. unsigned rangeID) const {
  789. switch (resClass) {
  790. case DXIL::ResourceClass::UAV:
  791. return m_UAVsLinkInfo[rangeID];
  792. case DXIL::ResourceClass::CBuffer:
  793. return m_CBuffersLinkInfo[rangeID];
  794. case DXIL::ResourceClass::Sampler:
  795. return m_SamplersLinkInfo[rangeID];
  796. default:
  797. DXASSERT(DXIL::ResourceClass::SRV == resClass,
  798. "else invalid resource class");
  799. return m_SRVsLinkInfo[rangeID];
  800. }
  801. }
  802. void DxilModule::LoadDxilResourceBaseFromMDNode(MDNode *MD, DxilResourceBase &R) {
  803. return m_pMDHelper->LoadDxilResourceBaseFromMDNode(MD, R);
  804. }
  805. void DxilModule::LoadDxilResourceFromMDNode(llvm::MDNode *MD, DxilResource &R) {
  806. return m_pMDHelper->LoadDxilResourceFromMDNode(MD, R);
  807. }
  808. void DxilModule::LoadDxilSamplerFromMDNode(llvm::MDNode *MD, DxilSampler &S) {
  809. return m_pMDHelper->LoadDxilSamplerFromMDNode(MD, S);
  810. }
  811. template <typename TResource>
  812. static void RemoveResources(std::vector<std::unique_ptr<TResource>> &vec,
  813. std::unordered_set<unsigned> &immResID) {
  814. for (std::vector<std::unique_ptr<TResource>>::iterator p = vec.begin(); p != vec.end();) {
  815. std::vector<std::unique_ptr<TResource>>::iterator c = p++;
  816. if (immResID.count((*c)->GetID()) == 0) {
  817. p = vec.erase(c);
  818. }
  819. }
  820. }
  821. static void CollectUsedResource(Value *resID,
  822. std::unordered_set<Value *> &usedResID) {
  823. if (usedResID.count(resID) > 0)
  824. return;
  825. usedResID.insert(resID);
  826. if (ConstantInt *cResID = dyn_cast<ConstantInt>(resID)) {
  827. // Do nothing
  828. } else if (ZExtInst *ZEI = dyn_cast<ZExtInst>(resID)) {
  829. if (ZEI->getSrcTy()->isIntegerTy()) {
  830. IntegerType *ITy = cast<IntegerType>(ZEI->getSrcTy());
  831. if (ITy->getBitWidth() == 1) {
  832. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 0));
  833. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 1));
  834. }
  835. }
  836. } else if (SelectInst *SI = dyn_cast<SelectInst>(resID)) {
  837. CollectUsedResource(SI->getTrueValue(), usedResID);
  838. CollectUsedResource(SI->getFalseValue(), usedResID);
  839. } else if (PHINode *Phi = dyn_cast<PHINode>(resID)) {
  840. for (Use &U : Phi->incoming_values()) {
  841. CollectUsedResource(U.get(), usedResID);
  842. }
  843. }
  844. // TODO: resID could be other types of instructions depending on the compiler optimization.
  845. }
  846. static void ConvertUsedResource(std::unordered_set<unsigned> &immResID,
  847. std::unordered_set<Value *> &usedResID) {
  848. for (Value *V : usedResID) {
  849. if (ConstantInt *cResID = dyn_cast<ConstantInt>(V)) {
  850. immResID.insert(cResID->getLimitedValue());
  851. }
  852. }
  853. }
  854. void DxilModule::RemoveFunction(llvm::Function *F) {
  855. DXASSERT_NOMSG(F != nullptr);
  856. m_DxilFunctionPropsMap.erase(F);
  857. m_DxilEntrySignatureMap.erase(F);
  858. if (m_pTypeSystem.get()->GetFunctionAnnotation(F))
  859. m_pTypeSystem.get()->EraseFunctionAnnotation(F);
  860. m_pOP->RemoveFunction(F);
  861. }
  862. void DxilModule::RemoveUnusedResources() {
  863. hlsl::OP *hlslOP = GetOP();
  864. Function *createHandleFunc = hlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(GetCtx()));
  865. if (createHandleFunc->user_empty()) {
  866. m_CBuffers.clear();
  867. m_UAVs.clear();
  868. m_SRVs.clear();
  869. m_Samplers.clear();
  870. createHandleFunc->eraseFromParent();
  871. return;
  872. }
  873. std::unordered_set<Value *> usedUAVID;
  874. std::unordered_set<Value *> usedSRVID;
  875. std::unordered_set<Value *> usedSamplerID;
  876. std::unordered_set<Value *> usedCBufID;
  877. // Collect used ID.
  878. for (User *U : createHandleFunc->users()) {
  879. CallInst *CI = cast<CallInst>(U);
  880. Value *vResClass =
  881. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
  882. ConstantInt *cResClass = cast<ConstantInt>(vResClass);
  883. DXIL::ResourceClass resClass =
  884. static_cast<DXIL::ResourceClass>(cResClass->getLimitedValue());
  885. // Skip unused resource handle.
  886. if (CI->user_empty())
  887. continue;
  888. Value *resID =
  889. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
  890. switch (resClass) {
  891. case DXIL::ResourceClass::CBuffer:
  892. CollectUsedResource(resID, usedCBufID);
  893. break;
  894. case DXIL::ResourceClass::Sampler:
  895. CollectUsedResource(resID, usedSamplerID);
  896. break;
  897. case DXIL::ResourceClass::SRV:
  898. CollectUsedResource(resID, usedSRVID);
  899. break;
  900. case DXIL::ResourceClass::UAV:
  901. CollectUsedResource(resID, usedUAVID);
  902. break;
  903. default:
  904. DXASSERT(0, "invalid res class");
  905. break;
  906. }
  907. }
  908. std::unordered_set<unsigned> immUAVID;
  909. std::unordered_set<unsigned> immSRVID;
  910. std::unordered_set<unsigned> immSamplerID;
  911. std::unordered_set<unsigned> immCBufID;
  912. ConvertUsedResource(immUAVID, usedUAVID);
  913. RemoveResources(m_UAVs, immUAVID);
  914. ConvertUsedResource(immSRVID, usedSRVID);
  915. ConvertUsedResource(immSamplerID, usedSamplerID);
  916. ConvertUsedResource(immCBufID, usedCBufID);
  917. RemoveResources(m_SRVs, immSRVID);
  918. RemoveResources(m_Samplers, immSamplerID);
  919. RemoveResources(m_CBuffers, immCBufID);
  920. }
  921. DxilSignature &DxilModule::GetInputSignature() {
  922. return m_EntrySignature->InputSignature;
  923. }
  924. const DxilSignature &DxilModule::GetInputSignature() const {
  925. return m_EntrySignature->InputSignature;
  926. }
  927. DxilSignature &DxilModule::GetOutputSignature() {
  928. return m_EntrySignature->OutputSignature;
  929. }
  930. const DxilSignature &DxilModule::GetOutputSignature() const {
  931. return m_EntrySignature->OutputSignature;
  932. }
  933. DxilSignature &DxilModule::GetPatchConstantSignature() {
  934. return m_EntrySignature->PatchConstantSignature;
  935. }
  936. const DxilSignature &DxilModule::GetPatchConstantSignature() const {
  937. return m_EntrySignature->PatchConstantSignature;
  938. }
  939. const RootSignatureHandle &DxilModule::GetRootSignature() const {
  940. return *m_RootSignature;
  941. }
  942. bool DxilModule::HasDxilEntrySignature(llvm::Function *F) const {
  943. return m_DxilEntrySignatureMap.find(F) != m_DxilEntrySignatureMap.end();
  944. }
  945. DxilEntrySignature &DxilModule::GetDxilEntrySignature(llvm::Function *F) {
  946. DXASSERT(m_DxilEntrySignatureMap.count(F) != 0, "cannot find F in map");
  947. return *m_DxilEntrySignatureMap[F];
  948. }
  949. void DxilModule::ReplaceDxilEntrySignature(llvm::Function *F,
  950. llvm::Function *NewF) {
  951. DXASSERT(m_DxilEntrySignatureMap.count(F) != 0, "cannot find F in map");
  952. std::unique_ptr<DxilEntrySignature> Sig =
  953. std::move(m_DxilEntrySignatureMap[F]);
  954. m_DxilEntrySignatureMap.erase(F);
  955. m_DxilEntrySignatureMap[NewF] = std::move(Sig);
  956. }
  957. bool DxilModule::HasDxilFunctionProps(llvm::Function *F) const {
  958. return m_DxilFunctionPropsMap.find(F) != m_DxilFunctionPropsMap.end();
  959. }
  960. DxilFunctionProps &DxilModule::GetDxilFunctionProps(llvm::Function *F) {
  961. DXASSERT(m_DxilFunctionPropsMap.count(F) != 0, "cannot find F in map");
  962. return *m_DxilFunctionPropsMap[F];
  963. }
  964. void DxilModule::ReplaceDxilFunctionProps(llvm::Function *F,
  965. llvm::Function *NewF) {
  966. DXASSERT(m_DxilFunctionPropsMap.count(F) != 0, "cannot find F in map");
  967. std::unique_ptr<DxilFunctionProps> props =
  968. std::move(m_DxilFunctionPropsMap[F]);
  969. m_DxilFunctionPropsMap.erase(F);
  970. m_DxilFunctionPropsMap[NewF] = std::move(props);
  971. }
  972. void DxilModule::StripRootSignatureFromMetadata() {
  973. NamedMDNode *pRootSignatureNamedMD = GetModule()->getNamedMetadata(DxilMDHelper::kDxilRootSignatureMDName);
  974. if (pRootSignatureNamedMD) {
  975. GetModule()->eraseNamedMetadata(pRootSignatureNamedMD);
  976. }
  977. }
  978. void DxilModule::UpdateValidatorVersionMetadata() {
  979. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  980. }
  981. void DxilModule::ResetEntrySignature(DxilEntrySignature *pValue) {
  982. m_EntrySignature.reset(pValue);
  983. }
  984. void DxilModule::ResetRootSignature(RootSignatureHandle *pValue) {
  985. m_RootSignature.reset(pValue);
  986. }
  987. DxilTypeSystem &DxilModule::GetTypeSystem() {
  988. return *m_pTypeSystem;
  989. }
  990. DxilViewIdState &DxilModule::GetViewIdState() {
  991. return *m_pViewIdState;
  992. }
  993. const DxilViewIdState &DxilModule::GetViewIdState() const {
  994. return *m_pViewIdState;
  995. }
  996. void DxilModule::ResetTypeSystem(DxilTypeSystem *pValue) {
  997. m_pTypeSystem.reset(pValue);
  998. }
  999. void DxilModule::ResetOP(hlsl::OP *hlslOP) { m_pOP.reset(hlslOP); }
  1000. void DxilModule::ResetFunctionPropsMap(
  1001. std::unordered_map<llvm::Function *, std::unique_ptr<DxilFunctionProps>>
  1002. &&propsMap) {
  1003. m_DxilFunctionPropsMap = std::move(propsMap);
  1004. }
  1005. void DxilModule::ResetEntrySignatureMap(
  1006. std::unordered_map<llvm::Function *, std::unique_ptr<DxilEntrySignature>>
  1007. &&SigMap) {
  1008. m_DxilEntrySignatureMap = std::move(SigMap);
  1009. }
  1010. void DxilModule::EmitLLVMUsed() {
  1011. if (m_LLVMUsed.empty())
  1012. return;
  1013. vector<llvm::Constant*> GVs;
  1014. Type *pI8PtrType = Type::getInt8PtrTy(m_Ctx, DXIL::kDefaultAddrSpace);
  1015. GVs.resize(m_LLVMUsed.size());
  1016. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  1017. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  1018. PointerType * pPtrType = dyn_cast<PointerType>(pConst->getType());
  1019. if (pPtrType->getPointerAddressSpace() != DXIL::kDefaultAddrSpace) {
  1020. // Cast pointer to addrspace 0, as LLVMUsed elements must have the same type.
  1021. GVs[i] = ConstantExpr::getAddrSpaceCast(pConst, pI8PtrType);
  1022. } else {
  1023. GVs[i] = ConstantExpr::getPointerCast(pConst, pI8PtrType);
  1024. }
  1025. }
  1026. ArrayType *pATy = ArrayType::get(pI8PtrType, GVs.size());
  1027. StringRef llvmUsedName = "llvm.used";
  1028. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  1029. oldGV->eraseFromParent();
  1030. }
  1031. GlobalVariable *pGV = new GlobalVariable(*m_pModule, pATy, false,
  1032. GlobalValue::AppendingLinkage,
  1033. ConstantArray::get(pATy, GVs),
  1034. llvmUsedName);
  1035. pGV->setSection("llvm.metadata");
  1036. }
  1037. vector<GlobalVariable* > &DxilModule::GetLLVMUsed() {
  1038. return m_LLVMUsed;
  1039. }
  1040. // DXIL metadata serialization/deserialization.
  1041. void DxilModule::EmitDxilMetadata() {
  1042. m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
  1043. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  1044. m_pMDHelper->EmitDxilShaderModel(m_pSM);
  1045. MDTuple *pMDProperties = EmitDxilShaderProperties();
  1046. MDTuple *pMDSignatures = m_pMDHelper->EmitDxilSignatures(*m_EntrySignature);
  1047. MDTuple *pMDResources = EmitDxilResources();
  1048. if (pMDResources)
  1049. m_pMDHelper->EmitDxilResources(pMDResources);
  1050. m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
  1051. if (!m_pSM->IsCS() &&
  1052. (m_ValMajor > 1 || (m_ValMajor == 1 && m_ValMinor >= 1))) {
  1053. m_pMDHelper->EmitDxilViewIdState(GetViewIdState());
  1054. }
  1055. EmitLLVMUsed();
  1056. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources, pMDProperties);
  1057. vector<MDNode *> Entries;
  1058. Entries.emplace_back(pEntry);
  1059. m_pMDHelper->EmitDxilEntryPoints(Entries);
  1060. if (!m_RootSignature->IsEmpty()) {
  1061. m_pMDHelper->EmitRootSignature(*m_RootSignature.get());
  1062. }
  1063. if (m_pSM->IsLib()) {
  1064. EmitDxilResourcesLinkInfo();
  1065. NamedMDNode *fnProps = m_pModule->getOrInsertNamedMetadata(
  1066. DxilMDHelper::kDxilFunctionPropertiesMDName);
  1067. for (auto &&pair : m_DxilFunctionPropsMap) {
  1068. const hlsl::DxilFunctionProps *props = pair.second.get();
  1069. MDTuple *pProps = m_pMDHelper->EmitDxilFunctionProps(props, pair.first);
  1070. fnProps->addOperand(pProps);
  1071. }
  1072. NamedMDNode *entrySigs = m_pModule->getOrInsertNamedMetadata(
  1073. DxilMDHelper::kDxilEntrySignaturesMDName);
  1074. for (auto &&pair : m_DxilEntrySignatureMap) {
  1075. Function *F = pair.first;
  1076. DxilEntrySignature *Sig = pair.second.get();
  1077. MDTuple *pSig = m_pMDHelper->EmitDxilSignatures(*Sig);
  1078. entrySigs->addOperand(
  1079. MDTuple::get(m_Ctx, {ValueAsMetadata::get(F), pSig}));
  1080. }
  1081. }
  1082. }
  1083. bool DxilModule::IsKnownNamedMetaData(llvm::NamedMDNode &Node) {
  1084. return DxilMDHelper::IsKnownNamedMetaData(Node);
  1085. }
  1086. void DxilModule::LoadDxilMetadata() {
  1087. m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
  1088. m_pMDHelper->LoadValidatorVersion(m_ValMajor, m_ValMinor);
  1089. const ShaderModel *loadedModule;
  1090. m_pMDHelper->LoadDxilShaderModel(loadedModule);
  1091. SetShaderModel(loadedModule);
  1092. DXASSERT(m_EntrySignature != nullptr, "else SetShaderModel didn't create entry signature");
  1093. const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
  1094. IFTBOOL(pEntries->getNumOperands() == 1, DXC_E_INCORRECT_DXIL_METADATA);
  1095. Function *pEntryFunc;
  1096. string EntryName;
  1097. const llvm::MDOperand *pSignatures, *pResources, *pProperties;
  1098. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0), pEntryFunc, EntryName, pSignatures, pResources, pProperties);
  1099. SetEntryFunction(pEntryFunc);
  1100. SetEntryFunctionName(EntryName);
  1101. LoadDxilShaderProperties(*pProperties);
  1102. m_pMDHelper->LoadDxilSignatures(*pSignatures, *m_EntrySignature);
  1103. LoadDxilResources(*pResources);
  1104. m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
  1105. m_pMDHelper->LoadRootSignature(*m_RootSignature.get());
  1106. m_pMDHelper->LoadDxilViewIdState(*m_pViewIdState.get());
  1107. if (loadedModule->IsLib()) {
  1108. LoadDxilResourcesLinkInfo();
  1109. NamedMDNode *fnProps = m_pModule->getNamedMetadata(
  1110. DxilMDHelper::kDxilFunctionPropertiesMDName);
  1111. size_t propIdx = 0;
  1112. while (propIdx < fnProps->getNumOperands()) {
  1113. MDTuple *pProps = dyn_cast<MDTuple>(fnProps->getOperand(propIdx++));
  1114. std::unique_ptr<hlsl::DxilFunctionProps> props =
  1115. llvm::make_unique<hlsl::DxilFunctionProps>();
  1116. Function *F = m_pMDHelper->LoadDxilFunctionProps(pProps, props.get());
  1117. m_DxilFunctionPropsMap[F] = std::move(props);
  1118. }
  1119. NamedMDNode *entrySigs = m_pModule->getOrInsertNamedMetadata(
  1120. DxilMDHelper::kDxilEntrySignaturesMDName);
  1121. size_t sigIdx = 0;
  1122. while (sigIdx < entrySigs->getNumOperands()) {
  1123. MDTuple *pSig = dyn_cast<MDTuple>(entrySigs->getOperand(sigIdx++));
  1124. unsigned idx = 0;
  1125. Function *F = dyn_cast<Function>(
  1126. dyn_cast<ValueAsMetadata>(pSig->getOperand(idx++))->getValue());
  1127. // Entry must have props.
  1128. IFTBOOL(m_DxilFunctionPropsMap.count(F), DXC_E_INCORRECT_DXIL_METADATA);
  1129. DXIL::ShaderKind shaderKind = m_DxilFunctionPropsMap[F]->shaderKind;
  1130. std::unique_ptr<hlsl::DxilEntrySignature> Sig =
  1131. llvm::make_unique<hlsl::DxilEntrySignature>(shaderKind);
  1132. m_pMDHelper->LoadDxilSignatures(pSig->getOperand(idx), *Sig);
  1133. m_DxilEntrySignatureMap[F] = std::move(Sig);
  1134. }
  1135. }
  1136. }
  1137. MDTuple *DxilModule::EmitDxilResources() {
  1138. // Emit SRV records.
  1139. MDTuple *pTupleSRVs = nullptr;
  1140. if (!m_SRVs.empty()) {
  1141. vector<Metadata *> MDVals;
  1142. for (size_t i = 0; i < m_SRVs.size(); i++) {
  1143. MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
  1144. }
  1145. pTupleSRVs = MDNode::get(m_Ctx, MDVals);
  1146. }
  1147. // Emit UAV records.
  1148. MDTuple *pTupleUAVs = nullptr;
  1149. if (!m_UAVs.empty()) {
  1150. vector<Metadata *> MDVals;
  1151. for (size_t i = 0; i < m_UAVs.size(); i++) {
  1152. MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
  1153. }
  1154. pTupleUAVs = MDNode::get(m_Ctx, MDVals);
  1155. }
  1156. // Emit CBuffer records.
  1157. MDTuple *pTupleCBuffers = nullptr;
  1158. if (!m_CBuffers.empty()) {
  1159. vector<Metadata *> MDVals;
  1160. for (size_t i = 0; i < m_CBuffers.size(); i++) {
  1161. MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
  1162. }
  1163. pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
  1164. }
  1165. // Emit Sampler records.
  1166. MDTuple *pTupleSamplers = nullptr;
  1167. if (!m_Samplers.empty()) {
  1168. vector<Metadata *> MDVals;
  1169. for (size_t i = 0; i < m_Samplers.size(); i++) {
  1170. MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
  1171. }
  1172. pTupleSamplers = MDNode::get(m_Ctx, MDVals);
  1173. }
  1174. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr || pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  1175. return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs, pTupleCBuffers, pTupleSamplers);
  1176. } else {
  1177. return nullptr;
  1178. }
  1179. }
  1180. void DxilModule::ReEmitDxilResources() {
  1181. MDTuple *pNewResource = EmitDxilResources();
  1182. m_pMDHelper->UpdateDxilResources(pNewResource);
  1183. const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
  1184. IFTBOOL(pEntries->getNumOperands() == 1, DXC_E_INCORRECT_DXIL_METADATA);
  1185. Function *pEntryFunc;
  1186. string EntryName;
  1187. const llvm::MDOperand *pSignatures, *pResources, *pProperties;
  1188. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0), pEntryFunc, EntryName, pSignatures, pResources, pProperties);
  1189. MDTuple *pMDSignatures = m_pMDHelper->EmitDxilSignatures(*m_EntrySignature);
  1190. MDTuple *pMDProperties = EmitDxilShaderProperties();
  1191. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(pEntryFunc, EntryName, pMDSignatures, pNewResource, pMDProperties);
  1192. vector<MDNode *> Entries;
  1193. Entries.emplace_back(pEntry);
  1194. m_pMDHelper->UpdateDxilEntryPoints(Entries);
  1195. }
  1196. void DxilModule::LoadDxilResources(const llvm::MDOperand &MDO) {
  1197. if (MDO.get() == nullptr)
  1198. return;
  1199. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  1200. m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
  1201. // Load SRV records.
  1202. if (pSRVs != nullptr) {
  1203. for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
  1204. unique_ptr<DxilResource> pSRV(new DxilResource);
  1205. m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
  1206. AddSRV(std::move(pSRV));
  1207. }
  1208. }
  1209. // Load UAV records.
  1210. if (pUAVs != nullptr) {
  1211. for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
  1212. unique_ptr<DxilResource> pUAV(new DxilResource);
  1213. m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
  1214. AddUAV(std::move(pUAV));
  1215. }
  1216. }
  1217. // Load CBuffer records.
  1218. if (pCBuffers != nullptr) {
  1219. for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
  1220. unique_ptr<DxilCBuffer> pCB(new DxilCBuffer);
  1221. m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
  1222. AddCBuffer(std::move(pCB));
  1223. }
  1224. }
  1225. // Load Sampler records.
  1226. if (pSamplers != nullptr) {
  1227. for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
  1228. unique_ptr<DxilSampler> pSampler(new DxilSampler);
  1229. m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
  1230. AddSampler(std::move(pSampler));
  1231. }
  1232. }
  1233. }
  1234. static MDTuple *CreateResourcesLinkInfo(std::vector<DxilModule::ResourceLinkInfo> &LinkInfoList,
  1235. unsigned size, LLVMContext &Ctx) {
  1236. DXASSERT(size == LinkInfoList.size(), "link info size must match resource size");
  1237. if (LinkInfoList.empty())
  1238. return nullptr;
  1239. vector<Metadata *> MDVals;
  1240. for (size_t i = 0; i < size; i++) {
  1241. MDVals.emplace_back(ValueAsMetadata::get(LinkInfoList[i].ResRangeID));
  1242. }
  1243. return MDNode::get(Ctx, MDVals);
  1244. }
  1245. void DxilModule::EmitDxilResourcesLinkInfo() {
  1246. // Emit SRV base records.
  1247. MDTuple *pTupleSRVs =
  1248. CreateResourcesLinkInfo(m_SRVsLinkInfo, m_SRVs.size(), m_Ctx);
  1249. // Emit UAV base records.
  1250. MDTuple *pTupleUAVs =
  1251. CreateResourcesLinkInfo(m_UAVsLinkInfo, m_UAVs.size(), m_Ctx);
  1252. // Emit CBuffer base records.
  1253. MDTuple *pTupleCBuffers =
  1254. CreateResourcesLinkInfo(m_CBuffersLinkInfo, m_CBuffers.size(), m_Ctx);
  1255. // Emit Sampler records.
  1256. MDTuple *pTupleSamplers =
  1257. CreateResourcesLinkInfo(m_SamplersLinkInfo, m_Samplers.size(), m_Ctx);
  1258. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr ||
  1259. pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  1260. m_pMDHelper->EmitDxilResourceLinkInfoTuple(pTupleSRVs, pTupleUAVs,
  1261. pTupleCBuffers, pTupleSamplers);
  1262. }
  1263. }
  1264. static void
  1265. LoadResourcesLinkInfo(const llvm::MDTuple *pMD,
  1266. std::vector<DxilModule::ResourceLinkInfo> &LinkInfoList,
  1267. unsigned size, DxilMDHelper *pMDHelper) {
  1268. if (!pMD) {
  1269. IFTBOOL(size == 0, DXC_E_INCORRECT_DXIL_METADATA);
  1270. return;
  1271. }
  1272. unsigned operandSize = pMD->getNumOperands();
  1273. IFTBOOL(operandSize == size, DXC_E_INCORRECT_DXIL_METADATA);
  1274. for (unsigned i = 0; i < operandSize; i++) {
  1275. Constant *rangeID =
  1276. dyn_cast<Constant>(pMDHelper->ValueMDToValue(pMD->getOperand(i)));
  1277. LinkInfoList.emplace_back(DxilModule::ResourceLinkInfo{rangeID});
  1278. }
  1279. }
  1280. void DxilModule::LoadDxilResourcesLinkInfo() {
  1281. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  1282. m_pMDHelper->LoadDxilResourceLinkInfoTuple(pSRVs, pUAVs, pCBuffers,
  1283. pSamplers);
  1284. // Load SRV base records.
  1285. LoadResourcesLinkInfo(pSRVs, m_SRVsLinkInfo, m_SRVs.size(),
  1286. m_pMDHelper.get());
  1287. // Load UAV base records.
  1288. LoadResourcesLinkInfo(pUAVs, m_UAVsLinkInfo, m_UAVs.size(),
  1289. m_pMDHelper.get());
  1290. // Load CBuffer records.
  1291. LoadResourcesLinkInfo(pCBuffers, m_CBuffersLinkInfo, m_CBuffers.size(),
  1292. m_pMDHelper.get());
  1293. // Load Sampler records.
  1294. LoadResourcesLinkInfo(pSamplers, m_SamplersLinkInfo, m_Samplers.size(),
  1295. m_pMDHelper.get());
  1296. }
  1297. MDTuple *DxilModule::EmitDxilShaderProperties() {
  1298. vector<Metadata *> MDVals;
  1299. // DXIL shader flags.
  1300. uint64_t Flags = m_ShaderFlags.GetShaderFlagsRaw();
  1301. if (Flags != 0) {
  1302. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilShaderFlagsTag));
  1303. MDVals.emplace_back(m_pMDHelper->Uint64ToConstMD(Flags));
  1304. }
  1305. // Compute shader.
  1306. if (m_pSM->IsCS()) {
  1307. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilNumThreadsTag));
  1308. vector<Metadata *> NumThreadVals;
  1309. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[0]));
  1310. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[1]));
  1311. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[2]));
  1312. MDVals.emplace_back(MDNode::get(m_Ctx, NumThreadVals));
  1313. }
  1314. // Geometry shader.
  1315. if (m_pSM->IsGS()) {
  1316. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilGSStateTag));
  1317. MDTuple *pMDTuple = m_pMDHelper->EmitDxilGSState(m_InputPrimitive,
  1318. m_MaxVertexCount,
  1319. GetActiveStreamMask(),
  1320. m_StreamPrimitiveTopology,
  1321. m_NumGSInstances);
  1322. MDVals.emplace_back(pMDTuple);
  1323. }
  1324. // Domain shader.
  1325. if (m_pSM->IsDS()) {
  1326. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilDSStateTag));
  1327. MDTuple *pMDTuple = m_pMDHelper->EmitDxilDSState(m_TessellatorDomain,
  1328. m_InputControlPointCount);
  1329. MDVals.emplace_back(pMDTuple);
  1330. }
  1331. // Hull shader.
  1332. if (m_pSM->IsHS()) {
  1333. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilHSStateTag));
  1334. MDTuple *pMDTuple = m_pMDHelper->EmitDxilHSState(m_pPatchConstantFunc,
  1335. m_InputControlPointCount,
  1336. m_OutputControlPointCount,
  1337. m_TessellatorDomain,
  1338. m_TessellatorPartitioning,
  1339. m_TessellatorOutputPrimitive,
  1340. m_MaxTessellationFactor);
  1341. MDVals.emplace_back(pMDTuple);
  1342. }
  1343. if (!MDVals.empty())
  1344. return MDNode::get(m_Ctx, MDVals);
  1345. else
  1346. return nullptr;
  1347. }
  1348. void DxilModule::LoadDxilShaderProperties(const MDOperand &MDO) {
  1349. if (MDO.get() == nullptr)
  1350. return;
  1351. const MDTuple *pTupleMD = dyn_cast<MDTuple>(MDO.get());
  1352. IFTBOOL(pTupleMD != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  1353. IFTBOOL((pTupleMD->getNumOperands() & 0x1) == 0, DXC_E_INCORRECT_DXIL_METADATA);
  1354. for (unsigned iNode = 0; iNode < pTupleMD->getNumOperands(); iNode += 2) {
  1355. unsigned Tag = DxilMDHelper::ConstMDToUint32(pTupleMD->getOperand(iNode));
  1356. const MDOperand &MDO = pTupleMD->getOperand(iNode + 1);
  1357. IFTBOOL(MDO.get() != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  1358. switch (Tag) {
  1359. case DxilMDHelper::kDxilShaderFlagsTag:
  1360. m_ShaderFlags.SetShaderFlagsRaw(DxilMDHelper::ConstMDToUint64(MDO));
  1361. break;
  1362. case DxilMDHelper::kDxilNumThreadsTag: {
  1363. MDNode *pNode = cast<MDNode>(MDO.get());
  1364. m_NumThreads[0] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(0));
  1365. m_NumThreads[1] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(1));
  1366. m_NumThreads[2] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(2));
  1367. break;
  1368. }
  1369. case DxilMDHelper::kDxilGSStateTag: {
  1370. m_pMDHelper->LoadDxilGSState(MDO, m_InputPrimitive, m_MaxVertexCount, m_ActiveStreamMask,
  1371. m_StreamPrimitiveTopology, m_NumGSInstances);
  1372. break;
  1373. }
  1374. case DxilMDHelper::kDxilDSStateTag:
  1375. m_pMDHelper->LoadDxilDSState(MDO, m_TessellatorDomain, m_InputControlPointCount);
  1376. break;
  1377. case DxilMDHelper::kDxilHSStateTag:
  1378. m_pMDHelper->LoadDxilHSState(MDO,
  1379. m_pPatchConstantFunc,
  1380. m_InputControlPointCount,
  1381. m_OutputControlPointCount,
  1382. m_TessellatorDomain,
  1383. m_TessellatorPartitioning,
  1384. m_TessellatorOutputPrimitive,
  1385. m_MaxTessellationFactor);
  1386. break;
  1387. default:
  1388. DXASSERT(false, "Unknown extended shader properties tag");
  1389. break;
  1390. }
  1391. }
  1392. }
  1393. void DxilModule::StripDebugRelatedCode() {
  1394. // Remove all users of global resources.
  1395. for (GlobalVariable &GV : m_pModule->globals()) {
  1396. if (GV.hasInternalLinkage())
  1397. continue;
  1398. if (GV.getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace)
  1399. continue;
  1400. for (auto git = GV.user_begin(); git != GV.user_end();) {
  1401. User *U = *(git++);
  1402. // Try to remove load of GV.
  1403. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1404. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1405. Instruction *LIUser = cast<Instruction>(*(it++));
  1406. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1407. Value *Ptr = SI->getPointerOperand();
  1408. SI->eraseFromParent();
  1409. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1410. if (Ptr->user_empty())
  1411. PtrInst->eraseFromParent();
  1412. }
  1413. }
  1414. }
  1415. if (LI->user_empty())
  1416. LI->eraseFromParent();
  1417. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  1418. for (auto GEPIt = GEP->user_begin(); GEPIt != GEP->user_end();) {
  1419. User *GEPU = *(GEPIt++);
  1420. // Try to remove load of GEP.
  1421. if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
  1422. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1423. Instruction *LIUser = cast<Instruction>(*(it++));
  1424. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1425. Value *Ptr = SI->getPointerOperand();
  1426. SI->eraseFromParent();
  1427. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1428. if (Ptr->user_empty())
  1429. PtrInst->eraseFromParent();
  1430. }
  1431. }
  1432. if (LI->user_empty())
  1433. LI->eraseFromParent();
  1434. }
  1435. }
  1436. }
  1437. if (GEP->user_empty())
  1438. GEP->eraseFromParent();
  1439. }
  1440. }
  1441. }
  1442. }
  1443. DebugInfoFinder &DxilModule::GetOrCreateDebugInfoFinder() {
  1444. if (m_pDebugInfoFinder == nullptr) {
  1445. m_pDebugInfoFinder = std::make_unique<llvm::DebugInfoFinder>();
  1446. m_pDebugInfoFinder->processModule(*m_pModule);
  1447. }
  1448. return *m_pDebugInfoFinder;
  1449. }
  1450. hlsl::DxilModule *hlsl::DxilModule::TryGetDxilModule(llvm::Module *pModule) {
  1451. LLVMContext &Ctx = pModule->getContext();
  1452. std::string diagStr;
  1453. raw_string_ostream diagStream(diagStr);
  1454. hlsl::DxilModule *pDxilModule = nullptr;
  1455. // TODO: add detail error in DxilMDHelper.
  1456. try {
  1457. pDxilModule = &pModule->GetOrCreateDxilModule();
  1458. } catch (const ::hlsl::Exception &hlslException) {
  1459. diagStream << "load dxil metadata failed -";
  1460. try {
  1461. const char *msg = hlslException.what();
  1462. if (msg == nullptr || *msg == '\0')
  1463. diagStream << " error code " << hlslException.hr << "\n";
  1464. else
  1465. diagStream << msg;
  1466. } catch (...) {
  1467. diagStream << " unable to retrieve error message.\n";
  1468. }
  1469. Ctx.diagnose(DxilErrorDiagnosticInfo(diagStream.str().c_str()));
  1470. } catch (...) {
  1471. Ctx.diagnose(DxilErrorDiagnosticInfo("load dxil metadata failed - unknown error.\n"));
  1472. }
  1473. return pDxilModule;
  1474. }
  1475. // Check if the instruction has fast math flags configured to indicate
  1476. // the instruction is precise.
  1477. // Precise fast math flags means none of the fast math flags are set.
  1478. bool DxilModule::HasPreciseFastMathFlags(const Instruction *inst) {
  1479. return isa<FPMathOperator>(inst) && !inst->getFastMathFlags().any();
  1480. }
  1481. // Set fast math flags configured to indicate the instruction is precise.
  1482. void DxilModule::SetPreciseFastMathFlags(llvm::Instruction *inst) {
  1483. assert(isa<FPMathOperator>(inst));
  1484. inst->copyFastMathFlags(FastMathFlags());
  1485. }
  1486. // True if fast math flags are preserved across serialization/deserialization
  1487. // of the dxil module.
  1488. //
  1489. // We need to check for this when querying fast math flags for preciseness
  1490. // otherwise we will be overly conservative by reporting instructions precise
  1491. // because their fast math flags were not preserved.
  1492. //
  1493. // Currently we restrict it to the instruction types that have fast math
  1494. // preserved in the bitcode. We can expand this by converting fast math
  1495. // flags to dx.precise metadata during serialization and back to fast
  1496. // math flags during deserialization.
  1497. bool DxilModule::PreservesFastMathFlags(const llvm::Instruction *inst) {
  1498. return
  1499. isa<FPMathOperator>(inst) && (isa<BinaryOperator>(inst) || isa<FCmpInst>(inst));
  1500. }
  1501. bool DxilModule::IsPrecise(const Instruction *inst) const {
  1502. if (m_ShaderFlags.GetDisableMathRefactoring())
  1503. return true;
  1504. else if (DxilMDHelper::IsMarkedPrecise(inst))
  1505. return true;
  1506. else if (PreservesFastMathFlags(inst))
  1507. return HasPreciseFastMathFlags(inst);
  1508. else
  1509. return false;
  1510. }
  1511. } // namespace hlsl
  1512. namespace llvm {
  1513. hlsl::DxilModule &Module::GetOrCreateDxilModule(bool skipInit) {
  1514. std::unique_ptr<hlsl::DxilModule> M;
  1515. if (!HasDxilModule()) {
  1516. M = std::make_unique<hlsl::DxilModule>(this);
  1517. if (!skipInit) {
  1518. M->LoadDxilMetadata();
  1519. }
  1520. SetDxilModule(M.release());
  1521. }
  1522. return GetDxilModule();
  1523. }
  1524. void Module::ResetDxilModule() {
  1525. if (HasDxilModule()) {
  1526. delete TheDxilModule;
  1527. TheDxilModule = nullptr;
  1528. }
  1529. }
  1530. }