2
0

DxilLinker.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  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. LiveSubprograms.push_back(DISP);
  916. if (Func->getParent() != &M)
  917. DISP->replaceFunction(nullptr);
  918. } else {
  919. // Copy it in anyway even if there's no function. When function is inlined
  920. // the function reference is gone, but the subprogram is still valid as
  921. // scope.
  922. LiveSubprograms.push_back(DISP);
  923. }
  924. }
  925. // Create our live global variable list.
  926. bool GlobalVariableChange = false;
  927. for (DIGlobalVariable *DIG : DIC->getGlobalVariables()) {
  928. // Make sure we only visit each global variable only once.
  929. if (!VisitedSet.insert(DIG).second)
  930. continue;
  931. // If the global variable referenced by DIG is not null, the global
  932. // variable is live.
  933. if (Constant *CV = DIG->getVariable()) {
  934. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CV)) {
  935. if (GV->getParent() == &M) {
  936. LiveGlobalVariables.push_back(DIG);
  937. } else {
  938. GlobalVariableChange = true;
  939. }
  940. } else {
  941. LiveGlobalVariables.push_back(DIG);
  942. }
  943. } else {
  944. GlobalVariableChange = true;
  945. }
  946. }
  947. // If we found dead subprograms or global variables, replace the current
  948. // subprogram list/global variable list with our new live subprogram/global
  949. // variable list.
  950. if (SubprogramChange) {
  951. DIC->replaceSubprograms(MDTuple::get(C, LiveSubprograms));
  952. }
  953. if (GlobalVariableChange) {
  954. DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
  955. }
  956. // Reset lists for the next iteration.
  957. LiveSubprograms.clear();
  958. LiveGlobalVariables.clear();
  959. }
  960. }
  961. // TODO: move FixShaderModelMismatch to separate file.
  962. #include "dxc/DXIL/DxilInstructions.h"
  963. namespace {
  964. bool onlyUsedByAnnotateHandle(Value *V) {
  965. bool bResult = true;
  966. for (User *U : V->users()) {
  967. CallInst *CI = dyn_cast<CallInst>(U);
  968. if (!CI) {
  969. bResult = false;
  970. break;
  971. }
  972. DxilInst_AnnotateHandle Hdl(CI);
  973. if (!Hdl) {
  974. bResult = false;
  975. break;
  976. }
  977. }
  978. return bResult;
  979. }
  980. DxilResourceBase *
  981. findResourceFromPtr(Value *Ptr, DxilModule &DM,
  982. DenseMap<Value *, DxilResourceBase *> &PtrResMap) {
  983. auto it = PtrResMap.find(Ptr);
  984. if (Ptr)
  985. return it->second;
  986. DxilResourceBase *Res = nullptr;
  987. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
  988. DXASSERT(false, "global resource should already in map");
  989. } else {
  990. // Not support allocaInst of resource when missing annotateHandle.
  991. GEPOperator *GEP = cast<GEPOperator>(Ptr);
  992. Res = findResourceFromPtr(GEP->getPointerOperand(), DM, PtrResMap);
  993. }
  994. PtrResMap[Ptr] = Res;
  995. return Res;
  996. }
  997. template <typename T>
  998. void addGVFromResTable(T &Tab,
  999. DenseMap<Value *, DxilResourceBase *> &PtrResMap) {
  1000. for (auto &it : Tab) {
  1001. PtrResMap[it->GetGlobalSymbol()] = it.get();
  1002. }
  1003. }
  1004. // Make sure createHandleForLib is annotated before use.
  1005. bool addAnnotHandle(Module &M, DxilModule &DM) {
  1006. hlsl::OP *hlslOP = DM.GetOP();
  1007. auto *pSM = DM.GetShaderModel();
  1008. if (!pSM->IsSM66Plus())
  1009. return false;
  1010. // If no createHandleForLib, do nothing.
  1011. if (!hlslOP->IsDxilOpUsed(DXIL::OpCode::CreateHandleForLib))
  1012. return false;
  1013. Type *pVoidTy = Type::getVoidTy(M.getContext());
  1014. SmallVector<CallInst *, 4> Candidates;
  1015. for (Function &F : M) {
  1016. if (!F.isDeclaration())
  1017. continue;
  1018. if (!hlslOP->IsDxilOpFunc(&F))
  1019. continue;
  1020. DXIL::OpCodeClass opClass;
  1021. if (!hlslOP->GetOpCodeClass(&F, opClass))
  1022. continue;
  1023. if (opClass != DXIL::OpCodeClass::CreateHandleForLib)
  1024. continue;
  1025. for (User *U : F.users()) {
  1026. CallInst *CI = cast<CallInst>(U);
  1027. // Check user is annotateHandle.
  1028. if (onlyUsedByAnnotateHandle(CI))
  1029. continue;
  1030. Candidates.emplace_back(CI);
  1031. }
  1032. }
  1033. if (Candidates.empty())
  1034. return false;
  1035. DenseMap<Value *, DxilResourceBase *> PtrResMap;
  1036. // Add GV from resTable first.
  1037. addGVFromResTable(DM.GetCBuffers(), PtrResMap);
  1038. addGVFromResTable(DM.GetSRVs(), PtrResMap);
  1039. addGVFromResTable(DM.GetUAVs(), PtrResMap);
  1040. addGVFromResTable(DM.GetSamplers(), PtrResMap);
  1041. Function *annotHandleFn =
  1042. hlslOP->GetOpFunc(DXIL::OpCode::AnnotateHandle, pVoidTy);
  1043. Value *annotHandleArg =
  1044. hlslOP->GetI32Const((unsigned)DXIL::OpCode::AnnotateHandle);
  1045. // Replace createHandle with annotateHandle and createHandleFromBinding.
  1046. Type *resPropertyTy = hlslOP->GetResourcePropertiesType();
  1047. for (CallInst *CI : Candidates) {
  1048. DxilInst_CreateHandleForLib Hdl(CI);
  1049. LoadInst *Ld = cast<LoadInst>(Hdl.get_Resource());
  1050. Value *Ptr = Ld->getPointerOperand();
  1051. DxilResourceBase *Res = findResourceFromPtr(Ptr, DM, PtrResMap);
  1052. DXASSERT(Res, "fail to find resource when missing annotateHandle");
  1053. DxilResourceProperties RP = resource_helper::loadPropsFromResourceBase(Res);
  1054. Value *propertiesV =
  1055. resource_helper::getAsConstant(RP, resPropertyTy, *DM.GetShaderModel());
  1056. IRBuilder<> B(CI->getNextNode());
  1057. CallInst *annotHdl =
  1058. B.CreateCall(annotHandleFn, {annotHandleArg, CI, propertiesV});
  1059. CI->replaceAllUsesWith(annotHdl);
  1060. annotHdl->setArgOperand(DxilInst_AnnotateHandle::arg_res, CI);
  1061. }
  1062. return true;
  1063. }
  1064. } // namespace
  1065. void DxilLinkJob::FixShaderModelMismatch(llvm::Module &M) {
  1066. // TODO: fix more issues.
  1067. addAnnotHandle(M, M.GetDxilModule());
  1068. }
  1069. void DxilLinkJob::RunPreparePass(Module &M) {
  1070. StripDeadDebugInfo(M);
  1071. FixShaderModelMismatch(M);
  1072. DxilModule &DM = M.GetDxilModule();
  1073. const ShaderModel *pSM = DM.GetShaderModel();
  1074. legacy::PassManager PM;
  1075. PM.add(createAlwaysInlinerPass(/*InsertLifeTime*/ false));
  1076. // Remove unused functions.
  1077. PM.add(createDxilDeadFunctionEliminationPass());
  1078. // SROA
  1079. PM.add(createSROAPass(/*RequiresDomTree*/false, /*SkipHLSLMat*/false));
  1080. // For static global handle.
  1081. PM.add(createLowerStaticGlobalIntoAlloca());
  1082. // Remove MultiDimArray from function call arg.
  1083. PM.add(createMultiDimArrayToOneDimArrayPass());
  1084. // Lower matrix bitcast.
  1085. PM.add(createMatrixBitcastLowerPass());
  1086. // mem2reg.
  1087. PM.add(createPromoteMemoryToRegisterPass());
  1088. // Clean up vectors, and run mem2reg again
  1089. PM.add(createScalarizerPass());
  1090. PM.add(createPromoteMemoryToRegisterPass());
  1091. PM.add(createSimplifyInstPass());
  1092. PM.add(createCFGSimplificationPass());
  1093. PM.add(createDeadCodeEliminationPass());
  1094. PM.add(createGlobalDCEPass());
  1095. if (pSM->IsSM66Plus() && pSM->IsLib())
  1096. PM.add(createDxilMutateResourceToHandlePass());
  1097. PM.add(createDxilLowerCreateHandleForLibPass());
  1098. PM.add(createDxilTranslateRawBuffer());
  1099. PM.add(createDxilFinalizeModulePass());
  1100. PM.add(createComputeViewIdStatePass());
  1101. PM.add(createDxilDeadFunctionEliminationPass());
  1102. PM.add(createNoPausePassesPass());
  1103. PM.add(createDxilEmitMetadataPass());
  1104. PM.run(M);
  1105. }
  1106. //------------------------------------------------------------------------------
  1107. //
  1108. // DxilLinkerImpl methods.
  1109. //
  1110. bool DxilLinkerImpl::HasLibNameRegistered(StringRef name) {
  1111. return m_LibMap.count(name);
  1112. }
  1113. bool DxilLinkerImpl::RegisterLib(StringRef name,
  1114. std::unique_ptr<llvm::Module> pModule,
  1115. std::unique_ptr<llvm::Module> pDebugModule) {
  1116. if (m_LibMap.count(name))
  1117. return false;
  1118. std::unique_ptr<llvm::Module> pM =
  1119. pDebugModule ? std::move(pDebugModule) : std::move(pModule);
  1120. if (!pM)
  1121. return false;
  1122. pM->setModuleIdentifier(name);
  1123. std::unique_ptr<DxilLib> pLib =
  1124. llvm::make_unique<DxilLib>(std::move(pM));
  1125. m_LibMap[name] = std::move(pLib);
  1126. return true;
  1127. }
  1128. bool DxilLinkerImpl::AttachLib(StringRef name) {
  1129. auto iter = m_LibMap.find(name);
  1130. if (iter == m_LibMap.end()) {
  1131. return false;
  1132. }
  1133. return AttachLib(iter->second.get());
  1134. }
  1135. bool DxilLinkerImpl::DetachLib(StringRef name) {
  1136. auto iter = m_LibMap.find(name);
  1137. if (iter == m_LibMap.end()) {
  1138. return false;
  1139. }
  1140. return DetachLib(iter->second.get());
  1141. }
  1142. void DxilLinkerImpl::DetachAll() {
  1143. m_functionNameMap.clear();
  1144. m_attachedLibs.clear();
  1145. }
  1146. bool DxilLinkerImpl::AttachLib(DxilLib *lib) {
  1147. if (!lib) {
  1148. // Invalid arg.
  1149. return false;
  1150. }
  1151. if (m_attachedLibs.count(lib))
  1152. return false;
  1153. StringMap<std::unique_ptr<DxilFunctionLinkInfo>> &funcTable =
  1154. lib->GetFunctionTable();
  1155. bool bSuccess = true;
  1156. for (auto it = funcTable.begin(), e = funcTable.end(); it != e; it++) {
  1157. StringRef name = it->getKey();
  1158. if (m_functionNameMap.count(name)) {
  1159. // Redefine of function.
  1160. const DxilFunctionLinkInfo *DFLI = it->getValue().get();
  1161. dxilutil::EmitErrorOnFunction(m_ctx, DFLI->func, Twine(kRedefineFunction) + name);
  1162. bSuccess = false;
  1163. continue;
  1164. }
  1165. m_functionNameMap[name] = std::make_pair(it->second.get(), lib);
  1166. }
  1167. if (bSuccess) {
  1168. m_attachedLibs.insert(lib);
  1169. } else {
  1170. for (auto it = funcTable.begin(), e = funcTable.end(); it != e; it++) {
  1171. StringRef name = it->getKey();
  1172. auto iter = m_functionNameMap.find(name);
  1173. if (iter == m_functionNameMap.end())
  1174. continue;
  1175. // Remove functions of lib.
  1176. if (m_functionNameMap[name].second == lib)
  1177. m_functionNameMap.erase(name);
  1178. }
  1179. }
  1180. return bSuccess;
  1181. }
  1182. bool DxilLinkerImpl::DetachLib(DxilLib *lib) {
  1183. if (!lib) {
  1184. // Invalid arg.
  1185. return false;
  1186. }
  1187. if (!m_attachedLibs.count(lib))
  1188. return false;
  1189. m_attachedLibs.erase(lib);
  1190. // Remove functions from lib.
  1191. StringMap<std::unique_ptr<DxilFunctionLinkInfo>> &funcTable =
  1192. lib->GetFunctionTable();
  1193. for (auto it = funcTable.begin(), e = funcTable.end(); it != e; it++) {
  1194. StringRef name = it->getKey();
  1195. m_functionNameMap.erase(name);
  1196. }
  1197. return true;
  1198. }
  1199. bool DxilLinkerImpl::AddFunctions(SmallVector<StringRef, 4> &workList,
  1200. SetVector<DxilLib *> &libSet,
  1201. SetVector<StringRef> &addedFunctionSet,
  1202. DxilLinkJob &linkJob, bool bLazyLoadDone,
  1203. bool bAllowFuncionDecls) {
  1204. while (!workList.empty()) {
  1205. StringRef name = workList.pop_back_val();
  1206. // Ignore added function.
  1207. if (addedFunctionSet.count(name))
  1208. continue;
  1209. if (!m_functionNameMap.count(name)) {
  1210. // Cannot find function, report error.
  1211. m_ctx.emitError(Twine(kUndefFunction) + name);
  1212. return false;
  1213. }
  1214. std::pair<DxilFunctionLinkInfo *, DxilLib *> &linkPair =
  1215. m_functionNameMap[name];
  1216. linkJob.AddFunction(linkPair);
  1217. DxilLib *pLib = linkPair.second;
  1218. libSet.insert(pLib);
  1219. if (!bLazyLoadDone) {
  1220. Function *F = linkPair.first->func;
  1221. pLib->LazyLoadFunction(F);
  1222. }
  1223. for (Function *F : linkPair.first->usedFunctions) {
  1224. if (hlsl::OP::IsDxilOpFunc(F) || F->isIntrinsic()) {
  1225. // Add dxil operations directly.
  1226. linkJob.AddFunction(F);
  1227. } else if (addedFunctionSet.count(F->getName()) == 0) {
  1228. if (bAllowFuncionDecls && F->isDeclaration() && !m_functionNameMap.count(F->getName())) {
  1229. // When linking to lib, use of undefined function is allowed; add directly.
  1230. linkJob.AddFunction(F);
  1231. } else {
  1232. // Push function name to work list.
  1233. workList.emplace_back(F->getName());
  1234. }
  1235. }
  1236. }
  1237. addedFunctionSet.insert(name);
  1238. }
  1239. return true;
  1240. }
  1241. std::unique_ptr<llvm::Module>
  1242. DxilLinkerImpl::Link(StringRef entry, StringRef profile, dxilutil::ExportMap &exportMap) {
  1243. const ShaderModel *pSM = ShaderModel::GetByName(profile.data());
  1244. DXIL::ShaderKind kind = pSM->GetKind();
  1245. if (kind == DXIL::ShaderKind::Invalid ||
  1246. (kind >= DXIL::ShaderKind::RayGeneration &&
  1247. kind <= DXIL::ShaderKind::Callable)) {
  1248. m_ctx.emitError(profile + Twine(kInvalidProfile));
  1249. // Invalid profile.
  1250. return nullptr;
  1251. }
  1252. if (!exportMap.empty() && kind != DXIL::ShaderKind::Library) {
  1253. m_ctx.emitError(Twine(kExportOnlyForLib));
  1254. return nullptr;
  1255. }
  1256. // Verifying validator version supports the requested profile
  1257. unsigned minValMajor, minValMinor;
  1258. pSM->GetMinValidatorVersion(minValMajor, minValMinor);
  1259. if (minValMajor > m_valMajor ||
  1260. (minValMajor == m_valMajor && minValMinor > m_valMinor)) {
  1261. m_ctx.emitError(Twine(kInvalidValidatorVersion) + profile);
  1262. return nullptr;
  1263. }
  1264. DxilLinkJob linkJob(m_ctx, exportMap, m_valMajor, m_valMinor);
  1265. SetVector<DxilLib *> libSet;
  1266. SetVector<StringRef> addedFunctionSet;
  1267. bool bIsLib = pSM->IsLib();
  1268. if (!bIsLib) {
  1269. SmallVector<StringRef, 4> workList;
  1270. workList.emplace_back(entry);
  1271. if (!AddFunctions(workList, libSet, addedFunctionSet, linkJob,
  1272. /*bLazyLoadDone*/ false,
  1273. /*bAllowFuncionDecls*/ false))
  1274. return nullptr;
  1275. } else {
  1276. if (exportMap.empty() && !exportMap.isExportShadersOnly()) {
  1277. // Add every function for lib profile.
  1278. for (auto &it : m_functionNameMap) {
  1279. StringRef name = it.getKey();
  1280. std::pair<DxilFunctionLinkInfo *, DxilLib *> &linkPair = it.second;
  1281. DxilFunctionLinkInfo *linkInfo = linkPair.first;
  1282. DxilLib *pLib = linkPair.second;
  1283. Function *F = linkInfo->func;
  1284. pLib->LazyLoadFunction(F);
  1285. linkJob.AddFunction(linkPair);
  1286. libSet.insert(pLib);
  1287. addedFunctionSet.insert(name);
  1288. }
  1289. // Add every dxil function and llvm intrinsic.
  1290. for (auto *pLib : libSet) {
  1291. auto &DM = pLib->GetDxilModule();
  1292. DM.GetOP();
  1293. auto *pM = DM.GetModule();
  1294. for (Function &F : pM->functions()) {
  1295. if (hlsl::OP::IsDxilOpFunc(&F) || F.isIntrinsic() ||
  1296. (F.isDeclaration() && m_functionNameMap.count(F.getName()) == 0)) {
  1297. // Add intrinsics and function decls still not defined in any lib
  1298. linkJob.AddFunction(&F);
  1299. }
  1300. }
  1301. }
  1302. } else if (exportMap.isExportShadersOnly()) {
  1303. SmallVector<StringRef, 4> workList;
  1304. for (auto *pLib : m_attachedLibs) {
  1305. auto &DM = pLib->GetDxilModule();
  1306. auto *pM = DM.GetModule();
  1307. for (Function &F : pM->functions()) {
  1308. if (!pLib->IsEntry(&F)) {
  1309. if (!F.isDeclaration()) {
  1310. // Set none entry to be internal so they could be removed.
  1311. F.setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  1312. }
  1313. continue;
  1314. }
  1315. workList.emplace_back(F.getName());
  1316. }
  1317. libSet.insert(pLib);
  1318. }
  1319. if (!AddFunctions(workList, libSet, addedFunctionSet, linkJob,
  1320. /*bLazyLoadDone*/ false,
  1321. /*bAllowFuncionDecls*/ false))
  1322. return nullptr;
  1323. } else {
  1324. SmallVector<StringRef, 4> workList;
  1325. // Only add exported functions.
  1326. for (auto &it : m_functionNameMap) {
  1327. StringRef name = it.getKey();
  1328. // Only add names exist in exportMap.
  1329. if (exportMap.IsExported(name))
  1330. workList.emplace_back(name);
  1331. }
  1332. if (!AddFunctions(workList, libSet, addedFunctionSet, linkJob,
  1333. /*bLazyLoadDone*/ false,
  1334. /*bAllowFuncionDecls*/ true))
  1335. return nullptr;
  1336. }
  1337. }
  1338. // Save global users.
  1339. for (auto &pLib : libSet) {
  1340. pLib->BuildGlobalUsage();
  1341. }
  1342. SmallVector<StringRef, 4> workList;
  1343. // Save global ctor users.
  1344. for (auto &pLib : libSet) {
  1345. pLib->CollectUsedInitFunctions(addedFunctionSet, workList);
  1346. }
  1347. for (auto &pLib : libSet) {
  1348. pLib->FixIntrinsicOverloads();
  1349. }
  1350. // Add init functions if used.
  1351. // All init function already loaded in BuildGlobalUsage,
  1352. // so set bLazyLoadDone to true here.
  1353. // Decls should have been added to addedFunctionSet if lib,
  1354. // so set bAllowFuncionDecls is false here.
  1355. if (!AddFunctions(workList, libSet, addedFunctionSet, linkJob,
  1356. /*bLazyLoadDone*/ true,
  1357. /*bAllowFuncionDecls*/ false))
  1358. return nullptr;
  1359. if (!bIsLib) {
  1360. std::pair<DxilFunctionLinkInfo *, DxilLib *> &entryLinkPair =
  1361. m_functionNameMap[entry];
  1362. return linkJob.Link(entryLinkPair, pSM);
  1363. } else {
  1364. return linkJob.LinkToLib(pSM);
  1365. }
  1366. }
  1367. namespace hlsl {
  1368. DxilLinker *DxilLinker::CreateLinker(LLVMContext &Ctx, unsigned valMajor, unsigned valMinor) {
  1369. return new DxilLinkerImpl(Ctx, valMajor, valMinor);
  1370. }
  1371. } // namespace hlsl