CGHLSLMSFinishCodeGen.cpp 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // CGHLSLMSFinishCodeGen.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. // Impliment FinishCodeGen. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "llvm/IR/Function.h"
  12. #include "llvm/IR/IRBuilder.h"
  13. #include "llvm/IR/Module.h"
  14. #include "llvm/IR/Type.h"
  15. #include "llvm/IR/Instructions.h"
  16. #include "llvm/IR/InstIterator.h"
  17. #include "llvm/IR/GetElementPtrTypeIterator.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/Analysis/DxilValueCache.h"
  21. #include "llvm/Transforms/Utils/ValueMapper.h"
  22. #include "llvm/Transforms/Utils/Cloning.h"
  23. #include "CodeGenModule.h"
  24. #include "clang/Frontend/CodeGenOptions.h"
  25. #include "clang/Basic/LangOptions.h"
  26. #include "clang/Parse/ParseHLSL.h" // root sig would be in Parser if part of lang
  27. #include "dxc/HLSL/HLModule.h"
  28. #include "dxc/HLSL/HLSLExtensionsCodegenHelper.h"
  29. #include "dxc/DXIL/DxilOperations.h"
  30. #include "dxc/HlslIntrinsicOp.h"
  31. #include "dxc/DXIL/DxilUtil.h"
  32. #include "dxc/HLSL/DxilExportMap.h"
  33. #include "dxc/DXIL/DxilResourceProperties.h"
  34. #include "dxc/DXIL/DxilTypeSystem.h"
  35. #include "dxc/DXIL/DxilConstants.h"
  36. #include "dxc/DxilRootSignature/DxilRootSignature.h"
  37. #include "dxc/HLSL/DxilGenerationPass.h"
  38. #include "dxc/HLSL/HLMatrixType.h"
  39. #include <vector>
  40. #include <memory>
  41. #include "CGHLSLMSHelper.h"
  42. using namespace llvm;
  43. using namespace hlsl;
  44. using namespace CGHLSLMSHelper;
  45. namespace {
  46. Value *CreateHandleFromResPtr(Value *ResPtr, HLModule &HLM,
  47. llvm::Type *HandleTy, IRBuilder<> &Builder) {
  48. Module &M = *HLM.GetModule();
  49. // Load to make sure resource only have Ld/St use so mem2reg could remove
  50. // temp resource.
  51. Value *ldObj = Builder.CreateLoad(ResPtr);
  52. Value *args[] = {ldObj};
  53. CallInst *Handle = HLM.EmitHLOperationCall(
  54. Builder, HLOpcodeGroup::HLCreateHandle, 0, HandleTy, args, M);
  55. return Handle;
  56. }
  57. Value *CreateAnnotateHandle(HLModule &HLM, Value *Handle,
  58. DxilResourceProperties &RP, llvm::Type *ResTy,
  59. IRBuilder<> &Builder) {
  60. Constant *RPConstant = resource_helper::getAsConstant(
  61. RP, HLM.GetOP()->GetResourcePropertiesType(), *HLM.GetShaderModel());
  62. return HLM.EmitHLOperationCall(
  63. Builder, HLOpcodeGroup::HLAnnotateHandle,
  64. (unsigned)HLOpcodeGroup::HLAnnotateHandle, Handle->getType(),
  65. {Handle, Builder.getInt8((uint8_t)RP.Class),
  66. Builder.getInt8((uint8_t)RP.Kind), RPConstant, UndefValue::get(ResTy)},
  67. *HLM.GetModule());
  68. }
  69. void LowerGetResourceFromHeap(
  70. HLModule &HLM, std::vector<std::pair<Function *, unsigned>> &intrinsicMap) {
  71. llvm::Module &M = *HLM.GetModule();
  72. llvm::Type *HandleTy = HLM.GetOP()->GetHandleType();
  73. unsigned GetResFromHeapOp =
  74. static_cast<unsigned>(IntrinsicOp::IOP_CreateResourceFromHeap);
  75. DenseMap<Instruction *, Instruction *> ResourcePtrToHandlePtrMap;
  76. for (auto it : intrinsicMap) {
  77. unsigned opcode = it.second;
  78. if (opcode != GetResFromHeapOp)
  79. continue;
  80. Function *F = it.first;
  81. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  82. if (group != HLOpcodeGroup::HLIntrinsic)
  83. continue;
  84. for (auto uit = F->user_begin(); uit != F->user_end();) {
  85. CallInst *CI = cast<CallInst>(*(uit++));
  86. Instruction *ResPtr = cast<Instruction>(CI->getArgOperand(0));
  87. Value *Index = CI->getArgOperand(1);
  88. IRBuilder<> Builder(CI);
  89. // Make a handle from GetResFromHeap.
  90. Value *Handle =
  91. HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLIntrinsic,
  92. GetResFromHeapOp, HandleTy, {Index}, M);
  93. // Find the handle ptr for res ptr.
  94. auto it = ResourcePtrToHandlePtrMap.find(ResPtr);
  95. Instruction *HandlePtr = nullptr;
  96. if (it != ResourcePtrToHandlePtrMap.end()) {
  97. HandlePtr = it->second;
  98. } else {
  99. IRBuilder<> AllocaBuilder(
  100. ResPtr->getParent()->getParent()->getEntryBlock().begin());
  101. HandlePtr = AllocaBuilder.CreateAlloca(HandleTy);
  102. ResourcePtrToHandlePtrMap[ResPtr] = HandlePtr;
  103. }
  104. // Store handle to handle ptr.
  105. Builder.CreateStore(Handle, HandlePtr);
  106. CI->eraseFromParent();
  107. }
  108. }
  109. // Replace load of Resource ptr into load of handel ptr.
  110. for (auto it : ResourcePtrToHandlePtrMap) {
  111. Instruction *resPtr = it.first;
  112. Instruction *handlePtr = it.second;
  113. for (auto uit = resPtr->user_begin(); uit != resPtr->user_end();) {
  114. User *U = *(uit++);
  115. BitCastInst *BCI = cast<BitCastInst>(U);
  116. DXASSERT(
  117. dxilutil::IsHLSLResourceType(BCI->getType()->getPointerElementType()),
  118. "illegal cast of resource ptr");
  119. for (auto cuit = BCI->user_begin(); cuit != BCI->user_end();) {
  120. LoadInst *LI = cast<LoadInst>(*(cuit++));
  121. IRBuilder<> Builder(LI);
  122. Value *Handle = Builder.CreateLoad(handlePtr);
  123. Value *Res =
  124. HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLCast,
  125. (unsigned)HLCastOpcode::HandleToResCast,
  126. LI->getType(), {Handle}, M);
  127. LI->replaceAllUsesWith(Res);
  128. LI->eraseFromParent();
  129. }
  130. BCI->eraseFromParent();
  131. }
  132. resPtr->eraseFromParent();
  133. }
  134. }
  135. void ReplaceBoolVectorSubscript(CallInst *CI) {
  136. Value *Ptr = CI->getArgOperand(0);
  137. Value *Idx = CI->getArgOperand(1);
  138. Value *IdxList[] = {ConstantInt::get(Idx->getType(), 0), Idx};
  139. for (auto It = CI->user_begin(), E = CI->user_end(); It != E;) {
  140. Instruction *user = cast<Instruction>(*(It++));
  141. IRBuilder<> Builder(user);
  142. Value *GEP = Builder.CreateInBoundsGEP(Ptr, IdxList);
  143. if (LoadInst *LI = dyn_cast<LoadInst>(user)) {
  144. Value *NewLd = Builder.CreateLoad(GEP);
  145. Value *cast = Builder.CreateZExt(NewLd, LI->getType());
  146. LI->replaceAllUsesWith(cast);
  147. LI->eraseFromParent();
  148. } else {
  149. // Must be a store inst here.
  150. StoreInst *SI = cast<StoreInst>(user);
  151. Value *V = SI->getValueOperand();
  152. Value *cast =
  153. Builder.CreateICmpNE(V, llvm::ConstantInt::get(V->getType(), 0));
  154. Builder.CreateStore(cast, GEP);
  155. SI->eraseFromParent();
  156. }
  157. }
  158. CI->eraseFromParent();
  159. }
  160. void ReplaceBoolVectorSubscript(Function *F) {
  161. for (auto It = F->user_begin(), E = F->user_end(); It != E;) {
  162. User *user = *(It++);
  163. CallInst *CI = cast<CallInst>(user);
  164. ReplaceBoolVectorSubscript(CI);
  165. }
  166. }
  167. // Add function body for intrinsic if possible.
  168. Function *CreateOpFunction(llvm::Module &M, Function *F,
  169. llvm::FunctionType *funcTy, HLOpcodeGroup group,
  170. unsigned opcode) {
  171. Function *opFunc = nullptr;
  172. AttributeSet attribs = F->getAttributes().getFnAttributes();
  173. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  174. if (group == HLOpcodeGroup::HLIntrinsic) {
  175. IntrinsicOp intriOp = static_cast<IntrinsicOp>(opcode);
  176. switch (intriOp) {
  177. case IntrinsicOp::MOP_Append:
  178. case IntrinsicOp::MOP_Consume: {
  179. bool bAppend = intriOp == IntrinsicOp::MOP_Append;
  180. llvm::Type *handleTy = funcTy->getParamType(HLOperandIndex::kHandleOpIdx);
  181. // Don't generate body for OutputStream::Append.
  182. if (bAppend && HLModule::IsStreamOutputPtrType(handleTy)) {
  183. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode, attribs);
  184. break;
  185. }
  186. opFunc = GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode,
  187. bAppend ? "append" : "consume");
  188. llvm::Type *counterTy = llvm::Type::getInt32Ty(M.getContext());
  189. llvm::FunctionType *IncCounterFuncTy =
  190. llvm::FunctionType::get(counterTy, {opcodeTy, handleTy}, false);
  191. unsigned counterOpcode =
  192. bAppend ? (unsigned)IntrinsicOp::MOP_IncrementCounter
  193. : (unsigned)IntrinsicOp::MOP_DecrementCounter;
  194. Function *incCounterFunc =
  195. GetOrCreateHLFunction(M, IncCounterFuncTy, group, counterOpcode, attribs);
  196. llvm::Type *idxTy = counterTy;
  197. llvm::Type *valTy =
  198. bAppend ? funcTy->getParamType(HLOperandIndex::kAppendValOpIndex)
  199. : funcTy->getReturnType();
  200. // Return type for subscript should be pointer type, hence in memory
  201. // representation
  202. llvm::Type *subscriptTy = valTy;
  203. bool isBoolScalarOrVector = false;
  204. if (!subscriptTy->isPointerTy()) {
  205. if (subscriptTy->getScalarType()->isIntegerTy(1)) {
  206. isBoolScalarOrVector = true;
  207. llvm::Type *memReprType =
  208. llvm::IntegerType::get(subscriptTy->getContext(), 32);
  209. subscriptTy =
  210. subscriptTy->isVectorTy()
  211. ? llvm::VectorType::get(memReprType,
  212. subscriptTy->getVectorNumElements())
  213. : memReprType;
  214. }
  215. subscriptTy = llvm::PointerType::get(subscriptTy, 0);
  216. }
  217. llvm::FunctionType *SubscriptFuncTy = llvm::FunctionType::get(
  218. subscriptTy, {opcodeTy, handleTy, idxTy}, false);
  219. Function *subscriptFunc =
  220. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  221. (unsigned)HLSubscriptOpcode::DefaultSubscript, attribs);
  222. BasicBlock *BB =
  223. BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  224. IRBuilder<> Builder(BB);
  225. auto argIter = opFunc->args().begin();
  226. // Skip the opcode arg.
  227. argIter++;
  228. Argument *thisArg = argIter++;
  229. // int counter = IncrementCounter/DecrementCounter(Buf);
  230. Value *incCounterOpArg = ConstantInt::get(idxTy, counterOpcode);
  231. Value *counter =
  232. Builder.CreateCall(incCounterFunc, {incCounterOpArg, thisArg});
  233. // Buf[counter];
  234. Value *subscriptOpArg = ConstantInt::get(
  235. idxTy, (unsigned)HLSubscriptOpcode::DefaultSubscript);
  236. Value *subscript =
  237. Builder.CreateCall(subscriptFunc, {subscriptOpArg, thisArg, counter});
  238. if (bAppend) {
  239. Argument *valArg = argIter;
  240. // Buf[counter] = val;
  241. if (valTy->isPointerTy()) {
  242. unsigned size = M.getDataLayout().getTypeAllocSize(
  243. subscript->getType()->getPointerElementType());
  244. Builder.CreateMemCpy(subscript, valArg, size, 1);
  245. } else {
  246. Value *storedVal = valArg;
  247. // Convert to memory representation
  248. if (isBoolScalarOrVector)
  249. storedVal = Builder.CreateZExt(
  250. storedVal, subscriptTy->getPointerElementType(), "frombool");
  251. Builder.CreateStore(storedVal, subscript);
  252. }
  253. Builder.CreateRetVoid();
  254. } else {
  255. // return Buf[counter];
  256. if (valTy->isPointerTy())
  257. Builder.CreateRet(subscript);
  258. else {
  259. Value *retVal = Builder.CreateLoad(subscript);
  260. // Convert to register representation
  261. if (isBoolScalarOrVector)
  262. retVal = Builder.CreateICmpNE(
  263. retVal, Constant::getNullValue(retVal->getType()), "tobool");
  264. Builder.CreateRet(retVal);
  265. }
  266. }
  267. } break;
  268. case IntrinsicOp::IOP_sincos: {
  269. opFunc =
  270. GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode, "sincos");
  271. llvm::Type *valTy =
  272. funcTy->getParamType(HLOperandIndex::kTrinaryOpSrc0Idx);
  273. llvm::FunctionType *sinFuncTy =
  274. llvm::FunctionType::get(valTy, {opcodeTy, valTy}, false);
  275. unsigned sinOp = static_cast<unsigned>(IntrinsicOp::IOP_sin);
  276. unsigned cosOp = static_cast<unsigned>(IntrinsicOp::IOP_cos);
  277. Function *sinFunc = GetOrCreateHLFunction(M, sinFuncTy, group, sinOp, attribs);
  278. Function *cosFunc = GetOrCreateHLFunction(M, sinFuncTy, group, cosOp, attribs);
  279. BasicBlock *BB =
  280. BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  281. IRBuilder<> Builder(BB);
  282. auto argIter = opFunc->args().begin();
  283. // Skip the opcode arg.
  284. argIter++;
  285. Argument *valArg = argIter++;
  286. Argument *sinPtrArg = argIter++;
  287. Argument *cosPtrArg = argIter++;
  288. Value *sinOpArg = ConstantInt::get(opcodeTy, sinOp);
  289. Value *sinVal = Builder.CreateCall(sinFunc, {sinOpArg, valArg});
  290. Builder.CreateStore(sinVal, sinPtrArg);
  291. Value *cosOpArg = ConstantInt::get(opcodeTy, cosOp);
  292. Value *cosVal = Builder.CreateCall(cosFunc, {cosOpArg, valArg});
  293. Builder.CreateStore(cosVal, cosPtrArg);
  294. // Ret.
  295. Builder.CreateRetVoid();
  296. } break;
  297. default:
  298. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode, attribs);
  299. break;
  300. }
  301. } else if (group == HLOpcodeGroup::HLExtIntrinsic) {
  302. llvm::StringRef fnName = F->getName();
  303. llvm::StringRef groupName = GetHLOpcodeGroupNameByAttr(F);
  304. opFunc =
  305. GetOrCreateHLFunction(M, funcTy, group, &groupName, &fnName, opcode, attribs);
  306. } else {
  307. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode, attribs);
  308. }
  309. return opFunc;
  310. }
  311. DxilResourceProperties GetResourcePropsFromIntrinsicObjectArg(
  312. Value *arg, HLModule &HLM, DxilTypeSystem &typeSys,
  313. DenseMap<Value *, DxilResourceProperties> &valToResPropertiesMap) {
  314. DxilResourceProperties RP;
  315. RP.Class = DXIL::ResourceClass::Invalid;
  316. auto RPIt = valToResPropertiesMap.find(arg);
  317. if (RPIt != valToResPropertiesMap.end()) {
  318. RP = RPIt->second;
  319. } else {
  320. // Must be GEP.
  321. GEPOperator *GEP = cast<GEPOperator>(arg);
  322. // Find RP from GEP.
  323. Value *Ptr = GEP->getPointerOperand();
  324. // When Ptr is array of resource, check if it is another GEP.
  325. while (
  326. dxilutil::IsHLSLResourceType(dxilutil::GetArrayEltTy(Ptr->getType()))) {
  327. if (GEPOperator *ParentGEP = dyn_cast<GEPOperator>(Ptr)) {
  328. GEP = ParentGEP;
  329. Ptr = GEP->getPointerOperand();
  330. } else {
  331. break;
  332. }
  333. }
  334. RPIt = valToResPropertiesMap.find(Ptr);
  335. // When ptr is array of resource, ptr could be in
  336. // valToResPropertiesMap.
  337. if (RPIt != valToResPropertiesMap.end()) {
  338. RP = RPIt->second;
  339. } else {
  340. DxilStructAnnotation *Anno = nullptr;
  341. for (auto gepIt = gep_type_begin(GEP), E = gep_type_end(GEP); gepIt != E;
  342. ++gepIt) {
  343. if (StructType *ST = dyn_cast<StructType>(*gepIt)) {
  344. Anno = typeSys.GetStructAnnotation(ST);
  345. DXASSERT(Anno, "missing type annotation");
  346. unsigned Index =
  347. cast<ConstantInt>(gepIt.getOperand())->getLimitedValue();
  348. DxilFieldAnnotation &fieldAnno = Anno->GetFieldAnnotation(Index);
  349. if (fieldAnno.HasResourceAttribute()) {
  350. MDNode *resAttrib = fieldAnno.GetResourceAttribute();
  351. DxilResourceBase R(DXIL::ResourceClass::Invalid);
  352. HLM.LoadDxilResourceBaseFromMDNode(resAttrib, R);
  353. switch (R.GetClass()) {
  354. case DXIL::ResourceClass::SRV:
  355. case DXIL::ResourceClass::UAV: {
  356. DxilResource Res;
  357. HLM.LoadDxilResourceFromMDNode(resAttrib, Res);
  358. RP = resource_helper::loadFromResourceBase(&Res);
  359. } break;
  360. case DXIL::ResourceClass::Sampler: {
  361. DxilSampler Sampler;
  362. HLM.LoadDxilSamplerFromMDNode(resAttrib, Sampler);
  363. RP = resource_helper::loadFromResourceBase(&Sampler);
  364. } break;
  365. default:
  366. DXASSERT(0, "invalid resource attribute in filed annotation");
  367. break;
  368. }
  369. break;
  370. }
  371. }
  372. }
  373. }
  374. }
  375. DXASSERT(RP.Class != DXIL::ResourceClass::Invalid,
  376. "invalid resource properties");
  377. return RP;
  378. }
  379. void AddOpcodeParamForIntrinsic(
  380. HLModule &HLM, Function *F, unsigned opcode, llvm::Type *HandleTy,
  381. DenseMap<Value *, DxilResourceProperties> &valToResPropertiesMap) {
  382. llvm::Module &M = *HLM.GetModule();
  383. llvm::FunctionType *oldFuncTy = F->getFunctionType();
  384. SmallVector<llvm::Type *, 4> paramTyList;
  385. // Add the opcode param
  386. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  387. paramTyList.emplace_back(opcodeTy);
  388. paramTyList.append(oldFuncTy->param_begin(), oldFuncTy->param_end());
  389. for (unsigned i = 1; i < paramTyList.size(); i++) {
  390. llvm::Type *Ty = paramTyList[i];
  391. if (Ty->isPointerTy()) {
  392. Ty = Ty->getPointerElementType();
  393. if (dxilutil::IsHLSLResourceType(Ty)) {
  394. // Use handle type for resource type.
  395. // This will make sure temp object variable only used by createHandle.
  396. paramTyList[i] = HandleTy;
  397. }
  398. }
  399. }
  400. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  401. if (group == HLOpcodeGroup::HLSubscript &&
  402. opcode == static_cast<unsigned>(HLSubscriptOpcode::VectorSubscript)) {
  403. llvm::FunctionType *FT = F->getFunctionType();
  404. llvm::Type *VecArgTy = FT->getParamType(0);
  405. llvm::VectorType *VType =
  406. cast<llvm::VectorType>(VecArgTy->getPointerElementType());
  407. llvm::Type *Ty = VType->getElementType();
  408. DXASSERT(Ty->isIntegerTy(), "Only bool could use VectorSubscript");
  409. llvm::IntegerType *ITy = cast<IntegerType>(Ty);
  410. DXASSERT_LOCALVAR(ITy, ITy->getBitWidth() == 1,
  411. "Only bool could use VectorSubscript");
  412. // The return type is i8*.
  413. // Replace all uses with i1*.
  414. ReplaceBoolVectorSubscript(F);
  415. return;
  416. }
  417. bool isDoubleSubscriptFunc =
  418. group == HLOpcodeGroup::HLSubscript &&
  419. opcode == static_cast<unsigned>(HLSubscriptOpcode::DoubleSubscript);
  420. llvm::Type *RetTy = oldFuncTy->getReturnType();
  421. if (isDoubleSubscriptFunc) {
  422. CallInst *doubleSub = cast<CallInst>(*F->user_begin());
  423. // Change currentIdx type into coord type.
  424. auto U = doubleSub->user_begin();
  425. Value *user = *U;
  426. CallInst *secSub = cast<CallInst>(user);
  427. unsigned coordIdx = HLOperandIndex::kSubscriptIndexOpIdx;
  428. // opcode operand not add yet, so the index need -1.
  429. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) ==
  430. HLOpcodeGroup::NotHL)
  431. coordIdx -= 1;
  432. Value *coord = secSub->getArgOperand(coordIdx);
  433. llvm::Type *coordTy = coord->getType();
  434. paramTyList[HLOperandIndex::kSubscriptIndexOpIdx] = coordTy;
  435. // Add the sampleIdx or mipLevel parameter to the end.
  436. paramTyList.emplace_back(opcodeTy);
  437. // Change return type to be resource ret type.
  438. // opcode operand not add yet, so the index need -1.
  439. Value *objPtr =
  440. doubleSub->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx - 1);
  441. // Must be a GEP
  442. GEPOperator *objGEP = cast<GEPOperator>(objPtr);
  443. gep_type_iterator GEPIt = gep_type_begin(objGEP), E = gep_type_end(objGEP);
  444. llvm::Type *resTy = nullptr;
  445. while (GEPIt != E) {
  446. if (dxilutil::IsHLSLResourceType(*GEPIt)) {
  447. resTy = *GEPIt;
  448. break;
  449. }
  450. GEPIt++;
  451. }
  452. DXASSERT(resTy, "must find the resource type");
  453. // Change object type to handle type.
  454. paramTyList[HLOperandIndex::kSubscriptObjectOpIdx] = HandleTy;
  455. // Change RetTy into pointer of resource reture type.
  456. RetTy = cast<StructType>(resTy)->getElementType(0)->getPointerTo();
  457. }
  458. llvm::FunctionType *funcTy =
  459. llvm::FunctionType::get(RetTy, paramTyList, oldFuncTy->isVarArg());
  460. Function *opFunc = CreateOpFunction(M, F, funcTy, group, opcode);
  461. StringRef lower = hlsl::GetHLLowerStrategy(F);
  462. if (!lower.empty())
  463. hlsl::SetHLLowerStrategy(opFunc, lower);
  464. DxilTypeSystem &typeSys = HLM.GetTypeSystem();
  465. for (auto user = F->user_begin(); user != F->user_end();) {
  466. // User must be a call.
  467. CallInst *oldCI = cast<CallInst>(*(user++));
  468. SmallVector<Value *, 4> opcodeParamList;
  469. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  470. opcodeParamList.emplace_back(opcodeConst);
  471. opcodeParamList.append(oldCI->arg_operands().begin(),
  472. oldCI->arg_operands().end());
  473. IRBuilder<> Builder(oldCI);
  474. if (isDoubleSubscriptFunc) {
  475. // Change obj to the resource pointer.
  476. Value *objVal = opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx];
  477. GEPOperator *objGEP = cast<GEPOperator>(objVal);
  478. SmallVector<Value *, 8> IndexList;
  479. IndexList.append(objGEP->idx_begin(), objGEP->idx_end());
  480. Value *lastIndex = IndexList.back();
  481. ConstantInt *constIndex = cast<ConstantInt>(lastIndex);
  482. DXASSERT_LOCALVAR(constIndex, constIndex->getLimitedValue() == 1,
  483. "last index must 1");
  484. // Remove the last index.
  485. IndexList.pop_back();
  486. objVal = objGEP->getPointerOperand();
  487. DxilResourceProperties RP = GetResourcePropsFromIntrinsicObjectArg(
  488. objVal, HLM, typeSys, valToResPropertiesMap);
  489. if (IndexList.size() > 1)
  490. objVal = Builder.CreateInBoundsGEP(objVal, IndexList);
  491. Value *Handle = CreateHandleFromResPtr(objVal, HLM, HandleTy, Builder);
  492. Type *ResTy = objVal->getType()->getPointerElementType();
  493. Handle = CreateAnnotateHandle(HLM, Handle, RP, ResTy, Builder);
  494. // Change obj to the resource pointer.
  495. opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  496. // Set idx and mipIdx.
  497. Value *mipIdx = opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx];
  498. auto U = oldCI->user_begin();
  499. Value *user = *U;
  500. CallInst *secSub = cast<CallInst>(user);
  501. unsigned idxOpIndex = HLOperandIndex::kSubscriptIndexOpIdx;
  502. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) ==
  503. HLOpcodeGroup::NotHL)
  504. idxOpIndex--;
  505. Value *idx = secSub->getArgOperand(idxOpIndex);
  506. DXASSERT(secSub->hasOneUse(), "subscript should only has one use");
  507. // Add the sampleIdx or mipLevel parameter to the end.
  508. opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx] = idx;
  509. opcodeParamList.emplace_back(mipIdx);
  510. // Insert new call before secSub to make sure idx is ready to use.
  511. Builder.SetInsertPoint(secSub);
  512. }
  513. for (unsigned i = 1; i < opcodeParamList.size(); i++) {
  514. Value *arg = opcodeParamList[i];
  515. llvm::Type *Ty = arg->getType();
  516. if (Ty->isPointerTy()) {
  517. Ty = Ty->getPointerElementType();
  518. if (dxilutil::IsHLSLResourceType(Ty)) {
  519. DxilResourceProperties RP = GetResourcePropsFromIntrinsicObjectArg(
  520. arg, HLM, typeSys, valToResPropertiesMap);
  521. // Use object type directly, not by pointer.
  522. // This will make sure temp object variable only used by ld/st.
  523. if (GEPOperator *argGEP = dyn_cast<GEPOperator>(arg)) {
  524. std::vector<Value *> idxList(argGEP->idx_begin(),
  525. argGEP->idx_end());
  526. // Create instruction to avoid GEPOperator.
  527. GetElementPtrInst *GEP = GetElementPtrInst::CreateInBounds(
  528. argGEP->getPointerOperand(), idxList);
  529. Builder.Insert(GEP);
  530. arg = GEP;
  531. }
  532. llvm::Type *ResTy = arg->getType()->getPointerElementType();
  533. Value *Handle = CreateHandleFromResPtr(arg, HLM, HandleTy, Builder);
  534. Handle = CreateAnnotateHandle(HLM, Handle, RP, ResTy, Builder);
  535. opcodeParamList[i] = Handle;
  536. }
  537. }
  538. }
  539. Value *CI = Builder.CreateCall(opFunc, opcodeParamList);
  540. if (!isDoubleSubscriptFunc) {
  541. // replace new call and delete the old call
  542. oldCI->replaceAllUsesWith(CI);
  543. oldCI->eraseFromParent();
  544. } else {
  545. // For double script.
  546. // Replace single users use with new CI.
  547. auto U = oldCI->user_begin();
  548. Value *user = *U;
  549. CallInst *secSub = cast<CallInst>(user);
  550. secSub->replaceAllUsesWith(CI);
  551. secSub->eraseFromParent();
  552. oldCI->eraseFromParent();
  553. }
  554. }
  555. // delete the function
  556. F->eraseFromParent();
  557. }
  558. void AddOpcodeParamForIntrinsics(
  559. HLModule &HLM, std::vector<std::pair<Function *, unsigned>> &intrinsicMap,
  560. DenseMap<Value *, DxilResourceProperties> &valToResPropertiesMap) {
  561. llvm::Type *HandleTy = HLM.GetOP()->GetHandleType();
  562. for (auto mapIter : intrinsicMap) {
  563. Function *F = mapIter.first;
  564. if (F->user_empty()) {
  565. // delete the function
  566. F->eraseFromParent();
  567. continue;
  568. }
  569. unsigned opcode = mapIter.second;
  570. AddOpcodeParamForIntrinsic(HLM, F, opcode, HandleTy, valToResPropertiesMap);
  571. }
  572. }
  573. }
  574. namespace {
  575. // Returns true a global value is being updated
  576. bool GlobalHasStoreUserRec(Value *V, std::set<Value *> &visited) {
  577. bool isWriteEnabled = false;
  578. if (V && visited.find(V) == visited.end()) {
  579. visited.insert(V);
  580. for (User *U : V->users()) {
  581. if (isa<StoreInst>(U)) {
  582. return true;
  583. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  584. Function *F = CI->getCalledFunction();
  585. if (!F->isIntrinsic()) {
  586. HLOpcodeGroup hlGroup = GetHLOpcodeGroup(F);
  587. switch (hlGroup) {
  588. case HLOpcodeGroup::NotHL:
  589. return true;
  590. case HLOpcodeGroup::HLMatLoadStore: {
  591. HLMatLoadStoreOpcode opCode =
  592. static_cast<HLMatLoadStoreOpcode>(hlsl::GetHLOpcode(CI));
  593. if (opCode == HLMatLoadStoreOpcode::ColMatStore ||
  594. opCode == HLMatLoadStoreOpcode::RowMatStore)
  595. return true;
  596. break;
  597. }
  598. case HLOpcodeGroup::HLCast:
  599. case HLOpcodeGroup::HLSubscript:
  600. if (GlobalHasStoreUserRec(U, visited))
  601. return true;
  602. break;
  603. default:
  604. break;
  605. }
  606. }
  607. } else if (isa<GEPOperator>(U) || isa<PHINode>(U) || isa<SelectInst>(U)) {
  608. if (GlobalHasStoreUserRec(U, visited))
  609. return true;
  610. }
  611. }
  612. }
  613. return isWriteEnabled;
  614. }
  615. // Returns true if any of the direct user of a global is a store inst
  616. // otherwise recurse through the remaining users and check if any GEP
  617. // exists and which in turn has a store inst as user.
  618. bool GlobalHasStoreUser(GlobalVariable *GV) {
  619. std::set<Value *> visited;
  620. Value *V = cast<Value>(GV);
  621. return GlobalHasStoreUserRec(V, visited);
  622. }
  623. GlobalVariable *CreateStaticGlobal(llvm::Module *M, GlobalVariable *GV) {
  624. Constant *GC = M->getOrInsertGlobal(GV->getName().str() + ".static.copy",
  625. GV->getType()->getPointerElementType());
  626. GlobalVariable *NGV = cast<GlobalVariable>(GC);
  627. if (GV->hasInitializer()) {
  628. NGV->setInitializer(GV->getInitializer());
  629. } else {
  630. // The copy being static, it should be initialized per llvm rules
  631. NGV->setInitializer(
  632. Constant::getNullValue(GV->getType()->getPointerElementType()));
  633. }
  634. // static global should have internal linkage
  635. NGV->setLinkage(GlobalValue::InternalLinkage);
  636. return NGV;
  637. }
  638. void CreateWriteEnabledStaticGlobals(llvm::Module *M, llvm::Function *EF) {
  639. std::vector<GlobalVariable *> worklist;
  640. for (GlobalVariable &GV : M->globals()) {
  641. if (!GV.isConstant() && GV.getLinkage() != GlobalValue::InternalLinkage &&
  642. // skip globals which are HLSL objects or group shared
  643. !dxilutil::IsHLSLObjectType(GV.getType()->getPointerElementType()) &&
  644. !dxilutil::IsSharedMemoryGlobal(&GV)) {
  645. if (GlobalHasStoreUser(&GV))
  646. worklist.emplace_back(&GV);
  647. // TODO: Ensure that constant globals aren't using initializer
  648. GV.setConstant(true);
  649. }
  650. }
  651. IRBuilder<> Builder(
  652. dxilutil::FirstNonAllocaInsertionPt(&EF->getEntryBlock()));
  653. for (GlobalVariable *GV : worklist) {
  654. GlobalVariable *NGV = CreateStaticGlobal(M, GV);
  655. GV->replaceAllUsesWith(NGV);
  656. // insert memcpy in all entryblocks
  657. uint64_t size = M->getDataLayout().getTypeAllocSize(
  658. GV->getType()->getPointerElementType());
  659. Builder.CreateMemCpy(NGV, GV, size, 1);
  660. }
  661. }
  662. } // namespace
  663. namespace {
  664. void SetEntryFunction(HLModule &HLM, Function *Entry,
  665. clang::CodeGen::CodeGenModule &CGM) {
  666. if (Entry == nullptr) {
  667. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  668. unsigned DiagID = Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
  669. "cannot find entry function %0");
  670. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLEntryFunction;
  671. return;
  672. }
  673. HLM.SetEntryFunction(Entry);
  674. }
  675. Function *CloneFunction(Function *Orig, const llvm::Twine &Name,
  676. llvm::Module *llvmModule, hlsl::DxilTypeSystem &TypeSys,
  677. hlsl::DxilTypeSystem &SrcTypeSys) {
  678. Function *F = Function::Create(Orig->getFunctionType(),
  679. GlobalValue::LinkageTypes::ExternalLinkage,
  680. Name, llvmModule);
  681. SmallVector<ReturnInst *, 2> Returns;
  682. ValueToValueMapTy vmap;
  683. // Map params.
  684. auto entryParamIt = F->arg_begin();
  685. for (Argument &param : Orig->args()) {
  686. vmap[&param] = (entryParamIt++);
  687. }
  688. llvm::CloneFunctionInto(F, Orig, vmap, /*ModuleLevelChagnes*/ false, Returns);
  689. TypeSys.CopyFunctionAnnotation(F, Orig, SrcTypeSys);
  690. return F;
  691. }
  692. // Clone shader entry function to be called by other functions.
  693. // The original function will be used as shader entry.
  694. void CloneShaderEntry(Function *ShaderF, StringRef EntryName, HLModule &HLM) {
  695. Function *F = CloneFunction(ShaderF, "", HLM.GetModule(), HLM.GetTypeSystem(),
  696. HLM.GetTypeSystem());
  697. F->takeName(ShaderF);
  698. F->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  699. // Set to name before mangled.
  700. ShaderF->setName(EntryName);
  701. DxilFunctionAnnotation *annot = HLM.GetFunctionAnnotation(F);
  702. DxilParameterAnnotation &cloneRetAnnot = annot->GetRetTypeAnnotation();
  703. // Clear semantic for cloned one.
  704. cloneRetAnnot.SetSemanticString("");
  705. cloneRetAnnot.SetSemanticIndexVec({});
  706. for (unsigned i = 0; i < annot->GetNumParameters(); i++) {
  707. DxilParameterAnnotation &cloneParamAnnot = annot->GetParameterAnnotation(i);
  708. // Clear semantic for cloned one.
  709. cloneParamAnnot.SetSemanticString("");
  710. cloneParamAnnot.SetSemanticIndexVec({});
  711. }
  712. }
  713. } // namespace
  714. namespace {
  715. bool IsPatchConstantFunction(
  716. const Function *F, StringMap<PatchConstantInfo> &patchConstantFunctionMap) {
  717. DXASSERT_NOMSG(F != nullptr);
  718. for (auto &&p : patchConstantFunctionMap) {
  719. if (p.second.Func == F)
  720. return true;
  721. }
  722. return false;
  723. }
  724. void SetPatchConstantFunctionWithAttr(
  725. const EntryFunctionInfo &EntryFunc,
  726. const clang::HLSLPatchConstantFuncAttr *PatchConstantFuncAttr,
  727. StringMap<PatchConstantInfo> &patchConstantFunctionMap,
  728. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  729. &patchConstantFunctionPropsMap,
  730. HLModule &HLM, clang::CodeGen::CodeGenModule &CGM) {
  731. StringRef funcName = PatchConstantFuncAttr->getFunctionName();
  732. auto Entry = patchConstantFunctionMap.find(funcName);
  733. if (Entry == patchConstantFunctionMap.end()) {
  734. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  735. unsigned DiagID = Diags.getCustomDiagID(
  736. clang::DiagnosticsEngine::Error, "Cannot find patchconstantfunc %0.");
  737. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID) << funcName;
  738. return;
  739. }
  740. if (Entry->second.NumOverloads != 1) {
  741. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  742. unsigned DiagID =
  743. Diags.getCustomDiagID(clang::DiagnosticsEngine::Warning,
  744. "Multiple overloads of patchconstantfunc %0.");
  745. unsigned NoteID = Diags.getCustomDiagID(clang::DiagnosticsEngine::Note,
  746. "This overload was selected.");
  747. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID) << funcName;
  748. Diags.Report(Entry->second.SL, NoteID);
  749. }
  750. Function *patchConstFunc = Entry->second.Func;
  751. DXASSERT(
  752. HLM.HasDxilFunctionProps(EntryFunc.Func),
  753. " else AddHLSLFunctionInfo did not save the dxil function props for the "
  754. "HS entry.");
  755. DxilFunctionProps *HSProps = &HLM.GetDxilFunctionProps(EntryFunc.Func);
  756. HLM.SetPatchConstantFunctionForHS(EntryFunc.Func, patchConstFunc);
  757. DXASSERT_NOMSG(patchConstantFunctionPropsMap.count(patchConstFunc));
  758. // Check no inout parameter for patch constant function.
  759. DxilFunctionAnnotation *patchConstFuncAnnotation =
  760. HLM.GetFunctionAnnotation(patchConstFunc);
  761. for (unsigned i = 0; i < patchConstFuncAnnotation->GetNumParameters(); i++) {
  762. if (patchConstFuncAnnotation->GetParameterAnnotation(i)
  763. .GetParamInputQual() == DxilParamInputQual::Inout) {
  764. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  765. unsigned DiagID = Diags.getCustomDiagID(
  766. clang::DiagnosticsEngine::Error,
  767. "Patch Constant function %0 should not have inout param.");
  768. Diags.Report(Entry->second.SL, DiagID) << funcName;
  769. }
  770. }
  771. // Input/Output control point validation.
  772. if (patchConstantFunctionPropsMap.count(patchConstFunc)) {
  773. const DxilFunctionProps &patchProps =
  774. *patchConstantFunctionPropsMap[patchConstFunc];
  775. if (patchProps.ShaderProps.HS.inputControlPoints != 0 &&
  776. patchProps.ShaderProps.HS.inputControlPoints !=
  777. HSProps->ShaderProps.HS.inputControlPoints) {
  778. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  779. unsigned DiagID =
  780. Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
  781. "Patch constant function's input patch input "
  782. "should have %0 elements, but has %1.");
  783. Diags.Report(Entry->second.SL, DiagID)
  784. << HSProps->ShaderProps.HS.inputControlPoints
  785. << patchProps.ShaderProps.HS.inputControlPoints;
  786. }
  787. if (patchProps.ShaderProps.HS.outputControlPoints != 0 &&
  788. patchProps.ShaderProps.HS.outputControlPoints !=
  789. HSProps->ShaderProps.HS.outputControlPoints) {
  790. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  791. unsigned DiagID =
  792. Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
  793. "Patch constant function's output patch input "
  794. "should have %0 elements, but has %1.");
  795. Diags.Report(Entry->second.SL, DiagID)
  796. << HSProps->ShaderProps.HS.outputControlPoints
  797. << patchProps.ShaderProps.HS.outputControlPoints;
  798. }
  799. }
  800. }
  801. void SetPatchConstantFunction(
  802. const EntryFunctionInfo &EntryFunc,
  803. std::unordered_map<Function *, const clang::HLSLPatchConstantFuncAttr *>
  804. &HSEntryPatchConstantFuncAttr,
  805. StringMap<PatchConstantInfo> &patchConstantFunctionMap,
  806. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  807. &patchConstantFunctionPropsMap,
  808. HLModule &HLM, clang::CodeGen::CodeGenModule &CGM) {
  809. auto AttrsIter = HSEntryPatchConstantFuncAttr.find(EntryFunc.Func);
  810. DXASSERT(AttrsIter != HSEntryPatchConstantFuncAttr.end(),
  811. "we have checked this in AddHLSLFunctionInfo()");
  812. SetPatchConstantFunctionWithAttr(EntryFunc, AttrsIter->second,
  813. patchConstantFunctionMap,
  814. patchConstantFunctionPropsMap, HLM, CGM);
  815. }
  816. } // namespace
  817. namespace {
  818. // For case like:
  819. // cbuffer A {
  820. // float a;
  821. // int b;
  822. //}
  823. //
  824. // const static struct {
  825. // float a;
  826. // int b;
  827. //} ST = { a, b };
  828. // Replace user of ST with a and b.
  829. bool ReplaceConstStaticGlobalUser(GEPOperator *GEP,
  830. std::vector<Constant *> &InitList,
  831. IRBuilder<> &Builder) {
  832. if (GEP->getNumIndices() < 2) {
  833. // Don't use sub element.
  834. return false;
  835. }
  836. SmallVector<Value *, 4> idxList;
  837. auto iter = GEP->idx_begin();
  838. idxList.emplace_back(*(iter++));
  839. ConstantInt *subIdx = dyn_cast<ConstantInt>(*(iter++));
  840. DXASSERT(subIdx, "else dynamic indexing on struct field");
  841. unsigned subIdxImm = subIdx->getLimitedValue();
  842. DXASSERT(subIdxImm < InitList.size(), "else struct index out of bound");
  843. Constant *subPtr = InitList[subIdxImm];
  844. // Move every idx to idxList except idx for InitList.
  845. while (iter != GEP->idx_end()) {
  846. idxList.emplace_back(*(iter++));
  847. }
  848. Value *NewGEP = Builder.CreateGEP(subPtr, idxList);
  849. GEP->replaceAllUsesWith(NewGEP);
  850. return true;
  851. }
  852. } // namespace
  853. namespace CGHLSLMSHelper {
  854. void ReplaceConstStaticGlobals(
  855. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  856. &staticConstGlobalInitListMap,
  857. std::unordered_map<GlobalVariable *, Function *>
  858. &staticConstGlobalCtorMap) {
  859. for (auto &iter : staticConstGlobalInitListMap) {
  860. GlobalVariable *GV = iter.first;
  861. std::vector<Constant *> &InitList = iter.second;
  862. LLVMContext &Ctx = GV->getContext();
  863. // Do the replace.
  864. bool bPass = true;
  865. for (User *U : GV->users()) {
  866. IRBuilder<> Builder(Ctx);
  867. if (GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
  868. Builder.SetInsertPoint(GEPInst);
  869. bPass &= ReplaceConstStaticGlobalUser(cast<GEPOperator>(GEPInst),
  870. InitList, Builder);
  871. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  872. bPass &= ReplaceConstStaticGlobalUser(GEP, InitList, Builder);
  873. } else {
  874. DXASSERT(false, "invalid user of const static global");
  875. }
  876. }
  877. // Clear the Ctor which is useless now.
  878. if (bPass) {
  879. Function *Ctor = staticConstGlobalCtorMap[GV];
  880. Ctor->getBasicBlockList().clear();
  881. BasicBlock *Entry = BasicBlock::Create(Ctx, "", Ctor);
  882. IRBuilder<> Builder(Entry);
  883. Builder.CreateRetVoid();
  884. }
  885. }
  886. }
  887. }
  888. namespace {
  889. Value *CastLdValue(Value *Ptr, llvm::Type *FromTy, llvm::Type *ToTy,
  890. IRBuilder<> &Builder) {
  891. if (ToTy->isVectorTy()) {
  892. unsigned vecSize = ToTy->getVectorNumElements();
  893. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  894. Value *V = Builder.CreateLoad(Ptr);
  895. // ScalarToVec1Splat
  896. // Change scalar into vec1.
  897. Value *Vec1 = UndefValue::get(ToTy);
  898. return Builder.CreateInsertElement(Vec1, V, (uint64_t)0);
  899. } else if (vecSize == 1 && FromTy->isIntegerTy() &&
  900. ToTy->getVectorElementType()->isIntegerTy(1)) {
  901. // load(bitcast i32* to <1 x i1>*)
  902. // Rewrite to
  903. // insertelement(icmp ne (load i32*), 0)
  904. Value *IntV = Builder.CreateLoad(Ptr);
  905. Value *BoolV = Builder.CreateICmpNE(
  906. IntV, ConstantInt::get(IntV->getType(), 0), "tobool");
  907. Value *Vec1 = UndefValue::get(ToTy);
  908. return Builder.CreateInsertElement(Vec1, BoolV, (uint64_t)0);
  909. } else if (FromTy->isVectorTy() && vecSize == 1) {
  910. Value *V = Builder.CreateLoad(Ptr);
  911. // VectorTrunc
  912. // Change vector into vec1.
  913. int mask[] = {0};
  914. return Builder.CreateShuffleVector(V, V, mask);
  915. } else if (FromTy->isArrayTy()) {
  916. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  917. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  918. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  919. // ArrayToVector.
  920. Value *NewLd = UndefValue::get(ToTy);
  921. Value *zeroIdx = Builder.getInt32(0);
  922. for (unsigned i = 0; i < vecSize; i++) {
  923. Value *GEP =
  924. Builder.CreateInBoundsGEP(Ptr, {zeroIdx, Builder.getInt32(i)});
  925. Value *Elt = Builder.CreateLoad(GEP);
  926. NewLd = Builder.CreateInsertElement(NewLd, Elt, i);
  927. }
  928. return NewLd;
  929. }
  930. }
  931. } else if (FromTy == Builder.getInt1Ty()) {
  932. Value *V = Builder.CreateLoad(Ptr);
  933. // BoolCast
  934. DXASSERT_NOMSG(ToTy->isIntegerTy());
  935. return Builder.CreateZExt(V, ToTy);
  936. }
  937. return nullptr;
  938. }
  939. Value *CastStValue(Value *Ptr, Value *V, llvm::Type *FromTy, llvm::Type *ToTy,
  940. IRBuilder<> &Builder) {
  941. if (ToTy->isVectorTy()) {
  942. unsigned vecSize = ToTy->getVectorNumElements();
  943. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  944. // ScalarToVec1Splat
  945. // Change vec1 back to scalar.
  946. Value *Elt = Builder.CreateExtractElement(V, (uint64_t)0);
  947. return Elt;
  948. } else if (FromTy->isVectorTy() && vecSize == 1) {
  949. // VectorTrunc
  950. // Change vec1 into vector.
  951. // Should not happen.
  952. // Reported error at Sema::ImpCastExprToType.
  953. DXASSERT_NOMSG(0);
  954. } else if (FromTy->isArrayTy()) {
  955. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  956. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  957. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  958. // ArrayToVector.
  959. Value *zeroIdx = Builder.getInt32(0);
  960. for (unsigned i = 0; i < vecSize; i++) {
  961. Value *Elt = Builder.CreateExtractElement(V, i);
  962. Value *GEP =
  963. Builder.CreateInBoundsGEP(Ptr, {zeroIdx, Builder.getInt32(i)});
  964. Builder.CreateStore(Elt, GEP);
  965. }
  966. // The store already done.
  967. // Return null to ignore use of the return value.
  968. return nullptr;
  969. }
  970. }
  971. } else if (FromTy == Builder.getInt1Ty()) {
  972. // BoolCast
  973. // Change i1 to ToTy.
  974. DXASSERT_NOMSG(ToTy->isIntegerTy());
  975. Value *CastV = Builder.CreateICmpNE(V, ConstantInt::get(V->getType(), 0));
  976. return CastV;
  977. }
  978. return nullptr;
  979. }
  980. bool SimplifyBitCastLoad(LoadInst *LI, llvm::Type *FromTy, llvm::Type *ToTy,
  981. Value *Ptr) {
  982. IRBuilder<> Builder(LI);
  983. // Cast FromLd to ToTy.
  984. Value *CastV = CastLdValue(Ptr, FromTy, ToTy, Builder);
  985. if (CastV) {
  986. LI->replaceAllUsesWith(CastV);
  987. return true;
  988. } else {
  989. return false;
  990. }
  991. }
  992. bool SimplifyBitCastStore(StoreInst *SI, llvm::Type *FromTy, llvm::Type *ToTy,
  993. Value *Ptr) {
  994. IRBuilder<> Builder(SI);
  995. Value *V = SI->getValueOperand();
  996. // Cast Val to FromTy.
  997. Value *CastV = CastStValue(Ptr, V, FromTy, ToTy, Builder);
  998. if (CastV) {
  999. Builder.CreateStore(CastV, Ptr);
  1000. return true;
  1001. } else {
  1002. return false;
  1003. }
  1004. }
  1005. bool SimplifyBitCastGEP(GEPOperator *GEP, llvm::Type *FromTy, llvm::Type *ToTy,
  1006. Value *Ptr) {
  1007. if (ToTy->isVectorTy()) {
  1008. unsigned vecSize = ToTy->getVectorNumElements();
  1009. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  1010. // ScalarToVec1Splat
  1011. GEP->replaceAllUsesWith(Ptr);
  1012. return true;
  1013. } else if (FromTy->isVectorTy() && vecSize == 1) {
  1014. // VectorTrunc
  1015. DXASSERT_NOMSG(
  1016. !isa<llvm::VectorType>(GEP->getType()->getPointerElementType()));
  1017. IRBuilder<> Builder(FromTy->getContext());
  1018. if (Instruction *I = dyn_cast<Instruction>(GEP))
  1019. Builder.SetInsertPoint(I);
  1020. std::vector<Value *> idxList(GEP->idx_begin(), GEP->idx_end());
  1021. Value *NewGEP = Builder.CreateInBoundsGEP(Ptr, idxList);
  1022. GEP->replaceAllUsesWith(NewGEP);
  1023. return true;
  1024. } else if (FromTy->isArrayTy()) {
  1025. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  1026. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  1027. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  1028. // ArrayToVector.
  1029. }
  1030. }
  1031. } else if (FromTy == llvm::Type::getInt1Ty(FromTy->getContext())) {
  1032. // BoolCast
  1033. }
  1034. return false;
  1035. }
  1036. typedef SmallPtrSet<Instruction *, 4> SmallInstSet;
  1037. void SimplifyBitCast(BitCastOperator *BC, SmallInstSet &deadInsts) {
  1038. Value *Ptr = BC->getOperand(0);
  1039. llvm::Type *FromTy = Ptr->getType();
  1040. llvm::Type *ToTy = BC->getType();
  1041. if (!FromTy->isPointerTy() || !ToTy->isPointerTy())
  1042. return;
  1043. FromTy = FromTy->getPointerElementType();
  1044. ToTy = ToTy->getPointerElementType();
  1045. // Take care case like %2 = bitcast %struct.T* %1 to <1 x float>*.
  1046. bool GEPCreated = false;
  1047. if (FromTy->isStructTy()) {
  1048. IRBuilder<> Builder(FromTy->getContext());
  1049. if (Instruction *I = dyn_cast<Instruction>(BC))
  1050. Builder.SetInsertPoint(I);
  1051. Value *zeroIdx = Builder.getInt32(0);
  1052. unsigned nestLevel = 1;
  1053. while (llvm::StructType *ST = dyn_cast<llvm::StructType>(FromTy)) {
  1054. if (ST->getNumElements() == 0)
  1055. break;
  1056. FromTy = ST->getElementType(0);
  1057. nestLevel++;
  1058. }
  1059. std::vector<Value *> idxList(nestLevel, zeroIdx);
  1060. Ptr = Builder.CreateGEP(Ptr, idxList);
  1061. GEPCreated = true;
  1062. }
  1063. for (User *U : BC->users()) {
  1064. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1065. if (SimplifyBitCastLoad(LI, FromTy, ToTy, Ptr)) {
  1066. LI->dropAllReferences();
  1067. deadInsts.insert(LI);
  1068. }
  1069. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  1070. if (SimplifyBitCastStore(SI, FromTy, ToTy, Ptr)) {
  1071. SI->dropAllReferences();
  1072. deadInsts.insert(SI);
  1073. }
  1074. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  1075. if (SimplifyBitCastGEP(GEP, FromTy, ToTy, Ptr))
  1076. if (Instruction *I = dyn_cast<Instruction>(GEP)) {
  1077. I->dropAllReferences();
  1078. deadInsts.insert(I);
  1079. }
  1080. } else if (dyn_cast<CallInst>(U)) {
  1081. // Skip function call.
  1082. } else if (dyn_cast<BitCastInst>(U)) {
  1083. // Skip bitcast.
  1084. } else if (dyn_cast<AddrSpaceCastInst>(U)) {
  1085. // Skip addrspacecast.
  1086. } else {
  1087. DXASSERT(0, "not support yet");
  1088. }
  1089. }
  1090. // We created a GEP instruction but didn't end up consuming it, so delete it.
  1091. if (GEPCreated && Ptr->use_empty()) {
  1092. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
  1093. GEP->eraseFromParent();
  1094. else
  1095. cast<Constant>(Ptr)->destroyConstant();
  1096. }
  1097. }
  1098. typedef float(__cdecl *FloatUnaryEvalFuncType)(float);
  1099. typedef double(__cdecl *DoubleUnaryEvalFuncType)(double);
  1100. typedef APInt(__cdecl *IntBinaryEvalFuncType)(const APInt &, const APInt &);
  1101. typedef float(__cdecl *FloatBinaryEvalFuncType)(float, float);
  1102. typedef double(__cdecl *DoubleBinaryEvalFuncType)(double, double);
  1103. Value *EvalUnaryIntrinsic(ConstantFP *fpV, FloatUnaryEvalFuncType floatEvalFunc,
  1104. DoubleUnaryEvalFuncType doubleEvalFunc) {
  1105. llvm::Type *Ty = fpV->getType();
  1106. Value *Result = nullptr;
  1107. if (Ty->isDoubleTy()) {
  1108. double dV = fpV->getValueAPF().convertToDouble();
  1109. Value *dResult = ConstantFP::get(Ty, doubleEvalFunc(dV));
  1110. Result = dResult;
  1111. } else {
  1112. DXASSERT_NOMSG(Ty->isFloatTy());
  1113. float fV = fpV->getValueAPF().convertToFloat();
  1114. Value *dResult = ConstantFP::get(Ty, floatEvalFunc(fV));
  1115. Result = dResult;
  1116. }
  1117. return Result;
  1118. }
  1119. Value *EvalBinaryIntrinsic(Constant *cV0, Constant *cV1,
  1120. FloatBinaryEvalFuncType floatEvalFunc,
  1121. DoubleBinaryEvalFuncType doubleEvalFunc,
  1122. IntBinaryEvalFuncType intEvalFunc) {
  1123. llvm::Type *Ty = cV0->getType();
  1124. Value *Result = nullptr;
  1125. if (Ty->isDoubleTy()) {
  1126. ConstantFP *fpV0 = cast<ConstantFP>(cV0);
  1127. ConstantFP *fpV1 = cast<ConstantFP>(cV1);
  1128. double dV0 = fpV0->getValueAPF().convertToDouble();
  1129. double dV1 = fpV1->getValueAPF().convertToDouble();
  1130. Value *dResult = ConstantFP::get(Ty, doubleEvalFunc(dV0, dV1));
  1131. Result = dResult;
  1132. } else if (Ty->isFloatTy()) {
  1133. ConstantFP *fpV0 = cast<ConstantFP>(cV0);
  1134. ConstantFP *fpV1 = cast<ConstantFP>(cV1);
  1135. float fV0 = fpV0->getValueAPF().convertToFloat();
  1136. float fV1 = fpV1->getValueAPF().convertToFloat();
  1137. Value *dResult = ConstantFP::get(Ty, floatEvalFunc(fV0, fV1));
  1138. Result = dResult;
  1139. } else {
  1140. DXASSERT_NOMSG(Ty->isIntegerTy());
  1141. DXASSERT_NOMSG(intEvalFunc);
  1142. ConstantInt *ciV0 = cast<ConstantInt>(cV0);
  1143. ConstantInt *ciV1 = cast<ConstantInt>(cV1);
  1144. const APInt &iV0 = ciV0->getValue();
  1145. const APInt &iV1 = ciV1->getValue();
  1146. Value *dResult = ConstantInt::get(Ty, intEvalFunc(iV0, iV1));
  1147. Result = dResult;
  1148. }
  1149. return Result;
  1150. }
  1151. Value *EvalUnaryIntrinsic(CallInst *CI, FloatUnaryEvalFuncType floatEvalFunc,
  1152. DoubleUnaryEvalFuncType doubleEvalFunc) {
  1153. Value *V = CI->getArgOperand(0);
  1154. llvm::Type *Ty = CI->getType();
  1155. Value *Result = nullptr;
  1156. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  1157. Result = UndefValue::get(Ty);
  1158. Constant *CV = cast<Constant>(V);
  1159. IRBuilder<> Builder(CI);
  1160. for (unsigned i = 0; i < VT->getNumElements(); i++) {
  1161. ConstantFP *fpV = cast<ConstantFP>(CV->getAggregateElement(i));
  1162. Value *EltResult = EvalUnaryIntrinsic(fpV, floatEvalFunc, doubleEvalFunc);
  1163. Result = Builder.CreateInsertElement(Result, EltResult, i);
  1164. }
  1165. } else {
  1166. ConstantFP *fpV = cast<ConstantFP>(V);
  1167. Result = EvalUnaryIntrinsic(fpV, floatEvalFunc, doubleEvalFunc);
  1168. }
  1169. CI->replaceAllUsesWith(Result);
  1170. CI->eraseFromParent();
  1171. return Result;
  1172. }
  1173. Value *EvalBinaryIntrinsic(CallInst *CI, FloatBinaryEvalFuncType floatEvalFunc,
  1174. DoubleBinaryEvalFuncType doubleEvalFunc,
  1175. IntBinaryEvalFuncType intEvalFunc = nullptr) {
  1176. Value *V0 = CI->getArgOperand(0);
  1177. Value *V1 = CI->getArgOperand(1);
  1178. llvm::Type *Ty = CI->getType();
  1179. Value *Result = nullptr;
  1180. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  1181. Result = UndefValue::get(Ty);
  1182. Constant *CV0 = cast<Constant>(V0);
  1183. Constant *CV1 = cast<Constant>(V1);
  1184. IRBuilder<> Builder(CI);
  1185. for (unsigned i = 0; i < VT->getNumElements(); i++) {
  1186. Constant *cV0 = cast<Constant>(CV0->getAggregateElement(i));
  1187. Constant *cV1 = cast<Constant>(CV1->getAggregateElement(i));
  1188. Value *EltResult = EvalBinaryIntrinsic(cV0, cV1, floatEvalFunc,
  1189. doubleEvalFunc, intEvalFunc);
  1190. Result = Builder.CreateInsertElement(Result, EltResult, i);
  1191. }
  1192. } else {
  1193. Constant *cV0 = cast<Constant>(V0);
  1194. Constant *cV1 = cast<Constant>(V1);
  1195. Result = EvalBinaryIntrinsic(cV0, cV1, floatEvalFunc, doubleEvalFunc,
  1196. intEvalFunc);
  1197. }
  1198. CI->replaceAllUsesWith(Result);
  1199. CI->eraseFromParent();
  1200. return Result;
  1201. CI->eraseFromParent();
  1202. return Result;
  1203. }
  1204. void SimpleTransformForHLDXIRInst(Instruction *I, SmallInstSet &deadInsts) {
  1205. unsigned opcode = I->getOpcode();
  1206. switch (opcode) {
  1207. case Instruction::BitCast: {
  1208. BitCastOperator *BCI = cast<BitCastOperator>(I);
  1209. SimplifyBitCast(BCI, deadInsts);
  1210. } break;
  1211. case Instruction::Load: {
  1212. LoadInst *ldInst = cast<LoadInst>(I);
  1213. DXASSERT(!HLMatrixType::isa(ldInst->getType()),
  1214. "matrix load should use HL LdStMatrix");
  1215. Value *Ptr = ldInst->getPointerOperand();
  1216. if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(Ptr)) {
  1217. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  1218. SimplifyBitCast(BCO, deadInsts);
  1219. }
  1220. }
  1221. } break;
  1222. case Instruction::Store: {
  1223. StoreInst *stInst = cast<StoreInst>(I);
  1224. Value *V = stInst->getValueOperand();
  1225. DXASSERT_LOCALVAR(V, !HLMatrixType::isa(V->getType()),
  1226. "matrix store should use HL LdStMatrix");
  1227. Value *Ptr = stInst->getPointerOperand();
  1228. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
  1229. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  1230. SimplifyBitCast(BCO, deadInsts);
  1231. }
  1232. }
  1233. } break;
  1234. case Instruction::LShr:
  1235. case Instruction::AShr:
  1236. case Instruction::Shl: {
  1237. llvm::BinaryOperator *BO = cast<llvm::BinaryOperator>(I);
  1238. Value *op2 = BO->getOperand(1);
  1239. IntegerType *Ty = cast<IntegerType>(BO->getType()->getScalarType());
  1240. unsigned bitWidth = Ty->getBitWidth();
  1241. // Clamp op2 to 0 ~ bitWidth-1
  1242. if (ConstantInt *cOp2 = dyn_cast<ConstantInt>(op2)) {
  1243. unsigned iOp2 = cOp2->getLimitedValue();
  1244. unsigned clampedOp2 = iOp2 & (bitWidth - 1);
  1245. if (iOp2 != clampedOp2) {
  1246. BO->setOperand(1, ConstantInt::get(op2->getType(), clampedOp2));
  1247. }
  1248. } else {
  1249. Value *mask = ConstantInt::get(op2->getType(), bitWidth - 1);
  1250. IRBuilder<> Builder(I);
  1251. op2 = Builder.CreateAnd(op2, mask);
  1252. BO->setOperand(1, op2);
  1253. }
  1254. } break;
  1255. }
  1256. }
  1257. } // namespace
  1258. namespace CGHLSLMSHelper {
  1259. Value *TryEvalIntrinsic(CallInst *CI, IntrinsicOp intriOp) {
  1260. switch (intriOp) {
  1261. case IntrinsicOp::IOP_tan: {
  1262. return EvalUnaryIntrinsic(CI, tanf, tan);
  1263. } break;
  1264. case IntrinsicOp::IOP_tanh: {
  1265. return EvalUnaryIntrinsic(CI, tanhf, tanh);
  1266. } break;
  1267. case IntrinsicOp::IOP_sin: {
  1268. return EvalUnaryIntrinsic(CI, sinf, sin);
  1269. } break;
  1270. case IntrinsicOp::IOP_sinh: {
  1271. return EvalUnaryIntrinsic(CI, sinhf, sinh);
  1272. } break;
  1273. case IntrinsicOp::IOP_cos: {
  1274. return EvalUnaryIntrinsic(CI, cosf, cos);
  1275. } break;
  1276. case IntrinsicOp::IOP_cosh: {
  1277. return EvalUnaryIntrinsic(CI, coshf, cosh);
  1278. } break;
  1279. case IntrinsicOp::IOP_asin: {
  1280. return EvalUnaryIntrinsic(CI, asinf, asin);
  1281. } break;
  1282. case IntrinsicOp::IOP_acos: {
  1283. return EvalUnaryIntrinsic(CI, acosf, acos);
  1284. } break;
  1285. case IntrinsicOp::IOP_atan: {
  1286. return EvalUnaryIntrinsic(CI, atanf, atan);
  1287. } break;
  1288. case IntrinsicOp::IOP_atan2: {
  1289. Value *V0 = CI->getArgOperand(0);
  1290. ConstantFP *fpV0 = cast<ConstantFP>(V0);
  1291. Value *V1 = CI->getArgOperand(1);
  1292. ConstantFP *fpV1 = cast<ConstantFP>(V1);
  1293. llvm::Type *Ty = CI->getType();
  1294. Value *Result = nullptr;
  1295. if (Ty->isDoubleTy()) {
  1296. double dV0 = fpV0->getValueAPF().convertToDouble();
  1297. double dV1 = fpV1->getValueAPF().convertToDouble();
  1298. Value *atanV = ConstantFP::get(CI->getType(), atan2(dV0, dV1));
  1299. CI->replaceAllUsesWith(atanV);
  1300. Result = atanV;
  1301. } else {
  1302. DXASSERT_NOMSG(Ty->isFloatTy());
  1303. float fV0 = fpV0->getValueAPF().convertToFloat();
  1304. float fV1 = fpV1->getValueAPF().convertToFloat();
  1305. Value *atanV = ConstantFP::get(CI->getType(), atan2f(fV0, fV1));
  1306. CI->replaceAllUsesWith(atanV);
  1307. Result = atanV;
  1308. }
  1309. CI->eraseFromParent();
  1310. return Result;
  1311. } break;
  1312. case IntrinsicOp::IOP_sqrt: {
  1313. return EvalUnaryIntrinsic(CI, sqrtf, sqrt);
  1314. } break;
  1315. case IntrinsicOp::IOP_rsqrt: {
  1316. auto rsqrtF = [](float v) -> float { return 1.0 / sqrtf(v); };
  1317. auto rsqrtD = [](double v) -> double { return 1.0 / sqrt(v); };
  1318. return EvalUnaryIntrinsic(CI, rsqrtF, rsqrtD);
  1319. } break;
  1320. case IntrinsicOp::IOP_exp: {
  1321. return EvalUnaryIntrinsic(CI, expf, exp);
  1322. } break;
  1323. case IntrinsicOp::IOP_exp2: {
  1324. return EvalUnaryIntrinsic(CI, exp2f, exp2);
  1325. } break;
  1326. case IntrinsicOp::IOP_log: {
  1327. return EvalUnaryIntrinsic(CI, logf, log);
  1328. } break;
  1329. case IntrinsicOp::IOP_log10: {
  1330. return EvalUnaryIntrinsic(CI, log10f, log10);
  1331. } break;
  1332. case IntrinsicOp::IOP_log2: {
  1333. return EvalUnaryIntrinsic(CI, log2f, log2);
  1334. } break;
  1335. case IntrinsicOp::IOP_pow: {
  1336. return EvalBinaryIntrinsic(CI, powf, pow);
  1337. } break;
  1338. case IntrinsicOp::IOP_max: {
  1339. auto maxF = [](float a, float b) -> float { return a > b ? a : b; };
  1340. auto maxD = [](double a, double b) -> double { return a > b ? a : b; };
  1341. auto imaxI = [](const APInt &a, const APInt &b) -> APInt {
  1342. return a.sgt(b) ? a : b;
  1343. };
  1344. return EvalBinaryIntrinsic(CI, maxF, maxD, imaxI);
  1345. } break;
  1346. case IntrinsicOp::IOP_min: {
  1347. auto minF = [](float a, float b) -> float { return a < b ? a : b; };
  1348. auto minD = [](double a, double b) -> double { return a < b ? a : b; };
  1349. auto iminI = [](const APInt &a, const APInt &b) -> APInt {
  1350. return a.slt(b) ? a : b;
  1351. };
  1352. return EvalBinaryIntrinsic(CI, minF, minD, iminI);
  1353. } break;
  1354. case IntrinsicOp::IOP_umax: {
  1355. DXASSERT_NOMSG(
  1356. CI->getArgOperand(0)->getType()->getScalarType()->isIntegerTy());
  1357. auto umaxI = [](const APInt &a, const APInt &b) -> APInt {
  1358. return a.ugt(b) ? a : b;
  1359. };
  1360. return EvalBinaryIntrinsic(CI, nullptr, nullptr, umaxI);
  1361. } break;
  1362. case IntrinsicOp::IOP_umin: {
  1363. DXASSERT_NOMSG(
  1364. CI->getArgOperand(0)->getType()->getScalarType()->isIntegerTy());
  1365. auto uminI = [](const APInt &a, const APInt &b) -> APInt {
  1366. return a.ult(b) ? a : b;
  1367. };
  1368. return EvalBinaryIntrinsic(CI, nullptr, nullptr, uminI);
  1369. } break;
  1370. case IntrinsicOp::IOP_rcp: {
  1371. auto rcpF = [](float v) -> float { return 1.0 / v; };
  1372. auto rcpD = [](double v) -> double { return 1.0 / v; };
  1373. return EvalUnaryIntrinsic(CI, rcpF, rcpD);
  1374. } break;
  1375. case IntrinsicOp::IOP_ceil: {
  1376. return EvalUnaryIntrinsic(CI, ceilf, ceil);
  1377. } break;
  1378. case IntrinsicOp::IOP_floor: {
  1379. return EvalUnaryIntrinsic(CI, floorf, floor);
  1380. } break;
  1381. case IntrinsicOp::IOP_round: {
  1382. return EvalUnaryIntrinsic(CI, roundf, round);
  1383. } break;
  1384. case IntrinsicOp::IOP_trunc: {
  1385. return EvalUnaryIntrinsic(CI, truncf, trunc);
  1386. } break;
  1387. case IntrinsicOp::IOP_frac: {
  1388. auto fracF = [](float v) -> float { return v - floor(v); };
  1389. auto fracD = [](double v) -> double { return v - floor(v); };
  1390. return EvalUnaryIntrinsic(CI, fracF, fracD);
  1391. } break;
  1392. case IntrinsicOp::IOP_isnan: {
  1393. Value *V = CI->getArgOperand(0);
  1394. ConstantFP *fV = cast<ConstantFP>(V);
  1395. bool isNan = fV->getValueAPF().isNaN();
  1396. Constant *cNan = ConstantInt::get(CI->getType(), isNan ? 1 : 0);
  1397. CI->replaceAllUsesWith(cNan);
  1398. CI->eraseFromParent();
  1399. return cNan;
  1400. } break;
  1401. default:
  1402. return nullptr;
  1403. }
  1404. }
  1405. // Do simple transform to make later lower pass easier.
  1406. void SimpleTransformForHLDXIR(llvm::Module *pM) {
  1407. SmallInstSet deadInsts;
  1408. for (Function &F : pM->functions()) {
  1409. for (BasicBlock &BB : F.getBasicBlockList()) {
  1410. for (BasicBlock::iterator Iter = BB.begin(); Iter != BB.end();) {
  1411. Instruction *I = (Iter++);
  1412. if (deadInsts.count(I))
  1413. continue; // Skip dead instructions
  1414. SimpleTransformForHLDXIRInst(I, deadInsts);
  1415. }
  1416. }
  1417. }
  1418. for (Instruction *I : deadInsts)
  1419. I->dropAllReferences();
  1420. for (Instruction *I : deadInsts)
  1421. I->eraseFromParent();
  1422. deadInsts.clear();
  1423. for (GlobalVariable &GV : pM->globals()) {
  1424. if (dxilutil::IsStaticGlobal(&GV)) {
  1425. for (User *U : GV.users()) {
  1426. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(U)) {
  1427. SimplifyBitCast(BCO, deadInsts);
  1428. }
  1429. }
  1430. }
  1431. }
  1432. for (Instruction *I : deadInsts)
  1433. I->dropAllReferences();
  1434. for (Instruction *I : deadInsts)
  1435. I->eraseFromParent();
  1436. }
  1437. } // namespace CGHLSLMSHelper
  1438. namespace {
  1439. unsigned RoundToAlign(unsigned num, unsigned mod) {
  1440. // round num to next highest mod
  1441. if (mod != 0)
  1442. return mod * ((num + mod - 1) / mod);
  1443. return num;
  1444. }
  1445. // Retrieve the last scalar or vector element type.
  1446. // This has to be recursive for the nasty empty struct case.
  1447. // returns true if found, false if we must backtrack.
  1448. bool RetrieveLastElementType(Type *Ty, Type *&EltTy) {
  1449. if (Ty->isStructTy()) {
  1450. if (Ty->getStructNumElements() == 0)
  1451. return false;
  1452. for (unsigned i = Ty->getStructNumElements(); i > 0; --i) {
  1453. if (RetrieveLastElementType(Ty->getStructElementType(i - 1), EltTy))
  1454. return true;
  1455. }
  1456. } else if (Ty->isArrayTy()) {
  1457. if (RetrieveLastElementType(Ty->getArrayElementType(), EltTy))
  1458. return true;
  1459. } else if ((Ty->isVectorTy() || Ty->isSingleValueType())) {
  1460. EltTy = Ty->getScalarType();
  1461. return true;
  1462. }
  1463. return false;
  1464. }
  1465. // Here the size is CB size.
  1466. // Offset still needs to be aligned based on type since this
  1467. // is the legacy cbuffer global path.
  1468. unsigned AlignCBufferOffset(unsigned offset, unsigned size, llvm::Type *Ty,
  1469. bool bRowMajor,
  1470. bool bMinPrecMode, bool &bCurRowIsMinPrec) {
  1471. DXASSERT(!(offset & 1), "otherwise we have an invalid offset.");
  1472. bool bNeedNewRow = Ty->isArrayTy();
  1473. // In min-precision mode, a new row is needed when
  1474. // going into or out of min-precision component type.
  1475. if (!bNeedNewRow) {
  1476. bool bMinPrec = false;
  1477. if (Ty->isStructTy()) {
  1478. if (HLMatrixType mat = HLMatrixType::dyn_cast(Ty)) {
  1479. bNeedNewRow |= !bRowMajor && mat.getNumColumns() > 1;
  1480. bNeedNewRow |= bRowMajor && mat.getNumRows() > 1;
  1481. bMinPrec = bMinPrecMode && mat.getElementType(false)->getScalarSizeInBits() < 32;
  1482. } else {
  1483. bNeedNewRow = true;
  1484. if (bMinPrecMode) {
  1485. // Need to get min-prec of last element of structure,
  1486. // in case we pack something else into the end.
  1487. Type *EltTy = nullptr;
  1488. if (RetrieveLastElementType(Ty, EltTy))
  1489. bCurRowIsMinPrec = EltTy->getScalarSizeInBits() < 32;
  1490. }
  1491. }
  1492. } else {
  1493. DXASSERT_NOMSG(Ty->isVectorTy() || Ty->isSingleValueType());
  1494. // vector or scalar
  1495. bMinPrec = bMinPrecMode && Ty->getScalarSizeInBits() < 32;
  1496. }
  1497. if (bMinPrecMode) {
  1498. bNeedNewRow |= bCurRowIsMinPrec != bMinPrec;
  1499. bCurRowIsMinPrec = bMinPrec;
  1500. }
  1501. }
  1502. unsigned scalarSizeInBytes = Ty->getScalarSizeInBits() / 8;
  1503. return AlignBufferOffsetInLegacy(offset, size, scalarSizeInBytes,
  1504. bNeedNewRow);
  1505. }
  1506. unsigned
  1507. AllocateDxilConstantBuffer(HLCBuffer &CB,
  1508. std::unordered_map<Constant *, DxilFieldAnnotation>
  1509. &constVarAnnotationMap,
  1510. bool bMinPrecMode) {
  1511. unsigned offset = 0;
  1512. // Scan user allocated constants first.
  1513. // Update offset.
  1514. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1515. if (C->GetLowerBound() == UINT_MAX)
  1516. continue;
  1517. unsigned size = C->GetRangeSize();
  1518. unsigned nextOffset = size + C->GetLowerBound();
  1519. if (offset < nextOffset)
  1520. offset = nextOffset;
  1521. }
  1522. // Alloc after user allocated constants.
  1523. bool bCurRowIsMinPrec = false;
  1524. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1525. if (C->GetLowerBound() != UINT_MAX)
  1526. continue;
  1527. unsigned size = C->GetRangeSize();
  1528. llvm::Type *Ty = C->GetGlobalSymbol()->getType()->getPointerElementType();
  1529. auto fieldAnnotation = constVarAnnotationMap.at(C->GetGlobalSymbol());
  1530. bool bRowMajor = HLMatrixType::isa(Ty)
  1531. ? fieldAnnotation.GetMatrixAnnotation().Orientation ==
  1532. MatrixOrientation::RowMajor
  1533. : false;
  1534. // Align offset.
  1535. offset = AlignCBufferOffset(offset, size, Ty, bRowMajor, bMinPrecMode, bCurRowIsMinPrec);
  1536. if (C->GetLowerBound() == UINT_MAX) {
  1537. C->SetLowerBound(offset);
  1538. }
  1539. offset += size;
  1540. }
  1541. return offset;
  1542. }
  1543. void AllocateDxilConstantBuffers(
  1544. HLModule &HLM, std::unordered_map<Constant *, DxilFieldAnnotation>
  1545. &constVarAnnotationMap) {
  1546. for (unsigned i = 0; i < HLM.GetCBuffers().size(); i++) {
  1547. HLCBuffer &CB = *static_cast<HLCBuffer *>(&(HLM.GetCBuffer(i)));
  1548. unsigned size = AllocateDxilConstantBuffer(CB, constVarAnnotationMap,
  1549. HLM.GetHLOptions().bUseMinPrecision);
  1550. CB.SetSize(size);
  1551. }
  1552. }
  1553. } // namespace
  1554. namespace {
  1555. void ReplaceUseInFunction(Value *V, Value *NewV, Function *F,
  1556. IRBuilder<> &Builder) {
  1557. for (auto U = V->user_begin(); U != V->user_end();) {
  1558. User *user = *(U++);
  1559. if (Instruction *I = dyn_cast<Instruction>(user)) {
  1560. if (I->getParent()->getParent() == F) {
  1561. // replace use with GEP if in F
  1562. for (unsigned i = 0; i < I->getNumOperands(); i++) {
  1563. if (I->getOperand(i) == V)
  1564. I->setOperand(i, NewV);
  1565. }
  1566. }
  1567. } else {
  1568. // For constant operator, create local clone which use GEP.
  1569. // Only support GEP and bitcast.
  1570. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  1571. std::vector<Value *> idxList(GEPOp->idx_begin(), GEPOp->idx_end());
  1572. Value *NewGEP = Builder.CreateInBoundsGEP(NewV, idxList);
  1573. ReplaceUseInFunction(GEPOp, NewGEP, F, Builder);
  1574. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  1575. // Change the init val into NewV with Store.
  1576. GV->setInitializer(nullptr);
  1577. Builder.CreateStore(NewV, GV);
  1578. } else {
  1579. // Must be bitcast here.
  1580. BitCastOperator *BC = cast<BitCastOperator>(user);
  1581. Value *NewBC = Builder.CreateBitCast(NewV, BC->getType());
  1582. ReplaceUseInFunction(BC, NewBC, F, Builder);
  1583. }
  1584. }
  1585. }
  1586. }
  1587. void MarkUsedFunctionForConst(Value *V,
  1588. std::unordered_set<Function *> &usedFunc) {
  1589. for (auto U = V->user_begin(); U != V->user_end();) {
  1590. User *user = *(U++);
  1591. if (Instruction *I = dyn_cast<Instruction>(user)) {
  1592. Function *F = I->getParent()->getParent();
  1593. usedFunc.insert(F);
  1594. } else {
  1595. // For constant operator, create local clone which use GEP.
  1596. // Only support GEP and bitcast.
  1597. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  1598. MarkUsedFunctionForConst(GEPOp, usedFunc);
  1599. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  1600. MarkUsedFunctionForConst(GV, usedFunc);
  1601. } else {
  1602. // Must be bitcast here.
  1603. BitCastOperator *BC = cast<BitCastOperator>(user);
  1604. MarkUsedFunctionForConst(BC, usedFunc);
  1605. }
  1606. }
  1607. }
  1608. }
  1609. bool CreateCBufferVariable(HLCBuffer &CB, HLModule &HLM, llvm::Type *HandleTy) {
  1610. bool bUsed = false;
  1611. // Build Struct for CBuffer.
  1612. SmallVector<llvm::Type *, 4> Elements;
  1613. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1614. Value *GV = C->GetGlobalSymbol();
  1615. if (GV->hasNUsesOrMore(1))
  1616. bUsed = true;
  1617. // Global variable must be pointer type.
  1618. llvm::Type *Ty = GV->getType()->getPointerElementType();
  1619. Elements.emplace_back(Ty);
  1620. }
  1621. // Don't create CBuffer variable for unused cbuffer.
  1622. if (!bUsed)
  1623. return false;
  1624. llvm::Module &M = *HLM.GetModule();
  1625. bool isCBArray = CB.GetRangeSize() != 1;
  1626. llvm::GlobalVariable *cbGV = nullptr;
  1627. llvm::Type *cbTy = nullptr;
  1628. unsigned cbIndexDepth = 0;
  1629. if (!isCBArray) {
  1630. llvm::StructType *CBStructTy =
  1631. llvm::StructType::create(Elements, CB.GetGlobalName());
  1632. cbGV = new llvm::GlobalVariable(M, CBStructTy, /*IsConstant*/ true,
  1633. llvm::GlobalValue::ExternalLinkage,
  1634. /*InitVal*/ nullptr, CB.GetGlobalName());
  1635. cbTy = cbGV->getType();
  1636. } else {
  1637. // For array of ConstantBuffer, create array of struct instead of struct of
  1638. // array.
  1639. DXASSERT(CB.GetConstants().size() == 1,
  1640. "ConstantBuffer should have 1 constant");
  1641. Value *GV = CB.GetConstants()[0]->GetGlobalSymbol();
  1642. llvm::Type *CBEltTy =
  1643. GV->getType()->getPointerElementType()->getArrayElementType();
  1644. cbIndexDepth = 1;
  1645. while (CBEltTy->isArrayTy()) {
  1646. CBEltTy = CBEltTy->getArrayElementType();
  1647. cbIndexDepth++;
  1648. }
  1649. // Add one level struct type to match normal case.
  1650. llvm::StructType *CBStructTy =
  1651. llvm::StructType::create({CBEltTy}, CB.GetGlobalName());
  1652. llvm::ArrayType *CBArrayTy =
  1653. llvm::ArrayType::get(CBStructTy, CB.GetRangeSize());
  1654. cbGV = new llvm::GlobalVariable(M, CBArrayTy, /*IsConstant*/ true,
  1655. llvm::GlobalValue::ExternalLinkage,
  1656. /*InitVal*/ nullptr, CB.GetGlobalName());
  1657. cbTy = llvm::PointerType::get(CBStructTy,
  1658. cbGV->getType()->getPointerAddressSpace());
  1659. }
  1660. CB.SetGlobalSymbol(cbGV);
  1661. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  1662. llvm::Type *idxTy = opcodeTy;
  1663. Constant *zeroIdx = ConstantInt::get(opcodeTy, 0);
  1664. Value *HandleArgs[] = {cbGV, zeroIdx};
  1665. llvm::FunctionType *SubscriptFuncTy =
  1666. llvm::FunctionType::get(cbTy, {opcodeTy, HandleTy, idxTy}, false);
  1667. Function *subscriptFunc =
  1668. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  1669. (unsigned)HLSubscriptOpcode::CBufferSubscript);
  1670. Constant *opArg =
  1671. ConstantInt::get(opcodeTy, (unsigned)HLSubscriptOpcode::CBufferSubscript);
  1672. Value *args[] = {opArg, nullptr, zeroIdx};
  1673. llvm::LLVMContext &Context = M.getContext();
  1674. llvm::Type *i32Ty = llvm::Type::getInt32Ty(Context);
  1675. Value *zero = ConstantInt::get(i32Ty, (uint64_t)0);
  1676. std::vector<Value *> indexArray(CB.GetConstants().size());
  1677. std::vector<std::unordered_set<Function *>> constUsedFuncList(
  1678. CB.GetConstants().size());
  1679. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1680. Value *idx = ConstantInt::get(i32Ty, C->GetID());
  1681. indexArray[C->GetID()] = idx;
  1682. Value *GV = C->GetGlobalSymbol();
  1683. MarkUsedFunctionForConst(GV, constUsedFuncList[C->GetID()]);
  1684. }
  1685. for (Function &F : M.functions()) {
  1686. if (F.isDeclaration())
  1687. continue;
  1688. if (GetHLOpcodeGroupByName(&F) != HLOpcodeGroup::NotHL)
  1689. continue;
  1690. IRBuilder<> Builder(F.getEntryBlock().getFirstInsertionPt());
  1691. // create HL subscript to make all the use of cbuffer start from it.
  1692. HandleArgs[HLOperandIndex::kCreateHandleResourceOpIdx-1] = cbGV;
  1693. CallInst *Handle = HLM.EmitHLOperationCall(
  1694. Builder, HLOpcodeGroup::HLCreateHandle, 0, HandleTy, HandleArgs, M);
  1695. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  1696. Instruction *cbSubscript =
  1697. cast<Instruction>(Builder.CreateCall(subscriptFunc, {args}));
  1698. // Replace constant var with GEP pGV
  1699. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1700. Value *GV = C->GetGlobalSymbol();
  1701. if (constUsedFuncList[C->GetID()].count(&F) == 0)
  1702. continue;
  1703. Value *idx = indexArray[C->GetID()];
  1704. if (!isCBArray) {
  1705. Instruction *GEP = cast<Instruction>(
  1706. Builder.CreateInBoundsGEP(cbSubscript, {zero, idx}));
  1707. // TODO: make sure the debug info is synced to GEP.
  1708. // GEP->setDebugLoc(GV);
  1709. ReplaceUseInFunction(GV, GEP, &F, Builder);
  1710. // Delete if no use in F.
  1711. if (GEP->user_empty())
  1712. GEP->eraseFromParent();
  1713. } else {
  1714. for (auto U = GV->user_begin(); U != GV->user_end();) {
  1715. User *user = *(U++);
  1716. if (user->user_empty())
  1717. continue;
  1718. Instruction *I = dyn_cast<Instruction>(user);
  1719. if (I && I->getParent()->getParent() != &F)
  1720. continue;
  1721. IRBuilder<> *instBuilder = &Builder;
  1722. std::unique_ptr<IRBuilder<>> B;
  1723. if (I) {
  1724. B = llvm::make_unique<IRBuilder<>>(I);
  1725. instBuilder = B.get();
  1726. }
  1727. GEPOperator *GEPOp = cast<GEPOperator>(user);
  1728. std::vector<Value *> idxList;
  1729. DXASSERT(GEPOp->getNumIndices() >= 1 + cbIndexDepth,
  1730. "must indexing ConstantBuffer array");
  1731. idxList.reserve(GEPOp->getNumIndices() - (cbIndexDepth - 1));
  1732. gep_type_iterator GI = gep_type_begin(*GEPOp),
  1733. E = gep_type_end(*GEPOp);
  1734. idxList.push_back(GI.getOperand());
  1735. // change array index with 0 for struct index.
  1736. idxList.push_back(zero);
  1737. GI++;
  1738. Value *arrayIdx = GI.getOperand();
  1739. GI++;
  1740. for (unsigned curIndex = 1; GI != E && curIndex < cbIndexDepth;
  1741. ++GI, ++curIndex) {
  1742. arrayIdx = instBuilder->CreateMul(
  1743. arrayIdx, Builder.getInt32(GI->getArrayNumElements()));
  1744. arrayIdx = instBuilder->CreateAdd(arrayIdx, GI.getOperand());
  1745. }
  1746. for (; GI != E; ++GI) {
  1747. idxList.push_back(GI.getOperand());
  1748. }
  1749. HandleArgs[HLOperandIndex::kCreateHandleIndexOpIdx-1] = arrayIdx;
  1750. CallInst *Handle =
  1751. HLM.EmitHLOperationCall(*instBuilder,
  1752. HLOpcodeGroup::HLCreateHandle, 0,
  1753. HandleTy, HandleArgs, M);
  1754. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  1755. args[HLOperandIndex::kSubscriptIndexOpIdx] = arrayIdx;
  1756. Instruction *cbSubscript =
  1757. cast<Instruction>(instBuilder->CreateCall(subscriptFunc, {args}));
  1758. Instruction *NewGEP = cast<Instruction>(
  1759. instBuilder->CreateInBoundsGEP(cbSubscript, idxList));
  1760. ReplaceUseInFunction(GEPOp, NewGEP, &F, *instBuilder);
  1761. }
  1762. }
  1763. }
  1764. // Delete if no use in F.
  1765. if (cbSubscript->user_empty()) {
  1766. cbSubscript->eraseFromParent();
  1767. Handle->eraseFromParent();
  1768. } else {
  1769. // merge GEP use for cbSubscript.
  1770. HLModule::MergeGepUse(cbSubscript);
  1771. }
  1772. }
  1773. return true;
  1774. }
  1775. void ConstructCBufferAnnotation(
  1776. HLCBuffer &CB, DxilTypeSystem &dxilTypeSys,
  1777. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  1778. Value *GV = CB.GetGlobalSymbol();
  1779. llvm::StructType *CBStructTy =
  1780. dyn_cast<llvm::StructType>(GV->getType()->getPointerElementType());
  1781. if (!CBStructTy) {
  1782. // For Array of ConstantBuffer.
  1783. llvm::ArrayType *CBArrayTy =
  1784. cast<llvm::ArrayType>(GV->getType()->getPointerElementType());
  1785. CBStructTy = cast<llvm::StructType>(CBArrayTy->getArrayElementType());
  1786. }
  1787. DxilStructAnnotation *CBAnnotation =
  1788. dxilTypeSys.AddStructAnnotation(CBStructTy);
  1789. CBAnnotation->SetCBufferSize(CB.GetSize());
  1790. // Set fieldAnnotation for each constant var.
  1791. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1792. Constant *GV = C->GetGlobalSymbol();
  1793. DxilFieldAnnotation &fieldAnnotation =
  1794. CBAnnotation->GetFieldAnnotation(C->GetID());
  1795. fieldAnnotation = AnnotationMap[GV];
  1796. // This is after CBuffer allocation.
  1797. fieldAnnotation.SetCBufferOffset(C->GetLowerBound());
  1798. fieldAnnotation.SetFieldName(C->GetGlobalName());
  1799. }
  1800. }
  1801. void ConstructCBuffer(
  1802. HLModule &HLM, llvm::Type *CBufferType,
  1803. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  1804. DxilTypeSystem &dxilTypeSys = HLM.GetTypeSystem();
  1805. llvm::Type *HandleTy = HLM.GetOP()->GetHandleType();
  1806. for (unsigned i = 0; i < HLM.GetCBuffers().size(); i++) {
  1807. HLCBuffer &CB = *static_cast<HLCBuffer *>(&(HLM.GetCBuffer(i)));
  1808. if (CB.GetConstants().size() == 0) {
  1809. // Create Fake variable for cbuffer which is empty.
  1810. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  1811. *HLM.GetModule(), CBufferType, true,
  1812. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  1813. CB.SetGlobalSymbol(pGV);
  1814. } else {
  1815. bool bCreated = CreateCBufferVariable(CB, HLM, HandleTy);
  1816. if (bCreated)
  1817. ConstructCBufferAnnotation(CB, dxilTypeSys, AnnotationMap);
  1818. else {
  1819. // Create Fake variable for cbuffer which is unused.
  1820. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  1821. *HLM.GetModule(), CBufferType, true,
  1822. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  1823. CB.SetGlobalSymbol(pGV);
  1824. }
  1825. }
  1826. // Clear the constants which useless now.
  1827. CB.GetConstants().clear();
  1828. }
  1829. }
  1830. }
  1831. namespace CGHLSLMSHelper {
  1832. // Align cbuffer offset in legacy mode (16 bytes per row).
  1833. unsigned AlignBufferOffsetInLegacy(unsigned offset, unsigned size,
  1834. unsigned scalarSizeInBytes,
  1835. bool bNeedNewRow) {
  1836. if (unsigned remainder = (offset & 0xf)) {
  1837. // Start from new row
  1838. if (remainder + size > 16 || bNeedNewRow) {
  1839. return offset + 16 - remainder;
  1840. }
  1841. // If not, naturally align data
  1842. return RoundToAlign(offset, scalarSizeInBytes);
  1843. }
  1844. return offset;
  1845. }
  1846. // Translate RayQuery constructor. From:
  1847. // %call = call %"RayQuery<flags>" @<constructor>(%"RayQuery<flags>" %ptr)
  1848. // To:
  1849. // i32 %handle = AllocateRayQuery(i32 <IntrinsicOp::IOP_AllocateRayQuery>, i32
  1850. // %flags) %gep = GEP %"RayQuery<flags>" %ptr, 0, 0 store i32* %gep, i32
  1851. // %handle ; and replace uses of %call with %ptr
  1852. void TranslateRayQueryConstructor(HLModule &HLM) {
  1853. llvm::Module &M = *HLM.GetModule();
  1854. SmallVector<Function *, 4> Constructors;
  1855. for (auto &F : M.functions()) {
  1856. // Match templated RayQuery constructor instantiation by prefix and
  1857. // signature. It should be impossible to achieve the same signature from
  1858. // HLSL.
  1859. if (!F.getName().startswith("\01??0?$RayQuery@$"))
  1860. continue;
  1861. llvm::Type *Ty = F.getReturnType();
  1862. if (!Ty->isPointerTy() ||
  1863. !dxilutil::IsHLSLRayQueryType(Ty->getPointerElementType()))
  1864. continue;
  1865. if (F.arg_size() != 1 || Ty != F.arg_begin()->getType())
  1866. continue;
  1867. Constructors.emplace_back(&F);
  1868. }
  1869. for (auto pConstructorFunc : Constructors) {
  1870. llvm::IntegerType *i32Ty = llvm::Type::getInt32Ty(M.getContext());
  1871. llvm::ConstantInt *i32Zero =
  1872. llvm::ConstantInt::get(i32Ty, (uint64_t)0, false);
  1873. llvm::FunctionType *funcTy =
  1874. llvm::FunctionType::get(i32Ty, {i32Ty, i32Ty}, false);
  1875. unsigned opcode = (unsigned)IntrinsicOp::IOP_AllocateRayQuery;
  1876. llvm::ConstantInt *opVal = llvm::ConstantInt::get(i32Ty, opcode, false);
  1877. Function *opFunc =
  1878. GetOrCreateHLFunction(M, funcTy, HLOpcodeGroup::HLIntrinsic, opcode);
  1879. while (!pConstructorFunc->user_empty()) {
  1880. Value *V = *pConstructorFunc->user_begin();
  1881. llvm::CallInst *CI = cast<CallInst>(V); // Must be call
  1882. llvm::Value *pThis = CI->getArgOperand(0);
  1883. llvm::StructType *pRQType =
  1884. cast<llvm::StructType>(pThis->getType()->getPointerElementType());
  1885. DxilStructAnnotation *SA =
  1886. HLM.GetTypeSystem().GetStructAnnotation(pRQType);
  1887. DXASSERT(SA, "otherwise, could not find type annoation for RayQuery "
  1888. "specialization");
  1889. DXASSERT(SA->GetNumTemplateArgs() == 1 &&
  1890. SA->GetTemplateArgAnnotation(0).IsIntegral(),
  1891. "otherwise, RayQuery has changed, or lacks template args");
  1892. llvm::IRBuilder<> Builder(CI);
  1893. llvm::Value *rayFlags =
  1894. Builder.getInt32(SA->GetTemplateArgAnnotation(0).GetIntegral());
  1895. llvm::Value *Call =
  1896. Builder.CreateCall(opFunc, {opVal, rayFlags}, pThis->getName());
  1897. llvm::Value *GEP = Builder.CreateInBoundsGEP(pThis, {i32Zero, i32Zero});
  1898. Builder.CreateStore(Call, GEP);
  1899. CI->replaceAllUsesWith(pThis);
  1900. CI->eraseFromParent();
  1901. }
  1902. pConstructorFunc->eraseFromParent();
  1903. }
  1904. }
  1905. }
  1906. namespace {
  1907. bool BuildImmInit(Function *Ctor) {
  1908. GlobalVariable *GV = nullptr;
  1909. SmallVector<Constant *, 4> ImmList;
  1910. bool allConst = true;
  1911. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E; ++I) {
  1912. if (StoreInst *SI = dyn_cast<StoreInst>(&(*I))) {
  1913. Value *V = SI->getValueOperand();
  1914. if (!isa<Constant>(V) || V->getType()->isPointerTy()) {
  1915. allConst = false;
  1916. break;
  1917. }
  1918. ImmList.emplace_back(cast<Constant>(V));
  1919. Value *Ptr = SI->getPointerOperand();
  1920. if (GEPOperator *GepOp = dyn_cast<GEPOperator>(Ptr)) {
  1921. Ptr = GepOp->getPointerOperand();
  1922. if (GlobalVariable *pGV = dyn_cast<GlobalVariable>(Ptr)) {
  1923. if (GV == nullptr)
  1924. GV = pGV;
  1925. else {
  1926. DXASSERT(GV == pGV, "else pointer mismatch");
  1927. }
  1928. }
  1929. }
  1930. } else {
  1931. if (!isa<ReturnInst>(*I)) {
  1932. allConst = false;
  1933. break;
  1934. }
  1935. }
  1936. }
  1937. if (!allConst)
  1938. return false;
  1939. if (!GV)
  1940. return false;
  1941. llvm::Type *Ty = GV->getType()->getElementType();
  1942. llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty);
  1943. // TODO: support other types.
  1944. if (!AT)
  1945. return false;
  1946. if (ImmList.size() != AT->getNumElements())
  1947. return false;
  1948. Constant *Init = llvm::ConstantArray::get(AT, ImmList);
  1949. GV->setInitializer(Init);
  1950. return true;
  1951. }
  1952. } // namespace
  1953. namespace CGHLSLMSHelper {
  1954. void ProcessCtorFunctions(llvm::Module &M, StringRef globalName,
  1955. Instruction *InsertPt) {
  1956. // add global call to entry func
  1957. GlobalVariable *GV = M.getGlobalVariable(globalName);
  1958. if (!GV)
  1959. return;
  1960. ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
  1961. if (!CA)
  1962. return;
  1963. IRBuilder<> Builder(InsertPt);
  1964. for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
  1965. if (isa<ConstantAggregateZero>(*i))
  1966. continue;
  1967. ConstantStruct *CS = cast<ConstantStruct>(*i);
  1968. if (isa<ConstantPointerNull>(CS->getOperand(1)))
  1969. continue;
  1970. // Must have a function or null ptr.
  1971. if (!isa<Function>(CS->getOperand(1)))
  1972. continue;
  1973. Function *Ctor = cast<Function>(CS->getOperand(1));
  1974. DXASSERT(Ctor->getReturnType()->isVoidTy() && Ctor->arg_size() == 0,
  1975. "function type must be void (void)");
  1976. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E; ++I) {
  1977. if (CallInst *CI = dyn_cast<CallInst>(&(*I))) {
  1978. Function *F = CI->getCalledFunction();
  1979. // Try to build imm initilizer.
  1980. // If not work, add global call to entry func.
  1981. if (BuildImmInit(F) == false) {
  1982. Builder.CreateCall(F);
  1983. }
  1984. } else {
  1985. DXASSERT(isa<ReturnInst>(&(*I)),
  1986. "else invalid Global constructor function");
  1987. }
  1988. }
  1989. }
  1990. // remove the GV
  1991. GV->eraseFromParent();
  1992. }
  1993. void FinishCBuffer(HLModule &HLM, llvm::Type *CBufferType,
  1994. std::unordered_map<Constant *, DxilFieldAnnotation>
  1995. &constVarAnnotationMap) {
  1996. // Allocate constant buffers.
  1997. AllocateDxilConstantBuffers(HLM, constVarAnnotationMap);
  1998. // TODO: create temp variable for constant which has store use.
  1999. // Create Global variable and type annotation for each CBuffer.
  2000. ConstructCBuffer(HLM, CBufferType, constVarAnnotationMap);
  2001. }
  2002. void AddRegBindingsForResourceInConstantBuffer(
  2003. HLModule &HLM,
  2004. llvm::DenseMap<llvm::Constant *,
  2005. llvm::SmallVector<std::pair<DXIL::ResourceClass, unsigned>,
  2006. 1>> &constantRegBindingMap) {
  2007. for (unsigned i = 0; i < HLM.GetCBuffers().size(); i++) {
  2008. HLCBuffer &CB = *static_cast<HLCBuffer *>(&(HLM.GetCBuffer(i)));
  2009. auto &Constants = CB.GetConstants();
  2010. for (unsigned j = 0; j < Constants.size(); j++) {
  2011. const std::unique_ptr<DxilResourceBase> &C = Constants[j];
  2012. Constant *CGV = C->GetGlobalSymbol();
  2013. auto &regBindings = constantRegBindingMap[CGV];
  2014. if (regBindings.empty())
  2015. continue;
  2016. unsigned Srv = UINT_MAX;
  2017. unsigned Uav = UINT_MAX;
  2018. unsigned Sampler = UINT_MAX;
  2019. for (auto it : regBindings) {
  2020. unsigned RegNum = it.second;
  2021. switch (it.first) {
  2022. case DXIL::ResourceClass::SRV:
  2023. Srv = RegNum;
  2024. break;
  2025. case DXIL::ResourceClass::UAV:
  2026. Uav = RegNum;
  2027. break;
  2028. case DXIL::ResourceClass::Sampler:
  2029. Sampler = RegNum;
  2030. break;
  2031. default:
  2032. DXASSERT(0, "invalid resource class");
  2033. break;
  2034. }
  2035. }
  2036. HLM.AddRegBinding(CB.GetID(), j, Srv, Uav, Sampler);
  2037. }
  2038. }
  2039. }
  2040. // extension codegen.
  2041. void ExtensionCodeGen(HLModule &HLM, clang::CodeGen::CodeGenModule &CGM) {
  2042. // Add semantic defines for extensions if any are available.
  2043. HLSLExtensionsCodegenHelper::SemanticDefineErrorList errors =
  2044. CGM.getCodeGenOpts().HLSLExtensionsCodegen->WriteSemanticDefines(
  2045. HLM.GetModule());
  2046. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  2047. for (const HLSLExtensionsCodegenHelper::SemanticDefineError &error : errors) {
  2048. clang::DiagnosticsEngine::Level level = clang::DiagnosticsEngine::Error;
  2049. if (error.IsWarning())
  2050. level = clang::DiagnosticsEngine::Warning;
  2051. unsigned DiagID = Diags.getCustomDiagID(level, "%0");
  2052. Diags.Report(clang::SourceLocation::getFromRawEncoding(error.Location()),
  2053. DiagID)
  2054. << error.Message();
  2055. }
  2056. // Add root signature from a #define. Overrides root signature in function
  2057. // attribute.
  2058. {
  2059. using Status = HLSLExtensionsCodegenHelper::CustomRootSignature::Status;
  2060. HLSLExtensionsCodegenHelper::CustomRootSignature customRootSig;
  2061. HLSLExtensionsCodegenHelper::CustomRootSignature::Status status =
  2062. CGM.getCodeGenOpts().HLSLExtensionsCodegen->GetCustomRootSignature(
  2063. &customRootSig);
  2064. if (status == Status::FOUND) {
  2065. DxilRootSignatureVersion rootSigVer;
  2066. // set root signature version.
  2067. if (CGM.getLangOpts().RootSigMinor == 0) {
  2068. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_0;
  2069. } else {
  2070. DXASSERT(CGM.getLangOpts().RootSigMinor == 1,
  2071. "else CGMSHLSLRuntime Constructor needs to be updated");
  2072. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_1;
  2073. }
  2074. RootSignatureHandle RootSigHandle;
  2075. CompileRootSignature(
  2076. customRootSig.RootSignature, Diags,
  2077. clang::SourceLocation::getFromRawEncoding(
  2078. customRootSig.EncodedSourceLocation),
  2079. rootSigVer, DxilRootSignatureCompilationFlags::GlobalRootSignature,
  2080. &RootSigHandle);
  2081. if (!RootSigHandle.IsEmpty()) {
  2082. RootSigHandle.EnsureSerializedAvailable();
  2083. HLM.SetSerializedRootSignature(RootSigHandle.GetSerializedBytes(),
  2084. RootSigHandle.GetSerializedSize());
  2085. }
  2086. }
  2087. }
  2088. }
  2089. } // namespace CGHLSLMSHelper
  2090. namespace {
  2091. void ReportDisallowedTypeInExportParam(clang::CodeGen ::CodeGenModule &CGM,
  2092. StringRef name) {
  2093. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  2094. unsigned DiagID =
  2095. Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
  2096. "Exported function %0 must not contain a "
  2097. "resource in parameter or return type.");
  2098. std::string escaped;
  2099. llvm::raw_string_ostream os(escaped);
  2100. dxilutil::PrintEscapedString(name, os);
  2101. Diags.Report(DiagID) << os.str();
  2102. }
  2103. } // namespace
  2104. namespace CGHLSLMSHelper {
  2105. void FinishClipPlane(HLModule &HLM, std::vector<Function *> &clipPlaneFuncList,
  2106. std::unordered_map<Value *, DebugLoc> &debugInfoMap,
  2107. clang::CodeGen::CodeGenModule &CGM) {
  2108. bool bDebugInfo = CGM.getCodeGenOpts().getDebugInfo() ==
  2109. clang::CodeGenOptions::FullDebugInfo;
  2110. Module &M = *HLM.GetModule();
  2111. for (Function *F : clipPlaneFuncList) {
  2112. DxilFunctionProps &props = HLM.GetDxilFunctionProps(F);
  2113. IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
  2114. for (unsigned i = 0; i < DXIL::kNumClipPlanes; i++) {
  2115. Value *clipPlane = props.ShaderProps.VS.clipPlanes[i];
  2116. if (!clipPlane)
  2117. continue;
  2118. if (bDebugInfo) {
  2119. Builder.SetCurrentDebugLocation(debugInfoMap[clipPlane]);
  2120. }
  2121. llvm::Type *Ty = clipPlane->getType()->getPointerElementType();
  2122. // Constant *zeroInit = ConstantFP::get(Ty, 0);
  2123. GlobalVariable *GV = new llvm::GlobalVariable(
  2124. M, Ty, /*IsConstant*/ false, // constant false to store.
  2125. llvm::GlobalValue::ExternalLinkage,
  2126. /*InitVal*/ nullptr, Twine("SV_ClipPlane") + Twine(i));
  2127. Value *initVal = Builder.CreateLoad(clipPlane);
  2128. Builder.CreateStore(initVal, GV);
  2129. props.ShaderProps.VS.clipPlanes[i] = GV;
  2130. }
  2131. }
  2132. }
  2133. } // namespace
  2134. namespace {
  2135. void LowerExportFunctions(HLModule &HLM, clang::CodeGen::CodeGenModule &CGM,
  2136. dxilutil::ExportMap &exportMap,
  2137. StringMap<EntryFunctionInfo> &entryFunctionMap) {
  2138. bool bIsLib = HLM.GetShaderModel()->IsLib();
  2139. Module &M = *HLM.GetModule();
  2140. if (bIsLib && !exportMap.empty()) {
  2141. for (auto &it : entryFunctionMap) {
  2142. if (HLM.HasDxilFunctionProps(it.second.Func)) {
  2143. const DxilFunctionProps &props =
  2144. HLM.GetDxilFunctionProps(it.second.Func);
  2145. if (props.IsHS())
  2146. exportMap.RegisterExportedFunction(
  2147. props.ShaderProps.HS.patchConstantFunc);
  2148. }
  2149. }
  2150. }
  2151. if (bIsLib && !exportMap.empty()) {
  2152. exportMap.BeginProcessing();
  2153. for (Function &f : M.functions()) {
  2154. if (f.isDeclaration() || f.isIntrinsic() ||
  2155. GetHLOpcodeGroup(&f) != HLOpcodeGroup::NotHL)
  2156. continue;
  2157. exportMap.ProcessFunction(&f, true);
  2158. }
  2159. // TODO: add subobject export names here.
  2160. if (!exportMap.EndProcessing()) {
  2161. for (auto &name : exportMap.GetNameCollisions()) {
  2162. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  2163. unsigned DiagID = Diags.getCustomDiagID(
  2164. clang::DiagnosticsEngine::Error,
  2165. "Export name collides with another export: %0");
  2166. std::string escaped;
  2167. llvm::raw_string_ostream os(escaped);
  2168. dxilutil::PrintEscapedString(name, os);
  2169. Diags.Report(DiagID) << os.str();
  2170. }
  2171. for (auto &name : exportMap.GetUnusedExports()) {
  2172. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  2173. unsigned DiagID =
  2174. Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
  2175. "Could not find target for export: %0");
  2176. std::string escaped;
  2177. llvm::raw_string_ostream os(escaped);
  2178. dxilutil::PrintEscapedString(name, os);
  2179. Diags.Report(DiagID) << os.str();
  2180. }
  2181. }
  2182. }
  2183. for (auto &it : exportMap.GetFunctionRenames()) {
  2184. Function *F = it.first;
  2185. auto &renames = it.second;
  2186. if (renames.empty())
  2187. continue;
  2188. // Rename the original, if necessary, then clone the rest
  2189. if (renames.find(F->getName()) == renames.end())
  2190. F->setName(*renames.begin());
  2191. for (auto &itName : renames) {
  2192. if (F->getName() != itName) {
  2193. Function *pClone = CloneFunction(F, itName, &M, HLM.GetTypeSystem(),
  2194. HLM.GetTypeSystem());
  2195. // add DxilFunctionProps if entry
  2196. if (HLM.HasDxilFunctionProps(F)) {
  2197. DxilFunctionProps &props = HLM.GetDxilFunctionProps(F);
  2198. auto newProps = llvm::make_unique<DxilFunctionProps>(props);
  2199. HLM.AddDxilFunctionProps(pClone, newProps);
  2200. }
  2201. }
  2202. }
  2203. }
  2204. }
  2205. void CheckResourceParameters(HLModule &HLM,
  2206. clang::CodeGen::CodeGenModule &CGM) {
  2207. Module &M = *HLM.GetModule();
  2208. for (Function &f : M.functions()) {
  2209. // Skip llvm intrinsics, non-external linkage, entry/patch constant func,
  2210. // and HL intrinsics
  2211. if (!f.isIntrinsic() &&
  2212. f.getLinkage() == GlobalValue::LinkageTypes::ExternalLinkage &&
  2213. !HLM.HasDxilFunctionProps(&f) && !HLM.IsPatchConstantShader(&f) &&
  2214. GetHLOpcodeGroup(&f) == HLOpcodeGroup::NotHL) {
  2215. // Verify no resources in param/return types
  2216. if (dxilutil::ContainsHLSLObjectType(f.getReturnType())) {
  2217. ReportDisallowedTypeInExportParam(CGM, f.getName());
  2218. continue;
  2219. }
  2220. for (auto &Arg : f.args()) {
  2221. if (dxilutil::ContainsHLSLObjectType(Arg.getType())) {
  2222. ReportDisallowedTypeInExportParam(CGM, f.getName());
  2223. break;
  2224. }
  2225. }
  2226. }
  2227. }
  2228. }
  2229. } // namespace
  2230. namespace CGHLSLMSHelper {
  2231. void UpdateLinkage(HLModule &HLM, clang::CodeGen::CodeGenModule &CGM,
  2232. dxilutil::ExportMap &exportMap,
  2233. StringMap<EntryFunctionInfo> &entryFunctionMap,
  2234. StringMap<PatchConstantInfo> &patchConstantFunctionMap) {
  2235. bool bIsLib = HLM.GetShaderModel()->IsLib();
  2236. Module &M = *HLM.GetModule();
  2237. // Pin entry point and constant buffers, mark everything else internal.
  2238. for (Function &f : M.functions()) {
  2239. if (!bIsLib) {
  2240. if (&f == HLM.GetEntryFunction() ||
  2241. IsPatchConstantFunction(&f, patchConstantFunctionMap) ||
  2242. f.isDeclaration()) {
  2243. if (f.isDeclaration() && !f.isIntrinsic() &&
  2244. GetHLOpcodeGroup(&f) == HLOpcodeGroup::NotHL) {
  2245. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  2246. unsigned DiagID = Diags.getCustomDiagID(
  2247. clang::DiagnosticsEngine::Error,
  2248. "External function used in non-library profile: %0");
  2249. std::string escaped;
  2250. llvm::raw_string_ostream os(escaped);
  2251. dxilutil::PrintEscapedString(f.getName(), os);
  2252. Diags.Report(DiagID) << os.str();
  2253. return;
  2254. }
  2255. f.setLinkage(GlobalValue::LinkageTypes::ExternalLinkage);
  2256. } else {
  2257. f.setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  2258. }
  2259. }
  2260. // Skip no inline functions.
  2261. if (f.hasFnAttribute(llvm::Attribute::NoInline))
  2262. continue;
  2263. // Always inline for used functions.
  2264. if (!f.user_empty() && !f.isDeclaration())
  2265. f.addFnAttr(llvm::Attribute::AlwaysInline);
  2266. }
  2267. LowerExportFunctions(HLM, CGM, exportMap, entryFunctionMap);
  2268. if (CGM.getCodeGenOpts().ExportShadersOnly) {
  2269. for (Function &f : M.functions()) {
  2270. // Skip declarations, intrinsics, shaders, and non-external linkage
  2271. if (f.isDeclaration() || f.isIntrinsic() ||
  2272. GetHLOpcodeGroup(&f) != HLOpcodeGroup::NotHL ||
  2273. HLM.HasDxilFunctionProps(&f) || HLM.IsPatchConstantShader(&f) ||
  2274. f.getLinkage() != GlobalValue::LinkageTypes::ExternalLinkage)
  2275. continue;
  2276. // Mark non-shader user functions as InternalLinkage
  2277. f.setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  2278. }
  2279. }
  2280. // Now iterate hull shaders and make sure their corresponding patch constant
  2281. // functions are marked ExternalLinkage:
  2282. for (Function &f : M.functions()) {
  2283. if (f.isDeclaration() || f.isIntrinsic() ||
  2284. GetHLOpcodeGroup(&f) != HLOpcodeGroup::NotHL ||
  2285. f.getLinkage() != GlobalValue::LinkageTypes::ExternalLinkage ||
  2286. !HLM.HasDxilFunctionProps(&f))
  2287. continue;
  2288. DxilFunctionProps &props = HLM.GetDxilFunctionProps(&f);
  2289. if (!props.IsHS())
  2290. continue;
  2291. Function *PCFunc = props.ShaderProps.HS.patchConstantFunc;
  2292. if (PCFunc->getLinkage() != GlobalValue::LinkageTypes::ExternalLinkage)
  2293. PCFunc->setLinkage(GlobalValue::LinkageTypes::ExternalLinkage);
  2294. }
  2295. // Disallow resource arguments in (non-entry) function exports
  2296. // unless offline linking target.
  2297. if (bIsLib &&
  2298. HLM.GetShaderModel()->GetMinor() != ShaderModel::kOfflineMinor) {
  2299. CheckResourceParameters(HLM, CGM);
  2300. }
  2301. }
  2302. void FinishEntries(
  2303. HLModule &HLM, const EntryFunctionInfo &Entry,
  2304. clang::CodeGen::CodeGenModule &CGM,
  2305. StringMap<EntryFunctionInfo> &entryFunctionMap,
  2306. std::unordered_map<Function *, const clang::HLSLPatchConstantFuncAttr *>
  2307. &HSEntryPatchConstantFuncAttr,
  2308. StringMap<PatchConstantInfo> &patchConstantFunctionMap,
  2309. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  2310. &patchConstantFunctionPropsMap) {
  2311. bool bIsLib = HLM.GetShaderModel()->IsLib();
  2312. // Library don't have entry.
  2313. if (!bIsLib) {
  2314. SetEntryFunction(HLM, Entry.Func, CGM);
  2315. // If at this point we haven't determined the entry function it's an error.
  2316. if (HLM.GetEntryFunction() == nullptr) {
  2317. assert(CGM.getDiags().hasErrorOccurred() &&
  2318. "else SetEntryFunction should have reported this condition");
  2319. return;
  2320. }
  2321. // In back-compat mode (with /Gec flag) create a static global for each
  2322. // const global to allow writing to it.
  2323. // TODO: Verfiy the behavior of static globals in hull shader
  2324. if (CGM.getLangOpts().EnableDX9CompatMode &&
  2325. CGM.getLangOpts().HLSLVersion <= 2016)
  2326. CreateWriteEnabledStaticGlobals(HLM.GetModule(), HLM.GetEntryFunction());
  2327. if (HLM.GetShaderModel()->IsHS()) {
  2328. SetPatchConstantFunction(Entry, HSEntryPatchConstantFuncAttr,
  2329. patchConstantFunctionMap,
  2330. patchConstantFunctionPropsMap, HLM, CGM);
  2331. }
  2332. } else {
  2333. for (auto &it : entryFunctionMap) {
  2334. // skip clone if RT entry
  2335. if (HLM.GetDxilFunctionProps(it.second.Func).IsRay())
  2336. continue;
  2337. // TODO: change flattened function names to dx.entry.<name>:
  2338. // std::string entryName = (Twine(dxilutil::EntryPrefix) +
  2339. // it.getKey()).str();
  2340. CloneShaderEntry(it.second.Func, it.getKey(), HLM);
  2341. auto AttrIter = HSEntryPatchConstantFuncAttr.find(it.second.Func);
  2342. if (AttrIter != HSEntryPatchConstantFuncAttr.end()) {
  2343. SetPatchConstantFunctionWithAttr(
  2344. it.second, AttrIter->second, patchConstantFunctionMap,
  2345. patchConstantFunctionPropsMap, HLM, CGM);
  2346. }
  2347. }
  2348. }
  2349. }
  2350. } // namespace
  2351. namespace CGHLSLMSHelper {
  2352. void FinishIntrinsics(
  2353. HLModule &HLM, std::vector<std::pair<Function *, unsigned>> &intrinsicMap,
  2354. DenseMap<Value *, DxilResourceProperties> &valToResPropertiesMap) {
  2355. // Lower getResourceHeap before AddOpcodeParamForIntrinsics to skip automatic
  2356. // lower for getResourceFromHeap.
  2357. LowerGetResourceFromHeap(HLM, intrinsicMap);
  2358. // translate opcode into parameter for intrinsic functions
  2359. // Do this before CloneShaderEntry and TranslateRayQueryConstructor to avoid
  2360. // update valToResPropertiesMap for cloned inst.
  2361. AddOpcodeParamForIntrinsics(HLM, intrinsicMap, valToResPropertiesMap);
  2362. }
  2363. // Add the dx.break temporary intrinsic and create Call Instructions
  2364. // to it for each branch that requires the artificial conditional.
  2365. void AddDxBreak(Module &M, const SmallVector<llvm::BranchInst*, 16> &DxBreaks) {
  2366. if (DxBreaks.empty())
  2367. return;
  2368. // Collect functions that make use of any wave operations
  2369. // Only they will need the dx.break condition added
  2370. SmallPtrSet<Function *, 16> WaveUsers;
  2371. for (Function &F : M.functions()) {
  2372. HLOpcodeGroup opgroup = hlsl::GetHLOpcodeGroup(&F);
  2373. if (F.isDeclaration() && IsHLWaveSensitive(&F) &&
  2374. (opgroup == HLOpcodeGroup::HLIntrinsic || opgroup == HLOpcodeGroup::HLExtIntrinsic)) {
  2375. for (User *U : F.users()) {
  2376. CallInst *CI = cast<CallInst>(U);
  2377. WaveUsers.insert(CI->getParent()->getParent());
  2378. }
  2379. }
  2380. }
  2381. // If there are no wave users, not even the function declaration is needed
  2382. if (WaveUsers.empty())
  2383. return;
  2384. // Create the dx.break function
  2385. FunctionType *FT = llvm::FunctionType::get(llvm::Type::getInt1Ty(M.getContext()), false);
  2386. Function *func = cast<llvm::Function>(M.getOrInsertFunction(DXIL::kDxBreakFuncName, FT));
  2387. func->addFnAttr(Attribute::AttrKind::NoUnwind);
  2388. // For all break branches recorded previously, if the function they are in makes
  2389. // any use of a wave op, it may need to be artificially conditional. Make it so now.
  2390. // The CleanupDxBreak pass will remove those that aren't needed when more is known.
  2391. for(llvm::BranchInst *BI : DxBreaks) {
  2392. if (WaveUsers.count(BI->getParent()->getParent())) {
  2393. CallInst *Call = CallInst::Create(FT, func, ArrayRef<Value *>(), "", BI);
  2394. BI->setCondition(Call);
  2395. }
  2396. }
  2397. }
  2398. }