DeclResultIdMapper.cpp 147 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834
  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 <sstream>
  11. #include "dxc/DXIL/DxilConstants.h"
  12. #include "dxc/DXIL/DxilTypeSystem.h"
  13. #include "clang/AST/Expr.h"
  14. #include "clang/AST/HlslTypes.h"
  15. #include "clang/SPIRV/AstTypeProbe.h"
  16. #include "llvm/ADT/SmallBitVector.h"
  17. #include "llvm/ADT/StringMap.h"
  18. #include "llvm/ADT/StringSet.h"
  19. #include "llvm/Support/Casting.h"
  20. #include "AlignmentSizeCalculator.h"
  21. #include "SpirvEmitter.h"
  22. namespace clang {
  23. namespace spirv {
  24. namespace {
  25. uint32_t getVkBindingAttrSet(const VKBindingAttr *attr, uint32_t defaultSet) {
  26. // If the [[vk::binding(x)]] attribute is provided without the descriptor set,
  27. // we should use the default descriptor set.
  28. if (attr->getSet() == INT_MIN) {
  29. return defaultSet;
  30. }
  31. return attr->getSet();
  32. }
  33. /// Returns the :packoffset() annotation on the given decl. Returns nullptr if
  34. /// the decl does not have one.
  35. hlsl::ConstantPacking *getPackOffset(const clang::NamedDecl *decl) {
  36. for (auto *annotation : decl->getUnusualAnnotations())
  37. if (auto *packing = llvm::dyn_cast<hlsl::ConstantPacking>(annotation))
  38. return packing;
  39. return nullptr;
  40. }
  41. /// Returns the number of binding numbers that are used up by the given type.
  42. /// An array of size N consumes N*M binding numbers where M is the number of
  43. /// binding numbers used by each array element.
  44. /// The number of binding numbers used by a structure is the sum of binding
  45. /// numbers used by its members.
  46. uint32_t getNumBindingsUsedByResourceType(QualType type) {
  47. // For custom-generated types that have SpirvType but no QualType.
  48. if (type.isNull())
  49. return 1;
  50. // For every array dimension, the number of bindings needed should be
  51. // multiplied by the array size. For example: an array of two Textures should
  52. // use 2 binding slots.
  53. uint32_t arrayFactor = 1;
  54. while (auto constArrayType = dyn_cast<ConstantArrayType>(type)) {
  55. arrayFactor *=
  56. static_cast<uint32_t>(constArrayType->getSize().getZExtValue());
  57. type = constArrayType->getElementType();
  58. }
  59. // Once we remove the arrayness, we expect the given type to be either a
  60. // resource OR a structure that only contains resources.
  61. assert(isResourceType(type) || isResourceOnlyStructure(type));
  62. // In the case of a resource, each resource takes 1 binding slot, so in total
  63. // it consumes: 1 * arrayFactor.
  64. if (isResourceType(type))
  65. return arrayFactor;
  66. // In the case of a struct of resources, we need to sum up the number of
  67. // bindings for the struct members. So in total it consumes:
  68. // sum(bindings of struct members) * arrayFactor.
  69. if (isResourceOnlyStructure(type)) {
  70. uint32_t sumOfMemberBindings = 0;
  71. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  72. assert(structDecl);
  73. for (const auto *field : structDecl->fields())
  74. sumOfMemberBindings += getNumBindingsUsedByResourceType(field->getType());
  75. return sumOfMemberBindings * arrayFactor;
  76. }
  77. llvm_unreachable(
  78. "getNumBindingsUsedByResourceType was called with unknown resource type");
  79. }
  80. QualType getUintTypeWithSourceComponents(const ASTContext &astContext,
  81. QualType sourceType) {
  82. if (isScalarType(sourceType)) {
  83. return astContext.UnsignedIntTy;
  84. }
  85. uint32_t elemCount = 0;
  86. if (isVectorType(sourceType, nullptr, &elemCount)) {
  87. return astContext.getExtVectorType(astContext.UnsignedIntTy, elemCount);
  88. }
  89. llvm_unreachable("only scalar and vector types are supported in "
  90. "getUintTypeWithSourceComponents");
  91. }
  92. uint32_t getLocationCount(const ASTContext &astContext, QualType type) {
  93. // See Vulkan spec 14.1.4. Location Assignment for the complete set of rules.
  94. const auto canonicalType = type.getCanonicalType();
  95. if (canonicalType != type)
  96. return getLocationCount(astContext, canonicalType);
  97. // Inputs and outputs of the following types consume a single interface
  98. // location:
  99. // * 16-bit scalar and vector types, and
  100. // * 32-bit scalar and vector types, and
  101. // * 64-bit scalar and 2-component vector types.
  102. // 64-bit three- and four- component vectors consume two consecutive
  103. // locations.
  104. // Primitive types
  105. if (isScalarType(type))
  106. return 1;
  107. // Vector types
  108. {
  109. QualType elemType = {};
  110. uint32_t elemCount = {};
  111. if (isVectorType(type, &elemType, &elemCount)) {
  112. const auto *builtinType = elemType->getAs<BuiltinType>();
  113. switch (builtinType->getKind()) {
  114. case BuiltinType::Double:
  115. case BuiltinType::LongLong:
  116. case BuiltinType::ULongLong:
  117. if (elemCount >= 3)
  118. return 2;
  119. default:
  120. // Filter switch only interested in types occupying 2 locations.
  121. break;
  122. }
  123. return 1;
  124. }
  125. }
  126. // If the declared input or output is an n * m 16- , 32- or 64- bit matrix,
  127. // it will be assigned multiple locations starting with the location
  128. // specified. The number of locations assigned for each matrix will be the
  129. // same as for an n-element array of m-component vectors.
  130. // Matrix types
  131. {
  132. QualType elemType = {};
  133. uint32_t rowCount = 0, colCount = 0;
  134. if (isMxNMatrix(type, &elemType, &rowCount, &colCount))
  135. return getLocationCount(astContext,
  136. astContext.getExtVectorType(elemType, colCount)) *
  137. rowCount;
  138. }
  139. // Typedefs
  140. if (const auto *typedefType = type->getAs<TypedefType>())
  141. return getLocationCount(astContext, typedefType->desugar());
  142. // Reference types
  143. if (const auto *refType = type->getAs<ReferenceType>())
  144. return getLocationCount(astContext, refType->getPointeeType());
  145. // Pointer types
  146. if (const auto *ptrType = type->getAs<PointerType>())
  147. return getLocationCount(astContext, ptrType->getPointeeType());
  148. // If a declared input or output is an array of size n and each element takes
  149. // m locations, it will be assigned m * n consecutive locations starting with
  150. // the location specified.
  151. // Array types
  152. if (const auto *arrayType = astContext.getAsConstantArrayType(type))
  153. return getLocationCount(astContext, arrayType->getElementType()) *
  154. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  155. // Struct type
  156. if (type->getAs<RecordType>()) {
  157. assert(false && "all structs should already be flattened");
  158. return 0;
  159. }
  160. llvm_unreachable(
  161. "calculating number of occupied locations for type unimplemented");
  162. return 0;
  163. }
  164. bool shouldSkipInStructLayout(const Decl *decl) {
  165. // Ignore implicit generated struct declarations/constructors/destructors
  166. if (decl->isImplicit())
  167. return true;
  168. // Ignore embedded type decls
  169. if (isa<TypeDecl>(decl))
  170. return true;
  171. // Ignore embeded function decls
  172. if (isa<FunctionDecl>(decl))
  173. return true;
  174. // Ignore empty decls
  175. if (isa<EmptyDecl>(decl))
  176. return true;
  177. // For the $Globals cbuffer, we only care about externally-visible
  178. // non-resource-type variables. The rest should be filtered out.
  179. const auto *declContext = decl->getDeclContext();
  180. // $Globals' "struct" is the TranslationUnit, so we should ignore resources
  181. // in the TranslationUnit "struct" and its child namespaces.
  182. if (declContext->isTranslationUnit() || declContext->isNamespace()) {
  183. // External visibility
  184. if (const auto *declDecl = dyn_cast<DeclaratorDecl>(decl))
  185. if (!declDecl->hasExternalFormalLinkage())
  186. return true;
  187. // cbuffer/tbuffer
  188. if (isa<HLSLBufferDecl>(decl))
  189. return true;
  190. // 'groupshared' variables should not be placed in $Globals cbuffer.
  191. if (decl->hasAttr<HLSLGroupSharedAttr>())
  192. return true;
  193. // Other resource types
  194. if (const auto *valueDecl = dyn_cast<ValueDecl>(decl)) {
  195. const auto declType = valueDecl->getType();
  196. if (isResourceType(declType) || isResourceOnlyStructure(declType))
  197. return true;
  198. }
  199. }
  200. return false;
  201. }
  202. void collectDeclsInField(const Decl *field,
  203. llvm::SmallVector<const Decl *, 4> *decls) {
  204. // Case of nested namespaces.
  205. if (const auto *nsDecl = dyn_cast<NamespaceDecl>(field)) {
  206. for (const auto *decl : nsDecl->decls()) {
  207. collectDeclsInField(decl, decls);
  208. }
  209. }
  210. if (shouldSkipInStructLayout(field))
  211. return;
  212. if (!isa<DeclaratorDecl>(field)) {
  213. return;
  214. }
  215. decls->push_back(field);
  216. }
  217. llvm::SmallVector<const Decl *, 4>
  218. collectDeclsInDeclContext(const DeclContext *declContext) {
  219. llvm::SmallVector<const Decl *, 4> decls;
  220. for (const auto *field : declContext->decls()) {
  221. collectDeclsInField(field, &decls);
  222. }
  223. return decls;
  224. }
  225. /// \brief Returns true if the given decl is a boolean stage I/O variable.
  226. /// Returns false if the type is not boolean, or the decl is a built-in stage
  227. /// variable.
  228. bool isBooleanStageIOVar(const NamedDecl *decl, QualType type,
  229. const hlsl::DXIL::SemanticKind semanticKind,
  230. const hlsl::SigPoint::Kind sigPointKind) {
  231. // [[vk::builtin(...)]] makes the decl a built-in stage variable.
  232. // IsFrontFace (if used as PSIn) is the only known boolean built-in stage
  233. // variable.
  234. const bool isBooleanBuiltin =
  235. (decl->getAttr<VKBuiltInAttr>() != nullptr) ||
  236. (semanticKind == hlsl::Semantic::Kind::IsFrontFace &&
  237. sigPointKind == hlsl::SigPoint::Kind::PSIn);
  238. // TODO: support boolean matrix stage I/O variable if needed.
  239. QualType elemType = {};
  240. const bool isBooleanType =
  241. ((isScalarType(type, &elemType) || isVectorType(type, &elemType)) &&
  242. elemType->isBooleanType());
  243. return isBooleanType && !isBooleanBuiltin;
  244. }
  245. /// \brief Returns the stage variable's register assignment for the given Decl.
  246. const hlsl::RegisterAssignment *getResourceBinding(const NamedDecl *decl) {
  247. for (auto *annotation : decl->getUnusualAnnotations()) {
  248. if (auto *reg = dyn_cast<hlsl::RegisterAssignment>(annotation)) {
  249. return reg;
  250. }
  251. }
  252. return nullptr;
  253. }
  254. /// \brief Returns the stage variable's 'register(c#) assignment for the given
  255. /// Decl. Return nullptr if the given variable does not have such assignment.
  256. const hlsl::RegisterAssignment *getRegisterCAssignment(const NamedDecl *decl) {
  257. const auto *regAssignment = getResourceBinding(decl);
  258. if (regAssignment)
  259. return regAssignment->RegisterType == 'c' ? regAssignment : nullptr;
  260. return nullptr;
  261. }
  262. /// \brief Returns true if the given declaration has a primitive type qualifier.
  263. /// Returns false otherwise.
  264. inline bool hasGSPrimitiveTypeQualifier(const Decl *decl) {
  265. return decl->hasAttr<HLSLTriangleAttr>() ||
  266. decl->hasAttr<HLSLTriangleAdjAttr>() ||
  267. decl->hasAttr<HLSLPointAttr>() || decl->hasAttr<HLSLLineAttr>() ||
  268. decl->hasAttr<HLSLLineAdjAttr>();
  269. }
  270. /// \brief Deduces the parameter qualifier for the given decl.
  271. hlsl::DxilParamInputQual deduceParamQual(const DeclaratorDecl *decl,
  272. bool asInput) {
  273. const auto type = decl->getType();
  274. if (hlsl::IsHLSLInputPatchType(type))
  275. return hlsl::DxilParamInputQual::InputPatch;
  276. if (hlsl::IsHLSLOutputPatchType(type))
  277. return hlsl::DxilParamInputQual::OutputPatch;
  278. // TODO: Add support for multiple output streams.
  279. if (hlsl::IsHLSLStreamOutputType(type))
  280. return hlsl::DxilParamInputQual::OutStream0;
  281. // The inputs to the geometry shader that have a primitive type qualifier
  282. // must use 'InputPrimitive'.
  283. if (hasGSPrimitiveTypeQualifier(decl))
  284. return hlsl::DxilParamInputQual::InputPrimitive;
  285. if (decl->hasAttr<HLSLIndicesAttr>())
  286. return hlsl::DxilParamInputQual::OutIndices;
  287. if (decl->hasAttr<HLSLVerticesAttr>())
  288. return hlsl::DxilParamInputQual::OutVertices;
  289. if (decl->hasAttr<HLSLPrimitivesAttr>())
  290. return hlsl::DxilParamInputQual::OutPrimitives;
  291. if (decl->hasAttr<HLSLPayloadAttr>())
  292. return hlsl::DxilParamInputQual::InPayload;
  293. return asInput ? hlsl::DxilParamInputQual::In : hlsl::DxilParamInputQual::Out;
  294. }
  295. /// \brief Deduces the HLSL SigPoint for the given decl appearing in the given
  296. /// shader model.
  297. const hlsl::SigPoint *deduceSigPoint(const DeclaratorDecl *decl, bool asInput,
  298. const hlsl::ShaderModel::Kind kind,
  299. bool forPCF) {
  300. return hlsl::SigPoint::GetSigPoint(hlsl::SigPointFromInputQual(
  301. deduceParamQual(decl, asInput), kind, forPCF));
  302. }
  303. /// Returns the type of the given decl. If the given decl is a FunctionDecl,
  304. /// returns its result type.
  305. inline QualType getTypeOrFnRetType(const DeclaratorDecl *decl) {
  306. if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  307. return funcDecl->getReturnType();
  308. }
  309. return decl->getType();
  310. }
  311. /// Returns the number of base classes if this type is a derived class/struct.
  312. /// Returns zero otherwise.
  313. inline uint32_t getNumBaseClasses(QualType type) {
  314. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  315. return cxxDecl->getNumBases();
  316. return 0;
  317. }
  318. /// Returns the appropriate storage class for an extern variable of the given
  319. /// type.
  320. spv::StorageClass getStorageClassForExternVar(QualType type,
  321. bool hasGroupsharedAttr) {
  322. // For CS groupshared variables
  323. if (hasGroupsharedAttr)
  324. return spv::StorageClass::Workgroup;
  325. if (isAKindOfStructuredOrByteBuffer(type))
  326. return spv::StorageClass::Uniform;
  327. return spv::StorageClass::UniformConstant;
  328. }
  329. /// Returns the appropriate layout rule for an extern variable of the given
  330. /// type.
  331. SpirvLayoutRule getLayoutRuleForExternVar(QualType type,
  332. const SpirvCodeGenOptions &opts) {
  333. if (isAKindOfStructuredOrByteBuffer(type))
  334. return opts.sBufferLayoutRule;
  335. return SpirvLayoutRule::Void;
  336. }
  337. spv::ImageFormat getSpvImageFormat(const VKImageFormatAttr *imageFormatAttr) {
  338. if (imageFormatAttr == nullptr)
  339. return spv::ImageFormat::Unknown;
  340. switch (imageFormatAttr->getImageFormat()) {
  341. case VKImageFormatAttr::unknown:
  342. return spv::ImageFormat::Unknown;
  343. case VKImageFormatAttr::rgba32f:
  344. return spv::ImageFormat::Rgba32f;
  345. case VKImageFormatAttr::rgba16f:
  346. return spv::ImageFormat::Rgba16f;
  347. case VKImageFormatAttr::r32f:
  348. return spv::ImageFormat::R32f;
  349. case VKImageFormatAttr::rgba8:
  350. return spv::ImageFormat::Rgba8;
  351. case VKImageFormatAttr::rgba8snorm:
  352. return spv::ImageFormat::Rgba8Snorm;
  353. case VKImageFormatAttr::rg32f:
  354. return spv::ImageFormat::Rg32f;
  355. case VKImageFormatAttr::rg16f:
  356. return spv::ImageFormat::Rg16f;
  357. case VKImageFormatAttr::r11g11b10f:
  358. return spv::ImageFormat::R11fG11fB10f;
  359. case VKImageFormatAttr::r16f:
  360. return spv::ImageFormat::R16f;
  361. case VKImageFormatAttr::rgba16:
  362. return spv::ImageFormat::Rgba16;
  363. case VKImageFormatAttr::rgb10a2:
  364. return spv::ImageFormat::Rgb10A2;
  365. case VKImageFormatAttr::rg16:
  366. return spv::ImageFormat::Rg16;
  367. case VKImageFormatAttr::rg8:
  368. return spv::ImageFormat::Rg8;
  369. case VKImageFormatAttr::r16:
  370. return spv::ImageFormat::R16;
  371. case VKImageFormatAttr::r8:
  372. return spv::ImageFormat::R8;
  373. case VKImageFormatAttr::rgba16snorm:
  374. return spv::ImageFormat::Rgba16Snorm;
  375. case VKImageFormatAttr::rg16snorm:
  376. return spv::ImageFormat::Rg16Snorm;
  377. case VKImageFormatAttr::rg8snorm:
  378. return spv::ImageFormat::Rg8Snorm;
  379. case VKImageFormatAttr::r16snorm:
  380. return spv::ImageFormat::R16Snorm;
  381. case VKImageFormatAttr::r8snorm:
  382. return spv::ImageFormat::R8Snorm;
  383. case VKImageFormatAttr::rgba32i:
  384. return spv::ImageFormat::Rgba32i;
  385. case VKImageFormatAttr::rgba16i:
  386. return spv::ImageFormat::Rgba16i;
  387. case VKImageFormatAttr::rgba8i:
  388. return spv::ImageFormat::Rgba8i;
  389. case VKImageFormatAttr::r32i:
  390. return spv::ImageFormat::R32i;
  391. case VKImageFormatAttr::rg32i:
  392. return spv::ImageFormat::Rg32i;
  393. case VKImageFormatAttr::rg16i:
  394. return spv::ImageFormat::Rg16i;
  395. case VKImageFormatAttr::rg8i:
  396. return spv::ImageFormat::Rg8i;
  397. case VKImageFormatAttr::r16i:
  398. return spv::ImageFormat::R16i;
  399. case VKImageFormatAttr::r8i:
  400. return spv::ImageFormat::R8i;
  401. case VKImageFormatAttr::rgba32ui:
  402. return spv::ImageFormat::Rgba32ui;
  403. case VKImageFormatAttr::rgba16ui:
  404. return spv::ImageFormat::Rgba16ui;
  405. case VKImageFormatAttr::rgba8ui:
  406. return spv::ImageFormat::Rgba8ui;
  407. case VKImageFormatAttr::r32ui:
  408. return spv::ImageFormat::R32ui;
  409. case VKImageFormatAttr::rgb10a2ui:
  410. return spv::ImageFormat::Rgb10a2ui;
  411. case VKImageFormatAttr::rg32ui:
  412. return spv::ImageFormat::Rg32ui;
  413. case VKImageFormatAttr::rg16ui:
  414. return spv::ImageFormat::Rg16ui;
  415. case VKImageFormatAttr::rg8ui:
  416. return spv::ImageFormat::Rg8ui;
  417. case VKImageFormatAttr::r16ui:
  418. return spv::ImageFormat::R16ui;
  419. case VKImageFormatAttr::r8ui:
  420. return spv::ImageFormat::R8ui;
  421. case VKImageFormatAttr::r64ui:
  422. return spv::ImageFormat::R64ui;
  423. case VKImageFormatAttr::r64i:
  424. return spv::ImageFormat::R64i;
  425. }
  426. return spv::ImageFormat::Unknown;
  427. }
  428. } // anonymous namespace
  429. std::string StageVar::getSemanticStr() const {
  430. // A special case for zero index, which is equivalent to no index.
  431. // Use what is in the source code.
  432. // TODO: this looks like a hack to make the current tests happy.
  433. // Should consider remove it and fix all tests.
  434. if (semanticInfo.index == 0)
  435. return semanticInfo.str;
  436. std::ostringstream ss;
  437. ss << semanticInfo.name.str() << semanticInfo.index;
  438. return ss.str();
  439. }
  440. SpirvInstruction *CounterIdAliasPair::get(SpirvBuilder &builder,
  441. SpirvContext &spvContext) const {
  442. if (isAlias) {
  443. const auto *counterType = spvContext.getACSBufferCounterType();
  444. const auto *counterVarType =
  445. spvContext.getPointerType(counterType, spv::StorageClass::Uniform);
  446. return builder.createLoad(counterVarType, counterVar,
  447. /* SourceLocation */ {});
  448. }
  449. return counterVar;
  450. }
  451. const CounterIdAliasPair *
  452. CounterVarFields::get(const llvm::SmallVectorImpl<uint32_t> &indices) const {
  453. for (const auto &field : fields)
  454. if (field.indices == indices)
  455. return &field.counterVar;
  456. return nullptr;
  457. }
  458. bool CounterVarFields::assign(const CounterVarFields &srcFields,
  459. SpirvBuilder &builder,
  460. SpirvContext &context) const {
  461. for (const auto &field : fields) {
  462. const auto *srcField = srcFields.get(field.indices);
  463. if (!srcField)
  464. return false;
  465. field.counterVar.assign(*srcField, builder, context);
  466. }
  467. return true;
  468. }
  469. bool CounterVarFields::assign(const CounterVarFields &srcFields,
  470. const llvm::SmallVector<uint32_t, 4> &dstPrefix,
  471. const llvm::SmallVector<uint32_t, 4> &srcPrefix,
  472. SpirvBuilder &builder,
  473. SpirvContext &context) const {
  474. if (dstPrefix.empty() && srcPrefix.empty())
  475. return assign(srcFields, builder, context);
  476. llvm::SmallVector<uint32_t, 4> srcIndices = srcPrefix;
  477. // If whole has the given prefix, appends all elements after the prefix in
  478. // whole to srcIndices.
  479. const auto applyDiff =
  480. [&srcIndices](const llvm::SmallVector<uint32_t, 4> &whole,
  481. const llvm::SmallVector<uint32_t, 4> &prefix) -> bool {
  482. uint32_t i = 0;
  483. for (; i < prefix.size(); ++i)
  484. if (whole[i] != prefix[i]) {
  485. break;
  486. }
  487. if (i == prefix.size()) {
  488. for (; i < whole.size(); ++i)
  489. srcIndices.push_back(whole[i]);
  490. return true;
  491. }
  492. return false;
  493. };
  494. for (const auto &field : fields)
  495. if (applyDiff(field.indices, dstPrefix)) {
  496. const auto *srcField = srcFields.get(srcIndices);
  497. if (!srcField)
  498. return false;
  499. field.counterVar.assign(*srcField, builder, context);
  500. for (uint32_t i = srcPrefix.size(); i < srcIndices.size(); ++i)
  501. srcIndices.pop_back();
  502. }
  503. return true;
  504. }
  505. SemanticInfo DeclResultIdMapper::getStageVarSemantic(const NamedDecl *decl) {
  506. for (auto *annotation : decl->getUnusualAnnotations()) {
  507. if (auto *sema = dyn_cast<hlsl::SemanticDecl>(annotation)) {
  508. llvm::StringRef semanticStr = sema->SemanticName;
  509. llvm::StringRef semanticName;
  510. uint32_t index = 0;
  511. hlsl::Semantic::DecomposeNameAndIndex(semanticStr, &semanticName, &index);
  512. const auto *semantic = hlsl::Semantic::GetByName(semanticName);
  513. return {semanticStr, semantic, semanticName, index, sema->Loc};
  514. }
  515. }
  516. return {};
  517. }
  518. bool DeclResultIdMapper::createStageOutputVar(const DeclaratorDecl *decl,
  519. SpirvInstruction *storedValue,
  520. bool forPCF) {
  521. QualType type = getTypeOrFnRetType(decl);
  522. uint32_t arraySize = 0;
  523. // Output stream types (PointStream, LineStream, TriangleStream) are
  524. // translated as their underlying struct types.
  525. if (hlsl::IsHLSLStreamOutputType(type))
  526. type = hlsl::GetHLSLResourceResultType(type);
  527. if (decl->hasAttr<HLSLIndicesAttr>() || decl->hasAttr<HLSLVerticesAttr>() ||
  528. decl->hasAttr<HLSLPrimitivesAttr>()) {
  529. const auto *typeDecl = astContext.getAsConstantArrayType(type);
  530. type = typeDecl->getElementType();
  531. arraySize = static_cast<uint32_t>(typeDecl->getSize().getZExtValue());
  532. if (decl->hasAttr<HLSLIndicesAttr>()) {
  533. // create SPIR-V builtin array PrimitiveIndicesNV of type
  534. // "uint [MaxPrimitiveCount * verticesPerPrim]"
  535. uint32_t verticesPerPrim = 1;
  536. if (!isVectorType(type, nullptr, &verticesPerPrim)) {
  537. assert(isScalarType(type));
  538. }
  539. arraySize = arraySize * verticesPerPrim;
  540. QualType arrayType = astContext.getConstantArrayType(
  541. astContext.UnsignedIntTy, llvm::APInt(32, arraySize),
  542. clang::ArrayType::Normal, 0);
  543. stageVarInstructions[cast<DeclaratorDecl>(decl)] = getBuiltinVar(
  544. spv::BuiltIn::PrimitiveIndicesNV, arrayType, decl->getLocation());
  545. return true;
  546. }
  547. }
  548. const auto *sigPoint = deduceSigPoint(
  549. decl, /*asInput=*/false, spvContext.getCurrentShaderModelKind(), forPCF);
  550. // HS output variables are created using the other overload. For the rest,
  551. // none of them should be created as arrays.
  552. assert(sigPoint->GetKind() != hlsl::DXIL::SigPointKind::HSCPOut);
  553. SemanticInfo inheritSemantic = {};
  554. // If storedValue is 0, it means this parameter in the original source code is
  555. // not used at all. Avoid writing back.
  556. //
  557. // Write back of stage output variables in GS is manually controlled by
  558. // .Append() intrinsic method, implemented in writeBackOutputStream(). So
  559. // ignoreValue should be set to true for GS.
  560. const bool noWriteBack =
  561. storedValue == nullptr || spvContext.isGS() || spvContext.isMS();
  562. return createStageVars(sigPoint, decl, /*asInput=*/false, type, arraySize,
  563. "out.var", llvm::None, &storedValue, noWriteBack,
  564. &inheritSemantic);
  565. }
  566. bool DeclResultIdMapper::createStageOutputVar(const DeclaratorDecl *decl,
  567. uint32_t arraySize,
  568. SpirvInstruction *invocationId,
  569. SpirvInstruction *storedValue) {
  570. assert(spvContext.isHS());
  571. QualType type = getTypeOrFnRetType(decl);
  572. const auto *sigPoint =
  573. hlsl::SigPoint::GetSigPoint(hlsl::DXIL::SigPointKind::HSCPOut);
  574. SemanticInfo inheritSemantic = {};
  575. return createStageVars(sigPoint, decl, /*asInput=*/false, type, arraySize,
  576. "out.var", invocationId, &storedValue,
  577. /*noWriteBack=*/false, &inheritSemantic);
  578. }
  579. bool DeclResultIdMapper::createStageInputVar(const ParmVarDecl *paramDecl,
  580. SpirvInstruction **loadedValue,
  581. bool forPCF) {
  582. uint32_t arraySize = 0;
  583. QualType type = paramDecl->getType();
  584. // Deprive the outermost arrayness for HS/DS/GS and use arraySize
  585. // to convey that information
  586. if (hlsl::IsHLSLInputPatchType(type)) {
  587. arraySize = hlsl::GetHLSLInputPatchCount(type);
  588. type = hlsl::GetHLSLInputPatchElementType(type);
  589. } else if (hlsl::IsHLSLOutputPatchType(type)) {
  590. arraySize = hlsl::GetHLSLOutputPatchCount(type);
  591. type = hlsl::GetHLSLOutputPatchElementType(type);
  592. }
  593. if (hasGSPrimitiveTypeQualifier(paramDecl)) {
  594. const auto *typeDecl = astContext.getAsConstantArrayType(type);
  595. arraySize = static_cast<uint32_t>(typeDecl->getSize().getZExtValue());
  596. type = typeDecl->getElementType();
  597. }
  598. const auto *sigPoint =
  599. deduceSigPoint(paramDecl, /*asInput=*/true,
  600. spvContext.getCurrentShaderModelKind(), forPCF);
  601. SemanticInfo inheritSemantic = {};
  602. if (paramDecl->hasAttr<HLSLPayloadAttr>()) {
  603. spv::StorageClass sc = getStorageClassForSigPoint(sigPoint);
  604. return createPayloadStageVars(sigPoint, sc, paramDecl, /*asInput=*/true,
  605. type, "in.var", loadedValue);
  606. } else {
  607. return createStageVars(sigPoint, paramDecl, /*asInput=*/true, type,
  608. arraySize, "in.var", llvm::None, loadedValue,
  609. /*noWriteBack=*/false, &inheritSemantic);
  610. }
  611. }
  612. const DeclResultIdMapper::DeclSpirvInfo *
  613. DeclResultIdMapper::getDeclSpirvInfo(const ValueDecl *decl) const {
  614. auto it = astDecls.find(decl);
  615. if (it != astDecls.end())
  616. return &it->second;
  617. return nullptr;
  618. }
  619. SpirvInstruction *DeclResultIdMapper::getDeclEvalInfo(const ValueDecl *decl,
  620. SourceLocation loc) {
  621. const DeclSpirvInfo *info = getDeclSpirvInfo(decl);
  622. // If DeclSpirvInfo is not found for this decl, it might be because it is an
  623. // implicit VarDecl. All implicit VarDecls are lazily created in order to
  624. // avoid creating large number of unused variables/constants/enums.
  625. if (!info) {
  626. tryToCreateImplicitConstVar(decl);
  627. info = getDeclSpirvInfo(decl);
  628. }
  629. if (info) {
  630. if (info->indexInCTBuffer >= 0) {
  631. // If this is a VarDecl inside a HLSLBufferDecl, we need to do an extra
  632. // OpAccessChain to get the pointer to the variable since we created
  633. // a single variable for the whole buffer object.
  634. // Should only have VarDecls in a HLSLBufferDecl.
  635. QualType valueType = cast<VarDecl>(decl)->getType();
  636. return spvBuilder.createAccessChain(
  637. valueType, info->instr,
  638. {spvBuilder.getConstantInt(
  639. astContext.IntTy, llvm::APInt(32, info->indexInCTBuffer, true))},
  640. loc);
  641. } else if (auto *type = info->instr->getResultType()) {
  642. const auto *ptrTy = dyn_cast<HybridPointerType>(type);
  643. // If it is a local variable or function parameter with a bindless
  644. // array of an opaque type, we have to load it because we pass a
  645. // pointer of a global variable that has the bindless opaque array.
  646. if (ptrTy != nullptr && isBindlessOpaqueArray(decl->getType())) {
  647. auto *load = spvBuilder.createLoad(ptrTy, info->instr, loc);
  648. load->setRValue(false);
  649. return load;
  650. } else {
  651. return *info;
  652. }
  653. } else {
  654. return *info;
  655. }
  656. }
  657. emitFatalError("found unregistered decl", decl->getLocation())
  658. << decl->getName();
  659. emitNote("please file a bug report on "
  660. "https://github.com/Microsoft/DirectXShaderCompiler/issues with "
  661. "source code if possible",
  662. {});
  663. return 0;
  664. }
  665. SpirvFunctionParameter *
  666. DeclResultIdMapper::createFnParam(const ParmVarDecl *param,
  667. uint32_t dbgArgNumber) {
  668. const auto type = getTypeOrFnRetType(param);
  669. const auto loc = param->getLocation();
  670. const auto name = param->getName();
  671. SpirvFunctionParameter *fnParamInstr = spvBuilder.addFnParam(
  672. type, param->hasAttr<HLSLPreciseAttr>(), loc, param->getName());
  673. bool isAlias = false;
  674. (void)getTypeAndCreateCounterForPotentialAliasVar(param, &isAlias);
  675. fnParamInstr->setContainsAliasComponent(isAlias);
  676. assert(astDecls[param].instr == nullptr);
  677. astDecls[param].instr = fnParamInstr;
  678. if (spirvOptions.debugInfoRich) {
  679. // Add DebugLocalVariable information
  680. const auto &sm = astContext.getSourceManager();
  681. const uint32_t line = sm.getPresumedLineNumber(loc);
  682. const uint32_t column = sm.getPresumedColumnNumber(loc);
  683. const auto *info = theEmitter.getOrCreateRichDebugInfo(loc);
  684. // TODO: replace this with FlagIsLocal enum.
  685. uint32_t flags = 1 << 2;
  686. auto *debugLocalVar = spvBuilder.createDebugLocalVariable(
  687. type, name, info->source, line, column, info->scopeStack.back(), flags,
  688. dbgArgNumber);
  689. spvBuilder.createDebugDeclare(debugLocalVar, fnParamInstr);
  690. }
  691. return fnParamInstr;
  692. }
  693. void DeclResultIdMapper::createCounterVarForDecl(const DeclaratorDecl *decl) {
  694. const QualType declType = getTypeOrFnRetType(decl);
  695. if (!counterVars.count(decl) && isRWAppendConsumeSBuffer(declType)) {
  696. createCounterVar(decl, /*declId=*/0, /*isAlias=*/true);
  697. } else if (!fieldCounterVars.count(decl) && declType->isStructureType() &&
  698. // Exclude other resource types which are represented as structs
  699. !hlsl::IsHLSLResourceType(declType)) {
  700. createFieldCounterVars(decl);
  701. }
  702. }
  703. SpirvVariable *
  704. DeclResultIdMapper::createFnVar(const VarDecl *var,
  705. llvm::Optional<SpirvInstruction *> init) {
  706. const auto type = getTypeOrFnRetType(var);
  707. const auto loc = var->getLocation();
  708. const auto name = var->getName();
  709. const bool isPrecise = var->hasAttr<HLSLPreciseAttr>();
  710. SpirvVariable *varInstr = spvBuilder.addFnVar(
  711. type, loc, name, isPrecise, init.hasValue() ? init.getValue() : nullptr);
  712. bool isAlias = false;
  713. (void)getTypeAndCreateCounterForPotentialAliasVar(var, &isAlias);
  714. varInstr->setContainsAliasComponent(isAlias);
  715. assert(astDecls[var].instr == nullptr);
  716. astDecls[var].instr = varInstr;
  717. return varInstr;
  718. }
  719. SpirvDebugGlobalVariable *DeclResultIdMapper::createDebugGlobalVariable(
  720. SpirvVariable *var, const QualType &type, const SourceLocation &loc,
  721. const StringRef &name) {
  722. if (spirvOptions.debugInfoRich) {
  723. // Add DebugGlobalVariable information
  724. const auto &sm = astContext.getSourceManager();
  725. const uint32_t line = sm.getPresumedLineNumber(loc);
  726. const uint32_t column = sm.getPresumedColumnNumber(loc);
  727. const auto *info = theEmitter.getOrCreateRichDebugInfo(loc);
  728. // TODO: replace this with FlagIsDefinition enum.
  729. uint32_t flags = 1 << 3;
  730. // TODO: update linkageName correctly.
  731. auto *dbgGlobalVar = spvBuilder.createDebugGlobalVariable(
  732. type, name, info->source, line, column, info->scopeStack.back(),
  733. /* linkageName */ name, var, flags);
  734. dbgGlobalVar->setDebugSpirvType(var->getResultType());
  735. dbgGlobalVar->setLayoutRule(var->getLayoutRule());
  736. return dbgGlobalVar;
  737. }
  738. return nullptr;
  739. }
  740. SpirvVariable *
  741. DeclResultIdMapper::createFileVar(const VarDecl *var,
  742. llvm::Optional<SpirvInstruction *> init) {
  743. const auto type = getTypeOrFnRetType(var);
  744. const auto loc = var->getLocation();
  745. const auto name = var->getName();
  746. SpirvVariable *varInstr =
  747. spvBuilder.addModuleVar(type, spv::StorageClass::Private,
  748. var->hasAttr<HLSLPreciseAttr>(), name, init, loc);
  749. bool isAlias = false;
  750. (void)getTypeAndCreateCounterForPotentialAliasVar(var, &isAlias);
  751. varInstr->setContainsAliasComponent(isAlias);
  752. assert(astDecls[var].instr == nullptr);
  753. astDecls[var].instr = varInstr;
  754. createDebugGlobalVariable(varInstr, type, loc, name);
  755. return varInstr;
  756. }
  757. SpirvVariable *DeclResultIdMapper::createExternVar(const VarDecl *var) {
  758. const auto type = var->getType();
  759. const bool isGroupShared = var->hasAttr<HLSLGroupSharedAttr>();
  760. const bool isACRWSBuffer = isRWAppendConsumeSBuffer(type);
  761. const auto storageClass = getStorageClassForExternVar(type, isGroupShared);
  762. const auto rule = getLayoutRuleForExternVar(type, spirvOptions);
  763. const auto loc = var->getLocation();
  764. if (!isGroupShared && !isResourceType(type) &&
  765. !isResourceOnlyStructure(type)) {
  766. // We currently cannot support global structures that contain both resources
  767. // and non-resources. That would require significant work in manipulating
  768. // structure field decls, manipulating QualTypes, as well as inserting
  769. // non-resources into the Globals cbuffer which changes offset decorations
  770. // for it.
  771. if (isStructureContainingMixOfResourcesAndNonResources(type)) {
  772. emitError("global structures containing both resources and non-resources "
  773. "are not supported",
  774. loc);
  775. return nullptr;
  776. }
  777. // This is a stand-alone externally-visiable non-resource-type variable.
  778. // They should be grouped into the $Globals cbuffer. We create that cbuffer
  779. // and record all variables inside it upon seeing the first such variable.
  780. if (astDecls.count(var) == 0)
  781. createGlobalsCBuffer(var);
  782. auto *varInstr = astDecls[var].instr;
  783. return varInstr ? cast<SpirvVariable>(varInstr) : nullptr;
  784. }
  785. if (isResourceOnlyStructure(type)) {
  786. // We currently do not support global structures that contain buffers.
  787. // Supporting global structures that contain buffers has two complications:
  788. //
  789. // 1- Buffers have the Uniform storage class, whereas Textures/Samplers have
  790. // UniformConstant storage class. As a result, if a struct contains both
  791. // textures and buffers, it is not clear what storage class should be used
  792. // for the struct. Also legalization cannot deduce the proper storage class
  793. // for struct members based on the structure's storage class.
  794. //
  795. // 2- Any kind of structured buffer has associated counters. The current DXC
  796. // code is not written in a way to place associated counters inside a
  797. // structure. Changing this behavior is non-trivial. There's also
  798. // significant work to be done both in DXC (to properly generate binding
  799. // numbers for the resource and its associated counters at correct offsets)
  800. // and in spirv-opt (to flatten such strcutures and modify the binding
  801. // numbers accordingly).
  802. if (isStructureContainingAnyKindOfBuffer(type)) {
  803. emitError("global structures containing buffers are not supported", loc);
  804. return nullptr;
  805. }
  806. needsFlatteningCompositeResources = true;
  807. }
  808. const auto name = var->getName();
  809. SpirvVariable *varInstr = spvBuilder.addModuleVar(
  810. type, storageClass, var->hasAttr<HLSLPreciseAttr>(), name, llvm::None,
  811. loc);
  812. varInstr->setLayoutRule(rule);
  813. // If this variable has [[vk::image_format("..")]] attribute, we have to keep
  814. // it in the SpirvContext and use it when we lower the QualType to SpirvType.
  815. auto spvImageFormat = getSpvImageFormat(var->getAttr<VKImageFormatAttr>());
  816. if (spvImageFormat != spv::ImageFormat::Unknown)
  817. spvContext.registerImageFormatForSpirvVariable(varInstr, spvImageFormat);
  818. DeclSpirvInfo info(varInstr);
  819. astDecls[var] = info;
  820. createDebugGlobalVariable(varInstr, type, loc, name);
  821. // Variables in Workgroup do not need descriptor decorations.
  822. if (storageClass == spv::StorageClass::Workgroup)
  823. return varInstr;
  824. const auto *regAttr = getResourceBinding(var);
  825. const auto *bindingAttr = var->getAttr<VKBindingAttr>();
  826. const auto *counterBindingAttr = var->getAttr<VKCounterBindingAttr>();
  827. resourceVars.emplace_back(varInstr, var, loc, regAttr, bindingAttr,
  828. counterBindingAttr);
  829. if (const auto *inputAttachment = var->getAttr<VKInputAttachmentIndexAttr>())
  830. spvBuilder.decorateInputAttachmentIndex(varInstr,
  831. inputAttachment->getIndex(), loc);
  832. if (isACRWSBuffer) {
  833. // For {Append|Consume|RW}StructuredBuffer, we need to always create another
  834. // variable for its associated counter.
  835. createCounterVar(var, varInstr, /*isAlias=*/false);
  836. }
  837. return varInstr;
  838. }
  839. SpirvInstruction *
  840. DeclResultIdMapper::createOrUpdateStringVar(const VarDecl *var) {
  841. assert(hlsl::IsStringType(var->getType()) ||
  842. hlsl::IsStringLiteralType(var->getType()));
  843. // If the string variable is not initialized to a string literal, we cannot
  844. // generate an OpString for it.
  845. if (!var->hasInit()) {
  846. emitError("Found uninitialized string variable.", var->getLocation());
  847. return nullptr;
  848. }
  849. const StringLiteral *stringLiteral =
  850. dyn_cast<StringLiteral>(var->getInit()->IgnoreParenCasts());
  851. SpirvString *init = spvBuilder.getString(stringLiteral->getString());
  852. DeclSpirvInfo info(init);
  853. astDecls[var] = info;
  854. return init;
  855. }
  856. SpirvVariable *DeclResultIdMapper::createStructOrStructArrayVarOfExplicitLayout(
  857. const DeclContext *decl, int arraySize, const ContextUsageKind usageKind,
  858. llvm::StringRef typeName, llvm::StringRef varName) {
  859. // cbuffers are translated into OpTypeStruct with Block decoration.
  860. // tbuffers are translated into OpTypeStruct with BufferBlock decoration.
  861. // Push constants are translated into OpTypeStruct with Block decoration.
  862. //
  863. // Both cbuffers and tbuffers have the SPIR-V Uniform storage class.
  864. // Push constants have the SPIR-V PushConstant storage class.
  865. const bool forCBuffer = usageKind == ContextUsageKind::CBuffer;
  866. const bool forTBuffer = usageKind == ContextUsageKind::TBuffer;
  867. const bool forGlobals = usageKind == ContextUsageKind::Globals;
  868. const bool forPC = usageKind == ContextUsageKind::PushConstant;
  869. const bool forShaderRecordNV =
  870. usageKind == ContextUsageKind::ShaderRecordBufferNV;
  871. const bool forShaderRecordEXT =
  872. usageKind == ContextUsageKind::ShaderRecordBufferEXT;
  873. const auto &declGroup = collectDeclsInDeclContext(decl);
  874. // Collect the type and name for each field
  875. llvm::SmallVector<HybridStructType::FieldInfo, 4> fields;
  876. for (const auto *subDecl : declGroup) {
  877. // The field can only be FieldDecl (for normal structs) or VarDecl (for
  878. // HLSLBufferDecls).
  879. assert(isa<VarDecl>(subDecl) || isa<FieldDecl>(subDecl));
  880. const auto *declDecl = cast<DeclaratorDecl>(subDecl);
  881. // In case 'register(c#)' annotation is placed on a global variable.
  882. const hlsl::RegisterAssignment *registerC =
  883. forGlobals ? getRegisterCAssignment(declDecl) : nullptr;
  884. // All fields are qualified with const. It will affect the debug name.
  885. // We don't need it here.
  886. auto varType = declDecl->getType();
  887. varType.removeLocalConst();
  888. HybridStructType::FieldInfo info(varType, declDecl->getName(),
  889. declDecl->getAttr<VKOffsetAttr>(),
  890. getPackOffset(declDecl), registerC,
  891. declDecl->hasAttr<HLSLPreciseAttr>());
  892. fields.push_back(info);
  893. }
  894. // Get the type for the whole struct
  895. // tbuffer/TextureBuffers are non-writable SSBOs.
  896. const SpirvType *resultType = spvContext.getHybridStructType(
  897. fields, typeName, /*isReadOnly*/ forTBuffer,
  898. forTBuffer ? StructInterfaceType::StorageBuffer
  899. : StructInterfaceType::UniformBuffer);
  900. // Make an array if requested.
  901. if (arraySize > 0) {
  902. resultType = spvContext.getArrayType(resultType, arraySize,
  903. /*ArrayStride*/ llvm::None);
  904. } else if (arraySize == -1) {
  905. resultType =
  906. spvContext.getRuntimeArrayType(resultType, /*ArrayStride*/ llvm::None);
  907. }
  908. // Register the <type-id> for this decl
  909. ctBufferPCTypes[decl] = resultType;
  910. const auto sc = forPC ? spv::StorageClass::PushConstant
  911. : forShaderRecordNV
  912. ? spv::StorageClass::ShaderRecordBufferNV
  913. : forShaderRecordEXT
  914. ? spv::StorageClass::ShaderRecordBufferKHR
  915. : spv::StorageClass::Uniform;
  916. // Create the variable for the whole struct / struct array.
  917. // The fields may be 'precise', but the structure itself is not.
  918. SpirvVariable *var =
  919. spvBuilder.addModuleVar(resultType, sc, /*isPrecise*/ false, varName);
  920. const SpirvLayoutRule layoutRule =
  921. (forCBuffer || forGlobals)
  922. ? spirvOptions.cBufferLayoutRule
  923. : (forTBuffer ? spirvOptions.tBufferLayoutRule
  924. : spirvOptions.sBufferLayoutRule);
  925. var->setHlslUserType(forCBuffer ? "cbuffer" : forTBuffer ? "tbuffer" : "");
  926. var->setLayoutRule(layoutRule);
  927. return var;
  928. }
  929. void DeclResultIdMapper::createEnumConstant(const EnumConstantDecl *decl) {
  930. const auto *valueDecl = dyn_cast<ValueDecl>(decl);
  931. const auto enumConstant =
  932. spvBuilder.getConstantInt(astContext.IntTy, decl->getInitVal());
  933. SpirvVariable *varInstr = spvBuilder.addModuleVar(
  934. astContext.IntTy, spv::StorageClass::Private, /*isPrecise*/ false,
  935. decl->getName(), enumConstant, decl->getLocation());
  936. astDecls[valueDecl] = DeclSpirvInfo(varInstr);
  937. }
  938. SpirvVariable *DeclResultIdMapper::createCTBuffer(const HLSLBufferDecl *decl) {
  939. // This function handles creation of cbuffer or tbuffer.
  940. const auto usageKind =
  941. decl->isCBuffer() ? ContextUsageKind::CBuffer : ContextUsageKind::TBuffer;
  942. const std::string structName = "type." + decl->getName().str();
  943. // The front-end does not allow arrays of cbuffer/tbuffer.
  944. SpirvVariable *bufferVar = createStructOrStructArrayVarOfExplicitLayout(
  945. decl, /*arraySize*/ 0, usageKind, structName, decl->getName());
  946. // We still register all VarDecls seperately here. All the VarDecls are
  947. // mapped to the <result-id> of the buffer object, which means when querying
  948. // querying the <result-id> for a certain VarDecl, we need to do an extra
  949. // OpAccessChain.
  950. int index = 0;
  951. for (const auto *subDecl : decl->decls()) {
  952. if (shouldSkipInStructLayout(subDecl))
  953. continue;
  954. const auto *varDecl = cast<VarDecl>(subDecl);
  955. astDecls[varDecl] = DeclSpirvInfo(bufferVar, index++);
  956. }
  957. resourceVars.emplace_back(
  958. bufferVar, decl, decl->getLocation(), getResourceBinding(decl),
  959. decl->getAttr<VKBindingAttr>(), decl->getAttr<VKCounterBindingAttr>());
  960. auto *dbgGlobalVar = createDebugGlobalVariable(
  961. bufferVar, QualType(), decl->getLocation(), decl->getName());
  962. if (dbgGlobalVar != nullptr) {
  963. // C/TBuffer needs HLSLBufferDecl for debug type lowering.
  964. spvContext.registerStructDeclForSpirvType(bufferVar->getResultType(), decl);
  965. }
  966. return bufferVar;
  967. }
  968. SpirvVariable *DeclResultIdMapper::createCTBuffer(const VarDecl *decl) {
  969. // This function handles creation of ConstantBuffer<T> or TextureBuffer<T>.
  970. // The way this is represented in the AST is as follows:
  971. //
  972. // |-VarDecl MyCbuffer 'ConstantBuffer<T>':'ConstantBuffer<T>'
  973. // |-CXXRecordDecl referenced struct T definition
  974. // |-CXXRecordDecl implicit struct T
  975. // |-FieldDecl
  976. // |-...
  977. // |-FieldDecl
  978. const QualType type = decl->getType();
  979. assert(isConstantTextureBuffer(type));
  980. const RecordType *recordType = nullptr;
  981. const RecordType *templatedType = nullptr;
  982. int arraySize = 0;
  983. // In case we have an array of ConstantBuffer/TextureBuffer:
  984. if (const auto *arrayType = type->getAsArrayTypeUnsafe()) {
  985. const QualType elemType = arrayType->getElementType();
  986. recordType = elemType->getAs<RecordType>();
  987. templatedType =
  988. hlsl::GetHLSLResourceResultType(elemType)->getAs<RecordType>();
  989. if (const auto *caType = astContext.getAsConstantArrayType(type)) {
  990. arraySize = static_cast<uint32_t>(caType->getSize().getZExtValue());
  991. } else {
  992. arraySize = -1;
  993. }
  994. } else {
  995. recordType = type->getAs<RecordType>();
  996. templatedType = hlsl::GetHLSLResourceResultType(type)->getAs<RecordType>();
  997. }
  998. if (!recordType) {
  999. emitError("constant/texture buffer type %0 unimplemented",
  1000. decl->getLocStart())
  1001. << type;
  1002. return nullptr;
  1003. }
  1004. if (!templatedType) {
  1005. emitError(
  1006. "the underlying type for constant/texture buffer must be a struct",
  1007. decl->getLocStart())
  1008. << type;
  1009. return nullptr;
  1010. }
  1011. const bool isConstBuffer = isConstantBuffer(type);
  1012. const auto usageKind =
  1013. isConstBuffer ? ContextUsageKind::CBuffer : ContextUsageKind::TBuffer;
  1014. const std::string structName = "type." +
  1015. recordType->getDecl()->getName().str() + "." +
  1016. templatedType->getDecl()->getName().str();
  1017. SpirvVariable *bufferVar = createStructOrStructArrayVarOfExplicitLayout(
  1018. templatedType->getDecl(), arraySize, usageKind, structName,
  1019. decl->getName());
  1020. // We register the VarDecl here.
  1021. astDecls[decl] = DeclSpirvInfo(bufferVar);
  1022. resourceVars.emplace_back(
  1023. bufferVar, decl, decl->getLocation(), getResourceBinding(decl),
  1024. decl->getAttr<VKBindingAttr>(), decl->getAttr<VKCounterBindingAttr>());
  1025. return bufferVar;
  1026. }
  1027. SpirvVariable *DeclResultIdMapper::createPushConstant(const VarDecl *decl) {
  1028. // The front-end errors out if non-struct type push constant is used.
  1029. const QualType type = decl->getType();
  1030. const auto *recordType = type->getAs<RecordType>();
  1031. if (isConstantBuffer(type)) {
  1032. // Get the templated type for ConstantBuffer.
  1033. recordType = hlsl::GetHLSLResourceResultType(type)->getAs<RecordType>();
  1034. }
  1035. assert(recordType);
  1036. const std::string structName =
  1037. "type.PushConstant." + recordType->getDecl()->getName().str();
  1038. SpirvVariable *var = createStructOrStructArrayVarOfExplicitLayout(
  1039. recordType->getDecl(), /*arraySize*/ 0, ContextUsageKind::PushConstant,
  1040. structName, decl->getName());
  1041. // Register the VarDecl
  1042. astDecls[decl] = DeclSpirvInfo(var);
  1043. // Do not push this variable into resourceVars since it does not need
  1044. // descriptor set.
  1045. return var;
  1046. }
  1047. SpirvVariable *
  1048. DeclResultIdMapper::createShaderRecordBuffer(const VarDecl *decl,
  1049. ContextUsageKind kind) {
  1050. const auto *recordType =
  1051. hlsl::GetHLSLResourceResultType(decl->getType())->getAs<RecordType>();
  1052. assert(recordType);
  1053. assert(kind == ContextUsageKind::ShaderRecordBufferEXT ||
  1054. kind == ContextUsageKind::ShaderRecordBufferNV);
  1055. const auto typeName = kind == ContextUsageKind::ShaderRecordBufferEXT
  1056. ? "type.ShaderRecordBufferEXT."
  1057. : "type.ShaderRecordBufferNV.";
  1058. const std::string structName =
  1059. typeName + recordType->getDecl()->getName().str();
  1060. SpirvVariable *var = createStructOrStructArrayVarOfExplicitLayout(
  1061. recordType->getDecl(), /*arraySize*/ 0,
  1062. kind, structName, decl->getName());
  1063. // Register the VarDecl
  1064. astDecls[decl] = DeclSpirvInfo(var);
  1065. // Do not push this variable into resourceVars since it does not need
  1066. // descriptor set.
  1067. return var;
  1068. }
  1069. SpirvVariable *
  1070. DeclResultIdMapper::createShaderRecordBuffer(const HLSLBufferDecl *decl,
  1071. ContextUsageKind kind) {
  1072. assert(kind == ContextUsageKind::ShaderRecordBufferEXT ||
  1073. kind == ContextUsageKind::ShaderRecordBufferNV);
  1074. const auto typeName = kind == ContextUsageKind::ShaderRecordBufferEXT
  1075. ? "type.ShaderRecordBufferEXT."
  1076. : "type.ShaderRecordBufferNV.";
  1077. const std::string structName =
  1078. typeName + decl->getName().str();
  1079. // The front-end does not allow arrays of cbuffer/tbuffer.
  1080. SpirvVariable *bufferVar = createStructOrStructArrayVarOfExplicitLayout(
  1081. decl, /*arraySize*/ 0, kind, structName,
  1082. decl->getName());
  1083. // We still register all VarDecls seperately here. All the VarDecls are
  1084. // mapped to the <result-id> of the buffer object, which means when
  1085. // querying the <result-id> for a certain VarDecl, we need to do an extra
  1086. // OpAccessChain.
  1087. int index = 0;
  1088. for (const auto *subDecl : decl->decls()) {
  1089. if (shouldSkipInStructLayout(subDecl))
  1090. continue;
  1091. const auto *varDecl = cast<VarDecl>(subDecl);
  1092. astDecls[varDecl] = DeclSpirvInfo(bufferVar, index++);
  1093. }
  1094. return bufferVar;
  1095. }
  1096. void DeclResultIdMapper::createGlobalsCBuffer(const VarDecl *var) {
  1097. if (astDecls.count(var) != 0)
  1098. return;
  1099. const auto *context = var->getTranslationUnitDecl();
  1100. SpirvVariable *globals = createStructOrStructArrayVarOfExplicitLayout(
  1101. context, /*arraySize*/ 0, ContextUsageKind::Globals, "type.$Globals",
  1102. "$Globals");
  1103. resourceVars.emplace_back(globals, /*decl*/ nullptr, SourceLocation(),
  1104. nullptr, nullptr, nullptr, /*isCounterVar*/ false,
  1105. /*isGlobalsCBuffer*/ true);
  1106. uint32_t index = 0;
  1107. for (const auto *decl : collectDeclsInDeclContext(context)) {
  1108. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  1109. if (!spirvOptions.noWarnIgnoredFeatures) {
  1110. if (const auto *init = varDecl->getInit())
  1111. emitWarning(
  1112. "variable '%0' will be placed in $Globals so initializer ignored",
  1113. init->getExprLoc())
  1114. << var->getName() << init->getSourceRange();
  1115. }
  1116. if (const auto *attr = varDecl->getAttr<VKBindingAttr>()) {
  1117. emitError("variable '%0' will be placed in $Globals so cannot have "
  1118. "vk::binding attribute",
  1119. attr->getLocation())
  1120. << var->getName();
  1121. return;
  1122. }
  1123. astDecls[varDecl] = DeclSpirvInfo(globals, index++);
  1124. }
  1125. }
  1126. }
  1127. SpirvFunction *DeclResultIdMapper::getOrRegisterFn(const FunctionDecl *fn) {
  1128. // Return it if it's already been created.
  1129. auto it = astFunctionDecls.find(fn);
  1130. if (it != astFunctionDecls.end()) {
  1131. return it->second;
  1132. }
  1133. bool isAlias = false;
  1134. (void)getTypeAndCreateCounterForPotentialAliasVar(fn, &isAlias);
  1135. const bool isPrecise = fn->hasAttr<HLSLPreciseAttr>();
  1136. const bool isNoInline = fn->hasAttr<NoInlineAttr>();
  1137. // Note: we do not need to worry about function parameter types at this point
  1138. // as this is used when function declarations are seen. When function
  1139. // definition is seen, the parameter types will be set properly and take into
  1140. // account whether the function is a member function of a class/struct (in
  1141. // which case a 'this' parameter is added at the beginnig).
  1142. SpirvFunction *spirvFunction =
  1143. spvBuilder.createSpirvFunction(fn->getReturnType(), fn->getLocation(),
  1144. fn->getName(), isPrecise, isNoInline);
  1145. // No need to dereference to get the pointer. Function returns that are
  1146. // stand-alone aliases are already pointers to values. All other cases should
  1147. // be normal rvalues.
  1148. if (!isAlias || !isAKindOfStructuredOrByteBuffer(fn->getReturnType()))
  1149. spirvFunction->setRValue();
  1150. spirvFunction->setConstainsAliasComponent(isAlias);
  1151. astFunctionDecls[fn] = spirvFunction;
  1152. return spirvFunction;
  1153. }
  1154. const CounterIdAliasPair *DeclResultIdMapper::getCounterIdAliasPair(
  1155. const DeclaratorDecl *decl, const llvm::SmallVector<uint32_t, 4> *indices) {
  1156. if (!decl)
  1157. return nullptr;
  1158. if (indices) {
  1159. // Indices are provided. Walk through the fields of the decl.
  1160. const auto counter = fieldCounterVars.find(decl);
  1161. if (counter != fieldCounterVars.end())
  1162. return counter->second.get(*indices);
  1163. } else {
  1164. // No indices. Check the stand-alone entities.
  1165. const auto counter = counterVars.find(decl);
  1166. if (counter != counterVars.end())
  1167. return &counter->second;
  1168. }
  1169. return nullptr;
  1170. }
  1171. const CounterVarFields *
  1172. DeclResultIdMapper::getCounterVarFields(const DeclaratorDecl *decl) {
  1173. if (!decl)
  1174. return nullptr;
  1175. const auto found = fieldCounterVars.find(decl);
  1176. if (found != fieldCounterVars.end())
  1177. return &found->second;
  1178. return nullptr;
  1179. }
  1180. void DeclResultIdMapper::registerSpecConstant(const VarDecl *decl,
  1181. SpirvInstruction *specConstant) {
  1182. specConstant->setRValue();
  1183. astDecls[decl] = DeclSpirvInfo(specConstant);
  1184. }
  1185. void DeclResultIdMapper::createCounterVar(
  1186. const DeclaratorDecl *decl, SpirvInstruction *declInstr, bool isAlias,
  1187. const llvm::SmallVector<uint32_t, 4> *indices) {
  1188. std::string counterName = "counter.var." + decl->getName().str();
  1189. if (indices) {
  1190. // Append field indices to the name
  1191. for (const auto index : *indices)
  1192. counterName += "." + std::to_string(index);
  1193. }
  1194. const SpirvType *counterType = spvContext.getACSBufferCounterType();
  1195. // {RW|Append|Consume}StructuredBuffer are all in Uniform storage class.
  1196. // Alias counter variables should be created into the Private storage class.
  1197. const spv::StorageClass sc =
  1198. isAlias ? spv::StorageClass::Private : spv::StorageClass::Uniform;
  1199. if (isAlias) {
  1200. // Apply an extra level of pointer for alias counter variable
  1201. counterType =
  1202. spvContext.getPointerType(counterType, spv::StorageClass::Uniform);
  1203. }
  1204. SpirvVariable *counterInstr = spvBuilder.addModuleVar(
  1205. counterType, sc, /*isPrecise*/ false, counterName);
  1206. if (!isAlias) {
  1207. // Non-alias counter variables should be put in to resourceVars so that
  1208. // descriptors can be allocated for them.
  1209. resourceVars.emplace_back(counterInstr, decl, decl->getLocation(),
  1210. getResourceBinding(decl),
  1211. decl->getAttr<VKBindingAttr>(),
  1212. decl->getAttr<VKCounterBindingAttr>(), true);
  1213. assert(declInstr);
  1214. spvBuilder.decorateCounterBuffer(declInstr, counterInstr,
  1215. decl->getLocation());
  1216. }
  1217. if (indices)
  1218. fieldCounterVars[decl].append(*indices, counterInstr);
  1219. else
  1220. counterVars[decl] = {counterInstr, isAlias};
  1221. }
  1222. void DeclResultIdMapper::createFieldCounterVars(
  1223. const DeclaratorDecl *rootDecl, const DeclaratorDecl *decl,
  1224. llvm::SmallVector<uint32_t, 4> *indices) {
  1225. const QualType type = getTypeOrFnRetType(decl);
  1226. const auto *recordType = type->getAs<RecordType>();
  1227. assert(recordType);
  1228. const auto *recordDecl = recordType->getDecl();
  1229. for (const auto *field : recordDecl->fields()) {
  1230. // Build up the index chain
  1231. indices->push_back(getNumBaseClasses(type) + field->getFieldIndex());
  1232. const QualType fieldType = field->getType();
  1233. if (isRWAppendConsumeSBuffer(fieldType))
  1234. createCounterVar(rootDecl, /*declId=*/0, /*isAlias=*/true, indices);
  1235. else if (fieldType->isStructureType() &&
  1236. !hlsl::IsHLSLResourceType(fieldType))
  1237. // Go recursively into all nested structs
  1238. createFieldCounterVars(rootDecl, field, indices);
  1239. indices->pop_back();
  1240. }
  1241. }
  1242. const SpirvType *
  1243. DeclResultIdMapper::getCTBufferPushConstantType(const DeclContext *decl) {
  1244. const auto found = ctBufferPCTypes.find(decl);
  1245. assert(found != ctBufferPCTypes.end());
  1246. return found->second;
  1247. }
  1248. std::vector<SpirvVariable *> DeclResultIdMapper::collectStageVars() const {
  1249. std::vector<SpirvVariable *> vars;
  1250. for (auto var : glPerVertex.getStageInVars())
  1251. vars.push_back(var);
  1252. for (auto var : glPerVertex.getStageOutVars())
  1253. vars.push_back(var);
  1254. llvm::DenseSet<SpirvInstruction *> seenVars;
  1255. for (const auto &var : stageVars) {
  1256. auto *instr = var.getSpirvInstr();
  1257. if (seenVars.count(instr) == 0) {
  1258. vars.push_back(instr);
  1259. seenVars.insert(instr);
  1260. }
  1261. }
  1262. return vars;
  1263. }
  1264. namespace {
  1265. /// A class for managing stage input/output locations to avoid duplicate uses of
  1266. /// the same location.
  1267. class LocationSet {
  1268. public:
  1269. /// Maximum number of indices supported
  1270. const static uint32_t kMaxIndex = 2;
  1271. /// Maximum number of locations supported
  1272. // Typically we won't have that many stage input or output variables.
  1273. // Using 64 should be fine here.
  1274. const static uint32_t kMaxLoc = 64;
  1275. LocationSet() {
  1276. for (uint32_t i = 0; i < kMaxIndex; ++i) {
  1277. usedLocs[i].resize(kMaxLoc);
  1278. nextLoc[i] = 0;
  1279. }
  1280. }
  1281. /// Uses the given location.
  1282. void useLoc(uint32_t loc, uint32_t index = 0) {
  1283. assert(index < kMaxIndex);
  1284. usedLocs[index].set(loc);
  1285. }
  1286. /// Uses the next |count| available location.
  1287. int useNextLocs(uint32_t count, uint32_t index = 0) {
  1288. assert(index < kMaxIndex);
  1289. auto &locs = usedLocs[index];
  1290. auto &next = nextLoc[index];
  1291. while (locs[next])
  1292. next++;
  1293. int toUse = next;
  1294. for (uint32_t i = 0; i < count; ++i) {
  1295. assert(!locs[next]);
  1296. locs.set(next++);
  1297. }
  1298. return toUse;
  1299. }
  1300. /// Returns true if the given location number is already used.
  1301. bool isLocUsed(uint32_t loc, uint32_t index = 0) {
  1302. assert(index < kMaxIndex);
  1303. return usedLocs[index][loc];
  1304. }
  1305. private:
  1306. llvm::SmallBitVector usedLocs[kMaxIndex]; ///< All previously used locations
  1307. uint32_t nextLoc[kMaxIndex]; ///< Next available location
  1308. };
  1309. /// A class for managing resource bindings to avoid duplicate uses of the same
  1310. /// set and binding number.
  1311. class BindingSet {
  1312. public:
  1313. /// Uses the given set and binding number. Returns false if the binding number
  1314. /// was already occupied in the set, and returns true otherwise.
  1315. bool useBinding(uint32_t binding, uint32_t set) {
  1316. bool inserted = false;
  1317. std::tie(std::ignore, inserted) = usedBindings[set].insert(binding);
  1318. return inserted;
  1319. }
  1320. /// Uses the next available binding number in |set|. If more than one binding
  1321. /// number is to be occupied, it finds the next available chunk that can fit
  1322. /// |numBindingsToUse| in the |set|.
  1323. uint32_t useNextBinding(uint32_t set, uint32_t numBindingsToUse = 1,
  1324. uint32_t bindingShift = 0) {
  1325. uint32_t bindingNoStart =
  1326. getNextBindingChunk(set, numBindingsToUse, bindingShift);
  1327. auto &binding = usedBindings[set];
  1328. for (uint32_t i = 0; i < numBindingsToUse; ++i)
  1329. binding.insert(bindingNoStart + i);
  1330. return bindingNoStart;
  1331. }
  1332. /// Returns the first available binding number in the |set| for which |n|
  1333. /// consecutive binding numbers are unused starting at |bindingShift|.
  1334. uint32_t getNextBindingChunk(uint32_t set, uint32_t n,
  1335. uint32_t bindingShift) {
  1336. auto &existingBindings = usedBindings[set];
  1337. // There were no bindings in this set. Can start at binding zero.
  1338. if (existingBindings.empty())
  1339. return bindingShift;
  1340. // Check whether the chunk of |n| binding numbers can be fitted at the
  1341. // very beginning of the list (start at binding 0 in the current set).
  1342. uint32_t curBinding = *existingBindings.begin();
  1343. if (curBinding >= (n + bindingShift))
  1344. return bindingShift;
  1345. auto iter = std::next(existingBindings.begin());
  1346. while (iter != existingBindings.end()) {
  1347. // There exists a next binding number that is used. Check to see if the
  1348. // gap between current binding number and next binding number is large
  1349. // enough to accommodate |n|.
  1350. uint32_t nextBinding = *iter;
  1351. if ((bindingShift > 0) && (curBinding < (bindingShift - 1)))
  1352. curBinding = bindingShift - 1;
  1353. if (curBinding < nextBinding && n <= nextBinding - curBinding - 1)
  1354. return curBinding + 1;
  1355. curBinding = nextBinding;
  1356. // Peek at the next binding that has already been used (if any).
  1357. ++iter;
  1358. }
  1359. // |curBinding| was the last binding that was used in this set. The next
  1360. // chunk of |n| bindings can start at |curBinding|+1.
  1361. return std::max(curBinding + 1, bindingShift);
  1362. }
  1363. private:
  1364. ///< set number -> set of used binding number
  1365. llvm::DenseMap<uint32_t, std::set<uint32_t>> usedBindings;
  1366. };
  1367. } // namespace
  1368. bool DeclResultIdMapper::checkSemanticDuplication(bool forInput) {
  1369. llvm::StringSet<> seenSemantics;
  1370. bool success = true;
  1371. for (const auto &var : stageVars) {
  1372. auto s = var.getSemanticStr();
  1373. if (s.empty()) {
  1374. // We translate WaveGetLaneCount(), WaveGetLaneIndex() and 'payload' param
  1375. // block declaration into builtin variables. Those variables are inserted
  1376. // into the normal stage IO processing pipeline, but with the semantics as
  1377. // empty strings.
  1378. assert(var.isSpirvBuitin());
  1379. continue;
  1380. }
  1381. // Allow builtin variables to alias each other. We already have uniqify
  1382. // mechanism in SpirvBuilder.
  1383. if (var.isSpirvBuitin())
  1384. continue;
  1385. if (forInput && var.getSigPoint()->IsInput()) {
  1386. if (seenSemantics.count(s)) {
  1387. emitError("input semantic '%0' used more than once", {}) << s;
  1388. success = false;
  1389. }
  1390. seenSemantics.insert(s);
  1391. } else if (!forInput && var.getSigPoint()->IsOutput()) {
  1392. if (seenSemantics.count(s)) {
  1393. emitError("output semantic '%0' used more than once", {}) << s;
  1394. success = false;
  1395. }
  1396. seenSemantics.insert(s);
  1397. }
  1398. }
  1399. return success;
  1400. }
  1401. bool DeclResultIdMapper::finalizeStageIOLocations(bool forInput) {
  1402. if (!checkSemanticDuplication(forInput))
  1403. return false;
  1404. // Returns false if the given StageVar is an input/output variable without
  1405. // explicit location assignment. Otherwise, returns true.
  1406. const auto locAssigned = [forInput, this](const StageVar &v) {
  1407. if (forInput == isInputStorageClass(v))
  1408. // No need to assign location for builtins. Treat as assigned.
  1409. return v.isSpirvBuitin() || v.getLocationAttr() != nullptr;
  1410. // For the ones we don't care, treat as assigned.
  1411. return true;
  1412. };
  1413. // If we have explicit location specified for all input/output variables,
  1414. // use them instead assign by ourselves.
  1415. if (std::all_of(stageVars.begin(), stageVars.end(), locAssigned)) {
  1416. LocationSet locSet;
  1417. bool noError = true;
  1418. for (const auto &var : stageVars) {
  1419. // Skip builtins & those stage variables we are not handling for this call
  1420. if (var.isSpirvBuitin() || forInput != isInputStorageClass(var))
  1421. continue;
  1422. const auto *attr = var.getLocationAttr();
  1423. const auto loc = attr->getNumber();
  1424. const auto attrLoc = attr->getLocation(); // Attr source code location
  1425. const auto idx = var.getIndexAttr() ? var.getIndexAttr()->getNumber() : 0;
  1426. if ((const unsigned)loc >= LocationSet::kMaxLoc) {
  1427. emitError("stage %select{output|input}0 location #%1 too large",
  1428. attrLoc)
  1429. << forInput << loc;
  1430. return false;
  1431. }
  1432. // Make sure the same location is not assigned more than once
  1433. if (locSet.isLocUsed(loc, idx)) {
  1434. emitError("stage %select{output|input}0 location #%1 already assigned",
  1435. attrLoc)
  1436. << forInput << loc;
  1437. noError = false;
  1438. }
  1439. locSet.useLoc(loc, idx);
  1440. spvBuilder.decorateLocation(var.getSpirvInstr(), loc);
  1441. if (var.getIndexAttr())
  1442. spvBuilder.decorateIndex(var.getSpirvInstr(), idx,
  1443. var.getSemanticInfo().loc);
  1444. }
  1445. return noError;
  1446. }
  1447. std::vector<const StageVar *> vars;
  1448. LocationSet locSet;
  1449. for (const auto &var : stageVars) {
  1450. if (var.isSpirvBuitin() || forInput != isInputStorageClass(var))
  1451. continue;
  1452. if (var.getLocationAttr()) {
  1453. // We have checked that not all of the stage variables have explicit
  1454. // location assignment.
  1455. emitError("partial explicit stage %select{output|input}0 location "
  1456. "assignment via vk::location(X) unsupported",
  1457. {})
  1458. << forInput;
  1459. return false;
  1460. }
  1461. const auto &semaInfo = var.getSemanticInfo();
  1462. // We should special rules for SV_Target: the location number comes from the
  1463. // semantic string index.
  1464. if (semaInfo.isTarget()) {
  1465. spvBuilder.decorateLocation(var.getSpirvInstr(), semaInfo.index);
  1466. locSet.useLoc(semaInfo.index);
  1467. } else {
  1468. vars.push_back(&var);
  1469. }
  1470. }
  1471. // If alphabetical ordering was requested, sort by semantic string.
  1472. // Since HS includes 2 sets of outputs (patch-constant output and
  1473. // OutputPatch), running into location mismatches between HS and DS is very
  1474. // likely. In order to avoid location mismatches between HS and DS, use
  1475. // alphabetical ordering.
  1476. if (spirvOptions.stageIoOrder == "alpha" ||
  1477. (!forInput && spvContext.isHS()) || (forInput && spvContext.isDS())) {
  1478. // Sort stage input/output variables alphabetically
  1479. std::sort(vars.begin(), vars.end(),
  1480. [](const StageVar *a, const StageVar *b) {
  1481. return a->getSemanticStr() < b->getSemanticStr();
  1482. });
  1483. }
  1484. for (const auto *var : vars)
  1485. spvBuilder.decorateLocation(var->getSpirvInstr(),
  1486. locSet.useNextLocs(var->getLocationCount()));
  1487. return true;
  1488. }
  1489. namespace {
  1490. /// A class for maintaining the binding number shift requested for descriptor
  1491. /// sets.
  1492. class BindingShiftMapper {
  1493. public:
  1494. explicit BindingShiftMapper(const llvm::SmallVectorImpl<int32_t> &shifts)
  1495. : masterShift(0) {
  1496. assert(shifts.size() % 2 == 0);
  1497. if (shifts.size() == 2 && shifts[1] == -1) {
  1498. masterShift = shifts[0];
  1499. } else {
  1500. for (uint32_t i = 0; i < shifts.size(); i += 2)
  1501. perSetShift[shifts[i + 1]] = shifts[i];
  1502. }
  1503. }
  1504. /// Returns the shift amount for the given set.
  1505. int32_t getShiftForSet(int32_t set) const {
  1506. const auto found = perSetShift.find(set);
  1507. if (found != perSetShift.end())
  1508. return found->second;
  1509. return masterShift;
  1510. }
  1511. private:
  1512. uint32_t masterShift; /// Shift amount applies to all sets.
  1513. llvm::DenseMap<int32_t, int32_t> perSetShift;
  1514. };
  1515. /// A class for maintaining the mapping from source code register attributes to
  1516. /// descriptor set and number settings.
  1517. class RegisterBindingMapper {
  1518. public:
  1519. /// Takes in the relation between register attributes and descriptor settings.
  1520. /// Each relation is represented by four strings:
  1521. /// <register-type-number> <space> <descriptor-binding> <set>
  1522. bool takeInRelation(const std::vector<std::string> &relation,
  1523. std::string *error) {
  1524. assert(relation.size() % 4 == 0);
  1525. mapping.clear();
  1526. for (uint32_t i = 0; i < relation.size(); i += 4) {
  1527. int32_t spaceNo = -1, setNo = -1, bindNo = -1;
  1528. if (StringRef(relation[i + 1]).getAsInteger(10, spaceNo) || spaceNo < 0) {
  1529. *error = "space number: " + relation[i + 1];
  1530. return false;
  1531. }
  1532. if (StringRef(relation[i + 2]).getAsInteger(10, bindNo) || bindNo < 0) {
  1533. *error = "binding number: " + relation[i + 2];
  1534. return false;
  1535. }
  1536. if (StringRef(relation[i + 3]).getAsInteger(10, setNo) || setNo < 0) {
  1537. *error = "set number: " + relation[i + 3];
  1538. return false;
  1539. }
  1540. mapping[relation[i + 1] + relation[i]] = std::make_pair(setNo, bindNo);
  1541. }
  1542. return true;
  1543. }
  1544. /// Returns true and set the correct set and binding number if we can find a
  1545. /// descriptor setting for the given register. False otherwise.
  1546. bool getSetBinding(const hlsl::RegisterAssignment *regAttr,
  1547. uint32_t defaultSpace, int *setNo, int *bindNo) const {
  1548. std::ostringstream iss;
  1549. iss << regAttr->RegisterSpace.getValueOr(defaultSpace)
  1550. << regAttr->RegisterType << regAttr->RegisterNumber;
  1551. auto found = mapping.find(iss.str());
  1552. if (found != mapping.end()) {
  1553. *setNo = found->second.first;
  1554. *bindNo = found->second.second;
  1555. return true;
  1556. }
  1557. return false;
  1558. }
  1559. private:
  1560. llvm::StringMap<std::pair<int, int>> mapping;
  1561. };
  1562. } // namespace
  1563. bool DeclResultIdMapper::decorateResourceBindings() {
  1564. // For normal resource, we support 4 approaches of setting binding numbers:
  1565. // - m1: [[vk::binding(...)]]
  1566. // - m2: :register(xX, spaceY)
  1567. // - m3: None
  1568. // - m4: :register(spaceY)
  1569. //
  1570. // For associated counters, we support 2 approaches:
  1571. // - c1: [[vk::counter_binding(...)]
  1572. // - c2: None
  1573. //
  1574. // In combination, we need to handle 12 cases:
  1575. // - 4 cases for nomral resoures (m1, m2, m3, m4)
  1576. // - 8 cases for associated counters (mX * cY)
  1577. //
  1578. // In the following order:
  1579. // - m1, mX * c1
  1580. // - m2
  1581. // - m3, m4, mX * c2
  1582. // The "-auto-binding-space" command line option can be used to specify a
  1583. // certain space as default. UINT_MAX means the user has not provided this
  1584. // option. If not provided, the SPIR-V backend uses space "0" as default.
  1585. auto defaultSpaceOpt =
  1586. theEmitter.getCompilerInstance().getCodeGenOpts().HLSLDefaultSpace;
  1587. uint32_t defaultSpace = (defaultSpaceOpt == UINT_MAX) ? 0 : defaultSpaceOpt;
  1588. const bool bindGlobals = !spirvOptions.bindGlobals.empty();
  1589. int32_t globalsBindNo = -1, globalsSetNo = -1;
  1590. if (bindGlobals) {
  1591. assert(spirvOptions.bindGlobals.size() == 2);
  1592. if (StringRef(spirvOptions.bindGlobals[0])
  1593. .getAsInteger(10, globalsBindNo) ||
  1594. globalsBindNo < 0) {
  1595. emitError("invalid -fvk-bind-globals binding number: %0", {})
  1596. << spirvOptions.bindGlobals[0];
  1597. return false;
  1598. }
  1599. if (StringRef(spirvOptions.bindGlobals[1]).getAsInteger(10, globalsSetNo) ||
  1600. globalsSetNo < 0) {
  1601. emitError("invalid -fvk-bind-globals set number: %0", {})
  1602. << spirvOptions.bindGlobals[1];
  1603. return false;
  1604. }
  1605. }
  1606. // Special handling of -fvk-bind-register, which requires
  1607. // * All resources are annoated with :register() in the source code
  1608. // * -fvk-bind-register is specified for every resource
  1609. if (!spirvOptions.bindRegister.empty()) {
  1610. RegisterBindingMapper bindingMapper;
  1611. std::string error;
  1612. if (!bindingMapper.takeInRelation(spirvOptions.bindRegister, &error)) {
  1613. emitError("invalid -fvk-bind-register %0", {}) << error;
  1614. return false;
  1615. }
  1616. for (const auto &var : resourceVars)
  1617. if (const auto *regAttr = var.getRegister()) {
  1618. if (var.isCounter()) {
  1619. emitError("-fvk-bind-register for RW/Append/Consume StructuredBuffer "
  1620. "unimplemented",
  1621. var.getSourceLocation());
  1622. } else {
  1623. int setNo = 0, bindNo = 0;
  1624. if (!bindingMapper.getSetBinding(regAttr, defaultSpace, &setNo,
  1625. &bindNo)) {
  1626. emitError("missing -fvk-bind-register for resource",
  1627. var.getSourceLocation());
  1628. return false;
  1629. }
  1630. spvBuilder.decorateDSetBinding(var.getSpirvInstr(), setNo, bindNo);
  1631. }
  1632. } else if (bindGlobals && var.isGlobalsBuffer()) {
  1633. spvBuilder.decorateDSetBinding(var.getSpirvInstr(), globalsSetNo,
  1634. globalsBindNo);
  1635. } else {
  1636. emitError(
  1637. "-fvk-bind-register requires register annotations on all resources",
  1638. var.getSourceLocation());
  1639. return false;
  1640. }
  1641. return true;
  1642. }
  1643. BindingSet bindingSet;
  1644. // Decorates the given varId of the given category with set number
  1645. // setNo, binding number bindingNo. Ignores overlaps.
  1646. const auto tryToDecorate = [this, &bindingSet](const ResourceVar &var,
  1647. const uint32_t setNo,
  1648. const uint32_t bindingNo) {
  1649. // By default we use one binding number per resource, and an array of
  1650. // resources also gets only one binding number. However, for array of
  1651. // resources (e.g. array of textures), DX uses one binding number per array
  1652. // element. We can match this behavior via a command line option.
  1653. uint32_t numBindingsToUse = 1;
  1654. if (spirvOptions.flattenResourceArrays || needsFlatteningCompositeResources)
  1655. numBindingsToUse = getNumBindingsUsedByResourceType(
  1656. var.getSpirvInstr()->getAstResultType());
  1657. for (uint32_t i = 0; i < numBindingsToUse; ++i) {
  1658. bool success = bindingSet.useBinding(bindingNo + i, setNo);
  1659. // We will not emit an error if we find a set/binding overlap because it
  1660. // is possible that the optimizer optimizes away a resource which resolves
  1661. // the overlap.
  1662. (void)success;
  1663. }
  1664. // No need to decorate multiple binding numbers for arrays. It will be done
  1665. // by legalization/optimization.
  1666. spvBuilder.decorateDSetBinding(var.getSpirvInstr(), setNo, bindingNo);
  1667. };
  1668. for (const auto &var : resourceVars) {
  1669. if (var.isCounter()) {
  1670. if (const auto *vkCBinding = var.getCounterBinding()) {
  1671. // Process mX * c1
  1672. uint32_t set = defaultSpace;
  1673. if (const auto *vkBinding = var.getBinding())
  1674. set = getVkBindingAttrSet(vkBinding, defaultSpace);
  1675. else if (const auto *reg = var.getRegister())
  1676. set = reg->RegisterSpace.getValueOr(defaultSpace);
  1677. tryToDecorate(var, set, vkCBinding->getBinding());
  1678. }
  1679. } else {
  1680. if (const auto *vkBinding = var.getBinding()) {
  1681. // Process m1
  1682. tryToDecorate(var, getVkBindingAttrSet(vkBinding, defaultSpace),
  1683. vkBinding->getBinding());
  1684. }
  1685. }
  1686. }
  1687. BindingShiftMapper bShiftMapper(spirvOptions.bShift);
  1688. BindingShiftMapper tShiftMapper(spirvOptions.tShift);
  1689. BindingShiftMapper sShiftMapper(spirvOptions.sShift);
  1690. BindingShiftMapper uShiftMapper(spirvOptions.uShift);
  1691. // Process m2
  1692. for (const auto &var : resourceVars)
  1693. if (!var.isCounter() && !var.getBinding())
  1694. if (const auto *reg = var.getRegister()) {
  1695. // Skip space-only register() annotations
  1696. if (reg->isSpaceOnly())
  1697. continue;
  1698. const uint32_t set = reg->RegisterSpace.getValueOr(defaultSpace);
  1699. uint32_t binding = reg->RegisterNumber;
  1700. switch (reg->RegisterType) {
  1701. case 'b':
  1702. binding += bShiftMapper.getShiftForSet(set);
  1703. break;
  1704. case 't':
  1705. binding += tShiftMapper.getShiftForSet(set);
  1706. break;
  1707. case 's':
  1708. binding += sShiftMapper.getShiftForSet(set);
  1709. break;
  1710. case 'u':
  1711. binding += uShiftMapper.getShiftForSet(set);
  1712. break;
  1713. case 'c':
  1714. // For setting packing offset. Does not affect binding.
  1715. break;
  1716. default:
  1717. llvm_unreachable("unknown register type found");
  1718. }
  1719. tryToDecorate(var, set, binding);
  1720. }
  1721. for (const auto &var : resourceVars) {
  1722. // By default we use one binding number per resource, and an array of
  1723. // resources also gets only one binding number. However, for array of
  1724. // resources (e.g. array of textures), DX uses one binding number per array
  1725. // element. We can match this behavior via a command line option.
  1726. uint32_t numBindingsToUse = 1;
  1727. if (spirvOptions.flattenResourceArrays || needsFlatteningCompositeResources)
  1728. numBindingsToUse = getNumBindingsUsedByResourceType(
  1729. var.getSpirvInstr()->getAstResultType());
  1730. BindingShiftMapper *bindingShiftMapper = nullptr;
  1731. if (spirvOptions.autoShiftBindings) {
  1732. char registerType = '\0';
  1733. if (getImplicitRegisterType(var, &registerType)) {
  1734. switch (registerType) {
  1735. case 'b':
  1736. bindingShiftMapper = &bShiftMapper;
  1737. break;
  1738. case 't':
  1739. bindingShiftMapper = &tShiftMapper;
  1740. break;
  1741. case 's':
  1742. bindingShiftMapper = &sShiftMapper;
  1743. break;
  1744. case 'u':
  1745. bindingShiftMapper = &uShiftMapper;
  1746. break;
  1747. default:
  1748. llvm_unreachable("unknown register type found");
  1749. }
  1750. }
  1751. }
  1752. if (var.isCounter()) {
  1753. if (!var.getCounterBinding()) {
  1754. // Process mX * c2
  1755. uint32_t set = defaultSpace;
  1756. if (const auto *vkBinding = var.getBinding())
  1757. set = getVkBindingAttrSet(vkBinding, defaultSpace);
  1758. else if (const auto *reg = var.getRegister())
  1759. set = reg->RegisterSpace.getValueOr(defaultSpace);
  1760. uint32_t bindingShift = 0;
  1761. if (bindingShiftMapper)
  1762. bindingShift = bindingShiftMapper->getShiftForSet(set);
  1763. spvBuilder.decorateDSetBinding(
  1764. var.getSpirvInstr(), set,
  1765. bindingSet.useNextBinding(set, numBindingsToUse, bindingShift));
  1766. }
  1767. } else if (!var.getBinding()) {
  1768. const auto *reg = var.getRegister();
  1769. if (reg && reg->isSpaceOnly()) {
  1770. const uint32_t set = reg->RegisterSpace.getValueOr(defaultSpace);
  1771. uint32_t bindingShift = 0;
  1772. if (bindingShiftMapper)
  1773. bindingShift = bindingShiftMapper->getShiftForSet(set);
  1774. spvBuilder.decorateDSetBinding(
  1775. var.getSpirvInstr(), set,
  1776. bindingSet.useNextBinding(set, numBindingsToUse, bindingShift));
  1777. } else if (!reg) {
  1778. // Process m3 (no 'vk::binding' and no ':register' assignment)
  1779. // There is a special case for the $Globals cbuffer. The $Globals buffer
  1780. // doesn't have either 'vk::binding' or ':register', but the user may
  1781. // ask for a specific binding for it via command line options.
  1782. if (bindGlobals && var.isGlobalsBuffer()) {
  1783. uint32_t bindingShift = 0;
  1784. if (bindingShiftMapper)
  1785. bindingShift = bindingShiftMapper->getShiftForSet(globalsSetNo);
  1786. spvBuilder.decorateDSetBinding(var.getSpirvInstr(), globalsSetNo,
  1787. globalsBindNo + bindingShift);
  1788. }
  1789. // The normal case
  1790. else {
  1791. uint32_t bindingShift = 0;
  1792. if (bindingShiftMapper)
  1793. bindingShift = bindingShiftMapper->getShiftForSet(defaultSpace);
  1794. spvBuilder.decorateDSetBinding(
  1795. var.getSpirvInstr(), defaultSpace,
  1796. bindingSet.useNextBinding(defaultSpace, numBindingsToUse,
  1797. bindingShift));
  1798. }
  1799. }
  1800. }
  1801. }
  1802. return true;
  1803. }
  1804. bool DeclResultIdMapper::decorateResourceCoherent() {
  1805. for (const auto &var : resourceVars) {
  1806. if (const auto *decl = var.getDeclaration()) {
  1807. if (decl->getAttr<HLSLGloballyCoherentAttr>()) {
  1808. spvBuilder.decorateCoherent(var.getSpirvInstr(),
  1809. var.getSourceLocation());
  1810. }
  1811. }
  1812. }
  1813. return true;
  1814. }
  1815. bool DeclResultIdMapper::createStageVars(
  1816. const hlsl::SigPoint *sigPoint, const NamedDecl *decl, bool asInput,
  1817. QualType type, uint32_t arraySize, const llvm::StringRef namePrefix,
  1818. llvm::Optional<SpirvInstruction *> invocationId, SpirvInstruction **value,
  1819. bool noWriteBack, SemanticInfo *inheritSemantic) {
  1820. assert(value);
  1821. // invocationId should only be used for handling HS per-vertex output.
  1822. if (invocationId.hasValue()) {
  1823. assert(spvContext.isHS() && arraySize != 0 && !asInput);
  1824. }
  1825. assert(inheritSemantic);
  1826. if (type->isVoidType()) {
  1827. // No stage variables will be created for void type.
  1828. return true;
  1829. }
  1830. // The type the variable is evaluated as for SPIR-V.
  1831. QualType evalType = type;
  1832. // We have several cases regarding HLSL semantics to handle here:
  1833. // * If the currrent decl inherits a semantic from some enclosing entity,
  1834. // use the inherited semantic no matter whether there is a semantic
  1835. // attached to the current decl.
  1836. // * If there is no semantic to inherit,
  1837. // * If the current decl is a struct,
  1838. // * If the current decl has a semantic, all its members inhert this
  1839. // decl's semantic, with the index sequentially increasing;
  1840. // * If the current decl does not have a semantic, all its members
  1841. // should have semantics attached;
  1842. // * If the current decl is not a struct, it should have semantic attached.
  1843. auto thisSemantic = getStageVarSemantic(decl);
  1844. // Which semantic we should use for this decl
  1845. auto *semanticToUse = &thisSemantic;
  1846. // Enclosing semantics override internal ones
  1847. if (inheritSemantic->isValid()) {
  1848. if (thisSemantic.isValid()) {
  1849. emitWarning(
  1850. "internal semantic '%0' overridden by enclosing semantic '%1'",
  1851. thisSemantic.loc)
  1852. << thisSemantic.str << inheritSemantic->str;
  1853. }
  1854. semanticToUse = inheritSemantic;
  1855. }
  1856. const auto loc = decl->getLocation();
  1857. if (semanticToUse->isValid() &&
  1858. // Structs with attached semantics will be handled later.
  1859. !type->isStructureType()) {
  1860. // Found semantic attached directly to this Decl. This means we need to
  1861. // map this decl to a single stage variable.
  1862. if (!validateVKAttributes(decl))
  1863. return false;
  1864. const auto semanticKind = semanticToUse->getKind();
  1865. const auto sigPointKind = sigPoint->GetKind();
  1866. // Error out when the given semantic is invalid in this shader model
  1867. if (hlsl::SigPoint::GetInterpretation(semanticKind, sigPointKind,
  1868. spvContext.getMajorVersion(),
  1869. spvContext.getMinorVersion()) ==
  1870. hlsl::DXIL::SemanticInterpretationKind::NA) {
  1871. // Special handle MSIn/ASIn allowing VK-only builtin "DrawIndex".
  1872. switch (sigPointKind) {
  1873. case hlsl::SigPoint::Kind::MSIn:
  1874. case hlsl::SigPoint::Kind::ASIn:
  1875. if (const auto *builtinAttr = decl->getAttr<VKBuiltInAttr>()) {
  1876. const llvm::StringRef builtin = builtinAttr->getBuiltIn();
  1877. if (builtin == "DrawIndex") {
  1878. break;
  1879. }
  1880. }
  1881. // fall through
  1882. default:
  1883. emitError("invalid usage of semantic '%0' in shader profile %1", loc)
  1884. << semanticToUse->str
  1885. << hlsl::ShaderModel::GetKindName(
  1886. spvContext.getCurrentShaderModelKind());
  1887. return false;
  1888. }
  1889. }
  1890. if (!validateVKBuiltins(decl, sigPoint))
  1891. return false;
  1892. const auto *builtinAttr = decl->getAttr<VKBuiltInAttr>();
  1893. // Special handling of certain mappings between HLSL semantics and
  1894. // SPIR-V builtins:
  1895. // * SV_CullDistance/SV_ClipDistance are outsourced to GlPerVertex.
  1896. // * SV_DomainLocation can refer to a float2, whereas TessCoord is a float3.
  1897. // To ensure SPIR-V validity, we must create a float3 and extract a
  1898. // float2 from it before passing it to the main function.
  1899. // * SV_TessFactor is an array of size 2 for isoline patch, array of size 3
  1900. // for tri patch, and array of size 4 for quad patch, but it must always
  1901. // be an array of size 4 in SPIR-V for Vulkan.
  1902. // * SV_InsideTessFactor is a single float for tri patch, and an array of
  1903. // size 2 for a quad patch, but it must always be an array of size 2 in
  1904. // SPIR-V for Vulkan.
  1905. // * SV_Coverage is an uint value, but the builtin it corresponds to,
  1906. // SampleMask, must be an array of integers.
  1907. // * SV_InnerCoverage is an uint value, but the corresponding builtin,
  1908. // FullyCoveredEXT, must be an boolean value.
  1909. // * SV_DispatchThreadID, SV_GroupThreadID, and SV_GroupID are allowed to be
  1910. // uint, uint2, or uint3, but the corresponding builtins
  1911. // (GlobalInvocationId, LocalInvocationId, WorkgroupId) must be a uint3.
  1912. // * SV_ShadingRate is a uint value, but the builtin it corresponds to is a
  1913. // int2.
  1914. if (glPerVertex.tryToAccess(sigPointKind, semanticKind,
  1915. semanticToUse->index, invocationId, value,
  1916. noWriteBack, /*vecComponent=*/nullptr, loc))
  1917. return true;
  1918. switch (semanticKind) {
  1919. case hlsl::Semantic::Kind::DomainLocation:
  1920. evalType = astContext.getExtVectorType(astContext.FloatTy, 3);
  1921. break;
  1922. case hlsl::Semantic::Kind::TessFactor:
  1923. evalType = astContext.getConstantArrayType(
  1924. astContext.FloatTy, llvm::APInt(32, 4), clang::ArrayType::Normal, 0);
  1925. break;
  1926. case hlsl::Semantic::Kind::InsideTessFactor:
  1927. evalType = astContext.getConstantArrayType(
  1928. astContext.FloatTy, llvm::APInt(32, 2), clang::ArrayType::Normal, 0);
  1929. break;
  1930. case hlsl::Semantic::Kind::Coverage:
  1931. evalType = astContext.getConstantArrayType(astContext.UnsignedIntTy,
  1932. llvm::APInt(32, 1),
  1933. clang::ArrayType::Normal, 0);
  1934. break;
  1935. case hlsl::Semantic::Kind::InnerCoverage:
  1936. if (!type->isSpecificBuiltinType(BuiltinType::UInt)) {
  1937. emitError("SV_InnerCoverage must be of uint type.", loc);
  1938. return false;
  1939. }
  1940. evalType = astContext.BoolTy;
  1941. break;
  1942. case hlsl::Semantic::Kind::Barycentrics:
  1943. evalType = astContext.getExtVectorType(astContext.FloatTy, 2);
  1944. break;
  1945. case hlsl::Semantic::Kind::DispatchThreadID:
  1946. case hlsl::Semantic::Kind::GroupThreadID:
  1947. case hlsl::Semantic::Kind::GroupID:
  1948. // Keep the original integer signedness
  1949. evalType = astContext.getExtVectorType(
  1950. hlsl::IsHLSLVecType(type) ? hlsl::GetHLSLVecElementType(type) : type,
  1951. 3);
  1952. break;
  1953. case hlsl::Semantic::Kind::ShadingRate:
  1954. evalType = astContext.getExtVectorType(astContext.IntTy, 2);
  1955. break;
  1956. default:
  1957. // Only the semantic kinds mentioned above are handled.
  1958. break;
  1959. }
  1960. // Boolean stage I/O variables must be represented as unsigned integers.
  1961. // Boolean built-in variables are represented as bool.
  1962. if (isBooleanStageIOVar(decl, type, semanticKind, sigPointKind)) {
  1963. evalType = getUintTypeWithSourceComponents(astContext, type);
  1964. }
  1965. // Handle the extra arrayness
  1966. if (arraySize != 0) {
  1967. evalType = astContext.getConstantArrayType(
  1968. evalType, llvm::APInt(32, arraySize), clang::ArrayType::Normal, 0);
  1969. }
  1970. StageVar stageVar(
  1971. sigPoint, *semanticToUse, builtinAttr, evalType,
  1972. // For HS/DS/GS, we have already stripped the outmost arrayness on type.
  1973. getLocationCount(astContext, type));
  1974. const auto name = namePrefix.str() + "." + stageVar.getSemanticStr();
  1975. SpirvVariable *varInstr =
  1976. createSpirvStageVar(&stageVar, decl, name, semanticToUse->loc);
  1977. if (!varInstr)
  1978. return false;
  1979. stageVar.setSpirvInstr(varInstr);
  1980. stageVar.setLocationAttr(decl->getAttr<VKLocationAttr>());
  1981. stageVar.setIndexAttr(decl->getAttr<VKIndexAttr>());
  1982. stageVars.push_back(stageVar);
  1983. // Emit OpDecorate* instructions to link this stage variable with the HLSL
  1984. // semantic it is created for
  1985. spvBuilder.decorateHlslSemantic(varInstr, stageVar.getSemanticStr());
  1986. // We have semantics attached to this decl, which means it must be a
  1987. // function/parameter/variable. All are DeclaratorDecls.
  1988. stageVarInstructions[cast<DeclaratorDecl>(decl)] = varInstr;
  1989. // Special case: The DX12 SV_InstanceID always counts from 0, even if the
  1990. // StartInstanceLocation parameter is non-zero. gl_InstanceIndex, however,
  1991. // starts from firstInstance. Thus it doesn't emulate actual DX12 shader
  1992. // behavior. To make it equivalent, SPIR-V codegen should emit:
  1993. // SV_InstanceID = gl_InstanceIndex - gl_BaseInstance
  1994. // Unfortunately, this means that there is no 1-to-1 mapping of the HLSL
  1995. // semantic to the SPIR-V builtin. As a result, we have to manually create
  1996. // a second stage variable for this specific case.
  1997. //
  1998. // According to the Vulkan spec on builtin variables:
  1999. // www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#interfaces-builtin-variables
  2000. //
  2001. // InstanceIndex:
  2002. // Decorating a variable in a vertex shader with the InstanceIndex
  2003. // built-in decoration will make that variable contain the index of the
  2004. // instance that is being processed by the current vertex shader
  2005. // invocation. InstanceIndex begins at the firstInstance.
  2006. // BaseInstance
  2007. // Decorating a variable with the BaseInstance built-in will make that
  2008. // variable contain the integer value corresponding to the first instance
  2009. // that was passed to the command that invoked the current vertex shader
  2010. // invocation. BaseInstance is the firstInstance parameter to a direct
  2011. // drawing command or the firstInstance member of a structure consumed by
  2012. // an indirect drawing command.
  2013. if (spirvOptions.supportNonzeroBaseInstance && asInput &&
  2014. semanticKind == hlsl::Semantic::Kind::InstanceID &&
  2015. sigPointKind == hlsl::SigPoint::Kind::VSIn) {
  2016. // The above call to createSpirvStageVar creates the gl_InstanceIndex.
  2017. // We should now manually create the gl_BaseInstance variable and do the
  2018. // subtraction.
  2019. auto *instanceIndexVar = varInstr;
  2020. auto *baseInstanceVar = spvBuilder.addStageBuiltinVar(
  2021. type, spv::StorageClass::Input, spv::BuiltIn::BaseInstance,
  2022. decl->hasAttr<HLSLPreciseAttr>(), semanticToUse->loc);
  2023. StageVar stageVar2(sigPoint, *semanticToUse, builtinAttr, evalType,
  2024. getLocationCount(astContext, type));
  2025. stageVar2.setSpirvInstr(baseInstanceVar);
  2026. stageVar2.setLocationAttr(decl->getAttr<VKLocationAttr>());
  2027. stageVar2.setIndexAttr(decl->getAttr<VKIndexAttr>());
  2028. stageVar2.setIsSpirvBuiltin();
  2029. stageVars.push_back(stageVar2);
  2030. // SPIR-V code fore 'SV_InstanceID = gl_InstanceIndex - gl_BaseInstance'
  2031. auto *instanceIdVar =
  2032. spvBuilder.addFnVar(type, semanticToUse->loc, "SV_InstanceID");
  2033. auto *instanceIndexValue =
  2034. spvBuilder.createLoad(type, instanceIndexVar, semanticToUse->loc);
  2035. auto *baseInstanceValue =
  2036. spvBuilder.createLoad(type, baseInstanceVar, semanticToUse->loc);
  2037. auto *instanceIdValue =
  2038. spvBuilder.createBinaryOp(spv::Op::OpISub, type, instanceIndexValue,
  2039. baseInstanceValue, semanticToUse->loc);
  2040. spvBuilder.createStore(instanceIdVar, instanceIdValue,
  2041. semanticToUse->loc);
  2042. stageVarInstructions[cast<DeclaratorDecl>(decl)] = instanceIdVar;
  2043. varInstr = instanceIdVar;
  2044. }
  2045. // Mark that we have used one index for this semantic
  2046. ++semanticToUse->index;
  2047. // TODO: the following may not be correct?
  2048. if (sigPoint->GetSignatureKind() ==
  2049. hlsl::DXIL::SignatureKind::PatchConstOrPrim) {
  2050. if (sigPointKind == hlsl::SigPoint::Kind::MSPOut) {
  2051. // Decorate with PerPrimitiveNV for per-primitive out variables.
  2052. spvBuilder.decoratePerPrimitiveNV(varInstr,
  2053. varInstr->getSourceLocation());
  2054. } else {
  2055. spvBuilder.decoratePatch(varInstr, varInstr->getSourceLocation());
  2056. }
  2057. }
  2058. // Decorate with interpolation modes for pixel shader input variables
  2059. // or vertex shader output variables.
  2060. if (((spvContext.isPS() && sigPoint->IsInput()) ||
  2061. (spvContext.isVS() && sigPoint->IsOutput())) &&
  2062. // BaryCoord*AMD buitins already encode the interpolation mode.
  2063. semanticKind != hlsl::Semantic::Kind::Barycentrics)
  2064. decorateInterpolationMode(decl, type, varInstr);
  2065. if (asInput) {
  2066. *value = spvBuilder.createLoad(evalType, varInstr, loc);
  2067. // Fix ups for corner cases
  2068. // Special handling of SV_TessFactor DS patch constant input.
  2069. // TessLevelOuter is always an array of size 4 in SPIR-V, but
  2070. // SV_TessFactor could be an array of size 2, 3, or 4 in HLSL. Only the
  2071. // relevant indexes must be loaded.
  2072. if (semanticKind == hlsl::Semantic::Kind::TessFactor &&
  2073. hlsl::GetArraySize(type) != 4) {
  2074. llvm::SmallVector<SpirvInstruction *, 4> components;
  2075. const auto tessFactorSize = hlsl::GetArraySize(type);
  2076. const auto arrType = astContext.getConstantArrayType(
  2077. astContext.FloatTy, llvm::APInt(32, tessFactorSize),
  2078. clang::ArrayType::Normal, 0);
  2079. for (uint32_t i = 0; i < tessFactorSize; ++i)
  2080. components.push_back(spvBuilder.createCompositeExtract(
  2081. astContext.FloatTy, *value, {i}, thisSemantic.loc));
  2082. *value = spvBuilder.createCompositeConstruct(arrType, components,
  2083. thisSemantic.loc);
  2084. }
  2085. // Special handling of SV_InsideTessFactor DS patch constant input.
  2086. // TessLevelInner is always an array of size 2 in SPIR-V, but
  2087. // SV_InsideTessFactor could be an array of size 1 (scalar) or size 2 in
  2088. // HLSL. If SV_InsideTessFactor is a scalar, only extract index 0 of
  2089. // TessLevelInner.
  2090. else if (semanticKind == hlsl::Semantic::Kind::InsideTessFactor &&
  2091. // Some developers use float[1] instead of a scalar float.
  2092. (!type->isArrayType() || hlsl::GetArraySize(type) == 1)) {
  2093. *value = spvBuilder.createCompositeExtract(astContext.FloatTy, *value,
  2094. {0}, thisSemantic.loc);
  2095. if (type->isArrayType()) { // float[1]
  2096. const auto arrType = astContext.getConstantArrayType(
  2097. astContext.FloatTy, llvm::APInt(32, 1), clang::ArrayType::Normal,
  2098. 0);
  2099. *value = spvBuilder.createCompositeConstruct(arrType, {*value},
  2100. thisSemantic.loc);
  2101. }
  2102. }
  2103. // SV_DomainLocation can refer to a float2 or a float3, whereas TessCoord
  2104. // is always a float3. To ensure SPIR-V validity, a float3 stage variable
  2105. // is created, and we must extract a float2 from it before passing it to
  2106. // the main function.
  2107. else if (semanticKind == hlsl::Semantic::Kind::DomainLocation &&
  2108. hlsl::GetHLSLVecSize(type) != 3) {
  2109. const auto domainLocSize = hlsl::GetHLSLVecSize(type);
  2110. *value = spvBuilder.createVectorShuffle(
  2111. astContext.getExtVectorType(astContext.FloatTy, domainLocSize),
  2112. *value, *value, {0, 1}, thisSemantic.loc);
  2113. }
  2114. // Special handling of SV_Coverage, which is an uint value. We need to
  2115. // read SampleMask and extract its first element.
  2116. else if (semanticKind == hlsl::Semantic::Kind::Coverage) {
  2117. *value = spvBuilder.createCompositeExtract(type, *value, {0},
  2118. thisSemantic.loc);
  2119. }
  2120. // Special handling of SV_InnerCoverage, which is an uint value. We need
  2121. // to read FullyCoveredEXT, which is a boolean value, and convert it to an
  2122. // uint value. According to D3D12 "Conservative Rasterization" doc: "The
  2123. // Pixel Shader has a 32-bit scalar integer System Generate Value
  2124. // available: InnerCoverage. This is a bit-field that has bit 0 from the
  2125. // LSB set to 1 for a given conservatively rasterized pixel, only when
  2126. // that pixel is guaranteed to be entirely inside the current primitive.
  2127. // All other input register bits must be set to 0 when bit 0 is not set,
  2128. // but are undefined when bit 0 is set to 1 (essentially, this bit-field
  2129. // represents a Boolean value where false must be exactly 0, but true can
  2130. // be any odd (i.e. bit 0 set) non-zero value)."
  2131. else if (semanticKind == hlsl::Semantic::Kind::InnerCoverage) {
  2132. const auto constOne = spvBuilder.getConstantInt(
  2133. astContext.UnsignedIntTy, llvm::APInt(32, 1));
  2134. const auto constZero = spvBuilder.getConstantInt(
  2135. astContext.UnsignedIntTy, llvm::APInt(32, 0));
  2136. *value = spvBuilder.createSelect(astContext.UnsignedIntTy, *value,
  2137. constOne, constZero, thisSemantic.loc);
  2138. }
  2139. // Special handling of SV_Barycentrics, which is a float3, but the
  2140. // underlying stage input variable is a float2 (only provides the first
  2141. // two components). Calculate the third element.
  2142. else if (semanticKind == hlsl::Semantic::Kind::Barycentrics) {
  2143. const auto x = spvBuilder.createCompositeExtract(
  2144. astContext.FloatTy, *value, {0}, thisSemantic.loc);
  2145. const auto y = spvBuilder.createCompositeExtract(
  2146. astContext.FloatTy, *value, {1}, thisSemantic.loc);
  2147. const auto xy = spvBuilder.createBinaryOp(
  2148. spv::Op::OpFAdd, astContext.FloatTy, x, y, thisSemantic.loc);
  2149. const auto z = spvBuilder.createBinaryOp(
  2150. spv::Op::OpFSub, astContext.FloatTy,
  2151. spvBuilder.getConstantFloat(astContext.FloatTy,
  2152. llvm::APFloat(1.0f)),
  2153. xy, thisSemantic.loc);
  2154. *value = spvBuilder.createCompositeConstruct(
  2155. astContext.getExtVectorType(astContext.FloatTy, 3), {x, y, z},
  2156. thisSemantic.loc);
  2157. }
  2158. // Special handling of SV_DispatchThreadID and SV_GroupThreadID, which may
  2159. // be a uint or uint2, but the underlying stage input variable is a uint3.
  2160. // The last component(s) should be discarded in needed.
  2161. else if ((semanticKind == hlsl::Semantic::Kind::DispatchThreadID ||
  2162. semanticKind == hlsl::Semantic::Kind::GroupThreadID ||
  2163. semanticKind == hlsl::Semantic::Kind::GroupID) &&
  2164. (!hlsl::IsHLSLVecType(type) ||
  2165. hlsl::GetHLSLVecSize(type) != 3)) {
  2166. const auto srcVecElemType = hlsl::IsHLSLVecType(type)
  2167. ? hlsl::GetHLSLVecElementType(type)
  2168. : type;
  2169. const auto vecSize =
  2170. hlsl::IsHLSLVecType(type) ? hlsl::GetHLSLVecSize(type) : 1;
  2171. if (vecSize == 1)
  2172. *value = spvBuilder.createCompositeExtract(srcVecElemType, *value,
  2173. {0}, thisSemantic.loc);
  2174. else if (vecSize == 2)
  2175. *value = spvBuilder.createVectorShuffle(
  2176. astContext.getExtVectorType(srcVecElemType, 2), *value, *value,
  2177. {0, 1}, thisSemantic.loc);
  2178. }
  2179. // Special handling of SV_ShadingRate, which is a bitpacked enum value,
  2180. // but SPIR-V's FragSizeEXT uses an int2. We build the enum value from
  2181. // the separate axis values.
  2182. else if (semanticKind == hlsl::Semantic::Kind::ShadingRate) {
  2183. // From the D3D12 functional spec for Variable-Rate Shading.
  2184. // #define D3D12_MAKE_COARSE_SHADING_RATE(x,y) ((x) << 2 | (y))
  2185. const auto x = spvBuilder.createCompositeExtract(
  2186. astContext.IntTy, *value, {0}, thisSemantic.loc);
  2187. const auto y = spvBuilder.createCompositeExtract(
  2188. astContext.IntTy, *value, {1}, thisSemantic.loc);
  2189. const auto constTwo =
  2190. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 2));
  2191. *value = spvBuilder.createBinaryOp(
  2192. spv::Op::OpBitwiseOr, astContext.UnsignedIntTy,
  2193. spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  2194. astContext.IntTy, x, constTwo,
  2195. thisSemantic.loc),
  2196. y, thisSemantic.loc);
  2197. }
  2198. // Reciprocate SV_Position.w if requested
  2199. if (semanticKind == hlsl::Semantic::Kind::Position)
  2200. *value = invertWIfRequested(*value, thisSemantic.loc);
  2201. // Since boolean stage input variables are represented as unsigned
  2202. // integers, after loading them, we should cast them to boolean.
  2203. if (isBooleanStageIOVar(decl, type, semanticKind, sigPointKind)) {
  2204. *value =
  2205. theEmitter.castToType(*value, evalType, type, thisSemantic.loc);
  2206. }
  2207. } else {
  2208. if (noWriteBack)
  2209. return true;
  2210. // Negate SV_Position.y if requested
  2211. if (semanticKind == hlsl::Semantic::Kind::Position)
  2212. *value = invertYIfRequested(*value, thisSemantic.loc);
  2213. SpirvInstruction *ptr = varInstr;
  2214. // Special handling of SV_TessFactor HS patch constant output.
  2215. // TessLevelOuter is always an array of size 4 in SPIR-V, but
  2216. // SV_TessFactor could be an array of size 2, 3, or 4 in HLSL. Only the
  2217. // relevant indexes must be written to.
  2218. if (semanticKind == hlsl::Semantic::Kind::TessFactor &&
  2219. hlsl::GetArraySize(type) != 4) {
  2220. const auto tessFactorSize = hlsl::GetArraySize(type);
  2221. for (uint32_t i = 0; i < tessFactorSize; ++i) {
  2222. ptr = spvBuilder.createAccessChain(
  2223. astContext.FloatTy, varInstr,
  2224. {spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2225. llvm::APInt(32, i))},
  2226. thisSemantic.loc);
  2227. spvBuilder.createStore(
  2228. ptr,
  2229. spvBuilder.createCompositeExtract(astContext.FloatTy, *value, {i},
  2230. thisSemantic.loc),
  2231. thisSemantic.loc);
  2232. }
  2233. }
  2234. // Special handling of SV_InsideTessFactor HS patch constant output.
  2235. // TessLevelInner is always an array of size 2 in SPIR-V, but
  2236. // SV_InsideTessFactor could be an array of size 1 (scalar) or size 2 in
  2237. // HLSL. If SV_InsideTessFactor is a scalar, only write to index 0 of
  2238. // TessLevelInner.
  2239. else if (semanticKind == hlsl::Semantic::Kind::InsideTessFactor &&
  2240. // Some developers use float[1] instead of a scalar float.
  2241. (!type->isArrayType() || hlsl::GetArraySize(type) == 1)) {
  2242. ptr = spvBuilder.createAccessChain(
  2243. astContext.FloatTy, varInstr,
  2244. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2245. llvm::APInt(32, 0)),
  2246. thisSemantic.loc);
  2247. if (type->isArrayType()) // float[1]
  2248. *value = spvBuilder.createCompositeExtract(astContext.FloatTy, *value,
  2249. {0}, thisSemantic.loc);
  2250. spvBuilder.createStore(ptr, *value, thisSemantic.loc);
  2251. }
  2252. // Special handling of SV_Coverage, which is an unit value. We need to
  2253. // write it to the first element in the SampleMask builtin.
  2254. else if (semanticKind == hlsl::Semantic::Kind::Coverage) {
  2255. ptr = spvBuilder.createAccessChain(
  2256. type, varInstr,
  2257. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2258. llvm::APInt(32, 0)),
  2259. thisSemantic.loc);
  2260. ptr->setStorageClass(spv::StorageClass::Output);
  2261. spvBuilder.createStore(ptr, *value, thisSemantic.loc);
  2262. }
  2263. // Special handling of HS ouput, for which we write to only one
  2264. // element in the per-vertex data array: the one indexed by
  2265. // SV_ControlPointID.
  2266. else if (invocationId.hasValue() && invocationId.getValue() != nullptr) {
  2267. // Remove the arrayness to get the element type.
  2268. assert(isa<ConstantArrayType>(evalType));
  2269. const auto elementType =
  2270. astContext.getAsArrayType(evalType)->getElementType();
  2271. auto index = invocationId.getValue();
  2272. ptr = spvBuilder.createAccessChain(elementType, varInstr, index,
  2273. thisSemantic.loc);
  2274. ptr->setStorageClass(spv::StorageClass::Output);
  2275. spvBuilder.createStore(ptr, *value, thisSemantic.loc);
  2276. }
  2277. // Since boolean output stage variables are represented as unsigned
  2278. // integers, we must cast the value to uint before storing.
  2279. else if (isBooleanStageIOVar(decl, type, semanticKind, sigPointKind)) {
  2280. *value =
  2281. theEmitter.castToType(*value, type, evalType, thisSemantic.loc);
  2282. spvBuilder.createStore(ptr, *value, thisSemantic.loc);
  2283. }
  2284. // For all normal cases
  2285. else {
  2286. spvBuilder.createStore(ptr, *value, thisSemantic.loc);
  2287. }
  2288. }
  2289. return true;
  2290. }
  2291. // If the decl itself doesn't have semantic string attached and there is no
  2292. // one to inherit, it should be a struct having all its fields with semantic
  2293. // strings.
  2294. if (!semanticToUse->isValid() && !type->isStructureType()) {
  2295. emitError("semantic string missing for shader %select{output|input}0 "
  2296. "variable '%1'",
  2297. loc)
  2298. << asInput << decl->getName();
  2299. return false;
  2300. }
  2301. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  2302. if (asInput) {
  2303. // If this decl translates into multiple stage input variables, we need to
  2304. // load their values into a composite.
  2305. llvm::SmallVector<SpirvInstruction *, 4> subValues;
  2306. // If we have base classes, we need to handle them first.
  2307. if (const auto *cxxDecl = type->getAsCXXRecordDecl()) {
  2308. for (auto base : cxxDecl->bases()) {
  2309. SpirvInstruction *subValue = nullptr;
  2310. if (!createStageVars(sigPoint, base.getType()->getAsCXXRecordDecl(),
  2311. asInput, base.getType(), arraySize, namePrefix,
  2312. invocationId, &subValue, noWriteBack,
  2313. semanticToUse))
  2314. return false;
  2315. subValues.push_back(subValue);
  2316. }
  2317. }
  2318. for (const auto *field : structDecl->fields()) {
  2319. SpirvInstruction *subValue = nullptr;
  2320. if (!createStageVars(sigPoint, field, asInput, field->getType(),
  2321. arraySize, namePrefix, invocationId, &subValue,
  2322. noWriteBack, semanticToUse))
  2323. return false;
  2324. subValues.push_back(subValue);
  2325. }
  2326. if (arraySize == 0) {
  2327. *value = spvBuilder.createCompositeConstruct(evalType, subValues, loc);
  2328. return true;
  2329. }
  2330. // Handle the extra level of arrayness.
  2331. // We need to return an array of structs. But we get arrays of fields
  2332. // from visiting all fields. So now we need to extract all the elements
  2333. // at the same index of each field arrays and compose a new struct out
  2334. // of them.
  2335. const auto structType = type;
  2336. const auto arrayType = astContext.getConstantArrayType(
  2337. structType, llvm::APInt(32, arraySize), clang::ArrayType::Normal, 0);
  2338. llvm::SmallVector<SpirvInstruction *, 16> arrayElements;
  2339. for (uint32_t arrayIndex = 0; arrayIndex < arraySize; ++arrayIndex) {
  2340. llvm::SmallVector<SpirvInstruction *, 8> fields;
  2341. // If we have base classes, we need to handle them first.
  2342. if (const auto *cxxDecl = type->getAsCXXRecordDecl()) {
  2343. uint32_t baseIndex = 0;
  2344. for (auto base : cxxDecl->bases()) {
  2345. const auto baseType = base.getType();
  2346. fields.push_back(spvBuilder.createCompositeExtract(
  2347. baseType, subValues[baseIndex++], {arrayIndex}, loc));
  2348. }
  2349. }
  2350. // Extract the element at index arrayIndex from each field
  2351. for (const auto *field : structDecl->fields()) {
  2352. const auto fieldType = field->getType();
  2353. fields.push_back(spvBuilder.createCompositeExtract(
  2354. fieldType,
  2355. subValues[getNumBaseClasses(type) + field->getFieldIndex()],
  2356. {arrayIndex}, loc));
  2357. }
  2358. // Compose a new struct out of them
  2359. arrayElements.push_back(
  2360. spvBuilder.createCompositeConstruct(structType, fields, loc));
  2361. }
  2362. *value = spvBuilder.createCompositeConstruct(arrayType, arrayElements, loc);
  2363. } else {
  2364. // If we have base classes, we need to handle them first.
  2365. if (const auto *cxxDecl = type->getAsCXXRecordDecl()) {
  2366. uint32_t baseIndex = 0;
  2367. for (auto base : cxxDecl->bases()) {
  2368. SpirvInstruction *subValue = nullptr;
  2369. if (!noWriteBack)
  2370. subValue = spvBuilder.createCompositeExtract(base.getType(), *value,
  2371. {baseIndex++}, loc);
  2372. if (!createStageVars(sigPoint, base.getType()->getAsCXXRecordDecl(),
  2373. asInput, base.getType(), arraySize, namePrefix,
  2374. invocationId, &subValue, noWriteBack,
  2375. semanticToUse))
  2376. return false;
  2377. }
  2378. }
  2379. // Unlike reading, which may require us to read stand-alone builtins and
  2380. // stage input variables and compose an array of structs out of them,
  2381. // it happens that we don't need to write an array of structs in a bunch
  2382. // for all shader stages:
  2383. //
  2384. // * VS: output is a single struct, without extra arrayness
  2385. // * HS: output is an array of structs, with extra arrayness,
  2386. // but we only write to the struct at the InvocationID index
  2387. // * DS: output is a single struct, without extra arrayness
  2388. // * GS: output is controlled by OpEmitVertex, one vertex per time
  2389. // * MS: output is an array of structs, with extra arrayness
  2390. //
  2391. // The interesting shader stage is HS. We need the InvocationID to write
  2392. // out the value to the correct array element.
  2393. for (const auto *field : structDecl->fields()) {
  2394. const auto fieldType = field->getType();
  2395. SpirvInstruction *subValue = nullptr;
  2396. if (!noWriteBack)
  2397. subValue = spvBuilder.createCompositeExtract(
  2398. fieldType, *value,
  2399. {getNumBaseClasses(type) + field->getFieldIndex()}, loc);
  2400. if (!createStageVars(sigPoint, field, asInput, field->getType(),
  2401. arraySize, namePrefix, invocationId, &subValue,
  2402. noWriteBack, semanticToUse))
  2403. return false;
  2404. }
  2405. }
  2406. return true;
  2407. }
  2408. bool DeclResultIdMapper::createPayloadStageVars(
  2409. const hlsl::SigPoint *sigPoint, spv::StorageClass sc, const NamedDecl *decl,
  2410. bool asInput, QualType type, const llvm::StringRef namePrefix,
  2411. SpirvInstruction **value, uint32_t payloadMemOffset) {
  2412. assert(spvContext.isMS() || spvContext.isAS());
  2413. assert(value);
  2414. if (type->isVoidType()) {
  2415. // No stage variables will be created for void type.
  2416. return true;
  2417. }
  2418. const auto loc = decl->getLocation();
  2419. if (!type->isStructureType()) {
  2420. StageVar stageVar(sigPoint, /*semaInfo=*/{}, /*builtinAttr=*/nullptr, type,
  2421. getLocationCount(astContext, type));
  2422. const auto name = namePrefix.str() + "." + decl->getNameAsString();
  2423. SpirvVariable *varInstr =
  2424. spvBuilder.addStageIOVar(type, sc, name, /*isPrecise=*/false, loc);
  2425. if (!varInstr)
  2426. return false;
  2427. // Even though these as user defined IO stage variables, set them as SPIR-V
  2428. // builtins in order to bypass any semantic string checks and location
  2429. // assignment.
  2430. stageVar.setIsSpirvBuiltin();
  2431. stageVar.setSpirvInstr(varInstr);
  2432. stageVars.push_back(stageVar);
  2433. // Decorate with PerTaskNV for mesh/amplification shader payload variables.
  2434. spvBuilder.decoratePerTaskNV(varInstr, payloadMemOffset,
  2435. varInstr->getSourceLocation());
  2436. if (asInput) {
  2437. *value = spvBuilder.createLoad(type, varInstr, loc);
  2438. } else {
  2439. spvBuilder.createStore(varInstr, *value, loc);
  2440. }
  2441. return true;
  2442. }
  2443. // This decl translates into multiple stage input/output payload variables
  2444. // and we need to load/store these individual member variables.
  2445. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  2446. llvm::SmallVector<SpirvInstruction *, 4> subValues;
  2447. AlignmentSizeCalculator alignmentCalc(astContext, spirvOptions);
  2448. uint32_t nextMemberOffset = 0;
  2449. for (const auto *field : structDecl->fields()) {
  2450. const auto fieldType = field->getType();
  2451. SpirvInstruction *subValue = nullptr;
  2452. uint32_t memberAlignment = 0, memberSize = 0, stride = 0;
  2453. // The next avaiable offset after laying out the previous members.
  2454. std::tie(memberAlignment, memberSize) = alignmentCalc.getAlignmentAndSize(
  2455. field->getType(), spirvOptions.ampPayloadLayoutRule,
  2456. /*isRowMajor*/ llvm::None, &stride);
  2457. alignmentCalc.alignUsingHLSLRelaxedLayout(
  2458. field->getType(), memberSize, memberAlignment, &nextMemberOffset);
  2459. // The vk::offset attribute takes precedence over all.
  2460. if (field->getAttr<VKOffsetAttr>()) {
  2461. nextMemberOffset = field->getAttr<VKOffsetAttr>()->getOffset();
  2462. }
  2463. // Each payload member must have an Offset Decoration.
  2464. payloadMemOffset = nextMemberOffset;
  2465. nextMemberOffset += memberSize;
  2466. if (!asInput) {
  2467. subValue = spvBuilder.createCompositeExtract(
  2468. fieldType, *value, {getNumBaseClasses(type) + field->getFieldIndex()},
  2469. loc);
  2470. }
  2471. if (!createPayloadStageVars(sigPoint, sc, field, asInput, field->getType(),
  2472. namePrefix, &subValue, payloadMemOffset))
  2473. return false;
  2474. if (asInput) {
  2475. subValues.push_back(subValue);
  2476. }
  2477. }
  2478. if (asInput) {
  2479. *value = spvBuilder.createCompositeConstruct(type, subValues, loc);
  2480. }
  2481. return true;
  2482. }
  2483. bool DeclResultIdMapper::writeBackOutputStream(const NamedDecl *decl,
  2484. QualType type,
  2485. SpirvInstruction *value) {
  2486. assert(spvContext.isGS()); // Only for GS use
  2487. if (hlsl::IsHLSLStreamOutputType(type))
  2488. type = hlsl::GetHLSLResourceResultType(type);
  2489. if (hasGSPrimitiveTypeQualifier(decl))
  2490. type = astContext.getAsConstantArrayType(type)->getElementType();
  2491. auto semanticInfo = getStageVarSemantic(decl);
  2492. const auto loc = decl->getLocation();
  2493. if (semanticInfo.isValid()) {
  2494. // Found semantic attached directly to this Decl. Write the value for this
  2495. // Decl to the corresponding stage output variable.
  2496. // Handle SV_ClipDistance, and SV_CullDistance
  2497. if (glPerVertex.tryToAccess(
  2498. hlsl::DXIL::SigPointKind::GSOut, semanticInfo.semantic->GetKind(),
  2499. semanticInfo.index, llvm::None, &value,
  2500. /*noWriteBack=*/false, /*vecComponent=*/nullptr, loc))
  2501. return true;
  2502. // Query the <result-id> for the stage output variable generated out
  2503. // of this decl.
  2504. // We have semantic string attached to this decl; therefore, it must be a
  2505. // DeclaratorDecl.
  2506. const auto found = stageVarInstructions.find(cast<DeclaratorDecl>(decl));
  2507. // We should have recorded its stage output variable previously.
  2508. assert(found != stageVarInstructions.end());
  2509. // Negate SV_Position.y if requested
  2510. if (semanticInfo.semantic->GetKind() == hlsl::Semantic::Kind::Position)
  2511. value = invertYIfRequested(value, loc);
  2512. // Boolean stage output variables are represented as unsigned integers.
  2513. if (isBooleanStageIOVar(decl, type, semanticInfo.semantic->GetKind(),
  2514. hlsl::SigPoint::Kind::GSOut)) {
  2515. QualType uintType = getUintTypeWithSourceComponents(astContext, type);
  2516. value = theEmitter.castToType(value, type, uintType, loc);
  2517. }
  2518. spvBuilder.createStore(found->second, value, loc);
  2519. return true;
  2520. }
  2521. // If the decl itself doesn't have semantic string attached, it should be
  2522. // a struct having all its fields with semantic strings.
  2523. if (!type->isStructureType()) {
  2524. emitError("semantic string missing for shader output variable '%0'", loc)
  2525. << decl->getName();
  2526. return false;
  2527. }
  2528. // If we have base classes, we need to handle them first.
  2529. if (const auto *cxxDecl = type->getAsCXXRecordDecl()) {
  2530. uint32_t baseIndex = 0;
  2531. for (auto base : cxxDecl->bases()) {
  2532. auto *subValue = spvBuilder.createCompositeExtract(base.getType(), value,
  2533. {baseIndex++}, loc);
  2534. if (!writeBackOutputStream(base.getType()->getAsCXXRecordDecl(),
  2535. base.getType(), subValue))
  2536. return false;
  2537. }
  2538. }
  2539. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  2540. // Write out each field
  2541. for (const auto *field : structDecl->fields()) {
  2542. const auto fieldType = field->getType();
  2543. auto *subValue = spvBuilder.createCompositeExtract(
  2544. fieldType, value, {getNumBaseClasses(type) + field->getFieldIndex()},
  2545. loc);
  2546. if (!writeBackOutputStream(field, field->getType(), subValue))
  2547. return false;
  2548. }
  2549. return true;
  2550. }
  2551. SpirvInstruction *
  2552. DeclResultIdMapper::invertYIfRequested(SpirvInstruction *position,
  2553. SourceLocation loc) {
  2554. // Negate SV_Position.y if requested
  2555. if (spirvOptions.invertY) {
  2556. const auto oldY = spvBuilder.createCompositeExtract(astContext.FloatTy,
  2557. position, {1}, loc);
  2558. const auto newY = spvBuilder.createUnaryOp(spv::Op::OpFNegate,
  2559. astContext.FloatTy, oldY, loc);
  2560. position = spvBuilder.createCompositeInsert(
  2561. astContext.getExtVectorType(astContext.FloatTy, 4), position, {1}, newY,
  2562. loc);
  2563. }
  2564. return position;
  2565. }
  2566. SpirvInstruction *
  2567. DeclResultIdMapper::invertWIfRequested(SpirvInstruction *position,
  2568. SourceLocation loc) {
  2569. // Reciprocate SV_Position.w if requested
  2570. if (spirvOptions.invertW && spvContext.isPS()) {
  2571. const auto oldW = spvBuilder.createCompositeExtract(astContext.FloatTy,
  2572. position, {3}, loc);
  2573. const auto newW = spvBuilder.createBinaryOp(
  2574. spv::Op::OpFDiv, astContext.FloatTy,
  2575. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(1.0f)),
  2576. oldW, loc);
  2577. position = spvBuilder.createCompositeInsert(
  2578. astContext.getExtVectorType(astContext.FloatTy, 4), position, {3}, newW,
  2579. loc);
  2580. }
  2581. return position;
  2582. }
  2583. void DeclResultIdMapper::decorateInterpolationMode(const NamedDecl *decl,
  2584. QualType type,
  2585. SpirvVariable *varInstr) {
  2586. const auto loc = decl->getLocation();
  2587. if (isUintOrVecMatOfUintType(type) || isSintOrVecMatOfSintType(type) ||
  2588. isBoolOrVecMatOfBoolType(type)) {
  2589. // TODO: Probably we can call hlsl::ValidateSignatureElement() for the
  2590. // following check.
  2591. if (decl->getAttr<HLSLLinearAttr>() || decl->getAttr<HLSLCentroidAttr>() ||
  2592. decl->getAttr<HLSLNoPerspectiveAttr>() ||
  2593. decl->getAttr<HLSLSampleAttr>()) {
  2594. emitError("only nointerpolation mode allowed for integer input "
  2595. "parameters in pixel shader or integer output in vertex shader",
  2596. decl->getLocation());
  2597. } else {
  2598. spvBuilder.decorateFlat(varInstr, loc);
  2599. }
  2600. } else {
  2601. // Do nothing for HLSLLinearAttr since its the default
  2602. // Attributes can be used together. So cannot use else if.
  2603. if (decl->getAttr<HLSLCentroidAttr>())
  2604. spvBuilder.decorateCentroid(varInstr, loc);
  2605. if (decl->getAttr<HLSLNoInterpolationAttr>())
  2606. spvBuilder.decorateFlat(varInstr, loc);
  2607. if (decl->getAttr<HLSLNoPerspectiveAttr>())
  2608. spvBuilder.decorateNoPerspective(varInstr, loc);
  2609. if (decl->getAttr<HLSLSampleAttr>()) {
  2610. spvBuilder.decorateSample(varInstr, loc);
  2611. }
  2612. }
  2613. }
  2614. SpirvVariable *DeclResultIdMapper::getBuiltinVar(spv::BuiltIn builtIn,
  2615. QualType type,
  2616. SourceLocation loc) {
  2617. // Guarantee uniqueness
  2618. uint32_t spvBuiltinId = static_cast<uint32_t>(builtIn);
  2619. const auto builtInVar = builtinToVarMap.find(spvBuiltinId);
  2620. if (builtInVar != builtinToVarMap.end()) {
  2621. return builtInVar->second;
  2622. }
  2623. spv::StorageClass sc = spv::StorageClass::Max;
  2624. // Valid builtins supported
  2625. switch (builtIn) {
  2626. case spv::BuiltIn::SubgroupSize:
  2627. case spv::BuiltIn::SubgroupLocalInvocationId:
  2628. case spv::BuiltIn::HitTNV:
  2629. case spv::BuiltIn::RayTmaxNV:
  2630. case spv::BuiltIn::RayTminNV:
  2631. case spv::BuiltIn::HitKindNV:
  2632. case spv::BuiltIn::IncomingRayFlagsNV:
  2633. case spv::BuiltIn::InstanceCustomIndexNV:
  2634. case spv::BuiltIn::RayGeometryIndexKHR:
  2635. case spv::BuiltIn::PrimitiveId:
  2636. case spv::BuiltIn::InstanceId:
  2637. case spv::BuiltIn::WorldRayDirectionNV:
  2638. case spv::BuiltIn::WorldRayOriginNV:
  2639. case spv::BuiltIn::ObjectRayDirectionNV:
  2640. case spv::BuiltIn::ObjectRayOriginNV:
  2641. case spv::BuiltIn::ObjectToWorldNV:
  2642. case spv::BuiltIn::WorldToObjectNV:
  2643. case spv::BuiltIn::LaunchIdNV:
  2644. case spv::BuiltIn::LaunchSizeNV:
  2645. case spv::BuiltIn::GlobalInvocationId:
  2646. case spv::BuiltIn::WorkgroupId:
  2647. case spv::BuiltIn::LocalInvocationIndex:
  2648. sc = spv::StorageClass::Input;
  2649. break;
  2650. case spv::BuiltIn::PrimitiveCountNV:
  2651. case spv::BuiltIn::PrimitiveIndicesNV:
  2652. case spv::BuiltIn::TaskCountNV:
  2653. sc = spv::StorageClass::Output;
  2654. break;
  2655. default:
  2656. assert(false && "unsupported SPIR-V builtin");
  2657. return nullptr;
  2658. }
  2659. // Create a dummy StageVar for this builtin variable
  2660. auto var = spvBuilder.addStageBuiltinVar(type, sc, builtIn,
  2661. /*isPrecise*/ false, loc);
  2662. const hlsl::SigPoint *sigPoint =
  2663. hlsl::SigPoint::GetSigPoint(hlsl::SigPointFromInputQual(
  2664. hlsl::DxilParamInputQual::In, spvContext.getCurrentShaderModelKind(),
  2665. /*isPatchConstant=*/false));
  2666. StageVar stageVar(sigPoint, /*semaInfo=*/{}, /*builtinAttr=*/nullptr, type,
  2667. /*locCount=*/0);
  2668. stageVar.setIsSpirvBuiltin();
  2669. stageVar.setSpirvInstr(var);
  2670. stageVars.push_back(stageVar);
  2671. // Store in map for re-use
  2672. builtinToVarMap[spvBuiltinId] = var;
  2673. return var;
  2674. }
  2675. SpirvVariable *DeclResultIdMapper::createSpirvIntermediateOutputStageVar(
  2676. const NamedDecl *decl, const llvm::StringRef name, QualType type) {
  2677. const auto *semantic = hlsl::Semantic::GetByName(name);
  2678. SemanticInfo thisSemantic{name, semantic, name, 0, decl->getLocation()};
  2679. const auto *sigPoint =
  2680. deduceSigPoint(cast<DeclaratorDecl>(decl), /*asInput=*/false,
  2681. spvContext.getCurrentShaderModelKind(), /*forPCF=*/false);
  2682. StageVar stageVar(sigPoint, thisSemantic, decl->getAttr<VKBuiltInAttr>(),
  2683. type, /*locCount=*/1);
  2684. SpirvVariable *varInstr =
  2685. createSpirvStageVar(&stageVar, decl, name, thisSemantic.loc);
  2686. if (!varInstr)
  2687. return nullptr;
  2688. stageVar.setSpirvInstr(varInstr);
  2689. stageVar.setLocationAttr(decl->getAttr<VKLocationAttr>());
  2690. stageVar.setIndexAttr(decl->getAttr<VKIndexAttr>());
  2691. stageVars.push_back(stageVar);
  2692. // Emit OpDecorate* instructions to link this stage variable with the HLSL
  2693. // semantic it is created for.
  2694. spvBuilder.decorateHlslSemantic(varInstr, stageVar.getSemanticStr());
  2695. // We have semantics attached to this decl, which means it must be a
  2696. // function/parameter/variable. All are DeclaratorDecls.
  2697. stageVarInstructions[cast<DeclaratorDecl>(decl)] = varInstr;
  2698. return varInstr;
  2699. }
  2700. SpirvVariable *DeclResultIdMapper::createSpirvStageVar(
  2701. StageVar *stageVar, const NamedDecl *decl, const llvm::StringRef name,
  2702. SourceLocation srcLoc) {
  2703. using spv::BuiltIn;
  2704. const auto sigPoint = stageVar->getSigPoint();
  2705. const auto semanticKind = stageVar->getSemanticInfo().getKind();
  2706. const auto sigPointKind = sigPoint->GetKind();
  2707. const auto type = stageVar->getAstType();
  2708. const auto isPrecise = decl->hasAttr<HLSLPreciseAttr>();
  2709. spv::StorageClass sc = getStorageClassForSigPoint(sigPoint);
  2710. if (sc == spv::StorageClass::Max)
  2711. return 0;
  2712. stageVar->setStorageClass(sc);
  2713. // [[vk::builtin(...)]] takes precedence.
  2714. if (const auto *builtinAttr = stageVar->getBuiltInAttr()) {
  2715. const auto spvBuiltIn =
  2716. llvm::StringSwitch<BuiltIn>(builtinAttr->getBuiltIn())
  2717. .Case("PointSize", BuiltIn::PointSize)
  2718. .Case("HelperInvocation", BuiltIn::HelperInvocation)
  2719. .Case("BaseVertex", BuiltIn::BaseVertex)
  2720. .Case("BaseInstance", BuiltIn::BaseInstance)
  2721. .Case("DrawIndex", BuiltIn::DrawIndex)
  2722. .Case("DeviceIndex", BuiltIn::DeviceIndex)
  2723. .Case("ViewportMaskNV", BuiltIn::ViewportMaskNV)
  2724. .Default(BuiltIn::Max);
  2725. assert(spvBuiltIn != BuiltIn::Max); // The frontend should guarantee this.
  2726. return spvBuilder.addStageBuiltinVar(type, sc, spvBuiltIn, isPrecise,
  2727. srcLoc);
  2728. }
  2729. // The following translation assumes that semantic validity in the current
  2730. // shader model is already checked, so it only covers valid SigPoints for
  2731. // each semantic.
  2732. switch (semanticKind) {
  2733. // According to DXIL spec, the Position SV can be used by all SigPoints
  2734. // other than PCIn, HSIn, GSIn, PSOut, CSIn, MSIn, MSPOut, ASIn.
  2735. // According to Vulkan spec, the Position BuiltIn can only be used
  2736. // by VSOut, HS/DS/GS In/Out, MSOut.
  2737. case hlsl::Semantic::Kind::Position: {
  2738. switch (sigPointKind) {
  2739. case hlsl::SigPoint::Kind::VSIn:
  2740. case hlsl::SigPoint::Kind::PCOut:
  2741. case hlsl::SigPoint::Kind::DSIn:
  2742. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2743. case hlsl::SigPoint::Kind::VSOut:
  2744. case hlsl::SigPoint::Kind::HSCPIn:
  2745. case hlsl::SigPoint::Kind::HSCPOut:
  2746. case hlsl::SigPoint::Kind::DSCPIn:
  2747. case hlsl::SigPoint::Kind::DSOut:
  2748. case hlsl::SigPoint::Kind::GSVIn:
  2749. case hlsl::SigPoint::Kind::GSOut:
  2750. case hlsl::SigPoint::Kind::MSOut:
  2751. stageVar->setIsSpirvBuiltin();
  2752. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::Position,
  2753. isPrecise, srcLoc);
  2754. case hlsl::SigPoint::Kind::PSIn:
  2755. stageVar->setIsSpirvBuiltin();
  2756. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::FragCoord,
  2757. isPrecise, srcLoc);
  2758. default:
  2759. llvm_unreachable("invalid usage of SV_Position sneaked in");
  2760. }
  2761. }
  2762. // According to DXIL spec, the VertexID SV can only be used by VSIn.
  2763. // According to Vulkan spec, the VertexIndex BuiltIn can only be used by
  2764. // VSIn.
  2765. case hlsl::Semantic::Kind::VertexID: {
  2766. stageVar->setIsSpirvBuiltin();
  2767. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::VertexIndex,
  2768. isPrecise, srcLoc);
  2769. }
  2770. // According to DXIL spec, the InstanceID SV can be used by VSIn, VSOut,
  2771. // HSCPIn, HSCPOut, DSCPIn, DSOut, GSVIn, GSOut, PSIn.
  2772. // According to Vulkan spec, the InstanceIndex BuitIn can only be used by
  2773. // VSIn.
  2774. case hlsl::Semantic::Kind::InstanceID: {
  2775. switch (sigPointKind) {
  2776. case hlsl::SigPoint::Kind::VSIn:
  2777. stageVar->setIsSpirvBuiltin();
  2778. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::InstanceIndex,
  2779. isPrecise, srcLoc);
  2780. case hlsl::SigPoint::Kind::VSOut:
  2781. case hlsl::SigPoint::Kind::HSCPIn:
  2782. case hlsl::SigPoint::Kind::HSCPOut:
  2783. case hlsl::SigPoint::Kind::DSCPIn:
  2784. case hlsl::SigPoint::Kind::DSOut:
  2785. case hlsl::SigPoint::Kind::GSVIn:
  2786. case hlsl::SigPoint::Kind::GSOut:
  2787. case hlsl::SigPoint::Kind::PSIn:
  2788. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2789. default:
  2790. llvm_unreachable("invalid usage of SV_InstanceID sneaked in");
  2791. }
  2792. }
  2793. // According to DXIL spec, the Depth{|GreaterEqual|LessEqual} SV can only be
  2794. // used by PSOut.
  2795. // According to Vulkan spec, the FragDepth BuiltIn can only be used by PSOut.
  2796. case hlsl::Semantic::Kind::Depth:
  2797. case hlsl::Semantic::Kind::DepthGreaterEqual:
  2798. case hlsl::Semantic::Kind::DepthLessEqual: {
  2799. stageVar->setIsSpirvBuiltin();
  2800. // Vulkan requires the DepthReplacing execution mode to write to FragDepth.
  2801. spvBuilder.addExecutionMode(entryFunction,
  2802. spv::ExecutionMode::DepthReplacing, {}, srcLoc);
  2803. if (semanticKind == hlsl::Semantic::Kind::DepthGreaterEqual)
  2804. spvBuilder.addExecutionMode(entryFunction,
  2805. spv::ExecutionMode::DepthGreater, {}, srcLoc);
  2806. else if (semanticKind == hlsl::Semantic::Kind::DepthLessEqual)
  2807. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::DepthLess,
  2808. {}, srcLoc);
  2809. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::FragDepth,
  2810. isPrecise, srcLoc);
  2811. }
  2812. // According to DXIL spec, the ClipDistance/CullDistance SV can be used by all
  2813. // SigPoints other than PCIn, HSIn, GSIn, PSOut, CSIn, MSIn, MSPOut, ASIn.
  2814. // According to Vulkan spec, the ClipDistance/CullDistance
  2815. // BuiltIn can only be used by VSOut, HS/DS/GS In/Out, MSOut.
  2816. case hlsl::Semantic::Kind::ClipDistance:
  2817. case hlsl::Semantic::Kind::CullDistance: {
  2818. switch (sigPointKind) {
  2819. case hlsl::SigPoint::Kind::VSIn:
  2820. case hlsl::SigPoint::Kind::PCOut:
  2821. case hlsl::SigPoint::Kind::DSIn:
  2822. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2823. case hlsl::SigPoint::Kind::VSOut:
  2824. case hlsl::SigPoint::Kind::HSCPIn:
  2825. case hlsl::SigPoint::Kind::HSCPOut:
  2826. case hlsl::SigPoint::Kind::DSCPIn:
  2827. case hlsl::SigPoint::Kind::DSOut:
  2828. case hlsl::SigPoint::Kind::GSVIn:
  2829. case hlsl::SigPoint::Kind::GSOut:
  2830. case hlsl::SigPoint::Kind::PSIn:
  2831. case hlsl::SigPoint::Kind::MSOut:
  2832. llvm_unreachable("should be handled in gl_PerVertex struct");
  2833. default:
  2834. llvm_unreachable(
  2835. "invalid usage of SV_ClipDistance/SV_CullDistance sneaked in");
  2836. }
  2837. }
  2838. // According to DXIL spec, the IsFrontFace SV can only be used by GSOut and
  2839. // PSIn.
  2840. // According to Vulkan spec, the FrontFacing BuitIn can only be used in PSIn.
  2841. case hlsl::Semantic::Kind::IsFrontFace: {
  2842. switch (sigPointKind) {
  2843. case hlsl::SigPoint::Kind::GSOut:
  2844. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2845. case hlsl::SigPoint::Kind::PSIn:
  2846. stageVar->setIsSpirvBuiltin();
  2847. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::FrontFacing,
  2848. isPrecise, srcLoc);
  2849. default:
  2850. llvm_unreachable("invalid usage of SV_IsFrontFace sneaked in");
  2851. }
  2852. }
  2853. // According to DXIL spec, the Target SV can only be used by PSOut.
  2854. // There is no corresponding builtin decoration in SPIR-V. So generate normal
  2855. // Vulkan stage input/output variables.
  2856. case hlsl::Semantic::Kind::Target:
  2857. // An arbitrary semantic is defined by users. Generate normal Vulkan stage
  2858. // input/output variables.
  2859. case hlsl::Semantic::Kind::Arbitrary: {
  2860. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2861. // TODO: patch constant function in hull shader
  2862. }
  2863. // According to DXIL spec, the DispatchThreadID SV can only be used by CSIn.
  2864. // According to Vulkan spec, the GlobalInvocationId can only be used in CSIn.
  2865. case hlsl::Semantic::Kind::DispatchThreadID: {
  2866. stageVar->setIsSpirvBuiltin();
  2867. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::GlobalInvocationId,
  2868. isPrecise, srcLoc);
  2869. }
  2870. // According to DXIL spec, the GroupID SV can only be used by CSIn.
  2871. // According to Vulkan spec, the WorkgroupId can only be used in CSIn.
  2872. case hlsl::Semantic::Kind::GroupID: {
  2873. stageVar->setIsSpirvBuiltin();
  2874. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::WorkgroupId,
  2875. isPrecise, srcLoc);
  2876. }
  2877. // According to DXIL spec, the GroupThreadID SV can only be used by CSIn.
  2878. // According to Vulkan spec, the LocalInvocationId can only be used in CSIn.
  2879. case hlsl::Semantic::Kind::GroupThreadID: {
  2880. stageVar->setIsSpirvBuiltin();
  2881. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::LocalInvocationId,
  2882. isPrecise, srcLoc);
  2883. }
  2884. // According to DXIL spec, the GroupIndex SV can only be used by CSIn.
  2885. // According to Vulkan spec, the LocalInvocationIndex can only be used in
  2886. // CSIn.
  2887. case hlsl::Semantic::Kind::GroupIndex: {
  2888. stageVar->setIsSpirvBuiltin();
  2889. return spvBuilder.addStageBuiltinVar(
  2890. type, sc, BuiltIn::LocalInvocationIndex, isPrecise, srcLoc);
  2891. }
  2892. // According to DXIL spec, the OutputControlID SV can only be used by HSIn.
  2893. // According to Vulkan spec, the InvocationId BuiltIn can only be used in
  2894. // HS/GS In.
  2895. case hlsl::Semantic::Kind::OutputControlPointID: {
  2896. stageVar->setIsSpirvBuiltin();
  2897. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::InvocationId,
  2898. isPrecise, srcLoc);
  2899. }
  2900. // According to DXIL spec, the PrimitiveID SV can only be used by PCIn, HSIn,
  2901. // DSIn, GSIn, GSOut, PSIn, and MSPOut.
  2902. // According to Vulkan spec, the PrimitiveId BuiltIn can only be used in
  2903. // HS/DS/PS In, GS In/Out, MSPOut.
  2904. case hlsl::Semantic::Kind::PrimitiveID: {
  2905. // Translate to PrimitiveId BuiltIn for all valid SigPoints.
  2906. stageVar->setIsSpirvBuiltin();
  2907. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::PrimitiveId,
  2908. isPrecise, srcLoc);
  2909. }
  2910. // According to DXIL spec, the TessFactor SV can only be used by PCOut and
  2911. // DSIn.
  2912. // According to Vulkan spec, the TessLevelOuter BuiltIn can only be used in
  2913. // PCOut and DSIn.
  2914. case hlsl::Semantic::Kind::TessFactor: {
  2915. stageVar->setIsSpirvBuiltin();
  2916. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::TessLevelOuter,
  2917. isPrecise, srcLoc);
  2918. }
  2919. // According to DXIL spec, the InsideTessFactor SV can only be used by PCOut
  2920. // and DSIn.
  2921. // According to Vulkan spec, the TessLevelInner BuiltIn can only be used in
  2922. // PCOut and DSIn.
  2923. case hlsl::Semantic::Kind::InsideTessFactor: {
  2924. stageVar->setIsSpirvBuiltin();
  2925. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::TessLevelInner,
  2926. isPrecise, srcLoc);
  2927. }
  2928. // According to DXIL spec, the DomainLocation SV can only be used by DSIn.
  2929. // According to Vulkan spec, the TessCoord BuiltIn can only be used in DSIn.
  2930. case hlsl::Semantic::Kind::DomainLocation: {
  2931. stageVar->setIsSpirvBuiltin();
  2932. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::TessCoord,
  2933. isPrecise, srcLoc);
  2934. }
  2935. // According to DXIL spec, the GSInstanceID SV can only be used by GSIn.
  2936. // According to Vulkan spec, the InvocationId BuiltIn can only be used in
  2937. // HS/GS In.
  2938. case hlsl::Semantic::Kind::GSInstanceID: {
  2939. stageVar->setIsSpirvBuiltin();
  2940. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::InvocationId,
  2941. isPrecise, srcLoc);
  2942. }
  2943. // According to DXIL spec, the SampleIndex SV can only be used by PSIn.
  2944. // According to Vulkan spec, the SampleId BuiltIn can only be used in PSIn.
  2945. case hlsl::Semantic::Kind::SampleIndex: {
  2946. stageVar->setIsSpirvBuiltin();
  2947. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::SampleId, isPrecise,
  2948. srcLoc);
  2949. }
  2950. // According to DXIL spec, the StencilRef SV can only be used by PSOut.
  2951. case hlsl::Semantic::Kind::StencilRef: {
  2952. stageVar->setIsSpirvBuiltin();
  2953. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::FragStencilRefEXT,
  2954. isPrecise, srcLoc);
  2955. }
  2956. // According to DXIL spec, the Barycentrics SV can only be used by PSIn.
  2957. case hlsl::Semantic::Kind::Barycentrics: {
  2958. stageVar->setIsSpirvBuiltin();
  2959. // Selecting the correct builtin according to interpolation mode
  2960. auto bi = BuiltIn::Max;
  2961. if (decl->hasAttr<HLSLNoPerspectiveAttr>()) {
  2962. if (decl->hasAttr<HLSLCentroidAttr>()) {
  2963. bi = BuiltIn::BaryCoordNoPerspCentroidAMD;
  2964. } else if (decl->hasAttr<HLSLSampleAttr>()) {
  2965. bi = BuiltIn::BaryCoordNoPerspSampleAMD;
  2966. } else {
  2967. bi = BuiltIn::BaryCoordNoPerspAMD;
  2968. }
  2969. } else {
  2970. if (decl->hasAttr<HLSLCentroidAttr>()) {
  2971. bi = BuiltIn::BaryCoordSmoothCentroidAMD;
  2972. } else if (decl->hasAttr<HLSLSampleAttr>()) {
  2973. bi = BuiltIn::BaryCoordSmoothSampleAMD;
  2974. } else {
  2975. bi = BuiltIn::BaryCoordSmoothAMD;
  2976. }
  2977. }
  2978. return spvBuilder.addStageBuiltinVar(type, sc, bi, isPrecise, srcLoc);
  2979. }
  2980. // According to DXIL spec, the RenderTargetArrayIndex SV can only be used by
  2981. // VSIn, VSOut, HSCPIn, HSCPOut, DSIn, DSOut, GSVIn, GSOut, PSIn, MSPOut.
  2982. // According to Vulkan spec, the Layer BuiltIn can only be used in GSOut
  2983. // PSIn, and MSPOut.
  2984. case hlsl::Semantic::Kind::RenderTargetArrayIndex: {
  2985. switch (sigPointKind) {
  2986. case hlsl::SigPoint::Kind::VSIn:
  2987. case hlsl::SigPoint::Kind::HSCPIn:
  2988. case hlsl::SigPoint::Kind::HSCPOut:
  2989. case hlsl::SigPoint::Kind::PCOut:
  2990. case hlsl::SigPoint::Kind::DSIn:
  2991. case hlsl::SigPoint::Kind::DSCPIn:
  2992. case hlsl::SigPoint::Kind::GSVIn:
  2993. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2994. case hlsl::SigPoint::Kind::VSOut:
  2995. case hlsl::SigPoint::Kind::DSOut:
  2996. stageVar->setIsSpirvBuiltin();
  2997. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::Layer, isPrecise,
  2998. srcLoc);
  2999. case hlsl::SigPoint::Kind::GSOut:
  3000. case hlsl::SigPoint::Kind::PSIn:
  3001. case hlsl::SigPoint::Kind::MSPOut:
  3002. stageVar->setIsSpirvBuiltin();
  3003. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::Layer, isPrecise,
  3004. srcLoc);
  3005. default:
  3006. llvm_unreachable("invalid usage of SV_RenderTargetArrayIndex sneaked in");
  3007. }
  3008. }
  3009. // According to DXIL spec, the ViewportArrayIndex SV can only be used by
  3010. // VSIn, VSOut, HSCPIn, HSCPOut, DSIn, DSOut, GSVIn, GSOut, PSIn, MSPOut.
  3011. // According to Vulkan spec, the ViewportIndex BuiltIn can only be used in
  3012. // GSOut, PSIn, and MSPOut.
  3013. case hlsl::Semantic::Kind::ViewPortArrayIndex: {
  3014. switch (sigPointKind) {
  3015. case hlsl::SigPoint::Kind::VSIn:
  3016. case hlsl::SigPoint::Kind::HSCPIn:
  3017. case hlsl::SigPoint::Kind::HSCPOut:
  3018. case hlsl::SigPoint::Kind::PCOut:
  3019. case hlsl::SigPoint::Kind::DSIn:
  3020. case hlsl::SigPoint::Kind::DSCPIn:
  3021. case hlsl::SigPoint::Kind::GSVIn:
  3022. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  3023. case hlsl::SigPoint::Kind::VSOut:
  3024. case hlsl::SigPoint::Kind::DSOut:
  3025. stageVar->setIsSpirvBuiltin();
  3026. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::ViewportIndex,
  3027. isPrecise, srcLoc);
  3028. case hlsl::SigPoint::Kind::GSOut:
  3029. case hlsl::SigPoint::Kind::PSIn:
  3030. case hlsl::SigPoint::Kind::MSPOut:
  3031. stageVar->setIsSpirvBuiltin();
  3032. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::ViewportIndex,
  3033. isPrecise, srcLoc);
  3034. default:
  3035. llvm_unreachable("invalid usage of SV_ViewportArrayIndex sneaked in");
  3036. }
  3037. }
  3038. // According to DXIL spec, the Coverage SV can only be used by PSIn and PSOut.
  3039. // According to Vulkan spec, the SampleMask BuiltIn can only be used in
  3040. // PSIn and PSOut.
  3041. case hlsl::Semantic::Kind::Coverage: {
  3042. stageVar->setIsSpirvBuiltin();
  3043. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::SampleMask,
  3044. isPrecise, srcLoc);
  3045. }
  3046. // According to DXIL spec, the ViewID SV can only be used by VSIn, PCIn,
  3047. // HSIn, DSIn, GSIn, PSIn.
  3048. // According to Vulkan spec, the ViewIndex BuiltIn can only be used in
  3049. // VS/HS/DS/GS/PS input.
  3050. case hlsl::Semantic::Kind::ViewID: {
  3051. stageVar->setIsSpirvBuiltin();
  3052. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::ViewIndex,
  3053. isPrecise, srcLoc);
  3054. }
  3055. // According to DXIL spec, the InnerCoverage SV can only be used as PSIn.
  3056. // According to Vulkan spec, the FullyCoveredEXT BuiltIn can only be used as
  3057. // PSIn.
  3058. case hlsl::Semantic::Kind::InnerCoverage: {
  3059. stageVar->setIsSpirvBuiltin();
  3060. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::FullyCoveredEXT,
  3061. isPrecise, srcLoc);
  3062. }
  3063. // According to DXIL spec, the ShadingRate SV can only be used by GSOut,
  3064. // VSOut, or PSIn. According to Vulkan spec, the FragSizeEXT BuiltIn can only
  3065. // be used as PSIn.
  3066. case hlsl::Semantic::Kind::ShadingRate: {
  3067. switch (sigPointKind) {
  3068. case hlsl::SigPoint::Kind::PSIn:
  3069. stageVar->setIsSpirvBuiltin();
  3070. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::FragSizeEXT,
  3071. isPrecise, srcLoc);
  3072. default:
  3073. emitError("semantic ShadingRate currently unsupported in non-PS shader"
  3074. " stages",
  3075. srcLoc);
  3076. break;
  3077. }
  3078. break;
  3079. }
  3080. default:
  3081. emitError("semantic %0 unimplemented", srcLoc)
  3082. << stageVar->getSemanticStr();
  3083. break;
  3084. }
  3085. return 0;
  3086. }
  3087. bool DeclResultIdMapper::validateVKAttributes(const NamedDecl *decl) {
  3088. bool success = true;
  3089. if (const auto *idxAttr = decl->getAttr<VKIndexAttr>()) {
  3090. if (!spvContext.isPS()) {
  3091. emitError("vk::index only allowed in pixel shader",
  3092. idxAttr->getLocation());
  3093. success = false;
  3094. }
  3095. const auto *locAttr = decl->getAttr<VKLocationAttr>();
  3096. if (!locAttr) {
  3097. emitError("vk::index should be used together with vk::location for "
  3098. "dual-source blending",
  3099. idxAttr->getLocation());
  3100. success = false;
  3101. } else {
  3102. const auto locNumber = locAttr->getNumber();
  3103. if (locNumber != 0) {
  3104. emitError("dual-source blending should use vk::location 0",
  3105. locAttr->getLocation());
  3106. success = false;
  3107. }
  3108. }
  3109. const auto idxNumber = idxAttr->getNumber();
  3110. if (idxNumber != 0 && idxNumber != 1) {
  3111. emitError("dual-source blending only accepts 0 or 1 as vk::index",
  3112. idxAttr->getLocation());
  3113. success = false;
  3114. }
  3115. }
  3116. return success;
  3117. }
  3118. bool DeclResultIdMapper::validateVKBuiltins(const NamedDecl *decl,
  3119. const hlsl::SigPoint *sigPoint) {
  3120. bool success = true;
  3121. if (const auto *builtinAttr = decl->getAttr<VKBuiltInAttr>()) {
  3122. // The front end parsing only allows vk::builtin to be attached to a
  3123. // function/parameter/variable; all of them are DeclaratorDecls.
  3124. const auto declType = getTypeOrFnRetType(cast<DeclaratorDecl>(decl));
  3125. const auto loc = builtinAttr->getLocation();
  3126. if (decl->hasAttr<VKLocationAttr>()) {
  3127. emitError("cannot use vk::builtin and vk::location together", loc);
  3128. success = false;
  3129. }
  3130. const llvm::StringRef builtin = builtinAttr->getBuiltIn();
  3131. if (builtin == "HelperInvocation") {
  3132. if (!declType->isBooleanType()) {
  3133. emitError("HelperInvocation builtin must be of boolean type", loc);
  3134. success = false;
  3135. }
  3136. if (sigPoint->GetKind() != hlsl::SigPoint::Kind::PSIn) {
  3137. emitError(
  3138. "HelperInvocation builtin can only be used as pixel shader input",
  3139. loc);
  3140. success = false;
  3141. }
  3142. } else if (builtin == "PointSize") {
  3143. if (!declType->isFloatingType()) {
  3144. emitError("PointSize builtin must be of float type", loc);
  3145. success = false;
  3146. }
  3147. switch (sigPoint->GetKind()) {
  3148. case hlsl::SigPoint::Kind::VSOut:
  3149. case hlsl::SigPoint::Kind::HSCPIn:
  3150. case hlsl::SigPoint::Kind::HSCPOut:
  3151. case hlsl::SigPoint::Kind::DSCPIn:
  3152. case hlsl::SigPoint::Kind::DSOut:
  3153. case hlsl::SigPoint::Kind::GSVIn:
  3154. case hlsl::SigPoint::Kind::GSOut:
  3155. case hlsl::SigPoint::Kind::PSIn:
  3156. case hlsl::SigPoint::Kind::MSOut:
  3157. break;
  3158. default:
  3159. emitError("PointSize builtin cannot be used as %0", loc)
  3160. << sigPoint->GetName();
  3161. success = false;
  3162. }
  3163. } else if (builtin == "BaseVertex" || builtin == "BaseInstance" ||
  3164. builtin == "DrawIndex") {
  3165. if (!declType->isSpecificBuiltinType(BuiltinType::Kind::Int) &&
  3166. !declType->isSpecificBuiltinType(BuiltinType::Kind::UInt)) {
  3167. emitError("%0 builtin must be of 32-bit scalar integer type", loc)
  3168. << builtin;
  3169. success = false;
  3170. }
  3171. switch (sigPoint->GetKind()) {
  3172. case hlsl::SigPoint::Kind::VSIn:
  3173. break;
  3174. case hlsl::SigPoint::Kind::MSIn:
  3175. case hlsl::SigPoint::Kind::ASIn:
  3176. if (builtin != "DrawIndex") {
  3177. emitError("%0 builtin cannot be used as %1", loc)
  3178. << builtin << sigPoint->GetName();
  3179. success = false;
  3180. }
  3181. break;
  3182. default:
  3183. emitError("%0 builtin cannot be used as %1", loc)
  3184. << builtin << sigPoint->GetName();
  3185. success = false;
  3186. }
  3187. } else if (builtin == "DeviceIndex") {
  3188. if (getStorageClassForSigPoint(sigPoint) != spv::StorageClass::Input) {
  3189. emitError("%0 builtin can only be used as shader input", loc)
  3190. << builtin;
  3191. success = false;
  3192. }
  3193. if (!declType->isSpecificBuiltinType(BuiltinType::Kind::Int) &&
  3194. !declType->isSpecificBuiltinType(BuiltinType::Kind::UInt)) {
  3195. emitError("%0 builtin must be of 32-bit scalar integer type", loc)
  3196. << builtin;
  3197. success = false;
  3198. }
  3199. } else if (builtin == "ViewportMaskNV") {
  3200. if (sigPoint->GetKind() != hlsl::SigPoint::Kind::MSPOut) {
  3201. emitError("%0 builtin can only be used as 'primitives' output in MS",
  3202. loc)
  3203. << builtin;
  3204. success = false;
  3205. }
  3206. if (!declType->isArrayType() ||
  3207. !declType->getArrayElementTypeNoTypeQual()->isSpecificBuiltinType(
  3208. BuiltinType::Kind::Int)) {
  3209. emitError("%0 builtin must be of type array of integers", loc)
  3210. << builtin;
  3211. success = false;
  3212. }
  3213. }
  3214. }
  3215. return success;
  3216. }
  3217. spv::StorageClass
  3218. DeclResultIdMapper::getStorageClassForSigPoint(const hlsl::SigPoint *sigPoint) {
  3219. // This translation is done based on the HLSL reference (see docs/dxil.rst).
  3220. const auto sigPointKind = sigPoint->GetKind();
  3221. const auto signatureKind = sigPoint->GetSignatureKind();
  3222. spv::StorageClass sc = spv::StorageClass::Max;
  3223. switch (signatureKind) {
  3224. case hlsl::DXIL::SignatureKind::Input:
  3225. sc = spv::StorageClass::Input;
  3226. break;
  3227. case hlsl::DXIL::SignatureKind::Output:
  3228. sc = spv::StorageClass::Output;
  3229. break;
  3230. case hlsl::DXIL::SignatureKind::Invalid: {
  3231. // There are some special cases in HLSL (See docs/dxil.rst):
  3232. // SignatureKind is "invalid" for PCIn, HSIn, GSIn, and CSIn.
  3233. switch (sigPointKind) {
  3234. case hlsl::DXIL::SigPointKind::PCIn:
  3235. case hlsl::DXIL::SigPointKind::HSIn:
  3236. case hlsl::DXIL::SigPointKind::GSIn:
  3237. case hlsl::DXIL::SigPointKind::CSIn:
  3238. case hlsl::DXIL::SigPointKind::MSIn:
  3239. case hlsl::DXIL::SigPointKind::ASIn:
  3240. sc = spv::StorageClass::Input;
  3241. break;
  3242. default:
  3243. llvm_unreachable("Found invalid SigPoint kind for semantic");
  3244. }
  3245. break;
  3246. }
  3247. case hlsl::DXIL::SignatureKind::PatchConstOrPrim: {
  3248. // There are some special cases in HLSL (See docs/dxil.rst):
  3249. // SignatureKind is "PatchConstOrPrim" for PCOut, MSPOut and DSIn.
  3250. switch (sigPointKind) {
  3251. case hlsl::DXIL::SigPointKind::PCOut:
  3252. case hlsl::DXIL::SigPointKind::MSPOut:
  3253. // Patch Constant Output (Output of Hull which is passed to Domain).
  3254. // Mesh Shader per-primitive output attributes.
  3255. sc = spv::StorageClass::Output;
  3256. break;
  3257. case hlsl::DXIL::SigPointKind::DSIn:
  3258. // Domain Shader regular input - Patch Constant data plus system values.
  3259. sc = spv::StorageClass::Input;
  3260. break;
  3261. default:
  3262. llvm_unreachable("Found invalid SigPoint kind for semantic");
  3263. }
  3264. break;
  3265. }
  3266. default:
  3267. llvm_unreachable("Found invalid SigPoint kind for semantic");
  3268. }
  3269. return sc;
  3270. }
  3271. QualType DeclResultIdMapper::getTypeAndCreateCounterForPotentialAliasVar(
  3272. const DeclaratorDecl *decl, bool *shouldBeAlias) {
  3273. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  3274. // This method is only intended to be used to create SPIR-V variables in the
  3275. // Function or Private storage class.
  3276. assert(!varDecl->isExternallyVisible() || varDecl->isStaticDataMember());
  3277. }
  3278. const QualType type = getTypeOrFnRetType(decl);
  3279. // Whether we should generate this decl as an alias variable.
  3280. bool genAlias = false;
  3281. // For ConstantBuffers, TextureBuffers, StructuredBuffers, ByteAddressBuffers
  3282. if (isConstantTextureBuffer(type) ||
  3283. isOrContainsAKindOfStructuredOrByteBuffer(type)) {
  3284. genAlias = true;
  3285. }
  3286. // Return via parameter whether alias was generated.
  3287. if (shouldBeAlias)
  3288. *shouldBeAlias = genAlias;
  3289. if (genAlias) {
  3290. needsLegalization = true;
  3291. createCounterVarForDecl(decl);
  3292. }
  3293. return type;
  3294. }
  3295. bool DeclResultIdMapper::getImplicitRegisterType(const ResourceVar &var,
  3296. char *registerTypeOut) const {
  3297. assert(registerTypeOut);
  3298. if (var.getSpirvInstr()) {
  3299. if (var.getSpirvInstr()->hasAstResultType()) {
  3300. QualType type = var.getSpirvInstr()->getAstResultType();
  3301. // Strip outer arrayness first
  3302. while (type->isArrayType())
  3303. type = type->getAsArrayTypeUnsafe()->getElementType();
  3304. // t - for shader resource views (SRV)
  3305. if (isTexture(type) || isNonWritableStructuredBuffer(type) ||
  3306. isByteAddressBuffer(type) || isBuffer(type)) {
  3307. *registerTypeOut = 't';
  3308. return true;
  3309. }
  3310. // s - for samplers
  3311. else if (isSampler(type)) {
  3312. *registerTypeOut = 's';
  3313. return true;
  3314. }
  3315. // u - for unordered access views (UAV)
  3316. else if (isRWByteAddressBuffer(type) || isRWAppendConsumeSBuffer(type) ||
  3317. isRWBuffer(type) || isRWTexture(type)) {
  3318. *registerTypeOut = 'u';
  3319. return true;
  3320. }
  3321. } else {
  3322. llvm::StringRef hlslUserType = var.getSpirvInstr()->getHlslUserType();
  3323. // b - for constant buffer views (CBV)
  3324. if (var.isGlobalsBuffer() || hlslUserType == "cbuffer" ||
  3325. hlslUserType == "ConstantBuffer") {
  3326. *registerTypeOut = 'b';
  3327. return true;
  3328. }
  3329. if (hlslUserType == "tbuffer") {
  3330. *registerTypeOut = 't';
  3331. return true;
  3332. }
  3333. }
  3334. }
  3335. *registerTypeOut = '\0';
  3336. return false;
  3337. }
  3338. SpirvVariable *
  3339. DeclResultIdMapper::createRayTracingNVStageVar(spv::StorageClass sc,
  3340. const VarDecl *decl) {
  3341. QualType type = decl->getType();
  3342. SpirvVariable *retVal = nullptr;
  3343. // Raytracing interface variables are special since they do not participate
  3344. // in any interface matching and hence do not create StageVar and
  3345. // track them under StageVars vector
  3346. const auto name = decl->getName();
  3347. switch (sc) {
  3348. case spv::StorageClass::IncomingRayPayloadNV:
  3349. case spv::StorageClass::IncomingCallableDataNV:
  3350. case spv::StorageClass::HitAttributeNV:
  3351. case spv::StorageClass::RayPayloadNV:
  3352. case spv::StorageClass::CallableDataNV:
  3353. retVal = spvBuilder.addModuleVar(type, sc, decl->hasAttr<HLSLPreciseAttr>(),
  3354. name.str());
  3355. break;
  3356. default:
  3357. assert(false && "Unsupported SPIR-V storage class for raytracing");
  3358. }
  3359. return retVal;
  3360. }
  3361. void DeclResultIdMapper::tryToCreateImplicitConstVar(const ValueDecl *decl) {
  3362. const VarDecl *varDecl = dyn_cast<VarDecl>(decl);
  3363. if (!varDecl || !varDecl->isImplicit())
  3364. return;
  3365. APValue *val = varDecl->evaluateValue();
  3366. if (!val)
  3367. return;
  3368. SpirvInstruction *constVal =
  3369. spvBuilder.getConstantInt(astContext.UnsignedIntTy, val->getInt());
  3370. constVal->setRValue(true);
  3371. astDecls[varDecl].instr = constVal;
  3372. }
  3373. SpirvInstruction *
  3374. DeclResultIdMapper::createHullMainOutputPatch(const ParmVarDecl *param,
  3375. const QualType retType,
  3376. uint32_t numOutputControlPoints) {
  3377. const QualType hullMainRetType = astContext.getConstantArrayType(
  3378. retType, llvm::APInt(32, numOutputControlPoints),
  3379. clang::ArrayType::Normal, 0);
  3380. SpirvInstruction *hullMainOutputPatch = createSpirvIntermediateOutputStageVar(
  3381. param, "temp.var.hullMainRetVal", hullMainRetType);
  3382. assert(astDecls[param].instr == nullptr);
  3383. astDecls[param].instr = hullMainOutputPatch;
  3384. return hullMainOutputPatch;
  3385. }
  3386. } // end namespace spirv
  3387. } // end namespace clang