DeclResultIdMapper.cpp 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654
  1. //===--- DeclResultIdMapper.cpp - DeclResultIdMapper impl --------*- C++ -*-==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "DeclResultIdMapper.h"
  10. #include <algorithm>
  11. #include <cstring>
  12. #include <sstream>
  13. #include <unordered_map>
  14. #include "dxc/HLSL/DxilConstants.h"
  15. #include "dxc/HLSL/DxilTypeSystem.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/HlslTypes.h"
  18. #include "clang/AST/RecursiveASTVisitor.h"
  19. #include "llvm/ADT/SmallBitVector.h"
  20. #include "llvm/ADT/StringMap.h"
  21. #include "llvm/ADT/StringSet.h"
  22. #include "SPIRVEmitter.h"
  23. namespace clang {
  24. namespace spirv {
  25. namespace {
  26. /// \brief Returns true if the given decl is a boolean stage I/O variable.
  27. /// Returns false if the type is not boolean, or the decl is a built-in stage
  28. /// variable.
  29. bool isBooleanStageIOVar(const NamedDecl *decl, QualType type,
  30. const hlsl::DXIL::SemanticKind semanticKind,
  31. const hlsl::SigPoint::Kind sigPointKind) {
  32. // [[vk::builtin(...)]] makes the decl a built-in stage variable.
  33. // IsFrontFace (if used as PSIn) is the only known boolean built-in stage
  34. // variable.
  35. const bool isBooleanBuiltin =
  36. (decl->getAttr<VKBuiltInAttr>() != nullptr) ||
  37. (semanticKind == hlsl::Semantic::Kind::IsFrontFace &&
  38. sigPointKind == hlsl::SigPoint::Kind::PSIn);
  39. // TODO: support boolean matrix stage I/O variable if needed.
  40. QualType elemType = {};
  41. const bool isBooleanType = ((TypeTranslator::isScalarType(type, &elemType) ||
  42. TypeTranslator::isVectorType(type, &elemType)) &&
  43. elemType->isBooleanType());
  44. return isBooleanType && !isBooleanBuiltin;
  45. }
  46. /// \brief Returns the stage variable's register assignment for the given Decl.
  47. const hlsl::RegisterAssignment *getResourceBinding(const NamedDecl *decl) {
  48. for (auto *annotation : decl->getUnusualAnnotations()) {
  49. if (auto *reg = dyn_cast<hlsl::RegisterAssignment>(annotation)) {
  50. return reg;
  51. }
  52. }
  53. return nullptr;
  54. }
  55. /// \brief Returns true if the given declaration has a primitive type qualifier.
  56. /// Returns false otherwise.
  57. inline bool hasGSPrimitiveTypeQualifier(const Decl *decl) {
  58. return decl->hasAttr<HLSLTriangleAttr>() ||
  59. decl->hasAttr<HLSLTriangleAdjAttr>() ||
  60. decl->hasAttr<HLSLPointAttr>() || decl->hasAttr<HLSLLineAttr>() ||
  61. decl->hasAttr<HLSLLineAdjAttr>();
  62. }
  63. /// \brief Deduces the parameter qualifier for the given decl.
  64. hlsl::DxilParamInputQual deduceParamQual(const DeclaratorDecl *decl,
  65. bool asInput) {
  66. const auto type = decl->getType();
  67. if (hlsl::IsHLSLInputPatchType(type))
  68. return hlsl::DxilParamInputQual::InputPatch;
  69. if (hlsl::IsHLSLOutputPatchType(type))
  70. return hlsl::DxilParamInputQual::OutputPatch;
  71. // TODO: Add support for multiple output streams.
  72. if (hlsl::IsHLSLStreamOutputType(type))
  73. return hlsl::DxilParamInputQual::OutStream0;
  74. // The inputs to the geometry shader that have a primitive type qualifier
  75. // must use 'InputPrimitive'.
  76. if (hasGSPrimitiveTypeQualifier(decl))
  77. return hlsl::DxilParamInputQual::InputPrimitive;
  78. return asInput ? hlsl::DxilParamInputQual::In : hlsl::DxilParamInputQual::Out;
  79. }
  80. /// \brief Deduces the HLSL SigPoint for the given decl appearing in the given
  81. /// shader model.
  82. const hlsl::SigPoint *deduceSigPoint(const DeclaratorDecl *decl, bool asInput,
  83. const hlsl::ShaderModel::Kind kind,
  84. bool forPCF) {
  85. return hlsl::SigPoint::GetSigPoint(hlsl::SigPointFromInputQual(
  86. deduceParamQual(decl, asInput), kind, forPCF));
  87. }
  88. /// Returns the type of the given decl. If the given decl is a FunctionDecl,
  89. /// returns its result type.
  90. inline QualType getTypeOrFnRetType(const DeclaratorDecl *decl) {
  91. if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  92. return funcDecl->getReturnType();
  93. }
  94. return decl->getType();
  95. }
  96. /// Returns the number of base classes if this type is a derived class/struct.
  97. /// Returns zero otherwise.
  98. inline uint32_t getNumBaseClasses(QualType type) {
  99. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  100. return cxxDecl->getNumBases();
  101. return 0;
  102. }
  103. } // anonymous namespace
  104. std::string StageVar::getSemanticStr() const {
  105. // A special case for zero index, which is equivalent to no index.
  106. // Use what is in the source code.
  107. // TODO: this looks like a hack to make the current tests happy.
  108. // Should consider remove it and fix all tests.
  109. if (semanticInfo.index == 0)
  110. return semanticInfo.str;
  111. std::ostringstream ss;
  112. ss << semanticInfo.name.str() << semanticInfo.index;
  113. return ss.str();
  114. }
  115. uint32_t CounterIdAliasPair::get(ModuleBuilder &builder,
  116. TypeTranslator &translator) const {
  117. if (isAlias) {
  118. const uint32_t counterVarType = builder.getPointerType(
  119. translator.getACSBufferCounter(), spv::StorageClass::Uniform);
  120. return builder.createLoad(counterVarType, resultId);
  121. }
  122. return resultId;
  123. }
  124. const CounterIdAliasPair *
  125. CounterVarFields::get(const llvm::SmallVectorImpl<uint32_t> &indices) const {
  126. for (const auto &field : fields)
  127. if (field.indices == indices)
  128. return &field.counterVar;
  129. return nullptr;
  130. }
  131. bool CounterVarFields::assign(const CounterVarFields &srcFields,
  132. ModuleBuilder &builder,
  133. TypeTranslator &translator) const {
  134. for (const auto &field : fields) {
  135. const auto *srcField = srcFields.get(field.indices);
  136. if (!srcField)
  137. return false;
  138. field.counterVar.assign(*srcField, builder, translator);
  139. }
  140. return true;
  141. }
  142. bool CounterVarFields::assign(const CounterVarFields &srcFields,
  143. const llvm::SmallVector<uint32_t, 4> &dstPrefix,
  144. const llvm::SmallVector<uint32_t, 4> &srcPrefix,
  145. ModuleBuilder &builder,
  146. TypeTranslator &translator) const {
  147. if (dstPrefix.empty() && srcPrefix.empty())
  148. return assign(srcFields, builder, translator);
  149. llvm::SmallVector<uint32_t, 4> srcIndices = srcPrefix;
  150. // If whole has the given prefix, appends all elements after the prefix in
  151. // whole to srcIndices.
  152. const auto applyDiff =
  153. [&srcIndices](const llvm::SmallVector<uint32_t, 4> &whole,
  154. const llvm::SmallVector<uint32_t, 4> &prefix) -> bool {
  155. uint32_t i = 0;
  156. for (; i < prefix.size(); ++i)
  157. if (whole[i] != prefix[i]) {
  158. break;
  159. }
  160. if (i == prefix.size()) {
  161. for (; i < whole.size(); ++i)
  162. srcIndices.push_back(whole[i]);
  163. return true;
  164. }
  165. return false;
  166. };
  167. for (const auto &field : fields)
  168. if (applyDiff(field.indices, dstPrefix)) {
  169. const auto *srcField = srcFields.get(srcIndices);
  170. if (!srcField)
  171. return false;
  172. field.counterVar.assign(*srcField, builder, translator);
  173. for (uint32_t i = srcPrefix.size(); i < srcIndices.size(); ++i)
  174. srcIndices.pop_back();
  175. }
  176. return true;
  177. }
  178. SemanticInfo DeclResultIdMapper::getStageVarSemantic(const NamedDecl *decl) {
  179. for (auto *annotation : decl->getUnusualAnnotations()) {
  180. if (auto *sema = dyn_cast<hlsl::SemanticDecl>(annotation)) {
  181. llvm::StringRef semanticStr = sema->SemanticName;
  182. llvm::StringRef semanticName;
  183. uint32_t index = 0;
  184. hlsl::Semantic::DecomposeNameAndIndex(semanticStr, &semanticName, &index);
  185. const auto *semantic = hlsl::Semantic::GetByName(semanticName);
  186. return {semanticStr, semantic, semanticName, index, sema->Loc};
  187. }
  188. }
  189. return {};
  190. }
  191. bool DeclResultIdMapper::createStageOutputVar(const DeclaratorDecl *decl,
  192. uint32_t storedValue,
  193. bool forPCF) {
  194. QualType type = getTypeOrFnRetType(decl);
  195. // Output stream types (PointStream, LineStream, TriangleStream) are
  196. // translated as their underlying struct types.
  197. if (hlsl::IsHLSLStreamOutputType(type))
  198. type = hlsl::GetHLSLResourceResultType(type);
  199. const auto *sigPoint =
  200. deduceSigPoint(decl, /*asInput=*/false, shaderModel.GetKind(), forPCF);
  201. // HS output variables are created using the other overload. For the rest,
  202. // none of them should be created as arrays.
  203. assert(sigPoint->GetKind() != hlsl::DXIL::SigPointKind::HSCPOut);
  204. SemanticInfo inheritSemantic = {};
  205. // If storedValue is 0, it means this parameter in the original source code is
  206. // not used at all. Avoid writing back.
  207. //
  208. // Write back of stage output variables in GS is manually controlled by
  209. // .Append() intrinsic method, implemented in writeBackOutputStream(). So
  210. // ignoreValue should be set to true for GS.
  211. const bool noWriteBack = storedValue == 0 || shaderModel.IsGS();
  212. return createStageVars(sigPoint, decl, /*asInput=*/false, type,
  213. /*arraySize=*/0, "out.var", llvm::None, &storedValue,
  214. noWriteBack, &inheritSemantic);
  215. }
  216. bool DeclResultIdMapper::createStageOutputVar(const DeclaratorDecl *decl,
  217. uint32_t arraySize,
  218. uint32_t invocationId,
  219. uint32_t storedValue) {
  220. assert(shaderModel.IsHS());
  221. QualType type = getTypeOrFnRetType(decl);
  222. const auto *sigPoint =
  223. hlsl::SigPoint::GetSigPoint(hlsl::DXIL::SigPointKind::HSCPOut);
  224. SemanticInfo inheritSemantic = {};
  225. return createStageVars(sigPoint, decl, /*asInput=*/false, type, arraySize,
  226. "out.var", invocationId, &storedValue,
  227. /*noWriteBack=*/false, &inheritSemantic);
  228. }
  229. bool DeclResultIdMapper::createStageInputVar(const ParmVarDecl *paramDecl,
  230. uint32_t *loadedValue,
  231. bool forPCF) {
  232. uint32_t arraySize = 0;
  233. QualType type = paramDecl->getType();
  234. // Deprive the outermost arrayness for HS/DS/GS and use arraySize
  235. // to convey that information
  236. if (hlsl::IsHLSLInputPatchType(type)) {
  237. arraySize = hlsl::GetHLSLInputPatchCount(type);
  238. type = hlsl::GetHLSLInputPatchElementType(type);
  239. } else if (hlsl::IsHLSLOutputPatchType(type)) {
  240. arraySize = hlsl::GetHLSLOutputPatchCount(type);
  241. type = hlsl::GetHLSLOutputPatchElementType(type);
  242. }
  243. if (hasGSPrimitiveTypeQualifier(paramDecl)) {
  244. const auto *typeDecl = astContext.getAsConstantArrayType(type);
  245. arraySize = static_cast<uint32_t>(typeDecl->getSize().getZExtValue());
  246. type = typeDecl->getElementType();
  247. }
  248. const auto *sigPoint = deduceSigPoint(paramDecl, /*asInput=*/true,
  249. shaderModel.GetKind(), forPCF);
  250. SemanticInfo inheritSemantic = {};
  251. return createStageVars(sigPoint, paramDecl, /*asInput=*/true, type, arraySize,
  252. "in.var", llvm::None, loadedValue,
  253. /*noWriteBack=*/false, &inheritSemantic);
  254. }
  255. const DeclResultIdMapper::DeclSpirvInfo *
  256. DeclResultIdMapper::getDeclSpirvInfo(const ValueDecl *decl) const {
  257. auto it = astDecls.find(decl);
  258. if (it != astDecls.end())
  259. return &it->second;
  260. return nullptr;
  261. }
  262. SpirvEvalInfo DeclResultIdMapper::getDeclEvalInfo(const ValueDecl *decl) {
  263. if (const auto *info = getDeclSpirvInfo(decl)) {
  264. if (info->indexInCTBuffer >= 0) {
  265. // If this is a VarDecl inside a HLSLBufferDecl, we need to do an extra
  266. // OpAccessChain to get the pointer to the variable since we created
  267. // a single variable for the whole buffer object.
  268. const uint32_t varType = typeTranslator.translateType(
  269. // Should only have VarDecls in a HLSLBufferDecl.
  270. cast<VarDecl>(decl)->getType(),
  271. // We need to set decorateLayout here to avoid creating SPIR-V
  272. // instructions for the current type without decorations.
  273. info->info.getLayoutRule());
  274. const uint32_t elemId = theBuilder.createAccessChain(
  275. theBuilder.getPointerType(varType, info->info.getStorageClass()),
  276. info->info, {theBuilder.getConstantInt32(info->indexInCTBuffer)});
  277. return info->info.substResultId(elemId);
  278. } else {
  279. return *info;
  280. }
  281. }
  282. emitFatalError("found unregistered decl", decl->getLocation())
  283. << decl->getName();
  284. emitNote("please file a bug report on "
  285. "https://github.com/Microsoft/DirectXShaderCompiler/issues with "
  286. "source code if possible",
  287. {});
  288. return 0;
  289. }
  290. uint32_t DeclResultIdMapper::createFnParam(const ParmVarDecl *param) {
  291. bool isAlias = false;
  292. auto &info = astDecls[param].info;
  293. const uint32_t type =
  294. getTypeAndCreateCounterForPotentialAliasVar(param, &isAlias, &info);
  295. const uint32_t ptrType =
  296. theBuilder.getPointerType(type, spv::StorageClass::Function);
  297. const uint32_t id = theBuilder.addFnParam(ptrType, param->getName());
  298. info.setResultId(id);
  299. return id;
  300. }
  301. void DeclResultIdMapper::createCounterVarForDecl(const DeclaratorDecl *decl) {
  302. const QualType declType = getTypeOrFnRetType(decl);
  303. if (!counterVars.count(decl) &&
  304. TypeTranslator::isRWAppendConsumeSBuffer(declType)) {
  305. createCounterVar(decl, /*declId=*/0, /*isAlias=*/true);
  306. } else if (!fieldCounterVars.count(decl) && declType->isStructureType() &&
  307. // Exclude other resource types which are represented as structs
  308. !hlsl::IsHLSLResourceType(declType)) {
  309. createFieldCounterVars(decl);
  310. }
  311. }
  312. SpirvEvalInfo DeclResultIdMapper::createFnVar(const VarDecl *var,
  313. llvm::Optional<uint32_t> init) {
  314. bool isAlias = false;
  315. auto &info = astDecls[var].info;
  316. const uint32_t type =
  317. getTypeAndCreateCounterForPotentialAliasVar(var, &isAlias, &info);
  318. const uint32_t id = theBuilder.addFnVar(type, var->getName(), init);
  319. info.setResultId(id);
  320. return info;
  321. }
  322. SpirvEvalInfo DeclResultIdMapper::createFileVar(const VarDecl *var,
  323. llvm::Optional<uint32_t> init) {
  324. bool isAlias = false;
  325. auto &info = astDecls[var].info;
  326. const uint32_t type =
  327. getTypeAndCreateCounterForPotentialAliasVar(var, &isAlias, &info);
  328. const uint32_t id = theBuilder.addModuleVar(type, spv::StorageClass::Private,
  329. var->getName(), init);
  330. info.setResultId(id).setStorageClass(spv::StorageClass::Private);
  331. return info;
  332. }
  333. SpirvEvalInfo DeclResultIdMapper::createExternVar(const VarDecl *var) {
  334. auto storageClass = spv::StorageClass::UniformConstant;
  335. auto rule = SpirvLayoutRule::Void;
  336. bool isACRWSBuffer = false; // Whether is {Append|Consume|RW}StructuredBuffer
  337. if (var->getAttr<HLSLGroupSharedAttr>()) {
  338. // For CS groupshared variables
  339. storageClass = spv::StorageClass::Workgroup;
  340. } else if (TypeTranslator::isResourceType(var)) {
  341. // See through the possible outer arrays
  342. QualType resourceType = var->getType();
  343. while (resourceType->isArrayType()) {
  344. resourceType = resourceType->getAsArrayTypeUnsafe()->getElementType();
  345. }
  346. const llvm::StringRef typeName =
  347. resourceType->getAs<RecordType>()->getDecl()->getName();
  348. // These types are all translated into OpTypeStruct with BufferBlock
  349. // decoration. They should follow standard storage buffer layout,
  350. // which GLSL std430 rules statisfies.
  351. if (typeName == "StructuredBuffer" || typeName == "ByteAddressBuffer" ||
  352. typeName == "RWByteAddressBuffer") {
  353. storageClass = spv::StorageClass::Uniform;
  354. rule = spirvOptions.sBufferLayoutRule;
  355. } else if (typeName == "RWStructuredBuffer" ||
  356. typeName == "AppendStructuredBuffer" ||
  357. typeName == "ConsumeStructuredBuffer") {
  358. storageClass = spv::StorageClass::Uniform;
  359. rule = spirvOptions.sBufferLayoutRule;
  360. isACRWSBuffer = true;
  361. }
  362. } else {
  363. // This is a stand-alone externally-visiable non-resource-type variable.
  364. // They should be grouped into the $Globals cbuffer. We create that cbuffer
  365. // and record all variables inside it upon seeing the first such variable.
  366. if (astDecls.count(var) == 0)
  367. createGlobalsCBuffer(var);
  368. return astDecls[var].info;
  369. }
  370. uint32_t varType = typeTranslator.translateType(var->getType(), rule);
  371. // Require corresponding capability for accessing 16-bit data.
  372. if (storageClass == spv::StorageClass::Uniform &&
  373. spirvOptions.enable16BitTypes &&
  374. typeTranslator.isOrContains16BitType(var->getType())) {
  375. theBuilder.addExtension(Extension::KHR_16bit_storage,
  376. "16-bit types in resource", var->getLocation());
  377. theBuilder.requireCapability(spv::Capability::StorageUniformBufferBlock16);
  378. }
  379. const uint32_t id = theBuilder.addModuleVar(varType, storageClass,
  380. var->getName(), llvm::None);
  381. const auto info =
  382. SpirvEvalInfo(id).setStorageClass(storageClass).setLayoutRule(rule);
  383. astDecls[var] = info;
  384. // Variables in Workgroup do not need descriptor decorations.
  385. if (storageClass == spv::StorageClass::Workgroup)
  386. return info;
  387. const auto *regAttr = getResourceBinding(var);
  388. const auto *bindingAttr = var->getAttr<VKBindingAttr>();
  389. const auto *counterBindingAttr = var->getAttr<VKCounterBindingAttr>();
  390. resourceVars.emplace_back(id, var->getLocation(), regAttr, bindingAttr,
  391. counterBindingAttr);
  392. if (const auto *inputAttachment = var->getAttr<VKInputAttachmentIndexAttr>())
  393. theBuilder.decorateInputAttachmentIndex(id, inputAttachment->getIndex());
  394. if (isACRWSBuffer) {
  395. // For {Append|Consume|RW}StructuredBuffer, we need to always create another
  396. // variable for its associated counter.
  397. createCounterVar(var, id, /*isAlias=*/false);
  398. }
  399. return info;
  400. }
  401. uint32_t DeclResultIdMapper::getMatrixStructType(const VarDecl *matVar,
  402. spv::StorageClass sc,
  403. SpirvLayoutRule rule) {
  404. const auto matType = matVar->getType();
  405. assert(TypeTranslator::isMxNMatrix(matType));
  406. auto &context = *theBuilder.getSPIRVContext();
  407. llvm::SmallVector<const Decoration *, 4> decorations;
  408. const bool isRowMajor = typeTranslator.isRowMajorMatrix(matType);
  409. uint32_t stride;
  410. (void)typeTranslator.getAlignmentAndSize(matType, rule, &stride);
  411. decorations.push_back(Decoration::getOffset(context, 0, 0));
  412. decorations.push_back(Decoration::getMatrixStride(context, stride, 0));
  413. decorations.push_back(isRowMajor ? Decoration::getColMajor(context, 0)
  414. : Decoration::getRowMajor(context, 0));
  415. decorations.push_back(Decoration::getBlock(context));
  416. // Get the type for the wrapping struct
  417. const std::string structName = "type." + matVar->getName().str();
  418. return theBuilder.getStructType({typeTranslator.translateType(matType)},
  419. structName, {}, decorations);
  420. }
  421. uint32_t DeclResultIdMapper::createStructOrStructArrayVarOfExplicitLayout(
  422. const DeclContext *decl, int arraySize, const ContextUsageKind usageKind,
  423. llvm::StringRef typeName, llvm::StringRef varName) {
  424. // cbuffers are translated into OpTypeStruct with Block decoration.
  425. // tbuffers are translated into OpTypeStruct with BufferBlock decoration.
  426. // Push constants are translated into OpTypeStruct with Block decoration.
  427. //
  428. // Both cbuffers and tbuffers have the SPIR-V Uniform storage class.
  429. // Push constants have the SPIR-V PushConstant storage class.
  430. const bool forCBuffer = usageKind == ContextUsageKind::CBuffer;
  431. const bool forTBuffer = usageKind == ContextUsageKind::TBuffer;
  432. const bool forGlobals = usageKind == ContextUsageKind::Globals;
  433. const bool forPC = usageKind == ContextUsageKind::PushConstant;
  434. auto &context = *theBuilder.getSPIRVContext();
  435. const SpirvLayoutRule layoutRule =
  436. (forCBuffer || forGlobals)
  437. ? spirvOptions.cBufferLayoutRule
  438. : (forTBuffer ? spirvOptions.tBufferLayoutRule
  439. : spirvOptions.sBufferLayoutRule);
  440. const auto *blockDec = forTBuffer ? Decoration::getBufferBlock(context)
  441. : Decoration::getBlock(context);
  442. const llvm::SmallVector<const Decl *, 4> &declGroup =
  443. typeTranslator.collectDeclsInDeclContext(decl);
  444. auto decorations = typeTranslator.getLayoutDecorations(declGroup, layoutRule);
  445. decorations.push_back(blockDec);
  446. // Collect the type and name for each field
  447. llvm::SmallVector<uint32_t, 4> fieldTypes;
  448. llvm::SmallVector<llvm::StringRef, 4> fieldNames;
  449. uint32_t fieldIndex = 0;
  450. for (const auto *subDecl : declGroup) {
  451. // The field can only be FieldDecl (for normal structs) or VarDecl (for
  452. // HLSLBufferDecls).
  453. assert(isa<VarDecl>(subDecl) || isa<FieldDecl>(subDecl));
  454. const auto *declDecl = cast<DeclaratorDecl>(subDecl);
  455. // All fields are qualified with const. It will affect the debug name.
  456. // We don't need it here.
  457. auto varType = declDecl->getType();
  458. varType.removeLocalConst();
  459. fieldTypes.push_back(typeTranslator.translateType(varType, layoutRule));
  460. fieldNames.push_back(declDecl->getName());
  461. // Require corresponding capability for accessing 16-bit data.
  462. if (spirvOptions.enable16BitTypes &&
  463. typeTranslator.isOrContains16BitType(varType)) {
  464. theBuilder.addExtension(Extension::KHR_16bit_storage,
  465. "16-bit types in resource",
  466. declDecl->getLocation());
  467. theBuilder.requireCapability(
  468. (forCBuffer || forGlobals)
  469. ? spv::Capability::StorageUniform16
  470. : forPC ? spv::Capability::StoragePushConstant16
  471. : spv::Capability::StorageUniformBufferBlock16);
  472. }
  473. // tbuffer/TextureBuffers are non-writable SSBOs. OpMemberDecorate
  474. // NonWritable must be applied to all fields.
  475. if (forTBuffer) {
  476. decorations.push_back(Decoration::getNonWritable(
  477. *theBuilder.getSPIRVContext(), fieldIndex));
  478. }
  479. ++fieldIndex;
  480. }
  481. // Get the type for the whole struct
  482. uint32_t resultType =
  483. theBuilder.getStructType(fieldTypes, typeName, fieldNames, decorations);
  484. // Make an array if requested.
  485. if (arraySize > 0) {
  486. resultType = theBuilder.getArrayType(
  487. resultType, theBuilder.getConstantUint32(arraySize));
  488. } else if (arraySize == -1) {
  489. // Runtime arrays of cbuffer/tbuffer needs additional capability.
  490. theBuilder.addExtension(Extension::EXT_descriptor_indexing,
  491. "runtime array of resources", {});
  492. theBuilder.requireCapability(spv::Capability::RuntimeDescriptorArrayEXT);
  493. resultType = theBuilder.getRuntimeArrayType(resultType);
  494. }
  495. // Register the <type-id> for this decl
  496. ctBufferPCTypeIds[decl] = resultType;
  497. const auto sc =
  498. forPC ? spv::StorageClass::PushConstant : spv::StorageClass::Uniform;
  499. // Create the variable for the whole struct / struct array.
  500. return theBuilder.addModuleVar(resultType, sc, varName);
  501. }
  502. uint32_t DeclResultIdMapper::createCTBuffer(const HLSLBufferDecl *decl) {
  503. const auto usageKind =
  504. decl->isCBuffer() ? ContextUsageKind::CBuffer : ContextUsageKind::TBuffer;
  505. const std::string structName = "type." + decl->getName().str();
  506. // The front-end does not allow arrays of cbuffer/tbuffer.
  507. const uint32_t bufferVar = createStructOrStructArrayVarOfExplicitLayout(
  508. decl, /*arraySize*/ 0, usageKind, structName, decl->getName());
  509. // We still register all VarDecls seperately here. All the VarDecls are
  510. // mapped to the <result-id> of the buffer object, which means when querying
  511. // querying the <result-id> for a certain VarDecl, we need to do an extra
  512. // OpAccessChain.
  513. int index = 0;
  514. for (const auto *subDecl : decl->decls()) {
  515. if (TypeTranslator::shouldSkipInStructLayout(subDecl))
  516. continue;
  517. const auto *varDecl = cast<VarDecl>(subDecl);
  518. astDecls[varDecl] =
  519. SpirvEvalInfo(bufferVar)
  520. .setStorageClass(spv::StorageClass::Uniform)
  521. .setLayoutRule(decl->isCBuffer() ? spirvOptions.cBufferLayoutRule
  522. : spirvOptions.tBufferLayoutRule);
  523. astDecls[varDecl].indexInCTBuffer = index++;
  524. }
  525. resourceVars.emplace_back(
  526. bufferVar, decl->getLocation(), getResourceBinding(decl),
  527. decl->getAttr<VKBindingAttr>(), decl->getAttr<VKCounterBindingAttr>());
  528. return bufferVar;
  529. }
  530. uint32_t DeclResultIdMapper::createCTBuffer(const VarDecl *decl) {
  531. const RecordType *recordType = nullptr;
  532. int arraySize = 0;
  533. // In case we have an array of ConstantBuffer/TextureBuffer:
  534. if (const auto *arrayType = decl->getType()->getAsArrayTypeUnsafe()) {
  535. recordType = arrayType->getElementType()->getAs<RecordType>();
  536. if (const auto *caType =
  537. astContext.getAsConstantArrayType(decl->getType())) {
  538. arraySize = static_cast<uint32_t>(caType->getSize().getZExtValue());
  539. } else {
  540. arraySize = -1;
  541. }
  542. } else {
  543. recordType = decl->getType()->getAs<RecordType>();
  544. }
  545. if (!recordType) {
  546. emitError("constant/texture buffer type %0 unimplemented",
  547. decl->getLocStart())
  548. << decl->getType();
  549. return 0;
  550. }
  551. const auto *context = cast<HLSLBufferDecl>(decl->getDeclContext());
  552. const auto usageKind = context->isCBuffer() ? ContextUsageKind::CBuffer
  553. : ContextUsageKind::TBuffer;
  554. const char *ctBufferName =
  555. context->isCBuffer() ? "ConstantBuffer." : "TextureBuffer.";
  556. const std::string structName = "type." + std::string(ctBufferName) +
  557. recordType->getDecl()->getName().str();
  558. const uint32_t bufferVar = createStructOrStructArrayVarOfExplicitLayout(
  559. recordType->getDecl(), arraySize, usageKind, structName, decl->getName());
  560. // We register the VarDecl here.
  561. astDecls[decl] =
  562. SpirvEvalInfo(bufferVar)
  563. .setStorageClass(spv::StorageClass::Uniform)
  564. .setLayoutRule(context->isCBuffer() ? spirvOptions.cBufferLayoutRule
  565. : spirvOptions.tBufferLayoutRule);
  566. resourceVars.emplace_back(
  567. bufferVar, decl->getLocation(), getResourceBinding(context),
  568. decl->getAttr<VKBindingAttr>(), decl->getAttr<VKCounterBindingAttr>());
  569. return bufferVar;
  570. }
  571. uint32_t DeclResultIdMapper::createPushConstant(const VarDecl *decl) {
  572. // The front-end errors out if non-struct type push constant is used.
  573. const auto *recordType = decl->getType()->getAs<RecordType>();
  574. assert(recordType);
  575. const std::string structName =
  576. "type.PushConstant." + recordType->getDecl()->getName().str();
  577. const uint32_t var = createStructOrStructArrayVarOfExplicitLayout(
  578. recordType->getDecl(), /*arraySize*/ 0, ContextUsageKind::PushConstant,
  579. structName, decl->getName());
  580. // Register the VarDecl
  581. astDecls[decl] = SpirvEvalInfo(var)
  582. .setStorageClass(spv::StorageClass::PushConstant)
  583. .setLayoutRule(spirvOptions.sBufferLayoutRule);
  584. // Do not push this variable into resourceVars since it does not need
  585. // descriptor set.
  586. return var;
  587. }
  588. void DeclResultIdMapper::createGlobalsCBuffer(const VarDecl *var) {
  589. if (astDecls.count(var) != 0)
  590. return;
  591. const auto *context = var->getTranslationUnitDecl();
  592. const uint32_t globals = createStructOrStructArrayVarOfExplicitLayout(
  593. context, /*arraySize*/ 0, ContextUsageKind::Globals, "type.$Globals",
  594. "$Globals");
  595. resourceVars.emplace_back(globals, SourceLocation(), nullptr, nullptr,
  596. nullptr);
  597. uint32_t index = 0;
  598. for (const auto *decl : typeTranslator.collectDeclsInDeclContext(context))
  599. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  600. if (!spirvOptions.noWarnIgnoredFeatures) {
  601. if (const auto *init = varDecl->getInit())
  602. emitWarning(
  603. "variable '%0' will be placed in $Globals so initializer ignored",
  604. init->getExprLoc())
  605. << var->getName() << init->getSourceRange();
  606. }
  607. if (const auto *attr = varDecl->getAttr<VKBindingAttr>()) {
  608. emitError("variable '%0' will be placed in $Globals so cannot have "
  609. "vk::binding attribute",
  610. attr->getLocation())
  611. << var->getName();
  612. return;
  613. }
  614. astDecls[varDecl] = SpirvEvalInfo(globals)
  615. .setStorageClass(spv::StorageClass::Uniform)
  616. .setLayoutRule(spirvOptions.cBufferLayoutRule);
  617. astDecls[varDecl].indexInCTBuffer = index++;
  618. }
  619. }
  620. uint32_t DeclResultIdMapper::getOrRegisterFnResultId(const FunctionDecl *fn) {
  621. if (const auto *info = getDeclSpirvInfo(fn))
  622. return info->info;
  623. auto &info = astDecls[fn].info;
  624. bool isAlias = false;
  625. (void)getTypeAndCreateCounterForPotentialAliasVar(fn, &isAlias, &info);
  626. const uint32_t id = theBuilder.getSPIRVContext()->takeNextId();
  627. info.setResultId(id);
  628. // No need to dereference to get the pointer. Function returns that are
  629. // stand-alone aliases are already pointers to values. All other cases should
  630. // be normal rvalues.
  631. if (!isAlias ||
  632. !TypeTranslator::isAKindOfStructuredOrByteBuffer(fn->getReturnType()))
  633. info.setRValue();
  634. return id;
  635. }
  636. const CounterIdAliasPair *DeclResultIdMapper::getCounterIdAliasPair(
  637. const DeclaratorDecl *decl, const llvm::SmallVector<uint32_t, 4> *indices) {
  638. if (!decl)
  639. return nullptr;
  640. if (indices) {
  641. // Indices are provided. Walk through the fields of the decl.
  642. const auto counter = fieldCounterVars.find(decl);
  643. if (counter != fieldCounterVars.end())
  644. return counter->second.get(*indices);
  645. } else {
  646. // No indices. Check the stand-alone entities.
  647. const auto counter = counterVars.find(decl);
  648. if (counter != counterVars.end())
  649. return &counter->second;
  650. }
  651. return nullptr;
  652. }
  653. const CounterVarFields *
  654. DeclResultIdMapper::getCounterVarFields(const DeclaratorDecl *decl) {
  655. if (!decl)
  656. return nullptr;
  657. const auto found = fieldCounterVars.find(decl);
  658. if (found != fieldCounterVars.end())
  659. return &found->second;
  660. return nullptr;
  661. }
  662. void DeclResultIdMapper::registerSpecConstant(const VarDecl *decl,
  663. uint32_t specConstant) {
  664. astDecls[decl].info.setResultId(specConstant).setRValue().setSpecConstant();
  665. }
  666. void DeclResultIdMapper::createCounterVar(
  667. const DeclaratorDecl *decl, uint32_t declId, bool isAlias,
  668. const llvm::SmallVector<uint32_t, 4> *indices) {
  669. std::string counterName = "counter.var." + decl->getName().str();
  670. if (indices) {
  671. // Append field indices to the name
  672. for (const auto index : *indices)
  673. counterName += "." + std::to_string(index);
  674. }
  675. uint32_t counterType = typeTranslator.getACSBufferCounter();
  676. // {RW|Append|Consume}StructuredBuffer are all in Uniform storage class.
  677. // Alias counter variables should be created into the Private storage class.
  678. const spv::StorageClass sc =
  679. isAlias ? spv::StorageClass::Private : spv::StorageClass::Uniform;
  680. if (isAlias) {
  681. // Apply an extra level of pointer for alias counter variable
  682. counterType =
  683. theBuilder.getPointerType(counterType, spv::StorageClass::Uniform);
  684. }
  685. const uint32_t counterId =
  686. theBuilder.addModuleVar(counterType, sc, counterName);
  687. if (!isAlias) {
  688. // Non-alias counter variables should be put in to resourceVars so that
  689. // descriptors can be allocated for them.
  690. resourceVars.emplace_back(counterId, decl->getLocation(),
  691. getResourceBinding(decl),
  692. decl->getAttr<VKBindingAttr>(),
  693. decl->getAttr<VKCounterBindingAttr>(), true);
  694. assert(declId);
  695. theBuilder.decorateCounterBufferId(declId, counterId);
  696. }
  697. if (indices)
  698. fieldCounterVars[decl].append(*indices, counterId);
  699. else
  700. counterVars[decl] = {counterId, isAlias};
  701. }
  702. void DeclResultIdMapper::createFieldCounterVars(
  703. const DeclaratorDecl *rootDecl, const DeclaratorDecl *decl,
  704. llvm::SmallVector<uint32_t, 4> *indices) {
  705. const QualType type = getTypeOrFnRetType(decl);
  706. const auto *recordType = type->getAs<RecordType>();
  707. assert(recordType);
  708. const auto *recordDecl = recordType->getDecl();
  709. for (const auto *field : recordDecl->fields()) {
  710. // Build up the index chain
  711. indices->push_back(getNumBaseClasses(type) + field->getFieldIndex());
  712. const QualType fieldType = field->getType();
  713. if (TypeTranslator::isRWAppendConsumeSBuffer(fieldType))
  714. createCounterVar(rootDecl, /*declId=*/0, /*isAlias=*/true, indices);
  715. else if (fieldType->isStructureType() &&
  716. !hlsl::IsHLSLResourceType(fieldType))
  717. // Go recursively into all nested structs
  718. createFieldCounterVars(rootDecl, field, indices);
  719. indices->pop_back();
  720. }
  721. }
  722. uint32_t
  723. DeclResultIdMapper::getCTBufferPushConstantTypeId(const DeclContext *decl) {
  724. const auto found = ctBufferPCTypeIds.find(decl);
  725. assert(found != ctBufferPCTypeIds.end());
  726. return found->second;
  727. }
  728. std::vector<uint32_t> DeclResultIdMapper::collectStageVars() const {
  729. std::vector<uint32_t> vars;
  730. for (auto var : glPerVertex.getStageInVars())
  731. vars.push_back(var);
  732. for (auto var : glPerVertex.getStageOutVars())
  733. vars.push_back(var);
  734. for (const auto &var : stageVars)
  735. vars.push_back(var.getSpirvId());
  736. return vars;
  737. }
  738. namespace {
  739. /// A class for managing stage input/output locations to avoid duplicate uses of
  740. /// the same location.
  741. class LocationSet {
  742. public:
  743. /// Maximum number of indices supported
  744. const static uint32_t kMaxIndex = 2;
  745. /// Maximum number of locations supported
  746. // Typically we won't have that many stage input or output variables.
  747. // Using 64 should be fine here.
  748. const static uint32_t kMaxLoc = 64;
  749. LocationSet() {
  750. for (uint32_t i = 0; i < kMaxIndex; ++i) {
  751. usedLocs[i].resize(kMaxLoc);
  752. nextLoc[i] = 0;
  753. }
  754. }
  755. /// Uses the given location.
  756. void useLoc(uint32_t loc, uint32_t index = 0) {
  757. assert(index < kMaxIndex);
  758. usedLocs[index].set(loc);
  759. }
  760. /// Uses the next |count| available location.
  761. int useNextLocs(uint32_t count, uint32_t index = 0) {
  762. assert(index < kMaxIndex);
  763. auto &locs = usedLocs[index];
  764. auto &next = nextLoc[index];
  765. while (locs[next])
  766. next++;
  767. int toUse = next;
  768. for (uint32_t i = 0; i < count; ++i) {
  769. assert(!locs[next]);
  770. locs.set(next++);
  771. }
  772. return toUse;
  773. }
  774. /// Returns true if the given location number is already used.
  775. bool isLocUsed(uint32_t loc, uint32_t index = 0) {
  776. assert(index < kMaxIndex);
  777. return usedLocs[index][loc];
  778. }
  779. private:
  780. llvm::SmallBitVector usedLocs[kMaxIndex]; ///< All previously used locations
  781. uint32_t nextLoc[kMaxIndex]; ///< Next available location
  782. };
  783. /// A class for managing resource bindings to avoid duplicate uses of the same
  784. /// set and binding number.
  785. class BindingSet {
  786. public:
  787. /// Uses the given set and binding number.
  788. void useBinding(uint32_t binding, uint32_t set) {
  789. usedBindings[set].insert(binding);
  790. }
  791. /// Uses the next avaiable binding number in set 0.
  792. uint32_t useNextBinding(uint32_t set) {
  793. auto &binding = usedBindings[set];
  794. auto &next = nextBindings[set];
  795. while (binding.count(next))
  796. ++next;
  797. binding.insert(next);
  798. return next++;
  799. }
  800. private:
  801. ///< set number -> set of used binding number
  802. llvm::DenseMap<uint32_t, llvm::DenseSet<uint32_t>> usedBindings;
  803. ///< set number -> next available binding number
  804. llvm::DenseMap<uint32_t, uint32_t> nextBindings;
  805. };
  806. } // namespace
  807. bool DeclResultIdMapper::checkSemanticDuplication(bool forInput) {
  808. llvm::StringSet<> seenSemantics;
  809. bool success = true;
  810. for (const auto &var : stageVars) {
  811. auto s = var.getSemanticStr();
  812. if (s.empty()) {
  813. // We translate WaveGetLaneCount() and WaveGetLaneIndex() into builtin
  814. // variables. Those variables are inserted into the normal stage IO
  815. // processing pipeline, but with the semantics as empty strings.
  816. assert(var.isSpirvBuitin());
  817. continue;
  818. }
  819. if (forInput && var.getSigPoint()->IsInput()) {
  820. if (seenSemantics.count(s)) {
  821. emitError("input semantic '%0' used more than once", {}) << s;
  822. success = false;
  823. }
  824. seenSemantics.insert(s);
  825. } else if (!forInput && var.getSigPoint()->IsOutput()) {
  826. if (seenSemantics.count(s)) {
  827. emitError("output semantic '%0' used more than once", {}) << s;
  828. success = false;
  829. }
  830. seenSemantics.insert(s);
  831. }
  832. }
  833. return success;
  834. }
  835. bool DeclResultIdMapper::finalizeStageIOLocations(bool forInput) {
  836. if (!checkSemanticDuplication(forInput))
  837. return false;
  838. // Returns false if the given StageVar is an input/output variable without
  839. // explicit location assignment. Otherwise, returns true.
  840. const auto locAssigned = [forInput, this](const StageVar &v) {
  841. if (forInput == isInputStorageClass(v))
  842. // No need to assign location for builtins. Treat as assigned.
  843. return v.isSpirvBuitin() || v.getLocationAttr() != nullptr;
  844. // For the ones we don't care, treat as assigned.
  845. return true;
  846. };
  847. // If we have explicit location specified for all input/output variables,
  848. // use them instead assign by ourselves.
  849. if (std::all_of(stageVars.begin(), stageVars.end(), locAssigned)) {
  850. LocationSet locSet;
  851. bool noError = true;
  852. for (const auto &var : stageVars) {
  853. // Skip builtins & those stage variables we are not handling for this call
  854. if (var.isSpirvBuitin() || forInput != isInputStorageClass(var))
  855. continue;
  856. const auto *attr = var.getLocationAttr();
  857. const auto loc = attr->getNumber();
  858. const auto attrLoc = attr->getLocation(); // Attr source code location
  859. const auto idx = var.getIndexAttr() ? var.getIndexAttr()->getNumber() : 0;
  860. if ((const unsigned)loc >= LocationSet::kMaxLoc) {
  861. emitError("stage %select{output|input}0 location #%1 too large",
  862. attrLoc)
  863. << forInput << loc;
  864. return false;
  865. }
  866. // Make sure the same location is not assigned more than once
  867. if (locSet.isLocUsed(loc, idx)) {
  868. emitError("stage %select{output|input}0 location #%1 already assigned",
  869. attrLoc)
  870. << forInput << loc;
  871. noError = false;
  872. }
  873. locSet.useLoc(loc, idx);
  874. theBuilder.decorateLocation(var.getSpirvId(), loc);
  875. if (var.getIndexAttr())
  876. theBuilder.decorateIndex(var.getSpirvId(), idx);
  877. }
  878. return noError;
  879. }
  880. std::vector<const StageVar *> vars;
  881. LocationSet locSet;
  882. for (const auto &var : stageVars) {
  883. if (var.isSpirvBuitin() || forInput != isInputStorageClass(var))
  884. continue;
  885. if (var.getLocationAttr()) {
  886. // We have checked that not all of the stage variables have explicit
  887. // location assignment.
  888. emitError("partial explicit stage %select{output|input}0 location "
  889. "assignment via vk::location(X) unsupported",
  890. {})
  891. << forInput;
  892. return false;
  893. }
  894. const auto &semaInfo = var.getSemanticInfo();
  895. // We should special rules for SV_Target: the location number comes from the
  896. // semantic string index.
  897. if (semaInfo.isTarget()) {
  898. theBuilder.decorateLocation(var.getSpirvId(), semaInfo.index);
  899. locSet.useLoc(semaInfo.index);
  900. } else {
  901. vars.push_back(&var);
  902. }
  903. }
  904. // If alphabetical ordering was requested, sort by semantic string.
  905. // Since HS includes 2 sets of outputs (patch-constant output and
  906. // OutputPatch), running into location mismatches between HS and DS is very
  907. // likely. In order to avoid location mismatches between HS and DS, use
  908. // alphabetical ordering.
  909. if (spirvOptions.stageIoOrder == "alpha" ||
  910. (!forInput && shaderModel.IsHS()) || (forInput && shaderModel.IsDS())) {
  911. // Sort stage input/output variables alphabetically
  912. std::sort(vars.begin(), vars.end(),
  913. [](const StageVar *a, const StageVar *b) {
  914. return a->getSemanticStr() < b->getSemanticStr();
  915. });
  916. }
  917. for (const auto *var : vars)
  918. theBuilder.decorateLocation(var->getSpirvId(),
  919. locSet.useNextLocs(var->getLocationCount()));
  920. return true;
  921. }
  922. namespace {
  923. /// A class for maintaining the binding number shift requested for descriptor
  924. /// sets.
  925. class BindingShiftMapper {
  926. public:
  927. explicit BindingShiftMapper(const llvm::SmallVectorImpl<int32_t> &shifts)
  928. : masterShift(0) {
  929. assert(shifts.size() % 2 == 0);
  930. if (shifts.size() == 2 && shifts[1] == -1) {
  931. masterShift = shifts[0];
  932. } else {
  933. for (uint32_t i = 0; i < shifts.size(); i += 2)
  934. perSetShift[shifts[i + 1]] = shifts[i];
  935. }
  936. }
  937. /// Returns the shift amount for the given set.
  938. int32_t getShiftForSet(int32_t set) const {
  939. const auto found = perSetShift.find(set);
  940. if (found != perSetShift.end())
  941. return found->second;
  942. return masterShift;
  943. }
  944. private:
  945. uint32_t masterShift; /// Shift amount applies to all sets.
  946. llvm::DenseMap<int32_t, int32_t> perSetShift;
  947. };
  948. /// A class for maintaining the mapping from source code register attributes to
  949. /// descriptor set and number settings.
  950. class RegisterBindingMapper {
  951. public:
  952. /// Takes in the relation between register attributes and descriptor settings.
  953. /// Each relation is represented by four strings:
  954. /// <register-type-number> <space> <descriptor-binding> <set>
  955. bool takeInRelation(const std::vector<std::string> &relation,
  956. std::string *error) {
  957. assert(relation.size() % 4 == 0);
  958. mapping.clear();
  959. for (uint32_t i = 0; i < relation.size(); i += 4) {
  960. int32_t spaceNo = -1, setNo = -1, bindNo = -1;
  961. if (StringRef(relation[i + 1]).getAsInteger(10, spaceNo) || spaceNo < 0) {
  962. *error = "space number: " + relation[i + 1];
  963. return false;
  964. }
  965. if (StringRef(relation[i + 2]).getAsInteger(10, bindNo) || bindNo < 0) {
  966. *error = "binding number: " + relation[i + 2];
  967. return false;
  968. }
  969. if (StringRef(relation[i + 3]).getAsInteger(10, setNo) || setNo < 0) {
  970. *error = "set number: " + relation[i + 3];
  971. return false;
  972. }
  973. mapping[relation[i + 1] + relation[i]] = std::make_pair(setNo, bindNo);
  974. }
  975. return true;
  976. }
  977. /// Returns true and set the correct set and binding number if we can find a
  978. /// descriptor setting for the given register. False otherwise.
  979. bool getSetBinding(const hlsl::RegisterAssignment *regAttr, int *setNo,
  980. int *bindNo) const {
  981. std::ostringstream iss;
  982. iss << regAttr->RegisterSpace << regAttr->RegisterType
  983. << regAttr->RegisterNumber;
  984. auto found = mapping.find(iss.str());
  985. if (found != mapping.end()) {
  986. *setNo = found->second.first;
  987. *bindNo = found->second.second;
  988. return true;
  989. }
  990. return false;
  991. }
  992. private:
  993. llvm::StringMap<std::pair<int, int>> mapping;
  994. };
  995. } // namespace
  996. bool DeclResultIdMapper::decorateResourceBindings() {
  997. // For normal resource, we support 3 approaches of setting binding numbers:
  998. // - m1: [[vk::binding(...)]]
  999. // - m2: :register(...)
  1000. // - m3: None
  1001. //
  1002. // For associated counters, we support 2 approaches:
  1003. // - c1: [[vk::counter_binding(...)]
  1004. // - c2: None
  1005. //
  1006. // In combination, we need to handle 9 cases:
  1007. // - 3 cases for nomral resoures (m1, m2, m3)
  1008. // - 6 cases for associated counters (mX * cY)
  1009. //
  1010. // In the following order:
  1011. // - m1, mX * c1
  1012. // - m2
  1013. // - m3, mX * c2
  1014. // Special handling of -fvk-bind-register, which requires
  1015. // * All resources are annoated with :register() in the source code
  1016. // * -fvk-bind-register is specified for every resource
  1017. if (!spirvOptions.bindRegister.empty()) {
  1018. RegisterBindingMapper bindingMapper;
  1019. std::string error;
  1020. if (!bindingMapper.takeInRelation(spirvOptions.bindRegister, &error)) {
  1021. emitError("invalid -fvk-bind-register %0", {}) << error;
  1022. return false;
  1023. }
  1024. for (const auto &var : resourceVars)
  1025. if (const auto *regAttr = var.getRegister()) {
  1026. if (var.isCounter()) {
  1027. emitError("-fvk-bind-register for RW/Append/Consume StructuredBuffer "
  1028. "umimplemented",
  1029. var.getSourceLocation());
  1030. } else {
  1031. int setNo = 0, bindNo = 0;
  1032. if (!bindingMapper.getSetBinding(regAttr, &setNo, &bindNo)) {
  1033. emitError("missing -fvk-bind-register for resource",
  1034. var.getSourceLocation());
  1035. return false;
  1036. }
  1037. theBuilder.decorateDSetBinding(var.getSpirvId(), setNo, bindNo);
  1038. }
  1039. } else {
  1040. emitError(
  1041. "-fvk-bind-register requires register annotations on all resources",
  1042. var.getSourceLocation());
  1043. return false;
  1044. }
  1045. return true;
  1046. }
  1047. BindingSet bindingSet;
  1048. // Decorates the given varId of the given category with set number
  1049. // setNo, binding number bindingNo. Ignores overlaps.
  1050. const auto tryToDecorate = [this, &bindingSet](const uint32_t varId,
  1051. const uint32_t setNo,
  1052. const uint32_t bindingNo) {
  1053. bindingSet.useBinding(bindingNo, setNo);
  1054. theBuilder.decorateDSetBinding(varId, setNo, bindingNo);
  1055. };
  1056. for (const auto &var : resourceVars) {
  1057. if (var.isCounter()) {
  1058. if (const auto *vkCBinding = var.getCounterBinding()) {
  1059. // Process mX * c1
  1060. uint32_t set = 0;
  1061. if (const auto *vkBinding = var.getBinding())
  1062. set = vkBinding->getSet();
  1063. else if (const auto *reg = var.getRegister())
  1064. set = reg->RegisterSpace;
  1065. tryToDecorate(var.getSpirvId(), set, vkCBinding->getBinding());
  1066. }
  1067. } else {
  1068. if (const auto *vkBinding = var.getBinding()) {
  1069. // Process m1
  1070. tryToDecorate(var.getSpirvId(), vkBinding->getSet(),
  1071. vkBinding->getBinding());
  1072. }
  1073. }
  1074. }
  1075. BindingShiftMapper bShiftMapper(spirvOptions.bShift);
  1076. BindingShiftMapper tShiftMapper(spirvOptions.tShift);
  1077. BindingShiftMapper sShiftMapper(spirvOptions.sShift);
  1078. BindingShiftMapper uShiftMapper(spirvOptions.uShift);
  1079. // Process m2
  1080. for (const auto &var : resourceVars)
  1081. if (!var.isCounter() && !var.getBinding())
  1082. if (const auto *reg = var.getRegister()) {
  1083. const uint32_t set = reg->RegisterSpace;
  1084. uint32_t binding = reg->RegisterNumber;
  1085. switch (reg->RegisterType) {
  1086. case 'b':
  1087. binding += bShiftMapper.getShiftForSet(set);
  1088. break;
  1089. case 't':
  1090. binding += tShiftMapper.getShiftForSet(set);
  1091. break;
  1092. case 's':
  1093. binding += sShiftMapper.getShiftForSet(set);
  1094. break;
  1095. case 'u':
  1096. binding += uShiftMapper.getShiftForSet(set);
  1097. break;
  1098. case 'c':
  1099. // For setting packing offset. Does not affect binding.
  1100. break;
  1101. default:
  1102. llvm_unreachable("unknown register type found");
  1103. }
  1104. tryToDecorate(var.getSpirvId(), set, binding);
  1105. }
  1106. for (const auto &var : resourceVars) {
  1107. if (var.isCounter()) {
  1108. if (!var.getCounterBinding()) {
  1109. // Process mX * c2
  1110. uint32_t set = 0;
  1111. if (const auto *vkBinding = var.getBinding())
  1112. set = vkBinding->getSet();
  1113. else if (const auto *reg = var.getRegister())
  1114. set = reg->RegisterSpace;
  1115. theBuilder.decorateDSetBinding(var.getSpirvId(), set,
  1116. bindingSet.useNextBinding(set));
  1117. }
  1118. } else if (!var.getBinding() && !var.getRegister()) {
  1119. // Process m3
  1120. theBuilder.decorateDSetBinding(var.getSpirvId(), 0,
  1121. bindingSet.useNextBinding(0));
  1122. }
  1123. }
  1124. return true;
  1125. }
  1126. bool DeclResultIdMapper::createStageVars(const hlsl::SigPoint *sigPoint,
  1127. const NamedDecl *decl, bool asInput,
  1128. QualType type, uint32_t arraySize,
  1129. const llvm::StringRef namePrefix,
  1130. llvm::Optional<uint32_t> invocationId,
  1131. uint32_t *value, bool noWriteBack,
  1132. SemanticInfo *inheritSemantic) {
  1133. // invocationId should only be used for handling HS per-vertex output.
  1134. if (invocationId.hasValue()) {
  1135. assert(shaderModel.IsHS() && arraySize != 0 && !asInput);
  1136. }
  1137. assert(inheritSemantic);
  1138. if (type->isVoidType()) {
  1139. // No stage variables will be created for void type.
  1140. return true;
  1141. }
  1142. uint32_t typeId = typeTranslator.translateType(type);
  1143. // We have several cases regarding HLSL semantics to handle here:
  1144. // * If the currrent decl inherits a semantic from some enclosing entity,
  1145. // use the inherited semantic no matter whether there is a semantic
  1146. // attached to the current decl.
  1147. // * If there is no semantic to inherit,
  1148. // * If the current decl is a struct,
  1149. // * If the current decl has a semantic, all its members inhert this
  1150. // decl's semantic, with the index sequentially increasing;
  1151. // * If the current decl does not have a semantic, all its members
  1152. // should have semantics attached;
  1153. // * If the current decl is not a struct, it should have semantic attached.
  1154. auto thisSemantic = getStageVarSemantic(decl);
  1155. // Which semantic we should use for this decl
  1156. auto *semanticToUse = &thisSemantic;
  1157. // Enclosing semantics override internal ones
  1158. if (inheritSemantic->isValid()) {
  1159. if (thisSemantic.isValid()) {
  1160. emitWarning(
  1161. "internal semantic '%0' overridden by enclosing semantic '%1'",
  1162. thisSemantic.loc)
  1163. << thisSemantic.str << inheritSemantic->str;
  1164. }
  1165. semanticToUse = inheritSemantic;
  1166. }
  1167. if (semanticToUse->isValid() &&
  1168. // Structs with attached semantics will be handled later.
  1169. !type->isStructureType()) {
  1170. // Found semantic attached directly to this Decl. This means we need to
  1171. // map this decl to a single stage variable.
  1172. if (!validateVKAttributes(decl))
  1173. return false;
  1174. const auto semanticKind = semanticToUse->getKind();
  1175. // Error out when the given semantic is invalid in this shader model
  1176. if (hlsl::SigPoint::GetInterpretation(semanticKind, sigPoint->GetKind(),
  1177. shaderModel.GetMajor(),
  1178. shaderModel.GetMinor()) ==
  1179. hlsl::DXIL::SemanticInterpretationKind::NA) {
  1180. emitError("invalid usage of semantic '%0' in shader profile %1",
  1181. decl->getLocation())
  1182. << semanticToUse->str << shaderModel.GetName();
  1183. return false;
  1184. }
  1185. if (!validateVKBuiltins(decl, sigPoint))
  1186. return false;
  1187. const auto *builtinAttr = decl->getAttr<VKBuiltInAttr>();
  1188. // Special handling of certain mappings between HLSL semantics and
  1189. // SPIR-V builtins:
  1190. // * SV_CullDistance/SV_ClipDistance are outsourced to GlPerVertex.
  1191. // * SV_DomainLocation can refer to a float2, whereas TessCoord is a float3.
  1192. // To ensure SPIR-V validity, we must create a float3 and extract a
  1193. // float2 from it before passing it to the main function.
  1194. // * SV_TessFactor is an array of size 2 for isoline patch, array of size 3
  1195. // for tri patch, and array of size 4 for quad patch, but it must always
  1196. // be an array of size 4 in SPIR-V for Vulkan.
  1197. // * SV_InsideTessFactor is a single float for tri patch, and an array of
  1198. // size 2 for a quad patch, but it must always be an array of size 2 in
  1199. // SPIR-V for Vulkan.
  1200. // * SV_Coverage is an uint value, but the builtin it corresponds to,
  1201. // SampleMask, must be an array of integers.
  1202. // * SV_InnerCoverage is an uint value, but the corresponding builtin,
  1203. // FullyCoveredEXT, must be an boolean value.
  1204. // * SV_DispatchThreadID, SV_GroupThreadID, and SV_GroupID are allowed to be
  1205. // uint, uint2, or uint3, but the corresponding builtins
  1206. // (GlobalInvocationId, LocalInvocationId, WorkgroupId) must be a uint3.
  1207. if (glPerVertex.tryToAccess(sigPoint->GetKind(), semanticKind,
  1208. semanticToUse->index, invocationId, value,
  1209. noWriteBack))
  1210. return true;
  1211. const uint32_t srcTypeId = typeId; // Variable type in source code
  1212. const QualType srcQualType = type; // Variable type in source code
  1213. uint32_t srcVecElemTypeId = 0; // Variable element type if vector
  1214. switch (semanticKind) {
  1215. case hlsl::Semantic::Kind::DomainLocation:
  1216. typeId = theBuilder.getVecType(theBuilder.getFloat32Type(), 3);
  1217. break;
  1218. case hlsl::Semantic::Kind::TessFactor:
  1219. typeId = theBuilder.getArrayType(theBuilder.getFloat32Type(),
  1220. theBuilder.getConstantUint32(4));
  1221. break;
  1222. case hlsl::Semantic::Kind::InsideTessFactor:
  1223. typeId = theBuilder.getArrayType(theBuilder.getFloat32Type(),
  1224. theBuilder.getConstantUint32(2));
  1225. break;
  1226. case hlsl::Semantic::Kind::Coverage:
  1227. typeId = theBuilder.getArrayType(typeId, theBuilder.getConstantUint32(1));
  1228. break;
  1229. case hlsl::Semantic::Kind::InnerCoverage:
  1230. typeId = theBuilder.getBoolType();
  1231. break;
  1232. case hlsl::Semantic::Kind::Barycentrics:
  1233. typeId = theBuilder.getVecType(theBuilder.getFloat32Type(), 2);
  1234. break;
  1235. case hlsl::Semantic::Kind::DispatchThreadID:
  1236. case hlsl::Semantic::Kind::GroupThreadID:
  1237. case hlsl::Semantic::Kind::GroupID:
  1238. // Keep the original integer signedness
  1239. srcVecElemTypeId = typeTranslator.translateType(
  1240. hlsl::IsHLSLVecType(type) ? hlsl::GetHLSLVecElementType(type) : type);
  1241. typeId = theBuilder.getVecType(srcVecElemTypeId, 3);
  1242. break;
  1243. default:
  1244. // Only the semantic kinds mentioned above are handled.
  1245. break;
  1246. }
  1247. // Boolean stage I/O variables must be represented as unsigned integers.
  1248. // Boolean built-in variables are represented as bool.
  1249. if (isBooleanStageIOVar(decl, type, semanticKind, sigPoint->GetKind())) {
  1250. type = typeTranslator.getUintTypeWithSourceComponents(type);
  1251. typeId = typeTranslator.translateType(type);
  1252. }
  1253. // Handle the extra arrayness
  1254. const uint32_t elementTypeId = typeId; // Array element's type
  1255. if (arraySize != 0)
  1256. typeId = theBuilder.getArrayType(typeId,
  1257. theBuilder.getConstantUint32(arraySize));
  1258. StageVar stageVar(
  1259. sigPoint, *semanticToUse, builtinAttr, typeId,
  1260. // For HS/DS/GS, we have already stripped the outmost arrayness on type.
  1261. typeTranslator.getLocationCount(type));
  1262. const auto name = namePrefix.str() + "." + stageVar.getSemanticStr();
  1263. const uint32_t varId =
  1264. createSpirvStageVar(&stageVar, decl, name, semanticToUse->loc);
  1265. if (varId == 0)
  1266. return false;
  1267. stageVar.setSpirvId(varId);
  1268. stageVar.setLocationAttr(decl->getAttr<VKLocationAttr>());
  1269. stageVar.setIndexAttr(decl->getAttr<VKIndexAttr>());
  1270. stageVars.push_back(stageVar);
  1271. // Emit OpDecorate* instructions to link this stage variable with the HLSL
  1272. // semantic it is created for
  1273. theBuilder.decorateHlslSemantic(varId, stageVar.getSemanticInfo().str);
  1274. // We have semantics attached to this decl, which means it must be a
  1275. // function/parameter/variable. All are DeclaratorDecls.
  1276. stageVarIds[cast<DeclaratorDecl>(decl)] = varId;
  1277. // Mark that we have used one index for this semantic
  1278. ++semanticToUse->index;
  1279. // Require extension and capability if using 16-bit types
  1280. if (typeTranslator.getElementSpirvBitwidth(type) == 16) {
  1281. theBuilder.addExtension(Extension::KHR_16bit_storage,
  1282. "16-bit stage IO variables", decl->getLocation());
  1283. theBuilder.requireCapability(spv::Capability::StorageInputOutput16);
  1284. }
  1285. // TODO: the following may not be correct?
  1286. if (sigPoint->GetSignatureKind() ==
  1287. hlsl::DXIL::SignatureKind::PatchConstant)
  1288. theBuilder.decoratePatch(varId);
  1289. // Decorate with interpolation modes for pixel shader input variables
  1290. if (shaderModel.IsPS() && sigPoint->IsInput() &&
  1291. // BaryCoord*AMD buitins already encode the interpolation mode.
  1292. semanticKind != hlsl::Semantic::Kind::Barycentrics)
  1293. decoratePSInterpolationMode(decl, type, varId);
  1294. if (asInput) {
  1295. *value = theBuilder.createLoad(typeId, varId);
  1296. // Fix ups for corner cases
  1297. // Special handling of SV_TessFactor DS patch constant input.
  1298. // TessLevelOuter is always an array of size 4 in SPIR-V, but
  1299. // SV_TessFactor could be an array of size 2, 3, or 4 in HLSL. Only the
  1300. // relevant indexes must be loaded.
  1301. if (semanticKind == hlsl::Semantic::Kind::TessFactor &&
  1302. hlsl::GetArraySize(type) != 4) {
  1303. llvm::SmallVector<uint32_t, 4> components;
  1304. const auto f32TypeId = theBuilder.getFloat32Type();
  1305. const auto tessFactorSize = hlsl::GetArraySize(type);
  1306. const auto arrType = theBuilder.getArrayType(
  1307. f32TypeId, theBuilder.getConstantUint32(tessFactorSize));
  1308. for (uint32_t i = 0; i < tessFactorSize; ++i)
  1309. components.push_back(
  1310. theBuilder.createCompositeExtract(f32TypeId, *value, {i}));
  1311. *value = theBuilder.createCompositeConstruct(arrType, components);
  1312. }
  1313. // Special handling of SV_InsideTessFactor DS patch constant input.
  1314. // TessLevelInner is always an array of size 2 in SPIR-V, but
  1315. // SV_InsideTessFactor could be an array of size 1 (scalar) or size 2 in
  1316. // HLSL. If SV_InsideTessFactor is a scalar, only extract index 0 of
  1317. // TessLevelInner.
  1318. else if (semanticKind == hlsl::Semantic::Kind::InsideTessFactor &&
  1319. // Some developers use float[1] instead of a scalar float.
  1320. (!type->isArrayType() || hlsl::GetArraySize(type) == 1)) {
  1321. const auto f32Type = theBuilder.getFloat32Type();
  1322. *value = theBuilder.createCompositeExtract(f32Type, *value, {0});
  1323. if (type->isArrayType()) // float[1]
  1324. *value = theBuilder.createCompositeConstruct(
  1325. theBuilder.getArrayType(f32Type, theBuilder.getConstantUint32(1)),
  1326. {*value});
  1327. }
  1328. // SV_DomainLocation can refer to a float2 or a float3, whereas TessCoord
  1329. // is always a float3. To ensure SPIR-V validity, a float3 stage variable
  1330. // is created, and we must extract a float2 from it before passing it to
  1331. // the main function.
  1332. else if (semanticKind == hlsl::Semantic::Kind::DomainLocation &&
  1333. hlsl::GetHLSLVecSize(type) != 3) {
  1334. const auto domainLocSize = hlsl::GetHLSLVecSize(type);
  1335. *value = theBuilder.createVectorShuffle(
  1336. theBuilder.getVecType(theBuilder.getFloat32Type(), domainLocSize),
  1337. *value, *value, {0, 1});
  1338. }
  1339. // Special handling of SV_Coverage, which is an uint value. We need to
  1340. // read SampleMask and extract its first element.
  1341. else if (semanticKind == hlsl::Semantic::Kind::Coverage) {
  1342. *value = theBuilder.createCompositeExtract(srcTypeId, *value, {0});
  1343. }
  1344. // Special handling of SV_InnerCoverage, which is an uint value. We need
  1345. // to read FullyCoveredEXT, which is a boolean value, and convert it to an
  1346. // uint value. According to D3D12 "Conservative Rasterization" doc: "The
  1347. // Pixel Shader has a 32-bit scalar integer System Generate Value
  1348. // available: InnerCoverage. This is a bit-field that has bit 0 from the
  1349. // LSB set to 1 for a given conservatively rasterized pixel, only when
  1350. // that pixel is guaranteed to be entirely inside the current primitive.
  1351. // All other input register bits must be set to 0 when bit 0 is not set,
  1352. // but are undefined when bit 0 is set to 1 (essentially, this bit-field
  1353. // represents a Boolean value where false must be exactly 0, but true can
  1354. // be any odd (i.e. bit 0 set) non-zero value)."
  1355. else if (semanticKind == hlsl::Semantic::Kind::InnerCoverage) {
  1356. const auto constOne = theBuilder.getConstantUint32(1);
  1357. const auto constZero = theBuilder.getConstantUint32(0);
  1358. *value = theBuilder.createSelect(theBuilder.getUint32Type(), *value,
  1359. constOne, constZero);
  1360. }
  1361. // Special handling of SV_Barycentrics, which is a float3, but the
  1362. // underlying stage input variable is a float2 (only provides the first
  1363. // two components). Calculate the third element.
  1364. else if (semanticKind == hlsl::Semantic::Kind::Barycentrics) {
  1365. const auto f32Type = theBuilder.getFloat32Type();
  1366. const auto x = theBuilder.createCompositeExtract(f32Type, *value, {0});
  1367. const auto y = theBuilder.createCompositeExtract(f32Type, *value, {1});
  1368. const auto xy =
  1369. theBuilder.createBinaryOp(spv::Op::OpFAdd, f32Type, x, y);
  1370. const auto z = theBuilder.createBinaryOp(
  1371. spv::Op::OpFSub, f32Type, theBuilder.getConstantFloat32(1), xy);
  1372. const auto v3f32Type = theBuilder.getVecType(f32Type, 3);
  1373. *value = theBuilder.createCompositeConstruct(v3f32Type, {x, y, z});
  1374. }
  1375. // Special handling of SV_DispatchThreadID and SV_GroupThreadID, which may
  1376. // be a uint or uint2, but the underlying stage input variable is a uint3.
  1377. // The last component(s) should be discarded in needed.
  1378. else if ((semanticKind == hlsl::Semantic::Kind::DispatchThreadID ||
  1379. semanticKind == hlsl::Semantic::Kind::GroupThreadID ||
  1380. semanticKind == hlsl::Semantic::Kind::GroupID) &&
  1381. (!hlsl::IsHLSLVecType(type) ||
  1382. hlsl::GetHLSLVecSize(type) != 3)) {
  1383. assert(srcVecElemTypeId);
  1384. const auto vecSize =
  1385. hlsl::IsHLSLVecType(type) ? hlsl::GetHLSLVecSize(type) : 1;
  1386. if (vecSize == 1)
  1387. *value =
  1388. theBuilder.createCompositeExtract(srcVecElemTypeId, *value, {0});
  1389. else if (vecSize == 2)
  1390. *value = theBuilder.createVectorShuffle(
  1391. theBuilder.getVecType(srcVecElemTypeId, 2), *value, *value,
  1392. {0, 1});
  1393. }
  1394. // Reciprocate SV_Position.w if requested
  1395. if (semanticKind == hlsl::Semantic::Kind::Position)
  1396. *value = invertWIfRequested(*value);
  1397. // Since boolean stage input variables are represented as unsigned
  1398. // integers, after loading them, we should cast them to boolean.
  1399. if (isBooleanStageIOVar(decl, srcQualType, semanticKind,
  1400. sigPoint->GetKind())) {
  1401. *value = theEmitter.castToType(*value, type, srcQualType,
  1402. decl->getLocation());
  1403. }
  1404. } else {
  1405. if (noWriteBack)
  1406. return true;
  1407. // Negate SV_Position.y if requested
  1408. if (semanticKind == hlsl::Semantic::Kind::Position)
  1409. *value = invertYIfRequested(*value);
  1410. uint32_t ptr = varId;
  1411. // Special handling of SV_TessFactor HS patch constant output.
  1412. // TessLevelOuter is always an array of size 4 in SPIR-V, but
  1413. // SV_TessFactor could be an array of size 2, 3, or 4 in HLSL. Only the
  1414. // relevant indexes must be written to.
  1415. if (semanticKind == hlsl::Semantic::Kind::TessFactor &&
  1416. hlsl::GetArraySize(type) != 4) {
  1417. const auto f32TypeId = theBuilder.getFloat32Type();
  1418. const auto tessFactorSize = hlsl::GetArraySize(type);
  1419. for (uint32_t i = 0; i < tessFactorSize; ++i) {
  1420. const uint32_t ptrType =
  1421. theBuilder.getPointerType(f32TypeId, spv::StorageClass::Output);
  1422. ptr = theBuilder.createAccessChain(ptrType, varId,
  1423. theBuilder.getConstantUint32(i));
  1424. theBuilder.createStore(
  1425. ptr, theBuilder.createCompositeExtract(f32TypeId, *value, i));
  1426. }
  1427. }
  1428. // Special handling of SV_InsideTessFactor HS patch constant output.
  1429. // TessLevelInner is always an array of size 2 in SPIR-V, but
  1430. // SV_InsideTessFactor could be an array of size 1 (scalar) or size 2 in
  1431. // HLSL. If SV_InsideTessFactor is a scalar, only write to index 0 of
  1432. // TessLevelInner.
  1433. else if (semanticKind == hlsl::Semantic::Kind::InsideTessFactor &&
  1434. // Some developers use float[1] instead of a scalar float.
  1435. (!type->isArrayType() || hlsl::GetArraySize(type) == 1)) {
  1436. const auto f32Type = theBuilder.getFloat32Type();
  1437. ptr = theBuilder.createAccessChain(
  1438. theBuilder.getPointerType(f32Type, spv::StorageClass::Output),
  1439. varId, theBuilder.getConstantUint32(0));
  1440. if (type->isArrayType()) // float[1]
  1441. *value = theBuilder.createCompositeExtract(f32Type, *value, {0});
  1442. theBuilder.createStore(ptr, *value);
  1443. }
  1444. // Special handling of SV_Coverage, which is an unit value. We need to
  1445. // write it to the first element in the SampleMask builtin.
  1446. else if (semanticKind == hlsl::Semantic::Kind::Coverage) {
  1447. ptr = theBuilder.createAccessChain(
  1448. theBuilder.getPointerType(srcTypeId, spv::StorageClass::Output),
  1449. varId, theBuilder.getConstantUint32(0));
  1450. theBuilder.createStore(ptr, *value);
  1451. }
  1452. // Special handling of HS ouput, for which we write to only one
  1453. // element in the per-vertex data array: the one indexed by
  1454. // SV_ControlPointID.
  1455. else if (invocationId.hasValue()) {
  1456. const uint32_t ptrType =
  1457. theBuilder.getPointerType(elementTypeId, spv::StorageClass::Output);
  1458. const uint32_t index = invocationId.getValue();
  1459. ptr = theBuilder.createAccessChain(ptrType, varId, index);
  1460. theBuilder.createStore(ptr, *value);
  1461. }
  1462. // Since boolean output stage variables are represented as unsigned
  1463. // integers, we must cast the value to uint before storing.
  1464. else if (isBooleanStageIOVar(decl, srcQualType, semanticKind,
  1465. sigPoint->GetKind())) {
  1466. *value = theEmitter.castToType(*value, srcQualType, type,
  1467. decl->getLocation());
  1468. theBuilder.createStore(ptr, *value);
  1469. }
  1470. // For all normal cases
  1471. else {
  1472. theBuilder.createStore(ptr, *value);
  1473. }
  1474. }
  1475. return true;
  1476. }
  1477. // If the decl itself doesn't have semantic string attached and there is no
  1478. // one to inherit, it should be a struct having all its fields with semantic
  1479. // strings.
  1480. if (!semanticToUse->isValid() && !type->isStructureType()) {
  1481. emitError("semantic string missing for shader %select{output|input}0 "
  1482. "variable '%1'",
  1483. decl->getLocation())
  1484. << asInput << decl->getName();
  1485. return false;
  1486. }
  1487. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  1488. if (asInput) {
  1489. // If this decl translates into multiple stage input variables, we need to
  1490. // load their values into a composite.
  1491. llvm::SmallVector<uint32_t, 4> subValues;
  1492. // If we have base classes, we need to handle them first.
  1493. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  1494. for (auto base : cxxDecl->bases()) {
  1495. uint32_t subValue = 0;
  1496. if (!createStageVars(sigPoint, base.getType()->getAsCXXRecordDecl(),
  1497. asInput, base.getType(), arraySize, namePrefix,
  1498. invocationId, &subValue, noWriteBack,
  1499. semanticToUse))
  1500. return false;
  1501. subValues.push_back(subValue);
  1502. }
  1503. for (const auto *field : structDecl->fields()) {
  1504. uint32_t subValue = 0;
  1505. if (!createStageVars(sigPoint, field, asInput, field->getType(),
  1506. arraySize, namePrefix, invocationId, &subValue,
  1507. noWriteBack, semanticToUse))
  1508. return false;
  1509. subValues.push_back(subValue);
  1510. }
  1511. if (arraySize == 0) {
  1512. *value = theBuilder.createCompositeConstruct(typeId, subValues);
  1513. return true;
  1514. }
  1515. // Handle the extra level of arrayness.
  1516. // We need to return an array of structs. But we get arrays of fields
  1517. // from visiting all fields. So now we need to extract all the elements
  1518. // at the same index of each field arrays and compose a new struct out
  1519. // of them.
  1520. const uint32_t structType = typeTranslator.translateType(type);
  1521. const uint32_t arrayType = theBuilder.getArrayType(
  1522. structType, theBuilder.getConstantUint32(arraySize));
  1523. llvm::SmallVector<uint32_t, 16> arrayElements;
  1524. for (uint32_t arrayIndex = 0; arrayIndex < arraySize; ++arrayIndex) {
  1525. llvm::SmallVector<uint32_t, 8> fields;
  1526. // If we have base classes, we need to handle them first.
  1527. if (const auto *cxxDecl = type->getAsCXXRecordDecl()) {
  1528. uint32_t baseIndex = 0;
  1529. for (auto base : cxxDecl->bases()) {
  1530. const auto baseType = typeTranslator.translateType(base.getType());
  1531. fields.push_back(theBuilder.createCompositeExtract(
  1532. baseType, subValues[baseIndex++], {arrayIndex}));
  1533. }
  1534. }
  1535. // Extract the element at index arrayIndex from each field
  1536. for (const auto *field : structDecl->fields()) {
  1537. const uint32_t fieldType =
  1538. typeTranslator.translateType(field->getType());
  1539. fields.push_back(theBuilder.createCompositeExtract(
  1540. fieldType,
  1541. subValues[getNumBaseClasses(type) + field->getFieldIndex()],
  1542. {arrayIndex}));
  1543. }
  1544. // Compose a new struct out of them
  1545. arrayElements.push_back(
  1546. theBuilder.createCompositeConstruct(structType, fields));
  1547. }
  1548. *value = theBuilder.createCompositeConstruct(arrayType, arrayElements);
  1549. } else {
  1550. // If we have base classes, we need to handle them first.
  1551. if (const auto *cxxDecl = type->getAsCXXRecordDecl()) {
  1552. uint32_t baseIndex = 0;
  1553. for (auto base : cxxDecl->bases()) {
  1554. uint32_t subValue = 0;
  1555. if (!noWriteBack)
  1556. subValue = theBuilder.createCompositeExtract(
  1557. typeTranslator.translateType(base.getType()), *value,
  1558. {baseIndex++});
  1559. if (!createStageVars(sigPoint, base.getType()->getAsCXXRecordDecl(),
  1560. asInput, base.getType(), arraySize, namePrefix,
  1561. invocationId, &subValue, noWriteBack,
  1562. semanticToUse))
  1563. return false;
  1564. }
  1565. }
  1566. // Unlike reading, which may require us to read stand-alone builtins and
  1567. // stage input variables and compose an array of structs out of them,
  1568. // it happens that we don't need to write an array of structs in a bunch
  1569. // for all shader stages:
  1570. //
  1571. // * VS: output is a single struct, without extra arrayness
  1572. // * HS: output is an array of structs, with extra arrayness,
  1573. // but we only write to the struct at the InvocationID index
  1574. // * DS: output is a single struct, without extra arrayness
  1575. // * GS: output is controlled by OpEmitVertex, one vertex per time
  1576. //
  1577. // The interesting shader stage is HS. We need the InvocationID to write
  1578. // out the value to the correct array element.
  1579. for (const auto *field : structDecl->fields()) {
  1580. const uint32_t fieldType = typeTranslator.translateType(field->getType());
  1581. uint32_t subValue = 0;
  1582. if (!noWriteBack)
  1583. subValue = theBuilder.createCompositeExtract(
  1584. fieldType, *value,
  1585. {getNumBaseClasses(type) + field->getFieldIndex()});
  1586. if (!createStageVars(sigPoint, field, asInput, field->getType(),
  1587. arraySize, namePrefix, invocationId, &subValue,
  1588. noWriteBack, semanticToUse))
  1589. return false;
  1590. }
  1591. }
  1592. return true;
  1593. }
  1594. bool DeclResultIdMapper::writeBackOutputStream(const NamedDecl *decl,
  1595. QualType type, uint32_t value) {
  1596. assert(shaderModel.IsGS()); // Only for GS use
  1597. if (hlsl::IsHLSLStreamOutputType(type))
  1598. type = hlsl::GetHLSLResourceResultType(type);
  1599. if (hasGSPrimitiveTypeQualifier(decl))
  1600. type = astContext.getAsConstantArrayType(type)->getElementType();
  1601. auto semanticInfo = getStageVarSemantic(decl);
  1602. if (semanticInfo.isValid()) {
  1603. // Found semantic attached directly to this Decl. Write the value for this
  1604. // Decl to the corresponding stage output variable.
  1605. // Handle SV_Position, SV_ClipDistance, and SV_CullDistance
  1606. if (glPerVertex.tryToAccess(
  1607. hlsl::DXIL::SigPointKind::GSOut, semanticInfo.semantic->GetKind(),
  1608. semanticInfo.index, llvm::None, &value, /*noWriteBack=*/false))
  1609. return true;
  1610. // Query the <result-id> for the stage output variable generated out
  1611. // of this decl.
  1612. // We have semantic string attached to this decl; therefore, it must be a
  1613. // DeclaratorDecl.
  1614. const auto found = stageVarIds.find(cast<DeclaratorDecl>(decl));
  1615. // We should have recorded its stage output variable previously.
  1616. assert(found != stageVarIds.end());
  1617. // Negate SV_Position.y if requested
  1618. if (semanticInfo.semantic->GetKind() == hlsl::Semantic::Kind::Position)
  1619. value = invertYIfRequested(value);
  1620. // Boolean stage output variables are represented as unsigned integers.
  1621. if (isBooleanStageIOVar(decl, type, semanticInfo.semantic->GetKind(),
  1622. hlsl::SigPoint::Kind::GSOut)) {
  1623. QualType uintType = typeTranslator.getUintTypeWithSourceComponents(type);
  1624. value = theEmitter.castToType(value, type, uintType, decl->getLocation());
  1625. }
  1626. theBuilder.createStore(found->second, value);
  1627. return true;
  1628. }
  1629. // If the decl itself doesn't have semantic string attached, it should be
  1630. // a struct having all its fields with semantic strings.
  1631. if (!type->isStructureType()) {
  1632. emitError("semantic string missing for shader output variable '%0'",
  1633. decl->getLocation())
  1634. << decl->getName();
  1635. return false;
  1636. }
  1637. // If we have base classes, we need to handle them first.
  1638. if (const auto *cxxDecl = type->getAsCXXRecordDecl()) {
  1639. uint32_t baseIndex = 0;
  1640. for (auto base : cxxDecl->bases()) {
  1641. const auto baseType = typeTranslator.translateType(base.getType());
  1642. const auto subValue =
  1643. theBuilder.createCompositeExtract(baseType, value, {baseIndex++});
  1644. if (!writeBackOutputStream(base.getType()->getAsCXXRecordDecl(),
  1645. base.getType(), subValue))
  1646. return false;
  1647. }
  1648. }
  1649. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  1650. // Write out each field
  1651. for (const auto *field : structDecl->fields()) {
  1652. const uint32_t fieldType = typeTranslator.translateType(field->getType());
  1653. const uint32_t subValue = theBuilder.createCompositeExtract(
  1654. fieldType, value, {getNumBaseClasses(type) + field->getFieldIndex()});
  1655. if (!writeBackOutputStream(field, field->getType(), subValue))
  1656. return false;
  1657. }
  1658. return true;
  1659. }
  1660. uint32_t DeclResultIdMapper::invertYIfRequested(uint32_t position) {
  1661. // Negate SV_Position.y if requested
  1662. if (spirvOptions.invertY) {
  1663. const auto f32Type = theBuilder.getFloat32Type();
  1664. const auto v4f32Type = theBuilder.getVecType(f32Type, 4);
  1665. const auto oldY = theBuilder.createCompositeExtract(f32Type, position, {1});
  1666. const auto newY =
  1667. theBuilder.createUnaryOp(spv::Op::OpFNegate, f32Type, oldY);
  1668. position = theBuilder.createCompositeInsert(v4f32Type, position, {1}, newY);
  1669. }
  1670. return position;
  1671. }
  1672. uint32_t DeclResultIdMapper::invertWIfRequested(uint32_t position) {
  1673. // Reciprocate SV_Position.w if requested
  1674. if (spirvOptions.invertW && shaderModel.IsPS()) {
  1675. const auto f32Type = theBuilder.getFloat32Type();
  1676. const auto v4f32Type = theBuilder.getVecType(f32Type, 4);
  1677. const auto oldW = theBuilder.createCompositeExtract(f32Type, position, {3});
  1678. const auto newW = theBuilder.createBinaryOp(
  1679. spv::Op::OpFDiv, f32Type, theBuilder.getConstantFloat32(1), oldW);
  1680. position = theBuilder.createCompositeInsert(v4f32Type, position, {3}, newW);
  1681. }
  1682. return position;
  1683. }
  1684. void DeclResultIdMapper::decoratePSInterpolationMode(const NamedDecl *decl,
  1685. QualType type,
  1686. uint32_t varId) {
  1687. const QualType elemType = typeTranslator.getElementType(type);
  1688. if (elemType->isBooleanType() || elemType->isIntegerType()) {
  1689. // TODO: Probably we can call hlsl::ValidateSignatureElement() for the
  1690. // following check.
  1691. if (decl->getAttr<HLSLLinearAttr>() || decl->getAttr<HLSLCentroidAttr>() ||
  1692. decl->getAttr<HLSLNoPerspectiveAttr>() ||
  1693. decl->getAttr<HLSLSampleAttr>()) {
  1694. emitError("only nointerpolation mode allowed for integer input "
  1695. "parameters in pixel shader",
  1696. decl->getLocation());
  1697. } else {
  1698. theBuilder.decorateFlat(varId);
  1699. }
  1700. } else {
  1701. // Do nothing for HLSLLinearAttr since its the default
  1702. // Attributes can be used together. So cannot use else if.
  1703. if (decl->getAttr<HLSLCentroidAttr>())
  1704. theBuilder.decorateCentroid(varId);
  1705. if (decl->getAttr<HLSLNoInterpolationAttr>())
  1706. theBuilder.decorateFlat(varId);
  1707. if (decl->getAttr<HLSLNoPerspectiveAttr>())
  1708. theBuilder.decorateNoPerspective(varId);
  1709. if (decl->getAttr<HLSLSampleAttr>()) {
  1710. theBuilder.requireCapability(spv::Capability::SampleRateShading);
  1711. theBuilder.decorateSample(varId);
  1712. }
  1713. }
  1714. }
  1715. uint32_t DeclResultIdMapper::getBuiltinVar(spv::BuiltIn builtIn) {
  1716. // Guarantee uniqueness
  1717. switch (builtIn) {
  1718. case spv::BuiltIn::SubgroupSize:
  1719. if (laneCountBuiltinId)
  1720. return laneCountBuiltinId;
  1721. break;
  1722. case spv::BuiltIn::SubgroupLocalInvocationId:
  1723. if (laneIndexBuiltinId)
  1724. return laneIndexBuiltinId;
  1725. break;
  1726. default:
  1727. // Only allow the two cases we know about
  1728. assert(false && "unsupported builtin case");
  1729. return 0;
  1730. }
  1731. theBuilder.requireCapability(spv::Capability::GroupNonUniform);
  1732. uint32_t type = theBuilder.getUint32Type();
  1733. // Create a dummy StageVar for this builtin variable
  1734. const uint32_t varId =
  1735. theBuilder.addStageBuiltinVar(type, spv::StorageClass::Input, builtIn);
  1736. const hlsl::SigPoint *sigPoint =
  1737. hlsl::SigPoint::GetSigPoint(hlsl::SigPointFromInputQual(
  1738. hlsl::DxilParamInputQual::In, shaderModel.GetKind(),
  1739. /*isPatchConstant=*/false));
  1740. StageVar stageVar(sigPoint, /*semaInfo=*/{}, /*builtinAttr=*/nullptr, type,
  1741. /*locCount=*/0);
  1742. stageVar.setIsSpirvBuiltin();
  1743. stageVar.setSpirvId(varId);
  1744. stageVars.push_back(stageVar);
  1745. switch (builtIn) {
  1746. case spv::BuiltIn::SubgroupSize:
  1747. laneCountBuiltinId = varId;
  1748. break;
  1749. case spv::BuiltIn::SubgroupLocalInvocationId:
  1750. laneIndexBuiltinId = varId;
  1751. break;
  1752. default:
  1753. // Only relevant to subgroup builtins.
  1754. break;
  1755. }
  1756. return varId;
  1757. }
  1758. uint32_t DeclResultIdMapper::createSpirvStageVar(StageVar *stageVar,
  1759. const NamedDecl *decl,
  1760. const llvm::StringRef name,
  1761. SourceLocation srcLoc) {
  1762. using spv::BuiltIn;
  1763. const auto sigPoint = stageVar->getSigPoint();
  1764. const auto semanticKind = stageVar->getSemanticInfo().getKind();
  1765. const auto sigPointKind = sigPoint->GetKind();
  1766. const uint32_t type = stageVar->getSpirvTypeId();
  1767. spv::StorageClass sc = getStorageClassForSigPoint(sigPoint);
  1768. if (sc == spv::StorageClass::Max)
  1769. return 0;
  1770. stageVar->setStorageClass(sc);
  1771. // [[vk::builtin(...)]] takes precedence.
  1772. if (const auto *builtinAttr = stageVar->getBuiltInAttr()) {
  1773. const auto spvBuiltIn =
  1774. llvm::StringSwitch<BuiltIn>(builtinAttr->getBuiltIn())
  1775. .Case("PointSize", BuiltIn::PointSize)
  1776. .Case("HelperInvocation", BuiltIn::HelperInvocation)
  1777. .Case("BaseVertex", BuiltIn::BaseVertex)
  1778. .Case("BaseInstance", BuiltIn::BaseInstance)
  1779. .Case("DrawIndex", BuiltIn::DrawIndex)
  1780. .Case("DeviceIndex", BuiltIn::DeviceIndex)
  1781. .Default(BuiltIn::Max);
  1782. assert(spvBuiltIn != BuiltIn::Max); // The frontend should guarantee this.
  1783. switch (spvBuiltIn) {
  1784. case BuiltIn::BaseVertex:
  1785. case BuiltIn::BaseInstance:
  1786. case BuiltIn::DrawIndex:
  1787. theBuilder.addExtension(Extension::KHR_shader_draw_parameters,
  1788. builtinAttr->getBuiltIn(),
  1789. builtinAttr->getLocation());
  1790. theBuilder.requireCapability(spv::Capability::DrawParameters);
  1791. break;
  1792. case BuiltIn::DeviceIndex:
  1793. theBuilder.addExtension(Extension::KHR_device_group,
  1794. stageVar->getSemanticStr(), srcLoc);
  1795. theBuilder.requireCapability(spv::Capability::DeviceGroup);
  1796. break;
  1797. default:
  1798. // Just seeking builtins requiring extensions. The rest can be ignored.
  1799. break;
  1800. }
  1801. return theBuilder.addStageBuiltinVar(type, sc, spvBuiltIn);
  1802. }
  1803. // The following translation assumes that semantic validity in the current
  1804. // shader model is already checked, so it only covers valid SigPoints for
  1805. // each semantic.
  1806. switch (semanticKind) {
  1807. // According to DXIL spec, the Position SV can be used by all SigPoints
  1808. // other than PCIn, HSIn, GSIn, PSOut, CSIn.
  1809. // According to Vulkan spec, the Position BuiltIn can only be used
  1810. // by VSOut, HS/DS/GS In/Out.
  1811. case hlsl::Semantic::Kind::Position: {
  1812. switch (sigPointKind) {
  1813. case hlsl::SigPoint::Kind::VSIn:
  1814. case hlsl::SigPoint::Kind::PCOut:
  1815. case hlsl::SigPoint::Kind::DSIn:
  1816. return theBuilder.addStageIOVar(type, sc, name.str());
  1817. case hlsl::SigPoint::Kind::VSOut:
  1818. case hlsl::SigPoint::Kind::HSCPIn:
  1819. case hlsl::SigPoint::Kind::HSCPOut:
  1820. case hlsl::SigPoint::Kind::DSCPIn:
  1821. case hlsl::SigPoint::Kind::DSOut:
  1822. case hlsl::SigPoint::Kind::GSVIn:
  1823. case hlsl::SigPoint::Kind::GSOut:
  1824. stageVar->setIsSpirvBuiltin();
  1825. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::Position);
  1826. case hlsl::SigPoint::Kind::PSIn:
  1827. stageVar->setIsSpirvBuiltin();
  1828. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::FragCoord);
  1829. default:
  1830. llvm_unreachable("invalid usage of SV_Position sneaked in");
  1831. }
  1832. }
  1833. // According to DXIL spec, the VertexID SV can only be used by VSIn.
  1834. // According to Vulkan spec, the VertexIndex BuiltIn can only be used by
  1835. // VSIn.
  1836. case hlsl::Semantic::Kind::VertexID: {
  1837. stageVar->setIsSpirvBuiltin();
  1838. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::VertexIndex);
  1839. }
  1840. // According to DXIL spec, the InstanceID SV can be used by VSIn, VSOut,
  1841. // HSCPIn, HSCPOut, DSCPIn, DSOut, GSVIn, GSOut, PSIn.
  1842. // According to Vulkan spec, the InstanceIndex BuitIn can only be used by
  1843. // VSIn.
  1844. case hlsl::Semantic::Kind::InstanceID: {
  1845. switch (sigPointKind) {
  1846. case hlsl::SigPoint::Kind::VSIn:
  1847. stageVar->setIsSpirvBuiltin();
  1848. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::InstanceIndex);
  1849. case hlsl::SigPoint::Kind::VSOut:
  1850. case hlsl::SigPoint::Kind::HSCPIn:
  1851. case hlsl::SigPoint::Kind::HSCPOut:
  1852. case hlsl::SigPoint::Kind::DSCPIn:
  1853. case hlsl::SigPoint::Kind::DSOut:
  1854. case hlsl::SigPoint::Kind::GSVIn:
  1855. case hlsl::SigPoint::Kind::GSOut:
  1856. case hlsl::SigPoint::Kind::PSIn:
  1857. return theBuilder.addStageIOVar(type, sc, name.str());
  1858. default:
  1859. llvm_unreachable("invalid usage of SV_InstanceID sneaked in");
  1860. }
  1861. }
  1862. // According to DXIL spec, the Depth{|GreaterEqual|LessEqual} SV can only be
  1863. // used by PSOut.
  1864. // According to Vulkan spec, the FragDepth BuiltIn can only be used by PSOut.
  1865. case hlsl::Semantic::Kind::Depth:
  1866. case hlsl::Semantic::Kind::DepthGreaterEqual:
  1867. case hlsl::Semantic::Kind::DepthLessEqual: {
  1868. stageVar->setIsSpirvBuiltin();
  1869. // Vulkan requires the DepthReplacing execution mode to write to FragDepth.
  1870. theBuilder.addExecutionMode(entryFunctionId,
  1871. spv::ExecutionMode::DepthReplacing, {});
  1872. if (semanticKind == hlsl::Semantic::Kind::DepthGreaterEqual)
  1873. theBuilder.addExecutionMode(entryFunctionId,
  1874. spv::ExecutionMode::DepthGreater, {});
  1875. else if (semanticKind == hlsl::Semantic::Kind::DepthLessEqual)
  1876. theBuilder.addExecutionMode(entryFunctionId,
  1877. spv::ExecutionMode::DepthLess, {});
  1878. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::FragDepth);
  1879. }
  1880. // According to DXIL spec, the ClipDistance/CullDistance SV can be used by all
  1881. // SigPoints other than PCIn, HSIn, GSIn, PSOut, CSIn.
  1882. // According to Vulkan spec, the ClipDistance/CullDistance BuiltIn can only
  1883. // be
  1884. // used by VSOut, HS/DS/GS In/Out.
  1885. case hlsl::Semantic::Kind::ClipDistance:
  1886. case hlsl::Semantic::Kind::CullDistance: {
  1887. switch (sigPointKind) {
  1888. case hlsl::SigPoint::Kind::VSIn:
  1889. case hlsl::SigPoint::Kind::PCOut:
  1890. case hlsl::SigPoint::Kind::DSIn:
  1891. return theBuilder.addStageIOVar(type, sc, name.str());
  1892. case hlsl::SigPoint::Kind::VSOut:
  1893. case hlsl::SigPoint::Kind::HSCPIn:
  1894. case hlsl::SigPoint::Kind::HSCPOut:
  1895. case hlsl::SigPoint::Kind::DSCPIn:
  1896. case hlsl::SigPoint::Kind::DSOut:
  1897. case hlsl::SigPoint::Kind::GSVIn:
  1898. case hlsl::SigPoint::Kind::GSOut:
  1899. case hlsl::SigPoint::Kind::PSIn:
  1900. llvm_unreachable("should be handled in gl_PerVertex struct");
  1901. default:
  1902. llvm_unreachable(
  1903. "invalid usage of SV_ClipDistance/SV_CullDistance sneaked in");
  1904. }
  1905. }
  1906. // According to DXIL spec, the IsFrontFace SV can only be used by GSOut and
  1907. // PSIn.
  1908. // According to Vulkan spec, the FrontFacing BuitIn can only be used in PSIn.
  1909. case hlsl::Semantic::Kind::IsFrontFace: {
  1910. switch (sigPointKind) {
  1911. case hlsl::SigPoint::Kind::GSOut:
  1912. return theBuilder.addStageIOVar(type, sc, name.str());
  1913. case hlsl::SigPoint::Kind::PSIn:
  1914. stageVar->setIsSpirvBuiltin();
  1915. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::FrontFacing);
  1916. default:
  1917. llvm_unreachable("invalid usage of SV_IsFrontFace sneaked in");
  1918. }
  1919. }
  1920. // According to DXIL spec, the Target SV can only be used by PSOut.
  1921. // There is no corresponding builtin decoration in SPIR-V. So generate normal
  1922. // Vulkan stage input/output variables.
  1923. case hlsl::Semantic::Kind::Target:
  1924. // An arbitrary semantic is defined by users. Generate normal Vulkan stage
  1925. // input/output variables.
  1926. case hlsl::Semantic::Kind::Arbitrary: {
  1927. return theBuilder.addStageIOVar(type, sc, name.str());
  1928. // TODO: patch constant function in hull shader
  1929. }
  1930. // According to DXIL spec, the DispatchThreadID SV can only be used by CSIn.
  1931. // According to Vulkan spec, the GlobalInvocationId can only be used in CSIn.
  1932. case hlsl::Semantic::Kind::DispatchThreadID: {
  1933. stageVar->setIsSpirvBuiltin();
  1934. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::GlobalInvocationId);
  1935. }
  1936. // According to DXIL spec, the GroupID SV can only be used by CSIn.
  1937. // According to Vulkan spec, the WorkgroupId can only be used in CSIn.
  1938. case hlsl::Semantic::Kind::GroupID: {
  1939. stageVar->setIsSpirvBuiltin();
  1940. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::WorkgroupId);
  1941. }
  1942. // According to DXIL spec, the GroupThreadID SV can only be used by CSIn.
  1943. // According to Vulkan spec, the LocalInvocationId can only be used in CSIn.
  1944. case hlsl::Semantic::Kind::GroupThreadID: {
  1945. stageVar->setIsSpirvBuiltin();
  1946. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::LocalInvocationId);
  1947. }
  1948. // According to DXIL spec, the GroupIndex SV can only be used by CSIn.
  1949. // According to Vulkan spec, the LocalInvocationIndex can only be used in
  1950. // CSIn.
  1951. case hlsl::Semantic::Kind::GroupIndex: {
  1952. stageVar->setIsSpirvBuiltin();
  1953. return theBuilder.addStageBuiltinVar(type, sc,
  1954. BuiltIn::LocalInvocationIndex);
  1955. }
  1956. // According to DXIL spec, the OutputControlID SV can only be used by HSIn.
  1957. // According to Vulkan spec, the InvocationId BuiltIn can only be used in
  1958. // HS/GS In.
  1959. case hlsl::Semantic::Kind::OutputControlPointID: {
  1960. stageVar->setIsSpirvBuiltin();
  1961. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::InvocationId);
  1962. }
  1963. // According to DXIL spec, the PrimitiveID SV can only be used by PCIn, HSIn,
  1964. // DSIn, GSIn, GSOut, and PSIn.
  1965. // According to Vulkan spec, the PrimitiveId BuiltIn can only be used in
  1966. // HS/DS/PS In, GS In/Out.
  1967. case hlsl::Semantic::Kind::PrimitiveID: {
  1968. // PrimitiveId requires either Tessellation or Geometry capability.
  1969. // Need to require one for PSIn.
  1970. if (sigPointKind == hlsl::SigPoint::Kind::PSIn)
  1971. theBuilder.requireCapability(spv::Capability::Geometry);
  1972. // Translate to PrimitiveId BuiltIn for all valid SigPoints.
  1973. stageVar->setIsSpirvBuiltin();
  1974. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::PrimitiveId);
  1975. }
  1976. // According to DXIL spec, the TessFactor SV can only be used by PCOut and
  1977. // DSIn.
  1978. // According to Vulkan spec, the TessLevelOuter BuiltIn can only be used in
  1979. // PCOut and DSIn.
  1980. case hlsl::Semantic::Kind::TessFactor: {
  1981. stageVar->setIsSpirvBuiltin();
  1982. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::TessLevelOuter);
  1983. }
  1984. // According to DXIL spec, the InsideTessFactor SV can only be used by PCOut
  1985. // and DSIn.
  1986. // According to Vulkan spec, the TessLevelInner BuiltIn can only be used in
  1987. // PCOut and DSIn.
  1988. case hlsl::Semantic::Kind::InsideTessFactor: {
  1989. stageVar->setIsSpirvBuiltin();
  1990. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::TessLevelInner);
  1991. }
  1992. // According to DXIL spec, the DomainLocation SV can only be used by DSIn.
  1993. // According to Vulkan spec, the TessCoord BuiltIn can only be used in DSIn.
  1994. case hlsl::Semantic::Kind::DomainLocation: {
  1995. stageVar->setIsSpirvBuiltin();
  1996. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::TessCoord);
  1997. }
  1998. // According to DXIL spec, the GSInstanceID SV can only be used by GSIn.
  1999. // According to Vulkan spec, the InvocationId BuiltIn can only be used in
  2000. // HS/GS In.
  2001. case hlsl::Semantic::Kind::GSInstanceID: {
  2002. stageVar->setIsSpirvBuiltin();
  2003. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::InvocationId);
  2004. }
  2005. // According to DXIL spec, the SampleIndex SV can only be used by PSIn.
  2006. // According to Vulkan spec, the SampleId BuiltIn can only be used in PSIn.
  2007. case hlsl::Semantic::Kind::SampleIndex: {
  2008. theBuilder.requireCapability(spv::Capability::SampleRateShading);
  2009. stageVar->setIsSpirvBuiltin();
  2010. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::SampleId);
  2011. }
  2012. // According to DXIL spec, the StencilRef SV can only be used by PSOut.
  2013. case hlsl::Semantic::Kind::StencilRef: {
  2014. theBuilder.addExtension(Extension::EXT_shader_stencil_export,
  2015. stageVar->getSemanticStr(), srcLoc);
  2016. theBuilder.requireCapability(spv::Capability::StencilExportEXT);
  2017. stageVar->setIsSpirvBuiltin();
  2018. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::FragStencilRefEXT);
  2019. }
  2020. // According to DXIL spec, the ViewID SV can only be used by PSIn.
  2021. case hlsl::Semantic::Kind::Barycentrics: {
  2022. theBuilder.addExtension(Extension::AMD_shader_explicit_vertex_parameter,
  2023. stageVar->getSemanticStr(), srcLoc);
  2024. stageVar->setIsSpirvBuiltin();
  2025. // Selecting the correct builtin according to interpolation mode
  2026. auto bi = BuiltIn::Max;
  2027. if (decl->hasAttr<HLSLNoPerspectiveAttr>()) {
  2028. if (decl->hasAttr<HLSLCentroidAttr>()) {
  2029. bi = BuiltIn::BaryCoordNoPerspCentroidAMD;
  2030. } else if (decl->hasAttr<HLSLSampleAttr>()) {
  2031. bi = BuiltIn::BaryCoordNoPerspSampleAMD;
  2032. } else {
  2033. bi = BuiltIn::BaryCoordNoPerspAMD;
  2034. }
  2035. } else {
  2036. if (decl->hasAttr<HLSLCentroidAttr>()) {
  2037. bi = BuiltIn::BaryCoordSmoothCentroidAMD;
  2038. } else if (decl->hasAttr<HLSLSampleAttr>()) {
  2039. bi = BuiltIn::BaryCoordSmoothSampleAMD;
  2040. } else {
  2041. bi = BuiltIn::BaryCoordSmoothAMD;
  2042. }
  2043. }
  2044. return theBuilder.addStageBuiltinVar(type, sc, bi);
  2045. }
  2046. // According to DXIL spec, the RenderTargetArrayIndex SV can only be used by
  2047. // VSIn, VSOut, HSCPIn, HSCPOut, DSIn, DSOut, GSVIn, GSOut, PSIn.
  2048. // According to Vulkan spec, the Layer BuiltIn can only be used in GSOut and
  2049. // PSIn.
  2050. case hlsl::Semantic::Kind::RenderTargetArrayIndex: {
  2051. switch (sigPointKind) {
  2052. case hlsl::SigPoint::Kind::VSIn:
  2053. case hlsl::SigPoint::Kind::HSCPIn:
  2054. case hlsl::SigPoint::Kind::HSCPOut:
  2055. case hlsl::SigPoint::Kind::PCOut:
  2056. case hlsl::SigPoint::Kind::DSIn:
  2057. case hlsl::SigPoint::Kind::DSCPIn:
  2058. case hlsl::SigPoint::Kind::GSVIn:
  2059. return theBuilder.addStageIOVar(type, sc, name.str());
  2060. case hlsl::SigPoint::Kind::VSOut:
  2061. case hlsl::SigPoint::Kind::DSOut:
  2062. theBuilder.addExtension(Extension::EXT_shader_viewport_index_layer,
  2063. "SV_RenderTargetArrayIndex", srcLoc);
  2064. theBuilder.requireCapability(
  2065. spv::Capability::ShaderViewportIndexLayerEXT);
  2066. stageVar->setIsSpirvBuiltin();
  2067. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::Layer);
  2068. case hlsl::SigPoint::Kind::GSOut:
  2069. case hlsl::SigPoint::Kind::PSIn:
  2070. theBuilder.requireCapability(spv::Capability::Geometry);
  2071. stageVar->setIsSpirvBuiltin();
  2072. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::Layer);
  2073. default:
  2074. llvm_unreachable("invalid usage of SV_RenderTargetArrayIndex sneaked in");
  2075. }
  2076. }
  2077. // According to DXIL spec, the ViewportArrayIndex SV can only be used by
  2078. // VSIn, VSOut, HSCPIn, HSCPOut, DSIn, DSOut, GSVIn, GSOut, PSIn.
  2079. // According to Vulkan spec, the ViewportIndex BuiltIn can only be used in
  2080. // GSOut and PSIn.
  2081. case hlsl::Semantic::Kind::ViewPortArrayIndex: {
  2082. switch (sigPointKind) {
  2083. case hlsl::SigPoint::Kind::VSIn:
  2084. case hlsl::SigPoint::Kind::HSCPIn:
  2085. case hlsl::SigPoint::Kind::HSCPOut:
  2086. case hlsl::SigPoint::Kind::PCOut:
  2087. case hlsl::SigPoint::Kind::DSIn:
  2088. case hlsl::SigPoint::Kind::DSCPIn:
  2089. case hlsl::SigPoint::Kind::GSVIn:
  2090. return theBuilder.addStageIOVar(type, sc, name.str());
  2091. case hlsl::SigPoint::Kind::VSOut:
  2092. case hlsl::SigPoint::Kind::DSOut:
  2093. theBuilder.addExtension(Extension::EXT_shader_viewport_index_layer,
  2094. "SV_ViewPortArrayIndex", srcLoc);
  2095. theBuilder.requireCapability(
  2096. spv::Capability::ShaderViewportIndexLayerEXT);
  2097. stageVar->setIsSpirvBuiltin();
  2098. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::ViewportIndex);
  2099. case hlsl::SigPoint::Kind::GSOut:
  2100. case hlsl::SigPoint::Kind::PSIn:
  2101. theBuilder.requireCapability(spv::Capability::MultiViewport);
  2102. stageVar->setIsSpirvBuiltin();
  2103. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::ViewportIndex);
  2104. default:
  2105. llvm_unreachable("invalid usage of SV_ViewportArrayIndex sneaked in");
  2106. }
  2107. }
  2108. // According to DXIL spec, the Coverage SV can only be used by PSIn and PSOut.
  2109. // According to Vulkan spec, the SampleMask BuiltIn can only be used in
  2110. // PSIn and PSOut.
  2111. case hlsl::Semantic::Kind::Coverage: {
  2112. stageVar->setIsSpirvBuiltin();
  2113. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::SampleMask);
  2114. }
  2115. // According to DXIL spec, the ViewID SV can only be used by VSIn, PCIn,
  2116. // HSIn, DSIn, GSIn, PSIn.
  2117. // According to Vulkan spec, the ViewIndex BuiltIn can only be used in
  2118. // VS/HS/DS/GS/PS input.
  2119. case hlsl::Semantic::Kind::ViewID: {
  2120. theBuilder.addExtension(Extension::KHR_multiview,
  2121. stageVar->getSemanticStr(), srcLoc);
  2122. theBuilder.requireCapability(spv::Capability::MultiView);
  2123. stageVar->setIsSpirvBuiltin();
  2124. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::ViewIndex);
  2125. }
  2126. // According to DXIL spec, the InnerCoverage SV can only be used as PSIn.
  2127. // According to Vulkan spec, the FullyCoveredEXT BuiltIn can only be used as
  2128. // PSIn.
  2129. case hlsl::Semantic::Kind::InnerCoverage: {
  2130. theBuilder.addExtension(Extension::EXT_fragment_fully_covered,
  2131. stageVar->getSemanticStr(), srcLoc);
  2132. theBuilder.requireCapability(spv::Capability::FragmentFullyCoveredEXT);
  2133. stageVar->setIsSpirvBuiltin();
  2134. return theBuilder.addStageBuiltinVar(type, sc, BuiltIn::FullyCoveredEXT);
  2135. }
  2136. default:
  2137. emitError("semantic %0 unimplemented", srcLoc)
  2138. << stageVar->getSemanticStr();
  2139. break;
  2140. }
  2141. return 0;
  2142. }
  2143. bool DeclResultIdMapper::validateVKAttributes(const NamedDecl *decl) {
  2144. bool success = true;
  2145. if (const auto *idxAttr = decl->getAttr<VKIndexAttr>()) {
  2146. if (!shaderModel.IsPS()) {
  2147. emitError("vk::index only allowed in pixel shader",
  2148. idxAttr->getLocation());
  2149. success = false;
  2150. }
  2151. const auto *locAttr = decl->getAttr<VKLocationAttr>();
  2152. if (!locAttr) {
  2153. emitError("vk::index should be used together with vk::location for "
  2154. "dual-source blending",
  2155. idxAttr->getLocation());
  2156. success = false;
  2157. } else {
  2158. const auto locNumber = locAttr->getNumber();
  2159. if (locNumber != 0) {
  2160. emitError("dual-source blending should use vk::location 0",
  2161. locAttr->getLocation());
  2162. success = false;
  2163. }
  2164. }
  2165. const auto idxNumber = idxAttr->getNumber();
  2166. if (idxNumber != 0 && idxNumber != 1) {
  2167. emitError("dual-source blending only accepts 0 or 1 as vk::index",
  2168. idxAttr->getLocation());
  2169. success = false;
  2170. }
  2171. }
  2172. return success;
  2173. }
  2174. bool DeclResultIdMapper::validateVKBuiltins(const NamedDecl *decl,
  2175. const hlsl::SigPoint *sigPoint) {
  2176. bool success = true;
  2177. if (const auto *builtinAttr = decl->getAttr<VKBuiltInAttr>()) {
  2178. // The front end parsing only allows vk::builtin to be attached to a
  2179. // function/parameter/variable; all of them are DeclaratorDecls.
  2180. const auto declType = getTypeOrFnRetType(cast<DeclaratorDecl>(decl));
  2181. const auto loc = builtinAttr->getLocation();
  2182. if (decl->hasAttr<VKLocationAttr>()) {
  2183. emitError("cannot use vk::builtin and vk::location together", loc);
  2184. success = false;
  2185. }
  2186. const llvm::StringRef builtin = builtinAttr->getBuiltIn();
  2187. if (builtin == "HelperInvocation") {
  2188. if (!declType->isBooleanType()) {
  2189. emitError("HelperInvocation builtin must be of boolean type", loc);
  2190. success = false;
  2191. }
  2192. if (sigPoint->GetKind() != hlsl::SigPoint::Kind::PSIn) {
  2193. emitError(
  2194. "HelperInvocation builtin can only be used as pixel shader input",
  2195. loc);
  2196. success = false;
  2197. }
  2198. } else if (builtin == "PointSize") {
  2199. if (!declType->isFloatingType()) {
  2200. emitError("PointSize builtin must be of float type", loc);
  2201. success = false;
  2202. }
  2203. switch (sigPoint->GetKind()) {
  2204. case hlsl::SigPoint::Kind::VSOut:
  2205. case hlsl::SigPoint::Kind::HSCPIn:
  2206. case hlsl::SigPoint::Kind::HSCPOut:
  2207. case hlsl::SigPoint::Kind::DSCPIn:
  2208. case hlsl::SigPoint::Kind::DSOut:
  2209. case hlsl::SigPoint::Kind::GSVIn:
  2210. case hlsl::SigPoint::Kind::GSOut:
  2211. case hlsl::SigPoint::Kind::PSIn:
  2212. break;
  2213. default:
  2214. emitError("PointSize builtin cannot be used as %0", loc)
  2215. << sigPoint->GetName();
  2216. success = false;
  2217. }
  2218. } else if (builtin == "BaseVertex" || builtin == "BaseInstance" ||
  2219. builtin == "DrawIndex") {
  2220. if (!declType->isSpecificBuiltinType(BuiltinType::Kind::Int) &&
  2221. !declType->isSpecificBuiltinType(BuiltinType::Kind::UInt)) {
  2222. emitError("%0 builtin must be of 32-bit scalar integer type", loc)
  2223. << builtin;
  2224. success = false;
  2225. }
  2226. if (sigPoint->GetKind() != hlsl::SigPoint::Kind::VSIn) {
  2227. emitError("%0 builtin can only be used in vertex shader input", loc)
  2228. << builtin;
  2229. success = false;
  2230. }
  2231. } else if (builtin == "DeviceIndex") {
  2232. if (getStorageClassForSigPoint(sigPoint) != spv::StorageClass::Input) {
  2233. emitError("%0 builtin can only be used as shader input", loc)
  2234. << builtin;
  2235. success = false;
  2236. }
  2237. if (!declType->isSpecificBuiltinType(BuiltinType::Kind::Int) &&
  2238. !declType->isSpecificBuiltinType(BuiltinType::Kind::UInt)) {
  2239. emitError("%0 builtin must be of 32-bit scalar integer type", loc)
  2240. << builtin;
  2241. success = false;
  2242. }
  2243. }
  2244. }
  2245. return success;
  2246. }
  2247. spv::StorageClass
  2248. DeclResultIdMapper::getStorageClassForSigPoint(const hlsl::SigPoint *sigPoint) {
  2249. // This translation is done based on the HLSL reference (see docs/dxil.rst).
  2250. const auto sigPointKind = sigPoint->GetKind();
  2251. const auto signatureKind = sigPoint->GetSignatureKind();
  2252. spv::StorageClass sc = spv::StorageClass::Max;
  2253. switch (signatureKind) {
  2254. case hlsl::DXIL::SignatureKind::Input:
  2255. sc = spv::StorageClass::Input;
  2256. break;
  2257. case hlsl::DXIL::SignatureKind::Output:
  2258. sc = spv::StorageClass::Output;
  2259. break;
  2260. case hlsl::DXIL::SignatureKind::Invalid: {
  2261. // There are some special cases in HLSL (See docs/dxil.rst):
  2262. // SignatureKind is "invalid" for PCIn, HSIn, GSIn, and CSIn.
  2263. switch (sigPointKind) {
  2264. case hlsl::DXIL::SigPointKind::PCIn:
  2265. case hlsl::DXIL::SigPointKind::HSIn:
  2266. case hlsl::DXIL::SigPointKind::GSIn:
  2267. case hlsl::DXIL::SigPointKind::CSIn:
  2268. sc = spv::StorageClass::Input;
  2269. break;
  2270. default:
  2271. llvm_unreachable("Found invalid SigPoint kind for semantic");
  2272. }
  2273. break;
  2274. }
  2275. case hlsl::DXIL::SignatureKind::PatchConstant: {
  2276. // There are some special cases in HLSL (See docs/dxil.rst):
  2277. // SignatureKind is "PatchConstant" for PCOut and DSIn.
  2278. switch (sigPointKind) {
  2279. case hlsl::DXIL::SigPointKind::PCOut:
  2280. // Patch Constant Output (Output of Hull which is passed to Domain).
  2281. sc = spv::StorageClass::Output;
  2282. break;
  2283. case hlsl::DXIL::SigPointKind::DSIn:
  2284. // Domain Shader regular input - Patch Constant data plus system values.
  2285. sc = spv::StorageClass::Input;
  2286. break;
  2287. default:
  2288. llvm_unreachable("Found invalid SigPoint kind for semantic");
  2289. }
  2290. break;
  2291. }
  2292. default:
  2293. llvm_unreachable("Found invalid SigPoint kind for semantic");
  2294. }
  2295. return sc;
  2296. }
  2297. uint32_t DeclResultIdMapper::getTypeAndCreateCounterForPotentialAliasVar(
  2298. const DeclaratorDecl *decl, bool *shouldBeAlias, SpirvEvalInfo *info) {
  2299. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  2300. // This method is only intended to be used to create SPIR-V variables in the
  2301. // Function or Private storage class.
  2302. assert(!varDecl->isExternallyVisible() || varDecl->isStaticDataMember());
  2303. }
  2304. const QualType type = getTypeOrFnRetType(decl);
  2305. // Whether we should generate this decl as an alias variable.
  2306. bool genAlias = false;
  2307. if (const auto *buffer = dyn_cast<HLSLBufferDecl>(decl->getDeclContext())) {
  2308. // For ConstantBuffer and TextureBuffer
  2309. if (buffer->isConstantBufferView())
  2310. genAlias = true;
  2311. } else if (TypeTranslator::isOrContainsAKindOfStructuredOrByteBuffer(type)) {
  2312. genAlias = true;
  2313. }
  2314. if (shouldBeAlias)
  2315. *shouldBeAlias = genAlias;
  2316. if (genAlias) {
  2317. needsLegalization = true;
  2318. createCounterVarForDecl(decl);
  2319. if (info)
  2320. info->setContainsAliasComponent(true);
  2321. }
  2322. return typeTranslator.translateType(type);
  2323. }
  2324. } // end namespace spirv
  2325. } // end namespace clang