DxilGenerationPass.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilGenerationPass.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. // DxilGenerationPass implementation. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/HLSL/DxilGenerationPass.h"
  12. #include "dxc/HLSL/DxilOperations.h"
  13. #include "dxc/HLSL/DxilModule.h"
  14. #include "dxc/HLSL/HLModule.h"
  15. #include "dxc/HLSL/HLOperations.h"
  16. #include "dxc/HLSL/HLMatrixLowerHelper.h"
  17. #include "dxc/HlslIntrinsicOp.h"
  18. #include "dxc/Support/Global.h"
  19. #include "dxc/HLSL/DxilTypeSystem.h"
  20. #include "dxc/HLSL/HLOperationLower.h"
  21. #include "HLSignatureLower.h"
  22. #include "dxc/HLSL/DxilUtil.h"
  23. #include "dxc/Support/exception.h"
  24. #include "llvm/IR/GetElementPtrTypeIterator.h"
  25. #include "llvm/IR/IRBuilder.h"
  26. #include "llvm/IR/Instructions.h"
  27. #include "llvm/IR/InstIterator.h"
  28. #include "llvm/IR/IntrinsicInst.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/IR/DebugInfo.h"
  31. #include "llvm/IR/PassManager.h"
  32. #include "llvm/ADT/BitVector.h"
  33. #include "llvm/Pass.h"
  34. #include "llvm/Transforms/Utils/SSAUpdater.h"
  35. #include "llvm/Analysis/AssumptionCache.h"
  36. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  37. #include <memory>
  38. #include <unordered_set>
  39. #include <iterator>
  40. using namespace llvm;
  41. using namespace hlsl;
  42. // TODO: use hlsl namespace for the most of this file.
  43. namespace {
  44. // Collect unused phi of resources and remove them.
  45. class ResourceRemover : public LoadAndStorePromoter {
  46. AllocaInst *AI;
  47. mutable std::unordered_set<PHINode *> unusedPhis;
  48. public:
  49. ResourceRemover(ArrayRef<Instruction *> Insts, SSAUpdater &S)
  50. : LoadAndStorePromoter(Insts, S), AI(nullptr) {}
  51. void run(AllocaInst *AI, const SmallVectorImpl<Instruction *> &Insts) {
  52. // Remember which alloca we're promoting (for isInstInList).
  53. this->AI = AI;
  54. LoadAndStorePromoter::run(Insts);
  55. for (PHINode *P : unusedPhis) {
  56. P->eraseFromParent();
  57. }
  58. }
  59. bool
  60. isInstInList(Instruction *I,
  61. const SmallVectorImpl<Instruction *> &Insts) const override {
  62. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  63. return LI->getOperand(0) == AI;
  64. return cast<StoreInst>(I)->getPointerOperand() == AI;
  65. }
  66. void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
  67. if (PHINode *PHI = dyn_cast<PHINode>(V)) {
  68. if (PHI->user_empty())
  69. unusedPhis.insert(PHI);
  70. }
  71. LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
  72. }
  73. };
  74. void SimplifyGlobalSymbol(GlobalVariable *GV) {
  75. Type *Ty = GV->getType()->getElementType();
  76. if (!Ty->isArrayTy()) {
  77. // Make sure only 1 load of GV in each function.
  78. std::unordered_map<Function *, Instruction *> handleMapOnFunction;
  79. for (User *U : GV->users()) {
  80. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  81. Function *F = LI->getParent()->getParent();
  82. auto it = handleMapOnFunction.find(F);
  83. if (it == handleMapOnFunction.end()) {
  84. handleMapOnFunction[F] = LI;
  85. } else {
  86. LI->replaceAllUsesWith(it->second);
  87. }
  88. }
  89. }
  90. for (auto it : handleMapOnFunction) {
  91. Function *F = it.first;
  92. Instruction *I = it.second;
  93. IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
  94. Value *headLI = Builder.CreateLoad(GV);
  95. I->replaceAllUsesWith(headLI);
  96. }
  97. }
  98. }
  99. void InitResourceBase(const DxilResourceBase *pSource,
  100. DxilResourceBase *pDest) {
  101. DXASSERT_NOMSG(pSource->GetClass() == pDest->GetClass());
  102. pDest->SetKind(pSource->GetKind());
  103. pDest->SetID(pSource->GetID());
  104. pDest->SetSpaceID(pSource->GetSpaceID());
  105. pDest->SetLowerBound(pSource->GetLowerBound());
  106. pDest->SetRangeSize(pSource->GetRangeSize());
  107. pDest->SetGlobalSymbol(pSource->GetGlobalSymbol());
  108. pDest->SetGlobalName(pSource->GetGlobalName());
  109. pDest->SetHandle(pSource->GetHandle());
  110. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(pSource->GetGlobalSymbol()))
  111. SimplifyGlobalSymbol(GV);
  112. }
  113. void InitResource(const DxilResource *pSource, DxilResource *pDest) {
  114. pDest->SetCompType(pSource->GetCompType());
  115. pDest->SetSampleCount(pSource->GetSampleCount());
  116. pDest->SetElementStride(pSource->GetElementStride());
  117. pDest->SetGloballyCoherent(pSource->IsGloballyCoherent());
  118. pDest->SetHasCounter(pSource->HasCounter());
  119. pDest->SetRW(pSource->IsRW());
  120. pDest->SetROV(pSource->IsROV());
  121. InitResourceBase(pSource, pDest);
  122. }
  123. void InitDxilModuleFromHLModule(HLModule &H, DxilModule &M, DxilEntrySignature *pSig, bool HasDebugInfo) {
  124. std::unique_ptr<DxilEntrySignature> pSigPtr(pSig);
  125. // Subsystems.
  126. unsigned ValMajor, ValMinor;
  127. H.GetValidatorVersion(ValMajor, ValMinor);
  128. M.SetValidatorVersion(ValMajor, ValMinor);
  129. M.SetShaderModel(H.GetShaderModel());
  130. // Entry function.
  131. Function *EntryFn = H.GetEntryFunction();
  132. DxilFunctionProps *FnProps = H.HasDxilFunctionProps(EntryFn) ? &H.GetDxilFunctionProps(EntryFn) : nullptr;
  133. M.SetEntryFunction(EntryFn);
  134. M.SetEntryFunctionName(H.GetEntryFunctionName());
  135. std::vector<GlobalVariable* > &LLVMUsed = M.GetLLVMUsed();
  136. // Resources
  137. for (auto && C : H.GetCBuffers()) {
  138. auto b = make_unique<DxilCBuffer>();
  139. InitResourceBase(C.get(), b.get());
  140. b->SetSize(C->GetSize());
  141. LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
  142. M.AddCBuffer(std::move(b));
  143. }
  144. for (auto && C : H.GetUAVs()) {
  145. auto b = make_unique<DxilResource>();
  146. InitResource(C.get(), b.get());
  147. LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
  148. M.AddUAV(std::move(b));
  149. }
  150. for (auto && C : H.GetSRVs()) {
  151. auto b = make_unique<DxilResource>();
  152. InitResource(C.get(), b.get());
  153. LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
  154. M.AddSRV(std::move(b));
  155. }
  156. for (auto && C : H.GetSamplers()) {
  157. auto b = make_unique<DxilSampler>();
  158. InitResourceBase(C.get(), b.get());
  159. b->SetSamplerKind(C->GetSamplerKind());
  160. LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
  161. M.AddSampler(std::move(b));
  162. }
  163. // Signatures.
  164. M.ResetEntrySignature(pSigPtr.release());
  165. M.ResetRootSignature(H.ReleaseRootSignature());
  166. // Shader properties.
  167. //bool m_bDisableOptimizations;
  168. M.SetDisableOptimization(H.GetHLOptions().bDisableOptimizations);
  169. //bool m_bDisableMathRefactoring;
  170. //bool m_bEnableDoublePrecision;
  171. //bool m_bEnableDoubleExtensions;
  172. //M.CollectShaderFlags();
  173. //bool m_bForceEarlyDepthStencil;
  174. //bool m_bEnableRawAndStructuredBuffers;
  175. //bool m_bEnableMSAD;
  176. //M.m_ShaderFlags.SetAllResourcesBound(H.GetHLOptions().bAllResourcesBound);
  177. M.SetUseMinPrecision(H.GetHLOptions().bUseMinPrecision);
  178. if (FnProps)
  179. M.SetShaderProperties(FnProps);
  180. // Move function props.
  181. if (M.GetShaderModel()->IsLib())
  182. M.ResetFunctionPropsMap(H.ReleaseFunctionPropsMap());
  183. // DXIL type system.
  184. M.ResetTypeSystem(H.ReleaseTypeSystem());
  185. // Dxil OP.
  186. M.ResetOP(H.ReleaseOP());
  187. // Keep llvm used.
  188. M.EmitLLVMUsed();
  189. M.SetAllResourcesBound(H.GetHLOptions().bAllResourcesBound);
  190. // Update Validator Version
  191. M.UpgradeToMinValidatorVersion();
  192. }
  193. class DxilGenerationPass : public ModulePass {
  194. HLModule *m_pHLModule;
  195. bool m_HasDbgInfo;
  196. HLSLExtensionsCodegenHelper *m_extensionsCodegenHelper;
  197. public:
  198. static char ID; // Pass identification, replacement for typeid
  199. explicit DxilGenerationPass(bool NoOpt = false)
  200. : ModulePass(ID), m_pHLModule(nullptr), NotOptimized(NoOpt), m_extensionsCodegenHelper(nullptr) {}
  201. const char *getPassName() const override { return "DXIL Generator"; }
  202. void SetExtensionsHelper(HLSLExtensionsCodegenHelper *helper) {
  203. m_extensionsCodegenHelper = helper;
  204. }
  205. bool runOnModule(Module &M) override {
  206. m_pHLModule = &M.GetOrCreateHLModule();
  207. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  208. // Load up debug information, to cross-reference values and the instructions
  209. // used to load them.
  210. m_HasDbgInfo = getDebugMetadataVersionFromModule(M) != 0;
  211. std::unique_ptr<DxilEntrySignature> pSig =
  212. llvm::make_unique<DxilEntrySignature>(SM->GetKind(), M.GetHLModule().GetHLOptions().bUseMinPrecision);
  213. // EntrySig for shader functions.
  214. DxilEntrySignatureMap DxilEntrySignatureMap;
  215. if (!SM->IsLib()) {
  216. HLSignatureLower sigLower(m_pHLModule->GetEntryFunction(), *m_pHLModule,
  217. *pSig);
  218. sigLower.Run();
  219. } else {
  220. for (auto It = M.begin(); It != M.end();) {
  221. Function &F = *(It++);
  222. // Lower signature for each graphics or compute entry function.
  223. if (m_pHLModule->IsGraphicsShader(&F) || m_pHLModule->IsComputeShader(&F)) {
  224. DxilFunctionProps &props = m_pHLModule->GetDxilFunctionProps(&F);
  225. std::unique_ptr<DxilEntrySignature> pSig =
  226. llvm::make_unique<DxilEntrySignature>(props.shaderKind, m_pHLModule->GetHLOptions().bUseMinPrecision);
  227. HLSignatureLower sigLower(&F, *m_pHLModule, *pSig);
  228. // TODO: BUG: This will lower patch constant function sigs twice if used by two hull shaders!
  229. sigLower.Run();
  230. DxilEntrySignatureMap[&F] = std::move(pSig);
  231. }
  232. }
  233. }
  234. std::unordered_set<LoadInst *> UpdateCounterSet;
  235. std::unordered_set<Value *> NonUniformSet;
  236. GenerateDxilOperations(M, UpdateCounterSet, NonUniformSet);
  237. GenerateDxilCBufferHandles(NonUniformSet);
  238. MarkUpdateCounter(UpdateCounterSet);
  239. LowerHLCreateHandle();
  240. MarkNonUniform(NonUniformSet);
  241. // For module which not promote mem2reg.
  242. // Remove local resource alloca/load/store/phi.
  243. // Skip lib in case alloca used as call arg.
  244. if (!SM->IsLib()) {
  245. for (auto It = M.begin(); It != M.end();) {
  246. Function &F = *(It++);
  247. if (!F.isDeclaration()) {
  248. RemoveLocalDxilResourceAllocas(&F);
  249. if (hlsl::GetHLOpcodeGroupByName(&F) ==
  250. HLOpcodeGroup::HLCreateHandle) {
  251. if (F.user_empty()) {
  252. F.eraseFromParent();
  253. } else {
  254. M.getContext().emitError("Fail to lower createHandle.");
  255. }
  256. }
  257. }
  258. }
  259. }
  260. // Translate precise on allocas into function call to keep the information after mem2reg.
  261. // The function calls will be removed after propagate precise attribute.
  262. TranslatePreciseAttribute();
  263. // High-level metadata should now be turned into low-level metadata.
  264. const bool SkipInit = true;
  265. hlsl::DxilModule &DxilMod = M.GetOrCreateDxilModule(SkipInit);
  266. InitDxilModuleFromHLModule(*m_pHLModule, DxilMod, pSig.release(),
  267. m_HasDbgInfo);
  268. if (SM->IsLib())
  269. DxilMod.ResetEntrySignatureMap(std::move(DxilEntrySignatureMap));
  270. HLModule::ClearHLMetadata(M);
  271. M.ResetHLModule();
  272. // We now have a DXIL representation - record this.
  273. SetPauseResumePasses(M, "hlsl-dxilemit", "hlsl-dxilload");
  274. return true;
  275. }
  276. private:
  277. void RemoveLocalDxilResourceAllocas(Function *F);
  278. void MarkUpdateCounter(std::unordered_set<LoadInst *> &UpdateCounterSet);
  279. void TranslateParamDxilResourceHandles(Function *F, std::unordered_map<Instruction *, Value *> &handleMap);
  280. void GenerateParamDxilResourceHandles(
  281. std::unordered_map<Instruction *, Value *> &handleMap);
  282. // Generate DXIL cbuffer handles.
  283. void
  284. GenerateDxilCBufferHandles(std::unordered_set<Value *> &NonUniformSet);
  285. // change built-in funtion into DXIL operations
  286. void GenerateDxilOperations(Module &M,
  287. std::unordered_set<LoadInst *> &UpdateCounterSet,
  288. std::unordered_set<Value *> &NonUniformSet);
  289. void LowerHLCreateHandle();
  290. void MarkNonUniform(std::unordered_set<Value *> &NonUniformSet);
  291. // Translate precise attribute into HL function call.
  292. void TranslatePreciseAttribute();
  293. // Input module is not optimized.
  294. bool NotOptimized;
  295. };
  296. }
  297. namespace {
  298. void CreateOperandSelect(Instruction *SelInst, Value *EmptyVal,
  299. std::unordered_map<Instruction *, Instruction *>
  300. &selInstToSelOperandInstMap) {
  301. IRBuilder<> Builder(SelInst);
  302. if (SelectInst *Sel = dyn_cast<SelectInst>(SelInst)) {
  303. Instruction *newSel = cast<Instruction>(
  304. Builder.CreateSelect(Sel->getCondition(), EmptyVal, EmptyVal));
  305. selInstToSelOperandInstMap[SelInst] = newSel;
  306. } else {
  307. PHINode *Phi = cast<PHINode>(SelInst);
  308. unsigned numIncoming = Phi->getNumIncomingValues();
  309. // Don't replace constant int operand.
  310. PHINode *newSel = Builder.CreatePHI(EmptyVal->getType(), numIncoming);
  311. for (unsigned j = 0; j < numIncoming; j++) {
  312. BasicBlock *BB = Phi->getIncomingBlock(j);
  313. newSel->addIncoming(EmptyVal, BB);
  314. }
  315. selInstToSelOperandInstMap[SelInst] = newSel;
  316. }
  317. }
  318. void UpdateOperandSelect(Instruction *SelInst, Instruction *Prototype,
  319. unsigned operandIdx,
  320. std::unordered_map<Instruction *, Instruction *>
  321. &selInstToSelOperandInstMap) {
  322. unsigned numOperands = SelInst->getNumOperands();
  323. unsigned startOpIdx = 0;
  324. // Skip Cond for Select.
  325. if (SelectInst *Sel = dyn_cast<SelectInst>(SelInst)) {
  326. startOpIdx = 1;
  327. }
  328. Instruction *newSel = selInstToSelOperandInstMap[SelInst];
  329. // Transform
  330. // phi0 = phi a0, b0, c0
  331. // phi1 = phi a1, b1, c1
  332. // NewInst = Add(phi0, phi1);
  333. // into
  334. // A = Add(a0, a1);
  335. // B = Add(b0, b1);
  336. // C = Add(c0, c1);
  337. // NewSelInst = phi A, B, C
  338. // Only support 1 operand now, other oerands should be Constant.
  339. // Each operand of newInst is a clone of prototype inst.
  340. // Now we set A operands based on operand 0 of phi0 and phi1.
  341. for (unsigned i = startOpIdx; i < numOperands; i++) {
  342. Instruction *selOp = cast<Instruction>(SelInst->getOperand(i));
  343. auto it = selInstToSelOperandInstMap.find(selOp);
  344. if (it != selInstToSelOperandInstMap.end()) {
  345. // Operand is an select.
  346. // Map to new created select inst.
  347. Instruction *newSelOp = it->second;
  348. newSel->setOperand(i, newSelOp);
  349. } else {
  350. // The operand is not select.
  351. // just use it for prototype operand.
  352. // Make sure function is the same.
  353. Instruction *op = Prototype->clone();
  354. op->setOperand(operandIdx, selOp);
  355. if (PHINode *phi = dyn_cast<PHINode>(SelInst)) {
  356. BasicBlock *BB = phi->getIncomingBlock(i);
  357. IRBuilder<> TmpBuilder(BB->getTerminator());
  358. TmpBuilder.Insert(op);
  359. } else {
  360. IRBuilder<> TmpBuilder(newSel);
  361. TmpBuilder.Insert(op);
  362. }
  363. newSel->setOperand(i, op);
  364. }
  365. }
  366. }
  367. void TranslateHLCreateHandle(Function *F, hlsl::OP &hlslOP) {
  368. Value *opArg = hlslOP.GetU32Const(
  369. (unsigned)DXIL::OpCode::CreateHandleFromResourceStructForLib);
  370. // Remove PhiNode createHandle first.
  371. std::vector<Instruction *> resSelects;
  372. std::unordered_set<llvm::Instruction *> selectSet;
  373. for (auto U = F->user_begin(); U != F->user_end();) {
  374. Value *user = *(U++);
  375. if (!isa<Instruction>(user))
  376. continue;
  377. // must be call inst
  378. CallInst *CI = cast<CallInst>(user);
  379. Value *res = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  380. if (isa<SelectInst>(res) || isa<PHINode>(res))
  381. dxilutil::CollectSelect(cast<Instruction>(res), selectSet);
  382. }
  383. if (!selectSet.empty()) {
  384. FunctionType *FT = F->getFunctionType();
  385. Type *ResTy = FT->getParamType(HLOperandIndex::kUnaryOpSrc0Idx);
  386. Value *UndefHandle = UndefValue::get(F->getReturnType());
  387. std::unordered_map<Instruction *, Instruction *> handleMap;
  388. for (Instruction *SelInst : selectSet) {
  389. CreateOperandSelect(SelInst, UndefHandle, handleMap);
  390. }
  391. Value *UndefRes = UndefValue::get(ResTy);
  392. std::unique_ptr<CallInst> PrototypeCall(
  393. CallInst::Create(F, {opArg, UndefRes}));
  394. for (Instruction *SelInst : selectSet) {
  395. UpdateOperandSelect(SelInst, PrototypeCall.get(),
  396. HLOperandIndex::kUnaryOpSrc0Idx, handleMap);
  397. }
  398. // Replace createHandle on select with select on createHandle.
  399. for (Instruction *SelInst : selectSet) {
  400. Value *NewSel = handleMap[SelInst];
  401. for (auto U = SelInst->user_begin(); U != SelInst->user_end();) {
  402. Value *user = *(U++);
  403. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  404. if (CI->getCalledFunction() == F) {
  405. CI->replaceAllUsesWith(NewSel);
  406. CI->eraseFromParent();
  407. }
  408. }
  409. }
  410. }
  411. }
  412. for (auto U = F->user_begin(); U != F->user_end();) {
  413. Value *user = *(U++);
  414. if (!isa<Instruction>(user))
  415. continue;
  416. // must be call inst
  417. CallInst *CI = cast<CallInst>(user);
  418. Value *res = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  419. Value *newHandle = nullptr;
  420. IRBuilder<> Builder(CI);
  421. // Must be load.
  422. LoadInst *LI = cast<LoadInst>(res);
  423. Function *createHandle = hlslOP.GetOpFunc(
  424. DXIL::OpCode::CreateHandleFromResourceStructForLib, LI->getType());
  425. newHandle = Builder.CreateCall(createHandle, {opArg, LI});
  426. CI->replaceAllUsesWith(newHandle);
  427. if (res->user_empty()) {
  428. if (Instruction *I = dyn_cast<Instruction>(res))
  429. I->eraseFromParent();
  430. }
  431. CI->eraseFromParent();
  432. }
  433. }
  434. } // namespace
  435. void DxilGenerationPass::LowerHLCreateHandle() {
  436. Module *M = m_pHLModule->GetModule();
  437. hlsl::OP &hlslOP = *m_pHLModule->GetOP();
  438. // generate dxil operation
  439. for (iplist<Function>::iterator F : M->getFunctionList()) {
  440. if (F->user_empty())
  441. continue;
  442. if (!F->isDeclaration()) {
  443. hlsl::HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  444. if (group == HLOpcodeGroup::HLCreateHandle) {
  445. // Will lower in later pass.
  446. TranslateHLCreateHandle(F, hlslOP);
  447. }
  448. }
  449. }
  450. }
  451. void DxilGenerationPass::MarkNonUniform(
  452. std::unordered_set<Value *> &NonUniformSet) {
  453. for (Value *V : NonUniformSet) {
  454. for (User *U : V->users()) {
  455. if (GetElementPtrInst *I = dyn_cast<GetElementPtrInst>(U)) {
  456. DxilMDHelper::MarkNonUniform(I);
  457. }
  458. }
  459. }
  460. }
  461. static Value *MergeImmResClass(Value *resClass) {
  462. if (ConstantInt *Imm = dyn_cast<ConstantInt>(resClass)) {
  463. return resClass;
  464. } else {
  465. PHINode *phi = cast<PHINode>(resClass);
  466. Value *immResClass = MergeImmResClass(phi->getIncomingValue(0));
  467. unsigned numOperands = phi->getNumOperands();
  468. for (unsigned i=0;i<numOperands;i++)
  469. phi->setIncomingValue(i, immResClass);
  470. return immResClass;
  471. }
  472. }
  473. static const StringRef kResourceMapErrorMsg = "local resource not guaranteed to map to unique global resource.";
  474. static void EmitResMappingError(Instruction *Res) {
  475. const DebugLoc &DL = Res->getDebugLoc();
  476. if (DL.get()) {
  477. Res->getContext().emitError("line:" + std::to_string(DL.getLine()) +
  478. " col:" + std::to_string(DL.getCol()) + " " +
  479. Twine(kResourceMapErrorMsg));
  480. } else {
  481. Res->getContext().emitError(Twine(kResourceMapErrorMsg) + " With /Zi to show more information.");
  482. }
  483. }
  484. static Value *SelectOnOperand(Value *Cond, CallInst *CIT, CallInst *CIF,
  485. unsigned idx, IRBuilder<> &Builder) {
  486. Value *OpT = CIT->getArgOperand(idx);
  487. Value *OpF = CIF->getArgOperand(idx);
  488. Value *OpSel = OpT;
  489. if (OpT != OpF) {
  490. OpSel = Builder.CreateSelect(Cond, OpT, OpF);
  491. }
  492. return OpSel;
  493. }
  494. static void ReplaceResourceUserWithHandle(LoadInst *Res, Value *handle) {
  495. for (auto resUser = Res->user_begin(); resUser != Res->user_end();) {
  496. CallInst *CI = dyn_cast<CallInst>(*(resUser++));
  497. DXASSERT(GetHLOpcodeGroupByName(CI->getCalledFunction()) ==
  498. HLOpcodeGroup::HLCreateHandle,
  499. "must be createHandle");
  500. CI->replaceAllUsesWith(handle);
  501. CI->eraseFromParent();
  502. }
  503. Res->eraseFromParent();
  504. }
  505. static bool IsResourceType(Type *Ty) {
  506. bool isResource = HLModule::IsHLSLObjectType(Ty);
  507. if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  508. Type *EltTy = AT->getElementType();
  509. while (isa<ArrayType>(EltTy)) {
  510. EltTy = EltTy->getArrayElementType();
  511. }
  512. isResource = HLModule::IsHLSLObjectType(EltTy);
  513. // TODO: support local resource array.
  514. DXASSERT(!isResource, "local resource array");
  515. }
  516. return isResource;
  517. }
  518. void DxilGenerationPass::RemoveLocalDxilResourceAllocas(Function *F) {
  519. BasicBlock &BB = F->getEntryBlock(); // Get the entry node for the function
  520. std::unordered_set<AllocaInst *> localResources;
  521. for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
  522. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { // Is it an alloca?
  523. if (IsResourceType(AI->getAllocatedType())) {
  524. localResources.insert(AI);
  525. }
  526. }
  527. SSAUpdater SSA;
  528. SmallVector<Instruction *, 4> Insts;
  529. for (AllocaInst *AI : localResources) {
  530. // Build list of instructions to promote.
  531. for (User *U : AI->users())
  532. Insts.emplace_back(cast<Instruction>(U));
  533. ResourceRemover(Insts, SSA).run(AI, Insts);
  534. Insts.clear();
  535. }
  536. }
  537. void DxilGenerationPass::TranslateParamDxilResourceHandles(Function *F, std::unordered_map<Instruction *, Value *> &handleMap) {
  538. Type *handleTy = m_pHLModule->GetOP()->GetHandleType();
  539. IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
  540. for (Argument &arg : F->args()) {
  541. Type *Ty = arg.getType();
  542. if (isa<PointerType>(Ty))
  543. Ty = Ty->getPointerElementType();
  544. SmallVector<unsigned,4> arraySizeList;
  545. while (isa<ArrayType>(Ty)) {
  546. arraySizeList.push_back(Ty->getArrayNumElements());
  547. Ty = Ty->getArrayElementType();
  548. }
  549. DXIL::ResourceClass RC = m_pHLModule->GetResourceClass(Ty);
  550. if (RC != DXIL::ResourceClass::Invalid) {
  551. Type *curTy = handleTy;
  552. for (auto it = arraySizeList.rbegin(), E = arraySizeList.rend(); it != E;
  553. it++) {
  554. curTy = ArrayType::get(curTy, *it);
  555. }
  556. curTy = PointerType::get(curTy, 0);
  557. CallInst *castToHandle = cast<CallInst>(HLModule::EmitHLOperationCall(
  558. Builder, HLOpcodeGroup::HLCast, 0, curTy,
  559. {UndefValue::get(arg.getType())}, *F->getParent()));
  560. for (User *U : arg.users()) {
  561. Instruction *I = cast<Instruction>(U);
  562. IRBuilder<> userBuilder(I);
  563. if (LoadInst *ldInst = dyn_cast<LoadInst>(U)) {
  564. Value *handleLd = userBuilder.CreateLoad(castToHandle);
  565. handleMap[ldInst] = handleLd;
  566. } else if (StoreInst *stInst = dyn_cast<StoreInst>(U)) {
  567. Value *res = stInst->getValueOperand();
  568. Value *handle = HLModule::EmitHLOperationCall(
  569. userBuilder, HLOpcodeGroup::HLCast, 0, handleTy, {res},
  570. *F->getParent());
  571. userBuilder.CreateStore(handle, castToHandle);
  572. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  573. // Don't flatten argument here.
  574. continue;
  575. } else {
  576. DXASSERT(
  577. dyn_cast<GEPOperator>(U) != nullptr,
  578. "else AddOpcodeParamForIntrinsic in CodeGen did not patch uses "
  579. "to only have ld/st refer to temp object");
  580. GEPOperator *GEP = cast<GEPOperator>(U);
  581. std::vector<Value *> idxList(GEP->idx_begin(), GEP->idx_end());
  582. Value *handleGEP = userBuilder.CreateGEP(castToHandle, idxList);
  583. for (auto GEPU : GEP->users()) {
  584. Instruction *GEPI = cast<Instruction>(GEPU);
  585. IRBuilder<> gepUserBuilder(GEPI);
  586. if (LoadInst *ldInst = dyn_cast<LoadInst>(GEPU)) {
  587. handleMap[ldInst] = gepUserBuilder.CreateLoad(handleGEP);
  588. } else {
  589. StoreInst *stInst = cast<StoreInst>(GEPU);
  590. Value *res = stInst->getValueOperand();
  591. Value *handle = HLModule::EmitHLOperationCall(
  592. gepUserBuilder, HLOpcodeGroup::HLCast, 0, handleTy, {res},
  593. *F->getParent());
  594. gepUserBuilder.CreateStore(handle, handleGEP);
  595. }
  596. }
  597. }
  598. }
  599. castToHandle->setArgOperand(0, &arg);
  600. }
  601. }
  602. }
  603. void DxilGenerationPass::GenerateParamDxilResourceHandles(
  604. std::unordered_map<Instruction *, Value *> &handleMap) {
  605. Module &M = *m_pHLModule->GetModule();
  606. for (Function &F : M.functions()) {
  607. if (!F.isDeclaration())
  608. TranslateParamDxilResourceHandles(&F, handleMap);
  609. }
  610. }
  611. static void
  612. MarkUavUpdateCounter(DxilResource &res,
  613. std::unordered_set<LoadInst *> &UpdateCounterSet) {
  614. Value *GV = res.GetGlobalSymbol();
  615. for (auto U = GV->user_begin(), E = GV->user_end(); U != E;) {
  616. User *user = *(U++);
  617. // Skip unused user.
  618. if (user->user_empty())
  619. continue;
  620. if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
  621. if (UpdateCounterSet.count(ldInst)) {
  622. DXASSERT_NOMSG(res.GetClass() == DXIL::ResourceClass::UAV);
  623. res.SetHasCounter(true);
  624. }
  625. } else {
  626. DXASSERT(dyn_cast<GEPOperator>(user) != nullptr,
  627. "else AddOpcodeParamForIntrinsic in CodeGen did not patch uses "
  628. "to only have ld/st refer to temp object");
  629. GEPOperator *GEP = cast<GEPOperator>(user);
  630. for (auto GEPU = GEP->user_begin(), GEPE = GEP->user_end();
  631. GEPU != GEPE;) {
  632. // Must be load inst.
  633. LoadInst *ldInst = cast<LoadInst>(*(GEPU++));
  634. if (UpdateCounterSet.count(ldInst)) {
  635. DXASSERT_NOMSG(res.GetClass() == DXIL::ResourceClass::UAV);
  636. res.SetHasCounter(true);
  637. }
  638. }
  639. }
  640. }
  641. }
  642. void DxilGenerationPass::MarkUpdateCounter(
  643. std::unordered_set<LoadInst *> &UpdateCounterSet) {
  644. for (size_t i = 0; i < m_pHLModule->GetUAVs().size(); i++) {
  645. HLResource &UAV = m_pHLModule->GetUAV(i);
  646. MarkUavUpdateCounter(UAV, UpdateCounterSet);
  647. }
  648. }
  649. void DxilGenerationPass::GenerateDxilCBufferHandles(
  650. std::unordered_set<Value *> &NonUniformSet) {
  651. // For CBuffer, handle are mapped to HLCreateHandle.
  652. OP *hlslOP = m_pHLModule->GetOP();
  653. Value *opArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CreateHandleFromResourceStructForLib);
  654. LLVMContext &Ctx = hlslOP->GetCtx();
  655. Value *zeroIdx = hlslOP->GetU32Const(0);
  656. for (size_t i = 0; i < m_pHLModule->GetCBuffers().size(); i++) {
  657. DxilCBuffer &CB = m_pHLModule->GetCBuffer(i);
  658. GlobalVariable *GV = cast<GlobalVariable>(CB.GetGlobalSymbol());
  659. // Remove GEP created in HLObjectOperationLowerHelper::UniformCbPtr.
  660. GV->removeDeadConstantUsers();
  661. std::string handleName = std::string(GV->getName());
  662. DIVariable *DIV = nullptr;
  663. DILocation *DL = nullptr;
  664. if (m_HasDbgInfo) {
  665. DebugInfoFinder &Finder = m_pHLModule->GetOrCreateDebugInfoFinder();
  666. DIV = HLModule::FindGlobalVariableDebugInfo(GV, Finder);
  667. if (DIV)
  668. // TODO: how to get col?
  669. DL = DILocation::get(Ctx, DIV->getLine(), 1,
  670. DIV->getScope());
  671. }
  672. if (CB.GetRangeSize() == 1) {
  673. Function *createHandle =
  674. hlslOP->GetOpFunc(OP::OpCode::CreateHandleFromResourceStructForLib,
  675. GV->getType()->getElementType());
  676. for (auto U = GV->user_begin(); U != GV->user_end(); ) {
  677. // Must HLCreateHandle.
  678. CallInst *CI = cast<CallInst>(*(U++));
  679. // Put createHandle to entry block.
  680. auto InsertPt =
  681. CI->getParent()->getParent()->getEntryBlock().getFirstInsertionPt();
  682. IRBuilder<> Builder(InsertPt);
  683. Value *V = Builder.CreateLoad(GV);
  684. CallInst *handle = Builder.CreateCall(createHandle, {opArg, V}, handleName);
  685. if (m_HasDbgInfo) {
  686. // TODO: add debug info.
  687. //handle->setDebugLoc(DL);
  688. }
  689. CI->replaceAllUsesWith(handle);
  690. CI->eraseFromParent();
  691. }
  692. } else {
  693. PointerType *Ty = GV->getType();
  694. Type *EltTy = Ty->getElementType()->getArrayElementType()->getPointerTo(
  695. Ty->getAddressSpace());
  696. Function *createHandle = hlslOP->GetOpFunc(
  697. OP::OpCode::CreateHandleFromResourceStructForLib, EltTy->getPointerElementType());
  698. for (auto U = GV->user_begin(); U != GV->user_end();) {
  699. // Must HLCreateHandle.
  700. CallInst *CI = cast<CallInst>(*(U++));
  701. IRBuilder<> Builder(CI);
  702. Value *CBIndex = CI->getArgOperand(HLOperandIndex::kCreateHandleIndexOpIdx);
  703. if (isa<ConstantInt>(CBIndex)) {
  704. // Put createHandle to entry block for const index.
  705. auto InsertPt = CI->getParent()
  706. ->getParent()
  707. ->getEntryBlock()
  708. .getFirstInsertionPt();
  709. Builder.SetInsertPoint(InsertPt);
  710. }
  711. // Add GEP for cbv array use.
  712. Value *GEP = Builder.CreateGEP(GV, {zeroIdx, CBIndex});
  713. /*
  714. if (!NonUniformSet.count(CBIndex))
  715. args[DXIL::OperandIndex::kCreateHandleIsUniformOpIdx] =
  716. hlslOP->GetI1Const(0);
  717. else
  718. args[DXIL::OperandIndex::kCreateHandleIsUniformOpIdx] =
  719. hlslOP->GetI1Const(1);*/
  720. Value *V = Builder.CreateLoad(GEP);
  721. CallInst *handle = Builder.CreateCall(createHandle, {opArg, V}, handleName);
  722. CI->replaceAllUsesWith(handle);
  723. CI->eraseFromParent();
  724. }
  725. }
  726. }
  727. }
  728. void DxilGenerationPass::GenerateDxilOperations(
  729. Module &M, std::unordered_set<LoadInst *> &UpdateCounterSet,
  730. std::unordered_set<Value *> &NonUniformSet) {
  731. // remove all functions except entry function
  732. Function *entry = m_pHLModule->GetEntryFunction();
  733. const ShaderModel *pSM = m_pHLModule->GetShaderModel();
  734. Function *patchConstantFunc = nullptr;
  735. if (pSM->IsHS()) {
  736. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(entry);
  737. patchConstantFunc = funcProps.ShaderProps.HS.patchConstantFunc;
  738. }
  739. if (!pSM->IsLib()) {
  740. for (auto F = M.begin(); F != M.end();) {
  741. Function *func = F++;
  742. if (func->isDeclaration())
  743. continue;
  744. if (func == entry)
  745. continue;
  746. if (func == patchConstantFunc)
  747. continue;
  748. if (func->user_empty())
  749. func->eraseFromParent();
  750. }
  751. }
  752. TranslateBuiltinOperations(*m_pHLModule, m_extensionsCodegenHelper,
  753. UpdateCounterSet, NonUniformSet);
  754. // Remove unused HL Operation functions.
  755. std::vector<Function *> deadList;
  756. for (iplist<Function>::iterator F : M.getFunctionList()) {
  757. hlsl::HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(F);
  758. if (group != HLOpcodeGroup::NotHL || F->isIntrinsic())
  759. if (F->user_empty())
  760. deadList.emplace_back(F);
  761. }
  762. for (Function *F : deadList)
  763. F->eraseFromParent();
  764. }
  765. static void TranslatePreciseAttributeOnFunction(Function &F, Module &M) {
  766. BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
  767. // Find allocas that has precise attribute, by looking at all instructions in
  768. // the entry node
  769. for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {
  770. Instruction *Inst = (I++);
  771. if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst)) {
  772. if (HLModule::HasPreciseAttributeWithMetadata(AI)) {
  773. HLModule::MarkPreciseAttributeOnPtrWithFunctionCall(AI, M);
  774. }
  775. } else {
  776. DXASSERT(!HLModule::HasPreciseAttributeWithMetadata(Inst), "Only alloca can has precise metadata.");
  777. }
  778. }
  779. FastMathFlags FMF;
  780. FMF.setUnsafeAlgebra();
  781. // Set fast math for all FPMathOperators.
  782. // Already set FastMath in options. But that only enable things like fadd.
  783. // Every inst which type is float can be cast to FPMathOperator.
  784. for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
  785. BasicBlock *BB = BBI;
  786. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  787. if (FPMathOperator *FPMath = dyn_cast<FPMathOperator>(I)) {
  788. // Set precise fast math on those instructions that support it.
  789. if (DxilModule::PreservesFastMathFlags(I))
  790. I->copyFastMathFlags(FMF);
  791. }
  792. }
  793. }
  794. }
  795. void DxilGenerationPass::TranslatePreciseAttribute() {
  796. bool bIEEEStrict = m_pHLModule->GetHLOptions().bIEEEStrict;
  797. // If IEEE strict, everying is precise, don't need to mark it.
  798. if (bIEEEStrict)
  799. return;
  800. Module &M = *m_pHLModule->GetModule();
  801. // TODO: If not inline every function, for function has call site with precise
  802. // argument and call site without precise argument, need to clone the function
  803. // to propagate the precise for the precise call site.
  804. // This should be done at CGMSHLSLRuntime::FinishCodeGen.
  805. if (m_pHLModule->GetShaderModel()->IsLib()) {
  806. // TODO: If all functions have been inlined, and unreferenced functions removed,
  807. // it should make sense to run on all funciton bodies,
  808. // even when not processing a library.
  809. for (Function &F : M.functions()) {
  810. if (!F.isDeclaration())
  811. TranslatePreciseAttributeOnFunction(F, M);
  812. }
  813. } else {
  814. Function *EntryFn = m_pHLModule->GetEntryFunction();
  815. TranslatePreciseAttributeOnFunction(*EntryFn, M);
  816. if (m_pHLModule->GetShaderModel()->IsHS()) {
  817. DxilFunctionProps &EntryQual = m_pHLModule->GetDxilFunctionProps(EntryFn);
  818. Function *patchConstantFunc = EntryQual.ShaderProps.HS.patchConstantFunc;
  819. TranslatePreciseAttributeOnFunction(*patchConstantFunc, M);
  820. }
  821. }
  822. }
  823. char DxilGenerationPass::ID = 0;
  824. ModulePass *llvm::createDxilGenerationPass(bool NotOptimized, hlsl::HLSLExtensionsCodegenHelper *extensionsHelper) {
  825. DxilGenerationPass *dxilPass = new DxilGenerationPass(NotOptimized);
  826. dxilPass->SetExtensionsHelper(extensionsHelper);
  827. return dxilPass;
  828. }
  829. INITIALIZE_PASS(DxilGenerationPass, "dxilgen", "HLSL DXIL Generation", false, false)
  830. ///////////////////////////////////////////////////////////////////////////////
  831. namespace {
  832. class HLEmitMetadata : public ModulePass {
  833. public:
  834. static char ID; // Pass identification, replacement for typeid
  835. explicit HLEmitMetadata() : ModulePass(ID) {}
  836. const char *getPassName() const override { return "HLSL High-Level Metadata Emit"; }
  837. bool runOnModule(Module &M) override {
  838. if (M.HasHLModule()) {
  839. HLModule::ClearHLMetadata(M);
  840. M.GetHLModule().EmitHLMetadata();
  841. return true;
  842. }
  843. return false;
  844. }
  845. };
  846. }
  847. char HLEmitMetadata::ID = 0;
  848. ModulePass *llvm::createHLEmitMetadataPass() {
  849. return new HLEmitMetadata();
  850. }
  851. INITIALIZE_PASS(HLEmitMetadata, "hlsl-hlemit", "HLSL High-Level Metadata Emit", false, false)
  852. ///////////////////////////////////////////////////////////////////////////////
  853. namespace {
  854. class HLEnsureMetadata : public ModulePass {
  855. public:
  856. static char ID; // Pass identification, replacement for typeid
  857. explicit HLEnsureMetadata() : ModulePass(ID) {}
  858. const char *getPassName() const override { return "HLSL High-Level Metadata Ensure"; }
  859. bool runOnModule(Module &M) override {
  860. if (!M.HasHLModule()) {
  861. M.GetOrCreateHLModule();
  862. return true;
  863. }
  864. return false;
  865. }
  866. };
  867. }
  868. char HLEnsureMetadata::ID = 0;
  869. ModulePass *llvm::createHLEnsureMetadataPass() {
  870. return new HLEnsureMetadata();
  871. }
  872. INITIALIZE_PASS(HLEnsureMetadata, "hlsl-hlensure", "HLSL High-Level Metadata Ensure", false, false)
  873. ///////////////////////////////////////////////////////////////////////////////
  874. // Precise propagate.
  875. namespace {
  876. class DxilPrecisePropagatePass : public ModulePass {
  877. HLModule *m_pHLModule;
  878. public:
  879. static char ID; // Pass identification, replacement for typeid
  880. explicit DxilPrecisePropagatePass() : ModulePass(ID), m_pHLModule(nullptr) {}
  881. const char *getPassName() const override { return "DXIL Precise Propagate"; }
  882. bool runOnModule(Module &M) override {
  883. DxilModule &dxilModule = M.GetOrCreateDxilModule();
  884. DxilTypeSystem &typeSys = dxilModule.GetTypeSystem();
  885. std::unordered_set<Instruction*> processedSet;
  886. std::vector<Function*> deadList;
  887. for (Function &F : M.functions()) {
  888. if (HLModule::HasPreciseAttribute(&F)) {
  889. PropagatePreciseOnFunctionUser(F, typeSys, processedSet);
  890. deadList.emplace_back(&F);
  891. }
  892. }
  893. for (Function *F : deadList)
  894. F->eraseFromParent();
  895. return true;
  896. }
  897. private:
  898. void PropagatePreciseOnFunctionUser(
  899. Function &F, DxilTypeSystem &typeSys,
  900. std::unordered_set<Instruction *> &processedSet);
  901. };
  902. char DxilPrecisePropagatePass::ID = 0;
  903. }
  904. static void PropagatePreciseAttribute(Instruction *I, DxilTypeSystem &typeSys,
  905. std::unordered_set<Instruction *> &processedSet);
  906. static void PropagatePreciseAttributeOnOperand(
  907. Value *V, DxilTypeSystem &typeSys, LLVMContext &Context,
  908. std::unordered_set<Instruction *> &processedSet) {
  909. Instruction *I = dyn_cast<Instruction>(V);
  910. // Skip none inst.
  911. if (!I)
  912. return;
  913. FPMathOperator *FPMath = dyn_cast<FPMathOperator>(I);
  914. // Skip none FPMath
  915. if (!FPMath)
  916. return;
  917. // Skip inst already marked.
  918. if (processedSet.count(I) > 0)
  919. return;
  920. // TODO: skip precise on integer type, sample instruction...
  921. processedSet.insert(I);
  922. // Set precise fast math on those instructions that support it.
  923. if (DxilModule::PreservesFastMathFlags(I))
  924. DxilModule::SetPreciseFastMathFlags(I);
  925. // Fast math not work on call, use metadata.
  926. if (CallInst *CI = dyn_cast<CallInst>(I))
  927. HLModule::MarkPreciseAttributeWithMetadata(CI);
  928. PropagatePreciseAttribute(I, typeSys, processedSet);
  929. }
  930. static void PropagatePreciseAttributeOnPointer(
  931. Value *Ptr, DxilTypeSystem &typeSys, LLVMContext &Context,
  932. std::unordered_set<Instruction *> &processedSet) {
  933. // Find all store and propagate on the val operand of store.
  934. // For CallInst, if Ptr is used as out parameter, mark it.
  935. for (User *U : Ptr->users()) {
  936. Instruction *user = cast<Instruction>(U);
  937. if (StoreInst *stInst = dyn_cast<StoreInst>(user)) {
  938. Value *val = stInst->getValueOperand();
  939. PropagatePreciseAttributeOnOperand(val, typeSys, Context, processedSet);
  940. } else if (CallInst *CI = dyn_cast<CallInst>(user)) {
  941. bool bReadOnly = true;
  942. Function *F = CI->getCalledFunction();
  943. const DxilFunctionAnnotation *funcAnnotation =
  944. typeSys.GetFunctionAnnotation(F);
  945. for (unsigned i = 0; i < CI->getNumArgOperands(); ++i) {
  946. if (Ptr != CI->getArgOperand(i))
  947. continue;
  948. const DxilParameterAnnotation &paramAnnotation =
  949. funcAnnotation->GetParameterAnnotation(i);
  950. // OutputPatch and OutputStream will be checked after scalar repl.
  951. // Here only check out/inout
  952. if (paramAnnotation.GetParamInputQual() == DxilParamInputQual::Out ||
  953. paramAnnotation.GetParamInputQual() == DxilParamInputQual::Inout) {
  954. bReadOnly = false;
  955. break;
  956. }
  957. }
  958. if (!bReadOnly)
  959. PropagatePreciseAttributeOnOperand(CI, typeSys, Context, processedSet);
  960. }
  961. }
  962. }
  963. static void
  964. PropagatePreciseAttribute(Instruction *I, DxilTypeSystem &typeSys,
  965. std::unordered_set<Instruction *> &processedSet) {
  966. LLVMContext &Context = I->getContext();
  967. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
  968. PropagatePreciseAttributeOnPointer(AI, typeSys, Context, processedSet);
  969. } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
  970. // Propagate every argument.
  971. // TODO: only propagate precise argument.
  972. for (Value *src : I->operands())
  973. PropagatePreciseAttributeOnOperand(src, typeSys, Context, processedSet);
  974. } else if (FPMathOperator *FPMath = dyn_cast<FPMathOperator>(I)) {
  975. // TODO: only propagate precise argument.
  976. for (Value *src : I->operands())
  977. PropagatePreciseAttributeOnOperand(src, typeSys, Context, processedSet);
  978. } else if (LoadInst *ldInst = dyn_cast<LoadInst>(I)) {
  979. Value *Ptr = ldInst->getPointerOperand();
  980. PropagatePreciseAttributeOnPointer(Ptr, typeSys, Context, processedSet);
  981. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
  982. PropagatePreciseAttributeOnPointer(GEP, typeSys, Context, processedSet);
  983. // TODO: support more case which need
  984. }
  985. void DxilPrecisePropagatePass::PropagatePreciseOnFunctionUser(
  986. Function &F, DxilTypeSystem &typeSys,
  987. std::unordered_set<Instruction *> &processedSet) {
  988. LLVMContext &Context = F.getContext();
  989. for (auto U = F.user_begin(), E = F.user_end(); U != E;) {
  990. CallInst *CI = cast<CallInst>(*(U++));
  991. Value *V = CI->getArgOperand(0);
  992. PropagatePreciseAttributeOnOperand(V, typeSys, Context, processedSet);
  993. CI->eraseFromParent();
  994. }
  995. }
  996. ModulePass *llvm::createDxilPrecisePropagatePass() {
  997. return new DxilPrecisePropagatePass();
  998. }
  999. INITIALIZE_PASS(DxilPrecisePropagatePass, "hlsl-dxil-precise", "DXIL precise attribute propagate", false, false)
  1000. ///////////////////////////////////////////////////////////////////////////////
  1001. namespace {
  1002. class HLDeadFunctionElimination : public ModulePass {
  1003. public:
  1004. static char ID; // Pass identification, replacement for typeid
  1005. explicit HLDeadFunctionElimination () : ModulePass(ID) {}
  1006. const char *getPassName() const override { return "Remove all unused function except entry from HLModule"; }
  1007. bool runOnModule(Module &M) override {
  1008. if (M.HasHLModule()) {
  1009. HLModule &HLM = M.GetHLModule();
  1010. bool IsLib = HLM.GetShaderModel()->IsLib();
  1011. // Remove unused functions except entry and patch constant func.
  1012. // For library profile, only remove unused external functions.
  1013. Function *EntryFunc = HLM.GetEntryFunction();
  1014. Function *PatchConstantFunc = HLM.GetPatchConstantFunction();
  1015. return dxilutil::RemoveUnusedFunctions(M, EntryFunc, PatchConstantFunc,
  1016. IsLib);
  1017. }
  1018. return false;
  1019. }
  1020. };
  1021. }
  1022. char HLDeadFunctionElimination::ID = 0;
  1023. ModulePass *llvm::createHLDeadFunctionEliminationPass() {
  1024. return new HLDeadFunctionElimination();
  1025. }
  1026. INITIALIZE_PASS(HLDeadFunctionElimination, "hl-dfe", "Remove all unused function except entry from HLModule", false, false)
  1027. ///////////////////////////////////////////////////////////////////////////////
  1028. // Legalize resource use.
  1029. // Map local or static global resource to global resource.
  1030. // Require inline for static global resource.
  1031. namespace {
  1032. class DxilLegalizeStaticResourceUsePass : public ModulePass {
  1033. public:
  1034. static char ID; // Pass identification, replacement for typeid
  1035. explicit DxilLegalizeStaticResourceUsePass()
  1036. : ModulePass(ID) {}
  1037. const char *getPassName() const override {
  1038. return "DXIL Legalize Static Resource Use";
  1039. }
  1040. bool runOnModule(Module &M) override {
  1041. HLModule &HLM = M.GetOrCreateHLModule();
  1042. OP *hlslOP = HLM.GetOP();
  1043. Type *HandleTy = hlslOP->GetHandleType();
  1044. // Promote static global variables.
  1045. PromoteStaticGlobalResources(M);
  1046. // Lower handle cast.
  1047. for (Function &F : M.functions()) {
  1048. if (!F.isDeclaration())
  1049. continue;
  1050. HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(&F);
  1051. if (group != HLOpcodeGroup::HLCast)
  1052. continue;
  1053. Type *Ty = F.getFunctionType()->getReturnType();
  1054. if (Ty->isPointerTy())
  1055. Ty = Ty->getPointerElementType();
  1056. if (HLModule::IsHLSLObjectType(Ty)) {
  1057. TransformHandleCast(F);
  1058. }
  1059. }
  1060. Value *UndefHandle = UndefValue::get(HandleTy);
  1061. if (!UndefHandle->user_empty()) {
  1062. for (User *U : UndefHandle->users()) {
  1063. // Report error if undef handle used for function call.
  1064. if (isa<CallInst>(U)) {
  1065. if (Instruction *UI = dyn_cast<Instruction>(U))
  1066. EmitResMappingError(UI);
  1067. else
  1068. M.getContext().emitError(kResourceMapErrorMsg);
  1069. }
  1070. }
  1071. }
  1072. return true;
  1073. }
  1074. private:
  1075. void PromoteStaticGlobalResources(Module &M);
  1076. void TransformHandleCast(Function &F);
  1077. };
  1078. char DxilLegalizeStaticResourceUsePass::ID = 0;
  1079. class DxilLegalizeResourceUsePass : public FunctionPass {
  1080. HLModule *m_pHLModule;
  1081. void getAnalysisUsage(AnalysisUsage &AU) const override;
  1082. public:
  1083. static char ID; // Pass identification, replacement for typeid
  1084. explicit DxilLegalizeResourceUsePass()
  1085. : FunctionPass(ID), m_pHLModule(nullptr) {}
  1086. const char *getPassName() const override {
  1087. return "DXIL Legalize Resource Use";
  1088. }
  1089. bool runOnFunction(Function &F) override {
  1090. // Promote local resource first.
  1091. PromoteLocalResource(F);
  1092. return true;
  1093. }
  1094. private:
  1095. void PromoteLocalResource(Function &F);
  1096. };
  1097. char DxilLegalizeResourceUsePass::ID = 0;
  1098. }
  1099. void DxilLegalizeResourceUsePass::getAnalysisUsage(AnalysisUsage &AU) const {
  1100. AU.addRequired<AssumptionCacheTracker>();
  1101. AU.addRequired<DominatorTreeWrapperPass>();
  1102. AU.setPreservesAll();
  1103. }
  1104. void DxilLegalizeResourceUsePass::PromoteLocalResource(Function &F) {
  1105. std::vector<AllocaInst *> Allocas;
  1106. DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1107. AssumptionCache &AC =
  1108. getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1109. HLModule &HLM = F.getParent()->GetOrCreateHLModule();
  1110. OP *hlslOP = HLM.GetOP();
  1111. Type *HandleTy = hlslOP->GetHandleType();
  1112. bool IsLib = HLM.GetShaderModel()->IsLib();
  1113. BasicBlock &BB = F.getEntryBlock();
  1114. unsigned allocaSize = 0;
  1115. while (1) {
  1116. Allocas.clear();
  1117. // Find allocas that are safe to promote, by looking at all instructions in
  1118. // the entry node
  1119. for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
  1120. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { // Is it an alloca?
  1121. if (HandleTy == dxilutil::GetArrayEltTy(AI->getAllocatedType())) {
  1122. // Skip for unpromotable for lib.
  1123. if (!isAllocaPromotable(AI) && IsLib)
  1124. continue;
  1125. if (!isAllocaPromotable(AI)) {
  1126. static const StringRef kNonPromotableLocalResourceErrorMsg =
  1127. "non-promotable local resource found.";
  1128. F.getContext().emitError(kNonPromotableLocalResourceErrorMsg);
  1129. throw hlsl::Exception(DXC_E_ABORT_COMPILATION_ERROR,
  1130. kNonPromotableLocalResourceErrorMsg);
  1131. continue;
  1132. }
  1133. Allocas.push_back(AI);
  1134. }
  1135. }
  1136. if (Allocas.empty())
  1137. break;
  1138. // No update.
  1139. // Report error and break.
  1140. if (allocaSize == Allocas.size()) {
  1141. F.getContext().emitError(kResourceMapErrorMsg);
  1142. break;
  1143. }
  1144. allocaSize = Allocas.size();
  1145. PromoteMemToReg(Allocas, *DT, nullptr, &AC);
  1146. }
  1147. return;
  1148. }
  1149. FunctionPass *llvm::createDxilLegalizeResourceUsePass() {
  1150. return new DxilLegalizeResourceUsePass();
  1151. }
  1152. INITIALIZE_PASS_BEGIN(DxilLegalizeResourceUsePass,
  1153. "hlsl-dxil-legalize-resource-use",
  1154. "DXIL legalize resource use", false, true)
  1155. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1156. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1157. INITIALIZE_PASS_END(DxilLegalizeResourceUsePass,
  1158. "hlsl-dxil-legalize-resource-use",
  1159. "DXIL legalize resource use", false, true)
  1160. void DxilLegalizeStaticResourceUsePass::PromoteStaticGlobalResources(
  1161. Module &M) {
  1162. HLModule &HLM = M.GetOrCreateHLModule();
  1163. Type *HandleTy = HLM.GetOP()->GetHandleType();
  1164. std::set<GlobalVariable *> staticResources;
  1165. for (auto &GV : M.globals()) {
  1166. if (GV.getLinkage() == GlobalValue::LinkageTypes::InternalLinkage &&
  1167. HandleTy == dxilutil::GetArrayEltTy(GV.getType())) {
  1168. staticResources.insert(&GV);
  1169. }
  1170. }
  1171. SSAUpdater SSA;
  1172. SmallVector<Instruction *, 4> Insts;
  1173. // Make sure every resource load has mapped to global variable.
  1174. while (!staticResources.empty()) {
  1175. bool bUpdated = false;
  1176. for (auto it = staticResources.begin(); it != staticResources.end();) {
  1177. GlobalVariable *GV = *(it++);
  1178. // Build list of instructions to promote.
  1179. for (User *U : GV->users()) {
  1180. Instruction *I = cast<Instruction>(U);
  1181. Insts.emplace_back(I);
  1182. }
  1183. LoadAndStorePromoter(Insts, SSA).run(Insts);
  1184. if (GV->user_empty()) {
  1185. bUpdated = true;
  1186. staticResources.erase(GV);
  1187. }
  1188. Insts.clear();
  1189. }
  1190. if (!bUpdated) {
  1191. M.getContext().emitError(kResourceMapErrorMsg);
  1192. break;
  1193. }
  1194. }
  1195. }
  1196. static void ReplaceResUseWithHandle(Instruction *Res, Value *Handle) {
  1197. Type *HandleTy = Handle->getType();
  1198. for (auto ResU = Res->user_begin(); ResU != Res->user_end();) {
  1199. Instruction *I = cast<Instruction>(*(ResU++));
  1200. if (isa<LoadInst>(I)) {
  1201. ReplaceResUseWithHandle(I, Handle);
  1202. } else if (isa<CallInst>(I)) {
  1203. if (I->getType() == HandleTy) {
  1204. I->replaceAllUsesWith(Handle);
  1205. } else {
  1206. DXASSERT(0, "must createHandle here");
  1207. }
  1208. } else {
  1209. DXASSERT(0, "should only used by load and createHandle");
  1210. }
  1211. if (I->user_empty() && !I->getType()->isVoidTy()) {
  1212. I->eraseFromParent();
  1213. }
  1214. }
  1215. }
  1216. void DxilLegalizeStaticResourceUsePass::TransformHandleCast(Function &F) {
  1217. for (auto U = F.user_begin(); U != F.user_end(); ) {
  1218. CallInst *CI = cast<CallInst>(*(U++));
  1219. Value *Handle = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1220. ReplaceResUseWithHandle(CI, Handle);
  1221. if (CI->user_empty())
  1222. CI->eraseFromParent();
  1223. }
  1224. }
  1225. ModulePass *llvm::createDxilLegalizeStaticResourceUsePass() {
  1226. return new DxilLegalizeStaticResourceUsePass();
  1227. }
  1228. INITIALIZE_PASS(DxilLegalizeStaticResourceUsePass,
  1229. "hlsl-dxil-legalize-static-resource-use",
  1230. "DXIL legalize static resource use", false, false)
  1231. ///////////////////////////////////////////////////////////////////////////////
  1232. // Legalize EvalOperations.
  1233. // Make sure src of EvalOperations are from function parameter.
  1234. // This is needed in order to translate EvaluateAttribute operations that traces
  1235. // back to LoadInput operations during translation stage. Promoting load/store
  1236. // instructions beforehand will allow us to easily trace back to loadInput from
  1237. // function call.
  1238. namespace {
  1239. class DxilLegalizeEvalOperations : public ModulePass {
  1240. public:
  1241. static char ID; // Pass identification, replacement for typeid
  1242. explicit DxilLegalizeEvalOperations() : ModulePass(ID) {}
  1243. const char *getPassName() const override {
  1244. return "DXIL Legalize EvalOperations";
  1245. }
  1246. bool runOnModule(Module &M) override {
  1247. for (Function &F : M.getFunctionList()) {
  1248. hlsl::HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(&F);
  1249. if (group != HLOpcodeGroup::NotHL) {
  1250. std::vector<CallInst *> EvalFunctionCalls;
  1251. // Find all EvaluateAttribute calls
  1252. for (User *U : F.users()) {
  1253. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  1254. IntrinsicOp evalOp =
  1255. static_cast<IntrinsicOp>(hlsl::GetHLOpcode(CI));
  1256. if (evalOp == IntrinsicOp::IOP_EvaluateAttributeAtSample ||
  1257. evalOp == IntrinsicOp::IOP_EvaluateAttributeCentroid ||
  1258. evalOp == IntrinsicOp::IOP_EvaluateAttributeSnapped) {
  1259. EvalFunctionCalls.push_back(CI);
  1260. }
  1261. }
  1262. }
  1263. if (EvalFunctionCalls.empty()) {
  1264. continue;
  1265. }
  1266. // Start from the call instruction, find all allocas that this call
  1267. // uses.
  1268. std::unordered_set<AllocaInst *> allocas;
  1269. for (CallInst *CI : EvalFunctionCalls) {
  1270. FindAllocasForEvalOperations(CI, allocas);
  1271. }
  1272. SSAUpdater SSA;
  1273. SmallVector<Instruction *, 4> Insts;
  1274. for (AllocaInst *AI : allocas) {
  1275. for (User *user : AI->users()) {
  1276. if (isa<LoadInst>(user) || isa<StoreInst>(user)) {
  1277. Insts.emplace_back(cast<Instruction>(user));
  1278. }
  1279. }
  1280. LoadAndStorePromoter(Insts, SSA).run(Insts);
  1281. Insts.clear();
  1282. }
  1283. }
  1284. }
  1285. return true;
  1286. }
  1287. private:
  1288. void FindAllocasForEvalOperations(Value *val,
  1289. std::unordered_set<AllocaInst *> &allocas);
  1290. };
  1291. char DxilLegalizeEvalOperations::ID = 0;
  1292. // Find allocas for EvaluateAttribute operations
  1293. void DxilLegalizeEvalOperations::FindAllocasForEvalOperations(
  1294. Value *val, std::unordered_set<AllocaInst *> &allocas) {
  1295. Value *CurVal = val;
  1296. while (!isa<AllocaInst>(CurVal)) {
  1297. if (CallInst *CI = dyn_cast<CallInst>(CurVal)) {
  1298. CurVal = CI->getOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1299. } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(CurVal)) {
  1300. Value *arg0 =
  1301. IE->getOperand(0); // Could be another insertelement or undef
  1302. Value *arg1 = IE->getOperand(1);
  1303. FindAllocasForEvalOperations(arg0, allocas);
  1304. CurVal = arg1;
  1305. } else if (ShuffleVectorInst *SV = dyn_cast<ShuffleVectorInst>(CurVal)) {
  1306. Value *arg0 = SV->getOperand(0);
  1307. Value *arg1 = SV->getOperand(1);
  1308. FindAllocasForEvalOperations(
  1309. arg0, allocas); // Shuffle vector could come from different allocas
  1310. CurVal = arg1;
  1311. } else if (ExtractElementInst *EE = dyn_cast<ExtractElementInst>(CurVal)) {
  1312. CurVal = EE->getOperand(0);
  1313. } else if (LoadInst *LI = dyn_cast<LoadInst>(CurVal)) {
  1314. CurVal = LI->getOperand(0);
  1315. } else {
  1316. break;
  1317. }
  1318. }
  1319. if (AllocaInst *AI = dyn_cast<AllocaInst>(CurVal)) {
  1320. allocas.insert(AI);
  1321. }
  1322. }
  1323. } // namespace
  1324. ModulePass *llvm::createDxilLegalizeEvalOperationsPass() {
  1325. return new DxilLegalizeEvalOperations();
  1326. }
  1327. INITIALIZE_PASS(DxilLegalizeEvalOperations,
  1328. "hlsl-dxil-legalize-eval-operations",
  1329. "DXIL legalize eval operations", false, false)
  1330. ///////////////////////////////////////////////////////////////////////////////
  1331. // Translate RawBufferLoad/RawBufferStore
  1332. // This pass is to make sure that we generate correct buffer load for DXIL
  1333. // For DXIL < 1.2, rawBufferLoad will be translated to BufferLoad instruction
  1334. // without mask.
  1335. // For DXIL >= 1.2, if min precision is enabled, currently generation pass is
  1336. // producing i16/f16 return type for min precisions. For rawBuffer, we will
  1337. // change this so that min precisions are returning its actual scalar type (i32/f32)
  1338. // and will be truncated to their corresponding types after loading / before storing.
  1339. namespace {
  1340. class DxilTranslateRawBuffer : public ModulePass {
  1341. public:
  1342. static char ID;
  1343. explicit DxilTranslateRawBuffer() : ModulePass(ID) {}
  1344. bool runOnModule(Module &M) {
  1345. unsigned major, minor;
  1346. M.GetDxilModule().GetDxilVersion(major, minor);
  1347. if (major == 1 && minor < 2) {
  1348. for (auto F = M.functions().begin(), E = M.functions().end(); F != E;) {
  1349. Function *func = &*(F++);
  1350. if (func->hasName()) {
  1351. if (func->getName().startswith("dx.op.rawBufferLoad")) {
  1352. ReplaceRawBufferLoad(func, M);
  1353. func->eraseFromParent();
  1354. } else if (func->getName().startswith("dx.op.rawBufferStore")) {
  1355. ReplaceRawBufferStore(func, M);
  1356. func->eraseFromParent();
  1357. }
  1358. }
  1359. }
  1360. } else if (M.GetDxilModule().GetUseMinPrecision()) {
  1361. for (auto F = M.functions().begin(), E = M.functions().end(); F != E;) {
  1362. Function *func = &*(F++);
  1363. if (func->hasName()) {
  1364. if (func->getName().startswith("dx.op.rawBufferLoad")) {
  1365. ReplaceMinPrecisionRawBufferLoad(func, M);
  1366. } else if (func->getName().startswith("dx.op.rawBufferStore")) {
  1367. ReplaceMinPrecisionRawBufferStore(func, M);
  1368. }
  1369. }
  1370. }
  1371. }
  1372. return true;
  1373. }
  1374. private:
  1375. // Replace RawBufferLoad/Store to BufferLoad/Store for DXIL < 1.2
  1376. void ReplaceRawBufferLoad(Function *F, Module &M);
  1377. void ReplaceRawBufferStore(Function *F, Module &M);
  1378. // Replace RawBufferLoad/Store of min-precision types to have its actual storage size
  1379. void ReplaceMinPrecisionRawBufferLoad(Function *F, Module &M);
  1380. void ReplaceMinPrecisionRawBufferStore(Function *F, Module &M);
  1381. void ReplaceMinPrecisionRawBufferLoadByType(Function *F, Type *FromTy,
  1382. Type *ToTy, OP *Op,
  1383. const DataLayout &DL);
  1384. };
  1385. } // namespace
  1386. void DxilTranslateRawBuffer::ReplaceRawBufferLoad(Function *F,
  1387. Module &M) {
  1388. OP *op = M.GetDxilModule().GetOP();
  1389. Type *RTy = F->getReturnType();
  1390. if (StructType *STy = dyn_cast<StructType>(RTy)) {
  1391. Type *ETy = STy->getElementType(0);
  1392. Function *newFunction = op->GetOpFunc(hlsl::DXIL::OpCode::BufferLoad, ETy);
  1393. for (auto U = F->user_begin(), E = F->user_end(); U != E;) {
  1394. User *user = *(U++);
  1395. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  1396. IRBuilder<> Builder(CI);
  1397. SmallVector<Value *, 4> args;
  1398. args.emplace_back(op->GetI32Const((unsigned)DXIL::OpCode::BufferLoad));
  1399. for (unsigned i = 1; i < 4; ++i) {
  1400. args.emplace_back(CI->getArgOperand(i));
  1401. }
  1402. CallInst *newCall = Builder.CreateCall(newFunction, args);
  1403. CI->replaceAllUsesWith(newCall);
  1404. CI->eraseFromParent();
  1405. } else {
  1406. DXASSERT(false, "function can only be used with call instructions.");
  1407. }
  1408. }
  1409. } else {
  1410. DXASSERT(false, "RawBufferLoad should return struct type.");
  1411. }
  1412. }
  1413. void DxilTranslateRawBuffer::ReplaceRawBufferStore(Function *F,
  1414. Module &M) {
  1415. OP *op = M.GetDxilModule().GetOP();
  1416. DXASSERT(F->getReturnType()->isVoidTy(), "rawBufferStore should return a void type.");
  1417. Type *ETy = F->getFunctionType()->getParamType(4); // value
  1418. Function *newFunction = op->GetOpFunc(hlsl::DXIL::OpCode::BufferStore, ETy);
  1419. for (auto U = F->user_begin(), E = F->user_end(); U != E;) {
  1420. User *user = *(U++);
  1421. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  1422. IRBuilder<> Builder(CI);
  1423. SmallVector<Value *, 4> args;
  1424. args.emplace_back(op->GetI32Const((unsigned)DXIL::OpCode::BufferStore));
  1425. for (unsigned i = 1; i < 9; ++i) {
  1426. args.emplace_back(CI->getArgOperand(i));
  1427. }
  1428. Builder.CreateCall(newFunction, args);
  1429. CI->eraseFromParent();
  1430. }
  1431. else {
  1432. DXASSERT(false, "function can only be used with call instructions.");
  1433. }
  1434. }
  1435. }
  1436. void DxilTranslateRawBuffer::ReplaceMinPrecisionRawBufferLoad(Function *F,
  1437. Module &M) {
  1438. OP *Op = M.GetDxilModule().GetOP();
  1439. Type *RetTy = F->getReturnType();
  1440. if (StructType *STy = dyn_cast<StructType>(RetTy)) {
  1441. Type *EltTy = STy->getElementType(0);
  1442. if (EltTy->isHalfTy()) {
  1443. ReplaceMinPrecisionRawBufferLoadByType(F, Type::getHalfTy(M.getContext()),
  1444. Type::getFloatTy(M.getContext()),
  1445. Op, M.getDataLayout());
  1446. } else if (EltTy == Type::getInt16Ty(M.getContext())) {
  1447. ReplaceMinPrecisionRawBufferLoadByType(
  1448. F, Type::getInt16Ty(M.getContext()), Type::getInt32Ty(M.getContext()),
  1449. Op, M.getDataLayout());
  1450. }
  1451. } else {
  1452. DXASSERT(false, "RawBufferLoad should return struct type.");
  1453. }
  1454. }
  1455. void DxilTranslateRawBuffer::ReplaceMinPrecisionRawBufferStore(Function *F,
  1456. Module &M) {
  1457. DXASSERT(F->getReturnType()->isVoidTy(), "rawBufferStore should return a void type.");
  1458. Type *ETy = F->getFunctionType()->getParamType(4); // value
  1459. Type *NewETy;
  1460. if (ETy->isHalfTy()) {
  1461. NewETy = Type::getFloatTy(M.getContext());
  1462. }
  1463. else if (ETy == Type::getInt16Ty(M.getContext())) {
  1464. NewETy = Type::getInt32Ty(M.getContext());
  1465. }
  1466. else {
  1467. return; // not a min precision type
  1468. }
  1469. Function *newFunction = M.GetDxilModule().GetOP()->GetOpFunc(
  1470. DXIL::OpCode::RawBufferStore, NewETy);
  1471. // for each function
  1472. // add argument 4-7 to its upconverted values
  1473. // replace function call
  1474. for (auto FuncUser = F->user_begin(), FuncEnd = F->user_end(); FuncUser != FuncEnd;) {
  1475. CallInst *CI = dyn_cast<CallInst>(*(FuncUser++));
  1476. DXASSERT(CI, "function user must be a call instruction.");
  1477. IRBuilder<> CIBuilder(CI);
  1478. SmallVector<Value *, 9> Args;
  1479. for (unsigned i = 0; i < 4; ++i) {
  1480. Args.emplace_back(CI->getArgOperand(i));
  1481. }
  1482. // values to store should be converted to its higher precision types
  1483. if (ETy->isHalfTy()) {
  1484. for (unsigned i = 4; i < 8; ++i) {
  1485. Value *NewV = CIBuilder.CreateFPExt(CI->getArgOperand(i),
  1486. Type::getFloatTy(M.getContext()));
  1487. Args.emplace_back(NewV);
  1488. }
  1489. }
  1490. else if (ETy == Type::getInt16Ty(M.getContext())) {
  1491. // This case only applies to typed buffer since Store operation of byte
  1492. // address buffer for min precision is handled by implicit conversion on
  1493. // intrinsic call. Since we are extending integer, we have to know if we
  1494. // should sign ext or zero ext. We can do this by iterating checking the
  1495. // size of the element at struct type and comp type at type annotation
  1496. CallInst *handleCI = dyn_cast<CallInst>(CI->getArgOperand(1));
  1497. DXASSERT(handleCI, "otherwise handle was not an argument to buffer store.");
  1498. ConstantInt *resClass = dyn_cast<ConstantInt>(handleCI->getArgOperand(1));
  1499. DXASSERT_LOCALVAR(resClass, resClass && resClass->getSExtValue() ==
  1500. (unsigned)DXIL::ResourceClass::UAV,
  1501. "otherwise buffer store called on non uav kind.");
  1502. ConstantInt *rangeID = dyn_cast<ConstantInt>(handleCI->getArgOperand(2)); // range id or idx?
  1503. DXASSERT(rangeID, "wrong createHandle call.");
  1504. DxilResource dxilRes = M.GetDxilModule().GetUAV(rangeID->getSExtValue());
  1505. StructType *STy = dyn_cast<StructType>(dxilRes.GetRetType());
  1506. DxilStructAnnotation *SAnnot = M.GetDxilModule().GetTypeSystem().GetStructAnnotation(STy);
  1507. ConstantInt *offsetInt = dyn_cast<ConstantInt>(CI->getArgOperand(3));
  1508. unsigned offset = offsetInt->getSExtValue();
  1509. unsigned currentOffset = 0;
  1510. for (DxilStructTypeIterator iter = begin(STy, SAnnot), ItEnd = end(STy, SAnnot); iter != ItEnd; ++iter) {
  1511. std::pair<Type *, DxilFieldAnnotation*> pair = *iter;
  1512. currentOffset += M.getDataLayout().getTypeAllocSize(pair.first);
  1513. if (currentOffset > offset) {
  1514. if (pair.second->GetCompType().IsUIntTy()) {
  1515. for (unsigned i = 4; i < 8; ++i) {
  1516. Value *NewV = CIBuilder.CreateZExt(CI->getArgOperand(i), Type::getInt32Ty(M.getContext()));
  1517. Args.emplace_back(NewV);
  1518. }
  1519. break;
  1520. }
  1521. else if (pair.second->GetCompType().IsIntTy()) {
  1522. for (unsigned i = 4; i < 8; ++i) {
  1523. Value *NewV = CIBuilder.CreateSExt(CI->getArgOperand(i), Type::getInt32Ty(M.getContext()));
  1524. Args.emplace_back(NewV);
  1525. }
  1526. break;
  1527. }
  1528. else {
  1529. DXASSERT(false, "Invalid comp type");
  1530. }
  1531. }
  1532. }
  1533. }
  1534. // mask
  1535. Args.emplace_back(CI->getArgOperand(8));
  1536. // alignment
  1537. Args.emplace_back(M.GetDxilModule().GetOP()->GetI32Const(
  1538. M.getDataLayout().getTypeAllocSize(NewETy)));
  1539. CIBuilder.CreateCall(newFunction, Args);
  1540. CI->eraseFromParent();
  1541. }
  1542. }
  1543. void DxilTranslateRawBuffer::ReplaceMinPrecisionRawBufferLoadByType(
  1544. Function *F, Type *FromTy, Type *ToTy, OP *Op, const DataLayout &DL) {
  1545. Function *newFunction = Op->GetOpFunc(DXIL::OpCode::RawBufferLoad, ToTy);
  1546. for (auto FUser = F->user_begin(), FEnd = F->user_end(); FUser != FEnd;) {
  1547. User *UserCI = *(FUser++);
  1548. if (CallInst *CI = dyn_cast<CallInst>(UserCI)) {
  1549. IRBuilder<> CIBuilder(CI);
  1550. SmallVector<Value *, 5> newFuncArgs;
  1551. // opcode, handle, index, elementOffset, mask
  1552. // Compiler is generating correct element offset even for min precision types
  1553. // So no need to recalculate here
  1554. for (unsigned i = 0; i < 5; ++i) {
  1555. newFuncArgs.emplace_back(CI->getArgOperand(i));
  1556. }
  1557. // new alignment for new type
  1558. newFuncArgs.emplace_back(Op->GetI32Const(DL.getTypeAllocSize(ToTy)));
  1559. CallInst *newCI = CIBuilder.CreateCall(newFunction, newFuncArgs);
  1560. for (auto CIUser = CI->user_begin(), CIEnd = CI->user_end();
  1561. CIUser != CIEnd;) {
  1562. User *UserEV = *(CIUser++);
  1563. if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(UserEV)) {
  1564. IRBuilder<> EVBuilder(EV);
  1565. ArrayRef<unsigned> Indices = EV->getIndices();
  1566. DXASSERT(Indices.size() == 1, "Otherwise we have wrong extract value.");
  1567. Value *newEV = EVBuilder.CreateExtractValue(newCI, Indices);
  1568. Value *newTruncV;
  1569. if (4 == Indices[0]) { // Don't truncate status
  1570. newTruncV = newEV;
  1571. }
  1572. else if (FromTy->isHalfTy()) {
  1573. newTruncV = EVBuilder.CreateFPTrunc(newEV, FromTy);
  1574. } else if (FromTy->isIntegerTy()) {
  1575. newTruncV = EVBuilder.CreateTrunc(newEV, FromTy);
  1576. } else {
  1577. DXASSERT(false, "unexpected type conversion");
  1578. }
  1579. EV->replaceAllUsesWith(newTruncV);
  1580. EV->eraseFromParent();
  1581. }
  1582. }
  1583. CI->eraseFromParent();
  1584. }
  1585. }
  1586. F->eraseFromParent();
  1587. }
  1588. char DxilTranslateRawBuffer::ID = 0;
  1589. ModulePass *llvm::createDxilTranslateRawBuffer() {
  1590. return new DxilTranslateRawBuffer();
  1591. }
  1592. INITIALIZE_PASS(DxilTranslateRawBuffer, "hlsl-translate-dxil-raw-buffer",
  1593. "Translate raw buffer load", false, false)