CGHLSLMSFinishCodeGen.cpp 93 KB

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