DxilLinker.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilLinker.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/HLSL/DxilLinker.h"
  10. #include "dxc/DXIL/DxilCBuffer.h"
  11. #include "dxc/DXIL/DxilFunctionProps.h"
  12. #include "dxc/DXIL/DxilEntryProps.h"
  13. #include "dxc/DXIL/DxilModule.h"
  14. #include "dxc/DXIL/DxilOperations.h"
  15. #include "dxc/DXIL/DxilResource.h"
  16. #include "dxc/DXIL/DxilSampler.h"
  17. #include "dxc/DXIL/DxilUtil.h"
  18. #include "dxc/Support/Global.h"
  19. #include "llvm/ADT/DenseSet.h"
  20. #include "llvm/ADT/MapVector.h"
  21. #include "llvm/ADT/SetVector.h"
  22. #include "llvm/ADT/StringSet.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/IRBuilder.h"
  25. #include "llvm/IR/Instructions.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/Transforms/Utils/Cloning.h"
  28. #include "llvm/ADT/StringMap.h"
  29. #include "llvm/ADT/SetVector.h"
  30. #include "llvm/ADT/STLExtras.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <memory>
  33. #include <vector>
  34. #include "dxc/DxilContainer/DxilContainer.h"
  35. #include "llvm/IR/DiagnosticPrinter.h"
  36. #include "llvm/IR/LLVMContext.h"
  37. #include "llvm/IR/DebugInfo.h"
  38. #include "dxc/HLSL/DxilGenerationPass.h"
  39. #include "llvm/IR/LegacyPassManager.h"
  40. #include "llvm/Transforms/IPO.h"
  41. #include "llvm/Transforms/Scalar.h"
  42. #include "dxc/HLSL/DxilExportMap.h"
  43. #include "dxc/HLSL/ComputeViewIdState.h"
  44. using namespace llvm;
  45. using namespace hlsl;
  46. namespace {
  47. void CollectUsedFunctions(Constant *C,
  48. llvm::SetVector<Function *> &funcSet) {
  49. for (User *U : C->users()) {
  50. if (Instruction *I = dyn_cast<Instruction>(U)) {
  51. funcSet.insert(I->getParent()->getParent());
  52. } else {
  53. Constant *CU = cast<Constant>(U);
  54. CollectUsedFunctions(CU, funcSet);
  55. }
  56. }
  57. }
  58. template <class T>
  59. void AddResourceMap(
  60. const std::vector<std::unique_ptr<T>> &resTab, DXIL::ResourceClass resClass,
  61. llvm::MapVector<const llvm::Constant *, DxilResourceBase *> &resMap,
  62. DxilModule &DM) {
  63. for (auto &Res : resTab) {
  64. resMap[Res->GetGlobalSymbol()] = Res.get();
  65. }
  66. }
  67. void CloneFunction(Function *F, Function *NewF, ValueToValueMapTy &vmap,
  68. hlsl::DxilTypeSystem *TypeSys = nullptr,
  69. hlsl::DxilTypeSystem *SrcTypeSys = nullptr) {
  70. SmallVector<ReturnInst *, 2> Returns;
  71. // Map params.
  72. auto paramIt = NewF->arg_begin();
  73. for (Argument &param : F->args()) {
  74. vmap[&param] = (paramIt++);
  75. }
  76. llvm::CloneFunctionInto(NewF, F, vmap, /*ModuleLevelChanges*/ true, Returns);
  77. if (TypeSys) {
  78. if (SrcTypeSys == nullptr)
  79. SrcTypeSys = TypeSys;
  80. TypeSys->CopyFunctionAnnotation(NewF, F, *SrcTypeSys);
  81. }
  82. // Remove params from vmap.
  83. for (Argument &param : F->args()) {
  84. vmap.erase(&param);
  85. }
  86. }
  87. } // namespace
  88. namespace {
  89. struct DxilFunctionLinkInfo {
  90. DxilFunctionLinkInfo(llvm::Function *F);
  91. llvm::Function *func;
  92. // SetVectors for deterministic iteration
  93. llvm::SetVector<llvm::Function *> usedFunctions;
  94. llvm::SetVector<llvm::GlobalVariable *> usedGVs;
  95. };
  96. // Library to link.
  97. class DxilLib {
  98. public:
  99. DxilLib(std::unique_ptr<llvm::Module> pModule);
  100. virtual ~DxilLib() {}
  101. bool HasFunction(std::string &name);
  102. llvm::StringMap<std::unique_ptr<DxilFunctionLinkInfo>> &GetFunctionTable() {
  103. return m_functionNameMap;
  104. }
  105. bool IsInitFunc(llvm::Function *F);
  106. bool IsEntry(llvm::Function *F);
  107. bool IsResourceGlobal(const llvm::Constant *GV);
  108. DxilResourceBase *GetResource(const llvm::Constant *GV);
  109. DxilModule &GetDxilModule() { return m_DM; }
  110. void LazyLoadFunction(Function *F);
  111. void BuildGlobalUsage();
  112. void CollectUsedInitFunctions(SetVector<StringRef> &addedFunctionSet,
  113. SmallVector<StringRef, 4> &workList);
  114. void FixIntrinsicOverloads();
  115. private:
  116. std::unique_ptr<llvm::Module> m_pModule;
  117. DxilModule &m_DM;
  118. // Map from name to Link info for extern functions.
  119. llvm::StringMap<std::unique_ptr<DxilFunctionLinkInfo>> m_functionNameMap;
  120. llvm::SmallPtrSet<llvm::Function*,4> m_entrySet;
  121. // Map from resource link global to resource. MapVector for deterministic iteration.
  122. llvm::MapVector<const llvm::Constant *, DxilResourceBase *> m_resourceMap;
  123. // Set of initialize functions for global variable. SetVector for deterministic iteration.
  124. llvm::SetVector<llvm::Function *> m_initFuncSet;
  125. };
  126. struct DxilLinkJob;
  127. class DxilLinkerImpl : public hlsl::DxilLinker {
  128. public:
  129. DxilLinkerImpl(LLVMContext &Ctx, unsigned valMajor, unsigned valMinor) : DxilLinker(Ctx, valMajor, valMinor) {}
  130. virtual ~DxilLinkerImpl() {}
  131. bool HasLibNameRegistered(StringRef name) override;
  132. bool RegisterLib(StringRef name, std::unique_ptr<llvm::Module> pModule,
  133. std::unique_ptr<llvm::Module> pDebugModule) override;
  134. bool AttachLib(StringRef name) override;
  135. bool DetachLib(StringRef name) override;
  136. void DetachAll() override;
  137. std::unique_ptr<llvm::Module>
  138. Link(StringRef entry, StringRef profile, dxilutil::ExportMap &exportMap) override;
  139. private:
  140. bool AttachLib(DxilLib *lib);
  141. bool DetachLib(DxilLib *lib);
  142. bool AddFunctions(SmallVector<StringRef, 4> &workList,
  143. SetVector<DxilLib *> &libSet, SetVector<StringRef> &addedFunctionSet,
  144. DxilLinkJob &linkJob, bool bLazyLoadDone,
  145. bool bAllowFuncionDecls);
  146. // Attached libs to link.
  147. std::unordered_set<DxilLib *> m_attachedLibs;
  148. // Owner of all DxilLib.
  149. StringMap<std::unique_ptr<DxilLib>> m_LibMap;
  150. llvm::StringMap<std::pair<DxilFunctionLinkInfo *, DxilLib *>>
  151. m_functionNameMap;
  152. };
  153. } // namespace
  154. //------------------------------------------------------------------------------
  155. //
  156. // DxilFunctionLinkInfo methods.
  157. //
  158. DxilFunctionLinkInfo::DxilFunctionLinkInfo(Function *F) : func(F) {
  159. DXASSERT_NOMSG(F);
  160. }
  161. //------------------------------------------------------------------------------
  162. //
  163. // DxilLib methods.
  164. //
  165. DxilLib::DxilLib(std::unique_ptr<llvm::Module> pModule)
  166. : m_pModule(std::move(pModule)), m_DM(m_pModule->GetOrCreateDxilModule()) {
  167. Module &M = *m_pModule;
  168. const std::string MID = (Twine(M.getModuleIdentifier()) + ".").str();
  169. // Collect function defines.
  170. for (Function &F : M.functions()) {
  171. if (F.isDeclaration())
  172. continue;
  173. if (F.getLinkage() == GlobalValue::LinkageTypes::InternalLinkage) {
  174. // Add prefix to internal function.
  175. F.setName(MID + F.getName());
  176. }
  177. m_functionNameMap[F.getName()] =
  178. llvm::make_unique<DxilFunctionLinkInfo>(&F);
  179. if (m_DM.IsEntry(&F))
  180. m_entrySet.insert(&F);
  181. }
  182. // Update internal global name.
  183. for (GlobalVariable &GV : M.globals()) {
  184. if (GV.getLinkage() == GlobalValue::LinkageTypes::InternalLinkage) {
  185. // Add prefix to internal global.
  186. GV.setName(MID + GV.getName());
  187. }
  188. }
  189. }
  190. void DxilLib::FixIntrinsicOverloads() {
  191. // Fix DXIL overload name collisions that may be caused by name
  192. // collisions between dxil ops with different overload types,
  193. // when those types may have had the same name in the original
  194. // modules.
  195. m_DM.GetOP()->FixOverloadNames();
  196. }
  197. void DxilLib::LazyLoadFunction(Function *F) {
  198. DXASSERT(m_functionNameMap.count(F->getName()), "else invalid Function");
  199. DxilFunctionLinkInfo *linkInfo = m_functionNameMap[F->getName()].get();
  200. std::error_code EC = F->materialize();
  201. DXASSERT_LOCALVAR(EC, !EC, "else fail to materialize");
  202. // Build used functions for F.
  203. for (auto &BB : F->getBasicBlockList()) {
  204. for (auto &I : BB.getInstList()) {
  205. if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  206. linkInfo->usedFunctions.insert(CI->getCalledFunction());
  207. }
  208. }
  209. }
  210. if (m_DM.HasDxilFunctionProps(F)) {
  211. DxilFunctionProps &props = m_DM.GetDxilFunctionProps(F);
  212. if (props.IsHS()) {
  213. // Add patch constant function to usedFunctions of entry.
  214. Function *patchConstantFunc = props.ShaderProps.HS.patchConstantFunc;
  215. linkInfo->usedFunctions.insert(patchConstantFunc);
  216. }
  217. }
  218. // Used globals will be build before link.
  219. }
  220. void DxilLib::BuildGlobalUsage() {
  221. Module &M = *m_pModule;
  222. // Collect init functions for static globals.
  223. if (GlobalVariable *Ctors = M.getGlobalVariable("llvm.global_ctors")) {
  224. if (ConstantArray *CA = dyn_cast<ConstantArray>(Ctors->getInitializer())) {
  225. for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e;
  226. ++i) {
  227. if (isa<ConstantAggregateZero>(*i))
  228. continue;
  229. ConstantStruct *CS = cast<ConstantStruct>(*i);
  230. if (isa<ConstantPointerNull>(CS->getOperand(1)))
  231. continue;
  232. // Must have a function or null ptr.
  233. if (!isa<Function>(CS->getOperand(1)))
  234. continue;
  235. Function *Ctor = cast<Function>(CS->getOperand(1));
  236. assert(Ctor->getReturnType()->isVoidTy() && Ctor->arg_size() == 0 &&
  237. "function type must be void (void)");
  238. // Add Ctor.
  239. m_initFuncSet.insert(Ctor);
  240. LazyLoadFunction(Ctor);
  241. }
  242. }
  243. }
  244. // Build used globals.
  245. for (GlobalVariable &GV : M.globals()) {
  246. llvm::SetVector<Function *> funcSet;
  247. CollectUsedFunctions(&GV, funcSet);
  248. for (Function *F : funcSet) {
  249. DXASSERT(m_functionNameMap.count(F->getName()), "must exist in table");
  250. DxilFunctionLinkInfo *linkInfo = m_functionNameMap[F->getName()].get();
  251. linkInfo->usedGVs.insert(&GV);
  252. }
  253. }
  254. // Build resource map.
  255. AddResourceMap(m_DM.GetUAVs(), DXIL::ResourceClass::UAV, m_resourceMap, m_DM);
  256. AddResourceMap(m_DM.GetSRVs(), DXIL::ResourceClass::SRV, m_resourceMap, m_DM);
  257. AddResourceMap(m_DM.GetCBuffers(), DXIL::ResourceClass::CBuffer,
  258. m_resourceMap, m_DM);
  259. AddResourceMap(m_DM.GetSamplers(), DXIL::ResourceClass::Sampler,
  260. m_resourceMap, m_DM);
  261. }
  262. void DxilLib::CollectUsedInitFunctions(SetVector<StringRef> &addedFunctionSet,
  263. SmallVector<StringRef, 4> &workList) {
  264. // Add init functions to used functions.
  265. for (Function *Ctor : m_initFuncSet) {
  266. DXASSERT(m_functionNameMap.count(Ctor->getName()),
  267. "must exist in internal table");
  268. DxilFunctionLinkInfo *linkInfo = m_functionNameMap[Ctor->getName()].get();
  269. // If function other than Ctor used GV of Ctor.
  270. // Add Ctor to usedFunctions for it.
  271. for (GlobalVariable *GV : linkInfo->usedGVs) {
  272. llvm::SetVector<Function *> funcSet;
  273. CollectUsedFunctions(GV, funcSet);
  274. bool bAdded = false;
  275. for (Function *F : funcSet) {
  276. if (F == Ctor)
  277. continue;
  278. // If F is added for link, add init func to workList.
  279. if (addedFunctionSet.count(F->getName())) {
  280. workList.emplace_back(Ctor->getName());
  281. bAdded = true;
  282. break;
  283. }
  284. }
  285. if (bAdded)
  286. break;
  287. }
  288. }
  289. }
  290. bool DxilLib::HasFunction(std::string &name) {
  291. return m_functionNameMap.count(name);
  292. }
  293. bool DxilLib::IsEntry(llvm::Function *F) { return m_entrySet.count(F); }
  294. bool DxilLib::IsInitFunc(llvm::Function *F) { return m_initFuncSet.count(F); }
  295. bool DxilLib::IsResourceGlobal(const llvm::Constant *GV) {
  296. return m_resourceMap.count(GV);
  297. }
  298. DxilResourceBase *DxilLib::GetResource(const llvm::Constant *GV) {
  299. if (IsResourceGlobal(GV))
  300. return m_resourceMap[GV];
  301. else
  302. return nullptr;
  303. }
  304. namespace {
  305. // Create module from link defines.
  306. struct DxilLinkJob {
  307. DxilLinkJob(LLVMContext &Ctx, dxilutil::ExportMap &exportMap,
  308. unsigned valMajor, unsigned valMinor)
  309. : m_ctx(Ctx), m_exportMap(exportMap), m_valMajor(valMajor),
  310. m_valMinor(valMinor) {}
  311. std::unique_ptr<llvm::Module>
  312. Link(std::pair<DxilFunctionLinkInfo *, DxilLib *> &entryLinkPair,
  313. const ShaderModel *pSM);
  314. std::unique_ptr<llvm::Module> LinkToLib(const ShaderModel *pSM);
  315. void StripDeadDebugInfo(llvm::Module &M);
  316. // Fix issues when link to different shader model.
  317. void FixShaderModelMismatch(llvm::Module &M);
  318. void RunPreparePass(llvm::Module &M);
  319. void AddFunction(std::pair<DxilFunctionLinkInfo *, DxilLib *> &linkPair);
  320. void AddFunction(llvm::Function *F);
  321. private:
  322. void LinkNamedMDNodes(Module *pM, ValueToValueMapTy &vmap);
  323. void AddFunctionDecls(Module *pM);
  324. bool AddGlobals(DxilModule &DM, ValueToValueMapTy &vmap);
  325. void EmitCtorListForLib(Module *pM);
  326. void CloneFunctions(ValueToValueMapTy &vmap);
  327. void AddFunctions(DxilModule &DM, ValueToValueMapTy &vmap);
  328. bool AddResource(DxilResourceBase *res, llvm::GlobalVariable *GV);
  329. void AddResourceToDM(DxilModule &DM);
  330. llvm::MapVector<DxilFunctionLinkInfo *, DxilLib *> m_functionDefs;
  331. // Function decls, in order added.
  332. llvm::MapVector<llvm::StringRef,
  333. std::pair<llvm::SmallPtrSet<llvm::FunctionType *, 2>,
  334. llvm::SmallVector<llvm::Function *, 2>>>
  335. m_functionDecls;
  336. // New created functions, in order added.
  337. llvm::MapVector<llvm::StringRef, llvm::Function *> m_newFunctions;
  338. // New created globals, in order added.
  339. llvm::MapVector<llvm::StringRef, llvm::GlobalVariable *> m_newGlobals;
  340. // Map for resource, ordered by name.
  341. std::map<llvm::StringRef,
  342. std::pair<DxilResourceBase *, llvm::GlobalVariable *>>
  343. m_resourceMap;
  344. LLVMContext &m_ctx;
  345. dxilutil::ExportMap &m_exportMap;
  346. unsigned m_valMajor, m_valMinor;
  347. };
  348. } // namespace
  349. namespace {
  350. const char kUndefFunction[] = "Cannot find definition of function ";
  351. const char kRedefineFunction[] = "Definition already exists for function ";
  352. const char kRedefineGlobal[] = "Definition already exists for global variable ";
  353. const char kInvalidProfile[] = " is invalid profile to link";
  354. const char kExportOnlyForLib[] = "export map is only for library";
  355. const char kShaderKindMismatch[] =
  356. "Profile mismatch between entry function and target profile:";
  357. const char kNoEntryProps[] =
  358. "Cannot find function property for entry function ";
  359. const char kRedefineResource[] =
  360. "Resource already exists as ";
  361. const char kInvalidValidatorVersion[] = "Validator version does not support target profile ";
  362. const char kExportNameCollision[] = "Export name collides with another export: ";
  363. const char kExportFunctionMissing[] = "Could not find target for export: ";
  364. const char kNoFunctionsToExport[] = "Library has no functions to export";
  365. } // namespace
  366. //------------------------------------------------------------------------------
  367. //
  368. // DxilLinkJob methods.
  369. //
  370. namespace {
  371. // Helper function to check type match.
  372. bool IsMatchedType(Type *Ty0, Type *Ty);
  373. StringRef RemoveNameSuffix(StringRef Name) {
  374. size_t DotPos = Name.rfind('.');
  375. if (DotPos != StringRef::npos && Name.back() != '.' &&
  376. isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
  377. Name = Name.substr(0, DotPos);
  378. return Name;
  379. }
  380. bool IsMatchedStructType(StructType *ST0, StructType *ST) {
  381. StringRef Name0 = RemoveNameSuffix(ST0->getName());
  382. StringRef Name = RemoveNameSuffix(ST->getName());
  383. if (Name0 != Name)
  384. return false;
  385. if (ST0->getNumElements() != ST->getNumElements())
  386. return false;
  387. if (ST0->isLayoutIdentical(ST))
  388. return true;
  389. for (unsigned i = 0; i < ST->getNumElements(); i++) {
  390. Type *Ty = ST->getElementType(i);
  391. Type *Ty0 = ST0->getElementType(i);
  392. if (!IsMatchedType(Ty, Ty0))
  393. return false;
  394. }
  395. return true;
  396. }
  397. bool IsMatchedArrayType(ArrayType *AT0, ArrayType *AT) {
  398. if (AT0->getNumElements() != AT->getNumElements())
  399. return false;
  400. return IsMatchedType(AT0->getElementType(), AT->getElementType());
  401. }
  402. bool IsMatchedType(Type *Ty0, Type *Ty) {
  403. if (Ty0->isStructTy() && Ty->isStructTy()) {
  404. StructType *ST0 = cast<StructType>(Ty0);
  405. StructType *ST = cast<StructType>(Ty);
  406. return IsMatchedStructType(ST0, ST);
  407. }
  408. if (Ty0->isArrayTy() && Ty->isArrayTy()) {
  409. ArrayType *AT0 = cast<ArrayType>(Ty0);
  410. ArrayType *AT = cast<ArrayType>(Ty);
  411. return IsMatchedArrayType(AT0, AT);
  412. }
  413. if (Ty0->isPointerTy() && Ty->isPointerTy()) {
  414. if (Ty0->getPointerAddressSpace() != Ty->getPointerAddressSpace())
  415. return false;
  416. return IsMatchedType(Ty0->getPointerElementType(),
  417. Ty->getPointerElementType());
  418. }
  419. return Ty0 == Ty;
  420. }
  421. } // namespace
  422. bool DxilLinkJob::AddResource(DxilResourceBase *res, llvm::GlobalVariable *GV) {
  423. if (m_resourceMap.count(res->GetGlobalName())) {
  424. DxilResourceBase *res0 = m_resourceMap[res->GetGlobalName()].first;
  425. Type *Ty0 = res0->GetHLSLType()->getPointerElementType();
  426. Type *Ty = res->GetHLSLType()->getPointerElementType();
  427. // Make sure res0 match res.
  428. bool bMatch = IsMatchedType(Ty0, Ty);
  429. if (!bMatch) {
  430. // Report error.
  431. dxilutil::EmitErrorOnGlobalVariable(m_ctx, dyn_cast<GlobalVariable>(res->GetGlobalSymbol()),
  432. Twine(kRedefineResource) + res->GetResClassName() + " for " +
  433. res->GetGlobalName());
  434. return false;
  435. }
  436. } else {
  437. m_resourceMap[res->GetGlobalName()] = std::make_pair(res, GV);
  438. }
  439. return true;
  440. }
  441. void DxilLinkJob::AddResourceToDM(DxilModule &DM) {
  442. for (auto &it : m_resourceMap) {
  443. DxilResourceBase *res = it.second.first;
  444. GlobalVariable *GV = it.second.second;
  445. unsigned ID = 0;
  446. DxilResourceBase *basePtr = nullptr;
  447. switch (res->GetClass()) {
  448. case DXIL::ResourceClass::UAV: {
  449. std::unique_ptr<DxilResource> pUAV = llvm::make_unique<DxilResource>();
  450. DxilResource *ptr = pUAV.get();
  451. // Copy the content.
  452. *ptr = *(static_cast<DxilResource *>(res));
  453. ID = DM.AddUAV(std::move(pUAV));
  454. basePtr = &DM.GetUAV(ID);
  455. } break;
  456. case DXIL::ResourceClass::SRV: {
  457. std::unique_ptr<DxilResource> pSRV = llvm::make_unique<DxilResource>();
  458. DxilResource *ptr = pSRV.get();
  459. // Copy the content.
  460. *ptr = *(static_cast<DxilResource *>(res));
  461. ID = DM.AddSRV(std::move(pSRV));
  462. basePtr = &DM.GetSRV(ID);
  463. } break;
  464. case DXIL::ResourceClass::CBuffer: {
  465. std::unique_ptr<DxilCBuffer> pCBuf = llvm::make_unique<DxilCBuffer>();
  466. DxilCBuffer *ptr = pCBuf.get();
  467. // Copy the content.
  468. *ptr = *(static_cast<DxilCBuffer *>(res));
  469. ID = DM.AddCBuffer(std::move(pCBuf));
  470. basePtr = &DM.GetCBuffer(ID);
  471. } break;
  472. case DXIL::ResourceClass::Sampler: {
  473. std::unique_ptr<DxilSampler> pSampler = llvm::make_unique<DxilSampler>();
  474. DxilSampler *ptr = pSampler.get();
  475. // Copy the content.
  476. *ptr = *(static_cast<DxilSampler *>(res));
  477. ID = DM.AddSampler(std::move(pSampler));
  478. basePtr = &DM.GetSampler(ID);
  479. }
  480. default:
  481. DXASSERT(res->GetClass() == DXIL::ResourceClass::Sampler,
  482. "else invalid resource");
  483. break;
  484. }
  485. // Update ID.
  486. basePtr->SetID(ID);
  487. basePtr->SetGlobalSymbol(GV);
  488. DM.GetLLVMUsed().push_back(GV);
  489. }
  490. // Prevent global vars used for resources from being deleted through optimizations
  491. // while we still have hidden uses (pointers in resource vectors).
  492. DM.EmitLLVMUsed();
  493. }
  494. void DxilLinkJob::LinkNamedMDNodes(Module *pM, ValueToValueMapTy &vmap) {
  495. SetVector<Module *> moduleSet;
  496. for (auto &it : m_functionDefs) {
  497. DxilLib *pLib = it.second;
  498. moduleSet.insert(pLib->GetDxilModule().GetModule());
  499. }
  500. // Link normal NamedMDNode.
  501. // TODO: skip duplicate operands.
  502. for (Module *pSrcM : moduleSet) {
  503. const NamedMDNode *pSrcModFlags = pSrcM->getModuleFlagsMetadata();
  504. for (const NamedMDNode &NMD : pSrcM->named_metadata()) {
  505. // Don't link module flags here. Do them separately.
  506. if (&NMD == pSrcModFlags)
  507. continue;
  508. // Skip dxil metadata which will be regenerated.
  509. if (DxilMDHelper::IsKnownNamedMetaData(NMD))
  510. continue;
  511. NamedMDNode *DestNMD = pM->getOrInsertNamedMetadata(NMD.getName());
  512. // Add Src elements into Dest node.
  513. for (const MDNode *op : NMD.operands())
  514. DestNMD->addOperand(MapMetadata(op, vmap, RF_None, /*TypeMap*/ nullptr,
  515. /*ValMaterializer*/ nullptr));
  516. }
  517. }
  518. // Link mod flags.
  519. SetVector<MDNode *> flagSet;
  520. for (Module *pSrcM : moduleSet) {
  521. NamedMDNode *pSrcModFlags = pSrcM->getModuleFlagsMetadata();
  522. if (pSrcModFlags) {
  523. for (MDNode *flag : pSrcModFlags->operands()) {
  524. flagSet.insert(flag);
  525. }
  526. }
  527. }
  528. // TODO: check conflict in flags.
  529. if (!flagSet.empty()) {
  530. NamedMDNode *ModFlags = pM->getOrInsertModuleFlagsMetadata();
  531. for (MDNode *flag : flagSet) {
  532. ModFlags->addOperand(flag);
  533. }
  534. }
  535. }
  536. void DxilLinkJob::AddFunctionDecls(Module *pM) {
  537. for (auto &it : m_functionDecls) {
  538. for (auto F : it.second.second) {
  539. Function *NewF = pM->getFunction(F->getName());
  540. if (!NewF || F->getFunctionType() != NewF->getFunctionType()) {
  541. NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
  542. F->getName(), pM);
  543. NewF->setAttributes(F->getAttributes());
  544. }
  545. m_newFunctions[F->getName()] = NewF;
  546. }
  547. }
  548. }
  549. bool DxilLinkJob::AddGlobals(DxilModule &DM, ValueToValueMapTy &vmap) {
  550. DxilTypeSystem &typeSys = DM.GetTypeSystem();
  551. Module *pM = DM.GetModule();
  552. bool bSuccess = true;
  553. for (auto &it : m_functionDefs) {
  554. DxilFunctionLinkInfo *linkInfo = it.first;
  555. DxilLib *pLib = it.second;
  556. DxilModule &tmpDM = pLib->GetDxilModule();
  557. DxilTypeSystem &tmpTypeSys = tmpDM.GetTypeSystem();
  558. for (GlobalVariable *GV : linkInfo->usedGVs) {
  559. // Skip added globals.
  560. if (m_newGlobals.count(GV->getName())) {
  561. if (vmap.find(GV) == vmap.end()) {
  562. if (DxilResourceBase *res = pLib->GetResource(GV)) {
  563. // For resource of same name, if class and type match, just map to
  564. // same NewGV.
  565. GlobalVariable *NewGV = m_newGlobals[GV->getName()];
  566. if (AddResource(res, NewGV)) {
  567. vmap[GV] = NewGV;
  568. } else {
  569. bSuccess = false;
  570. }
  571. continue;
  572. }
  573. // Redefine of global.
  574. dxilutil::EmitErrorOnGlobalVariable(m_ctx, GV, Twine(kRedefineGlobal) + GV->getName());
  575. bSuccess = false;
  576. }
  577. continue;
  578. }
  579. Constant *Initializer = nullptr;
  580. if (GV->hasInitializer())
  581. Initializer = GV->getInitializer();
  582. Type *Ty = GV->getType()->getElementType();
  583. GlobalVariable *NewGV = new GlobalVariable(
  584. *pM, Ty, GV->isConstant(), GV->getLinkage(), Initializer,
  585. GV->getName(),
  586. /*InsertBefore*/ nullptr, GV->getThreadLocalMode(),
  587. GV->getType()->getAddressSpace(), GV->isExternallyInitialized());
  588. m_newGlobals[GV->getName()] = NewGV;
  589. vmap[GV] = NewGV;
  590. typeSys.CopyTypeAnnotation(Ty, tmpTypeSys);
  591. if (DxilResourceBase *res = pLib->GetResource(GV)) {
  592. bSuccess &= AddResource(res, NewGV);
  593. }
  594. }
  595. }
  596. return bSuccess;
  597. }
  598. void DxilLinkJob::CloneFunctions(ValueToValueMapTy &vmap) {
  599. for (auto &it : m_functionDefs) {
  600. DxilFunctionLinkInfo *linkInfo = it.first;
  601. Function *F = linkInfo->func;
  602. Function *NewF = m_newFunctions[F->getName()];
  603. // Add dxil functions to vmap.
  604. for (Function *UsedF : linkInfo->usedFunctions) {
  605. if (!vmap.count(UsedF)) {
  606. // Extern function need match by name
  607. DXASSERT(m_newFunctions.count(UsedF->getName()),
  608. "Must have new function.");
  609. vmap[UsedF] = m_newFunctions[UsedF->getName()];
  610. }
  611. }
  612. CloneFunction(F, NewF, vmap);
  613. }
  614. }
  615. void DxilLinkJob::AddFunctions(DxilModule &DM, ValueToValueMapTy &vmap) {
  616. DxilTypeSystem &typeSys = DM.GetTypeSystem();
  617. Module *pM = DM.GetModule();
  618. for (auto &it : m_functionDefs) {
  619. DxilFunctionLinkInfo *linkInfo = it.first;
  620. DxilLib *pLib = it.second;
  621. DxilModule &tmpDM = pLib->GetDxilModule();
  622. DxilTypeSystem &tmpTypeSys = tmpDM.GetTypeSystem();
  623. Function *F = linkInfo->func;
  624. Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
  625. F->getName(), pM);
  626. NewF->setAttributes(F->getAttributes());
  627. if (!NewF->hasFnAttribute(llvm::Attribute::NoInline))
  628. NewF->addFnAttr(llvm::Attribute::AlwaysInline);
  629. if (DxilFunctionAnnotation *funcAnnotation =
  630. tmpTypeSys.GetFunctionAnnotation(F)) {
  631. // Clone funcAnnotation to typeSys.
  632. typeSys.CopyFunctionAnnotation(NewF, F, tmpTypeSys);
  633. }
  634. // Add to function map.
  635. m_newFunctions[NewF->getName()] = NewF;
  636. vmap[F] = NewF;
  637. }
  638. }
  639. std::unique_ptr<Module>
  640. DxilLinkJob::Link(std::pair<DxilFunctionLinkInfo *, DxilLib *> &entryLinkPair,
  641. const ShaderModel *pSM) {
  642. Function *entryFunc = entryLinkPair.first->func;
  643. DxilModule &entryDM = entryLinkPair.second->GetDxilModule();
  644. if (!entryDM.HasDxilFunctionProps(entryFunc)) {
  645. // Cannot get function props.
  646. dxilutil::EmitErrorOnFunction(m_ctx, entryFunc, Twine(kNoEntryProps) + entryFunc->getName());
  647. return nullptr;
  648. }
  649. DxilFunctionProps props = entryDM.GetDxilFunctionProps(entryFunc);
  650. if (pSM->GetKind() != props.shaderKind) {
  651. // Shader kind mismatch.
  652. dxilutil::EmitErrorOnFunction(m_ctx, entryFunc, Twine(kShaderKindMismatch) +
  653. ShaderModel::GetKindName(pSM->GetKind()) + " and " +
  654. ShaderModel::GetKindName(props.shaderKind));
  655. return nullptr;
  656. }
  657. // Create new module.
  658. std::unique_ptr<Module> pM =
  659. llvm::make_unique<Module>(entryFunc->getName(), entryDM.GetCtx());
  660. // Set target.
  661. pM->setTargetTriple(entryDM.GetModule()->getTargetTriple());
  662. // Add dxil operation functions before create DxilModule.
  663. AddFunctionDecls(pM.get());
  664. // Create DxilModule.
  665. const bool bSkipInit = true;
  666. DxilModule &DM = pM->GetOrCreateDxilModule(bSkipInit);
  667. DM.SetShaderModel(pSM, entryDM.GetUseMinPrecision());
  668. // Set Validator version.
  669. DM.SetValidatorVersion(m_valMajor, m_valMinor);
  670. ValueToValueMapTy vmap;
  671. // Add function
  672. AddFunctions(DM, vmap);
  673. // Set Entry
  674. Function *NewEntryFunc = m_newFunctions[entryFunc->getName()];
  675. DM.SetEntryFunction(NewEntryFunc);
  676. DM.SetEntryFunctionName(entryFunc->getName());
  677. DxilEntryPropsMap EntryPropMap;
  678. std::unique_ptr<DxilEntryProps> pProps =
  679. llvm::make_unique<DxilEntryProps>(entryDM.GetDxilEntryProps(entryFunc));
  680. EntryPropMap[NewEntryFunc] = std::move(pProps);
  681. DM.ResetEntryPropsMap(std::move(EntryPropMap));
  682. if (NewEntryFunc->hasFnAttribute(llvm::Attribute::AlwaysInline))
  683. NewEntryFunc->removeFnAttr(llvm::Attribute::AlwaysInline);
  684. if (props.IsHS()) {
  685. Function *patchConstantFunc = props.ShaderProps.HS.patchConstantFunc;
  686. Function *newPatchConstantFunc =
  687. m_newFunctions[patchConstantFunc->getName()];
  688. props.ShaderProps.HS.patchConstantFunc = newPatchConstantFunc;
  689. if (newPatchConstantFunc->hasFnAttribute(llvm::Attribute::AlwaysInline))
  690. newPatchConstantFunc->removeFnAttr(llvm::Attribute::AlwaysInline);
  691. }
  692. // Set root sig if exist.
  693. if (!props.serializedRootSignature.empty()) {
  694. DM.ResetSerializedRootSignature(props.serializedRootSignature);
  695. props.serializedRootSignature.clear();
  696. }
  697. // Set EntryProps
  698. DM.SetShaderProperties(&props);
  699. // Add global
  700. bool bSuccess = AddGlobals(DM, vmap);
  701. if (!bSuccess)
  702. return nullptr;
  703. // Clone functions.
  704. CloneFunctions(vmap);
  705. // Call global constrctor.
  706. IRBuilder<> Builder(dxilutil::FindAllocaInsertionPt(DM.GetEntryFunction()));
  707. for (auto &it : m_functionDefs) {
  708. DxilFunctionLinkInfo *linkInfo = it.first;
  709. DxilLib *pLib = it.second;
  710. // Skip constructor in entry lib which is already called for entries inside
  711. // entry lib.
  712. if (pLib == entryLinkPair.second)
  713. continue;
  714. Function *F = linkInfo->func;
  715. if (pLib->IsInitFunc(F)) {
  716. Function *NewF = m_newFunctions[F->getName()];
  717. Builder.CreateCall(NewF);
  718. }
  719. }
  720. // Refresh intrinsic cache.
  721. DM.GetOP()->RefreshCache();
  722. // Add resource to DM.
  723. // This should be after functions cloned.
  724. AddResourceToDM(DM);
  725. // Link metadata like debug info.
  726. LinkNamedMDNodes(pM.get(), vmap);
  727. RunPreparePass(*pM);
  728. return pM;
  729. }
  730. // Based on CodeGenModule::EmitCtorList.
  731. void DxilLinkJob::EmitCtorListForLib(Module *pM) {
  732. LLVMContext &Ctx = pM->getContext();
  733. Type *VoidTy = Type::getVoidTy(Ctx);
  734. Type *Int32Ty = Type::getInt32Ty(Ctx);
  735. Type *VoidPtrTy = Type::getInt8PtrTy(Ctx);
  736. // Ctor function type is void()*.
  737. llvm::FunctionType *CtorFTy = llvm::FunctionType::get(VoidTy, false);
  738. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  739. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  740. llvm::StructType *CtorStructTy = llvm::StructType::get(
  741. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
  742. // Construct the constructor and destructor arrays.
  743. SmallVector<llvm::Constant *, 8> Ctors;
  744. for (auto &it : m_functionDefs) {
  745. DxilFunctionLinkInfo *linkInfo = it.first;
  746. DxilLib *pLib = it.second;
  747. Function *F = linkInfo->func;
  748. if (pLib->IsInitFunc(F)) {
  749. Function *NewF = m_newFunctions[F->getName()];
  750. llvm::Constant *S[] = {
  751. llvm::ConstantInt::get(Int32Ty, 65535, false),
  752. llvm::ConstantExpr::getBitCast(NewF, CtorPFTy),
  753. (llvm::Constant::getNullValue(VoidPtrTy))};
  754. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  755. }
  756. }
  757. if (!Ctors.empty()) {
  758. const StringRef GlobalName = "llvm.global_ctors";
  759. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  760. new llvm::GlobalVariable(*pM, AT, false,
  761. llvm::GlobalValue::AppendingLinkage,
  762. llvm::ConstantArray::get(AT, Ctors), GlobalName);
  763. }
  764. }
  765. std::unique_ptr<Module>
  766. DxilLinkJob::LinkToLib(const ShaderModel *pSM) {
  767. if (m_functionDefs.empty()) {
  768. m_ctx.emitError(Twine(kNoFunctionsToExport));
  769. return nullptr;
  770. }
  771. DxilLib *pLib = m_functionDefs.begin()->second;
  772. DxilModule &tmpDM = pLib->GetDxilModule();
  773. // Create new module.
  774. std::unique_ptr<Module> pM =
  775. llvm::make_unique<Module>("merged_lib", tmpDM.GetCtx());
  776. // Set target.
  777. pM->setTargetTriple(tmpDM.GetModule()->getTargetTriple());
  778. // Add dxil operation functions and external decls before create DxilModule.
  779. AddFunctionDecls(pM.get());
  780. // Create DxilModule.
  781. const bool bSkipInit = true;
  782. DxilModule &DM = pM->GetOrCreateDxilModule(bSkipInit);
  783. DM.SetShaderModel(pSM, tmpDM.GetUseMinPrecision());
  784. // Set Validator version.
  785. DM.SetValidatorVersion(m_valMajor, m_valMinor);
  786. ValueToValueMapTy vmap;
  787. // Add function
  788. AddFunctions(DM, vmap);
  789. // Set DxilFunctionProps.
  790. DxilEntryPropsMap EntryPropMap;
  791. for (auto &it : m_functionDefs) {
  792. DxilFunctionLinkInfo *linkInfo = it.first;
  793. DxilLib *pLib = it.second;
  794. DxilModule &tmpDM = pLib->GetDxilModule();
  795. Function *F = linkInfo->func;
  796. if (tmpDM.HasDxilEntryProps(F)) {
  797. Function *NewF = m_newFunctions[F->getName()];
  798. DxilEntryProps &props = tmpDM.GetDxilEntryProps(F);
  799. std::unique_ptr<DxilEntryProps> pProps =
  800. llvm::make_unique<DxilEntryProps>(props);
  801. EntryPropMap[NewF] = std::move(pProps);
  802. }
  803. }
  804. DM.ResetEntryPropsMap(std::move(EntryPropMap));
  805. // Add global
  806. bool bSuccess = AddGlobals(DM, vmap);
  807. if (!bSuccess)
  808. return nullptr;
  809. // Clone functions.
  810. CloneFunctions(vmap);
  811. // Refresh intrinsic cache.
  812. DM.GetOP()->RefreshCache();
  813. // Add resource to DM.
  814. // This should be after functions cloned.
  815. AddResourceToDM(DM);
  816. // Link metadata like debug info.
  817. LinkNamedMDNodes(pM.get(), vmap);
  818. // Build global.ctors.
  819. EmitCtorListForLib(pM.get());
  820. RunPreparePass(*pM);
  821. if (!m_exportMap.empty()) {
  822. m_exportMap.BeginProcessing();
  823. DM.ClearDxilMetadata(*pM);
  824. for (auto it = pM->begin(); it != pM->end();) {
  825. Function *F = it++;
  826. if (F->isDeclaration())
  827. continue;
  828. if (!m_exportMap.ProcessFunction(F, true)) {
  829. // Remove Function not in exportMap.
  830. DM.RemoveFunction(F);
  831. F->eraseFromParent();
  832. }
  833. }
  834. if(!m_exportMap.EndProcessing()) {
  835. for (auto &name : m_exportMap.GetNameCollisions()) {
  836. std::string escaped;
  837. llvm::raw_string_ostream os(escaped);
  838. dxilutil::PrintEscapedString(name, os);
  839. m_ctx.emitError(Twine(kExportNameCollision) + os.str());
  840. }
  841. for (auto &name : m_exportMap.GetUnusedExports()) {
  842. std::string escaped;
  843. llvm::raw_string_ostream os(escaped);
  844. dxilutil::PrintEscapedString(name, os);
  845. m_ctx.emitError(Twine(kExportFunctionMissing) + os.str());
  846. }
  847. return nullptr;
  848. }
  849. // Rename the original, if necessary, then clone the rest
  850. for (auto &it : m_exportMap.GetFunctionRenames()) {
  851. Function *F = it.first;
  852. auto &renames = it.second;
  853. if (renames.empty())
  854. continue;
  855. auto itName = renames.begin();
  856. // Rename the original, if necessary, then clone the rest
  857. if (renames.find(F->getName()) == renames.end())
  858. F->setName(*(itName++));
  859. while (itName != renames.end()) {
  860. if (F->getName() != *itName) {
  861. Function *NewF = Function::Create(F->getFunctionType(),
  862. GlobalValue::LinkageTypes::ExternalLinkage,
  863. *itName, DM.GetModule());
  864. ValueToValueMapTy vmap;
  865. CloneFunction(F, NewF, vmap, &DM.GetTypeSystem());
  866. // add DxilFunctionProps if entry
  867. if (DM.HasDxilFunctionProps(F)) {
  868. DM.CloneDxilEntryProps(F, NewF);
  869. }
  870. }
  871. itName++;
  872. }
  873. }
  874. DM.EmitDxilMetadata();
  875. }
  876. return pM;
  877. }
  878. void DxilLinkJob::AddFunction(
  879. std::pair<DxilFunctionLinkInfo *, DxilLib *> &linkPair) {
  880. m_functionDefs[linkPair.first] = linkPair.second;
  881. }
  882. void DxilLinkJob::AddFunction(llvm::Function *F) {
  883. // Rarely, DXIL op overloads could collide, due to different types with same name.
  884. // Later, we will rename these functions, but for now, we need to prevent clobbering
  885. // an existing entry.
  886. auto &entry = m_functionDecls[F->getName()];
  887. if (entry.first.insert(F->getFunctionType()).second)
  888. entry.second.push_back(F);
  889. }
  890. // Clone of StripDeadDebugInfo::runOnModule.
  891. // Also remove function which not not in current Module.
  892. void DxilLinkJob::StripDeadDebugInfo(Module &M) {
  893. LLVMContext &C = M.getContext();
  894. // Find all debug info in F. This is actually overkill in terms of what we
  895. // want to do, but we want to try and be as resilient as possible in the face
  896. // of potential debug info changes by using the formal interfaces given to us
  897. // as much as possible.
  898. DebugInfoFinder F;
  899. F.processModule(M);
  900. // For each compile unit, find the live set of global variables/functions and
  901. // replace the current list of potentially dead global variables/functions
  902. // with the live list.
  903. SmallVector<Metadata *, 64> LiveGlobalVariables;
  904. SmallVector<Metadata *, 64> LiveSubprograms;
  905. DenseSet<const MDNode *> VisitedSet;
  906. for (DICompileUnit *DIC : F.compile_units()) {
  907. // Create our live subprogram list.
  908. bool SubprogramChange = false;
  909. for (DISubprogram *DISP : DIC->getSubprograms()) {
  910. // Make sure we visit each subprogram only once.
  911. if (!VisitedSet.insert(DISP).second)
  912. continue;
  913. // If the function referenced by DISP is not null, the function is live.
  914. if (Function *Func = DISP->getFunction()) {
  915. if (Func->getParent() == &M)
  916. LiveSubprograms.push_back(DISP);
  917. else
  918. SubprogramChange = true;
  919. } else {
  920. SubprogramChange = true;
  921. }
  922. }
  923. // Create our live global variable list.
  924. bool GlobalVariableChange = false;
  925. for (DIGlobalVariable *DIG : DIC->getGlobalVariables()) {
  926. // Make sure we only visit each global variable only once.
  927. if (!VisitedSet.insert(DIG).second)
  928. continue;
  929. // If the global variable referenced by DIG is not null, the global
  930. // variable is live.
  931. if (Constant *CV = DIG->getVariable()) {
  932. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CV)) {
  933. if (GV->getParent() == &M) {
  934. LiveGlobalVariables.push_back(DIG);
  935. } else {
  936. GlobalVariableChange = true;
  937. }
  938. } else {
  939. LiveGlobalVariables.push_back(DIG);
  940. }
  941. } else {
  942. GlobalVariableChange = true;
  943. }
  944. }
  945. // If we found dead subprograms or global variables, replace the current
  946. // subprogram list/global variable list with our new live subprogram/global
  947. // variable list.
  948. if (SubprogramChange) {
  949. DIC->replaceSubprograms(MDTuple::get(C, LiveSubprograms));
  950. }
  951. if (GlobalVariableChange) {
  952. DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
  953. }
  954. // Reset lists for the next iteration.
  955. LiveSubprograms.clear();
  956. LiveGlobalVariables.clear();
  957. }
  958. }
  959. // TODO: move FixShaderModelMismatch to separate file.
  960. #include "dxc/DXIL/DxilInstructions.h"
  961. namespace {
  962. bool onlyUsedByAnnotateHandle(Value *V) {
  963. bool bResult = true;
  964. for (User *U : V->users()) {
  965. CallInst *CI = dyn_cast<CallInst>(U);
  966. if (!CI) {
  967. bResult = false;
  968. break;
  969. }
  970. DxilInst_AnnotateHandle Hdl(CI);
  971. if (!Hdl) {
  972. bResult = false;
  973. break;
  974. }
  975. }
  976. return bResult;
  977. }
  978. DxilResourceBase *
  979. findResourceFromPtr(Value *Ptr, DxilModule &DM,
  980. DenseMap<Value *, DxilResourceBase *> &PtrResMap) {
  981. auto it = PtrResMap.find(Ptr);
  982. if (Ptr)
  983. return it->second;
  984. DxilResourceBase *Res = nullptr;
  985. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
  986. DXASSERT(false, "global resource should already in map");
  987. } else {
  988. // Not support allocaInst of resource when missing annotateHandle.
  989. GEPOperator *GEP = cast<GEPOperator>(Ptr);
  990. Res = findResourceFromPtr(GEP->getPointerOperand(), DM, PtrResMap);
  991. }
  992. PtrResMap[Ptr] = Res;
  993. return Res;
  994. }
  995. template <typename T>
  996. void addGVFromResTable(T &Tab,
  997. DenseMap<Value *, DxilResourceBase *> &PtrResMap) {
  998. for (auto &it : Tab) {
  999. PtrResMap[it->GetGlobalSymbol()] = it.get();
  1000. }
  1001. }
  1002. // Make sure createHandleForLib is annotated before use.
  1003. bool addAnnotHandle(Module &M, DxilModule &DM) {
  1004. hlsl::OP *hlslOP = DM.GetOP();
  1005. auto *pSM = DM.GetShaderModel();
  1006. if (!pSM->IsSM66Plus())
  1007. return false;
  1008. // If no createHandleForLib, do nothing.
  1009. if (!hlslOP->IsDxilOpUsed(DXIL::OpCode::CreateHandleForLib))
  1010. return false;
  1011. Type *pVoidTy = Type::getVoidTy(M.getContext());
  1012. SmallVector<CallInst *, 4> Candidates;
  1013. for (Function &F : M) {
  1014. if (!F.isDeclaration())
  1015. continue;
  1016. if (!hlslOP->IsDxilOpFunc(&F))
  1017. continue;
  1018. DXIL::OpCodeClass opClass;
  1019. if (!hlslOP->GetOpCodeClass(&F, opClass))
  1020. continue;
  1021. if (opClass != DXIL::OpCodeClass::CreateHandleForLib)
  1022. continue;
  1023. for (User *U : F.users()) {
  1024. CallInst *CI = cast<CallInst>(U);
  1025. // Check user is annotateHandle.
  1026. if (onlyUsedByAnnotateHandle(CI))
  1027. continue;
  1028. Candidates.emplace_back(CI);
  1029. }
  1030. }
  1031. if (Candidates.empty())
  1032. return false;
  1033. DenseMap<Value *, DxilResourceBase *> PtrResMap;
  1034. // Add GV from resTable first.
  1035. addGVFromResTable(DM.GetCBuffers(), PtrResMap);
  1036. addGVFromResTable(DM.GetSRVs(), PtrResMap);
  1037. addGVFromResTable(DM.GetUAVs(), PtrResMap);
  1038. addGVFromResTable(DM.GetSamplers(), PtrResMap);
  1039. Function *annotHandleFn =
  1040. hlslOP->GetOpFunc(DXIL::OpCode::AnnotateHandle, pVoidTy);
  1041. Value *annotHandleArg =
  1042. hlslOP->GetI32Const((unsigned)DXIL::OpCode::AnnotateHandle);
  1043. // Replace createHandle with annotateHandle and createHandleFromBinding.
  1044. Type *resPropertyTy = hlslOP->GetResourcePropertiesType();
  1045. for (CallInst *CI : Candidates) {
  1046. DxilInst_CreateHandleForLib Hdl(CI);
  1047. LoadInst *Ld = cast<LoadInst>(Hdl.get_Resource());
  1048. Value *Ptr = Ld->getPointerOperand();
  1049. DxilResourceBase *Res = findResourceFromPtr(Ptr, DM, PtrResMap);
  1050. DXASSERT(Res, "fail to find resource when missing annotateHandle");
  1051. DxilResourceProperties RP = resource_helper::loadPropsFromResourceBase(Res);
  1052. Value *propertiesV =
  1053. resource_helper::getAsConstant(RP, resPropertyTy, *DM.GetShaderModel());
  1054. IRBuilder<> B(CI->getNextNode());
  1055. CallInst *annotHdl =
  1056. B.CreateCall(annotHandleFn, {annotHandleArg, CI, propertiesV});
  1057. CI->replaceAllUsesWith(annotHdl);
  1058. annotHdl->setArgOperand(DxilInst_AnnotateHandle::arg_res, CI);
  1059. }
  1060. return true;
  1061. }
  1062. } // namespace
  1063. void DxilLinkJob::FixShaderModelMismatch(llvm::Module &M) {
  1064. // TODO: fix more issues.
  1065. addAnnotHandle(M, M.GetDxilModule());
  1066. }
  1067. void DxilLinkJob::RunPreparePass(Module &M) {
  1068. StripDeadDebugInfo(M);
  1069. FixShaderModelMismatch(M);
  1070. DxilModule &DM = M.GetDxilModule();
  1071. const ShaderModel *pSM = DM.GetShaderModel();
  1072. legacy::PassManager PM;
  1073. PM.add(createAlwaysInlinerPass(/*InsertLifeTime*/ false));
  1074. // Remove unused functions.
  1075. PM.add(createDxilDeadFunctionEliminationPass());
  1076. // SROA
  1077. PM.add(createSROAPass(/*RequiresDomTree*/false, /*SkipHLSLMat*/false));
  1078. // For static global handle.
  1079. PM.add(createLowerStaticGlobalIntoAlloca());
  1080. // Remove MultiDimArray from function call arg.
  1081. PM.add(createMultiDimArrayToOneDimArrayPass());
  1082. // Lower matrix bitcast.
  1083. PM.add(createMatrixBitcastLowerPass());
  1084. // mem2reg.
  1085. PM.add(createPromoteMemoryToRegisterPass());
  1086. // Clean up vectors, and run mem2reg again
  1087. PM.add(createScalarizerPass());
  1088. PM.add(createPromoteMemoryToRegisterPass());
  1089. PM.add(createSimplifyInstPass());
  1090. PM.add(createCFGSimplificationPass());
  1091. PM.add(createDeadCodeEliminationPass());
  1092. PM.add(createGlobalDCEPass());
  1093. if (pSM->IsSM66Plus() && pSM->IsLib())
  1094. PM.add(createDxilMutateResourceToHandlePass());
  1095. PM.add(createDxilLowerCreateHandleForLibPass());
  1096. PM.add(createDxilTranslateRawBuffer());
  1097. PM.add(createDxilFinalizeModulePass());
  1098. PM.add(createComputeViewIdStatePass());
  1099. PM.add(createDxilDeadFunctionEliminationPass());
  1100. PM.add(createNoPausePassesPass());
  1101. PM.add(createDxilEmitMetadataPass());
  1102. PM.run(M);
  1103. }
  1104. //------------------------------------------------------------------------------
  1105. //
  1106. // DxilLinkerImpl methods.
  1107. //
  1108. bool DxilLinkerImpl::HasLibNameRegistered(StringRef name) {
  1109. return m_LibMap.count(name);
  1110. }
  1111. bool DxilLinkerImpl::RegisterLib(StringRef name,
  1112. std::unique_ptr<llvm::Module> pModule,
  1113. std::unique_ptr<llvm::Module> pDebugModule) {
  1114. if (m_LibMap.count(name))
  1115. return false;
  1116. std::unique_ptr<llvm::Module> pM =
  1117. pDebugModule ? std::move(pDebugModule) : std::move(pModule);
  1118. if (!pM)
  1119. return false;
  1120. pM->setModuleIdentifier(name);
  1121. std::unique_ptr<DxilLib> pLib =
  1122. llvm::make_unique<DxilLib>(std::move(pM));
  1123. m_LibMap[name] = std::move(pLib);
  1124. return true;
  1125. }
  1126. bool DxilLinkerImpl::AttachLib(StringRef name) {
  1127. auto iter = m_LibMap.find(name);
  1128. if (iter == m_LibMap.end()) {
  1129. return false;
  1130. }
  1131. return AttachLib(iter->second.get());
  1132. }
  1133. bool DxilLinkerImpl::DetachLib(StringRef name) {
  1134. auto iter = m_LibMap.find(name);
  1135. if (iter == m_LibMap.end()) {
  1136. return false;
  1137. }
  1138. return DetachLib(iter->second.get());
  1139. }
  1140. void DxilLinkerImpl::DetachAll() {
  1141. m_functionNameMap.clear();
  1142. m_attachedLibs.clear();
  1143. }
  1144. bool DxilLinkerImpl::AttachLib(DxilLib *lib) {
  1145. if (!lib) {
  1146. // Invalid arg.
  1147. return false;
  1148. }
  1149. if (m_attachedLibs.count(lib))
  1150. return false;
  1151. StringMap<std::unique_ptr<DxilFunctionLinkInfo>> &funcTable =
  1152. lib->GetFunctionTable();
  1153. bool bSuccess = true;
  1154. for (auto it = funcTable.begin(), e = funcTable.end(); it != e; it++) {
  1155. StringRef name = it->getKey();
  1156. if (m_functionNameMap.count(name)) {
  1157. // Redefine of function.
  1158. const DxilFunctionLinkInfo *DFLI = it->getValue().get();
  1159. dxilutil::EmitErrorOnFunction(m_ctx, DFLI->func, Twine(kRedefineFunction) + name);
  1160. bSuccess = false;
  1161. continue;
  1162. }
  1163. m_functionNameMap[name] = std::make_pair(it->second.get(), lib);
  1164. }
  1165. if (bSuccess) {
  1166. m_attachedLibs.insert(lib);
  1167. } else {
  1168. for (auto it = funcTable.begin(), e = funcTable.end(); it != e; it++) {
  1169. StringRef name = it->getKey();
  1170. auto iter = m_functionNameMap.find(name);
  1171. if (iter == m_functionNameMap.end())
  1172. continue;
  1173. // Remove functions of lib.
  1174. if (m_functionNameMap[name].second == lib)
  1175. m_functionNameMap.erase(name);
  1176. }
  1177. }
  1178. return bSuccess;
  1179. }
  1180. bool DxilLinkerImpl::DetachLib(DxilLib *lib) {
  1181. if (!lib) {
  1182. // Invalid arg.
  1183. return false;
  1184. }
  1185. if (!m_attachedLibs.count(lib))
  1186. return false;
  1187. m_attachedLibs.erase(lib);
  1188. // Remove functions from lib.
  1189. StringMap<std::unique_ptr<DxilFunctionLinkInfo>> &funcTable =
  1190. lib->GetFunctionTable();
  1191. for (auto it = funcTable.begin(), e = funcTable.end(); it != e; it++) {
  1192. StringRef name = it->getKey();
  1193. m_functionNameMap.erase(name);
  1194. }
  1195. return true;
  1196. }
  1197. bool DxilLinkerImpl::AddFunctions(SmallVector<StringRef, 4> &workList,
  1198. SetVector<DxilLib *> &libSet,
  1199. SetVector<StringRef> &addedFunctionSet,
  1200. DxilLinkJob &linkJob, bool bLazyLoadDone,
  1201. bool bAllowFuncionDecls) {
  1202. while (!workList.empty()) {
  1203. StringRef name = workList.pop_back_val();
  1204. // Ignore added function.
  1205. if (addedFunctionSet.count(name))
  1206. continue;
  1207. if (!m_functionNameMap.count(name)) {
  1208. // Cannot find function, report error.
  1209. m_ctx.emitError(Twine(kUndefFunction) + name);
  1210. return false;
  1211. }
  1212. std::pair<DxilFunctionLinkInfo *, DxilLib *> &linkPair =
  1213. m_functionNameMap[name];
  1214. linkJob.AddFunction(linkPair);
  1215. DxilLib *pLib = linkPair.second;
  1216. libSet.insert(pLib);
  1217. if (!bLazyLoadDone) {
  1218. Function *F = linkPair.first->func;
  1219. pLib->LazyLoadFunction(F);
  1220. }
  1221. for (Function *F : linkPair.first->usedFunctions) {
  1222. if (hlsl::OP::IsDxilOpFunc(F) || F->isIntrinsic()) {
  1223. // Add dxil operations directly.
  1224. linkJob.AddFunction(F);
  1225. } else if (addedFunctionSet.count(F->getName()) == 0) {
  1226. if (bAllowFuncionDecls && F->isDeclaration() && !m_functionNameMap.count(F->getName())) {
  1227. // When linking to lib, use of undefined function is allowed; add directly.
  1228. linkJob.AddFunction(F);
  1229. } else {
  1230. // Push function name to work list.
  1231. workList.emplace_back(F->getName());
  1232. }
  1233. }
  1234. }
  1235. addedFunctionSet.insert(name);
  1236. }
  1237. return true;
  1238. }
  1239. std::unique_ptr<llvm::Module>
  1240. DxilLinkerImpl::Link(StringRef entry, StringRef profile, dxilutil::ExportMap &exportMap) {
  1241. const ShaderModel *pSM = ShaderModel::GetByName(profile.data());
  1242. DXIL::ShaderKind kind = pSM->GetKind();
  1243. if (kind == DXIL::ShaderKind::Invalid ||
  1244. (kind >= DXIL::ShaderKind::RayGeneration &&
  1245. kind <= DXIL::ShaderKind::Callable)) {
  1246. m_ctx.emitError(profile + Twine(kInvalidProfile));
  1247. // Invalid profile.
  1248. return nullptr;
  1249. }
  1250. if (!exportMap.empty() && kind != DXIL::ShaderKind::Library) {
  1251. m_ctx.emitError(Twine(kExportOnlyForLib));
  1252. return nullptr;
  1253. }
  1254. // Verifying validator version supports the requested profile
  1255. unsigned minValMajor, minValMinor;
  1256. pSM->GetMinValidatorVersion(minValMajor, minValMinor);
  1257. if (minValMajor > m_valMajor ||
  1258. (minValMajor == m_valMajor && minValMinor > m_valMinor)) {
  1259. m_ctx.emitError(Twine(kInvalidValidatorVersion) + profile);
  1260. return nullptr;
  1261. }
  1262. DxilLinkJob linkJob(m_ctx, exportMap, m_valMajor, m_valMinor);
  1263. SetVector<DxilLib *> libSet;
  1264. SetVector<StringRef> addedFunctionSet;
  1265. bool bIsLib = pSM->IsLib();
  1266. if (!bIsLib) {
  1267. SmallVector<StringRef, 4> workList;
  1268. workList.emplace_back(entry);
  1269. if (!AddFunctions(workList, libSet, addedFunctionSet, linkJob,
  1270. /*bLazyLoadDone*/ false,
  1271. /*bAllowFuncionDecls*/ false))
  1272. return nullptr;
  1273. } else {
  1274. if (exportMap.empty() && !exportMap.isExportShadersOnly()) {
  1275. // Add every function for lib profile.
  1276. for (auto &it : m_functionNameMap) {
  1277. StringRef name = it.getKey();
  1278. std::pair<DxilFunctionLinkInfo *, DxilLib *> &linkPair = it.second;
  1279. DxilFunctionLinkInfo *linkInfo = linkPair.first;
  1280. DxilLib *pLib = linkPair.second;
  1281. Function *F = linkInfo->func;
  1282. pLib->LazyLoadFunction(F);
  1283. linkJob.AddFunction(linkPair);
  1284. libSet.insert(pLib);
  1285. addedFunctionSet.insert(name);
  1286. }
  1287. // Add every dxil function and llvm intrinsic.
  1288. for (auto *pLib : libSet) {
  1289. auto &DM = pLib->GetDxilModule();
  1290. DM.GetOP();
  1291. auto *pM = DM.GetModule();
  1292. for (Function &F : pM->functions()) {
  1293. if (hlsl::OP::IsDxilOpFunc(&F) || F.isIntrinsic() ||
  1294. (F.isDeclaration() && m_functionNameMap.count(F.getName()) == 0)) {
  1295. // Add intrinsics and function decls still not defined in any lib
  1296. linkJob.AddFunction(&F);
  1297. }
  1298. }
  1299. }
  1300. } else if (exportMap.isExportShadersOnly()) {
  1301. SmallVector<StringRef, 4> workList;
  1302. for (auto *pLib : m_attachedLibs) {
  1303. auto &DM = pLib->GetDxilModule();
  1304. auto *pM = DM.GetModule();
  1305. for (Function &F : pM->functions()) {
  1306. if (!pLib->IsEntry(&F)) {
  1307. if (!F.isDeclaration()) {
  1308. // Set none entry to be internal so they could be removed.
  1309. F.setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  1310. }
  1311. continue;
  1312. }
  1313. workList.emplace_back(F.getName());
  1314. }
  1315. libSet.insert(pLib);
  1316. }
  1317. if (!AddFunctions(workList, libSet, addedFunctionSet, linkJob,
  1318. /*bLazyLoadDone*/ false,
  1319. /*bAllowFuncionDecls*/ false))
  1320. return nullptr;
  1321. } else {
  1322. SmallVector<StringRef, 4> workList;
  1323. // Only add exported functions.
  1324. for (auto &it : m_functionNameMap) {
  1325. StringRef name = it.getKey();
  1326. // Only add names exist in exportMap.
  1327. if (exportMap.IsExported(name))
  1328. workList.emplace_back(name);
  1329. }
  1330. if (!AddFunctions(workList, libSet, addedFunctionSet, linkJob,
  1331. /*bLazyLoadDone*/ false,
  1332. /*bAllowFuncionDecls*/ true))
  1333. return nullptr;
  1334. }
  1335. }
  1336. // Save global users.
  1337. for (auto &pLib : libSet) {
  1338. pLib->BuildGlobalUsage();
  1339. }
  1340. SmallVector<StringRef, 4> workList;
  1341. // Save global ctor users.
  1342. for (auto &pLib : libSet) {
  1343. pLib->CollectUsedInitFunctions(addedFunctionSet, workList);
  1344. }
  1345. for (auto &pLib : libSet) {
  1346. pLib->FixIntrinsicOverloads();
  1347. }
  1348. // Add init functions if used.
  1349. // All init function already loaded in BuildGlobalUsage,
  1350. // so set bLazyLoadDone to true here.
  1351. // Decls should have been added to addedFunctionSet if lib,
  1352. // so set bAllowFuncionDecls is false here.
  1353. if (!AddFunctions(workList, libSet, addedFunctionSet, linkJob,
  1354. /*bLazyLoadDone*/ true,
  1355. /*bAllowFuncionDecls*/ false))
  1356. return nullptr;
  1357. if (!bIsLib) {
  1358. std::pair<DxilFunctionLinkInfo *, DxilLib *> &entryLinkPair =
  1359. m_functionNameMap[entry];
  1360. return linkJob.Link(entryLinkPair, pSM);
  1361. } else {
  1362. return linkJob.LinkToLib(pSM);
  1363. }
  1364. }
  1365. namespace hlsl {
  1366. DxilLinker *DxilLinker::CreateLinker(LLVMContext &Ctx, unsigned valMajor, unsigned valMinor) {
  1367. return new DxilLinkerImpl(Ctx, valMajor, valMinor);
  1368. }
  1369. } // namespace hlsl