SPIRVEmitter.cpp 149 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921
  1. //===------- SPIRVEmitter.h - SPIR-V Binary Code Emitter --------*- 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. // This file implements a SPIR-V emitter class that takes in HLSL AST and emits
  10. // SPIR-V binary words.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "SPIRVEmitter.h"
  14. #include "dxc/HlslIntrinsicOp.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "InitListHandler.h"
  17. namespace clang {
  18. namespace spirv {
  19. namespace {
  20. // TODO: Maybe we should move these type probing functions to TypeTranslator.
  21. /// Returns true if the two types are the same scalar or vector type.
  22. bool isSameScalarOrVecType(QualType type1, QualType type2) {
  23. {
  24. QualType scalarType1 = {}, scalarType2 = {};
  25. if (TypeTranslator::isScalarType(type1, &scalarType1) &&
  26. TypeTranslator::isScalarType(type2, &scalarType2))
  27. return scalarType1.getCanonicalType() == scalarType2.getCanonicalType();
  28. }
  29. {
  30. QualType elemType1 = {}, elemType2 = {};
  31. uint32_t count1 = {}, count2 = {};
  32. if (TypeTranslator::isVectorType(type1, &elemType1, &count1) &&
  33. TypeTranslator::isVectorType(type2, &elemType2, &count2))
  34. return count1 == count2 &&
  35. elemType1.getCanonicalType() == elemType2.getCanonicalType();
  36. }
  37. return false;
  38. }
  39. /// Returns true if the given type is a bool or vector of bool type.
  40. bool isBoolOrVecOfBoolType(QualType type) {
  41. QualType elemType = {};
  42. return (TypeTranslator::isScalarType(type, &elemType) ||
  43. TypeTranslator::isVectorType(type, &elemType)) &&
  44. elemType->isBooleanType();
  45. }
  46. /// Returns true if the given type is a signed integer or vector of signed
  47. /// integer type.
  48. bool isSintOrVecOfSintType(QualType type) {
  49. QualType elemType = {};
  50. return (TypeTranslator::isScalarType(type, &elemType) ||
  51. TypeTranslator::isVectorType(type, &elemType)) &&
  52. elemType->isSignedIntegerType();
  53. }
  54. /// Returns true if the given type is an unsigned integer or vector of unsigned
  55. /// integer type.
  56. bool isUintOrVecOfUintType(QualType type) {
  57. QualType elemType = {};
  58. return (TypeTranslator::isScalarType(type, &elemType) ||
  59. TypeTranslator::isVectorType(type, &elemType)) &&
  60. elemType->isUnsignedIntegerType();
  61. }
  62. /// Returns true if the given type is a float or vector of float type.
  63. bool isFloatOrVecOfFloatType(QualType type) {
  64. QualType elemType = {};
  65. return (TypeTranslator::isScalarType(type, &elemType) ||
  66. TypeTranslator::isVectorType(type, &elemType)) &&
  67. elemType->isFloatingType();
  68. }
  69. /// Returns true if the given type is a bool or vector/matrix of bool type.
  70. bool isBoolOrVecMatOfBoolType(QualType type) {
  71. return isBoolOrVecOfBoolType(type) ||
  72. (hlsl::IsHLSLMatType(type) &&
  73. hlsl::GetHLSLMatElementType(type)->isBooleanType());
  74. }
  75. /// Returns true if the given type is a signed integer or vector/matrix of
  76. /// signed integer type.
  77. bool isSintOrVecMatOfSintType(QualType type) {
  78. return isSintOrVecOfSintType(type) ||
  79. (hlsl::IsHLSLMatType(type) &&
  80. hlsl::GetHLSLMatElementType(type)->isSignedIntegerType());
  81. }
  82. /// Returns true if the given type is an unsigned integer or vector/matrix of
  83. /// unsigned integer type.
  84. bool isUintOrVecMatOfUintType(QualType type) {
  85. return isUintOrVecOfUintType(type) ||
  86. (hlsl::IsHLSLMatType(type) &&
  87. hlsl::GetHLSLMatElementType(type)->isUnsignedIntegerType());
  88. }
  89. /// Returns true if the given type is a float or vector/matrix of float type.
  90. bool isFloatOrVecMatOfFloatType(QualType type) {
  91. return isFloatOrVecOfFloatType(type) ||
  92. (hlsl::IsHLSLMatType(type) &&
  93. hlsl::GetHLSLMatElementType(type)->isFloatingType());
  94. }
  95. /// Returns true if the given type is a (RW)StructuredBuffer type.
  96. bool isStructuredBuffer(QualType type) {
  97. const auto *recordType = type->getAs<RecordType>();
  98. if (!recordType)
  99. return false;
  100. const auto name = recordType->getDecl()->getName();
  101. return name == "StructuredBuffer" || name == "RWStructuredBuffer";
  102. }
  103. bool isSpirvMatrixOp(spv::Op opcode) {
  104. switch (opcode) {
  105. case spv::Op::OpMatrixTimesMatrix:
  106. case spv::Op::OpMatrixTimesVector:
  107. case spv::Op::OpMatrixTimesScalar:
  108. return true;
  109. default:
  110. break;
  111. }
  112. return false;
  113. }
  114. /// If expr is a (RW)StructuredBuffer.Load(), returns the object and writes
  115. /// index. Otherwiser, returns false.
  116. // TODO: The following doesn't handle Load(int, int) yet. And it is basically a
  117. // duplicate of doCXXMemberCallExpr.
  118. const Expr *isStructuredBufferLoad(const Expr *expr, const Expr **index) {
  119. using namespace hlsl;
  120. if (const auto *indexing = dyn_cast<CXXMemberCallExpr>(expr)) {
  121. const auto *callee = indexing->getDirectCallee();
  122. uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
  123. llvm::StringRef group;
  124. if (GetIntrinsicOp(callee, opcode, group)) {
  125. if (static_cast<IntrinsicOp>(opcode) == IntrinsicOp::MOP_Load) {
  126. const auto *object = indexing->getImplicitObjectArgument();
  127. if (isStructuredBuffer(object->getType())) {
  128. *index = indexing->getArg(0);
  129. return indexing->getImplicitObjectArgument();
  130. }
  131. }
  132. }
  133. }
  134. return nullptr;
  135. }
  136. /// \brief Returns the statement that is the immediate parent AST node of the
  137. /// given statement. Returns nullptr if there are no parents nodes.
  138. const Stmt *getImmediateParent(ASTContext &astContext, const Stmt *stmt) {
  139. const auto &parents = astContext.getParents(*stmt);
  140. return parents.empty() ? nullptr : parents[0].get<Stmt>();
  141. }
  142. bool isLoopStmt(const Stmt *stmt) {
  143. return isa<ForStmt>(stmt) || isa<WhileStmt>(stmt) || isa<DoStmt>(stmt);
  144. }
  145. } // namespace
  146. SPIRVEmitter::SPIRVEmitter(CompilerInstance &ci,
  147. const EmitSPIRVOptions &options)
  148. : theCompilerInstance(ci), astContext(ci.getASTContext()),
  149. diags(ci.getDiagnostics()), spirvOptions(options),
  150. entryFunctionName(ci.getCodeGenOpts().HLSLEntryFunction),
  151. shaderModel(*hlsl::ShaderModel::GetByName(
  152. ci.getCodeGenOpts().HLSLProfile.c_str())),
  153. theContext(), theBuilder(&theContext),
  154. declIdMapper(shaderModel, astContext, theBuilder, diags, spirvOptions),
  155. typeTranslator(astContext, theBuilder, diags), entryFunctionId(0),
  156. curFunction(nullptr) {
  157. if (shaderModel.GetKind() == hlsl::ShaderModel::Kind::Invalid)
  158. emitError("unknown shader module: %0") << shaderModel.GetName();
  159. }
  160. void SPIRVEmitter::HandleTranslationUnit(ASTContext &context) {
  161. AddRequiredCapabilitiesForShaderModel();
  162. // Addressing and memory model are required in a valid SPIR-V module.
  163. theBuilder.setAddressingModel(spv::AddressingModel::Logical);
  164. theBuilder.setMemoryModel(spv::MemoryModel::GLSL450);
  165. TranslationUnitDecl *tu = context.getTranslationUnitDecl();
  166. // The entry function is the seed of the queue.
  167. for (auto *decl : tu->decls()) {
  168. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  169. if (funcDecl->getName() == entryFunctionName) {
  170. workQueue.insert(funcDecl);
  171. }
  172. } else if (auto *varDecl = dyn_cast<VarDecl>(decl)) {
  173. if (isa<HLSLBufferDecl>(varDecl->getDeclContext())) {
  174. // This is a VarDecl of a ConstantBuffer/TextureBuffer type.
  175. (void)declIdMapper.createCTBuffer(varDecl);
  176. } else {
  177. doVarDecl(varDecl);
  178. }
  179. } else if (auto *bufferDecl = dyn_cast<HLSLBufferDecl>(decl)) {
  180. // This is a cbuffer/tbuffer decl.
  181. (void)declIdMapper.createCTBuffer(bufferDecl);
  182. }
  183. }
  184. // Translate all functions reachable from the entry function.
  185. // The queue can grow in the meanwhile; so need to keep evaluating
  186. // workQueue.size().
  187. for (uint32_t i = 0; i < workQueue.size(); ++i) {
  188. doDecl(workQueue[i]);
  189. }
  190. theBuilder.addEntryPoint(getSpirvShaderStage(shaderModel), entryFunctionId,
  191. entryFunctionName, declIdMapper.collectStageVars());
  192. AddExecutionModeForEntryPoint(entryFunctionId);
  193. // Add Location decorations to stage input/output variables.
  194. if (!declIdMapper.decorateStageIOLocations())
  195. return;
  196. // Add descriptor set and binding decorations to resource variables.
  197. if (!declIdMapper.decorateResourceBindings())
  198. return;
  199. // Output the constructed module.
  200. std::vector<uint32_t> m = theBuilder.takeModule();
  201. theCompilerInstance.getOutStream()->write(
  202. reinterpret_cast<const char *>(m.data()), m.size() * 4);
  203. }
  204. void SPIRVEmitter::doDecl(const Decl *decl) {
  205. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  206. doVarDecl(varDecl);
  207. } else if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  208. doFunctionDecl(funcDecl);
  209. } else if (dyn_cast<HLSLBufferDecl>(decl)) {
  210. llvm_unreachable("HLSLBufferDecl should not be handled here");
  211. } else {
  212. // TODO: Implement handling of other Decl types.
  213. emitWarning("Decl type '%0' is not supported yet.")
  214. << decl->getDeclKindName();
  215. }
  216. }
  217. void SPIRVEmitter::doStmt(const Stmt *stmt,
  218. llvm::ArrayRef<const Attr *> attrs) {
  219. if (const auto *compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
  220. for (auto *st : compoundStmt->body())
  221. doStmt(st);
  222. } else if (const auto *retStmt = dyn_cast<ReturnStmt>(stmt)) {
  223. doReturnStmt(retStmt);
  224. } else if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) {
  225. doDeclStmt(declStmt);
  226. } else if (const auto *ifStmt = dyn_cast<IfStmt>(stmt)) {
  227. doIfStmt(ifStmt);
  228. } else if (const auto *switchStmt = dyn_cast<SwitchStmt>(stmt)) {
  229. doSwitchStmt(switchStmt, attrs);
  230. } else if (const auto *caseStmt = dyn_cast<CaseStmt>(stmt)) {
  231. processCaseStmtOrDefaultStmt(stmt);
  232. } else if (const auto *defaultStmt = dyn_cast<DefaultStmt>(stmt)) {
  233. processCaseStmtOrDefaultStmt(stmt);
  234. } else if (const auto *breakStmt = dyn_cast<BreakStmt>(stmt)) {
  235. doBreakStmt(breakStmt);
  236. } else if (const auto *theDoStmt = dyn_cast<DoStmt>(stmt)) {
  237. doDoStmt(theDoStmt, attrs);
  238. } else if (const auto *discardStmt = dyn_cast<DiscardStmt>(stmt)) {
  239. doDiscardStmt(discardStmt);
  240. } else if (const auto *continueStmt = dyn_cast<ContinueStmt>(stmt)) {
  241. doContinueStmt(continueStmt);
  242. } else if (const auto *whileStmt = dyn_cast<WhileStmt>(stmt)) {
  243. doWhileStmt(whileStmt, attrs);
  244. } else if (const auto *forStmt = dyn_cast<ForStmt>(stmt)) {
  245. doForStmt(forStmt, attrs);
  246. } else if (const auto *nullStmt = dyn_cast<NullStmt>(stmt)) {
  247. // For the null statement ";". We don't need to do anything.
  248. } else if (const auto *expr = dyn_cast<Expr>(stmt)) {
  249. // All cases for expressions used as statements
  250. doExpr(expr);
  251. } else if (const auto *attrStmt = dyn_cast<AttributedStmt>(stmt)) {
  252. doStmt(attrStmt->getSubStmt(), attrStmt->getAttrs());
  253. } else {
  254. emitError("Stmt '%0' is not supported yet.") << stmt->getStmtClassName();
  255. }
  256. }
  257. uint32_t SPIRVEmitter::doExpr(const Expr *expr) {
  258. if (const auto *delRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  259. // Returns the <result-id> of the referenced Decl.
  260. return declIdMapper.getDeclResultId(delRefExpr->getFoundDecl());
  261. }
  262. if (const auto *parenExpr = dyn_cast<ParenExpr>(expr)) {
  263. // Just need to return what's inside the parentheses.
  264. return doExpr(parenExpr->getSubExpr());
  265. }
  266. if (const auto *memberExpr = dyn_cast<MemberExpr>(expr)) {
  267. return doMemberExpr(memberExpr);
  268. }
  269. if (const auto *castExpr = dyn_cast<CastExpr>(expr)) {
  270. return doCastExpr(castExpr);
  271. }
  272. if (const auto *initListExpr = dyn_cast<InitListExpr>(expr)) {
  273. return doInitListExpr(initListExpr);
  274. }
  275. if (const auto *boolLiteral = dyn_cast<CXXBoolLiteralExpr>(expr)) {
  276. const bool value = boolLiteral->getValue();
  277. return theBuilder.getConstantBool(value);
  278. }
  279. if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  280. return translateAPInt(intLiteral->getValue(), expr->getType());
  281. }
  282. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  283. return translateAPFloat(floatLiteral->getValue(), expr->getType());
  284. }
  285. // CompoundAssignOperator is a subclass of BinaryOperator. It should be
  286. // checked before BinaryOperator.
  287. if (const auto *compoundAssignOp = dyn_cast<CompoundAssignOperator>(expr)) {
  288. return doCompoundAssignOperator(compoundAssignOp);
  289. }
  290. if (const auto *binOp = dyn_cast<BinaryOperator>(expr)) {
  291. return doBinaryOperator(binOp);
  292. }
  293. if (const auto *unaryOp = dyn_cast<UnaryOperator>(expr)) {
  294. return doUnaryOperator(unaryOp);
  295. }
  296. if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  297. return doHLSLVectorElementExpr(vecElemExpr);
  298. }
  299. if (const auto *matElemExpr = dyn_cast<ExtMatrixElementExpr>(expr)) {
  300. return doExtMatrixElementExpr(matElemExpr);
  301. }
  302. if (const auto *funcCall = dyn_cast<CallExpr>(expr)) {
  303. return doCallExpr(funcCall);
  304. }
  305. if (const auto *subscriptExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  306. return doArraySubscriptExpr(subscriptExpr);
  307. }
  308. if (const auto *condExpr = dyn_cast<ConditionalOperator>(expr)) {
  309. return doConditionalOperator(condExpr);
  310. }
  311. emitError("Expr '%0' is not supported yet.") << expr->getStmtClassName();
  312. // TODO: handle other expressions
  313. return 0;
  314. }
  315. uint32_t SPIRVEmitter::loadIfGLValue(const Expr *expr) {
  316. const uint32_t result = doExpr(expr);
  317. if (expr->isGLValue()) {
  318. const uint32_t baseTyId = typeTranslator.translateType(expr->getType());
  319. return theBuilder.createLoad(baseTyId, result);
  320. }
  321. return result;
  322. }
  323. uint32_t SPIRVEmitter::castToType(uint32_t value, QualType fromType,
  324. QualType toType) {
  325. if (isFloatOrVecOfFloatType(toType))
  326. return castToFloat(value, fromType, toType);
  327. // Order matters here. Bool (vector) values will also be considered as uint
  328. // (vector) values. So given a bool (vector) argument, isUintOrVecOfUintType()
  329. // will also return true. We need to check bool before uint. The opposite is
  330. // not true.
  331. if (isBoolOrVecOfBoolType(toType))
  332. return castToBool(value, fromType, toType);
  333. if (isSintOrVecOfSintType(toType) || isUintOrVecOfUintType(toType))
  334. return castToInt(value, fromType, toType);
  335. emitError("casting to type %0 unimplemented") << toType;
  336. return 0;
  337. }
  338. void SPIRVEmitter::doFunctionDecl(const FunctionDecl *decl) {
  339. // We are about to start translation for a new function. Clear the break stack
  340. // and the continue stack.
  341. breakStack = std::stack<uint32_t>();
  342. continueStack = std::stack<uint32_t>();
  343. curFunction = decl;
  344. std::string funcName = decl->getName();
  345. uint32_t funcId = 0;
  346. if (funcName == entryFunctionName) {
  347. // The entry function surely does not have pre-assigned <result-id> for
  348. // it like other functions that got added to the work queue following
  349. // function calls.
  350. funcId = theContext.takeNextId();
  351. funcName = "src." + funcName;
  352. // Create wrapper for the entry function
  353. if (!emitEntryFunctionWrapper(decl, funcId))
  354. return;
  355. } else {
  356. // Non-entry functions are added to the work queue following function
  357. // calls. We have already assigned <result-id>s for it when translating
  358. // its call site. Query it here.
  359. funcId = declIdMapper.getDeclResultId(decl);
  360. }
  361. const uint32_t retType = typeTranslator.translateType(decl->getReturnType());
  362. // Construct the function signature.
  363. llvm::SmallVector<uint32_t, 4> paramTypes;
  364. for (const auto *param : decl->params()) {
  365. const uint32_t valueType = typeTranslator.translateType(param->getType());
  366. const uint32_t ptrType =
  367. theBuilder.getPointerType(valueType, spv::StorageClass::Function);
  368. paramTypes.push_back(ptrType);
  369. }
  370. const uint32_t funcType = theBuilder.getFunctionType(retType, paramTypes);
  371. theBuilder.beginFunction(funcType, retType, funcName, funcId);
  372. // Create all parameters.
  373. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  374. const ParmVarDecl *paramDecl = decl->getParamDecl(i);
  375. (void)declIdMapper.createFnParam(paramTypes[i], paramDecl);
  376. }
  377. if (decl->hasBody()) {
  378. // The entry basic block.
  379. const uint32_t entryLabel = theBuilder.createBasicBlock("bb.entry");
  380. theBuilder.setInsertPoint(entryLabel);
  381. // Process all statments in the body.
  382. doStmt(decl->getBody());
  383. // We have processed all Stmts in this function and now in the last
  384. // basic block. Make sure we have OpReturn if missing.
  385. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  386. theBuilder.createReturn();
  387. }
  388. }
  389. theBuilder.endFunction();
  390. curFunction = nullptr;
  391. }
  392. void SPIRVEmitter::doVarDecl(const VarDecl *decl) {
  393. // The contents in externally visible variables can be updated via the
  394. // pipeline. They should be handled differently from file and function scope
  395. // variables.
  396. // File scope variables (static "global" and "local" variables) belongs to
  397. // the Private storage class, while function scope variables (normal "local"
  398. // variables) belongs to the Function storage class.
  399. if (!decl->isExternallyVisible()) {
  400. // Note: cannot move varType outside of this scope because it generates
  401. // SPIR-V types without decorations, while external visible variable should
  402. // have SPIR-V type with decorations.
  403. const uint32_t varType = typeTranslator.translateType(decl->getType());
  404. // We already know the variable is not externally visible here. If it does
  405. // not have local storage, it should be file scope variable.
  406. const bool isFileScopeVar = !decl->hasLocalStorage();
  407. // Handle initializer. SPIR-V requires that "initializer must be an <id>
  408. // from a constant instruction or a global (module scope) OpVariable
  409. // instruction."
  410. llvm::Optional<uint32_t> constInit;
  411. if (decl->hasInit()) {
  412. if (const uint32_t id = tryToEvaluateAsConst(decl->getInit()))
  413. constInit = llvm::Optional<uint32_t>(id);
  414. } else if (isFileScopeVar) {
  415. // For static variables, if no initializers are provided, we should
  416. // initialize them to zero values.
  417. constInit = llvm::Optional<uint32_t>(theBuilder.getConstantNull(varType));
  418. }
  419. uint32_t varId;
  420. if (isFileScopeVar)
  421. varId = declIdMapper.createFileVar(varType, decl, constInit);
  422. else
  423. varId = declIdMapper.createFnVar(varType, decl, constInit);
  424. // If we cannot evaluate the initializer as a constant expression, we'll
  425. // need to use OpStore to write the initializer to the variable.
  426. // Also we should only evaluate the initializer once for a static variable.
  427. if (decl->hasInit() && !constInit.hasValue()) {
  428. if (isFileScopeVar) {
  429. if (decl->isStaticLocal()) {
  430. initOnce(decl->getName(), varId, decl->getInit());
  431. } else {
  432. // Defer to initialize these global variables at the beginning of the
  433. // entry function.
  434. toInitGloalVars.push_back(decl);
  435. }
  436. } else {
  437. theBuilder.createStore(varId, doExpr(decl->getInit()));
  438. }
  439. }
  440. } else {
  441. (void)declIdMapper.createExternVar(decl);
  442. }
  443. }
  444. spv::LoopControlMask SPIRVEmitter::translateLoopAttribute(const Attr &attr) {
  445. switch (attr.getKind()) {
  446. case attr::HLSLLoop:
  447. case attr::HLSLFastOpt:
  448. return spv::LoopControlMask::DontUnroll;
  449. case attr::HLSLUnroll:
  450. return spv::LoopControlMask::Unroll;
  451. case attr::HLSLAllowUAVCondition:
  452. emitWarning("Unsupported allow_uav_condition attribute ignored.");
  453. break;
  454. default:
  455. emitError("Found unknown loop attribute.");
  456. }
  457. return spv::LoopControlMask::MaskNone;
  458. }
  459. void SPIRVEmitter::doDiscardStmt(const DiscardStmt *discardStmt) {
  460. assert(!theBuilder.isCurrentBasicBlockTerminated());
  461. theBuilder.createKill();
  462. // Some statements that alter the control flow (break, continue, return, and
  463. // discard), require creation of a new basic block to hold any statement that
  464. // may follow them.
  465. const uint32_t newBB = theBuilder.createBasicBlock();
  466. theBuilder.setInsertPoint(newBB);
  467. }
  468. void SPIRVEmitter::doDoStmt(const DoStmt *theDoStmt,
  469. llvm::ArrayRef<const Attr *> attrs) {
  470. // do-while loops are composed of:
  471. //
  472. // do {
  473. // <body>
  474. // } while(<check>);
  475. //
  476. // SPIR-V requires loops to have a merge basic block as well as a continue
  477. // basic block. Even though do-while loops do not have an explicit continue
  478. // block as in for-loops, we still do need to create a continue block.
  479. //
  480. // Since SPIR-V requires structured control flow, we need two more basic
  481. // blocks, <header> and <merge>. <header> is the block before control flow
  482. // diverges, and <merge> is the block where control flow subsequently
  483. // converges. The <check> can be performed in the <continue> basic block.
  484. // The final CFG should normally be like the following. Exceptions
  485. // will occur with non-local exits like loop breaks or early returns.
  486. //
  487. // +----------+
  488. // | header | <-----------------------------------+
  489. // +----------+ |
  490. // | | (true)
  491. // v |
  492. // +------+ +--------------------+ |
  493. // | body | ----> | continue (<check>) |-----------+
  494. // +------+ +--------------------+
  495. // |
  496. // | (false)
  497. // +-------+ |
  498. // | merge | <-------------+
  499. // +-------+
  500. //
  501. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  502. const spv::LoopControlMask loopControl =
  503. attrs.empty() ? spv::LoopControlMask::MaskNone
  504. : translateLoopAttribute(*attrs.front());
  505. // Create basic blocks
  506. const uint32_t headerBB = theBuilder.createBasicBlock("do_while.header");
  507. const uint32_t bodyBB = theBuilder.createBasicBlock("do_while.body");
  508. const uint32_t continueBB = theBuilder.createBasicBlock("do_while.continue");
  509. const uint32_t mergeBB = theBuilder.createBasicBlock("do_while.merge");
  510. // Make sure any continue statements branch to the continue block, and any
  511. // break statements branch to the merge block.
  512. continueStack.push(continueBB);
  513. breakStack.push(mergeBB);
  514. // Branch from the current insert point to the header block.
  515. theBuilder.createBranch(headerBB);
  516. theBuilder.addSuccessor(headerBB);
  517. // Process the <header> block
  518. // The header block must always branch to the body.
  519. theBuilder.setInsertPoint(headerBB);
  520. theBuilder.createBranch(bodyBB, mergeBB, continueBB, loopControl);
  521. theBuilder.addSuccessor(bodyBB);
  522. // The current basic block has OpLoopMerge instruction. We need to set its
  523. // continue and merge target.
  524. theBuilder.setContinueTarget(continueBB);
  525. theBuilder.setMergeTarget(mergeBB);
  526. // Process the <body> block
  527. theBuilder.setInsertPoint(bodyBB);
  528. if (const Stmt *body = theDoStmt->getBody()) {
  529. doStmt(body);
  530. }
  531. if (!theBuilder.isCurrentBasicBlockTerminated())
  532. theBuilder.createBranch(continueBB);
  533. theBuilder.addSuccessor(continueBB);
  534. // Process the <continue> block. The check for whether the loop should
  535. // continue lies in the continue block.
  536. // *NOTE*: There's a SPIR-V rule that when a conditional branch is to occur in
  537. // a continue block of a loop, there should be no OpSelectionMerge. Only an
  538. // OpBranchConditional must be specified.
  539. theBuilder.setInsertPoint(continueBB);
  540. uint32_t condition = 0;
  541. if (const Expr *check = theDoStmt->getCond()) {
  542. condition = doExpr(check);
  543. } else {
  544. condition = theBuilder.getConstantBool(true);
  545. }
  546. theBuilder.createConditionalBranch(condition, headerBB, mergeBB);
  547. theBuilder.addSuccessor(headerBB);
  548. theBuilder.addSuccessor(mergeBB);
  549. // Set insertion point to the <merge> block for subsequent statements
  550. theBuilder.setInsertPoint(mergeBB);
  551. // Done with the current scope's continue block and merge block.
  552. continueStack.pop();
  553. breakStack.pop();
  554. }
  555. void SPIRVEmitter::doContinueStmt(const ContinueStmt *continueStmt) {
  556. assert(!theBuilder.isCurrentBasicBlockTerminated());
  557. const uint32_t continueTargetBB = continueStack.top();
  558. theBuilder.createBranch(continueTargetBB);
  559. theBuilder.addSuccessor(continueTargetBB);
  560. // Some statements that alter the control flow (break, continue, return, and
  561. // discard), require creation of a new basic block to hold any statement that
  562. // may follow them. For example: StmtB and StmtC below are put inside a new
  563. // basic block which is unreachable.
  564. //
  565. // while (true) {
  566. // StmtA;
  567. // continue;
  568. // StmtB;
  569. // StmtC;
  570. // }
  571. const uint32_t newBB = theBuilder.createBasicBlock();
  572. theBuilder.setInsertPoint(newBB);
  573. }
  574. void SPIRVEmitter::doWhileStmt(const WhileStmt *whileStmt,
  575. llvm::ArrayRef<const Attr *> attrs) {
  576. // While loops are composed of:
  577. // while (<check>) { <body> }
  578. //
  579. // SPIR-V requires loops to have a merge basic block as well as a continue
  580. // basic block. Even though while loops do not have an explicit continue
  581. // block as in for-loops, we still do need to create a continue block.
  582. //
  583. // Since SPIR-V requires structured control flow, we need two more basic
  584. // blocks, <header> and <merge>. <header> is the block before control flow
  585. // diverges, and <merge> is the block where control flow subsequently
  586. // converges. The <check> block can take the responsibility of the <header>
  587. // block. The final CFG should normally be like the following. Exceptions
  588. // will occur with non-local exits like loop breaks or early returns.
  589. //
  590. // +----------+
  591. // | header | <------------------+
  592. // | (check) | |
  593. // +----------+ |
  594. // | |
  595. // +-------+-------+ |
  596. // | false | true |
  597. // | v |
  598. // | +------+ +------------------+
  599. // | | body | --> | continue (no-op) |
  600. // v +------+ +------------------+
  601. // +-------+
  602. // | merge |
  603. // +-------+
  604. //
  605. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  606. const spv::LoopControlMask loopControl =
  607. attrs.empty() ? spv::LoopControlMask::MaskNone
  608. : translateLoopAttribute(*attrs.front());
  609. // Create basic blocks
  610. const uint32_t checkBB = theBuilder.createBasicBlock("while.check");
  611. const uint32_t bodyBB = theBuilder.createBasicBlock("while.body");
  612. const uint32_t continueBB = theBuilder.createBasicBlock("while.continue");
  613. const uint32_t mergeBB = theBuilder.createBasicBlock("while.merge");
  614. // Make sure any continue statements branch to the continue block, and any
  615. // break statements branch to the merge block.
  616. continueStack.push(continueBB);
  617. breakStack.push(mergeBB);
  618. // Process the <check> block
  619. theBuilder.createBranch(checkBB);
  620. theBuilder.addSuccessor(checkBB);
  621. theBuilder.setInsertPoint(checkBB);
  622. // If we have:
  623. // while (int a = foo()) {...}
  624. // we should evaluate 'a' by calling 'foo()' every single time the check has
  625. // to occur.
  626. if (const auto *condVarDecl = whileStmt->getConditionVariableDeclStmt())
  627. doStmt(condVarDecl);
  628. uint32_t condition = 0;
  629. if (const Expr *check = whileStmt->getCond()) {
  630. condition = doExpr(check);
  631. } else {
  632. condition = theBuilder.getConstantBool(true);
  633. }
  634. theBuilder.createConditionalBranch(condition, bodyBB,
  635. /*false branch*/ mergeBB,
  636. /*merge*/ mergeBB, continueBB,
  637. spv::SelectionControlMask::MaskNone,
  638. loopControl);
  639. theBuilder.addSuccessor(bodyBB);
  640. theBuilder.addSuccessor(mergeBB);
  641. // The current basic block has OpLoopMerge instruction. We need to set its
  642. // continue and merge target.
  643. theBuilder.setContinueTarget(continueBB);
  644. theBuilder.setMergeTarget(mergeBB);
  645. // Process the <body> block
  646. theBuilder.setInsertPoint(bodyBB);
  647. if (const Stmt *body = whileStmt->getBody()) {
  648. doStmt(body);
  649. }
  650. if (!theBuilder.isCurrentBasicBlockTerminated())
  651. theBuilder.createBranch(continueBB);
  652. theBuilder.addSuccessor(continueBB);
  653. // Process the <continue> block. While loops do not have an explicit
  654. // continue block. The continue block just branches to the <check> block.
  655. theBuilder.setInsertPoint(continueBB);
  656. theBuilder.createBranch(checkBB);
  657. theBuilder.addSuccessor(checkBB);
  658. // Set insertion point to the <merge> block for subsequent statements
  659. theBuilder.setInsertPoint(mergeBB);
  660. // Done with the current scope's continue and merge blocks.
  661. continueStack.pop();
  662. breakStack.pop();
  663. }
  664. void SPIRVEmitter::doForStmt(const ForStmt *forStmt,
  665. llvm::ArrayRef<const Attr *> attrs) {
  666. // for loops are composed of:
  667. // for (<init>; <check>; <continue>) <body>
  668. //
  669. // To translate a for loop, we'll need to emit all <init> statements
  670. // in the current basic block, and then have separate basic blocks for
  671. // <check>, <continue>, and <body>. Besides, since SPIR-V requires
  672. // structured control flow, we need two more basic blocks, <header>
  673. // and <merge>. <header> is the block before control flow diverges,
  674. // while <merge> is the block where control flow subsequently converges.
  675. // The <check> block can take the responsibility of the <header> block.
  676. // The final CFG should normally be like the following. Exceptions will
  677. // occur with non-local exits like loop breaks or early returns.
  678. // +--------+
  679. // | init |
  680. // +--------+
  681. // |
  682. // v
  683. // +----------+
  684. // | header | <---------------+
  685. // | (check) | |
  686. // +----------+ |
  687. // | |
  688. // +-------+-------+ |
  689. // | false | true |
  690. // | v |
  691. // | +------+ +----------+
  692. // | | body | --> | continue |
  693. // v +------+ +----------+
  694. // +-------+
  695. // | merge |
  696. // +-------+
  697. //
  698. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  699. const spv::LoopControlMask loopControl =
  700. attrs.empty() ? spv::LoopControlMask::MaskNone
  701. : translateLoopAttribute(*attrs.front());
  702. // Create basic blocks
  703. const uint32_t checkBB = theBuilder.createBasicBlock("for.check");
  704. const uint32_t bodyBB = theBuilder.createBasicBlock("for.body");
  705. const uint32_t continueBB = theBuilder.createBasicBlock("for.continue");
  706. const uint32_t mergeBB = theBuilder.createBasicBlock("for.merge");
  707. // Make sure any continue statements branch to the continue block, and any
  708. // break statements branch to the merge block.
  709. continueStack.push(continueBB);
  710. breakStack.push(mergeBB);
  711. // Process the <init> block
  712. if (const Stmt *initStmt = forStmt->getInit()) {
  713. doStmt(initStmt);
  714. }
  715. theBuilder.createBranch(checkBB);
  716. theBuilder.addSuccessor(checkBB);
  717. // Process the <check> block
  718. theBuilder.setInsertPoint(checkBB);
  719. uint32_t condition;
  720. if (const Expr *check = forStmt->getCond()) {
  721. condition = doExpr(check);
  722. } else {
  723. condition = theBuilder.getConstantBool(true);
  724. }
  725. theBuilder.createConditionalBranch(condition, bodyBB,
  726. /*false branch*/ mergeBB,
  727. /*merge*/ mergeBB, continueBB,
  728. spv::SelectionControlMask::MaskNone,
  729. loopControl);
  730. theBuilder.addSuccessor(bodyBB);
  731. theBuilder.addSuccessor(mergeBB);
  732. // The current basic block has OpLoopMerge instruction. We need to set its
  733. // continue and merge target.
  734. theBuilder.setContinueTarget(continueBB);
  735. theBuilder.setMergeTarget(mergeBB);
  736. // Process the <body> block
  737. theBuilder.setInsertPoint(bodyBB);
  738. if (const Stmt *body = forStmt->getBody()) {
  739. doStmt(body);
  740. }
  741. if (!theBuilder.isCurrentBasicBlockTerminated())
  742. theBuilder.createBranch(continueBB);
  743. theBuilder.addSuccessor(continueBB);
  744. // Process the <continue> block
  745. theBuilder.setInsertPoint(continueBB);
  746. if (const Expr *cont = forStmt->getInc()) {
  747. doExpr(cont);
  748. }
  749. theBuilder.createBranch(checkBB); // <continue> should jump back to header
  750. theBuilder.addSuccessor(checkBB);
  751. // Set insertion point to the <merge> block for subsequent statements
  752. theBuilder.setInsertPoint(mergeBB);
  753. // Done with the current scope's continue block and merge block.
  754. continueStack.pop();
  755. breakStack.pop();
  756. }
  757. void SPIRVEmitter::doIfStmt(const IfStmt *ifStmt) {
  758. // if statements are composed of:
  759. // if (<check>) { <then> } else { <else> }
  760. //
  761. // To translate if statements, we'll need to emit the <check> expressions
  762. // in the current basic block, and then create separate basic blocks for
  763. // <then> and <else>. Additionally, we'll need a <merge> block as per
  764. // SPIR-V's structured control flow requirements. Depending whether there
  765. // exists the else branch, the final CFG should normally be like the
  766. // following. Exceptions will occur with non-local exits like loop breaks
  767. // or early returns.
  768. // +-------+ +-------+
  769. // | check | | check |
  770. // +-------+ +-------+
  771. // | |
  772. // +-------+-------+ +-----+-----+
  773. // | true | false | true | false
  774. // v v or v |
  775. // +------+ +------+ +------+ |
  776. // | then | | else | | then | |
  777. // +------+ +------+ +------+ |
  778. // | | | v
  779. // | +-------+ | | +-------+
  780. // +-> | merge | <-+ +---> | merge |
  781. // +-------+ +-------+
  782. { // Try to see if we can const-eval the condition
  783. bool condition = false;
  784. if (ifStmt->getCond()->EvaluateAsBooleanCondition(condition, astContext)) {
  785. if (condition) {
  786. doStmt(ifStmt->getThen());
  787. } else if (ifStmt->getElse()) {
  788. doStmt(ifStmt->getElse());
  789. }
  790. return;
  791. }
  792. }
  793. if (const auto *declStmt = ifStmt->getConditionVariableDeclStmt())
  794. doDeclStmt(declStmt);
  795. // First emit the instruction for evaluating the condition.
  796. const uint32_t condition = doExpr(ifStmt->getCond());
  797. // Then we need to emit the instruction for the conditional branch.
  798. // We'll need the <label-id> for the then/else/merge block to do so.
  799. const bool hasElse = ifStmt->getElse() != nullptr;
  800. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  801. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  802. const uint32_t elseBB =
  803. hasElse ? theBuilder.createBasicBlock("if.false") : mergeBB;
  804. // Create the branch instruction. This will end the current basic block.
  805. theBuilder.createConditionalBranch(condition, thenBB, elseBB, mergeBB);
  806. theBuilder.addSuccessor(thenBB);
  807. theBuilder.addSuccessor(elseBB);
  808. // The current basic block has the OpSelectionMerge instruction. We need
  809. // to record its merge target.
  810. theBuilder.setMergeTarget(mergeBB);
  811. // Handle the then branch
  812. theBuilder.setInsertPoint(thenBB);
  813. doStmt(ifStmt->getThen());
  814. if (!theBuilder.isCurrentBasicBlockTerminated())
  815. theBuilder.createBranch(mergeBB);
  816. theBuilder.addSuccessor(mergeBB);
  817. // Handle the else branch (if exists)
  818. if (hasElse) {
  819. theBuilder.setInsertPoint(elseBB);
  820. doStmt(ifStmt->getElse());
  821. if (!theBuilder.isCurrentBasicBlockTerminated())
  822. theBuilder.createBranch(mergeBB);
  823. theBuilder.addSuccessor(mergeBB);
  824. }
  825. // From now on, we'll emit instructions into the merge block.
  826. theBuilder.setInsertPoint(mergeBB);
  827. }
  828. void SPIRVEmitter::doReturnStmt(const ReturnStmt *stmt) {
  829. if (const auto *retVal = stmt->getRetValue())
  830. theBuilder.createReturnValue(doExpr(retVal));
  831. else
  832. theBuilder.createReturn();
  833. // Some statements that alter the control flow (break, continue, return, and
  834. // discard), require creation of a new basic block to hold any statement that
  835. // may follow them. In this case, the newly created basic block will contain
  836. // any statement that may come after an early return.
  837. const uint32_t newBB = theBuilder.createBasicBlock();
  838. theBuilder.setInsertPoint(newBB);
  839. }
  840. void SPIRVEmitter::doBreakStmt(const BreakStmt *breakStmt) {
  841. assert(!theBuilder.isCurrentBasicBlockTerminated());
  842. uint32_t breakTargetBB = breakStack.top();
  843. theBuilder.addSuccessor(breakTargetBB);
  844. theBuilder.createBranch(breakTargetBB);
  845. // Some statements that alter the control flow (break, continue, return, and
  846. // discard), require creation of a new basic block to hold any statement that
  847. // may follow them. For example: StmtB and StmtC below are put inside a new
  848. // basic block which is unreachable.
  849. //
  850. // while (true) {
  851. // StmtA;
  852. // break;
  853. // StmtB;
  854. // StmtC;
  855. // }
  856. const uint32_t newBB = theBuilder.createBasicBlock();
  857. theBuilder.setInsertPoint(newBB);
  858. }
  859. void SPIRVEmitter::doSwitchStmt(const SwitchStmt *switchStmt,
  860. llvm::ArrayRef<const Attr *> attrs) {
  861. // Switch statements are composed of:
  862. // switch (<condition variable>) {
  863. // <CaseStmt>
  864. // <CaseStmt>
  865. // <CaseStmt>
  866. // <DefaultStmt> (optional)
  867. // }
  868. //
  869. // +-------+
  870. // | check |
  871. // +-------+
  872. // |
  873. // +-------+-------+----------------+---------------+
  874. // | 1 | 2 | 3 | (others)
  875. // v v v v
  876. // +-------+ +-------------+ +-------+ +------------+
  877. // | case1 | | case2 | | case3 | ... | default |
  878. // | | |(fallthrough)|---->| | | (optional) |
  879. // +-------+ |+------------+ +-------+ +------------+
  880. // | | |
  881. // | | |
  882. // | +-------+ | |
  883. // | | | <--------------------+ |
  884. // +-> | merge | |
  885. // | | <-------------------------------------+
  886. // +-------+
  887. // If no attributes are given, or if "forcecase" attribute was provided,
  888. // we'll do our best to use OpSwitch if possible.
  889. // If any of the cases compares to a variable (rather than an integer
  890. // literal), we cannot use OpSwitch because OpSwitch expects literal
  891. // numbers as parameters.
  892. const bool isAttrForceCase =
  893. !attrs.empty() && attrs.front()->getKind() == attr::HLSLForceCase;
  894. const bool canUseSpirvOpSwitch =
  895. (attrs.empty() || isAttrForceCase) &&
  896. allSwitchCasesAreIntegerLiterals(switchStmt->getBody());
  897. if (isAttrForceCase && !canUseSpirvOpSwitch)
  898. emitWarning("Ignored 'forcecase' attribute for the switch statement "
  899. "since one or more case values are not integer literals.");
  900. if (canUseSpirvOpSwitch)
  901. processSwitchStmtUsingSpirvOpSwitch(switchStmt);
  902. else
  903. processSwitchStmtUsingIfStmts(switchStmt);
  904. }
  905. uint32_t SPIRVEmitter::doArraySubscriptExpr(const ArraySubscriptExpr *expr) {
  906. llvm::SmallVector<uint32_t, 4> indices;
  907. const auto *base = collectArrayStructIndices(expr, &indices);
  908. const uint32_t ptrType =
  909. theBuilder.getPointerType(typeTranslator.translateType(expr->getType()),
  910. declIdMapper.resolveStorageClass(base));
  911. return theBuilder.createAccessChain(ptrType, doExpr(base), indices);
  912. }
  913. uint32_t SPIRVEmitter::doBinaryOperator(const BinaryOperator *expr) {
  914. const auto opcode = expr->getOpcode();
  915. // Handle assignment first since we need to evaluate rhs before lhs.
  916. // For other binary operations, we need to evaluate lhs before rhs.
  917. if (opcode == BO_Assign)
  918. return processAssignment(expr->getLHS(), doExpr(expr->getRHS()), false);
  919. // Try to optimize floatMxN * float and floatN * float case
  920. if (opcode == BO_Mul) {
  921. if (const uint32_t result = tryToGenFloatMatrixScale(expr))
  922. return result;
  923. if (const uint32_t result = tryToGenFloatVectorScale(expr))
  924. return result;
  925. }
  926. const uint32_t resultType = typeTranslator.translateType(expr->getType());
  927. return processBinaryOp(expr->getLHS(), expr->getRHS(), opcode, resultType);
  928. }
  929. uint32_t SPIRVEmitter::doCallExpr(const CallExpr *callExpr) {
  930. if (const auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(callExpr))
  931. return doCXXOperatorCallExpr(operatorCall);
  932. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr))
  933. return doCXXMemberCallExpr(memberCall);
  934. const FunctionDecl *callee = callExpr->getDirectCallee();
  935. // Intrinsic functions such as 'dot' or 'mul'
  936. if (hlsl::IsIntrinsicOp(callee)) {
  937. return processIntrinsicCallExpr(callExpr);
  938. }
  939. if (callee) {
  940. const auto numParams = callee->getNumParams();
  941. llvm::SmallVector<uint32_t, 4> params;
  942. llvm::SmallVector<uint32_t, 4> args;
  943. // Evaluate parameters
  944. for (uint32_t i = 0; i < numParams; ++i) {
  945. const auto *arg = callExpr->getArg(i);
  946. const auto *param = callee->getParamDecl(i);
  947. // We need to create variables for holding the values to be used as
  948. // arguments. The variables themselves are of pointer types.
  949. const uint32_t varType = typeTranslator.translateType(arg->getType());
  950. const std::string varName = "param.var." + param->getNameAsString();
  951. const uint32_t tempVarId = theBuilder.addFnVar(varType, varName);
  952. params.push_back(tempVarId);
  953. args.push_back(doExpr(arg));
  954. if (param->getAttr<HLSLOutAttr>() || param->getAttr<HLSLInOutAttr>()) {
  955. // The current parameter is marked as out/inout. The argument then is
  956. // essentially passed in by reference. We need to load the value
  957. // explicitly here since the AST won't inject LValueToRValue implicit
  958. // cast for this case.
  959. const uint32_t value = theBuilder.createLoad(varType, args.back());
  960. theBuilder.createStore(tempVarId, value);
  961. } else {
  962. theBuilder.createStore(tempVarId, args.back());
  963. }
  964. }
  965. // Push the callee into the work queue if it is not there.
  966. if (!workQueue.count(callee)) {
  967. workQueue.insert(callee);
  968. }
  969. const uint32_t retType = typeTranslator.translateType(callExpr->getType());
  970. // Get or forward declare the function <result-id>
  971. const uint32_t funcId = declIdMapper.getOrRegisterFnResultId(callee);
  972. const uint32_t retVal =
  973. theBuilder.createFunctionCall(retType, funcId, params);
  974. // Go through all parameters and write those marked as out/inout
  975. for (uint32_t i = 0; i < numParams; ++i) {
  976. const auto *param = callee->getParamDecl(i);
  977. if (param->getAttr<HLSLOutAttr>() || param->getAttr<HLSLInOutAttr>()) {
  978. const uint32_t typeId = typeTranslator.translateType(param->getType());
  979. const uint32_t value = theBuilder.createLoad(typeId, params[i]);
  980. theBuilder.createStore(args[i], value);
  981. }
  982. }
  983. return retVal;
  984. }
  985. emitError("calling non-function unimplemented");
  986. return 0;
  987. }
  988. uint32_t SPIRVEmitter::doCastExpr(const CastExpr *expr) {
  989. const Expr *subExpr = expr->getSubExpr();
  990. const QualType toType = expr->getType();
  991. switch (expr->getCastKind()) {
  992. case CastKind::CK_LValueToRValue: {
  993. const uint32_t fromValue = doExpr(subExpr);
  994. if (isVectorShuffle(subExpr) || isa<ExtMatrixElementExpr>(subExpr) ||
  995. isBufferIndexing(dyn_cast<CXXOperatorCallExpr>(subExpr))) {
  996. // By reaching here, it means the vector/matrix/Buffer/RWBuffer element
  997. // accessing operation is an lvalue. For vector element accessing, if we
  998. // generated a vector shuffle for it and trying to use it as a rvalue, we
  999. // cannot do the load here as normal. Need the upper nodes in the AST tree
  1000. // to handle it properly. For matrix element accessing, load should have
  1001. // already happened after creating access chain for each element.
  1002. // For (RW)Buffer element accessing, load should have already happened
  1003. // using OpImageFetch.
  1004. return fromValue;
  1005. }
  1006. // Using lvalue as rvalue means we need to OpLoad the contents from
  1007. // the parameter/variable first.
  1008. const uint32_t resultType = typeTranslator.translateType(toType);
  1009. return theBuilder.createLoad(resultType, fromValue);
  1010. }
  1011. case CastKind::CK_NoOp:
  1012. return doExpr(subExpr);
  1013. case CastKind::CK_IntegralCast:
  1014. case CastKind::CK_FloatingToIntegral:
  1015. case CastKind::CK_HLSLCC_IntegralCast:
  1016. case CastKind::CK_HLSLCC_FloatingToIntegral: {
  1017. // Integer literals in the AST are represented using 64bit APInt
  1018. // themselves and then implicitly casted into the expected bitwidth.
  1019. // We need special treatment of integer literals here because generating
  1020. // a 64bit constant and then explicit casting in SPIR-V requires Int64
  1021. // capability. We should avoid introducing unnecessary capabilities to
  1022. // our best.
  1023. llvm::APSInt intValue;
  1024. if (expr->EvaluateAsInt(intValue, astContext, Expr::SE_NoSideEffects)) {
  1025. return translateAPInt(intValue, toType);
  1026. }
  1027. return castToInt(doExpr(subExpr), subExpr->getType(), toType);
  1028. }
  1029. case CastKind::CK_FloatingCast:
  1030. case CastKind::CK_IntegralToFloating:
  1031. case CastKind::CK_HLSLCC_FloatingCast:
  1032. case CastKind::CK_HLSLCC_IntegralToFloating: {
  1033. // First try to see if we can do constant folding for floating point
  1034. // numbers like what we are doing for integers in the above.
  1035. Expr::EvalResult evalResult;
  1036. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  1037. !evalResult.HasSideEffects) {
  1038. return translateAPFloat(evalResult.Val.getFloat(), toType);
  1039. }
  1040. return castToFloat(doExpr(subExpr), subExpr->getType(), toType);
  1041. }
  1042. case CastKind::CK_IntegralToBoolean:
  1043. case CastKind::CK_FloatingToBoolean:
  1044. case CastKind::CK_HLSLCC_IntegralToBoolean:
  1045. case CastKind::CK_HLSLCC_FloatingToBoolean: {
  1046. // First try to see if we can do constant folding.
  1047. bool boolVal;
  1048. if (!expr->HasSideEffects(astContext) &&
  1049. expr->EvaluateAsBooleanCondition(boolVal, astContext)) {
  1050. return theBuilder.getConstantBool(boolVal);
  1051. }
  1052. return castToBool(doExpr(subExpr), subExpr->getType(), toType);
  1053. }
  1054. case CastKind::CK_HLSLVectorSplat: {
  1055. const size_t size = hlsl::GetHLSLVecSize(expr->getType());
  1056. return createVectorSplat(subExpr, size);
  1057. }
  1058. case CastKind::CK_HLSLVectorTruncationCast: {
  1059. const uint32_t toVecTypeId = typeTranslator.translateType(toType);
  1060. const uint32_t elemTypeId =
  1061. typeTranslator.translateType(hlsl::GetHLSLVecElementType(toType));
  1062. const auto toSize = hlsl::GetHLSLVecSize(toType);
  1063. const uint32_t composite = doExpr(subExpr);
  1064. llvm::SmallVector<uint32_t, 4> elements;
  1065. for (uint32_t i = 0; i < toSize; ++i) {
  1066. elements.push_back(
  1067. theBuilder.createCompositeExtract(elemTypeId, composite, {i}));
  1068. }
  1069. if (toSize == 1) {
  1070. return elements.front();
  1071. }
  1072. return theBuilder.createCompositeConstruct(toVecTypeId, elements);
  1073. }
  1074. case CastKind::CK_HLSLVectorToScalarCast: {
  1075. // The underlying should already be a vector of size 1.
  1076. assert(hlsl::GetHLSLVecSize(subExpr->getType()) == 1);
  1077. return doExpr(subExpr);
  1078. }
  1079. case CastKind::CK_HLSLVectorToMatrixCast: {
  1080. // The target type should already be a 1xN matrix type.
  1081. assert(TypeTranslator::is1xNMatrix(toType));
  1082. return doExpr(subExpr);
  1083. }
  1084. case CastKind::CK_HLSLMatrixSplat: {
  1085. // From scalar to matrix
  1086. uint32_t rowCount = 0, colCount = 0;
  1087. hlsl::GetHLSLMatRowColCount(toType, rowCount, colCount);
  1088. // Handle degenerated cases first
  1089. if (rowCount == 1 && colCount == 1)
  1090. return doExpr(subExpr);
  1091. if (colCount == 1)
  1092. return createVectorSplat(subExpr, rowCount);
  1093. bool isConstVec = false;
  1094. const uint32_t vecSplat = createVectorSplat(subExpr, colCount, &isConstVec);
  1095. if (rowCount == 1)
  1096. return vecSplat;
  1097. const uint32_t matType = typeTranslator.translateType(toType);
  1098. llvm::SmallVector<uint32_t, 4> vectors(size_t(rowCount), vecSplat);
  1099. if (isConstVec) {
  1100. return theBuilder.getConstantComposite(matType, vectors);
  1101. } else {
  1102. return theBuilder.createCompositeConstruct(matType, vectors);
  1103. }
  1104. }
  1105. case CastKind::CK_HLSLMatrixToScalarCast: {
  1106. // The underlying should already be a matrix of 1x1.
  1107. assert(TypeTranslator::is1x1Matrix(subExpr->getType()));
  1108. return doExpr(subExpr);
  1109. }
  1110. case CastKind::CK_HLSLMatrixToVectorCast: {
  1111. // The underlying should already be a matrix of 1xN.
  1112. assert(TypeTranslator::is1xNMatrix(subExpr->getType()) ||
  1113. TypeTranslator::isMx1Matrix(subExpr->getType()));
  1114. return doExpr(subExpr);
  1115. }
  1116. case CastKind::CK_FunctionToPointerDecay:
  1117. // Just need to return the function id
  1118. return doExpr(subExpr);
  1119. default:
  1120. emitError("ImplictCast Kind '%0' is not supported yet.")
  1121. << expr->getCastKindName();
  1122. expr->dump();
  1123. return 0;
  1124. }
  1125. }
  1126. uint32_t
  1127. SPIRVEmitter::doCompoundAssignOperator(const CompoundAssignOperator *expr) {
  1128. const auto opcode = expr->getOpcode();
  1129. // Try to optimize floatMxN *= float and floatN *= float case
  1130. if (opcode == BO_MulAssign) {
  1131. if (const uint32_t result = tryToGenFloatMatrixScale(expr))
  1132. return result;
  1133. if (const uint32_t result = tryToGenFloatVectorScale(expr))
  1134. return result;
  1135. }
  1136. const auto *rhs = expr->getRHS();
  1137. const auto *lhs = expr->getLHS();
  1138. uint32_t lhsPtr = 0;
  1139. const uint32_t resultType = typeTranslator.translateType(expr->getType());
  1140. const uint32_t result =
  1141. processBinaryOp(lhs, rhs, opcode, resultType, &lhsPtr);
  1142. return processAssignment(lhs, result, true, lhsPtr);
  1143. }
  1144. uint32_t SPIRVEmitter::doConditionalOperator(const ConditionalOperator *expr) {
  1145. // According to HLSL doc, all sides of the ?: expression are always
  1146. // evaluated.
  1147. const uint32_t type = typeTranslator.translateType(expr->getType());
  1148. const uint32_t condition = doExpr(expr->getCond());
  1149. const uint32_t trueBranch = doExpr(expr->getTrueExpr());
  1150. const uint32_t falseBranch = doExpr(expr->getFalseExpr());
  1151. return theBuilder.createSelect(type, condition, trueBranch, falseBranch);
  1152. }
  1153. uint32_t SPIRVEmitter::processBufferTextureLoad(const Expr *object,
  1154. const Expr *location,
  1155. uint32_t constOffset,
  1156. uint32_t varOffset) {
  1157. // Loading for Buffer and RWBuffer translates to an OpImageFetch.
  1158. // The result type of an OpImageFetch must be a vec4 of float or int.
  1159. const auto type = object->getType();
  1160. assert(TypeTranslator::isBuffer(type) || TypeTranslator::isRWBuffer(type) ||
  1161. TypeTranslator::isTexture(type));
  1162. const bool doFetch =
  1163. TypeTranslator::isBuffer(type) || TypeTranslator::isTexture(type);
  1164. const uint32_t objectId = loadIfGLValue(object);
  1165. const uint32_t locationId = doExpr(location);
  1166. // For Buffers/RWBuffers, the location is just an int, which should be used as
  1167. // the coordinate argument. Textures require an additional processing.
  1168. uint32_t coordinate = locationId, lod = 0;
  1169. if (TypeTranslator::isTexture(type)) {
  1170. // The location parameter is a vector that consists of both the coordinate
  1171. // and the mipmap level (via the last vector element). We need to split it
  1172. // here since the OpImageFetch SPIR-V instruction encodes them as separate
  1173. // arguments.
  1174. splitVecLastElement(location->getType(), locationId, &coordinate, &lod);
  1175. }
  1176. const auto sampledType = hlsl::GetHLSLResourceResultType(type);
  1177. QualType elemType = sampledType;
  1178. uint32_t elemCount = 1;
  1179. uint32_t elemTypeId = 0;
  1180. (void)TypeTranslator::isVectorType(sampledType, &elemType, &elemCount);
  1181. if (elemType->isFloatingType()) {
  1182. elemTypeId = theBuilder.getFloat32Type();
  1183. } else if (elemType->isSignedIntegerType()) {
  1184. elemTypeId = theBuilder.getInt32Type();
  1185. } else if (elemType->isUnsignedIntegerType()) {
  1186. elemTypeId = theBuilder.getUint32Type();
  1187. } else {
  1188. emitError("Unimplemented Buffer type");
  1189. return 0;
  1190. }
  1191. const uint32_t resultTypeId =
  1192. elemCount == 1 ? elemTypeId
  1193. : theBuilder.getVecType(elemTypeId, elemCount);
  1194. // Always need to fetch 4 elements.
  1195. const uint32_t fetchTypeId = theBuilder.getVecType(elemTypeId, 4u);
  1196. const uint32_t texel = theBuilder.createImageFetchOrRead(
  1197. doFetch, fetchTypeId, objectId, coordinate, lod, constOffset, varOffset);
  1198. // For the case of buffer elements being vec4, there's no need for extraction
  1199. // and composition.
  1200. switch (elemCount) {
  1201. case 1:
  1202. return theBuilder.createCompositeExtract(elemTypeId, texel, {0});
  1203. case 2:
  1204. return theBuilder.createVectorShuffle(resultTypeId, texel, texel, {0, 1});
  1205. case 3:
  1206. return theBuilder.createVectorShuffle(resultTypeId, texel, texel,
  1207. {0, 1, 2});
  1208. case 4:
  1209. return texel;
  1210. }
  1211. llvm_unreachable("Element count of a vector must be 1, 2, 3, or 4.");
  1212. }
  1213. uint32_t SPIRVEmitter::processByteAddressBufferLoadStore(
  1214. const CXXMemberCallExpr *expr, uint32_t numWords, bool doStore) {
  1215. uint32_t resultId = 0;
  1216. const auto object = expr->getImplicitObjectArgument();
  1217. const auto type = object->getType();
  1218. const uint32_t objectId = doExpr(object);
  1219. assert(numWords >= 1 && numWords <= 4);
  1220. if (doStore) {
  1221. assert(typeTranslator.isRWByteAddressBuffer(type));
  1222. assert(expr->getNumArgs() == 2);
  1223. } else {
  1224. assert(typeTranslator.isRWByteAddressBuffer(type) ||
  1225. typeTranslator.isByteAddressBuffer(type));
  1226. if (expr->getNumArgs() == 2) {
  1227. emitError("Load(in Address, out Status) has not been implemented for "
  1228. "(RW)ByteAddressBuffer yet.");
  1229. return 0;
  1230. }
  1231. }
  1232. const Expr *addressExpr = expr->getArg(0);
  1233. const uint32_t byteAddress = doExpr(addressExpr);
  1234. const uint32_t addressTypeId =
  1235. typeTranslator.translateType(addressExpr->getType());
  1236. // Do a OpShiftRightLogical by 2 (divide by 4 to get aligned memory
  1237. // access). The AST always casts the address to unsinged integer, so shift
  1238. // by unsinged integer 2.
  1239. const uint32_t constUint2 = theBuilder.getConstantUint32(2);
  1240. const uint32_t address = theBuilder.createBinaryOp(
  1241. spv::Op::OpShiftRightLogical, addressTypeId, byteAddress, constUint2);
  1242. // Perform access chain into the RWByteAddressBuffer.
  1243. // First index must be zero (member 0 of the struct is a
  1244. // runtimeArray). The second index passed to OpAccessChain should be
  1245. // the address.
  1246. const uint32_t uintTypeId = theBuilder.getUint32Type();
  1247. const uint32_t ptrType = theBuilder.getPointerType(
  1248. uintTypeId, declIdMapper.resolveStorageClass(object));
  1249. const uint32_t constUint0 = theBuilder.getConstantUint32(0);
  1250. if (doStore) {
  1251. const uint32_t valuesId = doExpr(expr->getArg(1));
  1252. uint32_t curStoreAddress = address;
  1253. for (uint32_t wordCounter = 0; wordCounter < numWords; ++wordCounter) {
  1254. // Extract a 32-bit word from the input.
  1255. const uint32_t curValue = numWords == 1
  1256. ? valuesId
  1257. : theBuilder.createCompositeExtract(
  1258. uintTypeId, valuesId, {wordCounter});
  1259. // Update the output address if necessary.
  1260. if (wordCounter > 0) {
  1261. const uint32_t offset = theBuilder.getConstantUint32(wordCounter);
  1262. curStoreAddress = theBuilder.createBinaryOp(
  1263. spv::Op::OpIAdd, addressTypeId, address, offset);
  1264. }
  1265. // Store the word to the right address at the output.
  1266. const uint32_t storePtr = theBuilder.createAccessChain(
  1267. ptrType, objectId, {constUint0, curStoreAddress});
  1268. theBuilder.createStore(storePtr, curValue);
  1269. }
  1270. } else {
  1271. uint32_t loadPtr =
  1272. theBuilder.createAccessChain(ptrType, objectId, {constUint0, address});
  1273. resultId = theBuilder.createLoad(uintTypeId, loadPtr);
  1274. if (numWords > 1) {
  1275. // Load word 2, 3, and 4 where necessary. Use OpCompositeConstruct to
  1276. // return a vector result.
  1277. llvm::SmallVector<uint32_t, 4> values;
  1278. values.push_back(resultId);
  1279. for (uint32_t wordCounter = 2; wordCounter <= numWords; ++wordCounter) {
  1280. const uint32_t offset = theBuilder.getConstantUint32(wordCounter - 1);
  1281. const uint32_t newAddress = theBuilder.createBinaryOp(
  1282. spv::Op::OpIAdd, addressTypeId, address, offset);
  1283. loadPtr = theBuilder.createAccessChain(ptrType, objectId,
  1284. {constUint0, newAddress});
  1285. values.push_back(theBuilder.createLoad(uintTypeId, loadPtr));
  1286. }
  1287. const uint32_t resultType =
  1288. theBuilder.getVecType(addressTypeId, numWords);
  1289. resultId = theBuilder.createCompositeConstruct(resultType, values);
  1290. }
  1291. }
  1292. return resultId;
  1293. }
  1294. uint32_t
  1295. SPIRVEmitter::processStructuredBufferLoad(const CXXMemberCallExpr *expr) {
  1296. if (expr->getNumArgs() == 2) {
  1297. emitError("Load(int, int) unimplemented for (RW)StructuredBuffer");
  1298. return 0;
  1299. }
  1300. const auto *buffer = expr->getImplicitObjectArgument();
  1301. const QualType structType =
  1302. hlsl::GetHLSLResourceResultType(buffer->getType());
  1303. const uint32_t ptrType = theBuilder.getPointerType(
  1304. typeTranslator.translateType(structType, LayoutRule::GLSLStd430),
  1305. declIdMapper.resolveStorageClass(buffer));
  1306. const uint32_t zero = theBuilder.getConstantInt32(0);
  1307. const uint32_t index = doExpr(expr->getArg(0));
  1308. return theBuilder.createAccessChain(ptrType, doExpr(buffer), {zero, index});
  1309. }
  1310. uint32_t SPIRVEmitter::doCXXMemberCallExpr(const CXXMemberCallExpr *expr) {
  1311. using namespace hlsl;
  1312. const FunctionDecl *callee = expr->getDirectCallee();
  1313. const auto retType = typeTranslator.translateType(callee->getReturnType());
  1314. // Handles the offset argument. If there exists an offset argument, writes the
  1315. // <result-id> to either *constOffset or *varOffset, depending on the
  1316. // constantness of the offset.
  1317. const auto handleOffset = [this](const CXXMemberCallExpr *expr,
  1318. uint32_t index, uint32_t *constOffset,
  1319. uint32_t *varOffset) {
  1320. *constOffset = *varOffset = 0; // Initialize both first
  1321. if (expr->getNumArgs() == index + 1) { // Has offset argument
  1322. if (*constOffset = tryToEvaluateAsConst(expr->getArg(index)))
  1323. return; // Constant offset
  1324. else
  1325. *varOffset = doExpr(expr->getArg(index));
  1326. }
  1327. };
  1328. llvm::StringRef group;
  1329. uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
  1330. if (GetIntrinsicOp(callee, opcode, group)) {
  1331. switch (static_cast<IntrinsicOp>(opcode)) {
  1332. case IntrinsicOp::MOP_Sample:
  1333. case IntrinsicOp::MOP_Gather: {
  1334. // Signatures:
  1335. // DXGI_FORMAT Object.Sample(sampler_state S,
  1336. // float Location
  1337. // [, int Offset]);
  1338. //
  1339. // <Template Type>4 Object.Gather(sampler_state S,
  1340. // float2|3|4 Location
  1341. // [, int2 Offset]);
  1342. const auto *imageExpr = expr->getImplicitObjectArgument();
  1343. const uint32_t imageType =
  1344. typeTranslator.translateType(imageExpr->getType());
  1345. const uint32_t image = loadIfGLValue(imageExpr);
  1346. const uint32_t sampler = doExpr(expr->getArg(0));
  1347. const uint32_t coordinate = doExpr(expr->getArg(1));
  1348. // .Sample()/.Gather() has a third optional paramter for offset.
  1349. uint32_t constOffset = 0, varOffset = 0;
  1350. handleOffset(expr, 2, &constOffset, &varOffset);
  1351. if (opcode == static_cast<uint32_t>(IntrinsicOp::MOP_Sample)) {
  1352. return theBuilder.createImageSample(
  1353. retType, imageType, image, sampler, coordinate, /*bias*/ 0,
  1354. /*lod*/ 0, std::make_pair(0, 0), constOffset, varOffset);
  1355. } else {
  1356. return theBuilder.createImageGather(
  1357. retType, imageType, image, sampler, coordinate,
  1358. // .Gather() doc says we return four components of red data.
  1359. theBuilder.getConstantInt32(0), constOffset, varOffset);
  1360. }
  1361. }
  1362. case IntrinsicOp::MOP_SampleBias:
  1363. case IntrinsicOp::MOP_SampleLevel: {
  1364. // Signatures:
  1365. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  1366. // float Location,
  1367. // float Bias
  1368. // [, int Offset]);
  1369. //
  1370. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  1371. // float Location,
  1372. // float LOD
  1373. // [, int Offset]);
  1374. const auto *imageExpr = expr->getImplicitObjectArgument();
  1375. const uint32_t imageType =
  1376. typeTranslator.translateType(imageExpr->getType());
  1377. const uint32_t image = loadIfGLValue(imageExpr);
  1378. const uint32_t sampler = doExpr(expr->getArg(0));
  1379. const uint32_t coordinate = doExpr(expr->getArg(1));
  1380. uint32_t lod = 0;
  1381. uint32_t bias = 0;
  1382. if (opcode == static_cast<uint32_t>(IntrinsicOp::MOP_SampleBias)) {
  1383. bias = doExpr(expr->getArg(2));
  1384. } else {
  1385. lod = doExpr(expr->getArg(2));
  1386. }
  1387. // .Bias()/.SampleLevel() has a fourth optional paramter for offset.
  1388. uint32_t constOffset = 0, varOffset = 0;
  1389. handleOffset(expr, 3, &constOffset, &varOffset);
  1390. return theBuilder.createImageSample(
  1391. retType, imageType, image, sampler, coordinate, bias, lod,
  1392. std::make_pair(0, 0), constOffset, varOffset);
  1393. }
  1394. case IntrinsicOp::MOP_SampleGrad: {
  1395. // Signature:
  1396. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  1397. // float Location,
  1398. // float DDX,
  1399. // float DDY
  1400. // [, int Offset]);
  1401. const auto *imageExpr = expr->getImplicitObjectArgument();
  1402. const uint32_t imageType =
  1403. typeTranslator.translateType(imageExpr->getType());
  1404. const uint32_t image = loadIfGLValue(imageExpr);
  1405. const uint32_t sampler = doExpr(expr->getArg(0));
  1406. const uint32_t coordinate = doExpr(expr->getArg(1));
  1407. const uint32_t ddx = doExpr(expr->getArg(2));
  1408. const uint32_t ddy = doExpr(expr->getArg(3));
  1409. // .SampleGrad() has a fifth optional paramter for offset.
  1410. uint32_t constOffset = 0, varOffset = 0;
  1411. handleOffset(expr, 4, &constOffset, &varOffset);
  1412. return theBuilder.createImageSample(
  1413. retType, imageType, image, sampler, coordinate, /*bias*/ 0, /*lod*/ 0,
  1414. std::make_pair(ddx, ddy), constOffset, varOffset);
  1415. }
  1416. case IntrinsicOp::MOP_Load: {
  1417. // Signature:
  1418. // ret Object.Load(int Location
  1419. // [, int SampleIndex,]
  1420. // [, int Offset]);
  1421. // SampleIndex is only available when the Object is of Texture2DMS or
  1422. // Texture2DMSArray types. Under those cases, Offset will be the third
  1423. // parameter. Otherwise, Offset should be the second parameter.
  1424. if (expr->getNumArgs() == 3) {
  1425. emitError("Texture2DMS[Array].Load() not implemented yet");
  1426. return 0;
  1427. }
  1428. const auto *object = expr->getImplicitObjectArgument();
  1429. const auto *location = expr->getArg(0);
  1430. const auto objectType = object->getType();
  1431. if (typeTranslator.isRWByteAddressBuffer(objectType) ||
  1432. typeTranslator.isByteAddressBuffer(objectType))
  1433. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ false);
  1434. if (isStructuredBuffer(objectType))
  1435. return processStructuredBufferLoad(expr);
  1436. if (TypeTranslator::isBuffer(objectType) ||
  1437. TypeTranslator::isRWBuffer(objectType))
  1438. return processBufferTextureLoad(object, location);
  1439. if (TypeTranslator::isTexture(objectType)) {
  1440. // .Load() has a second optional paramter for offset.
  1441. uint32_t constOffset = 0, varOffset = 0;
  1442. handleOffset(expr, 1, &constOffset, &varOffset);
  1443. return processBufferTextureLoad(object, location, constOffset,
  1444. varOffset);
  1445. }
  1446. emitError("Load() is not implemented for the given object type.");
  1447. return 0;
  1448. }
  1449. case IntrinsicOp::MOP_Load2: {
  1450. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ false);
  1451. }
  1452. case IntrinsicOp::MOP_Load3: {
  1453. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ false);
  1454. }
  1455. case IntrinsicOp::MOP_Load4: {
  1456. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ false);
  1457. }
  1458. case IntrinsicOp::MOP_Store: {
  1459. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ true);
  1460. }
  1461. case IntrinsicOp::MOP_Store2: {
  1462. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ true);
  1463. }
  1464. case IntrinsicOp::MOP_Store3: {
  1465. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ true);
  1466. }
  1467. case IntrinsicOp::MOP_Store4: {
  1468. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ true);
  1469. }
  1470. default:
  1471. emitError("HLSL intrinsic member call unimplemented: %0")
  1472. << callee->getName();
  1473. return 0;
  1474. }
  1475. } else {
  1476. emitError("C++ member function call unimplemented: %0")
  1477. << callee->getName();
  1478. return 0;
  1479. }
  1480. }
  1481. uint32_t SPIRVEmitter::doCXXOperatorCallExpr(const CXXOperatorCallExpr *expr) {
  1482. { // Handle Buffer/RWBuffer indexing
  1483. const Expr *baseExpr = nullptr;
  1484. const Expr *indexExpr = nullptr;
  1485. if (isBufferIndexing(expr, &baseExpr, &indexExpr)) {
  1486. return processBufferTextureLoad(baseExpr, indexExpr);
  1487. }
  1488. }
  1489. llvm::SmallVector<uint32_t, 4> indices;
  1490. const Expr *baseExpr = collectArrayStructIndices(expr, &indices);
  1491. uint32_t base = doExpr(baseExpr);
  1492. if (indices.empty())
  1493. return base; // For indexing into size-1 vectors and 1xN matrices
  1494. // If we are indexing into a rvalue, to use OpAccessChain, we first need
  1495. // to create a local variable to hold the rvalue.
  1496. //
  1497. // TODO: We can optimize the codegen by emitting OpCompositeExtract if
  1498. // all indices are contant integers.
  1499. if (!baseExpr->isGLValue()) {
  1500. const uint32_t baseType = typeTranslator.translateType(baseExpr->getType());
  1501. const uint32_t tempVar = theBuilder.addFnVar(baseType, "temp.var");
  1502. theBuilder.createStore(tempVar, base);
  1503. base = tempVar;
  1504. }
  1505. const uint32_t ptrType =
  1506. theBuilder.getPointerType(typeTranslator.translateType(expr->getType()),
  1507. declIdMapper.resolveStorageClass(baseExpr));
  1508. return theBuilder.createAccessChain(ptrType, base, indices);
  1509. }
  1510. uint32_t
  1511. SPIRVEmitter::doExtMatrixElementExpr(const ExtMatrixElementExpr *expr) {
  1512. const Expr *baseExpr = expr->getBase();
  1513. const uint32_t base = doExpr(baseExpr);
  1514. const auto accessor = expr->getEncodedElementAccess();
  1515. const uint32_t elemType = typeTranslator.translateType(
  1516. hlsl::GetHLSLMatElementType(baseExpr->getType()));
  1517. uint32_t rowCount = 0, colCount = 0;
  1518. hlsl::GetHLSLMatRowColCount(baseExpr->getType(), rowCount, colCount);
  1519. // Construct a temporary vector out of all elements accessed:
  1520. // 1. Create access chain for each element using OpAccessChain
  1521. // 2. Load each element using OpLoad
  1522. // 3. Create the vector using OpCompositeConstruct
  1523. llvm::SmallVector<uint32_t, 4> elements;
  1524. for (uint32_t i = 0; i < accessor.Count; ++i) {
  1525. uint32_t row = 0, col = 0, elem = 0;
  1526. accessor.GetPosition(i, &row, &col);
  1527. llvm::SmallVector<uint32_t, 2> indices;
  1528. // If the matrix only has one row/column, we are indexing into a vector
  1529. // then. Only one index is needed for such cases.
  1530. if (rowCount > 1)
  1531. indices.push_back(row);
  1532. if (colCount > 1)
  1533. indices.push_back(col);
  1534. if (baseExpr->isGLValue()) {
  1535. for (uint32_t i = 0; i < indices.size(); ++i)
  1536. indices[i] = theBuilder.getConstantInt32(indices[i]);
  1537. const uint32_t ptrType = theBuilder.getPointerType(
  1538. elemType, declIdMapper.resolveStorageClass(baseExpr));
  1539. if (!indices.empty()) {
  1540. // Load the element via access chain
  1541. elem = theBuilder.createAccessChain(ptrType, base, indices);
  1542. } else {
  1543. // The matrix is of size 1x1. No need to use access chain, base should
  1544. // be the source pointer.
  1545. elem = base;
  1546. }
  1547. elem = theBuilder.createLoad(elemType, elem);
  1548. } else { // e.g., (mat1 + mat2)._m11
  1549. elem = theBuilder.createCompositeExtract(elemType, base, indices);
  1550. }
  1551. elements.push_back(elem);
  1552. }
  1553. if (elements.size() == 1)
  1554. return elements.front();
  1555. const uint32_t vecType = theBuilder.getVecType(elemType, elements.size());
  1556. return theBuilder.createCompositeConstruct(vecType, elements);
  1557. }
  1558. uint32_t
  1559. SPIRVEmitter::doHLSLVectorElementExpr(const HLSLVectorElementExpr *expr) {
  1560. const Expr *baseExpr = nullptr;
  1561. hlsl::VectorMemberAccessPositions accessor;
  1562. condenseVectorElementExpr(expr, &baseExpr, &accessor);
  1563. const QualType baseType = baseExpr->getType();
  1564. assert(hlsl::IsHLSLVecType(baseType));
  1565. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  1566. const uint32_t type = typeTranslator.translateType(expr->getType());
  1567. const auto accessorSize = accessor.Count;
  1568. // Depending on the number of elements selected, we emit different
  1569. // instructions.
  1570. // For vectors of size greater than 1, if we are only selecting one element,
  1571. // typical access chain or composite extraction should be fine. But if we
  1572. // are selecting more than one elements, we must resolve to vector specific
  1573. // operations.
  1574. // For size-1 vectors, if we are selecting their single elements multiple
  1575. // times, we need composite construct instructions.
  1576. if (accessorSize == 1) {
  1577. if (baseSize == 1) {
  1578. // Selecting one element from a size-1 vector. The underlying vector is
  1579. // already treated as a scalar.
  1580. return doExpr(baseExpr);
  1581. }
  1582. // If the base is an lvalue, we should emit an access chain instruction
  1583. // so that we can load/store the specified element. For rvalue base,
  1584. // we should use composite extraction. We should check the immediate base
  1585. // instead of the original base here since we can have something like
  1586. // v.xyyz to turn a lvalue v into rvalue.
  1587. if (expr->getBase()->isGLValue()) { // E.g., v.x;
  1588. const uint32_t ptrType = theBuilder.getPointerType(
  1589. type, declIdMapper.resolveStorageClass(baseExpr));
  1590. const uint32_t index = theBuilder.getConstantInt32(accessor.Swz0);
  1591. // We need a lvalue here. Do not try to load.
  1592. return theBuilder.createAccessChain(ptrType, doExpr(baseExpr), {index});
  1593. } else { // E.g., (v + w).x;
  1594. // The original base vector may not be a rvalue. Need to load it if
  1595. // it is lvalue since ImplicitCastExpr (LValueToRValue) will be missing
  1596. // for that case.
  1597. return theBuilder.createCompositeExtract(type, loadIfGLValue(baseExpr),
  1598. {accessor.Swz0});
  1599. }
  1600. }
  1601. if (baseSize == 1) {
  1602. // Selecting one element from a size-1 vector. Construct the vector.
  1603. llvm::SmallVector<uint32_t, 4> components(static_cast<size_t>(accessorSize),
  1604. loadIfGLValue(baseExpr));
  1605. return theBuilder.createCompositeConstruct(type, components);
  1606. }
  1607. llvm::SmallVector<uint32_t, 4> selectors;
  1608. selectors.resize(accessorSize);
  1609. // Whether we are selecting elements in the original order
  1610. bool originalOrder = baseSize == accessorSize;
  1611. for (uint32_t i = 0; i < accessorSize; ++i) {
  1612. accessor.GetPosition(i, &selectors[i]);
  1613. // We can select more elements than the vector provides. This handles
  1614. // that case too.
  1615. originalOrder &= selectors[i] == i;
  1616. }
  1617. if (originalOrder)
  1618. return doExpr(baseExpr);
  1619. const uint32_t baseVal = loadIfGLValue(baseExpr);
  1620. // Use base for both vectors. But we are only selecting values from the
  1621. // first one.
  1622. return theBuilder.createVectorShuffle(type, baseVal, baseVal, selectors);
  1623. }
  1624. uint32_t SPIRVEmitter::doInitListExpr(const InitListExpr *expr) {
  1625. if (const uint32_t id = tryToEvaluateAsConst(expr))
  1626. return id;
  1627. return InitListHandler(*this).process(expr);
  1628. }
  1629. uint32_t SPIRVEmitter::doMemberExpr(const MemberExpr *expr) {
  1630. llvm::SmallVector<uint32_t, 4> indices;
  1631. const Expr *base = collectArrayStructIndices(expr, &indices);
  1632. const uint32_t ptrType =
  1633. theBuilder.getPointerType(typeTranslator.translateType(expr->getType()),
  1634. declIdMapper.resolveStorageClass(base));
  1635. return theBuilder.createAccessChain(ptrType, doExpr(base), indices);
  1636. }
  1637. uint32_t SPIRVEmitter::doUnaryOperator(const UnaryOperator *expr) {
  1638. const auto opcode = expr->getOpcode();
  1639. const auto *subExpr = expr->getSubExpr();
  1640. const auto subType = subExpr->getType();
  1641. const auto subValue = doExpr(subExpr);
  1642. const auto subTypeId = typeTranslator.translateType(subType);
  1643. switch (opcode) {
  1644. case UO_PreInc:
  1645. case UO_PreDec:
  1646. case UO_PostInc:
  1647. case UO_PostDec: {
  1648. const bool isPre = opcode == UO_PreInc || opcode == UO_PreDec;
  1649. const bool isInc = opcode == UO_PreInc || opcode == UO_PostInc;
  1650. const spv::Op spvOp = translateOp(isInc ? BO_Add : BO_Sub, subType);
  1651. const uint32_t originValue = theBuilder.createLoad(subTypeId, subValue);
  1652. const uint32_t one = hlsl::IsHLSLMatType(subType)
  1653. ? getMatElemValueOne(subType)
  1654. : getValueOne(subType);
  1655. uint32_t incValue = 0;
  1656. if (TypeTranslator::isSpirvAcceptableMatrixType(subType)) {
  1657. // For matrices, we can only increment/decrement each vector of it.
  1658. const auto actOnEachVec = [this, spvOp, one](
  1659. uint32_t /*index*/, uint32_t vecType, uint32_t lhsVec) {
  1660. return theBuilder.createBinaryOp(spvOp, vecType, lhsVec, one);
  1661. };
  1662. incValue = processEachVectorInMatrix(subExpr, originValue, actOnEachVec);
  1663. } else {
  1664. incValue = theBuilder.createBinaryOp(spvOp, subTypeId, originValue, one);
  1665. }
  1666. theBuilder.createStore(subValue, incValue);
  1667. // Prefix increment/decrement operator returns a lvalue, while postfix
  1668. // increment/decrement returns a rvalue.
  1669. return isPre ? subValue : originValue;
  1670. }
  1671. case UO_Not:
  1672. return theBuilder.createUnaryOp(spv::Op::OpNot, subTypeId, subValue);
  1673. case UO_LNot:
  1674. // Parsing will do the necessary casting to make sure we are applying the
  1675. // ! operator on boolean values.
  1676. return theBuilder.createUnaryOp(spv::Op::OpLogicalNot, subTypeId, subValue);
  1677. case UO_Plus:
  1678. // No need to do anything for the prefix + operator.
  1679. return subValue;
  1680. case UO_Minus: {
  1681. // SPIR-V have two opcodes for negating values: OpSNegate and OpFNegate.
  1682. const spv::Op spvOp = isFloatOrVecOfFloatType(subType) ? spv::Op::OpFNegate
  1683. : spv::Op::OpSNegate;
  1684. return theBuilder.createUnaryOp(spvOp, subTypeId, subValue);
  1685. }
  1686. default:
  1687. break;
  1688. }
  1689. emitError("unary operator '%0' unimplemented yet")
  1690. << expr->getOpcodeStr(opcode);
  1691. expr->dump();
  1692. return 0;
  1693. }
  1694. spv::Op SPIRVEmitter::translateOp(BinaryOperator::Opcode op, QualType type) {
  1695. const bool isSintType = isSintOrVecMatOfSintType(type);
  1696. const bool isUintType = isUintOrVecMatOfUintType(type);
  1697. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  1698. #define BIN_OP_CASE_INT_FLOAT(kind, intBinOp, floatBinOp) \
  1699. \
  1700. case BO_##kind : { \
  1701. if (isSintType || isUintType) { \
  1702. return spv::Op::Op##intBinOp; \
  1703. } \
  1704. if (isFloatType) { \
  1705. return spv::Op::Op##floatBinOp; \
  1706. } \
  1707. } \
  1708. break
  1709. #define BIN_OP_CASE_SINT_UINT_FLOAT(kind, sintBinOp, uintBinOp, floatBinOp) \
  1710. \
  1711. case BO_##kind : { \
  1712. if (isSintType) { \
  1713. return spv::Op::Op##sintBinOp; \
  1714. } \
  1715. if (isUintType) { \
  1716. return spv::Op::Op##uintBinOp; \
  1717. } \
  1718. if (isFloatType) { \
  1719. return spv::Op::Op##floatBinOp; \
  1720. } \
  1721. } \
  1722. break
  1723. #define BIN_OP_CASE_SINT_UINT(kind, sintBinOp, uintBinOp) \
  1724. \
  1725. case BO_##kind : { \
  1726. if (isSintType) { \
  1727. return spv::Op::Op##sintBinOp; \
  1728. } \
  1729. if (isUintType) { \
  1730. return spv::Op::Op##uintBinOp; \
  1731. } \
  1732. } \
  1733. break
  1734. switch (op) {
  1735. case BO_EQ: {
  1736. if (isBoolOrVecMatOfBoolType(type))
  1737. return spv::Op::OpLogicalEqual;
  1738. if (isSintType || isUintType)
  1739. return spv::Op::OpIEqual;
  1740. if (isFloatType)
  1741. return spv::Op::OpFOrdEqual;
  1742. } break;
  1743. case BO_NE: {
  1744. if (isBoolOrVecMatOfBoolType(type))
  1745. return spv::Op::OpLogicalNotEqual;
  1746. if (isSintType || isUintType)
  1747. return spv::Op::OpINotEqual;
  1748. if (isFloatType)
  1749. return spv::Op::OpFOrdNotEqual;
  1750. } break;
  1751. // According to HLSL doc, all sides of the && and || expression are always
  1752. // evaluated.
  1753. case BO_LAnd:
  1754. return spv::Op::OpLogicalAnd;
  1755. case BO_LOr:
  1756. return spv::Op::OpLogicalOr;
  1757. BIN_OP_CASE_INT_FLOAT(Add, IAdd, FAdd);
  1758. BIN_OP_CASE_INT_FLOAT(AddAssign, IAdd, FAdd);
  1759. BIN_OP_CASE_INT_FLOAT(Sub, ISub, FSub);
  1760. BIN_OP_CASE_INT_FLOAT(SubAssign, ISub, FSub);
  1761. BIN_OP_CASE_INT_FLOAT(Mul, IMul, FMul);
  1762. BIN_OP_CASE_INT_FLOAT(MulAssign, IMul, FMul);
  1763. BIN_OP_CASE_SINT_UINT_FLOAT(Div, SDiv, UDiv, FDiv);
  1764. BIN_OP_CASE_SINT_UINT_FLOAT(DivAssign, SDiv, UDiv, FDiv);
  1765. // According to HLSL spec, "the modulus operator returns the remainder of
  1766. // a division." "The % operator is defined only in cases where either both
  1767. // sides are positive or both sides are negative."
  1768. //
  1769. // In SPIR-V, there are two reminder operations: Op*Rem and Op*Mod. With
  1770. // the former, the sign of a non-0 result comes from Operand 1, while
  1771. // with the latter, from Operand 2.
  1772. //
  1773. // For operands with different signs, technically we can map % to either
  1774. // Op*Rem or Op*Mod since it's undefined behavior. But it is more
  1775. // consistent with C (HLSL starts as a C derivative) and Clang frontend
  1776. // const expression evaluation if we map % to Op*Rem.
  1777. //
  1778. // Note there is no OpURem in SPIR-V.
  1779. BIN_OP_CASE_SINT_UINT_FLOAT(Rem, SRem, UMod, FRem);
  1780. BIN_OP_CASE_SINT_UINT_FLOAT(RemAssign, SRem, UMod, FRem);
  1781. BIN_OP_CASE_SINT_UINT_FLOAT(LT, SLessThan, ULessThan, FOrdLessThan);
  1782. BIN_OP_CASE_SINT_UINT_FLOAT(LE, SLessThanEqual, ULessThanEqual,
  1783. FOrdLessThanEqual);
  1784. BIN_OP_CASE_SINT_UINT_FLOAT(GT, SGreaterThan, UGreaterThan,
  1785. FOrdGreaterThan);
  1786. BIN_OP_CASE_SINT_UINT_FLOAT(GE, SGreaterThanEqual, UGreaterThanEqual,
  1787. FOrdGreaterThanEqual);
  1788. BIN_OP_CASE_SINT_UINT(And, BitwiseAnd, BitwiseAnd);
  1789. BIN_OP_CASE_SINT_UINT(AndAssign, BitwiseAnd, BitwiseAnd);
  1790. BIN_OP_CASE_SINT_UINT(Or, BitwiseOr, BitwiseOr);
  1791. BIN_OP_CASE_SINT_UINT(OrAssign, BitwiseOr, BitwiseOr);
  1792. BIN_OP_CASE_SINT_UINT(Xor, BitwiseXor, BitwiseXor);
  1793. BIN_OP_CASE_SINT_UINT(XorAssign, BitwiseXor, BitwiseXor);
  1794. BIN_OP_CASE_SINT_UINT(Shl, ShiftLeftLogical, ShiftLeftLogical);
  1795. BIN_OP_CASE_SINT_UINT(ShlAssign, ShiftLeftLogical, ShiftLeftLogical);
  1796. BIN_OP_CASE_SINT_UINT(Shr, ShiftRightArithmetic, ShiftRightLogical);
  1797. BIN_OP_CASE_SINT_UINT(ShrAssign, ShiftRightArithmetic, ShiftRightLogical);
  1798. default:
  1799. break;
  1800. }
  1801. #undef BIN_OP_CASE_INT_FLOAT
  1802. #undef BIN_OP_CASE_SINT_UINT_FLOAT
  1803. #undef BIN_OP_CASE_SINT_UINT
  1804. emitError("translating binary operator '%0' unimplemented")
  1805. << BinaryOperator::getOpcodeStr(op);
  1806. return spv::Op::OpNop;
  1807. }
  1808. uint32_t SPIRVEmitter::processAssignment(const Expr *lhs, const uint32_t rhs,
  1809. bool isCompoundAssignment,
  1810. uint32_t lhsPtr) {
  1811. // Assigning to vector swizzling should be handled differently.
  1812. if (const uint32_t result = tryToAssignToVectorElements(lhs, rhs)) {
  1813. return result;
  1814. }
  1815. // Assigning to matrix swizzling should be handled differently.
  1816. if (const uint32_t result = tryToAssignToMatrixElements(lhs, rhs)) {
  1817. return result;
  1818. }
  1819. // Assigning to a RWBuffer should be handled differently.
  1820. if (const uint32_t result = tryToAssignToRWBuffer(lhs, rhs)) {
  1821. return result;
  1822. }
  1823. // Normal assignment procedure
  1824. if (lhsPtr == 0)
  1825. lhsPtr = doExpr(lhs);
  1826. theBuilder.createStore(lhsPtr, rhs);
  1827. // Plain assignment returns a rvalue, while compound assignment returns
  1828. // lvalue.
  1829. return isCompoundAssignment ? lhsPtr : rhs;
  1830. }
  1831. uint32_t SPIRVEmitter::processBinaryOp(const Expr *lhs, const Expr *rhs,
  1832. const BinaryOperatorKind opcode,
  1833. const uint32_t resultType,
  1834. uint32_t *lhsResultId,
  1835. const spv::Op mandateGenOpcode) {
  1836. // If the operands are of matrix type, we need to dispatch the operation
  1837. // onto each element vector iff the operands are not degenerated matrices
  1838. // and we don't have a matrix specific SPIR-V instruction for the operation.
  1839. if (!isSpirvMatrixOp(mandateGenOpcode) &&
  1840. TypeTranslator::isSpirvAcceptableMatrixType(lhs->getType())) {
  1841. return processMatrixBinaryOp(lhs, rhs, opcode);
  1842. }
  1843. const spv::Op spvOp = (mandateGenOpcode == spv::Op::Max)
  1844. ? translateOp(opcode, lhs->getType())
  1845. : mandateGenOpcode;
  1846. uint32_t rhsVal, lhsPtr, lhsVal;
  1847. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  1848. // Evalute rhs before lhs
  1849. rhsVal = doExpr(rhs);
  1850. lhsVal = lhsPtr = doExpr(lhs);
  1851. // This is a compound assignment. We need to load the lhs value if lhs
  1852. // does not generate a vector shuffle.
  1853. if (!isVectorShuffle(lhs)) {
  1854. const uint32_t lhsTy = typeTranslator.translateType(lhs->getType());
  1855. lhsVal = theBuilder.createLoad(lhsTy, lhsPtr);
  1856. }
  1857. } else {
  1858. // Evalute lhs before rhs
  1859. lhsVal = lhsPtr = doExpr(lhs);
  1860. rhsVal = doExpr(rhs);
  1861. }
  1862. if (lhsResultId)
  1863. *lhsResultId = lhsPtr;
  1864. switch (opcode) {
  1865. case BO_Add:
  1866. case BO_Sub:
  1867. case BO_Mul:
  1868. case BO_Div:
  1869. case BO_Rem:
  1870. case BO_LT:
  1871. case BO_LE:
  1872. case BO_GT:
  1873. case BO_GE:
  1874. case BO_EQ:
  1875. case BO_NE:
  1876. case BO_And:
  1877. case BO_Or:
  1878. case BO_Xor:
  1879. case BO_Shl:
  1880. case BO_Shr:
  1881. case BO_LAnd:
  1882. case BO_LOr:
  1883. case BO_AddAssign:
  1884. case BO_SubAssign:
  1885. case BO_MulAssign:
  1886. case BO_DivAssign:
  1887. case BO_RemAssign:
  1888. case BO_AndAssign:
  1889. case BO_OrAssign:
  1890. case BO_XorAssign:
  1891. case BO_ShlAssign:
  1892. case BO_ShrAssign:
  1893. return theBuilder.createBinaryOp(spvOp, resultType, lhsVal, rhsVal);
  1894. case BO_Assign:
  1895. llvm_unreachable("assignment should not be handled here");
  1896. default:
  1897. break;
  1898. }
  1899. emitError("BinaryOperator '%0' is not supported yet.")
  1900. << BinaryOperator::getOpcodeStr(opcode);
  1901. return 0;
  1902. }
  1903. void SPIRVEmitter::initOnce(std::string varName, uint32_t varPtr,
  1904. const Expr *varInit) {
  1905. const uint32_t boolType = theBuilder.getBoolType();
  1906. varName = "init.done." + varName;
  1907. // Create a file/module visible variable to hold the initialization state.
  1908. const uint32_t initDoneVar =
  1909. theBuilder.addModuleVar(boolType, spv::StorageClass::Private, varName,
  1910. theBuilder.getConstantBool(false));
  1911. const uint32_t condition = theBuilder.createLoad(boolType, initDoneVar);
  1912. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  1913. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  1914. theBuilder.createConditionalBranch(condition, thenBB, mergeBB, mergeBB);
  1915. theBuilder.addSuccessor(thenBB);
  1916. theBuilder.addSuccessor(mergeBB);
  1917. theBuilder.setMergeTarget(mergeBB);
  1918. theBuilder.setInsertPoint(thenBB);
  1919. // Do initialization and mark done
  1920. theBuilder.createStore(varPtr, doExpr(varInit));
  1921. theBuilder.createStore(initDoneVar, theBuilder.getConstantBool(true));
  1922. theBuilder.createBranch(mergeBB);
  1923. theBuilder.addSuccessor(mergeBB);
  1924. theBuilder.setInsertPoint(mergeBB);
  1925. }
  1926. bool SPIRVEmitter::isVectorShuffle(const Expr *expr) {
  1927. // TODO: the following check is essentially duplicated from
  1928. // doHLSLVectorElementExpr. Should unify them.
  1929. if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  1930. const Expr *base = nullptr;
  1931. hlsl::VectorMemberAccessPositions accessor;
  1932. condenseVectorElementExpr(vecElemExpr, &base, &accessor);
  1933. const auto accessorSize = accessor.Count;
  1934. if (accessorSize == 1) {
  1935. // Selecting only one element. OpAccessChain or OpCompositeExtract for
  1936. // such cases.
  1937. return false;
  1938. }
  1939. const auto baseSize = hlsl::GetHLSLVecSize(base->getType());
  1940. if (accessorSize != baseSize)
  1941. return true;
  1942. for (uint32_t i = 0; i < accessorSize; ++i) {
  1943. uint32_t position;
  1944. accessor.GetPosition(i, &position);
  1945. if (position != i)
  1946. return true;
  1947. }
  1948. // Selecting exactly the original vector. No vector shuffle generated.
  1949. return false;
  1950. }
  1951. return false;
  1952. }
  1953. bool SPIRVEmitter::isBufferIndexing(const CXXOperatorCallExpr *indexExpr,
  1954. const Expr **base, const Expr **index) {
  1955. if (!indexExpr)
  1956. return false;
  1957. // Must be operator[]
  1958. if (indexExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  1959. return false;
  1960. const Expr *object = indexExpr->getArg(0);
  1961. const auto objectType = object->getType();
  1962. if (typeTranslator.isBuffer(objectType) ||
  1963. typeTranslator.isRWBuffer(objectType)) {
  1964. if (base)
  1965. *base = object;
  1966. if (index)
  1967. *index = indexExpr->getArg(1);
  1968. return true;
  1969. }
  1970. return false;
  1971. }
  1972. void SPIRVEmitter::condenseVectorElementExpr(
  1973. const HLSLVectorElementExpr *expr, const Expr **basePtr,
  1974. hlsl::VectorMemberAccessPositions *flattenedAccessor) {
  1975. llvm::SmallVector<hlsl::VectorMemberAccessPositions, 2> accessors;
  1976. accessors.push_back(expr->getEncodedElementAccess());
  1977. // Recursively descending until we find the true base vector. In the
  1978. // meanwhile, collecting accessors in the reverse order.
  1979. *basePtr = expr->getBase();
  1980. while (const auto *vecElemBase = dyn_cast<HLSLVectorElementExpr>(*basePtr)) {
  1981. accessors.push_back(vecElemBase->getEncodedElementAccess());
  1982. *basePtr = vecElemBase->getBase();
  1983. }
  1984. *flattenedAccessor = accessors.back();
  1985. for (int32_t i = accessors.size() - 2; i >= 0; --i) {
  1986. const auto &currentAccessor = accessors[i];
  1987. // Apply the current level of accessor to the flattened accessor of all
  1988. // previous levels of ones.
  1989. hlsl::VectorMemberAccessPositions combinedAccessor;
  1990. for (uint32_t j = 0; j < currentAccessor.Count; ++j) {
  1991. uint32_t currentPosition = 0;
  1992. currentAccessor.GetPosition(j, &currentPosition);
  1993. uint32_t previousPosition = 0;
  1994. flattenedAccessor->GetPosition(currentPosition, &previousPosition);
  1995. combinedAccessor.SetPosition(j, previousPosition);
  1996. }
  1997. combinedAccessor.Count = currentAccessor.Count;
  1998. combinedAccessor.IsValid =
  1999. flattenedAccessor->IsValid && currentAccessor.IsValid;
  2000. *flattenedAccessor = combinedAccessor;
  2001. }
  2002. }
  2003. uint32_t SPIRVEmitter::createVectorSplat(const Expr *scalarExpr, uint32_t size,
  2004. bool *resultIsConstant) {
  2005. bool isConstVal = false;
  2006. uint32_t scalarVal = 0;
  2007. // Try to evaluate the element as constant first. If successful, then we
  2008. // can generate constant instructions for this vector splat.
  2009. if (scalarVal = tryToEvaluateAsConst(scalarExpr)) {
  2010. isConstVal = true;
  2011. } else {
  2012. scalarVal = doExpr(scalarExpr);
  2013. }
  2014. if (resultIsConstant)
  2015. *resultIsConstant = isConstVal;
  2016. // Just return the scalar value for vector splat with size 1
  2017. if (size == 1)
  2018. return scalarVal;
  2019. const uint32_t vecType = theBuilder.getVecType(
  2020. typeTranslator.translateType(scalarExpr->getType()), size);
  2021. llvm::SmallVector<uint32_t, 4> elements(size_t(size), scalarVal);
  2022. if (isConstVal) {
  2023. return theBuilder.getConstantComposite(vecType, elements);
  2024. } else {
  2025. return theBuilder.createCompositeConstruct(vecType, elements);
  2026. }
  2027. }
  2028. void SPIRVEmitter::splitVecLastElement(QualType vecType, uint32_t vec,
  2029. uint32_t *residual,
  2030. uint32_t *lastElement) {
  2031. assert(hlsl::IsHLSLVecType(vecType));
  2032. const uint32_t count = hlsl::GetHLSLVecSize(vecType);
  2033. assert(count > 1);
  2034. const uint32_t elemTypeId =
  2035. typeTranslator.translateType(hlsl::GetHLSLVecElementType(vecType));
  2036. if (count == 2) {
  2037. *residual = theBuilder.createCompositeExtract(elemTypeId, vec, 0);
  2038. } else {
  2039. llvm::SmallVector<uint32_t, 4> indices;
  2040. for (uint32_t i = 0; i < count - 1; ++i)
  2041. indices.push_back(i);
  2042. const uint32_t typeId = theBuilder.getVecType(elemTypeId, count - 1);
  2043. *residual = theBuilder.createVectorShuffle(typeId, vec, vec, indices);
  2044. }
  2045. *lastElement =
  2046. theBuilder.createCompositeExtract(elemTypeId, vec, {count - 1});
  2047. }
  2048. uint32_t SPIRVEmitter::tryToGenFloatVectorScale(const BinaryOperator *expr) {
  2049. const QualType type = expr->getType();
  2050. // We can only translate floatN * float into OpVectorTimesScalar.
  2051. // So the result type must be floatN.
  2052. if (!hlsl::IsHLSLVecType(type) ||
  2053. !hlsl::GetHLSLVecElementType(type)->isFloatingType())
  2054. return 0;
  2055. const Expr *lhs = expr->getLHS();
  2056. const Expr *rhs = expr->getRHS();
  2057. // Multiplying a float vector with a float scalar will be represented in
  2058. // AST via a binary operation with two float vectors as operands; one of
  2059. // the operand is from an implicit cast with kind CK_HLSLVectorSplat.
  2060. // vector * scalar
  2061. if (hlsl::IsHLSLVecType(lhs->getType())) {
  2062. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  2063. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  2064. const uint32_t vecType = typeTranslator.translateType(expr->getType());
  2065. if (isa<CompoundAssignOperator>(expr)) {
  2066. uint32_t lhsPtr = 0;
  2067. const uint32_t result =
  2068. processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  2069. vecType, &lhsPtr, spv::Op::OpVectorTimesScalar);
  2070. return processAssignment(lhs, result, true, lhsPtr);
  2071. } else {
  2072. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  2073. vecType, nullptr,
  2074. spv::Op::OpVectorTimesScalar);
  2075. }
  2076. }
  2077. }
  2078. }
  2079. // scalar * vector
  2080. if (hlsl::IsHLSLVecType(rhs->getType())) {
  2081. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  2082. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  2083. const uint32_t vecType = typeTranslator.translateType(expr->getType());
  2084. // We need to switch the positions of lhs and rhs here because
  2085. // OpVectorTimesScalar requires the first operand to be a vector and
  2086. // the second to be a scalar.
  2087. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  2088. vecType, nullptr, spv::Op::OpVectorTimesScalar);
  2089. }
  2090. }
  2091. }
  2092. return 0;
  2093. }
  2094. uint32_t SPIRVEmitter::tryToGenFloatMatrixScale(const BinaryOperator *expr) {
  2095. const QualType type = expr->getType();
  2096. // We can only translate floatMxN * float into OpMatrixTimesScalar.
  2097. // So the result type must be floatMxN.
  2098. if (!hlsl::IsHLSLMatType(type) ||
  2099. !hlsl::GetHLSLMatElementType(type)->isFloatingType())
  2100. return 0;
  2101. const Expr *lhs = expr->getLHS();
  2102. const Expr *rhs = expr->getRHS();
  2103. const QualType lhsType = lhs->getType();
  2104. const QualType rhsType = rhs->getType();
  2105. const auto selectOpcode = [](const QualType ty) {
  2106. return TypeTranslator::isMx1Matrix(ty) || TypeTranslator::is1xNMatrix(ty)
  2107. ? spv::Op::OpVectorTimesScalar
  2108. : spv::Op::OpMatrixTimesScalar;
  2109. };
  2110. // Multiplying a float matrix with a float scalar will be represented in
  2111. // AST via a binary operation with two float matrices as operands; one of
  2112. // the operand is from an implicit cast with kind CK_HLSLMatrixSplat.
  2113. // matrix * scalar
  2114. if (hlsl::IsHLSLMatType(lhsType)) {
  2115. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  2116. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  2117. const uint32_t matType = typeTranslator.translateType(expr->getType());
  2118. const spv::Op opcode = selectOpcode(lhsType);
  2119. if (isa<CompoundAssignOperator>(expr)) {
  2120. uint32_t lhsPtr = 0;
  2121. const uint32_t result =
  2122. processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  2123. matType, &lhsPtr, opcode);
  2124. return processAssignment(lhs, result, true, lhsPtr);
  2125. } else {
  2126. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  2127. matType, nullptr, opcode);
  2128. }
  2129. }
  2130. }
  2131. }
  2132. // scalar * matrix
  2133. if (hlsl::IsHLSLMatType(rhsType)) {
  2134. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  2135. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  2136. const uint32_t matType = typeTranslator.translateType(expr->getType());
  2137. const spv::Op opcode = selectOpcode(rhsType);
  2138. // We need to switch the positions of lhs and rhs here because
  2139. // OpMatrixTimesScalar requires the first operand to be a matrix and
  2140. // the second to be a scalar.
  2141. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  2142. matType, nullptr, opcode);
  2143. }
  2144. }
  2145. }
  2146. return 0;
  2147. }
  2148. uint32_t SPIRVEmitter::tryToAssignToVectorElements(const Expr *lhs,
  2149. const uint32_t rhs) {
  2150. // Assigning to a vector swizzling lhs is tricky if we are neither
  2151. // writing to one element nor all elements in their original order.
  2152. // Under such cases, we need to create a new vector swizzling involving
  2153. // both the lhs and rhs vectors and then write the result of this swizzling
  2154. // into the base vector of lhs.
  2155. // For example, for vec4.yz = vec2, we nee to do the following:
  2156. //
  2157. // %vec4Val = OpLoad %v4float %vec4
  2158. // %vec2Val = OpLoad %v2float %vec2
  2159. // %shuffle = OpVectorShuffle %v4float %vec4Val %vec2Val 0 4 5 3
  2160. // OpStore %vec4 %shuffle
  2161. //
  2162. // When doing the vector shuffle, we use the lhs base vector as the first
  2163. // vector and the rhs vector as the second vector. Therefore, all elements
  2164. // in the second vector will be selected into the shuffle result.
  2165. const auto *lhsExpr = dyn_cast<HLSLVectorElementExpr>(lhs);
  2166. if (!lhsExpr)
  2167. return 0;
  2168. if (!isVectorShuffle(lhs)) {
  2169. // No vector shuffle needed to be generated for this assignment.
  2170. // Should fall back to the normal handling of assignment.
  2171. return 0;
  2172. }
  2173. const Expr *base = nullptr;
  2174. hlsl::VectorMemberAccessPositions accessor;
  2175. condenseVectorElementExpr(lhsExpr, &base, &accessor);
  2176. const QualType baseType = base->getType();
  2177. assert(hlsl::IsHLSLVecType(baseType));
  2178. const auto baseSizse = hlsl::GetHLSLVecSize(baseType);
  2179. llvm::SmallVector<uint32_t, 4> selectors;
  2180. selectors.resize(baseSizse);
  2181. // Assume we are selecting all original elements first.
  2182. for (uint32_t i = 0; i < baseSizse; ++i) {
  2183. selectors[i] = i;
  2184. }
  2185. // Now fix up the elements that actually got overwritten by the rhs vector.
  2186. // Since we are using the rhs vector as the second vector, their index
  2187. // should be offset'ed by the size of the lhs base vector.
  2188. for (uint32_t i = 0; i < accessor.Count; ++i) {
  2189. uint32_t position;
  2190. accessor.GetPosition(i, &position);
  2191. selectors[position] = baseSizse + i;
  2192. }
  2193. const uint32_t baseTypeId = typeTranslator.translateType(baseType);
  2194. const uint32_t vec1 = doExpr(base);
  2195. const uint32_t vec1Val = theBuilder.createLoad(baseTypeId, vec1);
  2196. const uint32_t shuffle =
  2197. theBuilder.createVectorShuffle(baseTypeId, vec1Val, rhs, selectors);
  2198. theBuilder.createStore(vec1, shuffle);
  2199. // TODO: OK, this return value is incorrect for compound assignments, for
  2200. // which cases we should return lvalues. Should at least emit errors if
  2201. // this return value is used (can be checked via ASTContext.getParents).
  2202. return rhs;
  2203. }
  2204. uint32_t SPIRVEmitter::tryToAssignToRWBuffer(const Expr *lhs, uint32_t rhs) {
  2205. const Expr* baseExpr = nullptr;
  2206. const Expr* indexExpr = nullptr;
  2207. if (isBufferIndexing(dyn_cast<CXXOperatorCallExpr>(lhs), &baseExpr,
  2208. &indexExpr)) {
  2209. const uint32_t locId = doExpr(indexExpr);
  2210. const uint32_t imageId = theBuilder.createLoad(
  2211. typeTranslator.translateType(baseExpr->getType()), doExpr(baseExpr));
  2212. theBuilder.createImageWrite(imageId, locId, rhs);
  2213. return rhs;
  2214. }
  2215. return 0;
  2216. }
  2217. uint32_t SPIRVEmitter::tryToAssignToMatrixElements(const Expr *lhs,
  2218. uint32_t rhs) {
  2219. const auto *lhsExpr = dyn_cast<ExtMatrixElementExpr>(lhs);
  2220. if (!lhsExpr)
  2221. return 0;
  2222. const Expr *baseMat = lhsExpr->getBase();
  2223. const uint32_t base = doExpr(baseMat);
  2224. const QualType elemType = hlsl::GetHLSLMatElementType(baseMat->getType());
  2225. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  2226. uint32_t rowCount = 0, colCount = 0;
  2227. hlsl::GetHLSLMatRowColCount(baseMat->getType(), rowCount, colCount);
  2228. // For each lhs element written to:
  2229. // 1. Extract the corresponding rhs element using OpCompositeExtract
  2230. // 2. Create access chain for the lhs element using OpAccessChain
  2231. // 3. Write using OpStore
  2232. const auto accessor = lhsExpr->getEncodedElementAccess();
  2233. for (uint32_t i = 0; i < accessor.Count; ++i) {
  2234. uint32_t row = 0, col = 0;
  2235. accessor.GetPosition(i, &row, &col);
  2236. llvm::SmallVector<uint32_t, 2> indices;
  2237. // If the matrix only have one row/column, we are indexing into a vector
  2238. // then. Only one index is needed for such cases.
  2239. if (rowCount > 1)
  2240. indices.push_back(row);
  2241. if (colCount > 1)
  2242. indices.push_back(col);
  2243. for (uint32_t i = 0; i < indices.size(); ++i)
  2244. indices[i] = theBuilder.getConstantInt32(indices[i]);
  2245. // If we are writing to only one element, the rhs should already be a
  2246. // scalar value.
  2247. uint32_t rhsElem = rhs;
  2248. if (accessor.Count > 1)
  2249. rhsElem = theBuilder.createCompositeExtract(elemTypeId, rhs, {i});
  2250. const uint32_t ptrType = theBuilder.getPointerType(
  2251. elemTypeId, declIdMapper.resolveStorageClass(baseMat));
  2252. // If the lhs is actually a matrix of size 1x1, we don't need the access
  2253. // chain. base is already the dest pointer.
  2254. uint32_t lhsElemPtr = base;
  2255. if (!indices.empty()) {
  2256. // Load the element via access chain
  2257. lhsElemPtr = theBuilder.createAccessChain(ptrType, base, indices);
  2258. }
  2259. theBuilder.createStore(lhsElemPtr, rhsElem);
  2260. }
  2261. // TODO: OK, this return value is incorrect for compound assignments, for
  2262. // which cases we should return lvalues. Should at least emit errors if
  2263. // this return value is used (can be checked via ASTContext.getParents).
  2264. return rhs;
  2265. }
  2266. uint32_t SPIRVEmitter::processEachVectorInMatrix(
  2267. const Expr *matrix, const uint32_t matrixVal,
  2268. llvm::function_ref<uint32_t(uint32_t, uint32_t, uint32_t)>
  2269. actOnEachVector) {
  2270. const auto matType = matrix->getType();
  2271. assert(TypeTranslator::isSpirvAcceptableMatrixType(matType));
  2272. const uint32_t vecType = typeTranslator.getComponentVectorType(matType);
  2273. uint32_t rowCount = 0, colCount = 0;
  2274. hlsl::GetHLSLMatRowColCount(matType, rowCount, colCount);
  2275. llvm::SmallVector<uint32_t, 4> vectors;
  2276. // Extract each component vector and do operation on it
  2277. for (uint32_t i = 0; i < rowCount; ++i) {
  2278. const uint32_t lhsVec =
  2279. theBuilder.createCompositeExtract(vecType, matrixVal, {i});
  2280. vectors.push_back(actOnEachVector(i, vecType, lhsVec));
  2281. }
  2282. // Construct the result matrix
  2283. return theBuilder.createCompositeConstruct(
  2284. typeTranslator.translateType(matType), vectors);
  2285. }
  2286. uint32_t SPIRVEmitter::processMatrixBinaryOp(const Expr *lhs, const Expr *rhs,
  2287. const BinaryOperatorKind opcode) {
  2288. // TODO: some code are duplicated from processBinaryOp. Try to unify them.
  2289. const auto lhsType = lhs->getType();
  2290. assert(TypeTranslator::isSpirvAcceptableMatrixType(lhsType));
  2291. const spv::Op spvOp = translateOp(opcode, lhsType);
  2292. uint32_t rhsVal, lhsPtr, lhsVal;
  2293. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  2294. // Evalute rhs before lhs
  2295. rhsVal = doExpr(rhs);
  2296. lhsPtr = doExpr(lhs);
  2297. const uint32_t lhsTy = typeTranslator.translateType(lhsType);
  2298. lhsVal = theBuilder.createLoad(lhsTy, lhsPtr);
  2299. } else {
  2300. // Evalute lhs before rhs
  2301. lhsVal = lhsPtr = doExpr(lhs);
  2302. rhsVal = doExpr(rhs);
  2303. }
  2304. switch (opcode) {
  2305. case BO_Add:
  2306. case BO_Sub:
  2307. case BO_Mul:
  2308. case BO_Div:
  2309. case BO_Rem:
  2310. case BO_AddAssign:
  2311. case BO_SubAssign:
  2312. case BO_MulAssign:
  2313. case BO_DivAssign:
  2314. case BO_RemAssign: {
  2315. const uint32_t vecType = typeTranslator.getComponentVectorType(lhsType);
  2316. const auto actOnEachVec = [this, spvOp, rhsVal](
  2317. uint32_t index, uint32_t vecType, uint32_t lhsVec) {
  2318. // For each vector of lhs, we need to load the corresponding vector of
  2319. // rhs and do the operation on them.
  2320. const uint32_t rhsVec =
  2321. theBuilder.createCompositeExtract(vecType, rhsVal, {index});
  2322. return theBuilder.createBinaryOp(spvOp, vecType, lhsVec, rhsVec);
  2323. };
  2324. return processEachVectorInMatrix(lhs, lhsVal, actOnEachVec);
  2325. }
  2326. case BO_Assign:
  2327. llvm_unreachable("assignment should not be handled here");
  2328. default:
  2329. break;
  2330. }
  2331. emitError("BinaryOperator '%0' for matrices not supported yet")
  2332. << BinaryOperator::getOpcodeStr(opcode);
  2333. return 0;
  2334. }
  2335. const Expr *SPIRVEmitter::collectArrayStructIndices(
  2336. const Expr *expr, llvm::SmallVectorImpl<uint32_t> *indices) {
  2337. if (const auto *indexing = dyn_cast<MemberExpr>(expr)) {
  2338. const Expr *base = collectArrayStructIndices(
  2339. indexing->getBase()->IgnoreParenNoopCasts(astContext), indices);
  2340. // Append the index of the current level
  2341. const auto *fieldDecl = cast<FieldDecl>(indexing->getMemberDecl());
  2342. assert(fieldDecl);
  2343. indices->push_back(theBuilder.getConstantInt32(fieldDecl->getFieldIndex()));
  2344. return base;
  2345. }
  2346. if (const auto *indexing = dyn_cast<ArraySubscriptExpr>(expr)) {
  2347. // The base of an ArraySubscriptExpr has a wrapping LValueToRValue implicit
  2348. // cast. We need to ingore it to avoid creating OpLoad.
  2349. const Expr *thisBase = indexing->getBase()->IgnoreParenLValueCasts();
  2350. const Expr *base = collectArrayStructIndices(thisBase, indices);
  2351. indices->push_back(doExpr(indexing->getIdx()));
  2352. return base;
  2353. }
  2354. if (const auto *indexing = dyn_cast<CXXOperatorCallExpr>(expr))
  2355. if (indexing->getOperator() == OverloadedOperatorKind::OO_Subscript) {
  2356. const Expr *thisBase =
  2357. indexing->getArg(0)->IgnoreParenNoopCasts(astContext);
  2358. const auto thisBaseType = thisBase->getType();
  2359. const Expr *base = collectArrayStructIndices(thisBase, indices);
  2360. // If the base is a StructureType, we need to push an addtional index 0
  2361. // here. This is because we created an additional OpTypeRuntimeArray
  2362. // in the structure.
  2363. if (isStructuredBuffer(thisBaseType))
  2364. indices->push_back(theBuilder.getConstantInt32(0));
  2365. if ((hlsl::IsHLSLVecType(thisBaseType) &&
  2366. (hlsl::GetHLSLVecSize(thisBaseType) == 1)) ||
  2367. typeTranslator.is1x1Matrix(thisBaseType) ||
  2368. typeTranslator.is1xNMatrix(thisBaseType)) {
  2369. // If this is a size-1 vector or 1xN matrix, ignore the index.
  2370. } else {
  2371. indices->push_back(doExpr(indexing->getArg(1)));
  2372. }
  2373. return base;
  2374. }
  2375. {
  2376. const Expr *index = nullptr;
  2377. // TODO: the following is duplicating the logic in doCXXMemberCallExpr.
  2378. if (const auto *object = isStructuredBufferLoad(expr, &index)) {
  2379. // For object.Load(index), there should be no more indexing into the
  2380. // object.
  2381. indices->push_back(theBuilder.getConstantInt32(0));
  2382. indices->push_back(doExpr(index));
  2383. return object;
  2384. }
  2385. }
  2386. // This the deepest we can go. No more array or struct indexing.
  2387. return expr;
  2388. }
  2389. uint32_t SPIRVEmitter::castToBool(const uint32_t fromVal, QualType fromType,
  2390. QualType toBoolType) {
  2391. if (isSameScalarOrVecType(fromType, toBoolType))
  2392. return fromVal;
  2393. // Converting to bool means comparing with value zero.
  2394. const spv::Op spvOp = translateOp(BO_NE, fromType);
  2395. const uint32_t boolType = typeTranslator.translateType(toBoolType);
  2396. const uint32_t zeroVal = getValueZero(fromType);
  2397. return theBuilder.createBinaryOp(spvOp, boolType, fromVal, zeroVal);
  2398. }
  2399. uint32_t SPIRVEmitter::castToInt(const uint32_t fromVal, QualType fromType,
  2400. QualType toIntType) {
  2401. if (isSameScalarOrVecType(fromType, toIntType))
  2402. return fromVal;
  2403. const uint32_t intType = typeTranslator.translateType(toIntType);
  2404. if (isBoolOrVecOfBoolType(fromType)) {
  2405. const uint32_t one = getValueOne(toIntType);
  2406. const uint32_t zero = getValueZero(toIntType);
  2407. return theBuilder.createSelect(intType, fromVal, one, zero);
  2408. }
  2409. if (isSintOrVecOfSintType(fromType) || isUintOrVecOfUintType(fromType)) {
  2410. // TODO: handle different bitwidths
  2411. return theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, fromVal);
  2412. }
  2413. if (isFloatOrVecOfFloatType(fromType)) {
  2414. if (isSintOrVecOfSintType(toIntType)) {
  2415. return theBuilder.createUnaryOp(spv::Op::OpConvertFToS, intType, fromVal);
  2416. } else if (isUintOrVecOfUintType(toIntType)) {
  2417. return theBuilder.createUnaryOp(spv::Op::OpConvertFToU, intType, fromVal);
  2418. } else {
  2419. emitError("unimplemented casting to integer from floating point");
  2420. }
  2421. } else {
  2422. emitError("unimplemented casting to integer");
  2423. }
  2424. return 0;
  2425. }
  2426. uint32_t SPIRVEmitter::castToFloat(const uint32_t fromVal, QualType fromType,
  2427. QualType toFloatType) {
  2428. if (isSameScalarOrVecType(fromType, toFloatType))
  2429. return fromVal;
  2430. const uint32_t floatType = typeTranslator.translateType(toFloatType);
  2431. if (isBoolOrVecOfBoolType(fromType)) {
  2432. const uint32_t one = getValueOne(toFloatType);
  2433. const uint32_t zero = getValueZero(toFloatType);
  2434. return theBuilder.createSelect(floatType, fromVal, one, zero);
  2435. }
  2436. if (isSintOrVecOfSintType(fromType)) {
  2437. return theBuilder.createUnaryOp(spv::Op::OpConvertSToF, floatType, fromVal);
  2438. }
  2439. if (isUintOrVecOfUintType(fromType)) {
  2440. return theBuilder.createUnaryOp(spv::Op::OpConvertUToF, floatType, fromVal);
  2441. }
  2442. if (isFloatOrVecOfFloatType(fromType)) {
  2443. emitError("casting between different fp bitwidth unimplemented");
  2444. return 0;
  2445. }
  2446. emitError("unimplemented casting to floating point");
  2447. return 0;
  2448. }
  2449. uint32_t SPIRVEmitter::processIntrinsicCallExpr(const CallExpr *callExpr) {
  2450. const FunctionDecl *callee = callExpr->getDirectCallee();
  2451. assert(hlsl::IsIntrinsicOp(callee) &&
  2452. "doIntrinsicCallExpr was called for a non-intrinsic function.");
  2453. const bool isFloatType = isFloatOrVecMatOfFloatType(callExpr->getType());
  2454. const bool isSintType = isSintOrVecMatOfSintType(callExpr->getType());
  2455. // Figure out which intrinsic function to translate.
  2456. llvm::StringRef group;
  2457. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  2458. hlsl::GetIntrinsicOp(callee, opcode, group);
  2459. GLSLstd450 glslOpcode = GLSLstd450Bad;
  2460. #define INTRINSIC_OP_CASE(intrinsicOp, glslOp, doEachVec) \
  2461. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  2462. glslOpcode = GLSLstd450::GLSLstd450##glslOp; \
  2463. return processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  2464. } break
  2465. #define INTRINSIC_OP_CASE_INT_FLOAT(intrinsicOp, glslIntOp, glslFloatOp, \
  2466. doEachVec) \
  2467. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  2468. glslOpcode = isFloatType ? GLSLstd450::GLSLstd450##glslFloatOp \
  2469. : GLSLstd450::GLSLstd450##glslIntOp; \
  2470. return processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  2471. } break
  2472. #define INTRINSIC_OP_CASE_SINT_UINT_FLOAT(intrinsicOp, glslSintOp, glslUintOp, \
  2473. glslFloatOp, doEachVec) \
  2474. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  2475. glslOpcode = isFloatType \
  2476. ? GLSLstd450::GLSLstd450##glslFloatOp \
  2477. : isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  2478. : GLSLstd450::GLSLstd450##glslUintOp; \
  2479. return processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  2480. } break
  2481. switch (static_cast<hlsl::IntrinsicOp>(opcode)) {
  2482. case hlsl::IntrinsicOp::IOP_dot:
  2483. return processIntrinsicDot(callExpr);
  2484. case hlsl::IntrinsicOp::IOP_mul:
  2485. return processIntrinsicMul(callExpr);
  2486. case hlsl::IntrinsicOp::IOP_all:
  2487. return processIntrinsicAllOrAny(callExpr, spv::Op::OpAll);
  2488. case hlsl::IntrinsicOp::IOP_any:
  2489. return processIntrinsicAllOrAny(callExpr, spv::Op::OpAny);
  2490. case hlsl::IntrinsicOp::IOP_asfloat:
  2491. case hlsl::IntrinsicOp::IOP_asint:
  2492. case hlsl::IntrinsicOp::IOP_asuint:
  2493. return processIntrinsicAsType(callExpr);
  2494. case hlsl::IntrinsicOp::IOP_clamp:
  2495. case hlsl::IntrinsicOp::IOP_uclamp:
  2496. return processIntrinsicClamp(callExpr);
  2497. case hlsl::IntrinsicOp::IOP_sign: {
  2498. if (isFloatOrVecMatOfFloatType(callExpr->getArg(0)->getType()))
  2499. return processIntrinsicFloatSign(callExpr);
  2500. else
  2501. return processIntrinsicUsingGLSLInst(callExpr,
  2502. GLSLstd450::GLSLstd450SSign,
  2503. /*actPerRowForMatrices*/ true);
  2504. }
  2505. INTRINSIC_OP_CASE(round, Round, true);
  2506. INTRINSIC_OP_CASE_INT_FLOAT(abs, SAbs, FAbs, true);
  2507. INTRINSIC_OP_CASE(acos, Acos, true);
  2508. INTRINSIC_OP_CASE(asin, Asin, true);
  2509. INTRINSIC_OP_CASE(atan, Atan, true);
  2510. INTRINSIC_OP_CASE(ceil, Ceil, true);
  2511. INTRINSIC_OP_CASE(cos, Cos, true);
  2512. INTRINSIC_OP_CASE(cosh, Cosh, true);
  2513. INTRINSIC_OP_CASE(cross, Cross, false);
  2514. INTRINSIC_OP_CASE(degrees, Degrees, true);
  2515. INTRINSIC_OP_CASE(radians, Radians, true);
  2516. INTRINSIC_OP_CASE(determinant, Determinant, false);
  2517. INTRINSIC_OP_CASE(exp, Exp, true);
  2518. INTRINSIC_OP_CASE(exp2, Exp2, true);
  2519. INTRINSIC_OP_CASE(floor, Floor, true);
  2520. INTRINSIC_OP_CASE(length, Length, false);
  2521. INTRINSIC_OP_CASE(log, Log, true);
  2522. INTRINSIC_OP_CASE(log2, Log2, true);
  2523. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(max, SMax, UMax, FMax, true);
  2524. INTRINSIC_OP_CASE(umax, UMax, true);
  2525. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(min, SMin, UMin, FMin, true);
  2526. INTRINSIC_OP_CASE(umin, UMin, true);
  2527. INTRINSIC_OP_CASE(normalize, Normalize, false);
  2528. INTRINSIC_OP_CASE(pow, Pow, true);
  2529. INTRINSIC_OP_CASE(reflect, Reflect, false);
  2530. INTRINSIC_OP_CASE(rsqrt, InverseSqrt, true);
  2531. INTRINSIC_OP_CASE(step, Step, true);
  2532. INTRINSIC_OP_CASE(sin, Sin, true);
  2533. INTRINSIC_OP_CASE(sinh, Sinh, true);
  2534. INTRINSIC_OP_CASE(tan, Tan, true);
  2535. INTRINSIC_OP_CASE(tanh, Tanh, true);
  2536. INTRINSIC_OP_CASE(sqrt, Sqrt, true);
  2537. INTRINSIC_OP_CASE(trunc, Trunc, true);
  2538. default:
  2539. emitError("Intrinsic function '%0' not yet implemented.")
  2540. << callee->getName();
  2541. return 0;
  2542. }
  2543. #undef INTRINSIC_OP_CASE
  2544. #undef INTRINSIC_OP_CASE_INT_FLOAT
  2545. return 0;
  2546. }
  2547. uint32_t SPIRVEmitter::processIntrinsicClamp(const CallExpr *callExpr) {
  2548. // According the HLSL reference: clamp(X, Min, Max) takes 3 arguments. Each
  2549. // one may be int, uint, or float.
  2550. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  2551. const QualType returnType = callExpr->getType();
  2552. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  2553. GLSLstd450 glslOpcode = GLSLstd450::GLSLstd450UClamp;
  2554. if (isFloatOrVecMatOfFloatType(returnType))
  2555. glslOpcode = GLSLstd450::GLSLstd450FClamp;
  2556. else if (isSintOrVecMatOfSintType(returnType))
  2557. glslOpcode = GLSLstd450::GLSLstd450SClamp;
  2558. // Get the function parameters. Expect 3 parameters.
  2559. assert(callExpr->getNumArgs() == 3u);
  2560. const Expr *argX = callExpr->getArg(0);
  2561. const Expr *argMin = callExpr->getArg(1);
  2562. const Expr *argMax = callExpr->getArg(2);
  2563. const uint32_t argXId = doExpr(argX);
  2564. const uint32_t argMinId = doExpr(argMin);
  2565. const uint32_t argMaxId = doExpr(argMax);
  2566. // FClamp, UClamp, and SClamp do not operate on matrices, so we should perform
  2567. // the operation on each vector of the matrix.
  2568. if (TypeTranslator::isSpirvAcceptableMatrixType(argX->getType())) {
  2569. const auto actOnEachVec = [this, glslInstSetId, glslOpcode, argMinId,
  2570. argMaxId](uint32_t index, uint32_t vecType,
  2571. uint32_t curRowId) {
  2572. const auto minRowId =
  2573. theBuilder.createCompositeExtract(vecType, argMinId, {index});
  2574. const auto maxRowId =
  2575. theBuilder.createCompositeExtract(vecType, argMaxId, {index});
  2576. return theBuilder.createExtInst(vecType, glslInstSetId, glslOpcode,
  2577. {curRowId, minRowId, maxRowId});
  2578. };
  2579. return processEachVectorInMatrix(argX, argXId, actOnEachVec);
  2580. }
  2581. return theBuilder.createExtInst(returnTypeId, glslInstSetId, glslOpcode,
  2582. {argXId, argMinId, argMaxId});
  2583. }
  2584. uint32_t SPIRVEmitter::processIntrinsicMul(const CallExpr *callExpr) {
  2585. const QualType returnType = callExpr->getType();
  2586. const uint32_t returnTypeId =
  2587. typeTranslator.translateType(callExpr->getType());
  2588. // Get the function parameters. Expect 2 parameters.
  2589. assert(callExpr->getNumArgs() == 2u);
  2590. const Expr *arg0 = callExpr->getArg(0);
  2591. const Expr *arg1 = callExpr->getArg(1);
  2592. const QualType arg0Type = arg0->getType();
  2593. const QualType arg1Type = arg1->getType();
  2594. // The HLSL mul() function takes 2 arguments. Each argument may be a scalar,
  2595. // vector, or matrix. The frontend ensures that the two arguments have the
  2596. // same component type. The only allowed component types are int and float.
  2597. // mul(scalar, vector)
  2598. {
  2599. uint32_t elemCount = 0;
  2600. if (TypeTranslator::isScalarType(arg0Type) &&
  2601. TypeTranslator::isVectorType(arg1Type, nullptr, &elemCount)) {
  2602. const uint32_t arg1Id = doExpr(arg1);
  2603. // We can use OpVectorTimesScalar if arguments are floats.
  2604. if (arg0Type->isFloatingType())
  2605. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  2606. returnTypeId, arg1Id, doExpr(arg0));
  2607. // Use OpIMul for integers
  2608. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId,
  2609. createVectorSplat(arg0, elemCount),
  2610. arg1Id);
  2611. }
  2612. }
  2613. // mul(vector, scalar)
  2614. {
  2615. uint32_t elemCount = 0;
  2616. if (TypeTranslator::isVectorType(arg0Type, nullptr, &elemCount) &&
  2617. TypeTranslator::isScalarType(arg1Type)) {
  2618. const uint32_t arg0Id = doExpr(arg0);
  2619. // We can use OpVectorTimesScalar if arguments are floats.
  2620. if (arg1Type->isFloatingType())
  2621. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  2622. returnTypeId, arg0Id, doExpr(arg1));
  2623. // Use OpIMul for integers
  2624. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId, arg0Id,
  2625. createVectorSplat(arg1, elemCount));
  2626. }
  2627. }
  2628. // mul(vector, vector)
  2629. if (TypeTranslator::isVectorType(arg0Type) &&
  2630. TypeTranslator::isVectorType(arg1Type))
  2631. return processIntrinsicDot(callExpr);
  2632. // All the following cases require handling arg0 and arg1 expressions first.
  2633. const uint32_t arg0Id = doExpr(arg0);
  2634. const uint32_t arg1Id = doExpr(arg1);
  2635. // mul(scalar, scalar)
  2636. if (TypeTranslator::isScalarType(arg0Type) &&
  2637. TypeTranslator::isScalarType(arg1Type))
  2638. return theBuilder.createBinaryOp(translateOp(BO_Mul, arg0Type),
  2639. returnTypeId, arg0Id, arg1Id);
  2640. // mul(scalar, matrix)
  2641. if (TypeTranslator::isScalarType(arg0Type) &&
  2642. TypeTranslator::isMxNMatrix(arg1Type)) {
  2643. // We currently only support float matrices. So we can use
  2644. // OpMatrixTimesScalar
  2645. if (arg0Type->isFloatingType())
  2646. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  2647. returnTypeId, arg1Id, arg0Id);
  2648. }
  2649. // mul(matrix, scalar)
  2650. if (TypeTranslator::isScalarType(arg1Type) &&
  2651. TypeTranslator::isMxNMatrix(arg0Type)) {
  2652. // We currently only support float matrices. So we can use
  2653. // OpMatrixTimesScalar
  2654. if (arg1Type->isFloatingType())
  2655. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  2656. returnTypeId, arg0Id, arg1Id);
  2657. }
  2658. // mul(vector, matrix)
  2659. {
  2660. QualType elemType = {};
  2661. uint32_t elemCount = 0, numRows = 0;
  2662. if (TypeTranslator::isVectorType(arg0Type, &elemType, &elemCount) &&
  2663. TypeTranslator::isMxNMatrix(arg1Type, nullptr, &numRows, nullptr) &&
  2664. elemType->isFloatingType()) {
  2665. assert(elemCount == numRows);
  2666. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesVector,
  2667. returnTypeId, arg1Id, arg0Id);
  2668. }
  2669. }
  2670. // mul(matrix, vector)
  2671. {
  2672. QualType elemType = {};
  2673. uint32_t elemCount = 0, numCols = 0;
  2674. if (TypeTranslator::isMxNMatrix(arg0Type, nullptr, nullptr, &numCols) &&
  2675. TypeTranslator::isVectorType(arg1Type, &elemType, &elemCount) &&
  2676. elemType->isFloatingType()) {
  2677. assert(elemCount == numCols);
  2678. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesMatrix,
  2679. returnTypeId, arg1Id, arg0Id);
  2680. }
  2681. }
  2682. // mul(matrix, matrix)
  2683. {
  2684. QualType elemType = {};
  2685. uint32_t arg0Cols = 0, arg1Rows = 0;
  2686. if (TypeTranslator::isMxNMatrix(arg0Type, &elemType, nullptr, &arg0Cols) &&
  2687. TypeTranslator::isMxNMatrix(arg1Type, nullptr, &arg1Rows, nullptr) &&
  2688. elemType->isFloatingType()) {
  2689. assert(arg0Cols == arg1Rows);
  2690. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesMatrix,
  2691. returnTypeId, arg1Id, arg0Id);
  2692. }
  2693. }
  2694. emitError("Unsupported arguments passed to mul() function.");
  2695. return 0;
  2696. }
  2697. uint32_t SPIRVEmitter::processIntrinsicDot(const CallExpr *callExpr) {
  2698. const QualType returnType = callExpr->getType();
  2699. const uint32_t returnTypeId =
  2700. typeTranslator.translateType(callExpr->getType());
  2701. // Get the function parameters. Expect 2 vectors as parameters.
  2702. assert(callExpr->getNumArgs() == 2u);
  2703. const Expr *arg0 = callExpr->getArg(0);
  2704. const Expr *arg1 = callExpr->getArg(1);
  2705. const uint32_t arg0Id = doExpr(arg0);
  2706. const uint32_t arg1Id = doExpr(arg1);
  2707. QualType arg0Type = arg0->getType();
  2708. QualType arg1Type = arg1->getType();
  2709. const size_t vec0Size = hlsl::GetHLSLVecSize(arg0Type);
  2710. const size_t vec1Size = hlsl::GetHLSLVecSize(arg1Type);
  2711. const QualType vec0ComponentType = hlsl::GetHLSLVecElementType(arg0Type);
  2712. const QualType vec1ComponentType = hlsl::GetHLSLVecElementType(arg1Type);
  2713. assert(returnType == vec1ComponentType);
  2714. assert(vec0ComponentType == vec1ComponentType);
  2715. assert(vec0Size == vec1Size);
  2716. assert(vec0Size >= 1 && vec0Size <= 4);
  2717. // According to HLSL reference, the dot function only works on integers
  2718. // and floats.
  2719. assert(returnType->isFloatingType() || returnType->isIntegerType());
  2720. // Special case: dot product of two vectors, each of size 1. That is
  2721. // basically the same as regular multiplication of 2 scalars.
  2722. if (vec0Size == 1) {
  2723. const spv::Op spvOp = translateOp(BO_Mul, arg0Type);
  2724. return theBuilder.createBinaryOp(spvOp, returnTypeId, arg0Id, arg1Id);
  2725. }
  2726. // If the vectors are of type Float, we can use OpDot.
  2727. if (returnType->isFloatingType()) {
  2728. return theBuilder.createBinaryOp(spv::Op::OpDot, returnTypeId, arg0Id,
  2729. arg1Id);
  2730. }
  2731. // Vector component type is Integer (signed or unsigned).
  2732. // Create all instructions necessary to perform a dot product on
  2733. // two integer vectors. SPIR-V OpDot does not support integer vectors.
  2734. // Therefore, we use other SPIR-V instructions (addition and
  2735. // multiplication).
  2736. else {
  2737. uint32_t result = 0;
  2738. llvm::SmallVector<uint32_t, 4> multIds;
  2739. const spv::Op multSpvOp = translateOp(BO_Mul, arg0Type);
  2740. const spv::Op addSpvOp = translateOp(BO_Add, arg0Type);
  2741. // Extract members from the two vectors and multiply them.
  2742. for (unsigned int i = 0; i < vec0Size; ++i) {
  2743. const uint32_t vec0member =
  2744. theBuilder.createCompositeExtract(returnTypeId, arg0Id, {i});
  2745. const uint32_t vec1member =
  2746. theBuilder.createCompositeExtract(returnTypeId, arg1Id, {i});
  2747. const uint32_t multId = theBuilder.createBinaryOp(multSpvOp, returnTypeId,
  2748. vec0member, vec1member);
  2749. multIds.push_back(multId);
  2750. }
  2751. // Add all the multiplications.
  2752. result = multIds[0];
  2753. for (unsigned int i = 1; i < vec0Size; ++i) {
  2754. const uint32_t additionId =
  2755. theBuilder.createBinaryOp(addSpvOp, returnTypeId, result, multIds[i]);
  2756. result = additionId;
  2757. }
  2758. return result;
  2759. }
  2760. }
  2761. uint32_t SPIRVEmitter::processIntrinsicAllOrAny(const CallExpr *callExpr,
  2762. spv::Op spvOp) {
  2763. // 'all' and 'any' take only 1 parameter.
  2764. assert(callExpr->getNumArgs() == 1u);
  2765. const QualType returnType = callExpr->getType();
  2766. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  2767. const Expr *arg = callExpr->getArg(0);
  2768. const QualType argType = arg->getType();
  2769. // Handle scalars, vectors of size 1, and 1x1 matrices as arguments.
  2770. // Optimization: can directly cast them to boolean. No need for OpAny/OpAll.
  2771. {
  2772. QualType scalarType = {};
  2773. if (TypeTranslator::isScalarType(argType, &scalarType) &&
  2774. (scalarType->isBooleanType() || scalarType->isFloatingType() ||
  2775. scalarType->isIntegerType()))
  2776. return castToBool(doExpr(arg), argType, returnType);
  2777. }
  2778. // Handle vectors larger than 1, Mx1 matrices, and 1xN matrices as arguments.
  2779. // Cast the vector to a boolean vector, then run OpAny/OpAll on it.
  2780. {
  2781. QualType elemType = {};
  2782. uint32_t size = 0;
  2783. if (TypeTranslator::isVectorType(argType, &elemType, &size)) {
  2784. const QualType castToBoolType =
  2785. astContext.getExtVectorType(returnType, size);
  2786. uint32_t castedToBoolId =
  2787. castToBool(doExpr(arg), argType, castToBoolType);
  2788. return theBuilder.createUnaryOp(spvOp, returnTypeId, castedToBoolId);
  2789. }
  2790. }
  2791. // Handle MxN matrices as arguments.
  2792. {
  2793. QualType elemType = {};
  2794. uint32_t matRowCount = 0, matColCount = 0;
  2795. if (TypeTranslator::isMxNMatrix(argType, &elemType, &matRowCount,
  2796. &matColCount)) {
  2797. if (!elemType->isFloatingType()) {
  2798. emitError("'all' and 'any' currently do not take non-floating point "
  2799. "matrices as argument.");
  2800. return 0;
  2801. }
  2802. uint32_t matrixId = doExpr(arg);
  2803. const uint32_t vecType = typeTranslator.getComponentVectorType(argType);
  2804. llvm::SmallVector<uint32_t, 4> rowResults;
  2805. for (uint32_t i = 0; i < matRowCount; ++i) {
  2806. // Extract the row which is a float vector of size matColCount.
  2807. const uint32_t rowFloatVec =
  2808. theBuilder.createCompositeExtract(vecType, matrixId, {i});
  2809. // Cast the float vector to boolean vector.
  2810. const auto rowFloatQualType =
  2811. astContext.getExtVectorType(elemType, matColCount);
  2812. const auto rowBoolQualType =
  2813. astContext.getExtVectorType(returnType, matColCount);
  2814. const uint32_t rowBoolVec =
  2815. castToBool(rowFloatVec, rowFloatQualType, rowBoolQualType);
  2816. // Perform OpAny/OpAll on the boolean vector.
  2817. rowResults.push_back(
  2818. theBuilder.createUnaryOp(spvOp, returnTypeId, rowBoolVec));
  2819. }
  2820. // Create a new vector that is the concatenation of results of all rows.
  2821. uint32_t boolId = theBuilder.getBoolType();
  2822. uint32_t vecOfBoolsId = theBuilder.getVecType(boolId, matRowCount);
  2823. const uint32_t rowResultsId =
  2824. theBuilder.createCompositeConstruct(vecOfBoolsId, rowResults);
  2825. // Run OpAny/OpAll on the newly-created vector.
  2826. return theBuilder.createUnaryOp(spvOp, returnTypeId, rowResultsId);
  2827. }
  2828. }
  2829. // All types should be handled already.
  2830. llvm_unreachable("Unknown argument type passed to all()/any().");
  2831. return 0;
  2832. }
  2833. uint32_t SPIRVEmitter::processIntrinsicAsType(const CallExpr *callExpr) {
  2834. const QualType returnType = callExpr->getType();
  2835. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  2836. assert(callExpr->getNumArgs() == 1u);
  2837. const Expr *arg = callExpr->getArg(0);
  2838. const QualType argType = arg->getType();
  2839. // asfloat may take a float or a float vector or a float matrix as argument.
  2840. // These cases would be a no-op.
  2841. if (returnType.getCanonicalType() == argType.getCanonicalType())
  2842. return doExpr(arg);
  2843. // SPIR-V does not support non-floating point matrices. So 'asint' and
  2844. // 'asuint' for MxN matrices are currently not supported.
  2845. if (TypeTranslator::isMxNMatrix(argType)) {
  2846. emitError("SPIR-V does not support non-floating point matrices. Thus, "
  2847. "'asint' and 'asuint' currently do not take matrix arguments.");
  2848. return 0;
  2849. }
  2850. return theBuilder.createUnaryOp(spv::Op::OpBitcast, returnTypeId,
  2851. doExpr(arg));
  2852. }
  2853. uint32_t SPIRVEmitter::processIntrinsicFloatSign(const CallExpr *callExpr) {
  2854. // Import the GLSL.std.450 extended instruction set.
  2855. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  2856. const Expr *arg = callExpr->getArg(0);
  2857. const QualType returnType = callExpr->getType();
  2858. const QualType argType = arg->getType();
  2859. assert(isFloatOrVecMatOfFloatType(argType));
  2860. const uint32_t argTypeId = typeTranslator.translateType(argType);
  2861. const uint32_t argId = doExpr(arg);
  2862. uint32_t floatSignResultId = 0;
  2863. // For matrices, we can perform the instruction on each vector of the matrix.
  2864. if (TypeTranslator::isSpirvAcceptableMatrixType(argType)) {
  2865. const auto actOnEachVec = [this, glslInstSetId](
  2866. uint32_t /*index*/, uint32_t vecType, uint32_t curRowId) {
  2867. return theBuilder.createExtInst(vecType, glslInstSetId,
  2868. GLSLstd450::GLSLstd450FSign, {curRowId});
  2869. };
  2870. floatSignResultId = processEachVectorInMatrix(arg, argId, actOnEachVec);
  2871. } else {
  2872. floatSignResultId = theBuilder.createExtInst(
  2873. argTypeId, glslInstSetId, GLSLstd450::GLSLstd450FSign, {argId});
  2874. }
  2875. return castToInt(floatSignResultId, arg->getType(), returnType);
  2876. }
  2877. uint32_t SPIRVEmitter::processIntrinsicUsingGLSLInst(
  2878. const CallExpr *callExpr, GLSLstd450 opcode, bool actPerRowForMatrices) {
  2879. // Import the GLSL.std.450 extended instruction set.
  2880. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  2881. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  2882. if (callExpr->getNumArgs() == 1u) {
  2883. const Expr *arg = callExpr->getArg(0);
  2884. const uint32_t argId = doExpr(arg);
  2885. // If the instruction does not operate on matrices, we can perform the
  2886. // instruction on each vector of the matrix.
  2887. if (actPerRowForMatrices &&
  2888. TypeTranslator::isSpirvAcceptableMatrixType(arg->getType())) {
  2889. const auto actOnEachVec = [this, glslInstSetId, opcode](
  2890. uint32_t /*index*/, uint32_t vecType, uint32_t curRowId) {
  2891. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  2892. {curRowId});
  2893. };
  2894. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  2895. }
  2896. return theBuilder.createExtInst(returnType, glslInstSetId, opcode, {argId});
  2897. } else if (callExpr->getNumArgs() == 2u) {
  2898. const Expr *arg0 = callExpr->getArg(0);
  2899. const Expr *arg1 = callExpr->getArg(1);
  2900. const uint32_t arg0Id = doExpr(arg0);
  2901. const uint32_t arg1Id = doExpr(arg1);
  2902. // If the instruction does not operate on matrices, we can perform the
  2903. // instruction on each vector of the matrix.
  2904. if (actPerRowForMatrices &&
  2905. TypeTranslator::isSpirvAcceptableMatrixType(arg0->getType())) {
  2906. const auto actOnEachVec = [this, glslInstSetId, opcode, arg1Id](
  2907. uint32_t index, uint32_t vecType, uint32_t arg0RowId) {
  2908. const uint32_t arg1RowId =
  2909. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  2910. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  2911. {arg0RowId, arg1RowId});
  2912. };
  2913. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  2914. }
  2915. return theBuilder.createExtInst(returnType, glslInstSetId, opcode,
  2916. {arg0Id, arg1Id});
  2917. }
  2918. emitError("Unsupported intrinsic function %0.")
  2919. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  2920. return 0;
  2921. }
  2922. uint32_t SPIRVEmitter::getValueZero(QualType type) {
  2923. {
  2924. QualType scalarType = {};
  2925. if (TypeTranslator::isScalarType(type, &scalarType)) {
  2926. if (scalarType->isSignedIntegerType()) {
  2927. return theBuilder.getConstantInt32(0);
  2928. }
  2929. if (scalarType->isUnsignedIntegerType()) {
  2930. return theBuilder.getConstantUint32(0);
  2931. }
  2932. if (scalarType->isFloatingType()) {
  2933. return theBuilder.getConstantFloat32(0.0);
  2934. }
  2935. }
  2936. }
  2937. {
  2938. QualType elemType = {};
  2939. uint32_t size = {};
  2940. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  2941. return getVecValueZero(elemType, size);
  2942. }
  2943. }
  2944. // TODO: Handle getValueZero for MxN matrices.
  2945. emitError("getting value 0 for type '%0' unimplemented")
  2946. << type.getAsString();
  2947. return 0;
  2948. }
  2949. uint32_t SPIRVEmitter::getVecValueZero(QualType elemType, uint32_t size) {
  2950. const uint32_t elemZeroId = getValueZero(elemType);
  2951. if (size == 1)
  2952. return elemZeroId;
  2953. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemZeroId);
  2954. const uint32_t vecType =
  2955. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  2956. return theBuilder.getConstantComposite(vecType, elements);
  2957. }
  2958. uint32_t SPIRVEmitter::getValueOne(QualType type) {
  2959. {
  2960. QualType scalarType = {};
  2961. if (TypeTranslator::isScalarType(type, &scalarType)) {
  2962. if (scalarType->isSignedIntegerType()) {
  2963. return theBuilder.getConstantInt32(1);
  2964. }
  2965. if (scalarType->isUnsignedIntegerType()) {
  2966. return theBuilder.getConstantUint32(1);
  2967. }
  2968. if (scalarType->isFloatingType()) {
  2969. return theBuilder.getConstantFloat32(1.0);
  2970. }
  2971. }
  2972. }
  2973. {
  2974. QualType elemType = {};
  2975. uint32_t size = {};
  2976. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  2977. return getVecValueOne(elemType, size);
  2978. }
  2979. }
  2980. emitError("getting value 1 for type '%0' unimplemented") << type;
  2981. return 0;
  2982. }
  2983. uint32_t SPIRVEmitter::getVecValueOne(QualType elemType, uint32_t size) {
  2984. const uint32_t elemOneId = getValueOne(elemType);
  2985. if (size == 1)
  2986. return elemOneId;
  2987. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemOneId);
  2988. const uint32_t vecType =
  2989. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  2990. return theBuilder.getConstantComposite(vecType, elements);
  2991. }
  2992. uint32_t SPIRVEmitter::getMatElemValueOne(QualType type) {
  2993. assert(hlsl::IsHLSLMatType(type));
  2994. const auto elemType = hlsl::GetHLSLMatElementType(type);
  2995. uint32_t rowCount = 0, colCount = 0;
  2996. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  2997. if (rowCount == 1 && colCount == 1)
  2998. return getValueOne(elemType);
  2999. if (colCount == 1)
  3000. return getVecValueOne(elemType, rowCount);
  3001. return getVecValueOne(elemType, colCount);
  3002. }
  3003. uint32_t SPIRVEmitter::translateAPValue(const APValue &value,
  3004. const QualType targetType) {
  3005. if (targetType->isBooleanType()) {
  3006. const bool boolValue = value.getInt().getBoolValue();
  3007. return theBuilder.getConstantBool(boolValue);
  3008. }
  3009. if (targetType->isIntegerType()) {
  3010. const llvm::APInt &intValue = value.getInt();
  3011. return translateAPInt(intValue, targetType);
  3012. }
  3013. if (targetType->isFloatingType()) {
  3014. const llvm::APFloat &floatValue = value.getFloat();
  3015. return translateAPFloat(floatValue, targetType);
  3016. }
  3017. if (hlsl::IsHLSLVecType(targetType)) {
  3018. const uint32_t vecType = typeTranslator.translateType(targetType);
  3019. const QualType elemType = hlsl::GetHLSLVecElementType(targetType);
  3020. const auto numElements = value.getVectorLength();
  3021. // Special case for vectors of size 1. SPIR-V doesn't support this vector
  3022. // size so we need to translate it to scalar values.
  3023. if (numElements == 1) {
  3024. return translateAPValue(value.getVectorElt(0), elemType);
  3025. }
  3026. llvm::SmallVector<uint32_t, 4> elements;
  3027. for (uint32_t i = 0; i < numElements; ++i) {
  3028. elements.push_back(translateAPValue(value.getVectorElt(i), elemType));
  3029. }
  3030. return theBuilder.getConstantComposite(vecType, elements);
  3031. }
  3032. emitError("APValue of type '%0' is not supported yet.") << value.getKind();
  3033. value.dump();
  3034. return 0;
  3035. }
  3036. uint32_t SPIRVEmitter::translateAPInt(const llvm::APInt &intValue,
  3037. QualType targetType) {
  3038. if (targetType->isSignedIntegerType()) {
  3039. // Try to see if this integer can be represented in 32-bit
  3040. if (intValue.isSignedIntN(32))
  3041. return theBuilder.getConstantInt32(
  3042. static_cast<int32_t>(intValue.getSExtValue()));
  3043. } else {
  3044. // Try to see if this integer can be represented in 32-bit
  3045. if (intValue.isIntN(32))
  3046. return theBuilder.getConstantUint32(
  3047. static_cast<uint32_t>(intValue.getZExtValue()));
  3048. }
  3049. emitError("APInt for target bitwidth '%0' is not supported yet.")
  3050. << astContext.getIntWidth(targetType);
  3051. return 0;
  3052. }
  3053. uint32_t SPIRVEmitter::translateAPFloat(const llvm::APFloat &floatValue,
  3054. QualType targetType) {
  3055. const auto &semantics = astContext.getFloatTypeSemantics(targetType);
  3056. const auto bitwidth = llvm::APFloat::getSizeInBits(semantics);
  3057. switch (bitwidth) {
  3058. case 32:
  3059. return theBuilder.getConstantFloat32(floatValue.convertToFloat());
  3060. default:
  3061. break;
  3062. }
  3063. emitError("APFloat for target bitwidth '%0' is not supported yet.")
  3064. << bitwidth;
  3065. return 0;
  3066. }
  3067. uint32_t SPIRVEmitter::tryToEvaluateAsConst(const Expr *expr) {
  3068. Expr::EvalResult evalResult;
  3069. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  3070. !evalResult.HasSideEffects) {
  3071. return translateAPValue(evalResult.Val, expr->getType());
  3072. }
  3073. return 0;
  3074. }
  3075. spv::ExecutionModel
  3076. SPIRVEmitter::getSpirvShaderStage(const hlsl::ShaderModel &model) {
  3077. // DXIL Models are:
  3078. // Profile (DXIL Model) : HLSL Shader Kind : SPIR-V Shader Stage
  3079. // vs_<version> : Vertex Shader : Vertex Shader
  3080. // hs_<version> : Hull Shader : Tassellation Control Shader
  3081. // ds_<version> : Domain Shader : Tessellation Evaluation Shader
  3082. // gs_<version> : Geometry Shader : Geometry Shader
  3083. // ps_<version> : Pixel Shader : Fragment Shader
  3084. // cs_<version> : Compute Shader : Compute Shader
  3085. switch (model.GetKind()) {
  3086. case hlsl::ShaderModel::Kind::Vertex:
  3087. return spv::ExecutionModel::Vertex;
  3088. case hlsl::ShaderModel::Kind::Hull:
  3089. return spv::ExecutionModel::TessellationControl;
  3090. case hlsl::ShaderModel::Kind::Domain:
  3091. return spv::ExecutionModel::TessellationEvaluation;
  3092. case hlsl::ShaderModel::Kind::Geometry:
  3093. return spv::ExecutionModel::Geometry;
  3094. case hlsl::ShaderModel::Kind::Pixel:
  3095. return spv::ExecutionModel::Fragment;
  3096. case hlsl::ShaderModel::Kind::Compute:
  3097. return spv::ExecutionModel::GLCompute;
  3098. default:
  3099. break;
  3100. }
  3101. llvm_unreachable("unknown shader model");
  3102. }
  3103. void SPIRVEmitter::AddRequiredCapabilitiesForShaderModel() {
  3104. if (shaderModel.IsHS() || shaderModel.IsDS()) {
  3105. theBuilder.requireCapability(spv::Capability::Tessellation);
  3106. emitError("Tasselation shaders are currently not supported.");
  3107. } else if (shaderModel.IsGS()) {
  3108. theBuilder.requireCapability(spv::Capability::Geometry);
  3109. emitError("Geometry shaders are currently not supported.");
  3110. } else {
  3111. theBuilder.requireCapability(spv::Capability::Shader);
  3112. }
  3113. }
  3114. void SPIRVEmitter::AddExecutionModeForEntryPoint(uint32_t entryPointId) {
  3115. if (shaderModel.IsPS()) {
  3116. theBuilder.addExecutionMode(entryPointId,
  3117. spv::ExecutionMode::OriginUpperLeft, {});
  3118. }
  3119. }
  3120. bool SPIRVEmitter::emitEntryFunctionWrapper(const FunctionDecl *decl,
  3121. const uint32_t entryFuncId) {
  3122. // Construct the wrapper function signature.
  3123. const uint32_t voidType = theBuilder.getVoidType();
  3124. const uint32_t funcType = theBuilder.getFunctionType(voidType, {});
  3125. // The wrapper entry function surely does not have pre-assigned <result-id>
  3126. // for it like other functions that got added to the work queue following
  3127. // function calls. And the wrapper is the entry function.
  3128. entryFunctionId =
  3129. theBuilder.beginFunction(funcType, voidType, decl->getName());
  3130. declIdMapper.setEntryFunctionId(entryFunctionId);
  3131. // Handle translation of numthreads attribute for compute shaders.
  3132. if (shaderModel.IsCS()) {
  3133. // Number of threads attributes are stored as integers. We cast them to
  3134. // uint32_t to pass to OpExecutionMode SPIR-V instruction.
  3135. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  3136. theBuilder.addExecutionMode(
  3137. entryFunctionId, spv::ExecutionMode::LocalSize,
  3138. {static_cast<uint32_t>(numThreadsAttr->getX()),
  3139. static_cast<uint32_t>(numThreadsAttr->getY()),
  3140. static_cast<uint32_t>(numThreadsAttr->getZ())});
  3141. } else {
  3142. theBuilder.addExecutionMode(entryFunctionId,
  3143. spv::ExecutionMode::LocalSize, {1, 1, 1});
  3144. }
  3145. }
  3146. // The entry basic block.
  3147. const uint32_t entryLabel = theBuilder.createBasicBlock();
  3148. theBuilder.setInsertPoint(entryLabel);
  3149. // Initialize all global variables at the beginning of the wrapper
  3150. for (const VarDecl *varDecl : toInitGloalVars)
  3151. theBuilder.createStore(declIdMapper.getDeclResultId(varDecl),
  3152. doExpr(varDecl->getInit()));
  3153. // Create temporary variables for holding function call arguments
  3154. llvm::SmallVector<uint32_t, 4> params;
  3155. for (const auto *param : decl->params()) {
  3156. const uint32_t typeId = typeTranslator.translateType(param->getType());
  3157. std::string tempVarName = "param.var." + param->getNameAsString();
  3158. const uint32_t tempVar = theBuilder.addFnVar(typeId, tempVarName);
  3159. params.push_back(tempVar);
  3160. // Create the stage input variable for parameter not marked as pure out and
  3161. // initialize the corresponding temporary variable
  3162. if (!param->getAttr<HLSLOutAttr>()) {
  3163. uint32_t loadedValue = 0;
  3164. if (!declIdMapper.createStageInputVar(param, &loadedValue))
  3165. return false;
  3166. theBuilder.createStore(tempVar, loadedValue);
  3167. }
  3168. }
  3169. // Call the original entry function
  3170. const uint32_t retType = typeTranslator.translateType(decl->getReturnType());
  3171. const uint32_t retVal =
  3172. theBuilder.createFunctionCall(retType, entryFuncId, params);
  3173. // Create and write stage output variables for return value
  3174. if (!declIdMapper.createStageOutputVar(decl, retVal))
  3175. return false;
  3176. // Create and write stage output variables for parameters marked as out/inout
  3177. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  3178. const auto *param = decl->getParamDecl(i);
  3179. if (param->getAttr<HLSLOutAttr>() || param->getAttr<HLSLInOutAttr>()) {
  3180. // Load the value from the parameter after function call
  3181. const uint32_t typeId = typeTranslator.translateType(param->getType());
  3182. const uint32_t loadedParam = theBuilder.createLoad(typeId, params[i]);
  3183. if (!declIdMapper.createStageOutputVar(param, loadedParam))
  3184. return false;
  3185. }
  3186. }
  3187. theBuilder.createReturn();
  3188. theBuilder.endFunction();
  3189. return true;
  3190. }
  3191. bool SPIRVEmitter::allSwitchCasesAreIntegerLiterals(const Stmt *root) {
  3192. if (!root)
  3193. return false;
  3194. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  3195. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  3196. if (!caseStmt && !compoundStmt)
  3197. return true;
  3198. if (caseStmt) {
  3199. const Expr *caseExpr = caseStmt->getLHS();
  3200. return caseExpr && caseExpr->isEvaluatable(astContext);
  3201. }
  3202. // Recurse down if facing a compound statement.
  3203. for (auto *st : compoundStmt->body())
  3204. if (!allSwitchCasesAreIntegerLiterals(st))
  3205. return false;
  3206. return true;
  3207. }
  3208. void SPIRVEmitter::discoverAllCaseStmtInSwitchStmt(
  3209. const Stmt *root, uint32_t *defaultBB,
  3210. std::vector<std::pair<uint32_t, uint32_t>> *targets) {
  3211. if (!root)
  3212. return;
  3213. // A switch case can only appear in DefaultStmt, CaseStmt, or
  3214. // CompoundStmt. For the rest, we can just return.
  3215. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  3216. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  3217. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  3218. if (!defaultStmt && !caseStmt && !compoundStmt)
  3219. return;
  3220. // Recurse down if facing a compound statement.
  3221. if (compoundStmt) {
  3222. for (auto *st : compoundStmt->body())
  3223. discoverAllCaseStmtInSwitchStmt(st, defaultBB, targets);
  3224. return;
  3225. }
  3226. std::string caseLabel;
  3227. uint32_t caseValue = 0;
  3228. if (defaultStmt) {
  3229. // This is the default branch.
  3230. caseLabel = "switch.default";
  3231. } else if (caseStmt) {
  3232. // This is a non-default case.
  3233. // When using OpSwitch, we only allow integer literal cases. e.g:
  3234. // case <literal_integer>: {...; break;}
  3235. const Expr *caseExpr = caseStmt->getLHS();
  3236. assert(caseExpr && caseExpr->isEvaluatable(astContext));
  3237. auto bitWidth = astContext.getIntWidth(caseExpr->getType());
  3238. if (bitWidth != 32)
  3239. emitError("Switch statement translation currently only supports 32-bit "
  3240. "integer case values.");
  3241. Expr::EvalResult evalResult;
  3242. caseExpr->EvaluateAsRValue(evalResult, astContext);
  3243. const int64_t value = evalResult.Val.getInt().getSExtValue();
  3244. caseValue = static_cast<uint32_t>(value);
  3245. caseLabel = "switch." + std::string(value < 0 ? "n" : "") +
  3246. llvm::itostr(std::abs(value));
  3247. }
  3248. const uint32_t caseBB = theBuilder.createBasicBlock(caseLabel);
  3249. theBuilder.addSuccessor(caseBB);
  3250. stmtBasicBlock[root] = caseBB;
  3251. // Add all cases to the 'targets' vector.
  3252. if (caseStmt)
  3253. targets->emplace_back(caseValue, caseBB);
  3254. // The default label is not part of the 'targets' vector that is passed
  3255. // to the OpSwitch instruction.
  3256. // If default statement was discovered, return its label via defaultBB.
  3257. if (defaultStmt)
  3258. *defaultBB = caseBB;
  3259. // Process cases nested in other cases. It happens when we have fall through
  3260. // cases. For example:
  3261. // case 1: case 2: ...; break;
  3262. // will result in the CaseSmt for case 2 nested in the one for case 1.
  3263. discoverAllCaseStmtInSwitchStmt(caseStmt ? caseStmt->getSubStmt()
  3264. : defaultStmt->getSubStmt(),
  3265. defaultBB, targets);
  3266. }
  3267. void SPIRVEmitter::flattenSwitchStmtAST(const Stmt *root,
  3268. std::vector<const Stmt *> *flatSwitch) {
  3269. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  3270. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  3271. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  3272. if (!compoundStmt) {
  3273. flatSwitch->push_back(root);
  3274. }
  3275. if (compoundStmt) {
  3276. for (const auto *st : compoundStmt->body())
  3277. flattenSwitchStmtAST(st, flatSwitch);
  3278. } else if (caseStmt) {
  3279. flattenSwitchStmtAST(caseStmt->getSubStmt(), flatSwitch);
  3280. } else if (defaultStmt) {
  3281. flattenSwitchStmtAST(defaultStmt->getSubStmt(), flatSwitch);
  3282. }
  3283. }
  3284. void SPIRVEmitter::processCaseStmtOrDefaultStmt(const Stmt *stmt) {
  3285. auto *caseStmt = dyn_cast<CaseStmt>(stmt);
  3286. auto *defaultStmt = dyn_cast<DefaultStmt>(stmt);
  3287. assert(caseStmt || defaultStmt);
  3288. uint32_t caseBB = stmtBasicBlock[stmt];
  3289. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  3290. // We are about to handle the case passed in as parameter. If the current
  3291. // basic block is not terminated, it means the previous case is a fall
  3292. // through case. We need to link it to the case to be processed.
  3293. theBuilder.createBranch(caseBB);
  3294. theBuilder.addSuccessor(caseBB);
  3295. }
  3296. theBuilder.setInsertPoint(caseBB);
  3297. doStmt(caseStmt ? caseStmt->getSubStmt() : defaultStmt->getSubStmt());
  3298. }
  3299. void SPIRVEmitter::processSwitchStmtUsingSpirvOpSwitch(
  3300. const SwitchStmt *switchStmt) {
  3301. // First handle the condition variable DeclStmt if one exists.
  3302. // For example: handle 'int a = b' in the following:
  3303. // switch (int a = b) {...}
  3304. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  3305. doDeclStmt(condVarDeclStmt);
  3306. const uint32_t selector = doExpr(switchStmt->getCond());
  3307. // We need a merge block regardless of the number of switch cases.
  3308. // Since OpSwitch always requires a default label, if the switch statement
  3309. // does not have a default branch, we use the merge block as the default
  3310. // target.
  3311. const uint32_t mergeBB = theBuilder.createBasicBlock("switch.merge");
  3312. theBuilder.setMergeTarget(mergeBB);
  3313. breakStack.push(mergeBB);
  3314. uint32_t defaultBB = mergeBB;
  3315. // (literal, labelId) pairs to pass to the OpSwitch instruction.
  3316. std::vector<std::pair<uint32_t, uint32_t>> targets;
  3317. discoverAllCaseStmtInSwitchStmt(switchStmt->getBody(), &defaultBB, &targets);
  3318. // Create the OpSelectionMerge and OpSwitch.
  3319. theBuilder.createSwitch(mergeBB, selector, defaultBB, targets);
  3320. // Handle the switch body.
  3321. doStmt(switchStmt->getBody());
  3322. if (!theBuilder.isCurrentBasicBlockTerminated())
  3323. theBuilder.createBranch(mergeBB);
  3324. theBuilder.setInsertPoint(mergeBB);
  3325. breakStack.pop();
  3326. }
  3327. void SPIRVEmitter::processSwitchStmtUsingIfStmts(const SwitchStmt *switchStmt) {
  3328. std::vector<const Stmt *> flatSwitch;
  3329. flattenSwitchStmtAST(switchStmt->getBody(), &flatSwitch);
  3330. // First handle the condition variable DeclStmt if one exists.
  3331. // For example: handle 'int a = b' in the following:
  3332. // switch (int a = b) {...}
  3333. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  3334. doDeclStmt(condVarDeclStmt);
  3335. // Figure out the indexes of CaseStmts (and DefaultStmt if it exists) in
  3336. // the flattened switch AST.
  3337. // For instance, for the following flat vector:
  3338. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  3339. // |Case1|Stmt1|Case2|Stmt2|Break|Case3|Case4|Stmt4|Break|Default|Stmt5|
  3340. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  3341. // The indexes are: {0, 2, 5, 6, 9}
  3342. std::vector<uint32_t> caseStmtLocs;
  3343. for (uint32_t i = 0; i < flatSwitch.size(); ++i)
  3344. if (isa<CaseStmt>(flatSwitch[i]) || isa<DefaultStmt>(flatSwitch[i]))
  3345. caseStmtLocs.push_back(i);
  3346. IfStmt *prevIfStmt = nullptr;
  3347. IfStmt *rootIfStmt = nullptr;
  3348. CompoundStmt *defaultBody = nullptr;
  3349. // For each case, start at its index in the vector, and go forward
  3350. // accumulating statements until BreakStmt or end of vector is reached.
  3351. for (auto curCaseIndex : caseStmtLocs) {
  3352. const Stmt *curCase = flatSwitch[curCaseIndex];
  3353. // CompoundStmt to hold all statements for this case.
  3354. CompoundStmt *cs = new (astContext) CompoundStmt(Stmt::EmptyShell());
  3355. // Accumulate all non-case/default/break statements as the body for the
  3356. // current case.
  3357. std::vector<Stmt *> statements;
  3358. for (int i = curCaseIndex + 1;
  3359. i < flatSwitch.size() && !isa<BreakStmt>(flatSwitch[i]); ++i) {
  3360. if (!isa<CaseStmt>(flatSwitch[i]) && !isa<DefaultStmt>(flatSwitch[i]))
  3361. statements.push_back(const_cast<Stmt *>(flatSwitch[i]));
  3362. }
  3363. if (!statements.empty())
  3364. cs->setStmts(astContext, statements.data(), statements.size());
  3365. // For non-default cases, generate the IfStmt that compares the switch
  3366. // value to the case value.
  3367. if (auto *caseStmt = dyn_cast<CaseStmt>(curCase)) {
  3368. IfStmt *curIf = new (astContext) IfStmt(Stmt::EmptyShell());
  3369. BinaryOperator *bo = new (astContext) BinaryOperator(Stmt::EmptyShell());
  3370. bo->setLHS(const_cast<Expr *>(switchStmt->getCond()));
  3371. bo->setRHS(const_cast<Expr *>(caseStmt->getLHS()));
  3372. bo->setOpcode(BO_EQ);
  3373. bo->setType(astContext.getLogicalOperationType());
  3374. curIf->setCond(bo);
  3375. curIf->setThen(cs);
  3376. // No conditional variable associated with this faux if statement.
  3377. curIf->setConditionVariable(astContext, nullptr);
  3378. // Each If statement is the "else" of the previous if statement.
  3379. if (prevIfStmt)
  3380. prevIfStmt->setElse(curIf);
  3381. else
  3382. rootIfStmt = curIf;
  3383. prevIfStmt = curIf;
  3384. } else {
  3385. // Record the DefaultStmt body as it will be used as the body of the
  3386. // "else" block in the if-elseif-...-else pattern.
  3387. defaultBody = cs;
  3388. }
  3389. }
  3390. // If a default case exists, it is the "else" of the last if statement.
  3391. if (prevIfStmt)
  3392. prevIfStmt->setElse(defaultBody);
  3393. // Since all else-if and else statements are the child nodes of the first
  3394. // IfStmt, we only need to call doStmt for the first IfStmt.
  3395. if (rootIfStmt)
  3396. doStmt(rootIfStmt);
  3397. // If there are no CaseStmt and there is only 1 DefaultStmt, there will be
  3398. // no if statements. The switch in that case only executes the body of the
  3399. // default case.
  3400. else if (defaultBody)
  3401. doStmt(defaultBody);
  3402. }
  3403. } // end namespace spirv
  3404. } // end namespace clang