HLModule.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // HLModule.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. // HighLevel DX IR module. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/HLSL/DxilOperations.h"
  12. #include "dxc/HLSL/DxilShaderModel.h"
  13. #include "dxc/HLSL/DxilCBuffer.h"
  14. #include "dxc/HLSL/HLModule.h"
  15. #include "dxc/HLSL/DxilTypeSystem.h"
  16. #include "dxc/HLSL/DxilRootSignature.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/IR/Constants.h"
  19. #include "llvm/IR/Function.h"
  20. #include "llvm/IR/IRBuilder.h"
  21. #include "llvm/IR/LLVMContext.h"
  22. #include "llvm/IR/Metadata.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/IR/DebugInfo.h"
  25. #include "llvm/IR/DIBuilder.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "llvm/IR/GetElementPtrTypeIterator.h"
  28. using namespace llvm;
  29. using std::string;
  30. using std::vector;
  31. using std::unique_ptr;
  32. namespace hlsl {
  33. static void
  34. CreateSignatures(const ShaderModel *pSM,
  35. std::unique_ptr<DxilSignature> &InputSignature,
  36. std::unique_ptr<DxilSignature> &OutputSignature,
  37. std::unique_ptr<DxilSignature> &PatchConstantSignature,
  38. std::unique_ptr<RootSignatureHandle> &RootSignature) {
  39. DXIL::ShaderKind shaderKind = pSM->GetKind();
  40. InputSignature = llvm::make_unique<DxilSignature>(shaderKind, DxilSignature::Kind::Input);
  41. OutputSignature = llvm::make_unique<DxilSignature>(shaderKind, DxilSignature::Kind::Output);
  42. PatchConstantSignature = llvm::make_unique<DxilSignature>(shaderKind, DxilSignature::Kind::PatchConstant);
  43. RootSignature = llvm::make_unique<RootSignatureHandle>();
  44. }
  45. //------------------------------------------------------------------------------
  46. //
  47. // HLModule methods.
  48. //
  49. HLModule::HLModule(Module *pModule)
  50. : m_Ctx(pModule->getContext())
  51. , m_pModule(pModule)
  52. , m_pEntryFunc(nullptr)
  53. , m_EntryName("")
  54. , m_pMDHelper(llvm::make_unique<DxilMDHelper>(
  55. pModule, llvm::make_unique<HLExtraPropertyHelper>(pModule)))
  56. , m_pDebugInfoFinder(nullptr)
  57. , m_pSM(nullptr)
  58. , m_DxilMajor(1)
  59. , m_DxilMinor(0)
  60. , m_pOP(llvm::make_unique<OP>(pModule->getContext(), pModule))
  61. , m_pTypeSystem(llvm::make_unique<DxilTypeSystem>(pModule)) {
  62. DXASSERT_NOMSG(m_pModule != nullptr);
  63. // Pin LLVM dump methods. TODO: make debug-only.
  64. void (__thiscall Module::*pfnModuleDump)() const = &Module::dump;
  65. void (__thiscall Type::*pfnTypeDump)() const = &Type::dump;
  66. m_pUnused = (char *)&pfnModuleDump - (char *)&pfnTypeDump;
  67. }
  68. HLModule::~HLModule() {
  69. }
  70. LLVMContext &HLModule::GetCtx() const { return m_Ctx; }
  71. Module *HLModule::GetModule() const { return m_pModule; }
  72. OP *HLModule::GetOP() const { return m_pOP.get(); }
  73. void HLModule::SetShaderModel(const ShaderModel *pSM) {
  74. DXASSERT(m_pSM == nullptr, "shader model must not change for the module");
  75. m_pSM = pSM;
  76. m_pMDHelper->SetShaderModel(m_pSM);
  77. CreateSignatures(m_pSM, m_InputSignature, m_OutputSignature, m_PatchConstantSignature, m_RootSignature);
  78. }
  79. const ShaderModel *HLModule::GetShaderModel() const {
  80. return m_pSM;
  81. }
  82. uint32_t HLOptions::GetHLOptionsRaw() const {
  83. union Cast {
  84. Cast(const HLOptions &options) {
  85. hlOptions = options;
  86. }
  87. HLOptions hlOptions;
  88. uint32_t rawData;
  89. };
  90. static_assert(sizeof(uint32_t) == sizeof(HLOptions),
  91. "size must match to make sure no undefined bits when cast");
  92. Cast rawCast(*this);
  93. return rawCast.rawData;
  94. }
  95. void HLOptions::SetHLOptionsRaw(uint32_t data) {
  96. union Cast {
  97. Cast(uint32_t data) {
  98. rawData = data;
  99. }
  100. HLOptions hlOptions;
  101. uint64_t rawData;
  102. };
  103. Cast rawCast(data);
  104. *this = rawCast.hlOptions;
  105. }
  106. void HLModule::SetHLOptions(HLOptions &opts) {
  107. m_Options = opts;
  108. }
  109. const HLOptions &HLModule::GetHLOptions() const {
  110. return m_Options;
  111. }
  112. Function *HLModule::GetEntryFunction() const {
  113. return m_pEntryFunc;
  114. }
  115. void HLModule::SetEntryFunction(Function *pEntryFunc) {
  116. m_pEntryFunc = pEntryFunc;
  117. }
  118. const string &HLModule::GetEntryFunctionName() const { return m_EntryName; }
  119. void HLModule::SetEntryFunctionName(const string &name) { m_EntryName = name; }
  120. template<typename T> unsigned
  121. HLModule::AddResource(vector<unique_ptr<T> > &Vec, unique_ptr<T> pRes) {
  122. DXASSERT_NOMSG((unsigned)Vec.size() < UINT_MAX);
  123. unsigned Id = (unsigned)Vec.size();
  124. Vec.emplace_back(std::move(pRes));
  125. return Id;
  126. }
  127. unsigned HLModule::AddCBuffer(unique_ptr<DxilCBuffer> pCBuffer) {
  128. return AddResource<DxilCBuffer>(m_CBuffers, std::move(pCBuffer));
  129. }
  130. DxilCBuffer &HLModule::GetCBuffer(unsigned idx) {
  131. return *m_CBuffers[idx];
  132. }
  133. const DxilCBuffer &HLModule::GetCBuffer(unsigned idx) const {
  134. return *m_CBuffers[idx];
  135. }
  136. const vector<unique_ptr<DxilCBuffer> > &HLModule::GetCBuffers() const {
  137. return m_CBuffers;
  138. }
  139. unsigned HLModule::AddSampler(unique_ptr<DxilSampler> pSampler) {
  140. return AddResource<DxilSampler>(m_Samplers, std::move(pSampler));
  141. }
  142. DxilSampler &HLModule::GetSampler(unsigned idx) {
  143. return *m_Samplers[idx];
  144. }
  145. const DxilSampler &HLModule::GetSampler(unsigned idx) const {
  146. return *m_Samplers[idx];
  147. }
  148. const vector<unique_ptr<DxilSampler> > &HLModule::GetSamplers() const {
  149. return m_Samplers;
  150. }
  151. unsigned HLModule::AddSRV(unique_ptr<HLResource> pSRV) {
  152. return AddResource<HLResource>(m_SRVs, std::move(pSRV));
  153. }
  154. HLResource &HLModule::GetSRV(unsigned idx) {
  155. return *m_SRVs[idx];
  156. }
  157. const HLResource &HLModule::GetSRV(unsigned idx) const {
  158. return *m_SRVs[idx];
  159. }
  160. const vector<unique_ptr<HLResource> > &HLModule::GetSRVs() const {
  161. return m_SRVs;
  162. }
  163. unsigned HLModule::AddUAV(unique_ptr<HLResource> pUAV) {
  164. return AddResource<HLResource>(m_UAVs, std::move(pUAV));
  165. }
  166. HLResource &HLModule::GetUAV(unsigned idx) {
  167. return *m_UAVs[idx];
  168. }
  169. const HLResource &HLModule::GetUAV(unsigned idx) const {
  170. return *m_UAVs[idx];
  171. }
  172. const vector<unique_ptr<HLResource> > &HLModule::GetUAVs() const {
  173. return m_UAVs;
  174. }
  175. void HLModule::RemoveFunction(llvm::Function *F) {
  176. DXASSERT_NOMSG(F != nullptr);
  177. m_HLFunctionPropsMap.erase(F);
  178. if (m_pTypeSystem.get()->GetFunctionAnnotation(F))
  179. m_pTypeSystem.get()->EraseFunctionAnnotation(F);
  180. m_pOP->RemoveFunction(F);
  181. }
  182. template <typename TResource>
  183. bool RemoveResource(std::vector<std::unique_ptr<TResource>> &vec,
  184. GlobalVariable *pVariable) {
  185. for (auto p = vec.begin(), e = vec.end(); p != e; ++p) {
  186. if ((*p)->GetGlobalSymbol() == pVariable) {
  187. p = vec.erase(p);
  188. // Update ID.
  189. for (e = vec.end();p != e; ++p) {
  190. unsigned ID = (*p)->GetID()-1;
  191. (*p)->SetID(ID);
  192. }
  193. return true;
  194. }
  195. }
  196. return false;
  197. }
  198. bool RemoveResource(std::vector<GlobalVariable *> &vec,
  199. llvm::GlobalVariable *pVariable) {
  200. for (auto p = vec.begin(), e = vec.end(); p != e; ++p) {
  201. if (*p == pVariable) {
  202. vec.erase(p);
  203. return true;
  204. }
  205. }
  206. return false;
  207. }
  208. void HLModule::RemoveGlobal(llvm::GlobalVariable *GV) {
  209. RemoveResources(&GV, 1);
  210. }
  211. void HLModule::RemoveResources(llvm::GlobalVariable **ppVariables,
  212. unsigned count) {
  213. DXASSERT_NOMSG(count == 0 || ppVariables != nullptr);
  214. unsigned resourcesRemoved = count;
  215. for (unsigned i = 0; i < count; ++i) {
  216. GlobalVariable *pVariable = ppVariables[i];
  217. // This could be considerably faster - check variable type to see which
  218. // resource type this is rather than scanning all lists, and look for
  219. // usage and removal patterns.
  220. if (RemoveResource(m_CBuffers, pVariable))
  221. continue;
  222. if (RemoveResource(m_SRVs, pVariable))
  223. continue;
  224. if (RemoveResource(m_UAVs, pVariable))
  225. continue;
  226. if (RemoveResource(m_Samplers, pVariable))
  227. continue;
  228. // TODO: do m_TGSMVariables and m_StreamOutputs need maintenance?
  229. --resourcesRemoved; // Global variable is not a resource?
  230. }
  231. }
  232. HLModule::tgsm_iterator HLModule::tgsm_begin() {
  233. return m_TGSMVariables.begin();
  234. }
  235. HLModule::tgsm_iterator HLModule::tgsm_end() {
  236. return m_TGSMVariables.end();
  237. }
  238. void HLModule::AddGroupSharedVariable(GlobalVariable *GV) {
  239. m_TGSMVariables.emplace_back(GV);
  240. }
  241. DxilSignature &HLModule::GetInputSignature() {
  242. return *m_InputSignature;
  243. }
  244. DxilSignature &HLModule::GetOutputSignature() {
  245. return *m_OutputSignature;
  246. }
  247. DxilSignature &HLModule::GetPatchConstantSignature() {
  248. return *m_PatchConstantSignature;
  249. }
  250. RootSignatureHandle &HLModule::GetRootSignature() {
  251. return *m_RootSignature;
  252. }
  253. DxilTypeSystem &HLModule::GetTypeSystem() {
  254. return *m_pTypeSystem;
  255. }
  256. DxilSignature *HLModule::ReleaseInputSignature() {
  257. return m_InputSignature.release();
  258. }
  259. DxilSignature *HLModule::ReleaseOutputSignature() {
  260. return m_OutputSignature.release();
  261. }
  262. DxilSignature *HLModule::ReleasePatchConstantSignature() {
  263. return m_PatchConstantSignature.release();
  264. }
  265. DxilTypeSystem *HLModule::ReleaseTypeSystem() {
  266. return m_pTypeSystem.release();
  267. }
  268. hlsl::OP *HLModule::ReleaseOP() {
  269. return m_pOP.release();
  270. }
  271. RootSignatureHandle *HLModule::ReleaseRootSignature() {
  272. return m_RootSignature.release();
  273. }
  274. void HLModule::EmitLLVMUsed() {
  275. if (m_LLVMUsed.empty())
  276. return;
  277. vector<llvm::Constant*> GVs;
  278. GVs.resize(m_LLVMUsed.size());
  279. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  280. GVs[i] = ConstantExpr::getAddrSpaceCast(cast<llvm::Constant>(&*m_LLVMUsed[i]), Type::getInt8PtrTy(m_Ctx));
  281. }
  282. ArrayType *pATy = ArrayType::get(Type::getInt8PtrTy(m_Ctx), GVs.size());
  283. GlobalVariable *pGV = new GlobalVariable(*m_pModule, pATy, false,
  284. GlobalValue::AppendingLinkage,
  285. ConstantArray::get(pATy, GVs),
  286. "llvm.used");
  287. pGV->setSection("llvm.metadata");
  288. }
  289. vector<GlobalVariable* > &HLModule::GetLLVMUsed() {
  290. return m_LLVMUsed;
  291. }
  292. bool HLModule::HasHLFunctionProps(llvm::Function *F) {
  293. return m_HLFunctionPropsMap.find(F) != m_HLFunctionPropsMap.end();
  294. }
  295. HLFunctionProps &HLModule::GetHLFunctionProps(llvm::Function *F) {
  296. return *m_HLFunctionPropsMap[F];
  297. }
  298. void HLModule::AddHLFunctionProps(llvm::Function *F, std::unique_ptr<HLFunctionProps> &info) {
  299. DXASSERT(m_HLFunctionPropsMap.count(F) == 0, "F already in map, info will be overwritten");
  300. m_HLFunctionPropsMap[F] = std::move(info);
  301. }
  302. DxilFunctionAnnotation *HLModule::GetFunctionAnnotation(llvm::Function *F) {
  303. return m_pTypeSystem->GetFunctionAnnotation(F);
  304. }
  305. DxilFunctionAnnotation *HLModule::AddFunctionAnnotation(llvm::Function *F) {
  306. DXASSERT(m_pTypeSystem->GetFunctionAnnotation(F)==nullptr, "function annotation already exist");
  307. return m_pTypeSystem->AddFunctionAnnotation(F);
  308. }
  309. void HLModule::AddResourceTypeAnnotation(llvm::Type *Ty,
  310. DXIL::ResourceClass resClass,
  311. DXIL::ResourceKind kind) {
  312. if (m_ResTypeAnnotation.count(Ty) == 0) {
  313. m_ResTypeAnnotation.emplace(Ty, std::make_pair(resClass, kind));
  314. } else {
  315. DXASSERT(resClass == m_ResTypeAnnotation[Ty].first, "resClass mismatch");
  316. DXASSERT(kind == m_ResTypeAnnotation[Ty].second, "kind mismatch");
  317. }
  318. }
  319. DXIL::ResourceClass HLModule::GetResourceClass(llvm::Type *Ty) {
  320. if (m_ResTypeAnnotation.count(Ty) > 0) {
  321. return m_ResTypeAnnotation[Ty].first;
  322. } else {
  323. return DXIL::ResourceClass::Invalid;
  324. }
  325. }
  326. DXIL::ResourceKind HLModule::GetResourceKind(llvm::Type *Ty) {
  327. if (m_ResTypeAnnotation.count(Ty) > 0) {
  328. return m_ResTypeAnnotation[Ty].second;
  329. } else {
  330. return DXIL::ResourceKind::Invalid;
  331. }
  332. }
  333. static unsigned GetIntAt(MDTuple *tuple, unsigned idx) {
  334. return DxilMDHelper::ConstMDToUint32(tuple->getOperand(idx));
  335. }
  336. static unsigned GetFloatAt(MDTuple *tuple, unsigned idx) {
  337. return DxilMDHelper::ConstMDToFloat(tuple->getOperand(idx));
  338. }
  339. static const StringRef kHLDxilFunctionPropertiesMDName = "dx.fnprops";
  340. static const StringRef kHLDxilOptionsMDName = "dx.options";
  341. static const StringRef kHLDxilResourceTypeAnnotationMDName = "dx.resource.type.annotation";
  342. // DXIL metadata serialization/deserialization.
  343. void HLModule::EmitHLMetadata() {
  344. m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
  345. m_pMDHelper->EmitDxilShaderModel(m_pSM);
  346. MDTuple *pMDSignatures = m_pMDHelper->EmitDxilSignatures(*m_InputSignature,
  347. *m_OutputSignature,
  348. *m_PatchConstantSignature);
  349. MDTuple *pMDResources = EmitHLResources();
  350. MDTuple *pMDProperties = EmitHLShaderProperties();
  351. m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
  352. EmitLLVMUsed();
  353. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources, pMDProperties);
  354. vector<MDNode *> Entries;
  355. Entries.emplace_back(pEntry);
  356. m_pMDHelper->EmitDxilEntryPoints(Entries);
  357. {
  358. NamedMDNode * fnProps = m_pModule->getOrInsertNamedMetadata(kHLDxilFunctionPropertiesMDName);
  359. for (auto && pair : m_HLFunctionPropsMap) {
  360. const hlsl::HLFunctionProps * props = pair.second.get();
  361. Metadata *MDVals[30];
  362. std::fill(MDVals, MDVals + _countof(MDVals), nullptr);
  363. unsigned valIdx = 0;
  364. MDVals[valIdx++] = ValueAsMetadata::get(pair.first);
  365. switch (m_pSM->GetKind()) {
  366. case DXIL::ShaderKind::Compute:
  367. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.CS.numThreads[0]);
  368. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.CS.numThreads[1]);
  369. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.CS.numThreads[2]);
  370. break;
  371. case DXIL::ShaderKind::Geometry:
  372. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.GS.inputPrimitive);
  373. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.GS.maxVertexCount);
  374. for (size_t i = 0; i < _countof(props->ShaderProps.GS.streamPrimitiveTopologies); ++i)
  375. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.GS.streamPrimitiveTopologies[i]);
  376. break;
  377. case DXIL::ShaderKind::Hull:
  378. MDVals[valIdx++] = ValueAsMetadata::get(props->ShaderProps.HS.patchConstantFunc);
  379. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.HS.domain);
  380. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.HS.partition);
  381. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.HS.outputPrimitive);
  382. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.HS.inputControlPoints);
  383. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.HS.outputControlPoints);
  384. MDVals[valIdx++] = m_pMDHelper->FloatToConstMD(props->ShaderProps.HS.maxTessFactor);
  385. break;
  386. case DXIL::ShaderKind::Domain:
  387. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.DS.domain);
  388. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.DS.inputControlPoints);
  389. break;
  390. case DXIL::ShaderKind::Pixel:
  391. MDVals[valIdx++] = m_pMDHelper->BoolToConstMD(props->ShaderProps.PS.EarlyDepthStencil);
  392. break;
  393. }
  394. fnProps->addOperand(MDTuple::get(m_Ctx, ArrayRef<llvm::Metadata *>(MDVals, valIdx)));
  395. }
  396. NamedMDNode * options = m_pModule->getOrInsertNamedMetadata(kHLDxilOptionsMDName);
  397. uint32_t hlOptions = m_Options.GetHLOptionsRaw();
  398. options->addOperand(MDNode::get(m_Ctx, m_pMDHelper->Uint32ToConstMD(hlOptions)));
  399. NamedMDNode * resTyAnnotations = m_pModule->getOrInsertNamedMetadata(kHLDxilResourceTypeAnnotationMDName);
  400. resTyAnnotations->addOperand(EmitResTyAnnotations());
  401. }
  402. if (!m_RootSignature->IsEmpty()) {
  403. m_pMDHelper->EmitRootSignature(*m_RootSignature.get());
  404. }
  405. }
  406. void HLModule::LoadHLMetadata() {
  407. m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
  408. m_pMDHelper->LoadDxilShaderModel(m_pSM);
  409. CreateSignatures(m_pSM, m_InputSignature, m_OutputSignature, m_PatchConstantSignature, m_RootSignature);
  410. const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
  411. Function *pEntryFunc;
  412. string EntryName;
  413. const llvm::MDOperand *pSignatures, *pResources, *pProperties;
  414. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0), pEntryFunc, EntryName, pSignatures, pResources, pProperties);
  415. SetEntryFunction(pEntryFunc);
  416. SetEntryFunctionName(EntryName);
  417. m_pMDHelper->LoadDxilSignatures(*pSignatures, *m_InputSignature,
  418. *m_OutputSignature, *m_PatchConstantSignature);
  419. LoadHLResources(*pResources);
  420. LoadHLShaderProperties(*pProperties);
  421. m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
  422. {
  423. NamedMDNode * fnProps = m_pModule->getNamedMetadata(kHLDxilFunctionPropertiesMDName);
  424. size_t propIdx = 0;
  425. while (propIdx < fnProps->getNumOperands()) {
  426. MDTuple *pProps = dyn_cast<MDTuple>(fnProps->getOperand(propIdx++));
  427. std::unique_ptr<hlsl::HLFunctionProps> props = llvm::make_unique<hlsl::HLFunctionProps>();
  428. unsigned idx = 0;
  429. Function *F = dyn_cast<Function>(dyn_cast<ValueAsMetadata>(pProps->getOperand(idx++))->getValue());
  430. switch (m_pSM->GetKind()) {
  431. case DXIL::ShaderKind::Compute:
  432. props->ShaderProps.CS.numThreads[0] = GetIntAt(pProps, idx++);
  433. props->ShaderProps.CS.numThreads[1] = GetIntAt(pProps, idx++);
  434. props->ShaderProps.CS.numThreads[2] = GetIntAt(pProps, idx++);
  435. break;
  436. case DXIL::ShaderKind::Geometry:
  437. props->ShaderProps.GS.inputPrimitive = (DXIL::InputPrimitive)GetIntAt(pProps, idx++);
  438. props->ShaderProps.GS.maxVertexCount = GetIntAt(pProps, idx++);
  439. for (size_t i = 0; i < _countof(props->ShaderProps.GS.streamPrimitiveTopologies); ++i)
  440. props->ShaderProps.GS.streamPrimitiveTopologies[i] = (DXIL::PrimitiveTopology)GetIntAt(pProps, idx++);
  441. break;
  442. case DXIL::ShaderKind::Hull:
  443. props->ShaderProps.HS.patchConstantFunc = dyn_cast<Function>(dyn_cast<ValueAsMetadata>(pProps->getOperand(idx++))->getValue());
  444. props->ShaderProps.HS.domain = (DXIL::TessellatorDomain)GetIntAt(pProps, idx++);
  445. props->ShaderProps.HS.partition = (DXIL::TessellatorPartitioning)GetIntAt(pProps, idx++);
  446. props->ShaderProps.HS.outputPrimitive = (DXIL::TessellatorOutputPrimitive)GetIntAt(pProps, idx++);
  447. props->ShaderProps.HS.inputControlPoints = GetIntAt(pProps, idx++);
  448. props->ShaderProps.HS.outputControlPoints = GetIntAt(pProps, idx++);
  449. props->ShaderProps.HS.maxTessFactor = GetFloatAt(pProps, idx++);
  450. break;
  451. case DXIL::ShaderKind::Domain:
  452. props->ShaderProps.DS.domain = (DXIL::TessellatorDomain)GetIntAt(pProps, idx++);
  453. props->ShaderProps.DS.inputControlPoints = GetIntAt(pProps, idx++);
  454. break;
  455. case DXIL::ShaderKind::Pixel:
  456. props->ShaderProps.PS.EarlyDepthStencil = GetIntAt(pProps, idx++);
  457. break;
  458. }
  459. m_HLFunctionPropsMap[F] = std::move(props);
  460. }
  461. const NamedMDNode * options = m_pModule->getOrInsertNamedMetadata(kHLDxilOptionsMDName);
  462. const MDNode *MDOptions = options->getOperand(0);
  463. m_Options.SetHLOptionsRaw(DxilMDHelper::ConstMDToUint32(MDOptions->getOperand(0)));
  464. NamedMDNode * resTyAnnotations = m_pModule->getOrInsertNamedMetadata(kHLDxilResourceTypeAnnotationMDName);
  465. const MDNode *MDResTyAnnotations = resTyAnnotations->getOperand(0);
  466. if (MDResTyAnnotations->getNumOperands())
  467. LoadResTyAnnotations(MDResTyAnnotations->getOperand(0));
  468. }
  469. m_pMDHelper->LoadRootSignature(*m_RootSignature.get());
  470. }
  471. void HLModule::ClearHLMetadata(llvm::Module &M) {
  472. Module::named_metadata_iterator
  473. b = M.named_metadata_begin(),
  474. e = M.named_metadata_end();
  475. SmallVector<NamedMDNode*, 8> nodes;
  476. for (; b != e; ++b) {
  477. StringRef name = b->getName();
  478. if (name == DxilMDHelper::kDxilVersionMDName ||
  479. name == DxilMDHelper::kDxilShaderModelMDName ||
  480. name == DxilMDHelper::kDxilEntryPointsMDName ||
  481. name == DxilMDHelper::kDxilRootSignatureMDName ||
  482. name == DxilMDHelper::kDxilResourcesMDName ||
  483. name == DxilMDHelper::kDxilTypeSystemMDName ||
  484. name == kHLDxilFunctionPropertiesMDName || // TODO: adjust to proper name
  485. name == kHLDxilResourceTypeAnnotationMDName ||
  486. name == kHLDxilOptionsMDName ||
  487. name.startswith(DxilMDHelper::kDxilTypeSystemHelperVariablePrefix)) {
  488. nodes.push_back(b);
  489. }
  490. }
  491. for (size_t i = 0; i < nodes.size(); ++i) {
  492. M.eraseNamedMetadata(nodes[i]);
  493. }
  494. }
  495. MDTuple *HLModule::EmitHLResources() {
  496. // Emit SRV records.
  497. MDTuple *pTupleSRVs = nullptr;
  498. if (!m_SRVs.empty()) {
  499. vector<Metadata *> MDVals;
  500. for (size_t i = 0; i < m_SRVs.size(); i++) {
  501. MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
  502. }
  503. pTupleSRVs = MDNode::get(m_Ctx, MDVals);
  504. }
  505. // Emit UAV records.
  506. MDTuple *pTupleUAVs = nullptr;
  507. if (!m_UAVs.empty()) {
  508. vector<Metadata *> MDVals;
  509. for (size_t i = 0; i < m_UAVs.size(); i++) {
  510. MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
  511. }
  512. pTupleUAVs = MDNode::get(m_Ctx, MDVals);
  513. }
  514. // Emit CBuffer records.
  515. MDTuple *pTupleCBuffers = nullptr;
  516. if (!m_CBuffers.empty()) {
  517. vector<Metadata *> MDVals;
  518. for (size_t i = 0; i < m_CBuffers.size(); i++) {
  519. MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
  520. }
  521. pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
  522. }
  523. // Emit Sampler records.
  524. MDTuple *pTupleSamplers = nullptr;
  525. if (!m_Samplers.empty()) {
  526. vector<Metadata *> MDVals;
  527. for (size_t i = 0; i < m_Samplers.size(); i++) {
  528. MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
  529. }
  530. pTupleSamplers = MDNode::get(m_Ctx, MDVals);
  531. }
  532. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr || pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  533. return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs, pTupleCBuffers, pTupleSamplers);
  534. } else {
  535. return nullptr;
  536. }
  537. }
  538. void HLModule::LoadHLResources(const llvm::MDOperand &MDO) {
  539. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  540. m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
  541. // Load SRV records.
  542. if (pSRVs != nullptr) {
  543. for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
  544. unique_ptr<HLResource> pSRV(new HLResource);
  545. m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
  546. AddSRV(std::move(pSRV));
  547. }
  548. }
  549. // Load UAV records.
  550. if (pUAVs != nullptr) {
  551. for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
  552. unique_ptr<HLResource> pUAV(new HLResource);
  553. m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
  554. AddUAV(std::move(pUAV));
  555. }
  556. }
  557. // Load CBuffer records.
  558. if (pCBuffers != nullptr) {
  559. for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
  560. unique_ptr<DxilCBuffer> pCB = llvm::make_unique<DxilCBuffer>();
  561. m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
  562. AddCBuffer(std::move(pCB));
  563. }
  564. }
  565. // Load Sampler records.
  566. if (pSamplers != nullptr) {
  567. for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
  568. unique_ptr<DxilSampler> pSampler(new DxilSampler);
  569. m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
  570. AddSampler(std::move(pSampler));
  571. }
  572. }
  573. }
  574. llvm::MDTuple *HLModule::EmitResTyAnnotations() {
  575. vector<Metadata *> MDVals;
  576. for (auto &resAnnotation : m_ResTypeAnnotation) {
  577. Metadata *TyMeta =
  578. ValueAsMetadata::get(UndefValue::get(resAnnotation.first));
  579. MDVals.emplace_back(TyMeta);
  580. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(
  581. static_cast<unsigned>(resAnnotation.second.first)));
  582. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(
  583. static_cast<unsigned>(resAnnotation.second.second)));
  584. }
  585. return MDNode::get(m_Ctx, MDVals);
  586. }
  587. void HLModule::LoadResTyAnnotations(const llvm::MDOperand &MDO) {
  588. if (MDO.get() == nullptr)
  589. return;
  590. const MDTuple *pTupleMD = dyn_cast<MDTuple>(MDO.get());
  591. IFTBOOL(pTupleMD != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  592. IFTBOOL((pTupleMD->getNumOperands() & 0x3) == 0,
  593. DXC_E_INCORRECT_DXIL_METADATA);
  594. for (unsigned iNode = 0; iNode < pTupleMD->getNumOperands(); iNode += 3) {
  595. const MDOperand &MDTy = pTupleMD->getOperand(iNode);
  596. const MDOperand &MDClass = pTupleMD->getOperand(iNode + 1);
  597. const MDOperand &MDKind = pTupleMD->getOperand(iNode + 2);
  598. Type *Ty = m_pMDHelper->ValueMDToValue(MDTy)->getType();
  599. DXIL::ResourceClass resClass = static_cast<DXIL::ResourceClass>(
  600. DxilMDHelper::ConstMDToUint32(MDClass));
  601. DXIL::ResourceKind kind =
  602. static_cast<DXIL::ResourceKind>(DxilMDHelper::ConstMDToUint32(MDKind));
  603. AddResourceTypeAnnotation(Ty, resClass, kind);
  604. }
  605. }
  606. MDTuple *HLModule::EmitHLShaderProperties() {
  607. return nullptr;
  608. }
  609. void HLModule::LoadHLShaderProperties(const MDOperand &MDO) {
  610. return;
  611. }
  612. MDNode *HLModule::DxilSamplerToMDNode(const DxilSampler &S) {
  613. MDNode *MD = m_pMDHelper->EmitDxilSampler(S);
  614. ValueAsMetadata *ResClass =
  615. m_pMDHelper->Uint32ToConstMD((unsigned)DXIL::ResourceClass::Sampler);
  616. return MDNode::get(m_Ctx, {ResClass, MD});
  617. }
  618. MDNode *HLModule::DxilSRVToMDNode(const DxilResource &SRV) {
  619. MDNode *MD = m_pMDHelper->EmitDxilSRV(SRV);
  620. ValueAsMetadata *ResClass =
  621. m_pMDHelper->Uint32ToConstMD((unsigned)DXIL::ResourceClass::SRV);
  622. return MDNode::get(m_Ctx, {ResClass, MD});
  623. }
  624. MDNode *HLModule::DxilUAVToMDNode(const DxilResource &UAV) {
  625. MDNode *MD = m_pMDHelper->EmitDxilUAV(UAV);
  626. ValueAsMetadata *ResClass =
  627. m_pMDHelper->Uint32ToConstMD((unsigned)DXIL::ResourceClass::UAV);
  628. return MDNode::get(m_Ctx, {ResClass, MD});
  629. }
  630. MDNode *HLModule::DxilCBufferToMDNode(const DxilCBuffer &CB) {
  631. MDNode *MD = m_pMDHelper->EmitDxilCBuffer(CB);
  632. ValueAsMetadata *ResClass =
  633. m_pMDHelper->Uint32ToConstMD((unsigned)DXIL::ResourceClass::CBuffer);
  634. return MDNode::get(m_Ctx, {ResClass, MD});
  635. }
  636. DxilResourceBase HLModule::LoadDxilResourceBaseFromMDNode(
  637. MDNode *MD) {
  638. IFTBOOL(MD->getNumOperands() >= DxilMDHelper::kHLDxilResourceAttributeNumFields,
  639. DXC_E_INCORRECT_DXIL_METADATA);
  640. DxilResource::Class RC =
  641. static_cast<DxilResource::Class>(m_pMDHelper->ConstMDToUint32(
  642. MD->getOperand(DxilMDHelper::kHLDxilResourceAttributeClass)));
  643. const MDOperand &Meta =
  644. MD->getOperand(DxilMDHelper::kHLDxilResourceAttributeMeta);
  645. switch (RC) {
  646. case DxilResource::Class::CBuffer: {
  647. DxilCBuffer CB;
  648. m_pMDHelper->LoadDxilCBuffer(Meta, CB);
  649. return CB;
  650. } break;
  651. case DxilResource::Class::Sampler: {
  652. DxilSampler S;
  653. m_pMDHelper->LoadDxilSampler(Meta, S);
  654. return S;
  655. } break;
  656. case DxilResource::Class::SRV: {
  657. DxilResource Res;
  658. m_pMDHelper->LoadDxilSRV(Meta, Res);
  659. return Res;
  660. } break;
  661. case DxilResource::Class::UAV: {
  662. DxilResource Res;
  663. m_pMDHelper->LoadDxilUAV(Meta, Res);
  664. return Res;
  665. } break;
  666. default:
  667. DXASSERT(0, "Invalid metadata");
  668. return DxilResourceBase(DXIL::ResourceClass::Invalid);
  669. }
  670. }
  671. void HLModule::AddResourceWithGlobalVariableAndMDNode(llvm::Constant *GV,
  672. llvm::MDNode *MD) {
  673. IFTBOOL(MD->getNumOperands() >= DxilMDHelper::kHLDxilResourceAttributeNumFields,
  674. DXC_E_INCORRECT_DXIL_METADATA);
  675. DxilResource::Class RC =
  676. static_cast<DxilResource::Class>(m_pMDHelper->ConstMDToUint32(
  677. MD->getOperand(DxilMDHelper::kHLDxilResourceAttributeClass)));
  678. const MDOperand &Meta =
  679. MD->getOperand(DxilMDHelper::kHLDxilResourceAttributeMeta);
  680. unsigned rangeSize = 1;
  681. Type *Ty = GV->getType()->getPointerElementType();
  682. if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
  683. rangeSize = AT->getNumElements();
  684. switch (RC) {
  685. case DxilResource::Class::Sampler: {
  686. std::unique_ptr<DxilSampler> S = llvm::make_unique<DxilSampler>();
  687. m_pMDHelper->LoadDxilSampler(Meta, *S);
  688. S->SetGlobalSymbol(GV);
  689. S->SetGlobalName(GV->getName());
  690. S->SetRangeSize(rangeSize);
  691. AddSampler(std::move(S));
  692. } break;
  693. case DxilResource::Class::SRV: {
  694. std::unique_ptr<HLResource> Res = llvm::make_unique<HLResource>();
  695. m_pMDHelper->LoadDxilSRV(Meta, *Res);
  696. Res->SetGlobalSymbol(GV);
  697. Res->SetGlobalName(GV->getName());
  698. Res->SetRangeSize(rangeSize);
  699. AddSRV(std::move(Res));
  700. } break;
  701. case DxilResource::Class::UAV: {
  702. std::unique_ptr<HLResource> Res = llvm::make_unique<HLResource>();
  703. m_pMDHelper->LoadDxilUAV(Meta, *Res);
  704. Res->SetGlobalSymbol(GV);
  705. Res->SetGlobalName(GV->getName());
  706. Res->SetRangeSize(rangeSize);
  707. AddUAV(std::move(Res));
  708. } break;
  709. default:
  710. DXASSERT(0, "Invalid metadata for AddResourceWithGlobalVariableAndMDNode");
  711. }
  712. }
  713. // TODO: Don't check names.
  714. bool HLModule::IsStreamOutputType(llvm::Type *Ty) {
  715. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  716. if (ST->getName().startswith("class.PointStream"))
  717. return true;
  718. if (ST->getName().startswith("class.LineStream"))
  719. return true;
  720. if (ST->getName().startswith("class.TriangleStream"))
  721. return true;
  722. }
  723. return false;
  724. }
  725. bool HLModule::IsStreamOutputPtrType(llvm::Type *Ty) {
  726. if (!Ty->isPointerTy())
  727. return false;
  728. Ty = Ty->getPointerElementType();
  729. return IsStreamOutputType(Ty);
  730. }
  731. bool HLModule::IsHLSLObjectType(llvm::Type *Ty) {
  732. if (llvm::StructType *ST = dyn_cast<llvm::StructType>(Ty)) {
  733. StringRef name = ST->getName();
  734. if (name.startswith("dx.types.wave_t"))
  735. return true;
  736. if (name.endswith("_slice_type"))
  737. return false;
  738. name = name.ltrim("class.");
  739. name = name.ltrim("struct.");
  740. if (name == "SamplerState")
  741. return true;
  742. if (name == "SamplerComparisonState")
  743. return true;
  744. if (name.startswith("TriangleStream"))
  745. return true;
  746. if (name.startswith("PointStream"))
  747. return true;
  748. if (name.startswith("LineStream"))
  749. return true;
  750. if (name.startswith("AppendStructuredBuffer"))
  751. return true;
  752. if (name.startswith("ConsumeStructuredBuffer"))
  753. return true;
  754. if (name.startswith("ConstantBuffer"))
  755. return true;
  756. name = name.ltrim("RasterizerOrdered");
  757. name = name.ltrim("RW");
  758. if (name == "ByteAddressBuffer")
  759. return true;
  760. if (name.startswith("Buffer"))
  761. return true;
  762. if (name.startswith("StructuredBuffer"))
  763. return true;
  764. if (name.startswith("Texture1D"))
  765. return true;
  766. if (name.startswith("Texture1DArray"))
  767. return true;
  768. if (name.startswith("Texture2D"))
  769. return true;
  770. if (name.startswith("Texture2DArray"))
  771. return true;
  772. if (name.startswith("Texture3D"))
  773. return true;
  774. if (name.startswith("TextureCube"))
  775. return true;
  776. if (name.startswith("TextureCubeArray"))
  777. return true;
  778. if (name.startswith("Texture2DMS"))
  779. return true;
  780. if (name.startswith("Texture2DMSArray"))
  781. return true;
  782. }
  783. return false;
  784. }
  785. unsigned
  786. HLModule::GetLegacyCBufferFieldElementSize(DxilFieldAnnotation &fieldAnnotation,
  787. llvm::Type *Ty,
  788. DxilTypeSystem &typeSys) {
  789. while (isa<ArrayType>(Ty)) {
  790. Ty = Ty->getArrayElementType();
  791. }
  792. // Bytes.
  793. unsigned compSize = fieldAnnotation.GetCompType().Is64Bit()?8:4;
  794. unsigned fieldSize = compSize;
  795. if (Ty->isVectorTy()) {
  796. fieldSize *= Ty->getVectorNumElements();
  797. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  798. DxilStructAnnotation *EltAnnotation = typeSys.GetStructAnnotation(ST);
  799. if (EltAnnotation) {
  800. fieldSize = EltAnnotation->GetCBufferSize();
  801. } else {
  802. // Calculate size when don't have annotation.
  803. if (fieldAnnotation.HasMatrixAnnotation()) {
  804. const DxilMatrixAnnotation &matAnnotation =
  805. fieldAnnotation.GetMatrixAnnotation();
  806. unsigned rows = matAnnotation.Rows;
  807. unsigned cols = matAnnotation.Cols;
  808. if (matAnnotation.Orientation == MatrixOrientation::ColumnMajor) {
  809. rows = cols;
  810. cols = matAnnotation.Rows;
  811. } else if (matAnnotation.Orientation != MatrixOrientation::RowMajor) {
  812. // Invalid matrix orientation.
  813. fieldSize = 0;
  814. }
  815. fieldSize = (rows - 1) * 16 + cols * 4;
  816. } else {
  817. // Cannot find struct annotation.
  818. fieldSize = 0;
  819. }
  820. }
  821. }
  822. return fieldSize;
  823. }
  824. bool HLModule::IsStaticGlobal(GlobalVariable *GV) {
  825. return GV->getLinkage() == GlobalValue::LinkageTypes::InternalLinkage &&
  826. GV->getType()->getPointerAddressSpace() == DXIL::kDefaultAddrSpace;
  827. }
  828. bool HLModule::IsSharedMemoryGlobal(llvm::GlobalVariable *GV) {
  829. return GV->getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace;
  830. }
  831. void HLModule::GetParameterRowsAndCols(Type *Ty, unsigned &rows, unsigned &cols,
  832. DxilParameterAnnotation &paramAnnotation) {
  833. if (Ty->isPointerTy())
  834. Ty = Ty->getPointerElementType();
  835. // For array input of HS, DS, GS,
  836. // we need to skip the first level which size is based on primitive type.
  837. DxilParamInputQual inputQual = paramAnnotation.GetParamInputQual();
  838. bool skipOneLevelArray = inputQual == DxilParamInputQual::InputPatch;
  839. skipOneLevelArray |= inputQual == DxilParamInputQual::OutputPatch;
  840. skipOneLevelArray |= inputQual == DxilParamInputQual::InputPrimitive;
  841. if (skipOneLevelArray) {
  842. if (Ty->isArrayTy())
  843. Ty = Ty->getArrayElementType();
  844. }
  845. unsigned arraySize = 1;
  846. while (Ty->isArrayTy()) {
  847. arraySize *= Ty->getArrayNumElements();
  848. Ty = Ty->getArrayElementType();
  849. }
  850. rows = 1;
  851. cols = 1;
  852. if (paramAnnotation.HasMatrixAnnotation()) {
  853. const DxilMatrixAnnotation &matrix = paramAnnotation.GetMatrixAnnotation();
  854. if (matrix.Orientation == MatrixOrientation::RowMajor) {
  855. rows = matrix.Rows;
  856. cols = matrix.Cols;
  857. } else {
  858. DXASSERT(matrix.Orientation == MatrixOrientation::ColumnMajor, "");
  859. cols = matrix.Rows;
  860. rows = matrix.Cols;
  861. }
  862. } else if (Ty->isVectorTy())
  863. cols = Ty->getVectorNumElements();
  864. rows *= arraySize;
  865. }
  866. // For legacy data layout, everything less than 32 align to 32.
  867. static const StringRef kLegacyLayoutString = "e-m:e-p:32:32-i1:32:32-i8:32:32-i16:32:32-i64:64-f16:32-f80:32-n8:16:32-a:0:32-S32";
  868. const char *HLModule::GetLegacyDataLayoutDesc() {
  869. return kLegacyLayoutString.data();
  870. }
  871. static Value *MergeGEP(GEPOperator *SrcGEP, GetElementPtrInst *GEP) {
  872. IRBuilder<> Builder(GEP);
  873. SmallVector<Value *, 8> Indices;
  874. // Find out whether the last index in the source GEP is a sequential idx.
  875. bool EndsWithSequential = false;
  876. for (gep_type_iterator I = gep_type_begin(*SrcGEP), E = gep_type_end(*SrcGEP);
  877. I != E; ++I)
  878. EndsWithSequential = !(*I)->isStructTy();
  879. if (EndsWithSequential) {
  880. Value *Sum;
  881. Value *SO1 = SrcGEP->getOperand(SrcGEP->getNumOperands() - 1);
  882. Value *GO1 = GEP->getOperand(1);
  883. if (SO1 == Constant::getNullValue(SO1->getType())) {
  884. Sum = GO1;
  885. } else if (GO1 == Constant::getNullValue(GO1->getType())) {
  886. Sum = SO1;
  887. } else {
  888. // If they aren't the same type, then the input hasn't been processed
  889. // by the loop above yet (which canonicalizes sequential index types to
  890. // intptr_t). Just avoid transforming this until the input has been
  891. // normalized.
  892. if (SO1->getType() != GO1->getType())
  893. return nullptr;
  894. // Only do the combine when GO1 and SO1 are both constants. Only in
  895. // this case, we are sure the cost after the merge is never more than
  896. // that before the merge.
  897. if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
  898. return nullptr;
  899. Sum = Builder.CreateAdd(SO1, GO1);
  900. }
  901. // Update the GEP in place if possible.
  902. if (SrcGEP->getNumOperands() == 2) {
  903. GEP->setOperand(0, SrcGEP->getOperand(0));
  904. GEP->setOperand(1, Sum);
  905. return GEP;
  906. }
  907. Indices.append(SrcGEP->op_begin() + 1, SrcGEP->op_end() - 1);
  908. Indices.push_back(Sum);
  909. Indices.append(GEP->op_begin() + 2, GEP->op_end());
  910. } else if (isa<Constant>(*GEP->idx_begin()) &&
  911. cast<Constant>(*GEP->idx_begin())->isNullValue() &&
  912. SrcGEP->getNumOperands() != 1) {
  913. // Otherwise we can do the fold if the first index of the GEP is a zero
  914. Indices.append(SrcGEP->op_begin() + 1, SrcGEP->op_end());
  915. Indices.append(GEP->idx_begin() + 1, GEP->idx_end());
  916. }
  917. if (!Indices.empty())
  918. return Builder.CreateInBoundsGEP(SrcGEP->getSourceElementType(),
  919. SrcGEP->getOperand(0), Indices,
  920. GEP->getName());
  921. else
  922. llvm_unreachable("must merge");
  923. }
  924. void HLModule::MergeGepUse(Value *V) {
  925. for (auto U = V->user_begin(); U != V->user_end();) {
  926. auto Use = U++;
  927. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*Use)) {
  928. if (GEPOperator *prevGEP = dyn_cast<GEPOperator>(V)) {
  929. // merge the 2 GEPs
  930. Value *newGEP = MergeGEP(prevGEP, GEP);
  931. GEP->replaceAllUsesWith(newGEP);
  932. GEP->eraseFromParent();
  933. MergeGepUse(newGEP);
  934. } else {
  935. MergeGepUse(*Use);
  936. }
  937. } else if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(*Use)) {
  938. if (GEPOperator *prevGEP = dyn_cast<GEPOperator>(V)) {
  939. // merge the 2 GEPs
  940. Value *newGEP = MergeGEP(prevGEP, GEP);
  941. GEP->replaceAllUsesWith(newGEP);
  942. GEP->eraseFromParent();
  943. MergeGepUse(newGEP);
  944. } else {
  945. MergeGepUse(*Use);
  946. }
  947. }
  948. }
  949. if (V->user_empty()) {
  950. // Only remove GEP here, root ptr will be removed by DCE.
  951. if (GetElementPtrInst *I = dyn_cast<GetElementPtrInst>(V))
  952. I->eraseFromParent();
  953. }
  954. }
  955. template<typename BuilderTy>
  956. CallInst *HLModule::EmitHLOperationCall(BuilderTy &Builder,
  957. HLOpcodeGroup group, unsigned opcode,
  958. Type *RetType,
  959. ArrayRef<Value *> paramList,
  960. llvm::Module &M) {
  961. SmallVector<llvm::Type *, 4> paramTyList;
  962. // Add the opcode param
  963. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  964. paramTyList.emplace_back(opcodeTy);
  965. for (Value *param : paramList) {
  966. paramTyList.emplace_back(param->getType());
  967. }
  968. llvm::FunctionType *funcTy =
  969. llvm::FunctionType::get(RetType, paramTyList, false);
  970. Function *opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  971. SmallVector<Value *, 4> opcodeParamList;
  972. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  973. opcodeParamList.emplace_back(opcodeConst);
  974. opcodeParamList.append(paramList.begin(), paramList.end());
  975. return Builder.CreateCall(opFunc, opcodeParamList);
  976. }
  977. template
  978. CallInst *HLModule::EmitHLOperationCall(IRBuilder<> &Builder,
  979. HLOpcodeGroup group, unsigned opcode,
  980. Type *RetType,
  981. ArrayRef<Value *> paramList,
  982. llvm::Module &M);
  983. unsigned HLModule::FindCastOp(bool fromUnsigned, bool toUnsigned,
  984. llvm::Type *SrcTy, llvm::Type *DstTy) {
  985. Instruction::CastOps castOp = llvm::Instruction::CastOps::BitCast;
  986. if (SrcTy->isAggregateType() || DstTy->isAggregateType())
  987. return llvm::Instruction::CastOps::BitCast;
  988. uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
  989. uint32_t DstBitSize = DstTy->getScalarSizeInBits();
  990. if (SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy()) {
  991. if (SrcBitSize > DstBitSize)
  992. return Instruction::Trunc;
  993. if (toUnsigned)
  994. return Instruction::ZExt;
  995. else
  996. return Instruction::SExt;
  997. }
  998. if (SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy()) {
  999. if (SrcBitSize > DstBitSize)
  1000. return Instruction::FPTrunc;
  1001. else
  1002. return Instruction::FPExt;
  1003. }
  1004. if (SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy())
  1005. if (fromUnsigned)
  1006. return Instruction::UIToFP;
  1007. else
  1008. return Instruction::SIToFP;
  1009. if (SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy())
  1010. if (toUnsigned)
  1011. return Instruction::FPToUI;
  1012. else
  1013. return Instruction::FPToSI;
  1014. DXASSERT_NOMSG(0);
  1015. return castOp;
  1016. }
  1017. bool HLModule::HasPreciseAttributeWithMetadata(Instruction *I) {
  1018. MDNode *preciseNode =
  1019. I->getMetadata(DxilMDHelper::kDxilPreciseAttributeMDName);
  1020. return preciseNode != nullptr;
  1021. }
  1022. void HLModule::MarkPreciseAttributeWithMetadata(Instruction *I) {
  1023. LLVMContext &Ctx = I->getContext();
  1024. MDNode *preciseNode = MDNode::get(
  1025. Ctx,
  1026. {ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Ctx), 1))});
  1027. I->setMetadata(DxilMDHelper::kDxilPreciseAttributeMDName, preciseNode);
  1028. }
  1029. void HLModule::ClearPreciseAttributeWithMetadata(Instruction *I) {
  1030. I->setMetadata(DxilMDHelper::kDxilPreciseAttributeMDName, nullptr);
  1031. }
  1032. static void MarkPreciseAttribute(Function *F) {
  1033. LLVMContext &Ctx = F->getContext();
  1034. MDNode *preciseNode = MDNode::get(
  1035. Ctx, {MDString::get(Ctx, DxilMDHelper::kDxilPreciseAttributeMDName)});
  1036. F->setMetadata(DxilMDHelper::kDxilPreciseAttributeMDName, preciseNode);
  1037. }
  1038. static void MarkPreciseAttributeOnValWithFunctionCall(
  1039. llvm::Value *V, llvm::IRBuilder<> &Builder, llvm::Module &M) {
  1040. Type *Ty = V->getType();
  1041. Type *EltTy = Ty->getScalarType();
  1042. // TODO: Only do this on basic types.
  1043. FunctionType *preciseFuncTy =
  1044. FunctionType::get(Type::getVoidTy(M.getContext()), {EltTy}, false);
  1045. // The function will be deleted after precise propagate.
  1046. std::string preciseFuncName = "dx.attribute.precise.";
  1047. raw_string_ostream mangledNameStr(preciseFuncName);
  1048. EltTy->print(mangledNameStr);
  1049. mangledNameStr.flush();
  1050. Function *preciseFunc =
  1051. cast<Function>(M.getOrInsertFunction(preciseFuncName, preciseFuncTy));
  1052. if (!HLModule::HasPreciseAttribute(preciseFunc))
  1053. MarkPreciseAttribute(preciseFunc);
  1054. if (Ty->isVectorTy()) {
  1055. for (unsigned i = 0; i < Ty->getVectorNumElements(); i++) {
  1056. Value *Elt = Builder.CreateExtractElement(V, i);
  1057. Builder.CreateCall(preciseFunc, {Elt});
  1058. }
  1059. } else
  1060. Builder.CreateCall(preciseFunc, {V});
  1061. }
  1062. void HLModule::MarkPreciseAttributeOnPtrWithFunctionCall(llvm::Value *Ptr,
  1063. llvm::Module &M) {
  1064. for (User *U : Ptr->users()) {
  1065. // Skip load inst.
  1066. if (LoadInst *LI = dyn_cast<LoadInst>(U))
  1067. continue;
  1068. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  1069. Value *V = SI->getValueOperand();
  1070. if (isa<Instruction>(V)) {
  1071. // Mark the Value with function call.
  1072. IRBuilder<> Builder(SI);
  1073. MarkPreciseAttributeOnValWithFunctionCall(V, Builder, M);
  1074. }
  1075. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  1076. if (CI->getType()->isVoidTy()) {
  1077. IRBuilder<> Builder(CI);
  1078. // For void type, cannot use as function arg.
  1079. // Mark all arg for it?
  1080. for (auto &arg : CI->arg_operands()) {
  1081. MarkPreciseAttributeOnValWithFunctionCall(arg, Builder, M);
  1082. }
  1083. } else {
  1084. IRBuilder<> Builder(CI->getNextNode());
  1085. MarkPreciseAttributeOnValWithFunctionCall(CI, Builder, M);
  1086. }
  1087. } else {
  1088. // Must be GEP here.
  1089. GetElementPtrInst *GEP = cast<GetElementPtrInst>(U);
  1090. MarkPreciseAttributeOnPtrWithFunctionCall(GEP, M);
  1091. }
  1092. }
  1093. }
  1094. bool HLModule::HasPreciseAttribute(Function *F) {
  1095. MDNode *preciseNode =
  1096. F->getMetadata(DxilMDHelper::kDxilPreciseAttributeMDName);
  1097. return preciseNode != nullptr;
  1098. }
  1099. void HLModule::MarkDxilResourceAttrib(llvm::Function *F, MDNode *MD) {
  1100. F->setMetadata(DxilMDHelper::kHLDxilResourceAttributeMDName, MD);
  1101. }
  1102. MDNode *HLModule::GetDxilResourceAttrib(llvm::Function *F) {
  1103. return F->getMetadata(DxilMDHelper::kHLDxilResourceAttributeMDName);
  1104. }
  1105. DIGlobalVariable *
  1106. HLModule::FindGlobalVariableDebugInfo(GlobalVariable *GV,
  1107. DebugInfoFinder &DbgInfoFinder) {
  1108. struct GlobalFinder {
  1109. GlobalVariable *GV;
  1110. bool operator()(llvm::DIGlobalVariable *const arg) const {
  1111. return arg->getVariable() == GV;
  1112. }
  1113. };
  1114. GlobalFinder F = {GV};
  1115. DebugInfoFinder::global_variable_iterator Found =
  1116. std::find_if(DbgInfoFinder.global_variables().begin(),
  1117. DbgInfoFinder.global_variables().end(), F);
  1118. if (Found != DbgInfoFinder.global_variables().end()) {
  1119. return *Found;
  1120. }
  1121. return nullptr;
  1122. }
  1123. static void AddDIGlobalVariable(DIBuilder &Builder, DIGlobalVariable *LocDIGV,
  1124. StringRef Name, DIType *DITy,
  1125. GlobalVariable *GV, DebugInfoFinder &DbgInfoFinder, bool removeLocDIGV) {
  1126. DIGlobalVariable *EltDIGV = Builder.createGlobalVariable(
  1127. LocDIGV->getScope(), Name, GV->getName(), LocDIGV->getFile(),
  1128. LocDIGV->getLine(), DITy, false, GV);
  1129. DICompileUnit *DICU = dyn_cast<DICompileUnit>(LocDIGV->getScope());
  1130. if (!DICU) {
  1131. DISubprogram *DIS = dyn_cast<DISubprogram>(LocDIGV->getScope());
  1132. if (DIS) {
  1133. // Find the DICU which has this Subprogram.
  1134. NamedMDNode *CompileUnits = GV->getParent()->getNamedMetadata("llvm.dbg.cu");
  1135. DXASSERT_NOMSG(CompileUnits);
  1136. for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
  1137. auto *CU = cast<DICompileUnit>(CompileUnits->getOperand(I));
  1138. DXASSERT(CU , "Expected valid compile unit");
  1139. for (DISubprogram *SP : CU->getSubprograms()) {
  1140. if (SP == DIS) {
  1141. DICU = CU;
  1142. break;
  1143. }
  1144. }
  1145. }
  1146. }
  1147. }
  1148. DXASSERT_NOMSG(DICU);
  1149. // Add global to CU.
  1150. auto *GlobalVariables = DICU->getRawGlobalVariables();
  1151. DXASSERT_NOMSG(GlobalVariables);
  1152. MDTuple *GTuple = cast<MDTuple>(GlobalVariables);
  1153. std::vector<Metadata *> AllGVs(GTuple->operands().begin(),
  1154. GTuple->operands().end());
  1155. if (removeLocDIGV) {
  1156. auto locIt = std::find(AllGVs.begin(), AllGVs.end(), LocDIGV);
  1157. AllGVs.erase(locIt);
  1158. }
  1159. AllGVs.emplace_back(EltDIGV);
  1160. DICU->replaceGlobalVariables(MDTuple::get(GV->getContext(), AllGVs));
  1161. DXVERIFY_NOMSG(DbgInfoFinder.appendGlobalVariable(EltDIGV));
  1162. }
  1163. void HLModule::CreateElementGlobalVariableDebugInfo(
  1164. GlobalVariable *GV, DebugInfoFinder &DbgInfoFinder, GlobalVariable *EltGV,
  1165. unsigned sizeInBits, unsigned alignInBits, unsigned offsetInBits,
  1166. StringRef eltName) {
  1167. DIGlobalVariable *DIGV = FindGlobalVariableDebugInfo(GV, DbgInfoFinder);
  1168. DXASSERT_NOMSG(DIGV);
  1169. DIBuilder Builder(*GV->getParent());
  1170. DITypeIdentifierMap EmptyMap;
  1171. DIType *DITy = DIGV->getType().resolve(EmptyMap);
  1172. DIScope *DITyScope = DITy->getScope().resolve(EmptyMap);
  1173. // Create Elt type.
  1174. DIType *EltDITy =
  1175. Builder.createMemberType(DITyScope, DITy->getName().str() + eltName.str(),
  1176. DITy->getFile(), DITy->getLine(), sizeInBits,
  1177. alignInBits, offsetInBits, /*Flags*/ 0, DITy);
  1178. AddDIGlobalVariable(Builder, DIGV, DIGV->getName().str() + eltName.str(),
  1179. EltDITy, EltGV, DbgInfoFinder, /*removeDIGV*/false);
  1180. }
  1181. void HLModule::UpdateGlobalVariableDebugInfo(
  1182. llvm::GlobalVariable *GV, llvm::DebugInfoFinder &DbgInfoFinder,
  1183. llvm::GlobalVariable *NewGV) {
  1184. DIGlobalVariable *DIGV = FindGlobalVariableDebugInfo(GV, DbgInfoFinder);
  1185. DXASSERT_NOMSG(DIGV);
  1186. DIBuilder Builder(*GV->getParent());
  1187. DITypeIdentifierMap EmptyMap;
  1188. DIType *DITy = DIGV->getType().resolve(EmptyMap);
  1189. AddDIGlobalVariable(Builder, DIGV, DIGV->getName(), DITy, NewGV,
  1190. DbgInfoFinder,/*removeDIGV*/true);
  1191. }
  1192. DebugInfoFinder &HLModule::GetOrCreateDebugInfoFinder() {
  1193. if (m_pDebugInfoFinder == nullptr) {
  1194. m_pDebugInfoFinder = llvm::make_unique<llvm::DebugInfoFinder>();
  1195. m_pDebugInfoFinder->processModule(*m_pModule);
  1196. }
  1197. return *m_pDebugInfoFinder;
  1198. }
  1199. //------------------------------------------------------------------------------
  1200. //
  1201. // Signature methods.
  1202. //
  1203. HLExtraPropertyHelper::HLExtraPropertyHelper(llvm::Module *pModule)
  1204. : DxilExtraPropertyHelper(pModule) {
  1205. }
  1206. void HLExtraPropertyHelper::EmitSignatureElementProperties(const DxilSignatureElement &SE,
  1207. vector<Metadata *> &MDVals) {
  1208. }
  1209. void HLExtraPropertyHelper::LoadSignatureElementProperties(const MDOperand &MDO,
  1210. DxilSignatureElement &SE) {
  1211. if (MDO.get() == nullptr)
  1212. return;
  1213. }
  1214. } // namespace hlsl
  1215. namespace llvm {
  1216. hlsl::HLModule &Module::GetOrCreateHLModule(bool skipInit) {
  1217. std::unique_ptr<hlsl::HLModule> M;
  1218. if (!HasHLModule()) {
  1219. M = llvm::make_unique<hlsl::HLModule>(this);
  1220. if (!skipInit) {
  1221. M->LoadHLMetadata();
  1222. }
  1223. SetHLModule(M.release());
  1224. }
  1225. return GetHLModule();
  1226. }
  1227. void Module::ResetHLModule() {
  1228. if (HasHLModule()) {
  1229. delete TheHLModule;
  1230. TheHLModule = nullptr;
  1231. }
  1232. }
  1233. }