SpirvEmitter.cpp 466 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694
  1. //===------- SpirvEmitter.cpp - 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 "AlignmentSizeCalculator.h"
  15. #include "RawBufferMethods.h"
  16. #include "dxc/HlslIntrinsicOp.h"
  17. #include "spirv-tools/optimizer.hpp"
  18. #include "clang/SPIRV/AstTypeProbe.h"
  19. #include "clang/Sema/Sema.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "InitListHandler.h"
  22. #include "dxc/DXIL/DxilConstants.h"
  23. #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO
  24. #include "clang/Basic/Version.h"
  25. #else
  26. namespace clang {
  27. uint32_t getGitCommitCount() { return 0; }
  28. const char *getGitCommitHash() { return "<unknown-hash>"; }
  29. } // namespace clang
  30. #endif // SUPPORT_QUERY_GIT_COMMIT_INFO
  31. namespace clang {
  32. namespace spirv {
  33. namespace {
  34. // Returns true if the given decl has the given semantic.
  35. bool hasSemantic(const DeclaratorDecl *decl,
  36. hlsl::DXIL::SemanticKind semanticKind) {
  37. using namespace hlsl;
  38. for (auto *annotation : decl->getUnusualAnnotations()) {
  39. if (auto *semanticDecl = dyn_cast<SemanticDecl>(annotation)) {
  40. llvm::StringRef semanticName;
  41. uint32_t semanticIndex = 0;
  42. Semantic::DecomposeNameAndIndex(semanticDecl->SemanticName, &semanticName,
  43. &semanticIndex);
  44. const auto *semantic = Semantic::GetByName(semanticName);
  45. if (semantic->GetKind() == semanticKind)
  46. return true;
  47. }
  48. }
  49. return false;
  50. }
  51. bool patchConstFuncTakesHullOutputPatch(FunctionDecl *pcf) {
  52. for (const auto *param : pcf->parameters())
  53. if (hlsl::IsHLSLOutputPatchType(param->getType()))
  54. return true;
  55. return false;
  56. }
  57. inline bool isSpirvMatrixOp(spv::Op opcode) {
  58. return opcode == spv::Op::OpMatrixTimesMatrix ||
  59. opcode == spv::Op::OpMatrixTimesVector ||
  60. opcode == spv::Op::OpMatrixTimesScalar;
  61. }
  62. /// If expr is a (RW)StructuredBuffer.Load(), returns the object and writes
  63. /// index. Otherwiser, returns false.
  64. // TODO: The following doesn't handle Load(int, int) yet. And it is basically a
  65. // duplicate of doCXXMemberCallExpr.
  66. const Expr *isStructuredBufferLoad(const Expr *expr, const Expr **index) {
  67. using namespace hlsl;
  68. if (const auto *indexing = dyn_cast<CXXMemberCallExpr>(expr)) {
  69. const auto *callee = indexing->getDirectCallee();
  70. uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
  71. llvm::StringRef group;
  72. if (GetIntrinsicOp(callee, opcode, group)) {
  73. if (static_cast<IntrinsicOp>(opcode) == IntrinsicOp::MOP_Load) {
  74. const auto *object = indexing->getImplicitObjectArgument();
  75. if (isStructuredBuffer(object->getType())) {
  76. *index = indexing->getArg(0);
  77. return indexing->getImplicitObjectArgument();
  78. }
  79. }
  80. }
  81. }
  82. return nullptr;
  83. }
  84. /// Returns true if the given VarDecl will be translated into a SPIR-V variable
  85. /// not in the Private or Function storage class.
  86. inline bool isExternalVar(const VarDecl *var) {
  87. // Class static variables should be put in the Private storage class.
  88. // groupshared variables are allowed to be declared as "static". But we still
  89. // need to put them in the Workgroup storage class. That is, when seeing
  90. // "static groupshared", ignore "static".
  91. return var->hasExternalFormalLinkage()
  92. ? !var->isStaticDataMember()
  93. : (var->getAttr<HLSLGroupSharedAttr>() != nullptr);
  94. }
  95. /// Returns the referenced variable's DeclContext if the given expr is
  96. /// a DeclRefExpr referencing a ConstantBuffer/TextureBuffer. Otherwise,
  97. /// returns nullptr.
  98. const DeclContext *isConstantTextureBufferDeclRef(const Expr *expr) {
  99. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr->IgnoreParenCasts()))
  100. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  101. if (isConstantTextureBuffer(varDecl))
  102. return varDecl->getType()->getAs<RecordType>()->getDecl();
  103. return nullptr;
  104. }
  105. /// Returns true if
  106. /// * the given expr is an DeclRefExpr referencing a kind of structured or byte
  107. /// buffer and it is non-alias one, or
  108. /// * the given expr is an CallExpr returning a kind of structured or byte
  109. /// buffer.
  110. /// * the given expr is an ArraySubscriptExpr referencing a kind of structured
  111. /// or byte buffer.
  112. ///
  113. /// Note: legalization specific code
  114. bool isReferencingNonAliasStructuredOrByteBuffer(const Expr *expr) {
  115. expr = expr->IgnoreParenCasts();
  116. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  117. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  118. if (isAKindOfStructuredOrByteBuffer(varDecl->getType()))
  119. return isExternalVar(varDecl);
  120. } else if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  121. if (isAKindOfStructuredOrByteBuffer(callExpr->getType()))
  122. return true;
  123. } else if (const auto *arrSubExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  124. return isReferencingNonAliasStructuredOrByteBuffer(arrSubExpr->getBase());
  125. }
  126. return false;
  127. }
  128. bool spirvToolsLegalize(spv_target_env env, std::vector<uint32_t> *mod,
  129. std::string *messages) {
  130. spvtools::Optimizer optimizer(env);
  131. optimizer.SetMessageConsumer(
  132. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  133. const spv_position_t & /*position*/,
  134. const char *message) { *messages += message; });
  135. spvtools::OptimizerOptions options;
  136. options.set_run_validator(false);
  137. optimizer.RegisterLegalizationPasses();
  138. optimizer.RegisterPass(spvtools::CreateReplaceInvalidOpcodePass());
  139. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  140. return optimizer.Run(mod->data(), mod->size(), mod, options);
  141. }
  142. bool spirvToolsOptimize(spv_target_env env, std::vector<uint32_t> *mod,
  143. clang::spirv::SpirvCodeGenOptions &spirvOptions,
  144. std::string *messages) {
  145. spvtools::Optimizer optimizer(env);
  146. optimizer.SetMessageConsumer(
  147. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  148. const spv_position_t & /*position*/,
  149. const char *message) { *messages += message; });
  150. spvtools::OptimizerOptions options;
  151. options.set_run_validator(false);
  152. if (spirvOptions.optConfig.empty()) {
  153. optimizer.RegisterPerformancePasses();
  154. if (spirvOptions.flattenResourceArrays)
  155. optimizer.RegisterPass(spvtools::CreateDescriptorScalarReplacementPass());
  156. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  157. } else {
  158. // Command line options use llvm::SmallVector and llvm::StringRef, whereas
  159. // SPIR-V optimizer uses std::vector and std::string.
  160. std::vector<std::string> stdFlags;
  161. for (const auto &f : spirvOptions.optConfig)
  162. stdFlags.push_back(f.str());
  163. if (!optimizer.RegisterPassesFromFlags(stdFlags))
  164. return false;
  165. }
  166. return optimizer.Run(mod->data(), mod->size(), mod, options);
  167. }
  168. bool spirvToolsValidate(spv_target_env env, const SpirvCodeGenOptions &opts,
  169. bool beforeHlslLegalization, std::vector<uint32_t> *mod,
  170. std::string *messages) {
  171. spvtools::SpirvTools tools(env);
  172. tools.SetMessageConsumer(
  173. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  174. const spv_position_t & /*position*/,
  175. const char *message) { *messages += message; });
  176. spvtools::ValidatorOptions options;
  177. options.SetBeforeHlslLegalization(beforeHlslLegalization);
  178. // GL: strict block layout rules
  179. // VK: relaxed block layout rules
  180. // DX: Skip block layout rules
  181. if (opts.useScalarLayout || opts.useDxLayout) {
  182. options.SetScalarBlockLayout(true);
  183. } else if (opts.useGlLayout) {
  184. // spirv-val by default checks this.
  185. } else {
  186. options.SetRelaxBlockLayout(true);
  187. }
  188. return tools.Validate(mod->data(), mod->size(), options);
  189. }
  190. /// Translates atomic HLSL opcodes into the equivalent SPIR-V opcode.
  191. spv::Op translateAtomicHlslOpcodeToSpirvOpcode(hlsl::IntrinsicOp opcode) {
  192. using namespace hlsl;
  193. using namespace spv;
  194. switch (opcode) {
  195. case IntrinsicOp::IOP_InterlockedAdd:
  196. case IntrinsicOp::MOP_InterlockedAdd:
  197. return Op::OpAtomicIAdd;
  198. case IntrinsicOp::IOP_InterlockedAnd:
  199. case IntrinsicOp::MOP_InterlockedAnd:
  200. return Op::OpAtomicAnd;
  201. case IntrinsicOp::IOP_InterlockedOr:
  202. case IntrinsicOp::MOP_InterlockedOr:
  203. return Op::OpAtomicOr;
  204. case IntrinsicOp::IOP_InterlockedXor:
  205. case IntrinsicOp::MOP_InterlockedXor:
  206. return Op::OpAtomicXor;
  207. case IntrinsicOp::IOP_InterlockedUMax:
  208. case IntrinsicOp::MOP_InterlockedUMax:
  209. return Op::OpAtomicUMax;
  210. case IntrinsicOp::IOP_InterlockedUMin:
  211. case IntrinsicOp::MOP_InterlockedUMin:
  212. return Op::OpAtomicUMin;
  213. case IntrinsicOp::IOP_InterlockedMax:
  214. case IntrinsicOp::MOP_InterlockedMax:
  215. return Op::OpAtomicSMax;
  216. case IntrinsicOp::IOP_InterlockedMin:
  217. case IntrinsicOp::MOP_InterlockedMin:
  218. return Op::OpAtomicSMin;
  219. case IntrinsicOp::IOP_InterlockedExchange:
  220. case IntrinsicOp::MOP_InterlockedExchange:
  221. return Op::OpAtomicExchange;
  222. default:
  223. // Only atomic opcodes are relevant.
  224. break;
  225. }
  226. assert(false && "unimplemented hlsl intrinsic opcode");
  227. return Op::Max;
  228. }
  229. // Returns true if the given opcode is an accepted binary opcode in
  230. // OpSpecConstantOp.
  231. bool isAcceptedSpecConstantBinaryOp(spv::Op op) {
  232. switch (op) {
  233. case spv::Op::OpIAdd:
  234. case spv::Op::OpISub:
  235. case spv::Op::OpIMul:
  236. case spv::Op::OpUDiv:
  237. case spv::Op::OpSDiv:
  238. case spv::Op::OpUMod:
  239. case spv::Op::OpSRem:
  240. case spv::Op::OpSMod:
  241. case spv::Op::OpShiftRightLogical:
  242. case spv::Op::OpShiftRightArithmetic:
  243. case spv::Op::OpShiftLeftLogical:
  244. case spv::Op::OpBitwiseOr:
  245. case spv::Op::OpBitwiseXor:
  246. case spv::Op::OpBitwiseAnd:
  247. case spv::Op::OpVectorShuffle:
  248. case spv::Op::OpCompositeExtract:
  249. case spv::Op::OpCompositeInsert:
  250. case spv::Op::OpLogicalOr:
  251. case spv::Op::OpLogicalAnd:
  252. case spv::Op::OpLogicalNot:
  253. case spv::Op::OpLogicalEqual:
  254. case spv::Op::OpLogicalNotEqual:
  255. case spv::Op::OpIEqual:
  256. case spv::Op::OpINotEqual:
  257. case spv::Op::OpULessThan:
  258. case spv::Op::OpSLessThan:
  259. case spv::Op::OpUGreaterThan:
  260. case spv::Op::OpSGreaterThan:
  261. case spv::Op::OpULessThanEqual:
  262. case spv::Op::OpSLessThanEqual:
  263. case spv::Op::OpUGreaterThanEqual:
  264. case spv::Op::OpSGreaterThanEqual:
  265. return true;
  266. default:
  267. // Accepted binary opcodes return true. Anything else is false.
  268. return false;
  269. }
  270. return false;
  271. }
  272. /// Returns true if the given expression is an accepted initializer for a spec
  273. /// constant.
  274. bool isAcceptedSpecConstantInit(const Expr *init) {
  275. // Allow numeric casts
  276. init = init->IgnoreParenCasts();
  277. if (isa<CXXBoolLiteralExpr>(init) || isa<IntegerLiteral>(init) ||
  278. isa<FloatingLiteral>(init))
  279. return true;
  280. // Allow the minus operator which is used to specify negative values
  281. if (const auto *unaryOp = dyn_cast<UnaryOperator>(init))
  282. return unaryOp->getOpcode() == UO_Minus &&
  283. isAcceptedSpecConstantInit(unaryOp->getSubExpr());
  284. return false;
  285. }
  286. /// Returns true if the given function parameter can act as shader stage
  287. /// input parameter.
  288. inline bool canActAsInParmVar(const ParmVarDecl *param) {
  289. // If the parameter has no in/out/inout attribute, it is defaulted to
  290. // an in parameter.
  291. return !param->hasAttr<HLSLOutAttr>() &&
  292. // GS output streams are marked as inout, but it should not be
  293. // used as in parameter.
  294. !hlsl::IsHLSLStreamOutputType(param->getType());
  295. }
  296. /// Returns true if the given function parameter can act as shader stage
  297. /// output parameter.
  298. inline bool canActAsOutParmVar(const ParmVarDecl *param) {
  299. return param->hasAttr<HLSLOutAttr>() || param->hasAttr<HLSLInOutAttr>() ||
  300. hlsl::IsHLSLRayQueryType(param->getType());
  301. }
  302. /// Returns true if the given expression is of builtin type and can be evaluated
  303. /// to a constant zero. Returns false otherwise.
  304. inline bool evaluatesToConstZero(const Expr *expr, ASTContext &astContext) {
  305. const auto type = expr->getType();
  306. if (!type->isBuiltinType())
  307. return false;
  308. Expr::EvalResult evalResult;
  309. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  310. !evalResult.HasSideEffects) {
  311. const auto &val = evalResult.Val;
  312. return ((type->isBooleanType() && !val.getInt().getBoolValue()) ||
  313. (type->isIntegerType() && !val.getInt().getBoolValue()) ||
  314. (type->isFloatingType() && val.getFloat().isZero()));
  315. }
  316. return false;
  317. }
  318. /// Returns the HLSLBufferDecl if the given VarDecl is inside a cbuffer/tbuffer.
  319. /// Returns nullptr otherwise, including varDecl is a ConstantBuffer or
  320. /// TextureBuffer itself.
  321. inline const HLSLBufferDecl *getCTBufferContext(const VarDecl *varDecl) {
  322. if (const auto *bufferDecl =
  323. dyn_cast<HLSLBufferDecl>(varDecl->getDeclContext()))
  324. // Filter ConstantBuffer/TextureBuffer
  325. if (!bufferDecl->isConstantBufferView())
  326. return bufferDecl;
  327. return nullptr;
  328. }
  329. /// Returns the real definition of the callee of the given CallExpr.
  330. ///
  331. /// If we are calling a forward-declared function, callee will be the
  332. /// FunctionDecl for the foward-declared function, not the actual
  333. /// definition. The foward-delcaration and defintion are two completely
  334. /// different AST nodes.
  335. inline const FunctionDecl *getCalleeDefinition(const CallExpr *expr) {
  336. const auto *callee = expr->getDirectCallee();
  337. if (callee->isThisDeclarationADefinition())
  338. return callee;
  339. // We need to update callee to the actual definition here
  340. if (!callee->isDefined(callee))
  341. return nullptr;
  342. return callee;
  343. }
  344. /// Returns the referenced definition. The given expr is expected to be a
  345. /// DeclRefExpr or CallExpr after ignoring casts. Returns nullptr otherwise.
  346. const DeclaratorDecl *getReferencedDef(const Expr *expr) {
  347. if (!expr)
  348. return nullptr;
  349. expr = expr->IgnoreParenCasts();
  350. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  351. return dyn_cast_or_null<DeclaratorDecl>(declRefExpr->getDecl());
  352. }
  353. if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  354. return getCalleeDefinition(callExpr);
  355. }
  356. return nullptr;
  357. }
  358. /// Returns the number of base classes if this type is a derived class/struct.
  359. /// Returns zero otherwise.
  360. inline uint32_t getNumBaseClasses(QualType type) {
  361. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  362. return cxxDecl->getNumBases();
  363. return 0;
  364. }
  365. /// Gets the index sequence of casting a derived object to a base object by
  366. /// following the cast chain.
  367. void getBaseClassIndices(const CastExpr *expr,
  368. llvm::SmallVectorImpl<uint32_t> *indices) {
  369. assert(expr->getCastKind() == CK_UncheckedDerivedToBase ||
  370. expr->getCastKind() == CK_HLSLDerivedToBase);
  371. indices->clear();
  372. QualType derivedType = expr->getSubExpr()->getType();
  373. const auto *derivedDecl = derivedType->getAsCXXRecordDecl();
  374. // Go through the base cast chain: for each of the derived to base cast, find
  375. // the index of the base in question in the derived's bases.
  376. for (auto pathIt = expr->path_begin(), pathIe = expr->path_end();
  377. pathIt != pathIe; ++pathIt) {
  378. // The type of the base in question
  379. const auto baseType = (*pathIt)->getType();
  380. uint32_t index = 0;
  381. for (auto baseIt = derivedDecl->bases_begin(),
  382. baseIe = derivedDecl->bases_end();
  383. baseIt != baseIe; ++baseIt, ++index)
  384. if (baseIt->getType() == baseType) {
  385. indices->push_back(index);
  386. break;
  387. }
  388. assert(index < derivedDecl->getNumBases());
  389. // Continue to proceed the next base in the chain
  390. derivedType = baseType;
  391. derivedDecl = derivedType->getAsCXXRecordDecl();
  392. }
  393. }
  394. std::string getNamespacePrefix(const Decl *decl) {
  395. std::string nsPrefix = "";
  396. const DeclContext *dc = decl->getDeclContext();
  397. while (dc && !dc->isTranslationUnit()) {
  398. if (const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(dc)) {
  399. if (!ns->isAnonymousNamespace()) {
  400. nsPrefix = ns->getName().str() + "::" + nsPrefix;
  401. }
  402. }
  403. dc = dc->getParent();
  404. }
  405. return nsPrefix;
  406. }
  407. std::string getFnName(const FunctionDecl *fn) {
  408. // Prefix the function name with the struct name if necessary
  409. std::string classOrStructName = "";
  410. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(fn))
  411. if (const auto *st = dyn_cast<CXXRecordDecl>(memberFn->getDeclContext()))
  412. classOrStructName = st->getName().str() + ".";
  413. return getNamespacePrefix(fn) + classOrStructName + fn->getName().str();
  414. }
  415. } // namespace
  416. SpirvEmitter::SpirvEmitter(CompilerInstance &ci)
  417. : theCompilerInstance(ci), astContext(ci.getASTContext()),
  418. diags(ci.getDiagnostics()),
  419. spirvOptions(ci.getCodeGenOpts().SpirvOptions),
  420. entryFunctionName(ci.getCodeGenOpts().HLSLEntryFunction), spvContext(),
  421. featureManager(diags, spirvOptions),
  422. spvBuilder(astContext, spvContext, spirvOptions),
  423. declIdMapper(astContext, spvContext, spvBuilder, *this, featureManager,
  424. spirvOptions),
  425. entryFunction(nullptr), curFunction(nullptr), curThis(nullptr),
  426. seenPushConstantAt(), isSpecConstantMode(false), needsLegalization(false),
  427. beforeHlslLegalization(false), mainSourceFile(nullptr) {
  428. // Get ShaderModel from command line hlsl profile option.
  429. const hlsl::ShaderModel *shaderModel =
  430. hlsl::ShaderModel::GetByName(ci.getCodeGenOpts().HLSLProfile.c_str());
  431. if (shaderModel->GetKind() == hlsl::ShaderModel::Kind::Invalid)
  432. emitError("unknown shader module: %0", {}) << shaderModel->GetName();
  433. if (spirvOptions.invertY && !shaderModel->IsVS() && !shaderModel->IsDS() &&
  434. !shaderModel->IsGS())
  435. emitError("-fvk-invert-y can only be used in VS/DS/GS", {});
  436. if (spirvOptions.useGlLayout && spirvOptions.useDxLayout)
  437. emitError("cannot specify both -fvk-use-dx-layout and -fvk-use-gl-layout",
  438. {});
  439. // Set shader model kind and hlsl major/minor version.
  440. spvContext.setCurrentShaderModelKind(shaderModel->GetKind());
  441. spvContext.setMajorVersion(shaderModel->GetMajor());
  442. spvContext.setMinorVersion(shaderModel->GetMinor());
  443. if (spirvOptions.useDxLayout) {
  444. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::FxcCTBuffer;
  445. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::FxcCTBuffer;
  446. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::FxcSBuffer;
  447. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::FxcSBuffer;
  448. } else if (spirvOptions.useGlLayout) {
  449. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::GLSLStd140;
  450. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::GLSLStd430;
  451. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::GLSLStd430;
  452. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::GLSLStd430;
  453. } else if (spirvOptions.useScalarLayout) {
  454. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::Scalar;
  455. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::Scalar;
  456. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::Scalar;
  457. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::Scalar;
  458. } else {
  459. spirvOptions.cBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd140;
  460. spirvOptions.tBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  461. spirvOptions.sBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  462. spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
  463. }
  464. // Set shader module version, source file name, and source file content (if
  465. // needed).
  466. llvm::StringRef source = "";
  467. std::vector<llvm::StringRef> fileNames;
  468. const auto &inputFiles = ci.getFrontendOpts().Inputs;
  469. // File name
  470. if (spirvOptions.debugInfoFile && !inputFiles.empty()) {
  471. for (const auto &inputFile : inputFiles) {
  472. fileNames.push_back(inputFile.getFile());
  473. }
  474. }
  475. // Source code
  476. if (spirvOptions.debugInfoSource) {
  477. const auto &sm = ci.getSourceManager();
  478. const llvm::MemoryBuffer *mainFile =
  479. sm.getBuffer(sm.getMainFileID(), SourceLocation());
  480. source = StringRef(mainFile->getBufferStart(), mainFile->getBufferSize());
  481. }
  482. mainSourceFile = spvBuilder.setDebugSource(spvContext.getMajorVersion(),
  483. spvContext.getMinorVersion(),
  484. fileNames, source);
  485. if (spirvOptions.debugInfoTool &&
  486. spirvOptions.targetEnv.compare("vulkan1.1") >= 0) {
  487. // Emit OpModuleProcessed to indicate the commit information.
  488. std::string commitHash =
  489. std::string("dxc-commit-hash: ") + clang::getGitCommitHash();
  490. spvBuilder.addModuleProcessed(commitHash);
  491. // Emit OpModuleProcessed to indicate the command line options that were
  492. // used to generate this module.
  493. if (!spirvOptions.clOptions.empty()) {
  494. // Using this format: "dxc-cl-option: XXXXXX"
  495. std::string clOptionStr = "dxc-cl-option:" + spirvOptions.clOptions;
  496. spvBuilder.addModuleProcessed(clOptionStr);
  497. }
  498. }
  499. }
  500. void SpirvEmitter::HandleTranslationUnit(ASTContext &context) {
  501. // Stop translating if there are errors in previous compilation stages.
  502. if (context.getDiagnostics().hasErrorOccurred())
  503. return;
  504. TranslationUnitDecl *tu = context.getTranslationUnitDecl();
  505. uint32_t numEntryPoints = 0;
  506. // The entry function is the seed of the queue.
  507. for (auto *decl : tu->decls()) {
  508. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  509. if (spvContext.isLib()) {
  510. if (const auto *shaderAttr = funcDecl->getAttr<HLSLShaderAttr>()) {
  511. // If we are compiling as a library then add everything that has a
  512. // ShaderAttr.
  513. addFunctionToWorkQueue(getShaderModelKind(shaderAttr->getStage()),
  514. funcDecl, /*isEntryFunction*/ true);
  515. numEntryPoints++;
  516. }
  517. } else {
  518. if (funcDecl->getName() == entryFunctionName) {
  519. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(),
  520. funcDecl, /*isEntryFunction*/ true);
  521. numEntryPoints++;
  522. }
  523. }
  524. } else {
  525. doDecl(decl);
  526. }
  527. if (context.getDiagnostics().hasErrorOccurred())
  528. return;
  529. }
  530. // Translate all functions reachable from the entry function.
  531. // The queue can grow in the meanwhile; so need to keep evaluating
  532. // workQueue.size().
  533. for (uint32_t i = 0; i < workQueue.size(); ++i) {
  534. const FunctionInfo *curEntryOrCallee = workQueue[i];
  535. spvContext.setCurrentShaderModelKind(curEntryOrCallee->shaderModelKind);
  536. doDecl(curEntryOrCallee->funcDecl);
  537. if (context.getDiagnostics().hasErrorOccurred())
  538. return;
  539. }
  540. const spv_target_env targetEnv = featureManager.getTargetEnv();
  541. // Addressing and memory model are required in a valid SPIR-V module.
  542. spvBuilder.setMemoryModel(spv::AddressingModel::Logical,
  543. spv::MemoryModel::GLSL450);
  544. // Even though the 'workQueue' grows due to the above loop, the first
  545. // 'numEntryPoints' entries in the 'workQueue' are the ones with the HLSL
  546. // 'shader' attribute, and must therefore be entry functions.
  547. assert(numEntryPoints <= workQueue.size());
  548. for (uint32_t i = 0; i < numEntryPoints; ++i) {
  549. // TODO: assign specific StageVars w.r.t. to entry point
  550. const FunctionInfo *entryInfo = workQueue[i];
  551. assert(entryInfo->isEntryFunction);
  552. spvBuilder.addEntryPoint(
  553. getSpirvShaderStage(entryInfo->shaderModelKind),
  554. entryInfo->entryFunction, entryInfo->funcDecl->getName(),
  555. targetEnv == SPV_ENV_VULKAN_1_2
  556. ? spvBuilder.getModule()->getVariables()
  557. : llvm::ArrayRef<SpirvVariable *>(declIdMapper.collectStageVars()));
  558. }
  559. // Add Location decorations to stage input/output variables.
  560. if (!declIdMapper.decorateStageIOLocations())
  561. return;
  562. // Add descriptor set and binding decorations to resource variables.
  563. if (!declIdMapper.decorateResourceBindings())
  564. return;
  565. // Output the constructed module.
  566. std::vector<uint32_t> m = spvBuilder.takeModule();
  567. if (!spirvOptions.codeGenHighLevel) {
  568. // In order to flatten resource arrays, we must also unroll loops. Therefore
  569. // we should run legalization before optimization.
  570. needsLegalization = needsLegalization || spirvOptions.flattenResourceArrays;
  571. // Run legalization passes
  572. if (needsLegalization || declIdMapper.requiresLegalization()) {
  573. std::string messages;
  574. if (!spirvToolsLegalize(targetEnv, &m, &messages)) {
  575. emitFatalError("failed to legalize SPIR-V: %0", {}) << messages;
  576. emitNote("please file a bug report on "
  577. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  578. "with source code if possible",
  579. {});
  580. return;
  581. } else if (!messages.empty()) {
  582. emitWarning("SPIR-V legalization: %0", {}) << messages;
  583. }
  584. }
  585. // Run optimization passes
  586. if (theCompilerInstance.getCodeGenOpts().OptimizationLevel > 0) {
  587. std::string messages;
  588. if (!spirvToolsOptimize(targetEnv, &m, spirvOptions, &messages)) {
  589. emitFatalError("failed to optimize SPIR-V: %0", {}) << messages;
  590. emitNote("please file a bug report on "
  591. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  592. "with source code if possible",
  593. {});
  594. return;
  595. }
  596. }
  597. }
  598. // Validate the generated SPIR-V code
  599. if (!spirvOptions.disableValidation) {
  600. std::string messages;
  601. if (!spirvToolsValidate(targetEnv, spirvOptions,
  602. needsLegalization ||
  603. declIdMapper.requiresLegalization(),
  604. &m, &messages)) {
  605. emitFatalError("generated SPIR-V is invalid: %0", {}) << messages;
  606. emitNote("please file a bug report on "
  607. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  608. "with source code if possible",
  609. {});
  610. return;
  611. }
  612. }
  613. theCompilerInstance.getOutStream()->write(
  614. reinterpret_cast<const char *>(m.data()), m.size() * 4);
  615. }
  616. void SpirvEmitter::doDecl(const Decl *decl) {
  617. if (isa<EmptyDecl>(decl) || isa<TypedefDecl>(decl))
  618. return;
  619. if (decl->isImplicit()) {
  620. doImplicitDecl(decl);
  621. return;
  622. }
  623. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  624. // We can have VarDecls inside cbuffer/tbuffer. For those VarDecls, we need
  625. // to emit their cbuffer/tbuffer as a whole and access each individual one
  626. // using access chains.
  627. if (const auto *bufferDecl = getCTBufferContext(varDecl)) {
  628. doHLSLBufferDecl(bufferDecl);
  629. } else {
  630. doVarDecl(varDecl);
  631. }
  632. } else if (const auto *namespaceDecl = dyn_cast<NamespaceDecl>(decl)) {
  633. for (auto *subDecl : namespaceDecl->decls())
  634. // Note: We only emit functions as they are discovered through the call
  635. // graph starting from the entry-point. We should not emit unused
  636. // functions inside namespaces.
  637. if (!isa<FunctionDecl>(subDecl))
  638. doDecl(subDecl);
  639. } else if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  640. doFunctionDecl(funcDecl);
  641. } else if (const auto *bufferDecl = dyn_cast<HLSLBufferDecl>(decl)) {
  642. doHLSLBufferDecl(bufferDecl);
  643. } else if (const auto *recordDecl = dyn_cast<RecordDecl>(decl)) {
  644. doRecordDecl(recordDecl);
  645. } else if (const auto *enumDecl = dyn_cast<EnumDecl>(decl)) {
  646. doEnumDecl(enumDecl);
  647. } else {
  648. emitError("decl type %0 unimplemented", decl->getLocation())
  649. << decl->getDeclKindName();
  650. }
  651. }
  652. void SpirvEmitter::doStmt(const Stmt *stmt,
  653. llvm::ArrayRef<const Attr *> attrs) {
  654. if (const auto *compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
  655. for (auto *st : compoundStmt->body())
  656. doStmt(st);
  657. } else if (const auto *retStmt = dyn_cast<ReturnStmt>(stmt)) {
  658. doReturnStmt(retStmt);
  659. } else if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) {
  660. doDeclStmt(declStmt);
  661. } else if (const auto *ifStmt = dyn_cast<IfStmt>(stmt)) {
  662. doIfStmt(ifStmt, attrs);
  663. } else if (const auto *switchStmt = dyn_cast<SwitchStmt>(stmt)) {
  664. doSwitchStmt(switchStmt, attrs);
  665. } else if (dyn_cast<CaseStmt>(stmt)) {
  666. processCaseStmtOrDefaultStmt(stmt);
  667. } else if (dyn_cast<DefaultStmt>(stmt)) {
  668. processCaseStmtOrDefaultStmt(stmt);
  669. } else if (const auto *breakStmt = dyn_cast<BreakStmt>(stmt)) {
  670. doBreakStmt(breakStmt);
  671. } else if (const auto *theDoStmt = dyn_cast<DoStmt>(stmt)) {
  672. doDoStmt(theDoStmt, attrs);
  673. } else if (const auto *discardStmt = dyn_cast<DiscardStmt>(stmt)) {
  674. doDiscardStmt(discardStmt);
  675. } else if (const auto *continueStmt = dyn_cast<ContinueStmt>(stmt)) {
  676. doContinueStmt(continueStmt);
  677. } else if (const auto *whileStmt = dyn_cast<WhileStmt>(stmt)) {
  678. doWhileStmt(whileStmt, attrs);
  679. } else if (const auto *forStmt = dyn_cast<ForStmt>(stmt)) {
  680. doForStmt(forStmt, attrs);
  681. } else if (dyn_cast<NullStmt>(stmt)) {
  682. // For the null statement ";". We don't need to do anything.
  683. } else if (const auto *expr = dyn_cast<Expr>(stmt)) {
  684. // All cases for expressions used as statements
  685. doExpr(expr);
  686. } else if (const auto *attrStmt = dyn_cast<AttributedStmt>(stmt)) {
  687. doStmt(attrStmt->getSubStmt(), attrStmt->getAttrs());
  688. } else {
  689. emitError("statement class '%0' unimplemented", stmt->getLocStart())
  690. << stmt->getStmtClassName() << stmt->getSourceRange();
  691. }
  692. }
  693. SpirvInstruction *SpirvEmitter::doExpr(const Expr *expr) {
  694. SpirvInstruction *result = nullptr;
  695. expr = expr->IgnoreParens();
  696. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  697. result = declIdMapper.getDeclEvalInfo(declRefExpr->getDecl(),
  698. expr->getLocStart());
  699. } else if (const auto *memberExpr = dyn_cast<MemberExpr>(expr)) {
  700. result = doMemberExpr(memberExpr);
  701. } else if (const auto *castExpr = dyn_cast<CastExpr>(expr)) {
  702. result = doCastExpr(castExpr);
  703. } else if (const auto *initListExpr = dyn_cast<InitListExpr>(expr)) {
  704. result = doInitListExpr(initListExpr);
  705. } else if (const auto *boolLiteral = dyn_cast<CXXBoolLiteralExpr>(expr)) {
  706. result =
  707. spvBuilder.getConstantBool(boolLiteral->getValue(), isSpecConstantMode);
  708. result->setRValue();
  709. } else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  710. result = translateAPInt(intLiteral->getValue(), expr->getType());
  711. result->setRValue();
  712. } else if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  713. result = translateAPFloat(floatLiteral->getValue(), expr->getType());
  714. result->setRValue();
  715. } else if (const auto *stringLiteral = dyn_cast<StringLiteral>(expr)) {
  716. result = spvBuilder.getString(stringLiteral->getString());
  717. } else if (const auto *compoundAssignOp =
  718. dyn_cast<CompoundAssignOperator>(expr)) {
  719. // CompoundAssignOperator is a subclass of BinaryOperator. It should be
  720. // checked before BinaryOperator.
  721. result = doCompoundAssignOperator(compoundAssignOp);
  722. } else if (const auto *binOp = dyn_cast<BinaryOperator>(expr)) {
  723. result = doBinaryOperator(binOp);
  724. } else if (const auto *unaryOp = dyn_cast<UnaryOperator>(expr)) {
  725. result = doUnaryOperator(unaryOp);
  726. } else if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  727. result = doHLSLVectorElementExpr(vecElemExpr);
  728. } else if (const auto *matElemExpr = dyn_cast<ExtMatrixElementExpr>(expr)) {
  729. result = doExtMatrixElementExpr(matElemExpr);
  730. } else if (const auto *funcCall = dyn_cast<CallExpr>(expr)) {
  731. result = doCallExpr(funcCall);
  732. } else if (const auto *subscriptExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  733. result = doArraySubscriptExpr(subscriptExpr);
  734. } else if (const auto *condExpr = dyn_cast<ConditionalOperator>(expr)) {
  735. result = doConditionalOperator(condExpr);
  736. } else if (const auto *defaultArgExpr = dyn_cast<CXXDefaultArgExpr>(expr)) {
  737. result = doExpr(defaultArgExpr->getParam()->getDefaultArg());
  738. } else if (isa<CXXThisExpr>(expr)) {
  739. assert(curThis);
  740. result = curThis;
  741. } else if (isa<CXXConstructExpr>(expr)) {
  742. result = curThis;
  743. } else {
  744. emitError("expression class '%0' unimplemented", expr->getExprLoc())
  745. << expr->getStmtClassName() << expr->getSourceRange();
  746. }
  747. return result;
  748. }
  749. SpirvInstruction *SpirvEmitter::loadIfGLValue(const Expr *expr) {
  750. // We are trying to load the value here, which is what an LValueToRValue
  751. // implicit cast is intended to do. We can ignore the cast if exists.
  752. expr = expr->IgnoreParenLValueCasts();
  753. return loadIfGLValue(expr, doExpr(expr));
  754. }
  755. SpirvInstruction *SpirvEmitter::loadIfGLValue(const Expr *expr,
  756. SpirvInstruction *info) {
  757. const auto exprType = expr->getType();
  758. // Do nothing if this is already rvalue
  759. if (!info || info->isRValue())
  760. return info;
  761. // Check whether we are trying to load an array of opaque objects as a whole.
  762. // If true, we are likely to copy it as a whole. To assist per-element
  763. // copying, avoid the load here and return the pointer directly.
  764. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  765. if (isOpaqueArrayType(exprType))
  766. return info;
  767. // Check whether we are trying to load an externally visible structured/byte
  768. // buffer as a whole. If true, it means we are creating alias for it. Avoid
  769. // the load and write the pointer directly to the alias variable then.
  770. //
  771. // Also for the case of alias function returns. If we are trying to load an
  772. // alias function return as a whole, it means we are assigning it to another
  773. // alias variable. Avoid the load and write the pointer directly.
  774. //
  775. // Note: legalization specific code
  776. if (isReferencingNonAliasStructuredOrByteBuffer(expr)) {
  777. return info;
  778. }
  779. if (loadIfAliasVarRef(expr, &info)) {
  780. // We are loading an alias variable as a whole here. This is likely for
  781. // wholesale assignments or function returns. Need to load the pointer.
  782. //
  783. // Note: legalization specific code
  784. return info;
  785. }
  786. SpirvInstruction *loadedInstr = nullptr;
  787. // TODO: Ouch. Very hacky. We need special path to get the value type if
  788. // we are loading a whole ConstantBuffer/TextureBuffer since the normal
  789. // type translation path won't work.
  790. if (const auto *declContext = isConstantTextureBufferDeclRef(expr)) {
  791. loadedInstr = spvBuilder.createLoad(
  792. declIdMapper.getCTBufferPushConstantType(declContext), info,
  793. expr->getExprLoc());
  794. } else {
  795. loadedInstr = spvBuilder.createLoad(exprType, info, expr->getExprLoc());
  796. }
  797. assert(loadedInstr);
  798. // Special-case: According to the SPIR-V Spec: There is no physical size or
  799. // bit pattern defined for boolean type. Therefore an unsigned integer is used
  800. // to represent booleans when layout is required. In such cases, after loading
  801. // the uint, we should perform a comparison.
  802. {
  803. uint32_t vecSize = 1, numRows = 0, numCols = 0;
  804. if (info->getLayoutRule() != SpirvLayoutRule::Void &&
  805. isBoolOrVecMatOfBoolType(exprType)) {
  806. QualType uintType = astContext.UnsignedIntTy;
  807. if (isScalarType(exprType) || isVectorType(exprType, nullptr, &vecSize)) {
  808. const auto fromType =
  809. vecSize == 1 ? uintType
  810. : astContext.getExtVectorType(uintType, vecSize);
  811. loadedInstr =
  812. castToBool(loadedInstr, fromType, exprType, expr->getLocStart());
  813. } else {
  814. const bool isMat = isMxNMatrix(exprType, nullptr, &numRows, &numCols);
  815. assert(isMat);
  816. (void)isMat;
  817. const clang::Type *type = exprType.getCanonicalType().getTypePtr();
  818. const RecordType *RT = cast<RecordType>(type);
  819. const ClassTemplateSpecializationDecl *templateSpecDecl =
  820. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  821. ClassTemplateDecl *templateDecl =
  822. templateSpecDecl->getSpecializedTemplate();
  823. const auto fromType = getHLSLMatrixType(
  824. astContext, theCompilerInstance.getSema(), templateDecl,
  825. astContext.UnsignedIntTy, numRows, numCols);
  826. loadedInstr =
  827. castToBool(loadedInstr, fromType, exprType, expr->getLocStart());
  828. }
  829. // Now that it is converted to Bool, it has no layout rule.
  830. // This result-id should be evaluated as bool from here on out.
  831. loadedInstr->setLayoutRule(SpirvLayoutRule::Void);
  832. }
  833. }
  834. loadedInstr->setRValue();
  835. return loadedInstr;
  836. }
  837. SpirvInstruction *SpirvEmitter::loadIfAliasVarRef(const Expr *expr) {
  838. auto *instr = doExpr(expr);
  839. loadIfAliasVarRef(expr, &instr);
  840. return instr;
  841. }
  842. bool SpirvEmitter::loadIfAliasVarRef(const Expr *varExpr,
  843. SpirvInstruction **instr) {
  844. assert(instr);
  845. if ((*instr) && (*instr)->containsAliasComponent() &&
  846. isAKindOfStructuredOrByteBuffer(varExpr->getType())) {
  847. // Load the pointer of the aliased-to-variable if the expression has a
  848. // pointer to pointer type.
  849. if (varExpr->isGLValue()) {
  850. *instr = spvBuilder.createLoad(varExpr->getType(), *instr,
  851. varExpr->getExprLoc());
  852. }
  853. return true;
  854. }
  855. return false;
  856. }
  857. SpirvInstruction *SpirvEmitter::castToType(SpirvInstruction *value,
  858. QualType fromType, QualType toType,
  859. SourceLocation srcLoc) {
  860. if (isFloatOrVecMatOfFloatType(toType))
  861. return castToFloat(value, fromType, toType, srcLoc);
  862. // Order matters here. Bool (vector) values will also be considered as uint
  863. // (vector) values. So given a bool (vector) argument, isUintOrVecOfUintType()
  864. // will also return true. We need to check bool before uint. The opposite is
  865. // not true.
  866. if (isBoolOrVecMatOfBoolType(toType))
  867. return castToBool(value, fromType, toType, srcLoc);
  868. if (isSintOrVecMatOfSintType(toType) || isUintOrVecMatOfUintType(toType))
  869. return castToInt(value, fromType, toType, srcLoc);
  870. emitError("casting to type %0 unimplemented", {}) << toType;
  871. return nullptr;
  872. }
  873. void SpirvEmitter::doFunctionDecl(const FunctionDecl *decl) {
  874. assert(decl->isThisDeclarationADefinition());
  875. // A RAII class for maintaining the current function under traversal.
  876. class FnEnvRAII {
  877. public:
  878. // Creates a new instance which sets fnEnv to the newFn on creation,
  879. // and resets fnEnv to its original value on destruction.
  880. FnEnvRAII(const FunctionDecl **fnEnv, const FunctionDecl *newFn)
  881. : oldFn(*fnEnv), fnSlot(fnEnv) {
  882. *fnEnv = newFn;
  883. }
  884. ~FnEnvRAII() { *fnSlot = oldFn; }
  885. private:
  886. const FunctionDecl *oldFn;
  887. const FunctionDecl **fnSlot;
  888. };
  889. FnEnvRAII fnEnvRAII(&curFunction, decl);
  890. // We are about to start translation for a new function. Clear the break stack
  891. // and the continue stack.
  892. breakStack = std::stack<SpirvBasicBlock *>();
  893. continueStack = std::stack<SpirvBasicBlock *>();
  894. // This will allow the entry-point name to be something like
  895. // myNamespace::myEntrypointFunc.
  896. std::string funcName = getFnName(decl);
  897. SpirvFunction *func = declIdMapper.getOrRegisterFn(decl);
  898. const auto iter = functionInfoMap.find(decl);
  899. if (iter != functionInfoMap.end()) {
  900. const auto &entryInfo = iter->second;
  901. if (entryInfo->isEntryFunction) {
  902. funcName = "src." + funcName;
  903. // Create wrapper for the entry function
  904. if (!emitEntryFunctionWrapper(decl, func))
  905. return;
  906. }
  907. }
  908. const QualType retType =
  909. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(decl);
  910. // Construct the function signature.
  911. llvm::SmallVector<QualType, 4> paramTypes;
  912. bool isNonStaticMemberFn = false;
  913. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(decl)) {
  914. isNonStaticMemberFn = !memberFn->isStatic();
  915. if (isNonStaticMemberFn) {
  916. // For non-static member function, the first parameter should be the
  917. // object on which we are invoking this method.
  918. const QualType valueType =
  919. memberFn->getThisType(astContext)->getPointeeType();
  920. paramTypes.push_back(valueType);
  921. }
  922. }
  923. for (const auto *param : decl->params()) {
  924. const QualType valueType =
  925. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  926. paramTypes.push_back(valueType);
  927. }
  928. spvBuilder.beginFunction(retType, paramTypes, decl->getLocStart(), funcName,
  929. decl->hasAttr<HLSLPreciseAttr>(), func);
  930. if (isNonStaticMemberFn) {
  931. // Remember the parameter for the 'this' object so later we can handle
  932. // CXXThisExpr correctly.
  933. curThis = spvBuilder.addFnParam(paramTypes[0], /*isPrecise*/ false,
  934. decl->getLocStart(), "param.this");
  935. if (isOrContainsAKindOfStructuredOrByteBuffer(paramTypes[0])) {
  936. curThis->setContainsAliasComponent(true);
  937. needsLegalization = true;
  938. }
  939. }
  940. // Create all parameters.
  941. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  942. const ParmVarDecl *paramDecl = decl->getParamDecl(i);
  943. (void)declIdMapper.createFnParam(paramDecl);
  944. }
  945. if (decl->hasBody()) {
  946. // The entry basic block.
  947. auto *entryLabel = spvBuilder.createBasicBlock("bb.entry");
  948. spvBuilder.setInsertPoint(entryLabel);
  949. // Process all statments in the body.
  950. doStmt(decl->getBody());
  951. // We have processed all Stmts in this function and now in the last
  952. // basic block. Make sure we have a termination instruction.
  953. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  954. const auto retType = decl->getReturnType();
  955. const auto returnLoc = decl->getBody()->getLocEnd();
  956. if (retType->isVoidType()) {
  957. spvBuilder.createReturn(returnLoc);
  958. } else {
  959. // If the source code does not provide a proper return value for some
  960. // control flow path, it's undefined behavior. We just return null
  961. // value here.
  962. spvBuilder.createReturnValue(spvBuilder.getConstantNull(retType),
  963. returnLoc);
  964. }
  965. }
  966. }
  967. spvBuilder.endFunction();
  968. }
  969. bool SpirvEmitter::validateVKAttributes(const NamedDecl *decl) {
  970. bool success = true;
  971. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  972. const auto varType = varDecl->getType();
  973. if ((isSubpassInput(varType) || isSubpassInputMS(varType)) &&
  974. !varDecl->hasAttr<VKInputAttachmentIndexAttr>()) {
  975. emitError("missing vk::input_attachment_index attribute",
  976. varDecl->getLocation());
  977. success = false;
  978. }
  979. }
  980. if (decl->getAttr<VKInputAttachmentIndexAttr>()) {
  981. if (!spvContext.isPS()) {
  982. emitError("SubpassInput(MS) only allowed in pixel shader",
  983. decl->getLocation());
  984. success = false;
  985. }
  986. if (!decl->isExternallyVisible()) {
  987. emitError("SubpassInput(MS) must be externally visible",
  988. decl->getLocation());
  989. success = false;
  990. }
  991. // We only allow VKInputAttachmentIndexAttr to be attached to global
  992. // variables. So it should be fine to cast here.
  993. const auto elementType =
  994. hlsl::GetHLSLResourceResultType(cast<VarDecl>(decl)->getType());
  995. if (!isScalarType(elementType) && !isVectorType(elementType)) {
  996. emitError(
  997. "only scalar/vector types allowed as SubpassInput(MS) parameter type",
  998. decl->getLocation());
  999. // Return directly to avoid further type processing, which will hit
  1000. // asserts when lowering the type.
  1001. return false;
  1002. }
  1003. }
  1004. // The frontend will make sure that
  1005. // * vk::push_constant applies to global variables of struct type
  1006. // * vk::binding applies to global variables or cbuffers/tbuffers
  1007. // * vk::counter_binding applies to global variables of RW/Append/Consume
  1008. // StructuredBuffer
  1009. // * vk::location applies to function parameters/returns and struct fields
  1010. // So the only case we need to check co-existence is vk::push_constant and
  1011. // vk::binding.
  1012. if (const auto *pcAttr = decl->getAttr<VKPushConstantAttr>()) {
  1013. const auto loc = pcAttr->getLocation();
  1014. if (seenPushConstantAt.isInvalid()) {
  1015. seenPushConstantAt = loc;
  1016. } else {
  1017. // TODO: Actually this is slightly incorrect. The Vulkan spec says:
  1018. // There must be no more than one push constant block statically used
  1019. // per shader entry point.
  1020. // But we are checking whether there are more than one push constant
  1021. // blocks defined. Tracking usage requires more work.
  1022. emitError("cannot have more than one push constant block", loc);
  1023. emitNote("push constant block previously defined here",
  1024. seenPushConstantAt);
  1025. success = false;
  1026. }
  1027. if (decl->hasAttr<VKBindingAttr>()) {
  1028. emitError("vk::push_constant attribute cannot be used together with "
  1029. "vk::binding attribute",
  1030. loc);
  1031. success = false;
  1032. }
  1033. }
  1034. // vk::shader_record_nv is supported only on cbuffer/ConstantBuffer
  1035. if (const auto *srbAttr = decl->getAttr<VKShaderRecordNVAttr>()) {
  1036. const auto loc = srbAttr->getLocation();
  1037. const HLSLBufferDecl *bufDecl = nullptr;
  1038. bool isValidType = false;
  1039. if (bufDecl = dyn_cast<HLSLBufferDecl>(decl))
  1040. isValidType = bufDecl->isCBuffer();
  1041. else if (bufDecl = dyn_cast<HLSLBufferDecl>(decl->getDeclContext()))
  1042. isValidType = bufDecl->isCBuffer();
  1043. if (!isValidType) {
  1044. emitError(
  1045. "vk::shader_record_nv can be applied only to cbuffer/ConstantBuffer",
  1046. loc);
  1047. success = false;
  1048. }
  1049. if (decl->hasAttr<VKBindingAttr>()) {
  1050. emitError("vk::shader_record_nv attribute cannot be used together with "
  1051. "vk::binding attribute",
  1052. loc);
  1053. success = false;
  1054. }
  1055. }
  1056. return success;
  1057. }
  1058. void SpirvEmitter::doHLSLBufferDecl(const HLSLBufferDecl *bufferDecl) {
  1059. // This is a cbuffer/tbuffer decl.
  1060. // Check and emit warnings for member intializers which are not
  1061. // supported in Vulkan
  1062. for (const auto *member : bufferDecl->decls()) {
  1063. if (const auto *varMember = dyn_cast<VarDecl>(member)) {
  1064. if (!spirvOptions.noWarnIgnoredFeatures) {
  1065. if (const auto *init = varMember->getInit())
  1066. emitWarning("%select{tbuffer|cbuffer}0 member initializer "
  1067. "ignored since no Vulkan equivalent",
  1068. init->getExprLoc())
  1069. << bufferDecl->isCBuffer() << init->getSourceRange();
  1070. }
  1071. // We cannot handle external initialization of column-major matrices now.
  1072. if (isOrContainsNonFpColMajorMatrix(astContext, spirvOptions,
  1073. varMember->getType(), varMember)) {
  1074. emitError("externally initialized non-floating-point column-major "
  1075. "matrices not supported yet",
  1076. varMember->getLocation());
  1077. }
  1078. }
  1079. }
  1080. if (!validateVKAttributes(bufferDecl))
  1081. return;
  1082. if (bufferDecl->hasAttr<VKShaderRecordNVAttr>()) {
  1083. (void)declIdMapper.createShaderRecordBufferNV(bufferDecl);
  1084. } else {
  1085. (void)declIdMapper.createCTBuffer(bufferDecl);
  1086. }
  1087. }
  1088. void SpirvEmitter::doImplicitDecl(const Decl *decl) {
  1089. // We only handle specific implicit declaration for raytracing
  1090. // which are RayFlag/HitKind constant unsigned integers
  1091. // Ignore others
  1092. if (spvContext.isLib() || spvContext.isRay()) {
  1093. const VarDecl *implDecl = dyn_cast<VarDecl>(decl);
  1094. if (implDecl && (implDecl->getName().startswith(StringRef("RAY_FLAG")) ||
  1095. implDecl->getName().startswith(StringRef("HIT_KIND")))) {
  1096. (void)declIdMapper.createRayTracingNVImplicitVar(implDecl);
  1097. }
  1098. }
  1099. }
  1100. void SpirvEmitter::doRecordDecl(const RecordDecl *recordDecl) {
  1101. // Ignore implict records
  1102. // Somehow we'll have implicit records with:
  1103. // static const int Length = count;
  1104. // that can mess up with the normal CodeGen.
  1105. if (recordDecl->isImplicit())
  1106. return;
  1107. // Handle each static member with inline initializer.
  1108. // Each static member has a corresponding VarDecl inside the
  1109. // RecordDecl. For those defined in the translation unit,
  1110. // their VarDecls do not have initializer.
  1111. for (auto *subDecl : recordDecl->decls())
  1112. if (auto *varDecl = dyn_cast<VarDecl>(subDecl))
  1113. if (varDecl->isStaticDataMember() && varDecl->hasInit())
  1114. doVarDecl(varDecl);
  1115. }
  1116. void SpirvEmitter::doEnumDecl(const EnumDecl *decl) {
  1117. for (auto it = decl->enumerator_begin(); it != decl->enumerator_end(); ++it)
  1118. declIdMapper.createEnumConstant(*it);
  1119. }
  1120. void SpirvEmitter::doVarDecl(const VarDecl *decl) {
  1121. if (!validateVKAttributes(decl))
  1122. return;
  1123. // HLSL has the 'string' type which can be used for rare purposes such as
  1124. // printf (SPIR-V's DebugPrintf). SPIR-V does not have a 'char' or 'string'
  1125. // type, and therefore any variable of such type should not be created.
  1126. // DeclResultIdMapper maps such decl to an OpString instruction that
  1127. // represents the variable's initializer literal.
  1128. if (isStringType(decl->getType())) {
  1129. declIdMapper.createOrUpdateStringVar(decl);
  1130. return;
  1131. }
  1132. // We cannot handle external initialization of column-major matrices now.
  1133. if (isExternalVar(decl) &&
  1134. isOrContainsNonFpColMajorMatrix(astContext, spirvOptions, decl->getType(),
  1135. decl)) {
  1136. emitError("externally initialized non-floating-point column-major "
  1137. "matrices not supported yet",
  1138. decl->getLocation());
  1139. }
  1140. // Reject arrays of RW/append/consume structured buffers. They have assoicated
  1141. // counters, which are quite nasty to handle.
  1142. if (decl->getType()->isArrayType()) {
  1143. auto type = decl->getType();
  1144. do {
  1145. type = type->getAsArrayTypeUnsafe()->getElementType();
  1146. } while (type->isArrayType());
  1147. if (isRWAppendConsumeSBuffer(type)) {
  1148. emitError("arrays of RW/append/consume structured buffers unsupported",
  1149. decl->getLocation());
  1150. return;
  1151. }
  1152. }
  1153. if (decl->hasAttr<VKConstantIdAttr>()) {
  1154. // This is a VarDecl for specialization constant.
  1155. createSpecConstant(decl);
  1156. return;
  1157. }
  1158. if (decl->hasAttr<VKPushConstantAttr>()) {
  1159. // This is a VarDecl for PushConstant block.
  1160. (void)declIdMapper.createPushConstant(decl);
  1161. return;
  1162. }
  1163. if (decl->hasAttr<VKShaderRecordNVAttr>()) {
  1164. (void)declIdMapper.createShaderRecordBufferNV(decl);
  1165. return;
  1166. }
  1167. if (isa<HLSLBufferDecl>(decl->getDeclContext())) {
  1168. // This is a VarDecl of a ConstantBuffer/TextureBuffer type.
  1169. (void)declIdMapper.createCTBuffer(decl);
  1170. return;
  1171. }
  1172. SpirvVariable *var = nullptr;
  1173. // The contents in externally visible variables can be updated via the
  1174. // pipeline. They should be handled differently from file and function scope
  1175. // variables.
  1176. // File scope variables (static "global" and "local" variables) belongs to
  1177. // the Private storage class, while function scope variables (normal "local"
  1178. // variables) belongs to the Function storage class.
  1179. if (isExternalVar(decl)) {
  1180. var = declIdMapper.createExternVar(decl);
  1181. } else {
  1182. // We already know the variable is not externally visible here. If it does
  1183. // not have local storage, it should be file scope variable.
  1184. const bool isFileScopeVar = !decl->hasLocalStorage();
  1185. if (isFileScopeVar)
  1186. var = declIdMapper.createFileVar(decl, llvm::None);
  1187. else
  1188. var = declIdMapper.createFnVar(decl, llvm::None);
  1189. // Emit OpStore to initialize the variable
  1190. // TODO: revert back to use OpVariable initializer
  1191. // We should only evaluate the initializer once for a static variable.
  1192. if (isFileScopeVar) {
  1193. if (decl->isStaticLocal()) {
  1194. initOnce(decl->getType(), decl->getName(), var, decl->getInit());
  1195. } else {
  1196. // Defer to initialize these global variables at the beginning of the
  1197. // entry function.
  1198. toInitGloalVars.push_back(decl);
  1199. }
  1200. }
  1201. // Function local variables. Just emit OpStore at the current insert point.
  1202. else if (const Expr *init = decl->getInit()) {
  1203. if (auto *constInit = tryToEvaluateAsConst(init)) {
  1204. spvBuilder.createStore(var, constInit, decl->getLocation());
  1205. } else {
  1206. storeValue(var, loadIfGLValue(init), decl->getType(),
  1207. decl->getLocation());
  1208. }
  1209. // Update counter variable associated with local variables
  1210. tryToAssignCounterVar(decl, init);
  1211. }
  1212. // Variables that are not externally visible and of opaque types should
  1213. // request legalization.
  1214. if (!needsLegalization && isOpaqueType(decl->getType()))
  1215. needsLegalization = true;
  1216. }
  1217. // All variables that are of opaque struct types should request legalization.
  1218. if (!needsLegalization && isOpaqueStructType(decl->getType()))
  1219. needsLegalization = true;
  1220. }
  1221. spv::LoopControlMask SpirvEmitter::translateLoopAttribute(const Stmt *stmt,
  1222. const Attr &attr) {
  1223. switch (attr.getKind()) {
  1224. case attr::HLSLLoop:
  1225. case attr::HLSLFastOpt:
  1226. return spv::LoopControlMask::DontUnroll;
  1227. case attr::HLSLUnroll:
  1228. return spv::LoopControlMask::Unroll;
  1229. case attr::HLSLAllowUAVCondition:
  1230. if (!spirvOptions.noWarnIgnoredFeatures) {
  1231. emitWarning("unsupported allow_uav_condition attribute ignored",
  1232. stmt->getLocStart());
  1233. }
  1234. break;
  1235. default:
  1236. llvm_unreachable("found unknown loop attribute");
  1237. }
  1238. return spv::LoopControlMask::MaskNone;
  1239. }
  1240. void SpirvEmitter::doDiscardStmt(const DiscardStmt *discardStmt) {
  1241. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1242. // The discard statement can only be called from a pixel shader
  1243. if (!spvContext.isPS()) {
  1244. emitError("discard statement may only be used in pixel shaders",
  1245. discardStmt->getLoc());
  1246. return;
  1247. }
  1248. if (featureManager.isExtensionEnabled(
  1249. Extension::EXT_demote_to_helper_invocation)) {
  1250. // SPV_EXT_demote_to_helper_invocation SPIR-V extension provides a new
  1251. // instruction OpDemoteToHelperInvocationEXT allowing shaders to "demote" a
  1252. // fragment shader invocation to behave like a helper invocation for its
  1253. // duration. The demoted invocation will have no further side effects and
  1254. // will not output to the framebuffer, but remains active and can
  1255. // participate in computing derivatives and in subgroup operations. This is
  1256. // a better match for the "discard" instruction in HLSL.
  1257. spvBuilder.createDemoteToHelperInvocationEXT(discardStmt->getLoc());
  1258. } else {
  1259. // Note: if/when the demote behavior becomes part of the core Vulkan spec,
  1260. // we should no longer generate OpKill for 'discard', and always generate
  1261. // the demote behavior.
  1262. spvBuilder.createKill(discardStmt->getLoc());
  1263. // Some statements that alter the control flow (break, continue, return, and
  1264. // discard), require creation of a new basic block to hold any statement
  1265. // that may follow them.
  1266. auto *newBB = spvBuilder.createBasicBlock();
  1267. spvBuilder.setInsertPoint(newBB);
  1268. }
  1269. }
  1270. void SpirvEmitter::doDoStmt(const DoStmt *theDoStmt,
  1271. llvm::ArrayRef<const Attr *> attrs) {
  1272. // do-while loops are composed of:
  1273. //
  1274. // do {
  1275. // <body>
  1276. // } while(<check>);
  1277. //
  1278. // SPIR-V requires loops to have a merge basic block as well as a continue
  1279. // basic block. Even though do-while loops do not have an explicit continue
  1280. // block as in for-loops, we still do need to create a continue block.
  1281. //
  1282. // Since SPIR-V requires structured control flow, we need two more basic
  1283. // blocks, <header> and <merge>. <header> is the block before control flow
  1284. // diverges, and <merge> is the block where control flow subsequently
  1285. // converges. The <check> can be performed in the <continue> basic block.
  1286. // The final CFG should normally be like the following. Exceptions
  1287. // will occur with non-local exits like loop breaks or early returns.
  1288. //
  1289. // +----------+
  1290. // | header | <-----------------------------------+
  1291. // +----------+ |
  1292. // | | (true)
  1293. // v |
  1294. // +------+ +--------------------+ |
  1295. // | body | ----> | continue (<check>) |-----------+
  1296. // +------+ +--------------------+
  1297. // |
  1298. // | (false)
  1299. // +-------+ |
  1300. // | merge | <-------------+
  1301. // +-------+
  1302. //
  1303. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1304. const spv::LoopControlMask loopControl =
  1305. attrs.empty() ? spv::LoopControlMask::MaskNone
  1306. : translateLoopAttribute(theDoStmt, *attrs.front());
  1307. // Create basic blocks
  1308. auto *headerBB = spvBuilder.createBasicBlock("do_while.header");
  1309. auto *bodyBB = spvBuilder.createBasicBlock("do_while.body");
  1310. auto *continueBB = spvBuilder.createBasicBlock("do_while.continue");
  1311. auto *mergeBB = spvBuilder.createBasicBlock("do_while.merge");
  1312. // Make sure any continue statements branch to the continue block, and any
  1313. // break statements branch to the merge block.
  1314. continueStack.push(continueBB);
  1315. breakStack.push(mergeBB);
  1316. // Branch from the current insert point to the header block.
  1317. spvBuilder.createBranch(headerBB, theDoStmt->getLocStart());
  1318. spvBuilder.addSuccessor(headerBB);
  1319. // Process the <header> block
  1320. // The header block must always branch to the body.
  1321. spvBuilder.setInsertPoint(headerBB);
  1322. const Stmt *body = theDoStmt->getBody();
  1323. spvBuilder.createBranch(bodyBB,
  1324. body ? body->getLocStart() : theDoStmt->getLocStart(),
  1325. mergeBB, continueBB, loopControl);
  1326. spvBuilder.addSuccessor(bodyBB);
  1327. // The current basic block has OpLoopMerge instruction. We need to set its
  1328. // continue and merge target.
  1329. spvBuilder.setContinueTarget(continueBB);
  1330. spvBuilder.setMergeTarget(mergeBB);
  1331. // Process the <body> block
  1332. spvBuilder.setInsertPoint(bodyBB);
  1333. if (body) {
  1334. doStmt(body);
  1335. }
  1336. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  1337. spvBuilder.createBranch(continueBB, body ? body->getLocEnd()
  1338. : theDoStmt->getLocStart());
  1339. }
  1340. spvBuilder.addSuccessor(continueBB);
  1341. // Process the <continue> block. The check for whether the loop should
  1342. // continue lies in the continue block.
  1343. // *NOTE*: There's a SPIR-V rule that when a conditional branch is to occur in
  1344. // a continue block of a loop, there should be no OpSelectionMerge. Only an
  1345. // OpBranchConditional must be specified.
  1346. spvBuilder.setInsertPoint(continueBB);
  1347. SpirvInstruction *condition = nullptr;
  1348. if (const Expr *check = theDoStmt->getCond()) {
  1349. condition = doExpr(check);
  1350. } else {
  1351. condition = spvBuilder.getConstantBool(true);
  1352. }
  1353. spvBuilder.createConditionalBranch(condition, headerBB, mergeBB,
  1354. theDoStmt->getLocEnd());
  1355. spvBuilder.addSuccessor(headerBB);
  1356. spvBuilder.addSuccessor(mergeBB);
  1357. // Set insertion point to the <merge> block for subsequent statements
  1358. spvBuilder.setInsertPoint(mergeBB);
  1359. // Done with the current scope's continue block and merge block.
  1360. continueStack.pop();
  1361. breakStack.pop();
  1362. }
  1363. void SpirvEmitter::doContinueStmt(const ContinueStmt *continueStmt) {
  1364. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1365. auto *continueTargetBB = continueStack.top();
  1366. spvBuilder.createBranch(continueTargetBB, continueStmt->getLocStart());
  1367. spvBuilder.addSuccessor(continueTargetBB);
  1368. // Some statements that alter the control flow (break, continue, return, and
  1369. // discard), require creation of a new basic block to hold any statement that
  1370. // may follow them. For example: StmtB and StmtC below are put inside a new
  1371. // basic block which is unreachable.
  1372. //
  1373. // while (true) {
  1374. // StmtA;
  1375. // continue;
  1376. // StmtB;
  1377. // StmtC;
  1378. // }
  1379. auto *newBB = spvBuilder.createBasicBlock();
  1380. spvBuilder.setInsertPoint(newBB);
  1381. }
  1382. void SpirvEmitter::doWhileStmt(const WhileStmt *whileStmt,
  1383. llvm::ArrayRef<const Attr *> attrs) {
  1384. // While loops are composed of:
  1385. // while (<check>) { <body> }
  1386. //
  1387. // SPIR-V requires loops to have a merge basic block as well as a continue
  1388. // basic block. Even though while loops do not have an explicit continue
  1389. // block as in for-loops, we still do need to create a continue block.
  1390. //
  1391. // Since SPIR-V requires structured control flow, we need two more basic
  1392. // blocks, <header> and <merge>. <header> is the block before control flow
  1393. // diverges, and <merge> is the block where control flow subsequently
  1394. // converges. The <check> block can take the responsibility of the <header>
  1395. // block. The final CFG should normally be like the following. Exceptions
  1396. // will occur with non-local exits like loop breaks or early returns.
  1397. //
  1398. // +----------+
  1399. // | header | <------------------+
  1400. // | (check) | |
  1401. // +----------+ |
  1402. // | |
  1403. // +-------+-------+ |
  1404. // | false | true |
  1405. // | v |
  1406. // | +------+ +------------------+
  1407. // | | body | --> | continue (no-op) |
  1408. // v +------+ +------------------+
  1409. // +-------+
  1410. // | merge |
  1411. // +-------+
  1412. //
  1413. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1414. const spv::LoopControlMask loopControl =
  1415. attrs.empty() ? spv::LoopControlMask::MaskNone
  1416. : translateLoopAttribute(whileStmt, *attrs.front());
  1417. // Create basic blocks
  1418. auto *checkBB = spvBuilder.createBasicBlock("while.check");
  1419. auto *bodyBB = spvBuilder.createBasicBlock("while.body");
  1420. auto *continueBB = spvBuilder.createBasicBlock("while.continue");
  1421. auto *mergeBB = spvBuilder.createBasicBlock("while.merge");
  1422. // Make sure any continue statements branch to the continue block, and any
  1423. // break statements branch to the merge block.
  1424. continueStack.push(continueBB);
  1425. breakStack.push(mergeBB);
  1426. // Process the <check> block
  1427. spvBuilder.createBranch(checkBB, whileStmt->getLocStart());
  1428. spvBuilder.addSuccessor(checkBB);
  1429. spvBuilder.setInsertPoint(checkBB);
  1430. // If we have:
  1431. // while (int a = foo()) {...}
  1432. // we should evaluate 'a' by calling 'foo()' every single time the check has
  1433. // to occur.
  1434. if (const auto *condVarDecl = whileStmt->getConditionVariableDeclStmt())
  1435. doStmt(condVarDecl);
  1436. SpirvInstruction *condition = nullptr;
  1437. const Expr *check = whileStmt->getCond();
  1438. if (check) {
  1439. condition = doExpr(check);
  1440. } else {
  1441. condition = spvBuilder.getConstantBool(true);
  1442. }
  1443. spvBuilder.createConditionalBranch(
  1444. condition, bodyBB,
  1445. /*false branch*/ mergeBB, whileStmt->getLocStart(),
  1446. /*merge*/ mergeBB, continueBB, spv::SelectionControlMask::MaskNone,
  1447. loopControl);
  1448. spvBuilder.addSuccessor(bodyBB);
  1449. spvBuilder.addSuccessor(mergeBB);
  1450. // The current basic block has OpLoopMerge instruction. We need to set its
  1451. // continue and merge target.
  1452. spvBuilder.setContinueTarget(continueBB);
  1453. spvBuilder.setMergeTarget(mergeBB);
  1454. // Process the <body> block
  1455. spvBuilder.setInsertPoint(bodyBB);
  1456. const Stmt *body = whileStmt->getBody();
  1457. if (body) {
  1458. doStmt(body);
  1459. }
  1460. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1461. spvBuilder.createBranch(continueBB, whileStmt->getLocEnd());
  1462. spvBuilder.addSuccessor(continueBB);
  1463. // Process the <continue> block. While loops do not have an explicit
  1464. // continue block. The continue block just branches to the <check> block.
  1465. spvBuilder.setInsertPoint(continueBB);
  1466. spvBuilder.createBranch(checkBB, whileStmt->getLocEnd());
  1467. spvBuilder.addSuccessor(checkBB);
  1468. // Set insertion point to the <merge> block for subsequent statements
  1469. spvBuilder.setInsertPoint(mergeBB);
  1470. // Done with the current scope's continue and merge blocks.
  1471. continueStack.pop();
  1472. breakStack.pop();
  1473. }
  1474. void SpirvEmitter::doForStmt(const ForStmt *forStmt,
  1475. llvm::ArrayRef<const Attr *> attrs) {
  1476. // for loops are composed of:
  1477. // for (<init>; <check>; <continue>) <body>
  1478. //
  1479. // To translate a for loop, we'll need to emit all <init> statements
  1480. // in the current basic block, and then have separate basic blocks for
  1481. // <check>, <continue>, and <body>. Besides, since SPIR-V requires
  1482. // structured control flow, we need two more basic blocks, <header>
  1483. // and <merge>. <header> is the block before control flow diverges,
  1484. // while <merge> is the block where control flow subsequently converges.
  1485. // The <check> block can take the responsibility of the <header> block.
  1486. // The final CFG should normally be like the following. Exceptions will
  1487. // occur with non-local exits like loop breaks or early returns.
  1488. // +--------+
  1489. // | init |
  1490. // +--------+
  1491. // |
  1492. // v
  1493. // +----------+
  1494. // | header | <---------------+
  1495. // | (check) | |
  1496. // +----------+ |
  1497. // | |
  1498. // +-------+-------+ |
  1499. // | false | true |
  1500. // | v |
  1501. // | +------+ +----------+
  1502. // | | body | --> | continue |
  1503. // v +------+ +----------+
  1504. // +-------+
  1505. // | merge |
  1506. // +-------+
  1507. //
  1508. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1509. const spv::LoopControlMask loopControl =
  1510. attrs.empty() ? spv::LoopControlMask::MaskNone
  1511. : translateLoopAttribute(forStmt, *attrs.front());
  1512. // Create basic blocks
  1513. auto *checkBB = spvBuilder.createBasicBlock("for.check");
  1514. auto *bodyBB = spvBuilder.createBasicBlock("for.body");
  1515. auto *continueBB = spvBuilder.createBasicBlock("for.continue");
  1516. auto *mergeBB = spvBuilder.createBasicBlock("for.merge");
  1517. // Make sure any continue statements branch to the continue block, and any
  1518. // break statements branch to the merge block.
  1519. continueStack.push(continueBB);
  1520. breakStack.push(mergeBB);
  1521. // Process the <init> block
  1522. if (const Stmt *initStmt = forStmt->getInit()) {
  1523. doStmt(initStmt);
  1524. }
  1525. const Expr *check = forStmt->getCond();
  1526. spvBuilder.createBranch(checkBB, check ? check->getLocStart()
  1527. : forStmt->getLocStart());
  1528. spvBuilder.addSuccessor(checkBB);
  1529. // Process the <check> block
  1530. spvBuilder.setInsertPoint(checkBB);
  1531. SpirvInstruction *condition = nullptr;
  1532. if (check) {
  1533. condition = doExpr(check);
  1534. } else {
  1535. condition = spvBuilder.getConstantBool(true);
  1536. }
  1537. const Stmt *body = forStmt->getBody();
  1538. spvBuilder.createConditionalBranch(
  1539. condition, bodyBB,
  1540. /*false branch*/ mergeBB,
  1541. check ? check->getLocEnd()
  1542. : (body ? body->getLocStart() : forStmt->getLocStart()),
  1543. /*merge*/ mergeBB, continueBB, spv::SelectionControlMask::MaskNone,
  1544. loopControl);
  1545. spvBuilder.addSuccessor(bodyBB);
  1546. spvBuilder.addSuccessor(mergeBB);
  1547. // The current basic block has OpLoopMerge instruction. We need to set its
  1548. // continue and merge target.
  1549. spvBuilder.setContinueTarget(continueBB);
  1550. spvBuilder.setMergeTarget(mergeBB);
  1551. // Process the <body> block
  1552. spvBuilder.setInsertPoint(bodyBB);
  1553. if (body) {
  1554. doStmt(body);
  1555. }
  1556. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1557. spvBuilder.createBranch(continueBB, forStmt->getLocEnd());
  1558. spvBuilder.addSuccessor(continueBB);
  1559. // Process the <continue> block
  1560. spvBuilder.setInsertPoint(continueBB);
  1561. if (const Expr *cont = forStmt->getInc()) {
  1562. doExpr(cont);
  1563. }
  1564. // <continue> should jump back to header
  1565. spvBuilder.createBranch(checkBB, forStmt->getLocEnd());
  1566. spvBuilder.addSuccessor(checkBB);
  1567. // Set insertion point to the <merge> block for subsequent statements
  1568. spvBuilder.setInsertPoint(mergeBB);
  1569. // Done with the current scope's continue block and merge block.
  1570. continueStack.pop();
  1571. breakStack.pop();
  1572. }
  1573. void SpirvEmitter::doIfStmt(const IfStmt *ifStmt,
  1574. llvm::ArrayRef<const Attr *> attrs) {
  1575. // if statements are composed of:
  1576. // if (<check>) { <then> } else { <else> }
  1577. //
  1578. // To translate if statements, we'll need to emit the <check> expressions
  1579. // in the current basic block, and then create separate basic blocks for
  1580. // <then> and <else>. Additionally, we'll need a <merge> block as per
  1581. // SPIR-V's structured control flow requirements. Depending whether there
  1582. // exists the else branch, the final CFG should normally be like the
  1583. // following. Exceptions will occur with non-local exits like loop breaks
  1584. // or early returns.
  1585. // +-------+ +-------+
  1586. // | check | | check |
  1587. // +-------+ +-------+
  1588. // | |
  1589. // +-------+-------+ +-----+-----+
  1590. // | true | false | true | false
  1591. // v v or v |
  1592. // +------+ +------+ +------+ |
  1593. // | then | | else | | then | |
  1594. // +------+ +------+ +------+ |
  1595. // | | | v
  1596. // | +-------+ | | +-------+
  1597. // +-> | merge | <-+ +---> | merge |
  1598. // +-------+ +-------+
  1599. { // Try to see if we can const-eval the condition
  1600. bool condition = false;
  1601. if (ifStmt->getCond()->EvaluateAsBooleanCondition(condition, astContext)) {
  1602. if (condition) {
  1603. doStmt(ifStmt->getThen());
  1604. } else if (ifStmt->getElse()) {
  1605. doStmt(ifStmt->getElse());
  1606. }
  1607. return;
  1608. }
  1609. }
  1610. auto selectionControl = spv::SelectionControlMask::MaskNone;
  1611. if (!attrs.empty()) {
  1612. const Attr *attribute = attrs.front();
  1613. switch (attribute->getKind()) {
  1614. case attr::HLSLBranch:
  1615. selectionControl = spv::SelectionControlMask::DontFlatten;
  1616. break;
  1617. case attr::HLSLFlatten:
  1618. selectionControl = spv::SelectionControlMask::Flatten;
  1619. break;
  1620. default:
  1621. if (!spirvOptions.noWarnIgnoredFeatures) {
  1622. emitWarning("unknown if statement attribute '%0' ignored",
  1623. attribute->getLocation())
  1624. << attribute->getSpelling();
  1625. }
  1626. break;
  1627. }
  1628. }
  1629. if (const auto *declStmt = ifStmt->getConditionVariableDeclStmt())
  1630. doDeclStmt(declStmt);
  1631. // First emit the instruction for evaluating the condition.
  1632. auto *condition = doExpr(ifStmt->getCond());
  1633. // Then we need to emit the instruction for the conditional branch.
  1634. // We'll need the <label-id> for the then/else/merge block to do so.
  1635. const bool hasElse = ifStmt->getElse() != nullptr;
  1636. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  1637. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  1638. auto *elseBB = hasElse ? spvBuilder.createBasicBlock("if.false") : mergeBB;
  1639. // Create the branch instruction. This will end the current basic block.
  1640. const auto *then = ifStmt->getThen();
  1641. spvBuilder.createConditionalBranch(condition, thenBB, elseBB,
  1642. then->getLocStart(), mergeBB,
  1643. /*continue*/ 0, selectionControl);
  1644. spvBuilder.addSuccessor(thenBB);
  1645. spvBuilder.addSuccessor(elseBB);
  1646. // The current basic block has the OpSelectionMerge instruction. We need
  1647. // to record its merge target.
  1648. spvBuilder.setMergeTarget(mergeBB);
  1649. // Handle the then branch
  1650. spvBuilder.setInsertPoint(thenBB);
  1651. doStmt(then);
  1652. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1653. spvBuilder.createBranch(mergeBB, ifStmt->getLocEnd());
  1654. spvBuilder.addSuccessor(mergeBB);
  1655. // Handle the else branch (if exists)
  1656. if (hasElse) {
  1657. spvBuilder.setInsertPoint(elseBB);
  1658. const auto *elseStmt = ifStmt->getElse();
  1659. doStmt(elseStmt);
  1660. if (!spvBuilder.isCurrentBasicBlockTerminated())
  1661. spvBuilder.createBranch(mergeBB, elseStmt->getLocEnd());
  1662. spvBuilder.addSuccessor(mergeBB);
  1663. }
  1664. // From now on, we'll emit instructions into the merge block.
  1665. spvBuilder.setInsertPoint(mergeBB);
  1666. }
  1667. void SpirvEmitter::doReturnStmt(const ReturnStmt *stmt) {
  1668. if (const auto *retVal = stmt->getRetValue()) {
  1669. // Update counter variable associated with function returns
  1670. tryToAssignCounterVar(curFunction, retVal);
  1671. auto *retInfo = loadIfGLValue(retVal);
  1672. if (!retInfo)
  1673. return;
  1674. auto retType = retVal->getType();
  1675. if (retInfo->getStorageClass() != spv::StorageClass::Function &&
  1676. retType->isStructureType()) {
  1677. // We are returning some value from a non-Function storage class. Need to
  1678. // create a temporary variable to "convert" the value to Function storage
  1679. // class and then return.
  1680. auto *tempVar =
  1681. spvBuilder.addFnVar(retType, retVal->getLocEnd(), "temp.var.ret");
  1682. storeValue(tempVar, retInfo, retType, retVal->getLocEnd());
  1683. spvBuilder.createReturnValue(
  1684. spvBuilder.createLoad(retType, tempVar, retVal->getLocEnd()),
  1685. stmt->getReturnLoc());
  1686. } else {
  1687. spvBuilder.createReturnValue(retInfo, stmt->getReturnLoc());
  1688. }
  1689. } else {
  1690. spvBuilder.createReturn(stmt->getReturnLoc());
  1691. }
  1692. // We are translating a ReturnStmt, we should be in some function's body.
  1693. assert(curFunction->hasBody());
  1694. // If this return statement is the last statement in the function, then
  1695. // whe have no more work to do.
  1696. if (cast<CompoundStmt>(curFunction->getBody())->body_back() == stmt)
  1697. return;
  1698. // Some statements that alter the control flow (break, continue, return, and
  1699. // discard), require creation of a new basic block to hold any statement that
  1700. // may follow them. In this case, the newly created basic block will contain
  1701. // any statement that may come after an early return.
  1702. auto *newBB = spvBuilder.createBasicBlock();
  1703. spvBuilder.setInsertPoint(newBB);
  1704. }
  1705. void SpirvEmitter::doBreakStmt(const BreakStmt *breakStmt) {
  1706. assert(!spvBuilder.isCurrentBasicBlockTerminated());
  1707. auto *breakTargetBB = breakStack.top();
  1708. spvBuilder.addSuccessor(breakTargetBB);
  1709. spvBuilder.createBranch(breakTargetBB, breakStmt->getLocStart());
  1710. // Some statements that alter the control flow (break, continue, return, and
  1711. // discard), require creation of a new basic block to hold any statement that
  1712. // may follow them. For example: StmtB and StmtC below are put inside a new
  1713. // basic block which is unreachable.
  1714. //
  1715. // while (true) {
  1716. // StmtA;
  1717. // break;
  1718. // StmtB;
  1719. // StmtC;
  1720. // }
  1721. auto *newBB = spvBuilder.createBasicBlock();
  1722. spvBuilder.setInsertPoint(newBB);
  1723. }
  1724. void SpirvEmitter::doSwitchStmt(const SwitchStmt *switchStmt,
  1725. llvm::ArrayRef<const Attr *> attrs) {
  1726. // Switch statements are composed of:
  1727. // switch (<condition variable>) {
  1728. // <CaseStmt>
  1729. // <CaseStmt>
  1730. // <CaseStmt>
  1731. // <DefaultStmt> (optional)
  1732. // }
  1733. //
  1734. // +-------+
  1735. // | check |
  1736. // +-------+
  1737. // |
  1738. // +-------+-------+----------------+---------------+
  1739. // | 1 | 2 | 3 | (others)
  1740. // v v v v
  1741. // +-------+ +-------------+ +-------+ +------------+
  1742. // | case1 | | case2 | | case3 | ... | default |
  1743. // | | |(fallthrough)|---->| | | (optional) |
  1744. // +-------+ |+------------+ +-------+ +------------+
  1745. // | | |
  1746. // | | |
  1747. // | +-------+ | |
  1748. // | | | <--------------------+ |
  1749. // +-> | merge | |
  1750. // | | <-------------------------------------+
  1751. // +-------+
  1752. // If no attributes are given, or if "forcecase" attribute was provided,
  1753. // we'll do our best to use OpSwitch if possible.
  1754. // If any of the cases compares to a variable (rather than an integer
  1755. // literal), we cannot use OpSwitch because OpSwitch expects literal
  1756. // numbers as parameters.
  1757. const bool isAttrForceCase =
  1758. !attrs.empty() && attrs.front()->getKind() == attr::HLSLForceCase;
  1759. const bool canUseSpirvOpSwitch =
  1760. (attrs.empty() || isAttrForceCase) &&
  1761. allSwitchCasesAreIntegerLiterals(switchStmt->getBody());
  1762. if (isAttrForceCase && !canUseSpirvOpSwitch &&
  1763. !spirvOptions.noWarnIgnoredFeatures) {
  1764. emitWarning("ignored 'forcecase' attribute for the switch statement "
  1765. "since one or more case values are not integer literals",
  1766. switchStmt->getLocStart());
  1767. }
  1768. if (canUseSpirvOpSwitch)
  1769. processSwitchStmtUsingSpirvOpSwitch(switchStmt);
  1770. else
  1771. processSwitchStmtUsingIfStmts(switchStmt);
  1772. }
  1773. SpirvInstruction *
  1774. SpirvEmitter::doArraySubscriptExpr(const ArraySubscriptExpr *expr) {
  1775. llvm::SmallVector<SpirvInstruction *, 4> indices;
  1776. const auto *base = collectArrayStructIndices(
  1777. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  1778. auto *info = loadIfAliasVarRef(base);
  1779. if (!indices.empty()) {
  1780. info = turnIntoElementPtr(base->getType(), info, expr->getType(), indices,
  1781. base->getExprLoc());
  1782. }
  1783. return info;
  1784. }
  1785. SpirvInstruction *SpirvEmitter::doBinaryOperator(const BinaryOperator *expr) {
  1786. const auto opcode = expr->getOpcode();
  1787. // Handle assignment first since we need to evaluate rhs before lhs.
  1788. // For other binary operations, we need to evaluate lhs before rhs.
  1789. if (opcode == BO_Assign) {
  1790. // Update counter variable associated with lhs of assignments
  1791. tryToAssignCounterVar(expr->getLHS(), expr->getRHS());
  1792. return processAssignment(expr->getLHS(), loadIfGLValue(expr->getRHS()),
  1793. /*isCompoundAssignment=*/false);
  1794. }
  1795. // Try to optimize floatMxN * float and floatN * float case
  1796. if (opcode == BO_Mul) {
  1797. if (auto *result = tryToGenFloatMatrixScale(expr))
  1798. return result;
  1799. if (auto *result = tryToGenFloatVectorScale(expr))
  1800. return result;
  1801. }
  1802. return processBinaryOp(expr->getLHS(), expr->getRHS(), opcode,
  1803. expr->getLHS()->getType(), expr->getType(),
  1804. expr->getSourceRange(), expr->getOperatorLoc());
  1805. }
  1806. SpirvInstruction *SpirvEmitter::doCallExpr(const CallExpr *callExpr) {
  1807. if (const auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(callExpr))
  1808. return doCXXOperatorCallExpr(operatorCall);
  1809. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr))
  1810. return doCXXMemberCallExpr(memberCall);
  1811. // Intrinsic functions such as 'dot' or 'mul'
  1812. if (hlsl::IsIntrinsicOp(callExpr->getDirectCallee())) {
  1813. return processIntrinsicCallExpr(callExpr);
  1814. }
  1815. // Normal standalone functions
  1816. return processCall(callExpr);
  1817. }
  1818. SpirvInstruction *SpirvEmitter::processCall(const CallExpr *callExpr) {
  1819. const FunctionDecl *callee = getCalleeDefinition(callExpr);
  1820. // Note that we always want the defintion because Stmts/Exprs in the
  1821. // function body references the parameters in the definition.
  1822. if (!callee) {
  1823. emitError("found undefined function", callExpr->getExprLoc());
  1824. return nullptr;
  1825. }
  1826. const auto paramTypeMatchesArgType = [](QualType paramType,
  1827. QualType argType) {
  1828. if (argType == paramType)
  1829. return true;
  1830. if (const auto *refType = paramType->getAs<ReferenceType>())
  1831. paramType = refType->getPointeeType();
  1832. auto argUnqualifiedType = argType->getUnqualifiedDesugaredType();
  1833. auto paramUnqualifiedType = paramType->getUnqualifiedDesugaredType();
  1834. if (argUnqualifiedType == paramUnqualifiedType)
  1835. return true;
  1836. return false;
  1837. };
  1838. const auto numParams = callee->getNumParams();
  1839. bool isNonStaticMemberCall = false;
  1840. QualType objectType = {}; // Type of the object (if exists)
  1841. SpirvInstruction *objInstr = nullptr; // EvalInfo for the object (if exists)
  1842. llvm::SmallVector<SpirvInstruction *, 4> vars; // Variables for function call
  1843. llvm::SmallVector<bool, 4> isTempVar; // Temporary variable or not
  1844. llvm::SmallVector<SpirvInstruction *, 4> args; // Evaluated arguments
  1845. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr)) {
  1846. const auto *memberFn = cast<CXXMethodDecl>(memberCall->getCalleeDecl());
  1847. isNonStaticMemberCall = !memberFn->isStatic();
  1848. if (isNonStaticMemberCall) {
  1849. // For non-static member calls, evaluate the object and pass it as the
  1850. // first argument.
  1851. const auto *object = memberCall->getImplicitObjectArgument();
  1852. object = object->IgnoreParenNoopCasts(astContext);
  1853. // Update counter variable associated with the implicit object
  1854. tryToAssignCounterVar(getOrCreateDeclForMethodObject(memberFn), object);
  1855. objectType = object->getType();
  1856. objInstr = doExpr(object);
  1857. // If not already a variable, we need to create a temporary variable and
  1858. // pass the object pointer to the function. Example:
  1859. // getObject().objectMethod();
  1860. // Also, any parameter passed to the member function must be of Function
  1861. // storage class.
  1862. if (objInstr->isRValue()) {
  1863. args.push_back(createTemporaryVar(
  1864. objectType, getAstTypeName(objectType),
  1865. // May need to load to use as initializer
  1866. loadIfGLValue(object, objInstr), object->getLocStart()));
  1867. } else {
  1868. // Based on SPIR-V spec, function parameter must always be in Function
  1869. // scope. If we pass a non-function scope argument, we need
  1870. // the legalization.
  1871. if (objInstr->getStorageClass() != spv::StorageClass::Function)
  1872. beforeHlslLegalization = true;
  1873. args.push_back(objInstr);
  1874. }
  1875. // We do not need to create a new temporary variable for the this
  1876. // object. Use the evaluated argument.
  1877. vars.push_back(args.back());
  1878. isTempVar.push_back(false);
  1879. }
  1880. }
  1881. // Evaluate parameters
  1882. for (uint32_t i = 0; i < numParams; ++i) {
  1883. // We want the argument variable here so that we can write back to it
  1884. // later. We will do the OpLoad of this argument manually. So ingore
  1885. // the LValueToRValue implicit cast here.
  1886. auto *arg = callExpr->getArg(i)->IgnoreParenLValueCasts();
  1887. const auto *param = callee->getParamDecl(i);
  1888. // Get the evaluation info if this argument is referencing some variable
  1889. // *as a whole*, in which case we can avoid creating the temporary variable
  1890. // for it if it can act as out parameter.
  1891. SpirvInstruction *argInfo = nullptr;
  1892. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(arg)) {
  1893. argInfo = declIdMapper.getDeclEvalInfo(declRefExpr->getDecl(),
  1894. arg->getLocStart());
  1895. }
  1896. auto *argInst = doExpr(arg);
  1897. auto argType = arg->getType();
  1898. // If argInfo is nullptr and argInst is a rvalue, we do not have a proper
  1899. // pointer to pass to the function. we need a temporary variable in that
  1900. // case.
  1901. if ((argInfo || (argInst && !argInst->isRValue())) &&
  1902. canActAsOutParmVar(param) &&
  1903. paramTypeMatchesArgType(param->getType(), arg->getType())) {
  1904. // Based on SPIR-V spec, function parameter must be always Function
  1905. // scope. In addition, we must pass memory object declaration argument
  1906. // to function. If we pass an argument that is not function scope
  1907. // or not memory object declaration, we need the legalization.
  1908. if (!argInfo || argInfo->getStorageClass() != spv::StorageClass::Function)
  1909. beforeHlslLegalization = true;
  1910. isTempVar.push_back(false);
  1911. args.push_back(argInst);
  1912. vars.push_back(argInfo ? argInfo : argInst);
  1913. } else {
  1914. // We need to create variables for holding the values to be used as
  1915. // arguments. The variables themselves are of pointer types.
  1916. const QualType varType =
  1917. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  1918. const std::string varName = "param.var." + param->getNameAsString();
  1919. // Temporary "param.var.*" variables are used for OpFunctionCall purposes.
  1920. // 'precise' attribute on function parameters only affect computations
  1921. // inside the function, not the variables at the call sites. Therefore, we
  1922. // do not need to mark the "param.var.*" variables as precise.
  1923. const bool isPrecise = false;
  1924. auto *tempVar =
  1925. spvBuilder.addFnVar(varType, arg->getLocStart(), varName, isPrecise);
  1926. vars.push_back(tempVar);
  1927. isTempVar.push_back(true);
  1928. args.push_back(argInst);
  1929. // Update counter variable associated with function parameters
  1930. tryToAssignCounterVar(param, arg);
  1931. // Manually load the argument here
  1932. auto *rhsVal = loadIfGLValue(arg, args.back());
  1933. // The AST does not include cast nodes to and from the function parameter
  1934. // type for 'out' and 'inout' cases. Example:
  1935. //
  1936. // void foo(out half3 param) {...}
  1937. // void main() { float3 arg; foo(arg); }
  1938. //
  1939. // In such cases, we first do a manual cast before passing the argument to
  1940. // the function. And we will cast back the results once the function call
  1941. // has returned.
  1942. if (canActAsOutParmVar(param) &&
  1943. !paramTypeMatchesArgType(param->getType(), arg->getType())) {
  1944. auto paramType = param->getType();
  1945. if (const auto *refType = paramType->getAs<ReferenceType>())
  1946. paramType = refType->getPointeeType();
  1947. rhsVal =
  1948. castToType(rhsVal, arg->getType(), paramType, arg->getLocStart());
  1949. }
  1950. // Initialize the temporary variables using the contents of the arguments
  1951. storeValue(tempVar, rhsVal, param->getType(), arg->getLocStart());
  1952. }
  1953. }
  1954. if (beforeHlslLegalization)
  1955. needsLegalization = true;
  1956. assert(vars.size() == isTempVar.size());
  1957. assert(vars.size() == args.size());
  1958. // Push the callee into the work queue if it is not there.
  1959. addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(), callee,
  1960. /*isEntryFunction*/ false);
  1961. const QualType retType =
  1962. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(callee);
  1963. // Get or forward declare the function <result-id>
  1964. SpirvFunction *func = declIdMapper.getOrRegisterFn(callee);
  1965. auto *retVal = spvBuilder.createFunctionCall(
  1966. retType, func, vars, callExpr->getCallee()->getExprLoc());
  1967. // Go through all parameters and write those marked as out/inout
  1968. for (uint32_t i = 0; i < numParams; ++i) {
  1969. const auto *param = callee->getParamDecl(i);
  1970. // If it calls a non-static member function, the object itself is argument
  1971. // 0, and therefore all other argument positions are shifted by 1.
  1972. const uint32_t index = i + isNonStaticMemberCall;
  1973. if (isTempVar[index] && canActAsOutParmVar(param)) {
  1974. const auto *arg = callExpr->getArg(i);
  1975. SpirvInstruction *value = spvBuilder.createLoad(
  1976. param->getType(), vars[index], arg->getLocStart());
  1977. // Now we want to assign 'value' to arg. But first, in rare cases when
  1978. // using 'out' or 'inout' where the parameter and argument have a type
  1979. // mismatch, we need to first cast 'value' to the type of 'arg' because
  1980. // the AST will not include a cast node.
  1981. if (!paramTypeMatchesArgType(param->getType(), arg->getType())) {
  1982. auto paramType = param->getType();
  1983. if (const auto *refType = paramType->getAs<ReferenceType>())
  1984. paramType = refType->getPointeeType();
  1985. value =
  1986. castToType(value, paramType, arg->getType(), arg->getLocStart());
  1987. }
  1988. processAssignment(arg, value, false, args[index]);
  1989. }
  1990. }
  1991. return retVal;
  1992. }
  1993. SpirvInstruction *SpirvEmitter::doCastExpr(const CastExpr *expr) {
  1994. const Expr *subExpr = expr->getSubExpr();
  1995. const QualType subExprType = subExpr->getType();
  1996. const QualType toType = expr->getType();
  1997. const auto srcLoc = expr->getExprLoc();
  1998. switch (expr->getCastKind()) {
  1999. case CastKind::CK_LValueToRValue:
  2000. return loadIfGLValue(subExpr);
  2001. case CastKind::CK_NoOp:
  2002. return doExpr(subExpr);
  2003. case CastKind::CK_IntegralCast:
  2004. case CastKind::CK_FloatingToIntegral:
  2005. case CastKind::CK_HLSLCC_IntegralCast:
  2006. case CastKind::CK_HLSLCC_FloatingToIntegral: {
  2007. // Integer literals in the AST are represented using 64bit APInt
  2008. // themselves and then implicitly casted into the expected bitwidth.
  2009. // We need special treatment of integer literals here because generating
  2010. // a 64bit constant and then explicit casting in SPIR-V requires Int64
  2011. // capability. We should avoid introducing unnecessary capabilities to
  2012. // our best.
  2013. if (auto *value = tryToEvaluateAsConst(expr)) {
  2014. value->setRValue();
  2015. return value;
  2016. }
  2017. auto *value = castToInt(loadIfGLValue(subExpr), subExprType, toType,
  2018. subExpr->getLocStart());
  2019. value->setRValue();
  2020. return value;
  2021. }
  2022. case CastKind::CK_FloatingCast:
  2023. case CastKind::CK_IntegralToFloating:
  2024. case CastKind::CK_HLSLCC_FloatingCast:
  2025. case CastKind::CK_HLSLCC_IntegralToFloating: {
  2026. // First try to see if we can do constant folding for floating point
  2027. // numbers like what we are doing for integers in the above.
  2028. if (auto *value = tryToEvaluateAsConst(expr)) {
  2029. value->setRValue();
  2030. return value;
  2031. }
  2032. auto *value = castToFloat(loadIfGLValue(subExpr), subExprType, toType,
  2033. subExpr->getLocStart());
  2034. value->setRValue();
  2035. return value;
  2036. }
  2037. case CastKind::CK_IntegralToBoolean:
  2038. case CastKind::CK_FloatingToBoolean:
  2039. case CastKind::CK_HLSLCC_IntegralToBoolean:
  2040. case CastKind::CK_HLSLCC_FloatingToBoolean: {
  2041. // First try to see if we can do constant folding.
  2042. if (auto *value = tryToEvaluateAsConst(expr)) {
  2043. value->setRValue();
  2044. return value;
  2045. }
  2046. auto *value = castToBool(loadIfGLValue(subExpr), subExprType, toType,
  2047. subExpr->getLocStart());
  2048. value->setRValue();
  2049. return value;
  2050. }
  2051. case CastKind::CK_HLSLVectorSplat: {
  2052. const size_t size = hlsl::GetHLSLVecSize(expr->getType());
  2053. return createVectorSplat(subExpr, size);
  2054. }
  2055. case CastKind::CK_HLSLVectorTruncationCast: {
  2056. const QualType toVecType = toType;
  2057. const QualType elemType = hlsl::GetHLSLVecElementType(toType);
  2058. const auto toSize = hlsl::GetHLSLVecSize(toType);
  2059. auto *composite = doExpr(subExpr);
  2060. llvm::SmallVector<SpirvInstruction *, 4> elements;
  2061. for (uint32_t i = 0; i < toSize; ++i) {
  2062. elements.push_back(spvBuilder.createCompositeExtract(
  2063. elemType, composite, {i}, expr->getExprLoc()));
  2064. }
  2065. auto *value = elements.front();
  2066. if (toSize > 1) {
  2067. value = spvBuilder.createCompositeConstruct(toVecType, elements,
  2068. expr->getExprLoc());
  2069. }
  2070. value->setRValue();
  2071. return value;
  2072. }
  2073. case CastKind::CK_HLSLVectorToScalarCast: {
  2074. // The underlying should already be a vector of size 1.
  2075. assert(hlsl::GetHLSLVecSize(subExprType) == 1);
  2076. return doExpr(subExpr);
  2077. }
  2078. case CastKind::CK_HLSLVectorToMatrixCast: {
  2079. // If target type is already an 1xN matrix type, we just return the
  2080. // underlying vector.
  2081. if (is1xNMatrix(toType))
  2082. return doExpr(subExpr);
  2083. // A vector can have no more than 4 elements. The only remaining case
  2084. // is casting from size-4 vector to size-2-by-2 matrix.
  2085. auto *vec = loadIfGLValue(subExpr);
  2086. QualType elemType = {};
  2087. uint32_t rowCount = 0, colCount = 0;
  2088. const bool isMat = isMxNMatrix(toType, &elemType, &rowCount, &colCount);
  2089. assert(isMat && rowCount == 2 && colCount == 2);
  2090. (void)isMat;
  2091. QualType vec2Type = astContext.getExtVectorType(elemType, 2);
  2092. auto *subVec1 = spvBuilder.createVectorShuffle(vec2Type, vec, vec, {0, 1},
  2093. expr->getLocStart());
  2094. auto *subVec2 = spvBuilder.createVectorShuffle(vec2Type, vec, vec, {2, 3},
  2095. expr->getLocStart());
  2096. auto *mat = spvBuilder.createCompositeConstruct(toType, {subVec1, subVec2},
  2097. expr->getLocStart());
  2098. mat->setRValue();
  2099. return mat;
  2100. }
  2101. case CastKind::CK_HLSLMatrixSplat: {
  2102. // From scalar to matrix
  2103. uint32_t rowCount = 0, colCount = 0;
  2104. hlsl::GetHLSLMatRowColCount(toType, rowCount, colCount);
  2105. // Handle degenerated cases first
  2106. if (rowCount == 1 && colCount == 1)
  2107. return doExpr(subExpr);
  2108. if (colCount == 1)
  2109. return createVectorSplat(subExpr, rowCount);
  2110. const auto vecSplat = createVectorSplat(subExpr, colCount);
  2111. if (rowCount == 1)
  2112. return vecSplat;
  2113. if (isa<SpirvConstant>(vecSplat)) {
  2114. llvm::SmallVector<SpirvConstant *, 4> vectors(
  2115. size_t(rowCount), cast<SpirvConstant>(vecSplat));
  2116. auto *value = spvBuilder.getConstantComposite(toType, vectors);
  2117. value->setRValue();
  2118. return value;
  2119. } else {
  2120. llvm::SmallVector<SpirvInstruction *, 4> vectors(size_t(rowCount),
  2121. vecSplat);
  2122. auto *value = spvBuilder.createCompositeConstruct(toType, vectors,
  2123. expr->getLocEnd());
  2124. value->setRValue();
  2125. return value;
  2126. }
  2127. }
  2128. case CastKind::CK_HLSLMatrixTruncationCast: {
  2129. const QualType srcType = subExprType;
  2130. auto *src = doExpr(subExpr);
  2131. const QualType elemType = hlsl::GetHLSLMatElementType(srcType);
  2132. llvm::SmallVector<uint32_t, 4> indexes;
  2133. // It is possible that the source matrix is in fact a vector.
  2134. // For example: Truncate float1x3 --> float1x2.
  2135. // The front-end disallows float1x3 --> float2x1.
  2136. {
  2137. uint32_t srcVecSize = 0, dstVecSize = 0;
  2138. if (isVectorType(srcType, nullptr, &srcVecSize) &&
  2139. isVectorType(toType, nullptr, &dstVecSize)) {
  2140. for (uint32_t i = 0; i < dstVecSize; ++i)
  2141. indexes.push_back(i);
  2142. auto *val = spvBuilder.createVectorShuffle(toType, src, src, indexes,
  2143. expr->getLocStart());
  2144. val->setRValue();
  2145. return val;
  2146. }
  2147. }
  2148. uint32_t srcRows = 0, srcCols = 0, dstRows = 0, dstCols = 0;
  2149. hlsl::GetHLSLMatRowColCount(srcType, srcRows, srcCols);
  2150. hlsl::GetHLSLMatRowColCount(toType, dstRows, dstCols);
  2151. const QualType srcRowType = astContext.getExtVectorType(elemType, srcCols);
  2152. const QualType dstRowType = astContext.getExtVectorType(elemType, dstCols);
  2153. // Indexes to pass to OpVectorShuffle
  2154. for (uint32_t i = 0; i < dstCols; ++i)
  2155. indexes.push_back(i);
  2156. llvm::SmallVector<SpirvInstruction *, 4> extractedVecs;
  2157. for (uint32_t row = 0; row < dstRows; ++row) {
  2158. // Extract a row
  2159. SpirvInstruction *rowInstr = spvBuilder.createCompositeExtract(
  2160. srcRowType, src, {row}, expr->getExprLoc());
  2161. // Extract the necessary columns from that row.
  2162. // The front-end ensures dstCols <= srcCols.
  2163. // If dstCols equals srcCols, we can use the whole row directly.
  2164. if (dstCols == 1) {
  2165. rowInstr = spvBuilder.createCompositeExtract(elemType, rowInstr, {0},
  2166. expr->getLocStart());
  2167. } else if (dstCols < srcCols) {
  2168. rowInstr = spvBuilder.createVectorShuffle(
  2169. dstRowType, rowInstr, rowInstr, indexes, expr->getLocStart());
  2170. }
  2171. extractedVecs.push_back(rowInstr);
  2172. }
  2173. auto *val = extractedVecs.front();
  2174. if (extractedVecs.size() > 1) {
  2175. val = spvBuilder.createCompositeConstruct(toType, extractedVecs,
  2176. expr->getExprLoc());
  2177. }
  2178. val->setRValue();
  2179. return val;
  2180. }
  2181. case CastKind::CK_HLSLMatrixToScalarCast: {
  2182. // The underlying should already be a matrix of 1x1.
  2183. assert(is1x1Matrix(subExprType));
  2184. return doExpr(subExpr);
  2185. }
  2186. case CastKind::CK_HLSLMatrixToVectorCast: {
  2187. // If the underlying matrix is Mx1 or 1xM for M in {1, 2,3,4}, we can return
  2188. // the underlying matrix because it'll be evaluated as a vector by default.
  2189. if (is1x1Matrix(subExprType) || is1xNMatrix(subExprType) ||
  2190. isMx1Matrix(subExprType))
  2191. return doExpr(subExpr);
  2192. // A vector can have no more than 4 elements. The only remaining case
  2193. // is casting from a 2x2 matrix to a vector of size 4.
  2194. auto *mat = loadIfGLValue(subExpr);
  2195. QualType elemType = {};
  2196. uint32_t rowCount = 0, colCount = 0, elemCount = 0;
  2197. const bool isMat =
  2198. isMxNMatrix(subExprType, &elemType, &rowCount, &colCount);
  2199. const bool isVec = isVectorType(toType, nullptr, &elemCount);
  2200. assert(isMat && rowCount == 2 && colCount == 2);
  2201. assert(isVec && elemCount == 4);
  2202. (void)isMat;
  2203. (void)isVec;
  2204. QualType vec2Type = astContext.getExtVectorType(elemType, 2);
  2205. auto *row0 = spvBuilder.createCompositeExtract(vec2Type, mat, {0}, srcLoc);
  2206. auto *row1 = spvBuilder.createCompositeExtract(vec2Type, mat, {1}, srcLoc);
  2207. auto *vec = spvBuilder.createVectorShuffle(toType, row0, row1, {0, 1, 2, 3},
  2208. srcLoc);
  2209. vec->setRValue();
  2210. return vec;
  2211. }
  2212. case CastKind::CK_FunctionToPointerDecay:
  2213. // Just need to return the function id
  2214. return doExpr(subExpr);
  2215. case CastKind::CK_FlatConversion: {
  2216. SpirvInstruction *subExprInstr = nullptr;
  2217. QualType evalType = subExprType;
  2218. // Optimization: we can use OpConstantNull for cases where we want to
  2219. // initialize an entire data structure to zeros.
  2220. if (evaluatesToConstZero(subExpr, astContext)) {
  2221. subExprInstr = spvBuilder.getConstantNull(toType);
  2222. subExprInstr->setRValue();
  2223. return subExprInstr;
  2224. }
  2225. // Try to evaluate float literals as float rather than double.
  2226. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(subExpr)) {
  2227. subExprInstr = tryToEvaluateAsFloat32(floatLiteral->getValue());
  2228. if (subExprInstr)
  2229. evalType = astContext.FloatTy;
  2230. }
  2231. // Evaluate 'literal float' initializer type as float rather than double.
  2232. // TODO: This could result in rounding error if the initializer is a
  2233. // non-literal expression that requires larger than 32 bits and has the
  2234. // 'literal float' type.
  2235. else if (subExprType->isSpecificBuiltinType(BuiltinType::LitFloat)) {
  2236. evalType = astContext.FloatTy;
  2237. }
  2238. // Try to evaluate integer literals as 32-bit int rather than 64-bit int.
  2239. else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(subExpr)) {
  2240. const bool isSigned = subExprType->isSignedIntegerType();
  2241. subExprInstr = tryToEvaluateAsInt32(intLiteral->getValue(), isSigned);
  2242. if (subExprInstr)
  2243. evalType = isSigned ? astContext.IntTy : astContext.UnsignedIntTy;
  2244. }
  2245. // For assigning one array instance to another one with the same array type
  2246. // (regardless of constness and literalness), the rhs will be wrapped in a
  2247. // FlatConversion. Similarly for assigning a struct to another struct with
  2248. // identical members.
  2249. // |- <lhs>
  2250. // `- ImplicitCastExpr <FlatConversion>
  2251. // `- ImplicitCastExpr <LValueToRValue>
  2252. // `- <rhs>
  2253. else if (isSameType(astContext, toType, evalType) ||
  2254. // We can have casts changing the shape but without affecting
  2255. // memory order, e.g., `float4 a[2]; float b[8] = (float[8])a;`.
  2256. // This is also represented as FlatConversion. For such cases, we
  2257. // can rely on the InitListHandler, which can decompse
  2258. // vectors/matrices.
  2259. subExprType->isArrayType()) {
  2260. auto *valInstr =
  2261. InitListHandler(astContext, *this).processCast(toType, subExpr);
  2262. if (valInstr)
  2263. valInstr->setRValue();
  2264. return valInstr;
  2265. }
  2266. // We can have casts changing the shape but without affecting memory order,
  2267. // e.g., `float4 a[2]; float b[8] = (float[8])a;`. This is also represented
  2268. // as FlatConversion. For such cases, we can rely on the InitListHandler,
  2269. // which can decompse vectors/matrices.
  2270. else if (subExprType->isArrayType()) {
  2271. auto *valInstr = InitListHandler(astContext, *this)
  2272. .processCast(expr->getType(), subExpr);
  2273. if (valInstr)
  2274. valInstr->setRValue();
  2275. return valInstr;
  2276. }
  2277. if (!subExprInstr)
  2278. subExprInstr = doExpr(subExpr);
  2279. auto *val = processFlatConversion(toType, evalType, subExprInstr,
  2280. expr->getExprLoc());
  2281. val->setRValue();
  2282. return val;
  2283. }
  2284. case CastKind::CK_UncheckedDerivedToBase:
  2285. case CastKind::CK_HLSLDerivedToBase: {
  2286. // Find the index sequence of the base to which we are casting
  2287. llvm::SmallVector<uint32_t, 4> baseIndices;
  2288. getBaseClassIndices(expr, &baseIndices);
  2289. // Turn them in to SPIR-V constants
  2290. llvm::SmallVector<SpirvInstruction *, 4> baseIndexInstructions(
  2291. baseIndices.size(), nullptr);
  2292. for (uint32_t i = 0; i < baseIndices.size(); ++i)
  2293. baseIndexInstructions[i] = spvBuilder.getConstantInt(
  2294. astContext.UnsignedIntTy, llvm::APInt(32, baseIndices[i]));
  2295. auto *derivedInfo = doExpr(subExpr);
  2296. return turnIntoElementPtr(subExpr->getType(), derivedInfo, expr->getType(),
  2297. baseIndexInstructions, subExpr->getExprLoc());
  2298. }
  2299. case CastKind::CK_ArrayToPointerDecay: {
  2300. // Literal string to const string conversion falls under this category.
  2301. if (hlsl::IsStringLiteralType(subExprType) && hlsl::IsStringType(toType)) {
  2302. return doExpr(subExpr);
  2303. } else {
  2304. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  2305. << expr->getCastKindName() << expr->getSourceRange();
  2306. expr->dump();
  2307. return 0;
  2308. }
  2309. }
  2310. default:
  2311. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  2312. << expr->getCastKindName() << expr->getSourceRange();
  2313. expr->dump();
  2314. return 0;
  2315. }
  2316. }
  2317. SpirvInstruction *SpirvEmitter::processFlatConversion(
  2318. const QualType type, const QualType initType, SpirvInstruction *initInstr,
  2319. SourceLocation srcLoc) {
  2320. // Try to translate the canonical type first
  2321. const auto canonicalType = type.getCanonicalType();
  2322. if (canonicalType != type)
  2323. return processFlatConversion(canonicalType, initType, initInstr, srcLoc);
  2324. // Primitive types
  2325. {
  2326. QualType ty = {};
  2327. if (isScalarType(type, &ty)) {
  2328. if (const auto *builtinType = ty->getAs<BuiltinType>()) {
  2329. switch (builtinType->getKind()) {
  2330. case BuiltinType::Void: {
  2331. emitError("cannot create a constant of void type", srcLoc);
  2332. return 0;
  2333. }
  2334. case BuiltinType::Bool:
  2335. return castToBool(initInstr, initType, ty, srcLoc);
  2336. // Target type is an integer variant.
  2337. case BuiltinType::Int:
  2338. case BuiltinType::Short:
  2339. case BuiltinType::Min12Int:
  2340. case BuiltinType::Min16Int:
  2341. case BuiltinType::Min16UInt:
  2342. case BuiltinType::UShort:
  2343. case BuiltinType::UInt:
  2344. case BuiltinType::Long:
  2345. case BuiltinType::LongLong:
  2346. case BuiltinType::ULong:
  2347. case BuiltinType::ULongLong:
  2348. return castToInt(initInstr, initType, ty, srcLoc);
  2349. // Target type is a float variant.
  2350. case BuiltinType::Double:
  2351. case BuiltinType::Float:
  2352. case BuiltinType::Half:
  2353. case BuiltinType::HalfFloat:
  2354. case BuiltinType::Min10Float:
  2355. case BuiltinType::Min16Float:
  2356. return castToFloat(initInstr, initType, ty, srcLoc);
  2357. default:
  2358. emitError("flat conversion of type %0 unimplemented", srcLoc)
  2359. << builtinType->getTypeClassName();
  2360. return 0;
  2361. }
  2362. }
  2363. }
  2364. }
  2365. // Vector types
  2366. {
  2367. QualType elemType = {};
  2368. uint32_t elemCount = {};
  2369. if (isVectorType(type, &elemType, &elemCount)) {
  2370. auto *elem = processFlatConversion(elemType, initType, initInstr, srcLoc);
  2371. llvm::SmallVector<SpirvInstruction *, 4> constituents(size_t(elemCount),
  2372. elem);
  2373. return spvBuilder.createCompositeConstruct(type, constituents, srcLoc);
  2374. }
  2375. }
  2376. // Matrix types
  2377. {
  2378. QualType elemType = {};
  2379. uint32_t rowCount = 0, colCount = 0;
  2380. if (isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  2381. // By default HLSL matrices are row major, while SPIR-V matrices are
  2382. // column major. We are mapping what HLSL semantically mean a row into a
  2383. // column here.
  2384. const QualType vecType = astContext.getExtVectorType(elemType, colCount);
  2385. auto *elem = processFlatConversion(elemType, initType, initInstr, srcLoc);
  2386. const llvm::SmallVector<SpirvInstruction *, 4> constituents(
  2387. size_t(colCount), elem);
  2388. auto *col =
  2389. spvBuilder.createCompositeConstruct(vecType, constituents, srcLoc);
  2390. const llvm::SmallVector<SpirvInstruction *, 4> rows(size_t(rowCount),
  2391. col);
  2392. return spvBuilder.createCompositeConstruct(type, rows, srcLoc);
  2393. }
  2394. }
  2395. // Struct type
  2396. if (const auto *structType = type->getAs<RecordType>()) {
  2397. const auto *decl = structType->getDecl();
  2398. llvm::SmallVector<SpirvInstruction *, 4> fields;
  2399. for (const auto *field : decl->fields()) {
  2400. // There is a special case for FlatConversion. If T is a struct with only
  2401. // one member, S, then (T)<an-instance-of-S> is allowed, which essentially
  2402. // constructs a new T instance using the instance of S as its only member.
  2403. // Check whether we are handling that case here first.
  2404. if (field->getType().getCanonicalType() == initType.getCanonicalType()) {
  2405. fields.push_back(initInstr);
  2406. } else {
  2407. fields.push_back(processFlatConversion(field->getType(), initType,
  2408. initInstr, srcLoc));
  2409. }
  2410. }
  2411. return spvBuilder.createCompositeConstruct(type, fields, srcLoc);
  2412. }
  2413. // Array type
  2414. if (const auto *arrayType = astContext.getAsConstantArrayType(type)) {
  2415. const auto size =
  2416. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  2417. auto *elem = processFlatConversion(arrayType->getElementType(), initType,
  2418. initInstr, srcLoc);
  2419. llvm::SmallVector<SpirvInstruction *, 4> constituents(size_t(size), elem);
  2420. return spvBuilder.createCompositeConstruct(type, constituents, srcLoc);
  2421. }
  2422. emitError("flat conversion of type %0 unimplemented", {})
  2423. << type->getTypeClassName();
  2424. type->dump();
  2425. return 0;
  2426. }
  2427. SpirvInstruction *
  2428. SpirvEmitter::doCompoundAssignOperator(const CompoundAssignOperator *expr) {
  2429. const auto opcode = expr->getOpcode();
  2430. // Try to optimize floatMxN *= float and floatN *= float case
  2431. if (opcode == BO_MulAssign) {
  2432. if (auto *result = tryToGenFloatMatrixScale(expr))
  2433. return result;
  2434. if (auto *result = tryToGenFloatVectorScale(expr))
  2435. return result;
  2436. }
  2437. const auto *rhs = expr->getRHS();
  2438. const auto *lhs = expr->getLHS();
  2439. SpirvInstruction *lhsPtr = nullptr;
  2440. auto *result = processBinaryOp(
  2441. lhs, rhs, opcode, expr->getComputationLHSType(), expr->getType(),
  2442. expr->getSourceRange(), expr->getOperatorLoc(), &lhsPtr);
  2443. return processAssignment(lhs, result, true, lhsPtr);
  2444. }
  2445. SpirvInstruction *
  2446. SpirvEmitter::doConditionalOperator(const ConditionalOperator *expr) {
  2447. const auto type = expr->getType();
  2448. const SourceLocation loc = expr->getExprLoc();
  2449. // According to HLSL doc, all sides of the ?: expression are always evaluated.
  2450. // If we are selecting between two SampleState objects, none of the three
  2451. // operands has a LValueToRValue implicit cast.
  2452. auto *condition = loadIfGLValue(expr->getCond());
  2453. auto *trueBranch = loadIfGLValue(expr->getTrueExpr());
  2454. auto *falseBranch = loadIfGLValue(expr->getFalseExpr());
  2455. // For cases where the return type is a scalar or a vector, we can use
  2456. // OpSelect to choose between the two. OpSelect's return type must be either
  2457. // scalar or vector.
  2458. if (isScalarType(type) || isVectorType(type)) {
  2459. // The SPIR-V OpSelect instruction must have a selection argument that is
  2460. // the same size as the return type. If the return type is a vector, the
  2461. // selection must be a vector of booleans (one per output component).
  2462. uint32_t count = 0;
  2463. if (isVectorType(expr->getType(), nullptr, &count) &&
  2464. !isVectorType(expr->getCond()->getType())) {
  2465. const llvm::SmallVector<SpirvInstruction *, 4> components(size_t(count),
  2466. condition);
  2467. condition = spvBuilder.createCompositeConstruct(
  2468. astContext.getExtVectorType(astContext.BoolTy, count), components,
  2469. expr->getCond()->getLocEnd());
  2470. }
  2471. auto *value =
  2472. spvBuilder.createSelect(type, condition, trueBranch, falseBranch, loc);
  2473. value->setRValue();
  2474. return value;
  2475. }
  2476. // If we can't use OpSelect, we need to create if-else control flow.
  2477. auto *tempVar = spvBuilder.addFnVar(type, loc, "temp.var.ternary");
  2478. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  2479. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  2480. auto *elseBB = spvBuilder.createBasicBlock("if.false");
  2481. // Create the branch instruction. This will end the current basic block.
  2482. spvBuilder.createConditionalBranch(condition, thenBB, elseBB,
  2483. expr->getCond()->getLocEnd(), mergeBB);
  2484. spvBuilder.addSuccessor(thenBB);
  2485. spvBuilder.addSuccessor(elseBB);
  2486. spvBuilder.setMergeTarget(mergeBB);
  2487. // Handle the then branch
  2488. spvBuilder.setInsertPoint(thenBB);
  2489. spvBuilder.createStore(tempVar, trueBranch,
  2490. expr->getTrueExpr()->getLocStart());
  2491. spvBuilder.createBranch(mergeBB, expr->getTrueExpr()->getLocEnd());
  2492. spvBuilder.addSuccessor(mergeBB);
  2493. // Handle the else branch
  2494. spvBuilder.setInsertPoint(elseBB);
  2495. spvBuilder.createStore(tempVar, falseBranch,
  2496. expr->getFalseExpr()->getLocStart());
  2497. spvBuilder.createBranch(mergeBB, expr->getFalseExpr()->getLocEnd());
  2498. spvBuilder.addSuccessor(mergeBB);
  2499. // From now on, emit instructions into the merge block.
  2500. spvBuilder.setInsertPoint(mergeBB);
  2501. auto *result = spvBuilder.createLoad(type, tempVar, expr->getLocEnd());
  2502. result->setRValue();
  2503. return result;
  2504. }
  2505. SpirvInstruction *
  2506. SpirvEmitter::processByteAddressBufferStructuredBufferGetDimensions(
  2507. const CXXMemberCallExpr *expr) {
  2508. const auto *object = expr->getImplicitObjectArgument();
  2509. auto *objectInstr = loadIfAliasVarRef(object);
  2510. const auto type = object->getType();
  2511. const bool isBABuf = isByteAddressBuffer(type) || isRWByteAddressBuffer(type);
  2512. const bool isStructuredBuf = isStructuredBuffer(type) ||
  2513. isAppendStructuredBuffer(type) ||
  2514. isConsumeStructuredBuffer(type);
  2515. assert(isBABuf || isStructuredBuf);
  2516. // (RW)ByteAddressBuffers/(RW)StructuredBuffers are represented as a structure
  2517. // with only one member that is a runtime array. We need to perform
  2518. // OpArrayLength on member 0.
  2519. SpirvInstruction *length = spvBuilder.createArrayLength(
  2520. astContext.UnsignedIntTy, expr->getExprLoc(), objectInstr, 0);
  2521. // For (RW)ByteAddressBuffers, GetDimensions() must return the array length
  2522. // in bytes, but OpArrayLength returns the number of uints in the runtime
  2523. // array. Therefore we must multiply the results by 4.
  2524. if (isBABuf) {
  2525. length = spvBuilder.createBinaryOp(
  2526. spv::Op::OpIMul, astContext.UnsignedIntTy, length,
  2527. // TODO(jaebaek): What line info we should emit for constants?
  2528. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2529. llvm::APInt(32, 4u)),
  2530. expr->getExprLoc());
  2531. }
  2532. spvBuilder.createStore(doExpr(expr->getArg(0)), length,
  2533. expr->getArg(0)->getLocStart());
  2534. if (isStructuredBuf) {
  2535. // For (RW)StructuredBuffer, the stride of the runtime array (which is the
  2536. // size of the struct) must also be written to the second argument.
  2537. AlignmentSizeCalculator alignmentCalc(astContext, spirvOptions);
  2538. uint32_t size = 0, stride = 0;
  2539. std::tie(std::ignore, size) =
  2540. alignmentCalc.getAlignmentAndSize(type, spirvOptions.sBufferLayoutRule,
  2541. /*isRowMajor*/ llvm::None, &stride);
  2542. auto *sizeInstr = spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2543. llvm::APInt(32, size));
  2544. spvBuilder.createStore(doExpr(expr->getArg(1)), sizeInstr,
  2545. expr->getArg(1)->getLocStart());
  2546. }
  2547. return nullptr;
  2548. }
  2549. SpirvInstruction *SpirvEmitter::processRWByteAddressBufferAtomicMethods(
  2550. hlsl::IntrinsicOp opcode, const CXXMemberCallExpr *expr) {
  2551. // The signature of RWByteAddressBuffer atomic methods are largely:
  2552. // void Interlocked*(in UINT dest, in UINT value);
  2553. // void Interlocked*(in UINT dest, in UINT value, out UINT original_value);
  2554. const auto *object = expr->getImplicitObjectArgument();
  2555. auto *objectInfo = loadIfAliasVarRef(object);
  2556. auto *zero =
  2557. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  2558. auto *offset = doExpr(expr->getArg(0));
  2559. // Right shift by 2 to convert the byte offset to uint32_t offset
  2560. auto *address = spvBuilder.createBinaryOp(
  2561. spv::Op::OpShiftRightLogical, astContext.UnsignedIntTy, offset,
  2562. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2)),
  2563. expr->getExprLoc());
  2564. auto *ptr =
  2565. spvBuilder.createAccessChain(astContext.UnsignedIntTy, objectInfo,
  2566. {zero, address}, object->getLocStart());
  2567. const bool isCompareExchange =
  2568. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareExchange;
  2569. const bool isCompareStore =
  2570. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareStore;
  2571. if (isCompareExchange || isCompareStore) {
  2572. auto *comparator = doExpr(expr->getArg(1));
  2573. auto *originalVal = spvBuilder.createAtomicCompareExchange(
  2574. astContext.UnsignedIntTy, ptr, spv::Scope::Device,
  2575. spv::MemorySemanticsMask::MaskNone, spv::MemorySemanticsMask::MaskNone,
  2576. doExpr(expr->getArg(2)), comparator, expr->getCallee()->getExprLoc());
  2577. if (isCompareExchange)
  2578. spvBuilder.createStore(doExpr(expr->getArg(3)), originalVal,
  2579. expr->getArg(3)->getLocStart());
  2580. } else {
  2581. auto *value = doExpr(expr->getArg(1));
  2582. SpirvInstruction *originalVal = spvBuilder.createAtomicOp(
  2583. translateAtomicHlslOpcodeToSpirvOpcode(opcode),
  2584. astContext.UnsignedIntTy, ptr, spv::Scope::Device,
  2585. spv::MemorySemanticsMask::MaskNone, value,
  2586. expr->getCallee()->getExprLoc());
  2587. if (expr->getNumArgs() > 2) {
  2588. originalVal = castToType(originalVal, astContext.UnsignedIntTy,
  2589. expr->getArg(2)->getType(),
  2590. expr->getArg(2)->getLocStart());
  2591. spvBuilder.createStore(doExpr(expr->getArg(2)), originalVal,
  2592. expr->getArg(2)->getLocStart());
  2593. }
  2594. }
  2595. return nullptr;
  2596. }
  2597. SpirvInstruction *
  2598. SpirvEmitter::processGetSamplePosition(const CXXMemberCallExpr *expr) {
  2599. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2600. auto *sampleCount = spvBuilder.createImageQuery(
  2601. spv::Op::OpImageQuerySamples, astContext.UnsignedIntTy,
  2602. expr->getExprLoc(), loadIfGLValue(object));
  2603. if (!spirvOptions.noWarnEmulatedFeatures)
  2604. emitWarning("GetSamplePosition is emulated using many SPIR-V instructions "
  2605. "due to lack of direct SPIR-V equivalent, so it only supports "
  2606. "standard sample settings with 1, 2, 4, 8, or 16 samples and "
  2607. "will return float2(0, 0) for other cases",
  2608. expr->getCallee()->getExprLoc());
  2609. return emitGetSamplePosition(sampleCount, doExpr(expr->getArg(0)),
  2610. expr->getCallee()->getExprLoc());
  2611. }
  2612. SpirvInstruction *
  2613. SpirvEmitter::processSubpassLoad(const CXXMemberCallExpr *expr) {
  2614. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2615. SpirvInstruction *sample =
  2616. expr->getNumArgs() == 1 ? doExpr(expr->getArg(0)) : nullptr;
  2617. auto *zero = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  2618. auto *location = spvBuilder.getConstantComposite(
  2619. astContext.getExtVectorType(astContext.IntTy, 2), {zero, zero});
  2620. return processBufferTextureLoad(object, location, /*constOffset*/ 0,
  2621. /*varOffset*/ 0, /*lod*/ sample,
  2622. /*residencyCode*/ 0, expr->getExprLoc());
  2623. }
  2624. SpirvInstruction *
  2625. SpirvEmitter::processBufferTextureGetDimensions(const CXXMemberCallExpr *expr) {
  2626. const auto *object = expr->getImplicitObjectArgument();
  2627. auto *objectInstr = loadIfGLValue(object);
  2628. const auto type = object->getType();
  2629. const auto *recType = type->getAs<RecordType>();
  2630. assert(recType);
  2631. const auto typeName = recType->getDecl()->getName();
  2632. const auto numArgs = expr->getNumArgs();
  2633. const Expr *mipLevel = nullptr, *numLevels = nullptr, *numSamples = nullptr;
  2634. assert(isTexture(type) || isRWTexture(type) || isBuffer(type) ||
  2635. isRWBuffer(type));
  2636. // For Texture1D, arguments are either:
  2637. // a) width
  2638. // b) MipLevel, width, NumLevels
  2639. // For Texture1DArray, arguments are either:
  2640. // a) width, elements
  2641. // b) MipLevel, width, elements, NumLevels
  2642. // For Texture2D, arguments are either:
  2643. // a) width, height
  2644. // b) MipLevel, width, height, NumLevels
  2645. // For Texture2DArray, arguments are either:
  2646. // a) width, height, elements
  2647. // b) MipLevel, width, height, elements, NumLevels
  2648. // For Texture3D, arguments are either:
  2649. // a) width, height, depth
  2650. // b) MipLevel, width, height, depth, NumLevels
  2651. // For Texture2DMS, arguments are: width, height, NumSamples
  2652. // For Texture2DMSArray, arguments are: width, height, elements, NumSamples
  2653. // For TextureCube, arguments are either:
  2654. // a) width, height
  2655. // b) MipLevel, width, height, NumLevels
  2656. // For TextureCubeArray, arguments are either:
  2657. // a) width, height, elements
  2658. // b) MipLevel, width, height, elements, NumLevels
  2659. // Note: SPIR-V Spec requires return type of OpImageQuerySize(Lod) to be a
  2660. // scalar/vector of integers. SPIR-V Spec also requires return type of
  2661. // OpImageQueryLevels and OpImageQuerySamples to be scalar integers.
  2662. // The HLSL methods, however, have overloaded functions which have float
  2663. // output arguments. Since the AST naturally won't have casting AST nodes for
  2664. // such cases, we'll have to perform the cast ourselves.
  2665. const auto storeToOutputArg = [this](const Expr *outputArg,
  2666. SpirvInstruction *id, QualType type) {
  2667. id = castToType(id, type, outputArg->getType(), outputArg->getExprLoc());
  2668. spvBuilder.createStore(doExpr(outputArg), id, outputArg->getLocStart());
  2669. };
  2670. if ((typeName == "Texture1D" && numArgs > 1) ||
  2671. (typeName == "Texture2D" && numArgs > 2) ||
  2672. (typeName == "TextureCube" && numArgs > 2) ||
  2673. (typeName == "Texture3D" && numArgs > 3) ||
  2674. (typeName == "Texture1DArray" && numArgs > 2) ||
  2675. (typeName == "TextureCubeArray" && numArgs > 3) ||
  2676. (typeName == "Texture2DArray" && numArgs > 3)) {
  2677. mipLevel = expr->getArg(0);
  2678. numLevels = expr->getArg(numArgs - 1);
  2679. }
  2680. if (isTextureMS(type)) {
  2681. numSamples = expr->getArg(numArgs - 1);
  2682. }
  2683. uint32_t querySize = numArgs;
  2684. // If numLevels arg is present, mipLevel must also be present. These are not
  2685. // queried via ImageQuerySizeLod.
  2686. if (numLevels)
  2687. querySize -= 2;
  2688. // If numLevels arg is present, mipLevel must also be present.
  2689. else if (numSamples)
  2690. querySize -= 1;
  2691. const QualType resultQualType =
  2692. querySize == 1
  2693. ? astContext.UnsignedIntTy
  2694. : astContext.getExtVectorType(astContext.UnsignedIntTy, querySize);
  2695. // Only Texture types use ImageQuerySizeLod.
  2696. // TextureMS, RWTexture, Buffers, RWBuffers use ImageQuerySize.
  2697. SpirvInstruction *lod = nullptr;
  2698. if (isTexture(type) && !numSamples) {
  2699. if (mipLevel) {
  2700. // For Texture types when mipLevel argument is present.
  2701. lod = doExpr(mipLevel);
  2702. } else {
  2703. // For Texture types when mipLevel argument is omitted.
  2704. lod = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  2705. }
  2706. }
  2707. SpirvInstruction *query =
  2708. lod ? cast<SpirvInstruction>(spvBuilder.createImageQuery(
  2709. spv::Op::OpImageQuerySizeLod, resultQualType,
  2710. expr->getCallee()->getExprLoc(), objectInstr, lod))
  2711. : cast<SpirvInstruction>(spvBuilder.createImageQuery(
  2712. spv::Op::OpImageQuerySize, resultQualType,
  2713. expr->getCallee()->getExprLoc(), objectInstr));
  2714. if (querySize == 1) {
  2715. const uint32_t argIndex = mipLevel ? 1 : 0;
  2716. storeToOutputArg(expr->getArg(argIndex), query, resultQualType);
  2717. } else {
  2718. for (uint32_t i = 0; i < querySize; ++i) {
  2719. const uint32_t argIndex = mipLevel ? i + 1 : i;
  2720. auto *component = spvBuilder.createCompositeExtract(
  2721. astContext.UnsignedIntTy, query, {i},
  2722. expr->getCallee()->getExprLoc());
  2723. // If the first arg is the mipmap level, we must write the results
  2724. // starting from Arg(i+1), not Arg(i).
  2725. storeToOutputArg(expr->getArg(argIndex), component,
  2726. astContext.UnsignedIntTy);
  2727. }
  2728. }
  2729. if (numLevels || numSamples) {
  2730. const Expr *numLevelsSamplesArg = numLevels ? numLevels : numSamples;
  2731. const spv::Op opcode =
  2732. numLevels ? spv::Op::OpImageQueryLevels : spv::Op::OpImageQuerySamples;
  2733. auto *numLevelsSamplesQuery = spvBuilder.createImageQuery(
  2734. opcode, astContext.UnsignedIntTy, expr->getCallee()->getExprLoc(),
  2735. objectInstr);
  2736. storeToOutputArg(numLevelsSamplesArg, numLevelsSamplesQuery,
  2737. astContext.UnsignedIntTy);
  2738. }
  2739. return nullptr;
  2740. }
  2741. SpirvInstruction *
  2742. SpirvEmitter::processTextureLevelOfDetail(const CXXMemberCallExpr *expr,
  2743. bool unclamped) {
  2744. // Possible signatures are as follows:
  2745. // Texture1D(Array).CalculateLevelOfDetail(SamplerState S, float x);
  2746. // Texture2D(Array).CalculateLevelOfDetail(SamplerState S, float2 xy);
  2747. // TextureCube(Array).CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2748. // Texture3D.CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2749. // Return type is always a single float (LOD).
  2750. assert(expr->getNumArgs() == 2u);
  2751. const auto *object = expr->getImplicitObjectArgument();
  2752. auto *objectInfo = loadIfGLValue(object);
  2753. auto *samplerState = doExpr(expr->getArg(0));
  2754. auto *coordinate = doExpr(expr->getArg(1));
  2755. auto *sampledImage = spvBuilder.createSampledImage(
  2756. object->getType(), objectInfo, samplerState, expr->getExprLoc());
  2757. // The result type of OpImageQueryLod must be a float2.
  2758. const QualType queryResultType =
  2759. astContext.getExtVectorType(astContext.FloatTy, 2u);
  2760. auto *query =
  2761. spvBuilder.createImageQuery(spv::Op::OpImageQueryLod, queryResultType,
  2762. expr->getExprLoc(), sampledImage, coordinate);
  2763. // The first component of the float2 contains the mipmap array layer.
  2764. // The second component of the float2 represents the unclamped lod.
  2765. return spvBuilder.createCompositeExtract(astContext.FloatTy, query,
  2766. unclamped ? 1 : 0,
  2767. expr->getCallee()->getExprLoc());
  2768. }
  2769. SpirvInstruction *SpirvEmitter::processTextureGatherRGBACmpRGBA(
  2770. const CXXMemberCallExpr *expr, const bool isCmp, const uint32_t component) {
  2771. // Parameters for .Gather{Red|Green|Blue|Alpha}() are one of the following
  2772. // two sets:
  2773. // * SamplerState s, float2 location, int2 offset
  2774. // * SamplerState s, float2 location, int2 offset0, int2 offset1,
  2775. // int offset2, int2 offset3
  2776. //
  2777. // An additional 'out uint status' parameter can appear in both of the above.
  2778. //
  2779. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() are one of the following
  2780. // two sets:
  2781. // * SamplerState s, float2 location, float compare_value, int2 offset
  2782. // * SamplerState s, float2 location, float compare_value, int2 offset1,
  2783. // int2 offset2, int2 offset3, int2 offset4
  2784. //
  2785. // An additional 'out uint status' parameter can appear in both of the above.
  2786. //
  2787. // TextureCube's signature is somewhat different from the rest.
  2788. // Parameters for .Gather{Red|Green|Blue|Alpha}() for TextureCube are:
  2789. // * SamplerState s, float2 location, out uint status
  2790. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() for TextureCube are:
  2791. // * SamplerState s, float2 location, float compare_value, out uint status
  2792. //
  2793. // Return type is always a 4-component vector.
  2794. const FunctionDecl *callee = expr->getDirectCallee();
  2795. const auto numArgs = expr->getNumArgs();
  2796. const auto *imageExpr = expr->getImplicitObjectArgument();
  2797. const auto loc = expr->getCallee()->getExprLoc();
  2798. const QualType imageType = imageExpr->getType();
  2799. const QualType retType = callee->getReturnType();
  2800. // If the last arg is an unsigned integer, it must be the status.
  2801. const bool hasStatusArg =
  2802. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2803. // Subtract 1 for status arg (if it exists), subtract 1 for compare_value (if
  2804. // it exists), and subtract 2 for SamplerState and location.
  2805. const auto numOffsetArgs = numArgs - hasStatusArg - isCmp - 2;
  2806. // No offset args for TextureCube, 1 or 4 offset args for the rest.
  2807. assert(numOffsetArgs == 0 || numOffsetArgs == 1 || numOffsetArgs == 4);
  2808. auto *image = loadIfGLValue(imageExpr);
  2809. auto *sampler = doExpr(expr->getArg(0));
  2810. auto *coordinate = doExpr(expr->getArg(1));
  2811. auto *compareVal = isCmp ? doExpr(expr->getArg(2)) : nullptr;
  2812. // Handle offsets (if any).
  2813. bool needsEmulation = false;
  2814. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr,
  2815. *constOffsets = nullptr;
  2816. if (numOffsetArgs == 1) {
  2817. // The offset arg is not optional.
  2818. handleOffsetInMethodCall(expr, 2 + isCmp, &constOffset, &varOffset);
  2819. } else if (numOffsetArgs == 4) {
  2820. auto *offset0 = tryToEvaluateAsConst(expr->getArg(2 + isCmp));
  2821. auto *offset1 = tryToEvaluateAsConst(expr->getArg(3 + isCmp));
  2822. auto *offset2 = tryToEvaluateAsConst(expr->getArg(4 + isCmp));
  2823. auto *offset3 = tryToEvaluateAsConst(expr->getArg(5 + isCmp));
  2824. // If any of the offsets is not constant, we then need to emulate the call
  2825. // using 4 OpImageGather instructions. Otherwise, we can leverage the
  2826. // ConstOffsets image operand.
  2827. if (offset0 && offset1 && offset2 && offset3) {
  2828. const QualType v2i32 = astContext.getExtVectorType(astContext.IntTy, 2);
  2829. const auto offsetType = astContext.getConstantArrayType(
  2830. v2i32, llvm::APInt(32, 4), clang::ArrayType::Normal, 0);
  2831. constOffsets = spvBuilder.getConstantComposite(
  2832. offsetType, {offset0, offset1, offset2, offset3});
  2833. } else {
  2834. needsEmulation = true;
  2835. }
  2836. }
  2837. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  2838. if (needsEmulation) {
  2839. const auto elemType = hlsl::GetHLSLVecElementType(callee->getReturnType());
  2840. SpirvInstruction *texels[4];
  2841. for (uint32_t i = 0; i < 4; ++i) {
  2842. varOffset = doExpr(expr->getArg(2 + isCmp + i));
  2843. auto *gatherRet = spvBuilder.createImageGather(
  2844. retType, imageType, image, sampler, coordinate,
  2845. spvBuilder.getConstantInt(astContext.IntTy,
  2846. llvm::APInt(32, component, true)),
  2847. compareVal,
  2848. /*constOffset*/ nullptr, varOffset, /*constOffsets*/ nullptr,
  2849. /*sampleNumber*/ nullptr, status, loc);
  2850. texels[i] =
  2851. spvBuilder.createCompositeExtract(elemType, gatherRet, {i}, loc);
  2852. }
  2853. return spvBuilder.createCompositeConstruct(
  2854. retType, {texels[0], texels[1], texels[2], texels[3]}, loc);
  2855. }
  2856. return spvBuilder.createImageGather(
  2857. retType, imageType, image, sampler, coordinate,
  2858. spvBuilder.getConstantInt(astContext.IntTy,
  2859. llvm::APInt(32, component, true)),
  2860. compareVal, constOffset, varOffset, constOffsets,
  2861. /*sampleNumber*/ nullptr, status, loc);
  2862. }
  2863. SpirvInstruction *
  2864. SpirvEmitter::processTextureGatherCmp(const CXXMemberCallExpr *expr) {
  2865. // Signature for Texture2D/Texture2DArray:
  2866. //
  2867. // float4 GatherCmp(
  2868. // in SamplerComparisonState s,
  2869. // in float2 location,
  2870. // in float compare_value
  2871. // [,in int2 offset]
  2872. // [,out uint Status]
  2873. // );
  2874. //
  2875. // Signature for TextureCube/TextureCubeArray:
  2876. //
  2877. // float4 GatherCmp(
  2878. // in SamplerComparisonState s,
  2879. // in float2 location,
  2880. // in float compare_value,
  2881. // out uint Status
  2882. // );
  2883. //
  2884. // Other Texture types do not have the GatherCmp method.
  2885. const FunctionDecl *callee = expr->getDirectCallee();
  2886. const auto numArgs = expr->getNumArgs();
  2887. const auto loc = expr->getExprLoc();
  2888. const bool hasStatusArg =
  2889. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2890. const bool hasOffsetArg = (numArgs == 5) || (numArgs == 4 && !hasStatusArg);
  2891. const auto *imageExpr = expr->getImplicitObjectArgument();
  2892. auto *image = loadIfGLValue(imageExpr);
  2893. auto *sampler = doExpr(expr->getArg(0));
  2894. auto *coordinate = doExpr(expr->getArg(1));
  2895. auto *comparator = doExpr(expr->getArg(2));
  2896. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  2897. if (hasOffsetArg)
  2898. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  2899. const auto retType = callee->getReturnType();
  2900. const auto imageType = imageExpr->getType();
  2901. const auto status =
  2902. hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  2903. return spvBuilder.createImageGather(
  2904. retType, imageType, image, sampler, coordinate,
  2905. /*component*/ nullptr, comparator, constOffset, varOffset,
  2906. /*constOffsets*/ nullptr,
  2907. /*sampleNumber*/ nullptr, status, loc);
  2908. }
  2909. SpirvInstruction *SpirvEmitter::processBufferTextureLoad(
  2910. const Expr *object, SpirvInstruction *location,
  2911. SpirvInstruction *constOffset, SpirvInstruction *varOffset,
  2912. SpirvInstruction *lod, SpirvInstruction *residencyCode,
  2913. SourceLocation loc) {
  2914. // Loading for Buffer and RWBuffer translates to an OpImageFetch.
  2915. // The result type of an OpImageFetch must be a vec4 of float or int.
  2916. const auto type = object->getType();
  2917. assert(isBuffer(type) || isRWBuffer(type) || isTexture(type) ||
  2918. isRWTexture(type) || isSubpassInput(type) || isSubpassInputMS(type));
  2919. const bool doFetch = isBuffer(type) || isTexture(type);
  2920. auto *objectInfo = loadIfGLValue(object);
  2921. // For Texture2DMS and Texture2DMSArray, Sample must be used rather than Lod.
  2922. SpirvInstruction *sampleNumber = nullptr;
  2923. if (isTextureMS(type) || isSubpassInputMS(type)) {
  2924. sampleNumber = lod;
  2925. lod = nullptr;
  2926. }
  2927. const auto sampledType = hlsl::GetHLSLResourceResultType(type);
  2928. QualType elemType = sampledType;
  2929. uint32_t elemCount = 1;
  2930. bool isTemplateOverStruct = false;
  2931. // Check whether the template type is a vector type or struct type.
  2932. if (!isVectorType(sampledType, &elemType, &elemCount)) {
  2933. if (sampledType->getAsStructureType()) {
  2934. isTemplateOverStruct = true;
  2935. // For struct type, we need to make sure it can fit into a 4-component
  2936. // vector. Detailed failing reasons will be emitted by the function so
  2937. // we don't need to emit errors here.
  2938. if (!canFitIntoOneRegister(astContext, sampledType, &elemType,
  2939. &elemCount))
  2940. return nullptr;
  2941. }
  2942. }
  2943. if (!elemType->isFloatingType() && !elemType->isIntegerType()) {
  2944. emitError("loading %0 value unsupported", object->getExprLoc()) << type;
  2945. return nullptr;
  2946. }
  2947. // OpImageFetch and OpImageRead can only fetch a vector of 4 elements.
  2948. const QualType texelType = astContext.getExtVectorType(elemType, 4u);
  2949. auto *texel = spvBuilder.createImageFetchOrRead(
  2950. doFetch, texelType, type, objectInfo, location, lod, constOffset,
  2951. varOffset, /*constOffsets*/ nullptr, sampleNumber, residencyCode, loc);
  2952. // If the result type is a vec1, vec2, or vec3, some extra processing
  2953. // (extraction) is required.
  2954. auto *retVal = extractVecFromVec4(texel, elemCount, elemType, loc);
  2955. if (isTemplateOverStruct) {
  2956. // Convert to the struct so that we are consistent with types in the AST.
  2957. retVal = convertVectorToStruct(sampledType, elemType, retVal, loc);
  2958. }
  2959. retVal->setRValue();
  2960. return retVal;
  2961. }
  2962. SpirvInstruction *SpirvEmitter::processByteAddressBufferLoadStore(
  2963. const CXXMemberCallExpr *expr, uint32_t numWords, bool doStore) {
  2964. SpirvInstruction *result = nullptr;
  2965. const auto object = expr->getImplicitObjectArgument();
  2966. auto *objectInfo = loadIfAliasVarRef(object);
  2967. assert(numWords >= 1 && numWords <= 4);
  2968. if (doStore) {
  2969. assert(isRWByteAddressBuffer(object->getType()));
  2970. assert(expr->getNumArgs() == 2);
  2971. } else {
  2972. assert(isRWByteAddressBuffer(object->getType()) ||
  2973. isByteAddressBuffer(object->getType()));
  2974. if (expr->getNumArgs() == 2) {
  2975. emitError(
  2976. "(RW)ByteAddressBuffer::Load(in address, out status) not supported",
  2977. expr->getExprLoc());
  2978. return 0;
  2979. }
  2980. }
  2981. const Expr *addressExpr = expr->getArg(0);
  2982. auto *byteAddress = doExpr(addressExpr);
  2983. const QualType addressType = addressExpr->getType();
  2984. // The front-end prevents usage of templated Load2, Load3, Load4, Store2,
  2985. // Store3, Store4 intrinsic functions.
  2986. const bool isTemplatedLoadOrStore =
  2987. (numWords == 1) &&
  2988. (doStore ? !expr->getArg(1)->getType()->isSpecificBuiltinType(
  2989. BuiltinType::UInt)
  2990. : !expr->getType()->isSpecificBuiltinType(BuiltinType::UInt));
  2991. // Do a OpShiftRightLogical by 2 (divide by 4 to get aligned memory
  2992. // access). The AST always casts the address to unsinged integer, so shift
  2993. // by unsinged integer 2.
  2994. auto *constUint2 =
  2995. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2));
  2996. SpirvInstruction *address =
  2997. spvBuilder.createBinaryOp(spv::Op::OpShiftRightLogical, addressType,
  2998. byteAddress, constUint2, expr->getExprLoc());
  2999. if (isTemplatedLoadOrStore) {
  3000. // Templated load. Need to (potentially) perform more
  3001. // loads/casts/composite-constructs.
  3002. uint32_t bitOffset = 0;
  3003. if (doStore) {
  3004. auto *values = doExpr(expr->getArg(1));
  3005. RawBufferHandler(*this).processTemplatedStoreToBuffer(
  3006. values, objectInfo, address, expr->getArg(1)->getType(), bitOffset);
  3007. return nullptr;
  3008. } else {
  3009. RawBufferHandler rawBufferHandler(*this);
  3010. return rawBufferHandler.processTemplatedLoadFromBuffer(
  3011. objectInfo, address, expr->getType(), bitOffset);
  3012. }
  3013. }
  3014. // Perform access chain into the RWByteAddressBuffer.
  3015. // First index must be zero (member 0 of the struct is a
  3016. // runtimeArray). The second index passed to OpAccessChain should be
  3017. // the address.
  3018. auto *constUint0 =
  3019. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3020. if (doStore) {
  3021. auto *values = doExpr(expr->getArg(1));
  3022. auto *curStoreAddress = address;
  3023. for (uint32_t wordCounter = 0; wordCounter < numWords; ++wordCounter) {
  3024. // Extract a 32-bit word from the input.
  3025. auto *curValue = numWords == 1
  3026. ? values
  3027. : spvBuilder.createCompositeExtract(
  3028. astContext.UnsignedIntTy, values,
  3029. {wordCounter}, expr->getArg(1)->getExprLoc());
  3030. // Update the output address if necessary.
  3031. if (wordCounter > 0) {
  3032. auto *offset = spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  3033. llvm::APInt(32, wordCounter));
  3034. curStoreAddress =
  3035. spvBuilder.createBinaryOp(spv::Op::OpIAdd, addressType, address,
  3036. offset, expr->getCallee()->getExprLoc());
  3037. }
  3038. // Store the word to the right address at the output.
  3039. auto *storePtr = spvBuilder.createAccessChain(
  3040. astContext.UnsignedIntTy, objectInfo, {constUint0, curStoreAddress},
  3041. object->getLocStart());
  3042. spvBuilder.createStore(storePtr, curValue,
  3043. expr->getCallee()->getExprLoc());
  3044. }
  3045. } else {
  3046. auto *loadPtr = spvBuilder.createAccessChain(
  3047. astContext.UnsignedIntTy, objectInfo, {constUint0, address},
  3048. object->getLocStart());
  3049. result = spvBuilder.createLoad(astContext.UnsignedIntTy, loadPtr,
  3050. expr->getCallee()->getExprLoc());
  3051. if (numWords > 1) {
  3052. // Load word 2, 3, and 4 where necessary. Use OpCompositeConstruct to
  3053. // return a vector result.
  3054. llvm::SmallVector<SpirvInstruction *, 4> values;
  3055. values.push_back(result);
  3056. for (uint32_t wordCounter = 2; wordCounter <= numWords; ++wordCounter) {
  3057. auto *offset = spvBuilder.getConstantInt(
  3058. astContext.UnsignedIntTy, llvm::APInt(32, wordCounter - 1));
  3059. auto *newAddress =
  3060. spvBuilder.createBinaryOp(spv::Op::OpIAdd, addressType, address,
  3061. offset, expr->getCallee()->getExprLoc());
  3062. loadPtr = spvBuilder.createAccessChain(
  3063. astContext.UnsignedIntTy, objectInfo, {constUint0, newAddress},
  3064. object->getLocStart());
  3065. values.push_back(
  3066. spvBuilder.createLoad(astContext.UnsignedIntTy, loadPtr,
  3067. expr->getCallee()->getExprLoc()));
  3068. }
  3069. const QualType resultType =
  3070. astContext.getExtVectorType(addressType, numWords);
  3071. result = spvBuilder.createCompositeConstruct(resultType, values,
  3072. expr->getLocStart());
  3073. result->setRValue();
  3074. }
  3075. }
  3076. return result;
  3077. }
  3078. SpirvInstruction *
  3079. SpirvEmitter::processStructuredBufferLoad(const CXXMemberCallExpr *expr) {
  3080. if (expr->getNumArgs() == 2) {
  3081. emitError(
  3082. "(RW)StructuredBuffer::Load(in location, out status) not supported",
  3083. expr->getExprLoc());
  3084. return 0;
  3085. }
  3086. const auto *buffer = expr->getImplicitObjectArgument();
  3087. auto *info = loadIfAliasVarRef(buffer);
  3088. const QualType structType =
  3089. hlsl::GetHLSLResourceResultType(buffer->getType());
  3090. auto *zero = spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0));
  3091. auto *index = doExpr(expr->getArg(0));
  3092. return turnIntoElementPtr(buffer->getType(), info, structType, {zero, index},
  3093. buffer->getExprLoc());
  3094. }
  3095. SpirvInstruction *
  3096. SpirvEmitter::incDecRWACSBufferCounter(const CXXMemberCallExpr *expr,
  3097. bool isInc, bool loadObject) {
  3098. auto *zero =
  3099. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3100. auto *sOne =
  3101. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 1, true));
  3102. const auto srcLoc = expr->getCallee()->getExprLoc();
  3103. const auto *object =
  3104. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3105. if (loadObject) {
  3106. // We don't need the object's <result-id> here since counter variable is a
  3107. // separate variable. But we still need the side effects of evaluating the
  3108. // object, e.g., if the source code is foo(...).IncrementCounter(), we still
  3109. // want to emit the code for foo(...).
  3110. (void)doExpr(object);
  3111. }
  3112. const auto *counterPair = getFinalACSBufferCounter(object);
  3113. if (!counterPair) {
  3114. emitFatalError("cannot find the associated counter variable",
  3115. object->getExprLoc());
  3116. return nullptr;
  3117. }
  3118. auto *counterPtr = spvBuilder.createAccessChain(
  3119. astContext.IntTy, counterPair->get(spvBuilder, spvContext), {zero},
  3120. srcLoc);
  3121. SpirvInstruction *index = nullptr;
  3122. if (isInc) {
  3123. index = spvBuilder.createAtomicOp(
  3124. spv::Op::OpAtomicIAdd, astContext.IntTy, counterPtr, spv::Scope::Device,
  3125. spv::MemorySemanticsMask::MaskNone, sOne, srcLoc);
  3126. } else {
  3127. // Note that OpAtomicISub returns the value before the subtraction;
  3128. // so we need to do substraction again with OpAtomicISub's return value.
  3129. auto *prev = spvBuilder.createAtomicOp(
  3130. spv::Op::OpAtomicISub, astContext.IntTy, counterPtr, spv::Scope::Device,
  3131. spv::MemorySemanticsMask::MaskNone, sOne, srcLoc);
  3132. index = spvBuilder.createBinaryOp(spv::Op::OpISub, astContext.IntTy, prev,
  3133. sOne, srcLoc);
  3134. }
  3135. return index;
  3136. }
  3137. bool SpirvEmitter::tryToAssignCounterVar(const DeclaratorDecl *dstDecl,
  3138. const Expr *srcExpr) {
  3139. // We are handling associated counters here. Casts should not alter which
  3140. // associated counter to manipulate.
  3141. srcExpr = srcExpr->IgnoreParenCasts();
  3142. // For parameters of forward-declared functions. We must make sure the
  3143. // associated counter variable is created. But for forward-declared functions,
  3144. // the translation of the real definition may not be started yet.
  3145. if (const auto *param = dyn_cast<ParmVarDecl>(dstDecl))
  3146. declIdMapper.createFnParamCounterVar(param);
  3147. // For implicit objects of methods. Similar to the above.
  3148. else if (const auto *thisObject = dyn_cast<ImplicitParamDecl>(dstDecl))
  3149. declIdMapper.createFnParamCounterVar(thisObject);
  3150. // Handle AssocCounter#1 (see CounterVarFields comment)
  3151. if (const auto *dstPair = declIdMapper.getCounterIdAliasPair(dstDecl)) {
  3152. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  3153. if (!srcPair) {
  3154. emitFatalError("cannot find the associated counter variable",
  3155. srcExpr->getExprLoc());
  3156. return false;
  3157. }
  3158. dstPair->assign(*srcPair, spvBuilder, spvContext);
  3159. return true;
  3160. }
  3161. // Handle AssocCounter#3
  3162. llvm::SmallVector<uint32_t, 4> srcIndices;
  3163. const auto *dstFields = declIdMapper.getCounterVarFields(dstDecl);
  3164. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  3165. if (dstFields && srcFields) {
  3166. // The destination is a struct whose fields are directly alias resources.
  3167. // But that's not necessarily true for the source, which can be deep
  3168. // nested structs. That means they will have different index "prefixes"
  3169. // for all their fields; while the "prefix" for destination is effectively
  3170. // an empty list (since it is not nested in other structs). We need to
  3171. // strip the index prefix from the source.
  3172. return dstFields->assign(*srcFields, /*dstIndices=*/{}, srcIndices,
  3173. spvBuilder, spvContext);
  3174. }
  3175. // AssocCounter#2 and AssocCounter#4 for the lhs cannot happen since the lhs
  3176. // is a stand-alone decl in this method.
  3177. return false;
  3178. }
  3179. bool SpirvEmitter::tryToAssignCounterVar(const Expr *dstExpr,
  3180. const Expr *srcExpr) {
  3181. dstExpr = dstExpr->IgnoreParenCasts();
  3182. srcExpr = srcExpr->IgnoreParenCasts();
  3183. const auto *dstPair = getFinalACSBufferCounter(dstExpr);
  3184. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  3185. if ((dstPair == nullptr) != (srcPair == nullptr)) {
  3186. emitFatalError("cannot handle associated counter variable assignment",
  3187. srcExpr->getExprLoc());
  3188. return false;
  3189. }
  3190. // Handle AssocCounter#1 & AssocCounter#2
  3191. if (dstPair && srcPair) {
  3192. dstPair->assign(*srcPair, spvBuilder, spvContext);
  3193. return true;
  3194. }
  3195. // Handle AssocCounter#3 & AssocCounter#4
  3196. llvm::SmallVector<uint32_t, 4> dstIndices;
  3197. llvm::SmallVector<uint32_t, 4> srcIndices;
  3198. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  3199. const auto *dstFields = getIntermediateACSBufferCounter(dstExpr, &dstIndices);
  3200. if (dstFields && srcFields) {
  3201. return dstFields->assign(*srcFields, dstIndices, srcIndices, spvBuilder,
  3202. spvContext);
  3203. }
  3204. return false;
  3205. }
  3206. const CounterIdAliasPair *
  3207. SpirvEmitter::getFinalACSBufferCounter(const Expr *expr) {
  3208. // AssocCounter#1: referencing some stand-alone variable
  3209. if (const auto *decl = getReferencedDef(expr))
  3210. return declIdMapper.getCounterIdAliasPair(decl);
  3211. // AssocCounter#2: referencing some non-struct field
  3212. llvm::SmallVector<uint32_t, 4> rawIndices;
  3213. const auto *base = collectArrayStructIndices(
  3214. expr, /*rawIndex=*/true, &rawIndices, /*indices*/ nullptr);
  3215. const auto *decl =
  3216. (base && isa<CXXThisExpr>(base))
  3217. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  3218. : getReferencedDef(base);
  3219. return declIdMapper.getCounterIdAliasPair(decl, &rawIndices);
  3220. }
  3221. const CounterVarFields *SpirvEmitter::getIntermediateACSBufferCounter(
  3222. const Expr *expr, llvm::SmallVector<uint32_t, 4> *rawIndices) {
  3223. const auto *base = collectArrayStructIndices(expr, /*rawIndex=*/true,
  3224. rawIndices, /*indices*/ nullptr);
  3225. const auto *decl =
  3226. (base && isa<CXXThisExpr>(base))
  3227. // Use the decl we created to represent the implicit object
  3228. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  3229. // Find the referenced decl from the original source code
  3230. : getReferencedDef(base);
  3231. return declIdMapper.getCounterVarFields(decl);
  3232. }
  3233. const ImplicitParamDecl *
  3234. SpirvEmitter::getOrCreateDeclForMethodObject(const CXXMethodDecl *method) {
  3235. const auto found = thisDecls.find(method);
  3236. if (found != thisDecls.end())
  3237. return found->second;
  3238. const std::string name = method->getName().str() + ".this";
  3239. // Create a new identifier to convey the name
  3240. auto &identifier = astContext.Idents.get(name);
  3241. return thisDecls[method] = ImplicitParamDecl::Create(
  3242. astContext, /*DC=*/nullptr, SourceLocation(), &identifier,
  3243. method->getThisType(astContext)->getPointeeType());
  3244. }
  3245. SpirvInstruction *
  3246. SpirvEmitter::processACSBufferAppendConsume(const CXXMemberCallExpr *expr) {
  3247. const bool isAppend = expr->getNumArgs() == 1;
  3248. auto *zero =
  3249. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  3250. const auto *object =
  3251. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3252. auto *bufferInfo = loadIfAliasVarRef(object);
  3253. auto *index = incDecRWACSBufferCounter(
  3254. expr, isAppend,
  3255. // We have already translated the object in the above. Avoid duplication.
  3256. /*loadObject=*/false);
  3257. auto bufferElemTy = hlsl::GetHLSLResourceResultType(object->getType());
  3258. // If this is a variable to communicate with host e.g., ACSBuffer
  3259. // and its type is bool or vector of bool, its effective type used
  3260. // for SPIRV must be uint not bool. We must convert it to uint here.
  3261. bool needCast = false;
  3262. if (bufferInfo->getLayoutRule() != SpirvLayoutRule::Void &&
  3263. isBoolOrVecOfBoolType(bufferElemTy)) {
  3264. uint32_t vecSize = 1;
  3265. const bool isVec = isVectorType(bufferElemTy, nullptr, &vecSize);
  3266. bufferElemTy =
  3267. isVec ? astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize)
  3268. : astContext.UnsignedIntTy;
  3269. needCast = true;
  3270. }
  3271. bufferInfo = turnIntoElementPtr(object->getType(), bufferInfo, bufferElemTy,
  3272. {zero, index}, object->getExprLoc());
  3273. if (isAppend) {
  3274. // Write out the value
  3275. auto *arg0 = doExpr(expr->getArg(0));
  3276. if (!arg0)
  3277. return nullptr;
  3278. if (!arg0->isRValue()) {
  3279. arg0 = spvBuilder.createLoad(bufferElemTy, arg0,
  3280. expr->getArg(0)->getExprLoc());
  3281. }
  3282. if (needCast &&
  3283. !isSameType(astContext, bufferElemTy, arg0->getAstResultType())) {
  3284. arg0 = castToType(arg0, arg0->getAstResultType(), bufferElemTy,
  3285. expr->getArg(0)->getExprLoc());
  3286. }
  3287. storeValue(bufferInfo, arg0, bufferElemTy, expr->getCallee()->getExprLoc());
  3288. return 0;
  3289. } else {
  3290. // Note that we are returning a pointer (lvalue) here inorder to further
  3291. // acess the fields in this element, e.g., buffer.Consume().a.b. So we
  3292. // cannot forcefully set all normal function calls as returning rvalue.
  3293. return bufferInfo;
  3294. }
  3295. }
  3296. SpirvInstruction *
  3297. SpirvEmitter::processStreamOutputAppend(const CXXMemberCallExpr *expr) {
  3298. // TODO: handle multiple stream-output objects
  3299. const auto *object =
  3300. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3301. const auto *stream = cast<DeclRefExpr>(object)->getDecl();
  3302. auto *value = doExpr(expr->getArg(0));
  3303. declIdMapper.writeBackOutputStream(stream, stream->getType(), value);
  3304. spvBuilder.createEmitVertex(expr->getExprLoc());
  3305. return nullptr;
  3306. }
  3307. SpirvInstruction *
  3308. SpirvEmitter::processStreamOutputRestart(const CXXMemberCallExpr *expr) {
  3309. // TODO: handle multiple stream-output objects
  3310. spvBuilder.createEndPrimitive(expr->getExprLoc());
  3311. return 0;
  3312. }
  3313. SpirvInstruction *
  3314. SpirvEmitter::emitGetSamplePosition(SpirvInstruction *sampleCount,
  3315. SpirvInstruction *sampleIndex,
  3316. SourceLocation loc) {
  3317. struct Float2 {
  3318. float x;
  3319. float y;
  3320. };
  3321. static const Float2 pos2[] = {
  3322. {4.0 / 16.0, 4.0 / 16.0},
  3323. {-4.0 / 16.0, -4.0 / 16.0},
  3324. };
  3325. static const Float2 pos4[] = {
  3326. {-2.0 / 16.0, -6.0 / 16.0},
  3327. {6.0 / 16.0, -2.0 / 16.0},
  3328. {-6.0 / 16.0, 2.0 / 16.0},
  3329. {2.0 / 16.0, 6.0 / 16.0},
  3330. };
  3331. static const Float2 pos8[] = {
  3332. {1.0 / 16.0, -3.0 / 16.0}, {-1.0 / 16.0, 3.0 / 16.0},
  3333. {5.0 / 16.0, 1.0 / 16.0}, {-3.0 / 16.0, -5.0 / 16.0},
  3334. {-5.0 / 16.0, 5.0 / 16.0}, {-7.0 / 16.0, -1.0 / 16.0},
  3335. {3.0 / 16.0, 7.0 / 16.0}, {7.0 / 16.0, -7.0 / 16.0},
  3336. };
  3337. static const Float2 pos16[] = {
  3338. {1.0 / 16.0, 1.0 / 16.0}, {-1.0 / 16.0, -3.0 / 16.0},
  3339. {-3.0 / 16.0, 2.0 / 16.0}, {4.0 / 16.0, -1.0 / 16.0},
  3340. {-5.0 / 16.0, -2.0 / 16.0}, {2.0 / 16.0, 5.0 / 16.0},
  3341. {5.0 / 16.0, 3.0 / 16.0}, {3.0 / 16.0, -5.0 / 16.0},
  3342. {-2.0 / 16.0, 6.0 / 16.0}, {0.0 / 16.0, -7.0 / 16.0},
  3343. {-4.0 / 16.0, -6.0 / 16.0}, {-6.0 / 16.0, 4.0 / 16.0},
  3344. {-8.0 / 16.0, 0.0 / 16.0}, {7.0 / 16.0, -4.0 / 16.0},
  3345. {6.0 / 16.0, 7.0 / 16.0}, {-7.0 / 16.0, -8.0 / 16.0},
  3346. };
  3347. // We are emitting the SPIR-V for the following HLSL source code:
  3348. //
  3349. // float2 position;
  3350. //
  3351. // if (count == 2) {
  3352. // position = pos2[index];
  3353. // }
  3354. // else if (count == 4) {
  3355. // position = pos4[index];
  3356. // }
  3357. // else if (count == 8) {
  3358. // position = pos8[index];
  3359. // }
  3360. // else if (count == 16) {
  3361. // position = pos16[index];
  3362. // }
  3363. // else {
  3364. // position = float2(0.0f, 0.0f);
  3365. // }
  3366. const auto v2f32Type = astContext.getExtVectorType(astContext.FloatTy, 2);
  3367. // Creates a SPIR-V function scope variable of type float2[len].
  3368. const auto createArray = [this, v2f32Type, loc](const Float2 *ptr,
  3369. uint32_t len) {
  3370. llvm::SmallVector<SpirvConstant *, 16> components;
  3371. for (uint32_t i = 0; i < len; ++i) {
  3372. auto *x = spvBuilder.getConstantFloat(astContext.FloatTy,
  3373. llvm::APFloat(ptr[i].x));
  3374. auto *y = spvBuilder.getConstantFloat(astContext.FloatTy,
  3375. llvm::APFloat(ptr[i].y));
  3376. components.push_back(spvBuilder.getConstantComposite(v2f32Type, {x, y}));
  3377. }
  3378. const auto arrType = astContext.getConstantArrayType(
  3379. v2f32Type, llvm::APInt(32, len), clang::ArrayType::Normal, 0);
  3380. auto *val = spvBuilder.getConstantComposite(arrType, components);
  3381. const std::string varName =
  3382. "var.GetSamplePosition.data." + std::to_string(len);
  3383. auto *var = spvBuilder.addFnVar(arrType, loc, varName);
  3384. spvBuilder.createStore(var, val, loc);
  3385. return var;
  3386. };
  3387. auto *pos2Arr = createArray(pos2, 2);
  3388. auto *pos4Arr = createArray(pos4, 4);
  3389. auto *pos8Arr = createArray(pos8, 8);
  3390. auto *pos16Arr = createArray(pos16, 16);
  3391. auto *resultVar =
  3392. spvBuilder.addFnVar(v2f32Type, loc, "var.GetSamplePosition.result");
  3393. auto *then2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then2");
  3394. auto *then4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then4");
  3395. auto *then8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then8");
  3396. auto *then16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.then16");
  3397. auto *else2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else2");
  3398. auto *else4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else4");
  3399. auto *else8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else8");
  3400. auto *else16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.else16");
  3401. auto *merge2BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge2");
  3402. auto *merge4BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge4");
  3403. auto *merge8BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge8");
  3404. auto *merge16BB = spvBuilder.createBasicBlock("if.GetSamplePosition.merge16");
  3405. // if (count == 2) {
  3406. const auto check2 = spvBuilder.createBinaryOp(
  3407. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3408. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2)),
  3409. loc);
  3410. spvBuilder.createConditionalBranch(check2, then2BB, else2BB, loc, merge2BB);
  3411. spvBuilder.addSuccessor(then2BB);
  3412. spvBuilder.addSuccessor(else2BB);
  3413. spvBuilder.setMergeTarget(merge2BB);
  3414. // position = pos2[index];
  3415. // }
  3416. spvBuilder.setInsertPoint(then2BB);
  3417. auto *ac =
  3418. spvBuilder.createAccessChain(v2f32Type, pos2Arr, {sampleIndex}, loc);
  3419. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3420. loc);
  3421. spvBuilder.createBranch(merge2BB, loc);
  3422. spvBuilder.addSuccessor(merge2BB);
  3423. // else if (count == 4) {
  3424. spvBuilder.setInsertPoint(else2BB);
  3425. const auto check4 = spvBuilder.createBinaryOp(
  3426. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3427. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 4)),
  3428. loc);
  3429. spvBuilder.createConditionalBranch(check4, then4BB, else4BB, loc, merge4BB);
  3430. spvBuilder.addSuccessor(then4BB);
  3431. spvBuilder.addSuccessor(else4BB);
  3432. spvBuilder.setMergeTarget(merge4BB);
  3433. // position = pos4[index];
  3434. // }
  3435. spvBuilder.setInsertPoint(then4BB);
  3436. ac = spvBuilder.createAccessChain(v2f32Type, pos4Arr, {sampleIndex}, loc);
  3437. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3438. loc);
  3439. spvBuilder.createBranch(merge4BB, loc);
  3440. spvBuilder.addSuccessor(merge4BB);
  3441. // else if (count == 8) {
  3442. spvBuilder.setInsertPoint(else4BB);
  3443. const auto check8 = spvBuilder.createBinaryOp(
  3444. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3445. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 8)),
  3446. loc);
  3447. spvBuilder.createConditionalBranch(check8, then8BB, else8BB, loc, merge8BB);
  3448. spvBuilder.addSuccessor(then8BB);
  3449. spvBuilder.addSuccessor(else8BB);
  3450. spvBuilder.setMergeTarget(merge8BB);
  3451. // position = pos8[index];
  3452. // }
  3453. spvBuilder.setInsertPoint(then8BB);
  3454. ac = spvBuilder.createAccessChain(v2f32Type, pos8Arr, {sampleIndex}, loc);
  3455. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3456. loc);
  3457. spvBuilder.createBranch(merge8BB, loc);
  3458. spvBuilder.addSuccessor(merge8BB);
  3459. // else if (count == 16) {
  3460. spvBuilder.setInsertPoint(else8BB);
  3461. const auto check16 = spvBuilder.createBinaryOp(
  3462. spv::Op::OpIEqual, astContext.BoolTy, sampleCount,
  3463. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 16)),
  3464. loc);
  3465. spvBuilder.createConditionalBranch(check16, then16BB, else16BB, loc,
  3466. merge16BB);
  3467. spvBuilder.addSuccessor(then16BB);
  3468. spvBuilder.addSuccessor(else16BB);
  3469. spvBuilder.setMergeTarget(merge16BB);
  3470. // position = pos16[index];
  3471. // }
  3472. spvBuilder.setInsertPoint(then16BB);
  3473. ac = spvBuilder.createAccessChain(v2f32Type, pos16Arr, {sampleIndex}, loc);
  3474. spvBuilder.createStore(resultVar, spvBuilder.createLoad(v2f32Type, ac, loc),
  3475. loc);
  3476. spvBuilder.createBranch(merge16BB, loc);
  3477. spvBuilder.addSuccessor(merge16BB);
  3478. // else {
  3479. // position = float2(0.0f, 0.0f);
  3480. // }
  3481. spvBuilder.setInsertPoint(else16BB);
  3482. auto *zero =
  3483. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.0f));
  3484. auto *v2f32Zero = spvBuilder.getConstantComposite(v2f32Type, {zero, zero});
  3485. spvBuilder.createStore(resultVar, v2f32Zero, loc);
  3486. spvBuilder.createBranch(merge16BB, loc);
  3487. spvBuilder.addSuccessor(merge16BB);
  3488. spvBuilder.setInsertPoint(merge16BB);
  3489. spvBuilder.createBranch(merge8BB, loc);
  3490. spvBuilder.addSuccessor(merge8BB);
  3491. spvBuilder.setInsertPoint(merge8BB);
  3492. spvBuilder.createBranch(merge4BB, loc);
  3493. spvBuilder.addSuccessor(merge4BB);
  3494. spvBuilder.setInsertPoint(merge4BB);
  3495. spvBuilder.createBranch(merge2BB, loc);
  3496. spvBuilder.addSuccessor(merge2BB);
  3497. spvBuilder.setInsertPoint(merge2BB);
  3498. return spvBuilder.createLoad(v2f32Type, resultVar, loc);
  3499. }
  3500. SpirvInstruction *
  3501. SpirvEmitter::doCXXMemberCallExpr(const CXXMemberCallExpr *expr) {
  3502. const FunctionDecl *callee = expr->getDirectCallee();
  3503. llvm::StringRef group;
  3504. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  3505. if (hlsl::GetIntrinsicOp(callee, opcode, group)) {
  3506. return processIntrinsicMemberCall(expr,
  3507. static_cast<hlsl::IntrinsicOp>(opcode));
  3508. }
  3509. return processCall(expr);
  3510. }
  3511. void SpirvEmitter::handleOffsetInMethodCall(const CXXMemberCallExpr *expr,
  3512. uint32_t index,
  3513. SpirvInstruction **constOffset,
  3514. SpirvInstruction **varOffset) {
  3515. assert(constOffset && varOffset);
  3516. // Ensure the given arg index is not out-of-range.
  3517. assert(index < expr->getNumArgs());
  3518. *constOffset = *varOffset = nullptr; // Initialize both first
  3519. if ((*constOffset = tryToEvaluateAsConst(expr->getArg(index))))
  3520. return; // Constant offset
  3521. else
  3522. *varOffset = doExpr(expr->getArg(index));
  3523. }
  3524. SpirvInstruction *
  3525. SpirvEmitter::processIntrinsicMemberCall(const CXXMemberCallExpr *expr,
  3526. hlsl::IntrinsicOp opcode) {
  3527. using namespace hlsl;
  3528. SpirvInstruction *retVal = nullptr;
  3529. switch (opcode) {
  3530. case IntrinsicOp::MOP_Sample:
  3531. retVal = processTextureSampleGather(expr, /*isSample=*/true);
  3532. break;
  3533. case IntrinsicOp::MOP_Gather:
  3534. retVal = processTextureSampleGather(expr, /*isSample=*/false);
  3535. break;
  3536. case IntrinsicOp::MOP_SampleBias:
  3537. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/true);
  3538. break;
  3539. case IntrinsicOp::MOP_SampleLevel:
  3540. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/false);
  3541. break;
  3542. case IntrinsicOp::MOP_SampleGrad:
  3543. retVal = processTextureSampleGrad(expr);
  3544. break;
  3545. case IntrinsicOp::MOP_SampleCmp:
  3546. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/true);
  3547. break;
  3548. case IntrinsicOp::MOP_SampleCmpLevelZero:
  3549. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/false);
  3550. break;
  3551. case IntrinsicOp::MOP_GatherRed:
  3552. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 0);
  3553. break;
  3554. case IntrinsicOp::MOP_GatherGreen:
  3555. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 1);
  3556. break;
  3557. case IntrinsicOp::MOP_GatherBlue:
  3558. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 2);
  3559. break;
  3560. case IntrinsicOp::MOP_GatherAlpha:
  3561. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 3);
  3562. break;
  3563. case IntrinsicOp::MOP_GatherCmp:
  3564. retVal = processTextureGatherCmp(expr);
  3565. break;
  3566. case IntrinsicOp::MOP_GatherCmpRed:
  3567. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/true, 0);
  3568. break;
  3569. case IntrinsicOp::MOP_Load:
  3570. return processBufferTextureLoad(expr);
  3571. case IntrinsicOp::MOP_Load2:
  3572. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ false);
  3573. case IntrinsicOp::MOP_Load3:
  3574. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ false);
  3575. case IntrinsicOp::MOP_Load4:
  3576. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ false);
  3577. case IntrinsicOp::MOP_Store:
  3578. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ true);
  3579. case IntrinsicOp::MOP_Store2:
  3580. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ true);
  3581. case IntrinsicOp::MOP_Store3:
  3582. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ true);
  3583. case IntrinsicOp::MOP_Store4:
  3584. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ true);
  3585. case IntrinsicOp::MOP_GetDimensions:
  3586. retVal = processGetDimensions(expr);
  3587. break;
  3588. case IntrinsicOp::MOP_CalculateLevelOfDetail:
  3589. retVal = processTextureLevelOfDetail(expr, /* unclamped */ false);
  3590. case IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped:
  3591. retVal = processTextureLevelOfDetail(expr, /* unclamped */ true);
  3592. break;
  3593. case IntrinsicOp::MOP_IncrementCounter:
  3594. retVal =
  3595. spvBuilder.createUnaryOp(spv::Op::OpBitcast, astContext.UnsignedIntTy,
  3596. incDecRWACSBufferCounter(expr, /*isInc*/ true),
  3597. expr->getCallee()->getExprLoc());
  3598. break;
  3599. case IntrinsicOp::MOP_DecrementCounter:
  3600. retVal = spvBuilder.createUnaryOp(
  3601. spv::Op::OpBitcast, astContext.UnsignedIntTy,
  3602. incDecRWACSBufferCounter(expr, /*isInc*/ false),
  3603. expr->getCallee()->getExprLoc());
  3604. break;
  3605. case IntrinsicOp::MOP_Append:
  3606. if (hlsl::IsHLSLStreamOutputType(
  3607. expr->getImplicitObjectArgument()->getType()))
  3608. return processStreamOutputAppend(expr);
  3609. else
  3610. return processACSBufferAppendConsume(expr);
  3611. case IntrinsicOp::MOP_Consume:
  3612. return processACSBufferAppendConsume(expr);
  3613. case IntrinsicOp::MOP_RestartStrip:
  3614. retVal = processStreamOutputRestart(expr);
  3615. break;
  3616. case IntrinsicOp::MOP_InterlockedAdd:
  3617. case IntrinsicOp::MOP_InterlockedAnd:
  3618. case IntrinsicOp::MOP_InterlockedOr:
  3619. case IntrinsicOp::MOP_InterlockedXor:
  3620. case IntrinsicOp::MOP_InterlockedUMax:
  3621. case IntrinsicOp::MOP_InterlockedUMin:
  3622. case IntrinsicOp::MOP_InterlockedMax:
  3623. case IntrinsicOp::MOP_InterlockedMin:
  3624. case IntrinsicOp::MOP_InterlockedExchange:
  3625. case IntrinsicOp::MOP_InterlockedCompareExchange:
  3626. case IntrinsicOp::MOP_InterlockedCompareStore:
  3627. retVal = processRWByteAddressBufferAtomicMethods(opcode, expr);
  3628. break;
  3629. case IntrinsicOp::MOP_GetSamplePosition:
  3630. retVal = processGetSamplePosition(expr);
  3631. break;
  3632. case IntrinsicOp::MOP_SubpassLoad:
  3633. retVal = processSubpassLoad(expr);
  3634. break;
  3635. case IntrinsicOp::MOP_GatherCmpGreen:
  3636. case IntrinsicOp::MOP_GatherCmpBlue:
  3637. case IntrinsicOp::MOP_GatherCmpAlpha:
  3638. emitError("no equivalent for %0 intrinsic method in Vulkan",
  3639. expr->getCallee()->getExprLoc())
  3640. << expr->getMethodDecl()->getName();
  3641. return nullptr;
  3642. case IntrinsicOp::MOP_TraceRayInline:
  3643. return processTraceRayInline(expr);
  3644. case IntrinsicOp::MOP_Abort:
  3645. case IntrinsicOp::MOP_CandidateGeometryIndex:
  3646. case IntrinsicOp::MOP_CandidateInstanceContributionToHitGroupIndex:
  3647. case IntrinsicOp::MOP_CandidateInstanceID:
  3648. case IntrinsicOp::MOP_CandidateInstanceIndex:
  3649. case IntrinsicOp::MOP_CandidateObjectRayDirection:
  3650. case IntrinsicOp::MOP_CandidateObjectRayOrigin:
  3651. case IntrinsicOp::MOP_CandidateObjectToWorld3x4:
  3652. case IntrinsicOp::MOP_CandidateObjectToWorld4x3:
  3653. case IntrinsicOp::MOP_CandidatePrimitiveIndex:
  3654. case IntrinsicOp::MOP_CandidateProceduralPrimitiveNonOpaque:
  3655. case IntrinsicOp::MOP_CandidateTriangleBarycentrics:
  3656. case IntrinsicOp::MOP_CandidateTriangleFrontFace:
  3657. case IntrinsicOp::MOP_CandidateTriangleRayT:
  3658. case IntrinsicOp::MOP_CandidateType:
  3659. case IntrinsicOp::MOP_CandidateWorldToObject3x4:
  3660. case IntrinsicOp::MOP_CandidateWorldToObject4x3:
  3661. case IntrinsicOp::MOP_CommitNonOpaqueTriangleHit:
  3662. case IntrinsicOp::MOP_CommitProceduralPrimitiveHit:
  3663. case IntrinsicOp::MOP_CommittedGeometryIndex:
  3664. case IntrinsicOp::MOP_CommittedInstanceContributionToHitGroupIndex:
  3665. case IntrinsicOp::MOP_CommittedInstanceID:
  3666. case IntrinsicOp::MOP_CommittedInstanceIndex:
  3667. case IntrinsicOp::MOP_CommittedObjectRayDirection:
  3668. case IntrinsicOp::MOP_CommittedObjectRayOrigin:
  3669. case IntrinsicOp::MOP_CommittedObjectToWorld3x4:
  3670. case IntrinsicOp::MOP_CommittedObjectToWorld4x3:
  3671. case IntrinsicOp::MOP_CommittedPrimitiveIndex:
  3672. case IntrinsicOp::MOP_CommittedRayT:
  3673. case IntrinsicOp::MOP_CommittedStatus:
  3674. case IntrinsicOp::MOP_CommittedTriangleBarycentrics:
  3675. case IntrinsicOp::MOP_CommittedTriangleFrontFace:
  3676. case IntrinsicOp::MOP_CommittedWorldToObject3x4:
  3677. case IntrinsicOp::MOP_CommittedWorldToObject4x3:
  3678. case IntrinsicOp::MOP_Proceed:
  3679. case IntrinsicOp::MOP_RayFlags:
  3680. case IntrinsicOp::MOP_RayTMin:
  3681. case IntrinsicOp::MOP_WorldRayDirection:
  3682. case IntrinsicOp::MOP_WorldRayOrigin:
  3683. return processRayQueryIntrinsics(expr, opcode);
  3684. default:
  3685. emitError("intrinsic '%0' method unimplemented",
  3686. expr->getCallee()->getExprLoc())
  3687. << expr->getDirectCallee()->getName();
  3688. return nullptr;
  3689. }
  3690. if (retVal)
  3691. retVal->setRValue();
  3692. return retVal;
  3693. }
  3694. SpirvInstruction *SpirvEmitter::createImageSample(
  3695. QualType retType, QualType imageType, SpirvInstruction *image,
  3696. SpirvInstruction *sampler, SpirvInstruction *coordinate,
  3697. SpirvInstruction *compareVal, SpirvInstruction *bias, SpirvInstruction *lod,
  3698. std::pair<SpirvInstruction *, SpirvInstruction *> grad,
  3699. SpirvInstruction *constOffset, SpirvInstruction *varOffset,
  3700. SpirvInstruction *constOffsets, SpirvInstruction *sample,
  3701. SpirvInstruction *minLod, SpirvInstruction *residencyCodeId,
  3702. SourceLocation loc) {
  3703. // SampleDref* instructions in SPIR-V always return a scalar.
  3704. // They also have the correct type in HLSL.
  3705. if (compareVal) {
  3706. return spvBuilder.createImageSample(retType, imageType, image, sampler,
  3707. coordinate, compareVal, bias, lod, grad,
  3708. constOffset, varOffset, constOffsets,
  3709. sample, minLod, residencyCodeId, loc);
  3710. }
  3711. // Non-Dref Sample instructions in SPIR-V must always return a vec4.
  3712. auto texelType = retType;
  3713. QualType elemType = {};
  3714. uint32_t retVecSize = 0;
  3715. if (isVectorType(retType, &elemType, &retVecSize) && retVecSize != 4) {
  3716. texelType = astContext.getExtVectorType(elemType, 4);
  3717. } else if (isScalarType(retType)) {
  3718. retVecSize = 1;
  3719. elemType = retType;
  3720. texelType = astContext.getExtVectorType(retType, 4);
  3721. }
  3722. // The Lod and Grad image operands requires explicit-lod instructions.
  3723. // Otherwise we use implicit-lod instructions.
  3724. const bool isExplicit = lod || (grad.first && grad.second);
  3725. // Implicit-lod instructions are only allowed in pixel shader.
  3726. if (!spvContext.isPS() && !isExplicit)
  3727. needsLegalization = true;
  3728. auto *retVal = spvBuilder.createImageSample(
  3729. texelType, imageType, image, sampler, coordinate, compareVal, bias, lod,
  3730. grad, constOffset, varOffset, constOffsets, sample, minLod,
  3731. residencyCodeId, loc);
  3732. // Extract smaller vector from the vec4 result if necessary.
  3733. if (texelType != retType) {
  3734. retVal = extractVecFromVec4(retVal, retVecSize, elemType, loc);
  3735. }
  3736. return retVal;
  3737. }
  3738. SpirvInstruction *
  3739. SpirvEmitter::processTextureSampleGather(const CXXMemberCallExpr *expr,
  3740. const bool isSample) {
  3741. // Signatures:
  3742. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3743. // DXGI_FORMAT Object.Sample(sampler_state S,
  3744. // float Location
  3745. // [, int Offset]
  3746. // [, float Clamp]
  3747. // [, out uint Status]);
  3748. //
  3749. // For TextureCube and TextureCubeArray:
  3750. // DXGI_FORMAT Object.Sample(sampler_state S,
  3751. // float Location
  3752. // [, float Clamp]
  3753. // [, out uint Status]);
  3754. //
  3755. // For Texture2D/Texture2DArray:
  3756. // <Template Type>4 Object.Gather(sampler_state S,
  3757. // float2|3|4 Location,
  3758. // int2 Offset
  3759. // [, uint Status]);
  3760. //
  3761. // For TextureCube/TextureCubeArray:
  3762. // <Template Type>4 Object.Gather(sampler_state S,
  3763. // float2|3|4 Location
  3764. // [, uint Status]);
  3765. //
  3766. // Other Texture types do not have a Gather method.
  3767. const auto numArgs = expr->getNumArgs();
  3768. const auto loc = expr->getExprLoc();
  3769. const bool hasStatusArg =
  3770. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3771. SpirvInstruction *clamp = nullptr;
  3772. if (numArgs > 2 && expr->getArg(2)->getType()->isFloatingType())
  3773. clamp = doExpr(expr->getArg(2));
  3774. else if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3775. clamp = doExpr(expr->getArg(3));
  3776. const bool hasClampArg = (clamp != 0);
  3777. const auto status =
  3778. hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3779. // Subtract 1 for status (if it exists), subtract 1 for clamp (if it exists),
  3780. // and subtract 2 for sampler_state and location.
  3781. const bool hasOffsetArg = numArgs - hasStatusArg - hasClampArg - 2 > 0;
  3782. const auto *imageExpr = expr->getImplicitObjectArgument();
  3783. const QualType imageType = imageExpr->getType();
  3784. auto *image = loadIfGLValue(imageExpr);
  3785. auto *sampler = doExpr(expr->getArg(0));
  3786. auto *coordinate = doExpr(expr->getArg(1));
  3787. // .Sample()/.Gather() may have a third optional paramter for offset.
  3788. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  3789. if (hasOffsetArg)
  3790. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3791. const auto retType = expr->getDirectCallee()->getReturnType();
  3792. if (isSample) {
  3793. return createImageSample(retType, imageType, image, sampler, coordinate,
  3794. /*compareVal*/ nullptr, /*bias*/ nullptr,
  3795. /*lod*/ nullptr, std::make_pair(nullptr, nullptr),
  3796. constOffset, varOffset,
  3797. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  3798. /*minLod*/ clamp, status,
  3799. expr->getCallee()->getLocStart());
  3800. } else {
  3801. return spvBuilder.createImageGather(
  3802. retType, imageType, image, sampler, coordinate,
  3803. // .Gather() doc says we return four components of red data.
  3804. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)),
  3805. /*compareVal*/ nullptr, constOffset, varOffset,
  3806. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr, status, loc);
  3807. }
  3808. }
  3809. SpirvInstruction *
  3810. SpirvEmitter::processTextureSampleBiasLevel(const CXXMemberCallExpr *expr,
  3811. const bool isBias) {
  3812. // Signatures:
  3813. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3814. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3815. // float Location,
  3816. // float Bias
  3817. // [, int Offset]
  3818. // [, float clamp]
  3819. // [, out uint Status]);
  3820. //
  3821. // For TextureCube and TextureCubeArray:
  3822. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3823. // float Location,
  3824. // float Bias
  3825. // [, float clamp]
  3826. // [, out uint Status]);
  3827. //
  3828. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3829. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3830. // float Location,
  3831. // float LOD
  3832. // [, int Offset]
  3833. // [, out uint Status]);
  3834. //
  3835. // For TextureCube and TextureCubeArray:
  3836. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3837. // float Location,
  3838. // float LOD
  3839. // [, out uint Status]);
  3840. const auto numArgs = expr->getNumArgs();
  3841. const bool hasStatusArg =
  3842. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3843. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3844. SpirvInstruction *clamp = nullptr;
  3845. // The .SampleLevel() methods do not take the clamp argument.
  3846. if (isBias) {
  3847. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3848. clamp = doExpr(expr->getArg(3));
  3849. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3850. clamp = doExpr(expr->getArg(4));
  3851. }
  3852. const bool hasClampArg = clamp != nullptr;
  3853. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3854. // and 3 for sampler_state, location, and Bias/LOD.
  3855. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3856. const auto *imageExpr = expr->getImplicitObjectArgument();
  3857. const QualType imageType = imageExpr->getType();
  3858. auto *image = loadIfGLValue(imageExpr);
  3859. auto *sampler = doExpr(expr->getArg(0));
  3860. auto *coordinate = doExpr(expr->getArg(1));
  3861. SpirvInstruction *lod = nullptr;
  3862. SpirvInstruction *bias = nullptr;
  3863. if (isBias) {
  3864. bias = doExpr(expr->getArg(2));
  3865. } else {
  3866. lod = doExpr(expr->getArg(2));
  3867. }
  3868. // If offset is present in .Bias()/.SampleLevel(), it is the fourth argument.
  3869. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  3870. if (hasOffsetArg)
  3871. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3872. const auto retType = expr->getDirectCallee()->getReturnType();
  3873. return createImageSample(
  3874. retType, imageType, image, sampler, coordinate,
  3875. /*compareVal*/ nullptr, bias, lod, std::make_pair(nullptr, nullptr),
  3876. constOffset, varOffset,
  3877. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  3878. /*minLod*/ clamp, status, expr->getCallee()->getLocStart());
  3879. }
  3880. SpirvInstruction *
  3881. SpirvEmitter::processTextureSampleGrad(const CXXMemberCallExpr *expr) {
  3882. // Signature:
  3883. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3884. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3885. // float Location,
  3886. // float DDX,
  3887. // float DDY
  3888. // [, int Offset]
  3889. // [, float Clamp]
  3890. // [, out uint Status]);
  3891. //
  3892. // For TextureCube and TextureCubeArray:
  3893. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3894. // float Location,
  3895. // float DDX,
  3896. // float DDY
  3897. // [, float Clamp]
  3898. // [, out uint Status]);
  3899. const auto numArgs = expr->getNumArgs();
  3900. const bool hasStatusArg =
  3901. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3902. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3903. SpirvInstruction *clamp = nullptr;
  3904. if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3905. clamp = doExpr(expr->getArg(4));
  3906. else if (numArgs > 5 && expr->getArg(5)->getType()->isFloatingType())
  3907. clamp = doExpr(expr->getArg(5));
  3908. const bool hasClampArg = clamp != nullptr;
  3909. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3910. // and 4 for sampler_state, location, DDX, and DDY;
  3911. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 4 > 0;
  3912. const auto *imageExpr = expr->getImplicitObjectArgument();
  3913. const QualType imageType = imageExpr->getType();
  3914. auto *image = loadIfGLValue(imageExpr);
  3915. auto *sampler = doExpr(expr->getArg(0));
  3916. auto *coordinate = doExpr(expr->getArg(1));
  3917. auto *ddx = doExpr(expr->getArg(2));
  3918. auto *ddy = doExpr(expr->getArg(3));
  3919. // If offset is present in .SampleGrad(), it is the fifth argument.
  3920. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  3921. if (hasOffsetArg)
  3922. handleOffsetInMethodCall(expr, 4, &constOffset, &varOffset);
  3923. const auto retType = expr->getDirectCallee()->getReturnType();
  3924. return createImageSample(
  3925. retType, imageType, image, sampler, coordinate,
  3926. /*compareVal*/ nullptr, /*bias*/ nullptr,
  3927. /*lod*/ nullptr, std::make_pair(ddx, ddy), constOffset, varOffset,
  3928. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr,
  3929. /*minLod*/ clamp, status, expr->getCallee()->getLocStart());
  3930. }
  3931. SpirvInstruction *
  3932. SpirvEmitter::processTextureSampleCmpCmpLevelZero(const CXXMemberCallExpr *expr,
  3933. const bool isCmp) {
  3934. // .SampleCmp() Signature:
  3935. //
  3936. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3937. // float Object.SampleCmp(
  3938. // SamplerComparisonState S,
  3939. // float Location,
  3940. // float CompareValue
  3941. // [, int Offset]
  3942. // [, float Clamp]
  3943. // [, out uint Status]
  3944. // );
  3945. //
  3946. // For TextureCube and TextureCubeArray:
  3947. // float Object.SampleCmp(
  3948. // SamplerComparisonState S,
  3949. // float Location,
  3950. // float CompareValue
  3951. // [, float Clamp]
  3952. // [, out uint Status]
  3953. // );
  3954. //
  3955. // .SampleCmpLevelZero() is identical to .SampleCmp() on mipmap level 0 only.
  3956. // It never takes a clamp argument, which is good because lod and clamp may
  3957. // not be used together.
  3958. //
  3959. // .SampleCmpLevelZero() Signature:
  3960. //
  3961. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3962. // float Object.SampleCmpLevelZero(
  3963. // SamplerComparisonState S,
  3964. // float Location,
  3965. // float CompareValue
  3966. // [, int Offset]
  3967. // [, out uint Status]
  3968. // );
  3969. //
  3970. // For TextureCube and TextureCubeArray:
  3971. // float Object.SampleCmpLevelZero(
  3972. // SamplerComparisonState S,
  3973. // float Location,
  3974. // float CompareValue
  3975. // [, out uint Status]
  3976. // );
  3977. const auto numArgs = expr->getNumArgs();
  3978. const bool hasStatusArg =
  3979. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3980. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  3981. SpirvInstruction *clamp = nullptr;
  3982. // The .SampleCmpLevelZero() methods do not take the clamp argument.
  3983. if (isCmp) {
  3984. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3985. clamp = doExpr(expr->getArg(3));
  3986. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3987. clamp = doExpr(expr->getArg(4));
  3988. }
  3989. const bool hasClampArg = clamp != nullptr;
  3990. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3991. // and 3 for sampler_state, location, and compare_value.
  3992. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3993. const auto *imageExpr = expr->getImplicitObjectArgument();
  3994. auto *image = loadIfGLValue(imageExpr);
  3995. auto *sampler = doExpr(expr->getArg(0));
  3996. auto *coordinate = doExpr(expr->getArg(1));
  3997. auto *compareVal = doExpr(expr->getArg(2));
  3998. // If offset is present in .SampleCmp(), it will be the fourth argument.
  3999. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4000. if (hasOffsetArg)
  4001. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  4002. auto *lod = isCmp ? nullptr
  4003. : spvBuilder.getConstantFloat(astContext.FloatTy,
  4004. llvm::APFloat(0.0f));
  4005. const auto retType = expr->getDirectCallee()->getReturnType();
  4006. const auto imageType = imageExpr->getType();
  4007. return createImageSample(
  4008. retType, imageType, image, sampler, coordinate, compareVal,
  4009. /*bias*/ nullptr, lod, std::make_pair(nullptr, nullptr), constOffset,
  4010. varOffset,
  4011. /*constOffsets*/ nullptr, /*sampleNumber*/ nullptr, /*minLod*/ clamp,
  4012. status, expr->getCallee()->getLocStart());
  4013. }
  4014. SpirvInstruction *
  4015. SpirvEmitter::processBufferTextureLoad(const CXXMemberCallExpr *expr) {
  4016. // Signature:
  4017. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  4018. // ret Object.Load(int Location
  4019. // [, int Offset]
  4020. // [, uint status]);
  4021. //
  4022. // For Texture2DMS and Texture2DMSArray, there is one additional argument:
  4023. // ret Object.Load(int Location
  4024. // [, int SampleIndex]
  4025. // [, int Offset]
  4026. // [, uint status]);
  4027. //
  4028. // For (RW)Buffer, RWTexture1D, RWTexture1DArray, RWTexture2D,
  4029. // RWTexture2DArray, RWTexture3D:
  4030. // ret Object.Load (int Location
  4031. // [, uint status]);
  4032. //
  4033. // Note: (RW)ByteAddressBuffer and (RW)StructuredBuffer types also have Load
  4034. // methods that take an additional Status argument. However, since these types
  4035. // are not represented as OpTypeImage in SPIR-V, we don't have a way of
  4036. // figuring out the Residency Code for them. Therefore having the Status
  4037. // argument for these types is not supported.
  4038. //
  4039. // For (RW)ByteAddressBuffer:
  4040. // ret Object.{Load,Load2,Load3,Load4} (int Location
  4041. // [, uint status]);
  4042. //
  4043. // For (RW)StructuredBuffer:
  4044. // ret Object.Load (int Location
  4045. // [, uint status]);
  4046. //
  4047. const auto *object = expr->getImplicitObjectArgument();
  4048. const auto objectType = object->getType();
  4049. if (isRWByteAddressBuffer(objectType) || isByteAddressBuffer(objectType))
  4050. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ false);
  4051. if (isStructuredBuffer(objectType))
  4052. return processStructuredBufferLoad(expr);
  4053. const auto numArgs = expr->getNumArgs();
  4054. const auto *locationArg = expr->getArg(0);
  4055. const bool textureMS = isTextureMS(objectType);
  4056. const bool hasStatusArg =
  4057. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  4058. auto *status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : nullptr;
  4059. auto loc = expr->getExprLoc();
  4060. if (isBuffer(objectType) || isRWBuffer(objectType) || isRWTexture(objectType))
  4061. return processBufferTextureLoad(object, doExpr(locationArg),
  4062. /*constOffset*/ nullptr,
  4063. /*varOffset*/ nullptr, /*lod*/ nullptr,
  4064. /*residencyCode*/ status, loc);
  4065. // Subtract 1 for status (if it exists), and 1 for sampleIndex (if it exists),
  4066. // and 1 for location.
  4067. const bool hasOffsetArg = numArgs - hasStatusArg - textureMS - 1 > 0;
  4068. if (isTexture(objectType)) {
  4069. // .Load() has a second optional paramter for offset.
  4070. SpirvInstruction *location = doExpr(locationArg);
  4071. SpirvInstruction *constOffset = nullptr, *varOffset = nullptr;
  4072. SpirvInstruction *coordinate = location, *lod = nullptr;
  4073. if (textureMS) {
  4074. // SampleIndex is only available when the Object is of Texture2DMS or
  4075. // Texture2DMSArray types. Under those cases, Offset will be the third
  4076. // parameter (index 2).
  4077. lod = doExpr(expr->getArg(1));
  4078. if (hasOffsetArg)
  4079. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  4080. } else {
  4081. // For Texture Load() functions, the location parameter is a vector
  4082. // that consists of both the coordinate and the mipmap level (via the
  4083. // last vector element). We need to split it here since the
  4084. // OpImageFetch SPIR-V instruction encodes them as separate arguments.
  4085. splitVecLastElement(locationArg->getType(), location, &coordinate, &lod,
  4086. locationArg->getExprLoc());
  4087. // For textures other than Texture2DMS(Array), offset should be the
  4088. // second parameter (index 1).
  4089. if (hasOffsetArg)
  4090. handleOffsetInMethodCall(expr, 1, &constOffset, &varOffset);
  4091. }
  4092. return processBufferTextureLoad(object, coordinate, constOffset, varOffset,
  4093. lod, status, loc);
  4094. }
  4095. emitError("Load() of the given object type unimplemented",
  4096. object->getExprLoc());
  4097. return nullptr;
  4098. }
  4099. SpirvInstruction *
  4100. SpirvEmitter::processGetDimensions(const CXXMemberCallExpr *expr) {
  4101. const auto objectType = expr->getImplicitObjectArgument()->getType();
  4102. if (isTexture(objectType) || isRWTexture(objectType) ||
  4103. isBuffer(objectType) || isRWBuffer(objectType)) {
  4104. return processBufferTextureGetDimensions(expr);
  4105. } else if (isByteAddressBuffer(objectType) ||
  4106. isRWByteAddressBuffer(objectType) ||
  4107. isStructuredBuffer(objectType) ||
  4108. isAppendStructuredBuffer(objectType) ||
  4109. isConsumeStructuredBuffer(objectType)) {
  4110. return processByteAddressBufferStructuredBufferGetDimensions(expr);
  4111. } else {
  4112. emitError("GetDimensions() of the given object type unimplemented",
  4113. expr->getExprLoc());
  4114. return nullptr;
  4115. }
  4116. }
  4117. SpirvInstruction *
  4118. SpirvEmitter::doCXXOperatorCallExpr(const CXXOperatorCallExpr *expr) {
  4119. { // Handle Buffer/RWBuffer/Texture/RWTexture indexing
  4120. const Expr *baseExpr = nullptr;
  4121. const Expr *indexExpr = nullptr;
  4122. const Expr *lodExpr = nullptr;
  4123. // For Textures, regular indexing (operator[]) uses slice 0.
  4124. if (isBufferTextureIndexing(expr, &baseExpr, &indexExpr)) {
  4125. auto *lod = isTexture(baseExpr->getType())
  4126. ? spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  4127. llvm::APInt(32, 0))
  4128. : nullptr;
  4129. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  4130. /*constOffset*/ nullptr,
  4131. /*varOffset*/ nullptr, lod,
  4132. /*residencyCode*/ nullptr,
  4133. expr->getExprLoc());
  4134. }
  4135. // .mips[][] or .sample[][] must use the correct slice.
  4136. if (isTextureMipsSampleIndexing(expr, &baseExpr, &indexExpr, &lodExpr)) {
  4137. auto *lod = doExpr(lodExpr);
  4138. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  4139. /*constOffset*/ nullptr,
  4140. /*varOffset*/ nullptr, lod,
  4141. /*residencyCode*/ nullptr,
  4142. expr->getExprLoc());
  4143. }
  4144. }
  4145. llvm::SmallVector<SpirvInstruction *, 4> indices;
  4146. const Expr *baseExpr = collectArrayStructIndices(
  4147. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  4148. auto base = loadIfAliasVarRef(baseExpr);
  4149. if (indices.empty())
  4150. return base; // For indexing into size-1 vectors and 1xN matrices
  4151. // If we are indexing into a rvalue, to use OpAccessChain, we first need
  4152. // to create a local variable to hold the rvalue.
  4153. //
  4154. // TODO: We can optimize the codegen by emitting OpCompositeExtract if
  4155. // all indices are contant integers.
  4156. if (base->isRValue()) {
  4157. base = createTemporaryVar(baseExpr->getType(), "vector", base,
  4158. baseExpr->getExprLoc());
  4159. }
  4160. return turnIntoElementPtr(baseExpr->getType(), base, expr->getType(), indices,
  4161. baseExpr->getExprLoc());
  4162. }
  4163. SpirvInstruction *
  4164. SpirvEmitter::doExtMatrixElementExpr(const ExtMatrixElementExpr *expr) {
  4165. const Expr *baseExpr = expr->getBase();
  4166. auto *baseInfo = doExpr(baseExpr);
  4167. const auto layoutRule = baseInfo->getLayoutRule();
  4168. const auto elemType = hlsl::GetHLSLMatElementType(baseExpr->getType());
  4169. const auto accessor = expr->getEncodedElementAccess();
  4170. uint32_t rowCount = 0, colCount = 0;
  4171. hlsl::GetHLSLMatRowColCount(baseExpr->getType(), rowCount, colCount);
  4172. // Construct a temporary vector out of all elements accessed:
  4173. // 1. Create access chain for each element using OpAccessChain
  4174. // 2. Load each element using OpLoad
  4175. // 3. Create the vector using OpCompositeConstruct
  4176. llvm::SmallVector<SpirvInstruction *, 4> elements;
  4177. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4178. uint32_t row = 0, col = 0;
  4179. SpirvInstruction *elem = nullptr;
  4180. accessor.GetPosition(i, &row, &col);
  4181. llvm::SmallVector<uint32_t, 2> indices;
  4182. // If the matrix only has one row/column, we are indexing into a vector
  4183. // then. Only one index is needed for such cases.
  4184. if (rowCount > 1)
  4185. indices.push_back(row);
  4186. if (colCount > 1)
  4187. indices.push_back(col);
  4188. if (!baseInfo->isRValue()) {
  4189. llvm::SmallVector<SpirvInstruction *, 2> indexInstructions(indices.size(),
  4190. nullptr);
  4191. for (uint32_t i = 0; i < indices.size(); ++i)
  4192. indexInstructions[i] = spvBuilder.getConstantInt(
  4193. astContext.IntTy, llvm::APInt(32, indices[i], true));
  4194. if (!indices.empty()) {
  4195. assert(!baseInfo->isRValue());
  4196. // Load the element via access chain
  4197. elem = spvBuilder.createAccessChain(
  4198. elemType, baseInfo, indexInstructions, baseExpr->getLocStart());
  4199. } else {
  4200. // The matrix is of size 1x1. No need to use access chain, base should
  4201. // be the source pointer.
  4202. elem = baseInfo;
  4203. }
  4204. elem = spvBuilder.createLoad(elemType, elem, baseExpr->getLocStart());
  4205. } else { // e.g., (mat1 + mat2)._m11
  4206. elem = spvBuilder.createCompositeExtract(elemType, baseInfo, indices,
  4207. baseExpr->getLocStart());
  4208. }
  4209. elements.push_back(elem);
  4210. }
  4211. const auto size = elements.size();
  4212. auto *value = elements.front();
  4213. if (size > 1) {
  4214. value = spvBuilder.createCompositeConstruct(
  4215. astContext.getExtVectorType(elemType, size), elements,
  4216. expr->getLocStart());
  4217. }
  4218. // Note: Special-case: Booleans have no physical layout, and therefore when
  4219. // layout is required booleans are represented as unsigned integers.
  4220. // Therefore, after loading the uint we should convert it boolean.
  4221. if (elemType->isBooleanType() && layoutRule != SpirvLayoutRule::Void) {
  4222. const auto fromType =
  4223. size == 1 ? astContext.UnsignedIntTy
  4224. : astContext.getExtVectorType(astContext.UnsignedIntTy, size);
  4225. const auto toType =
  4226. size == 1 ? astContext.BoolTy
  4227. : astContext.getExtVectorType(astContext.BoolTy, size);
  4228. value = castToBool(value, fromType, toType, expr->getLocStart());
  4229. }
  4230. value->setRValue();
  4231. return value;
  4232. }
  4233. SpirvInstruction *
  4234. SpirvEmitter::doHLSLVectorElementExpr(const HLSLVectorElementExpr *expr) {
  4235. const Expr *baseExpr = nullptr;
  4236. hlsl::VectorMemberAccessPositions accessor;
  4237. condenseVectorElementExpr(expr, &baseExpr, &accessor);
  4238. const QualType baseType = baseExpr->getType();
  4239. assert(hlsl::IsHLSLVecType(baseType));
  4240. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  4241. const auto accessorSize = static_cast<size_t>(accessor.Count);
  4242. // Depending on the number of elements selected, we emit different
  4243. // instructions.
  4244. // For vectors of size greater than 1, if we are only selecting one element,
  4245. // typical access chain or composite extraction should be fine. But if we
  4246. // are selecting more than one elements, we must resolve to vector specific
  4247. // operations.
  4248. // For size-1 vectors, if we are selecting their single elements multiple
  4249. // times, we need composite construct instructions.
  4250. if (accessorSize == 1) {
  4251. auto *baseInfo = doExpr(baseExpr);
  4252. if (!baseInfo || baseSize == 1) {
  4253. // Selecting one element from a size-1 vector. The underlying vector is
  4254. // already treated as a scalar.
  4255. return baseInfo;
  4256. }
  4257. // If the base is an lvalue, we should emit an access chain instruction
  4258. // so that we can load/store the specified element. For rvalue base,
  4259. // we should use composite extraction. We should check the immediate base
  4260. // instead of the original base here since we can have something like
  4261. // v.xyyz to turn a lvalue v into rvalue.
  4262. const auto type = expr->getType();
  4263. if (!baseInfo->isRValue()) { // E.g., v.x;
  4264. auto *index = spvBuilder.getConstantInt(
  4265. astContext.IntTy, llvm::APInt(32, accessor.Swz0, true));
  4266. // We need a lvalue here. Do not try to load.
  4267. return spvBuilder.createAccessChain(type, baseInfo, {index},
  4268. baseExpr->getLocStart());
  4269. } else { // E.g., (v + w).x;
  4270. // The original base vector may not be a rvalue. Need to load it if
  4271. // it is lvalue since ImplicitCastExpr (LValueToRValue) will be missing
  4272. // for that case.
  4273. SpirvInstruction *result = spvBuilder.createCompositeExtract(
  4274. type, baseInfo, {accessor.Swz0}, baseExpr->getLocStart());
  4275. // Special-case: Booleans in SPIR-V do not have a physical layout. Uint is
  4276. // used to represent them when layout is required.
  4277. if (expr->getType()->isBooleanType() &&
  4278. baseInfo->getLayoutRule() != SpirvLayoutRule::Void)
  4279. result = castToBool(result, astContext.UnsignedIntTy, astContext.BoolTy,
  4280. expr->getLocStart());
  4281. return result;
  4282. }
  4283. }
  4284. if (baseSize == 1) {
  4285. // Selecting more than one element from a size-1 vector, for example,
  4286. // <scalar>.xx. Construct the vector.
  4287. auto *info = loadIfGLValue(baseExpr);
  4288. const auto type = expr->getType();
  4289. llvm::SmallVector<SpirvInstruction *, 4> components(accessorSize, info);
  4290. info = spvBuilder.createCompositeConstruct(type, components,
  4291. expr->getLocStart());
  4292. info->setRValue();
  4293. return info;
  4294. }
  4295. llvm::SmallVector<uint32_t, 4> selectors;
  4296. selectors.resize(accessorSize);
  4297. // Whether we are selecting elements in the original order
  4298. bool originalOrder = baseSize == accessorSize;
  4299. for (uint32_t i = 0; i < accessorSize; ++i) {
  4300. accessor.GetPosition(i, &selectors[i]);
  4301. // We can select more elements than the vector provides. This handles
  4302. // that case too.
  4303. originalOrder &= selectors[i] == i;
  4304. }
  4305. if (originalOrder)
  4306. return doExpr(baseExpr);
  4307. auto *info = loadIfGLValue(baseExpr);
  4308. // Use base for both vectors. But we are only selecting values from the
  4309. // first one.
  4310. return spvBuilder.createVectorShuffle(expr->getType(), info, info, selectors,
  4311. expr->getLocStart());
  4312. }
  4313. SpirvInstruction *SpirvEmitter::doInitListExpr(const InitListExpr *expr) {
  4314. if (auto *id = tryToEvaluateAsConst(expr)) {
  4315. id->setRValue();
  4316. return id;
  4317. }
  4318. auto *result = InitListHandler(astContext, *this).processInit(expr);
  4319. result->setRValue();
  4320. return result;
  4321. }
  4322. SpirvInstruction *SpirvEmitter::doMemberExpr(const MemberExpr *expr) {
  4323. llvm::SmallVector<SpirvInstruction *, 4> indices;
  4324. const Expr *base = collectArrayStructIndices(
  4325. expr, /*rawIndex*/ false, /*rawIndices*/ nullptr, &indices);
  4326. auto *instr = loadIfAliasVarRef(base);
  4327. if (instr && !indices.empty()) {
  4328. instr = turnIntoElementPtr(base->getType(), instr, expr->getType(), indices,
  4329. base->getExprLoc());
  4330. }
  4331. return instr;
  4332. }
  4333. SpirvVariable *SpirvEmitter::createTemporaryVar(QualType type,
  4334. llvm::StringRef name,
  4335. SpirvInstruction *init,
  4336. SourceLocation loc) {
  4337. // We are creating a temporary variable in the Function storage class here,
  4338. // which means it has void layout rule.
  4339. const std::string varName = "temp.var." + name.str();
  4340. auto *var = spvBuilder.addFnVar(type, loc, varName);
  4341. storeValue(var, init, type, loc);
  4342. return var;
  4343. }
  4344. SpirvInstruction *SpirvEmitter::doUnaryOperator(const UnaryOperator *expr) {
  4345. const auto opcode = expr->getOpcode();
  4346. const auto *subExpr = expr->getSubExpr();
  4347. const auto subType = subExpr->getType();
  4348. auto *subValue = doExpr(subExpr);
  4349. switch (opcode) {
  4350. case UO_PreInc:
  4351. case UO_PreDec:
  4352. case UO_PostInc:
  4353. case UO_PostDec: {
  4354. const bool isPre = opcode == UO_PreInc || opcode == UO_PreDec;
  4355. const bool isInc = opcode == UO_PreInc || opcode == UO_PostInc;
  4356. const spv::Op spvOp = translateOp(isInc ? BO_Add : BO_Sub, subType);
  4357. SpirvInstruction *originValue =
  4358. subValue->isRValue()
  4359. ? subValue
  4360. : spvBuilder.createLoad(subType, subValue, subExpr->getLocStart());
  4361. auto *one = hlsl::IsHLSLMatType(subType) ? getMatElemValueOne(subType)
  4362. : getValueOne(subType);
  4363. SpirvInstruction *incValue = nullptr;
  4364. if (isMxNMatrix(subType)) {
  4365. // For matrices, we can only increment/decrement each vector of it.
  4366. const auto actOnEachVec = [this, spvOp, one,
  4367. expr](uint32_t /*index*/, QualType vecType,
  4368. SpirvInstruction *lhsVec) {
  4369. auto *val = spvBuilder.createBinaryOp(spvOp, vecType, lhsVec, one,
  4370. expr->getOperatorLoc());
  4371. val->setRValue();
  4372. return val;
  4373. };
  4374. incValue = processEachVectorInMatrix(subExpr, originValue, actOnEachVec,
  4375. expr->getLocStart());
  4376. } else {
  4377. incValue = spvBuilder.createBinaryOp(spvOp, subType, originValue, one,
  4378. expr->getOperatorLoc());
  4379. }
  4380. // If this is a RWBuffer/RWTexture assignment, OpImageWrite will be used.
  4381. // Otherwise, store using OpStore.
  4382. if (tryToAssignToRWBufferRWTexture(subExpr, incValue)) {
  4383. incValue->setRValue();
  4384. subValue = incValue;
  4385. } else {
  4386. spvBuilder.createStore(subValue, incValue, subExpr->getLocStart());
  4387. }
  4388. // Prefix increment/decrement operator returns a lvalue, while postfix
  4389. // increment/decrement returns a rvalue.
  4390. if (isPre) {
  4391. return subValue;
  4392. } else {
  4393. originValue->setRValue();
  4394. return originValue;
  4395. }
  4396. }
  4397. case UO_Not: {
  4398. subValue = spvBuilder.createUnaryOp(spv::Op::OpNot, subType, subValue,
  4399. expr->getOperatorLoc());
  4400. subValue->setRValue();
  4401. return subValue;
  4402. }
  4403. case UO_LNot: {
  4404. // Parsing will do the necessary casting to make sure we are applying the
  4405. // ! operator on boolean values.
  4406. subValue = spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, subType,
  4407. subValue, expr->getOperatorLoc());
  4408. subValue->setRValue();
  4409. return subValue;
  4410. }
  4411. case UO_Plus:
  4412. // No need to do anything for the prefix + operator.
  4413. return subValue;
  4414. case UO_Minus: {
  4415. // SPIR-V have two opcodes for negating values: OpSNegate and OpFNegate.
  4416. const spv::Op spvOp = isFloatOrVecOfFloatType(subType) ? spv::Op::OpFNegate
  4417. : spv::Op::OpSNegate;
  4418. subValue = spvBuilder.createUnaryOp(spvOp, subType, subValue,
  4419. expr->getOperatorLoc());
  4420. subValue->setRValue();
  4421. return subValue;
  4422. }
  4423. default:
  4424. break;
  4425. }
  4426. emitError("unary operator '%0' unimplemented", expr->getExprLoc())
  4427. << expr->getOpcodeStr(opcode);
  4428. expr->dump();
  4429. return 0;
  4430. }
  4431. spv::Op SpirvEmitter::translateOp(BinaryOperator::Opcode op, QualType type) {
  4432. const bool isSintType = isSintOrVecMatOfSintType(type);
  4433. const bool isUintType = isUintOrVecMatOfUintType(type);
  4434. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  4435. #define BIN_OP_CASE_INT_FLOAT(kind, intBinOp, floatBinOp) \
  4436. \
  4437. case BO_##kind: { \
  4438. if (isSintType || isUintType) { \
  4439. return spv::Op::Op##intBinOp; \
  4440. } \
  4441. if (isFloatType) { \
  4442. return spv::Op::Op##floatBinOp; \
  4443. } \
  4444. } break
  4445. #define BIN_OP_CASE_SINT_UINT_FLOAT(kind, sintBinOp, uintBinOp, floatBinOp) \
  4446. \
  4447. case BO_##kind: { \
  4448. if (isSintType) { \
  4449. return spv::Op::Op##sintBinOp; \
  4450. } \
  4451. if (isUintType) { \
  4452. return spv::Op::Op##uintBinOp; \
  4453. } \
  4454. if (isFloatType) { \
  4455. return spv::Op::Op##floatBinOp; \
  4456. } \
  4457. } break
  4458. #define BIN_OP_CASE_SINT_UINT(kind, sintBinOp, uintBinOp) \
  4459. \
  4460. case BO_##kind: { \
  4461. if (isSintType) { \
  4462. return spv::Op::Op##sintBinOp; \
  4463. } \
  4464. if (isUintType) { \
  4465. return spv::Op::Op##uintBinOp; \
  4466. } \
  4467. } break
  4468. switch (op) {
  4469. case BO_EQ: {
  4470. if (isBoolOrVecMatOfBoolType(type))
  4471. return spv::Op::OpLogicalEqual;
  4472. if (isSintType || isUintType)
  4473. return spv::Op::OpIEqual;
  4474. if (isFloatType)
  4475. return spv::Op::OpFOrdEqual;
  4476. } break;
  4477. case BO_NE: {
  4478. if (isBoolOrVecMatOfBoolType(type))
  4479. return spv::Op::OpLogicalNotEqual;
  4480. if (isSintType || isUintType)
  4481. return spv::Op::OpINotEqual;
  4482. if (isFloatType)
  4483. return spv::Op::OpFOrdNotEqual;
  4484. } break;
  4485. // According to HLSL doc, all sides of the && and || expression are always
  4486. // evaluated.
  4487. case BO_LAnd:
  4488. return spv::Op::OpLogicalAnd;
  4489. case BO_LOr:
  4490. return spv::Op::OpLogicalOr;
  4491. BIN_OP_CASE_INT_FLOAT(Add, IAdd, FAdd);
  4492. BIN_OP_CASE_INT_FLOAT(AddAssign, IAdd, FAdd);
  4493. BIN_OP_CASE_INT_FLOAT(Sub, ISub, FSub);
  4494. BIN_OP_CASE_INT_FLOAT(SubAssign, ISub, FSub);
  4495. BIN_OP_CASE_INT_FLOAT(Mul, IMul, FMul);
  4496. BIN_OP_CASE_INT_FLOAT(MulAssign, IMul, FMul);
  4497. BIN_OP_CASE_SINT_UINT_FLOAT(Div, SDiv, UDiv, FDiv);
  4498. BIN_OP_CASE_SINT_UINT_FLOAT(DivAssign, SDiv, UDiv, FDiv);
  4499. // According to HLSL spec, "the modulus operator returns the remainder of
  4500. // a division." "The % operator is defined only in cases where either both
  4501. // sides are positive or both sides are negative."
  4502. //
  4503. // In SPIR-V, there are two reminder operations: Op*Rem and Op*Mod. With
  4504. // the former, the sign of a non-0 result comes from Operand 1, while
  4505. // with the latter, from Operand 2.
  4506. //
  4507. // For operands with different signs, technically we can map % to either
  4508. // Op*Rem or Op*Mod since it's undefined behavior. But it is more
  4509. // consistent with C (HLSL starts as a C derivative) and Clang frontend
  4510. // const expression evaluation if we map % to Op*Rem.
  4511. //
  4512. // Note there is no OpURem in SPIR-V.
  4513. BIN_OP_CASE_SINT_UINT_FLOAT(Rem, SRem, UMod, FRem);
  4514. BIN_OP_CASE_SINT_UINT_FLOAT(RemAssign, SRem, UMod, FRem);
  4515. BIN_OP_CASE_SINT_UINT_FLOAT(LT, SLessThan, ULessThan, FOrdLessThan);
  4516. BIN_OP_CASE_SINT_UINT_FLOAT(LE, SLessThanEqual, ULessThanEqual,
  4517. FOrdLessThanEqual);
  4518. BIN_OP_CASE_SINT_UINT_FLOAT(GT, SGreaterThan, UGreaterThan,
  4519. FOrdGreaterThan);
  4520. BIN_OP_CASE_SINT_UINT_FLOAT(GE, SGreaterThanEqual, UGreaterThanEqual,
  4521. FOrdGreaterThanEqual);
  4522. BIN_OP_CASE_SINT_UINT(And, BitwiseAnd, BitwiseAnd);
  4523. BIN_OP_CASE_SINT_UINT(AndAssign, BitwiseAnd, BitwiseAnd);
  4524. BIN_OP_CASE_SINT_UINT(Or, BitwiseOr, BitwiseOr);
  4525. BIN_OP_CASE_SINT_UINT(OrAssign, BitwiseOr, BitwiseOr);
  4526. BIN_OP_CASE_SINT_UINT(Xor, BitwiseXor, BitwiseXor);
  4527. BIN_OP_CASE_SINT_UINT(XorAssign, BitwiseXor, BitwiseXor);
  4528. BIN_OP_CASE_SINT_UINT(Shl, ShiftLeftLogical, ShiftLeftLogical);
  4529. BIN_OP_CASE_SINT_UINT(ShlAssign, ShiftLeftLogical, ShiftLeftLogical);
  4530. BIN_OP_CASE_SINT_UINT(Shr, ShiftRightArithmetic, ShiftRightLogical);
  4531. BIN_OP_CASE_SINT_UINT(ShrAssign, ShiftRightArithmetic, ShiftRightLogical);
  4532. default:
  4533. break;
  4534. }
  4535. #undef BIN_OP_CASE_INT_FLOAT
  4536. #undef BIN_OP_CASE_SINT_UINT_FLOAT
  4537. #undef BIN_OP_CASE_SINT_UINT
  4538. emitError("translating binary operator '%0' unimplemented", {})
  4539. << BinaryOperator::getOpcodeStr(op);
  4540. return spv::Op::OpNop;
  4541. }
  4542. SpirvInstruction *
  4543. SpirvEmitter::processAssignment(const Expr *lhs, SpirvInstruction *rhs,
  4544. const bool isCompoundAssignment,
  4545. SpirvInstruction *lhsPtr) {
  4546. lhs = lhs->IgnoreParenNoopCasts(astContext);
  4547. // Assigning to vector swizzling should be handled differently.
  4548. if (SpirvInstruction *result = tryToAssignToVectorElements(lhs, rhs))
  4549. return result;
  4550. // Assigning to matrix swizzling should be handled differently.
  4551. if (SpirvInstruction *result = tryToAssignToMatrixElements(lhs, rhs))
  4552. return result;
  4553. // Assigning to a RWBuffer/RWTexture should be handled differently.
  4554. if (SpirvInstruction *result = tryToAssignToRWBufferRWTexture(lhs, rhs))
  4555. return result;
  4556. // Assigning to a out attribute or indices object in mesh shader should be
  4557. // handled differently.
  4558. if (SpirvInstruction *result = tryToAssignToMSOutAttrsOrIndices(lhs, rhs))
  4559. return result;
  4560. // Assigning to a 'string' variable. SPIR-V doesn't have a string type, and we
  4561. // do not allow creating or modifying string variables. We do allow use of
  4562. // string literals using OpString.
  4563. if (isStringType(lhs->getType())) {
  4564. emitError("string variables are immutable in SPIR-V.", lhs->getExprLoc());
  4565. return nullptr;
  4566. }
  4567. // Normal assignment procedure
  4568. if (!lhsPtr)
  4569. lhsPtr = doExpr(lhs);
  4570. storeValue(lhsPtr, rhs, lhs->getType(), lhs->getLocStart());
  4571. // Plain assignment returns a rvalue, while compound assignment returns
  4572. // lvalue.
  4573. return isCompoundAssignment ? lhsPtr : rhs;
  4574. }
  4575. void SpirvEmitter::storeValue(SpirvInstruction *lhsPtr,
  4576. SpirvInstruction *rhsVal, QualType lhsValType,
  4577. SourceLocation loc) {
  4578. // Defend against nullptr source or destination so errors can bubble up to the
  4579. // user.
  4580. if (!lhsPtr || !rhsVal)
  4581. return;
  4582. if (const auto *refType = lhsValType->getAs<ReferenceType>())
  4583. lhsValType = refType->getPointeeType();
  4584. QualType matElemType = {};
  4585. const bool lhsIsMat = isMxNMatrix(lhsValType, &matElemType);
  4586. const bool lhsIsFloatMat = lhsIsMat && matElemType->isFloatingType();
  4587. const bool lhsIsNonFpMat = lhsIsMat && !matElemType->isFloatingType();
  4588. if (isScalarType(lhsValType) || isVectorType(lhsValType) || lhsIsFloatMat) {
  4589. // Special-case: According to the SPIR-V Spec: There is no physical size
  4590. // or bit pattern defined for boolean type. Therefore an unsigned integer
  4591. // is used to represent booleans when layout is required. In such cases,
  4592. // we should cast the boolean to uint before creating OpStore.
  4593. if (isBoolOrVecOfBoolType(lhsValType) &&
  4594. lhsPtr->getLayoutRule() != SpirvLayoutRule::Void) {
  4595. uint32_t vecSize = 1;
  4596. const bool isVec = isVectorType(lhsValType, nullptr, &vecSize);
  4597. const auto toType =
  4598. isVec ? astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize)
  4599. : astContext.UnsignedIntTy;
  4600. const auto fromType =
  4601. isVec ? astContext.getExtVectorType(astContext.BoolTy, vecSize)
  4602. : astContext.BoolTy;
  4603. rhsVal = castToInt(rhsVal, fromType, toType, {});
  4604. }
  4605. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4606. } else if (isOpaqueType(lhsValType)) {
  4607. // Resource types are represented using RecordType in the AST.
  4608. // Handle them before the general RecordType.
  4609. //
  4610. // HLSL allows to put resource types that translating into SPIR-V opaque
  4611. // types in structs, or assign to variables of resource types. These can all
  4612. // result in illegal SPIR-V for Vulkan. We just translate here literally and
  4613. // let SPIRV-Tools opt to do the legalization work.
  4614. //
  4615. // Note: legalization specific code
  4616. if (hlsl::IsHLSLRayQueryType(lhsValType)) {
  4617. emitError("store value of type %0 is unsupported", {}) << lhsValType;
  4618. return;
  4619. }
  4620. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4621. needsLegalization = true;
  4622. } else if (isAKindOfStructuredOrByteBuffer(lhsValType)) {
  4623. // The rhs should be a pointer and the lhs should be a pointer-to-pointer.
  4624. // Directly store the pointer here and let SPIRV-Tools opt to do the clean
  4625. // up.
  4626. //
  4627. // Note: legalization specific code
  4628. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4629. needsLegalization = true;
  4630. // For ConstantBuffers/TextureBuffers, we decompose and assign each field
  4631. // recursively like normal structs using the following logic.
  4632. //
  4633. // The frontend forbids declaring ConstantBuffer<T> or TextureBuffer<T>
  4634. // variables as function parameters/returns/variables, but happily accepts
  4635. // assignments/returns from ConstantBuffer<T>/TextureBuffer<T> to function
  4636. // parameters/returns/variables of type T. And ConstantBuffer<T> is not
  4637. // represented differently as struct T.
  4638. } else if (isOpaqueArrayType(lhsValType)) {
  4639. // For opaque array types, we cannot perform OpLoad on the whole array and
  4640. // then write out as a whole; instead, we need to OpLoad each element
  4641. // using access chains. This is to influence later SPIR-V transformations
  4642. // to use access chains to access each opaque object; if we do array
  4643. // wholesale handling here, they will be in the final transformed code.
  4644. // Drivers don't like that.
  4645. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  4646. assert(lhsValType->isConstantArrayType());
  4647. assert(!rhsVal->isRValue());
  4648. const auto *arrayType = astContext.getAsConstantArrayType(lhsValType);
  4649. const auto elemType = arrayType->getElementType();
  4650. const auto arraySize =
  4651. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4652. // Do separate load of each element via access chain
  4653. llvm::SmallVector<SpirvInstruction *, 8> elements;
  4654. for (uint32_t i = 0; i < arraySize; ++i) {
  4655. auto *subRhsPtr = spvBuilder.createAccessChain(
  4656. elemType, rhsVal,
  4657. {spvBuilder.getConstantInt(astContext.IntTy,
  4658. llvm::APInt(32, i, true))},
  4659. loc);
  4660. elements.push_back(spvBuilder.createLoad(elemType, subRhsPtr, loc));
  4661. }
  4662. // Create a new composite and write out once
  4663. spvBuilder.createStore(
  4664. lhsPtr,
  4665. spvBuilder.createCompositeConstruct(lhsValType, elements,
  4666. rhsVal->getSourceLocation()),
  4667. loc);
  4668. } else if (lhsPtr->getLayoutRule() == rhsVal->getLayoutRule()) {
  4669. // If lhs and rhs has the same memory layout, we should be safe to load
  4670. // from rhs and directly store into lhs and avoid decomposing rhs.
  4671. // Note: this check should happen after those setting needsLegalization.
  4672. // TODO: is this optimization always correct?
  4673. spvBuilder.createStore(lhsPtr, rhsVal, loc);
  4674. } else if (lhsValType->isRecordType() || lhsValType->isConstantArrayType() ||
  4675. lhsIsNonFpMat) {
  4676. spvBuilder.createStore(
  4677. lhsPtr,
  4678. reconstructValue(rhsVal, lhsValType, lhsPtr->getLayoutRule(), loc),
  4679. loc);
  4680. } else {
  4681. emitError("storing value of type %0 unimplemented", {}) << lhsValType;
  4682. }
  4683. }
  4684. SpirvInstruction *SpirvEmitter::reconstructValue(SpirvInstruction *srcVal,
  4685. const QualType valType,
  4686. SpirvLayoutRule dstLR,
  4687. SourceLocation loc) {
  4688. // Lambda for casting scalar or vector of bool<-->uint in cases where one side
  4689. // of the reconstruction (lhs or rhs) has a layout rule.
  4690. const auto handleBooleanLayout = [this, &srcVal, dstLR,
  4691. loc](SpirvInstruction *val,
  4692. QualType valType) {
  4693. // We only need to cast if we have a scalar or vector of booleans.
  4694. if (!isBoolOrVecOfBoolType(valType))
  4695. return val;
  4696. SpirvLayoutRule srcLR = srcVal->getLayoutRule();
  4697. // Source value has a layout rule, and has therefore been represented
  4698. // as a uint. Cast it to boolean before using.
  4699. bool shouldCastToBool =
  4700. srcLR != SpirvLayoutRule::Void && dstLR == SpirvLayoutRule::Void;
  4701. // Destination has a layout rule, and should therefore be represented
  4702. // as a uint. Cast to uint before using.
  4703. bool shouldCastToUint =
  4704. srcLR == SpirvLayoutRule::Void && dstLR != SpirvLayoutRule::Void;
  4705. // No boolean layout issues to take care of.
  4706. if (!shouldCastToBool && !shouldCastToUint)
  4707. return val;
  4708. uint32_t vecSize = 1;
  4709. isVectorType(valType, nullptr, &vecSize);
  4710. QualType boolType =
  4711. vecSize == 1 ? astContext.BoolTy
  4712. : astContext.getExtVectorType(astContext.BoolTy, vecSize);
  4713. QualType uintType =
  4714. vecSize == 1
  4715. ? astContext.UnsignedIntTy
  4716. : astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize);
  4717. if (shouldCastToBool)
  4718. return castToBool(val, uintType, boolType, loc);
  4719. if (shouldCastToUint)
  4720. return castToInt(val, boolType, uintType, loc);
  4721. return val;
  4722. };
  4723. // Lambda for cases where we want to reconstruct an array
  4724. const auto reconstructArray = [this, &srcVal, valType, dstLR,
  4725. loc](uint32_t arraySize,
  4726. QualType arrayElemType) {
  4727. llvm::SmallVector<SpirvInstruction *, 4> elements;
  4728. for (uint32_t i = 0; i < arraySize; ++i) {
  4729. SpirvInstruction *subSrcVal =
  4730. spvBuilder.createCompositeExtract(arrayElemType, srcVal, {i}, loc);
  4731. subSrcVal->setLayoutRule(srcVal->getLayoutRule());
  4732. elements.push_back(
  4733. reconstructValue(subSrcVal, arrayElemType, dstLR, loc));
  4734. }
  4735. auto *result = spvBuilder.createCompositeConstruct(
  4736. valType, elements, srcVal->getSourceLocation());
  4737. result->setLayoutRule(dstLR);
  4738. return result;
  4739. };
  4740. // Constant arrays
  4741. if (const auto *arrayType = astContext.getAsConstantArrayType(valType)) {
  4742. const auto elemType = arrayType->getElementType();
  4743. const auto size =
  4744. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4745. return reconstructArray(size, elemType);
  4746. }
  4747. // Non-floating-point matrices
  4748. QualType matElemType = {};
  4749. uint32_t numRows = 0, numCols = 0;
  4750. const bool isNonFpMat =
  4751. isMxNMatrix(valType, &matElemType, &numRows, &numCols) &&
  4752. !matElemType->isFloatingType();
  4753. if (isNonFpMat) {
  4754. // Note: This check should happen before the RecordType check.
  4755. // Non-fp matrices are represented as arrays of vectors in SPIR-V.
  4756. // Each array element is a vector. Get the QualType for the vector.
  4757. const auto elemType = astContext.getExtVectorType(matElemType, numCols);
  4758. return reconstructArray(numRows, elemType);
  4759. }
  4760. // Note: This check should happen before the RecordType check since
  4761. // vector/matrix/resource types are represented as RecordType in the AST.
  4762. if (hlsl::IsHLSLVecMatType(valType) || hlsl::IsHLSLResourceType(valType))
  4763. return handleBooleanLayout(srcVal, valType);
  4764. // Structs
  4765. if (const auto *recordType = valType->getAs<RecordType>()) {
  4766. uint32_t index = 0;
  4767. llvm::SmallVector<SpirvInstruction *, 4> elements;
  4768. for (const auto *field : recordType->getDecl()->fields()) {
  4769. SpirvInstruction *subSrcVal = spvBuilder.createCompositeExtract(
  4770. field->getType(), srcVal, {index}, loc);
  4771. subSrcVal->setLayoutRule(srcVal->getLayoutRule());
  4772. elements.push_back(
  4773. reconstructValue(subSrcVal, field->getType(), dstLR, loc));
  4774. ++index;
  4775. }
  4776. auto *result = spvBuilder.createCompositeConstruct(
  4777. valType, elements, srcVal->getSourceLocation());
  4778. result->setLayoutRule(dstLR);
  4779. return result;
  4780. }
  4781. return handleBooleanLayout(srcVal, valType);
  4782. }
  4783. SpirvInstruction *SpirvEmitter::processBinaryOp(
  4784. const Expr *lhs, const Expr *rhs, const BinaryOperatorKind opcode,
  4785. const QualType computationType, const QualType resultType,
  4786. SourceRange sourceRange, SourceLocation loc, SpirvInstruction **lhsInfo,
  4787. const spv::Op mandateGenOpcode) {
  4788. const QualType lhsType = lhs->getType();
  4789. const QualType rhsType = rhs->getType();
  4790. // If the operands are of matrix type, we need to dispatch the operation
  4791. // onto each element vector iff the operands are not degenerated matrices
  4792. // and we don't have a matrix specific SPIR-V instruction for the operation.
  4793. if (!isSpirvMatrixOp(mandateGenOpcode) && isMxNMatrix(lhsType)) {
  4794. return processMatrixBinaryOp(lhs, rhs, opcode, sourceRange, loc);
  4795. }
  4796. // Comma operator works differently from other binary operations as there is
  4797. // no SPIR-V instruction for it. For each comma, we must evaluate lhs and rhs
  4798. // respectively, and return the results of rhs.
  4799. if (opcode == BO_Comma) {
  4800. (void)doExpr(lhs);
  4801. return doExpr(rhs);
  4802. }
  4803. SpirvInstruction *rhsVal = nullptr, *lhsPtr = nullptr, *lhsVal = nullptr;
  4804. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4805. // Evalute rhs before lhs
  4806. rhsVal = loadIfGLValue(rhs);
  4807. lhsVal = lhsPtr = doExpr(lhs);
  4808. // This is a compound assignment. We need to load the lhs value if lhs
  4809. // is not already rvalue and does not generate a vector shuffle.
  4810. if (!lhsPtr->isRValue() && !isVectorShuffle(lhs)) {
  4811. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4812. }
  4813. // For a compound assignments, the AST does not have the proper implicit
  4814. // cast if lhs and rhs have different types. So we need to manually cast lhs
  4815. // to the computation type.
  4816. if (computationType != lhsType)
  4817. lhsVal = castToType(lhsVal, lhsType, computationType, lhs->getExprLoc());
  4818. } else {
  4819. // Evalute lhs before rhs
  4820. lhsPtr = doExpr(lhs);
  4821. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4822. rhsVal = loadIfGLValue(rhs);
  4823. }
  4824. if (lhsInfo)
  4825. *lhsInfo = lhsPtr;
  4826. const spv::Op spvOp = (mandateGenOpcode == spv::Op::Max)
  4827. ? translateOp(opcode, computationType)
  4828. : mandateGenOpcode;
  4829. switch (opcode) {
  4830. case BO_Shl:
  4831. case BO_Shr:
  4832. case BO_ShlAssign:
  4833. case BO_ShrAssign:
  4834. // We need to cull the RHS to make sure that we are not shifting by an
  4835. // amount that is larger than the bitwidth of the LHS.
  4836. rhsVal = spvBuilder.createBinaryOp(spv::Op::OpBitwiseAnd, computationType,
  4837. rhsVal, getMaskForBitwidthValue(rhsType),
  4838. loc);
  4839. // Fall through
  4840. case BO_Add:
  4841. case BO_Sub:
  4842. case BO_Mul:
  4843. case BO_Div:
  4844. case BO_Rem:
  4845. case BO_LT:
  4846. case BO_LE:
  4847. case BO_GT:
  4848. case BO_GE:
  4849. case BO_EQ:
  4850. case BO_NE:
  4851. case BO_And:
  4852. case BO_Or:
  4853. case BO_Xor:
  4854. case BO_LAnd:
  4855. case BO_LOr:
  4856. case BO_AddAssign:
  4857. case BO_SubAssign:
  4858. case BO_MulAssign:
  4859. case BO_DivAssign:
  4860. case BO_RemAssign:
  4861. case BO_AndAssign:
  4862. case BO_OrAssign:
  4863. case BO_XorAssign: {
  4864. // To evaluate this expression as an OpSpecConstantOp, we need to make sure
  4865. // both operands are constant and at least one of them is a spec constant.
  4866. if (SpirvConstant *lhsValConstant = dyn_cast<SpirvConstant>(lhsVal)) {
  4867. if (SpirvConstant *rhsValConstant = dyn_cast<SpirvConstant>(rhsVal)) {
  4868. if (isAcceptedSpecConstantBinaryOp(spvOp)) {
  4869. if (lhsValConstant->isSpecConstant() ||
  4870. rhsValConstant->isSpecConstant()) {
  4871. auto *val = spvBuilder.createSpecConstantBinaryOp(
  4872. spvOp, resultType, lhsVal, rhsVal, loc);
  4873. val->setRValue();
  4874. return val;
  4875. }
  4876. }
  4877. }
  4878. }
  4879. // Normal binary operation
  4880. SpirvInstruction *val = nullptr;
  4881. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4882. val = spvBuilder.createBinaryOp(spvOp, computationType, lhsVal, rhsVal,
  4883. loc);
  4884. // For a compound assignments, the AST does not have the proper implicit
  4885. // cast if lhs and rhs have different types. So we need to manually cast
  4886. // the result back to lhs' type.
  4887. if (computationType != lhsType)
  4888. val = castToType(val, computationType, lhsType, lhs->getExprLoc());
  4889. } else {
  4890. val = spvBuilder.createBinaryOp(spvOp, resultType, lhsVal, rhsVal, loc);
  4891. }
  4892. val->setRValue();
  4893. // Propagate RelaxedPrecision
  4894. if (lhsVal->isRelaxedPrecision() || rhsVal->isRelaxedPrecision())
  4895. val->setRelaxedPrecision();
  4896. return val;
  4897. }
  4898. case BO_Assign:
  4899. llvm_unreachable("assignment should not be handled here");
  4900. break;
  4901. case BO_PtrMemD:
  4902. case BO_PtrMemI:
  4903. case BO_Comma:
  4904. // Unimplemented
  4905. break;
  4906. }
  4907. emitError("binary operator '%0' unimplemented", lhs->getExprLoc())
  4908. << BinaryOperator::getOpcodeStr(opcode) << sourceRange;
  4909. return nullptr;
  4910. }
  4911. void SpirvEmitter::initOnce(QualType varType, std::string varName,
  4912. SpirvVariable *var, const Expr *varInit) {
  4913. // For uninitialized resource objects, we do nothing since there is no
  4914. // meaningful zero values for them.
  4915. if (!varInit && hlsl::IsHLSLResourceType(varType))
  4916. return;
  4917. varName = "init.done." + varName;
  4918. auto loc = varInit ? varInit->getLocStart() : SourceLocation();
  4919. // Create a file/module visible variable to hold the initialization state.
  4920. SpirvVariable *initDoneVar = spvBuilder.addModuleVar(
  4921. astContext.BoolTy, spv::StorageClass::Private, /*isPrecise*/ false,
  4922. varName, spvBuilder.getConstantBool(false));
  4923. auto *condition = spvBuilder.createLoad(astContext.BoolTy, initDoneVar, loc);
  4924. auto *todoBB = spvBuilder.createBasicBlock("if.init.todo");
  4925. auto *doneBB = spvBuilder.createBasicBlock("if.init.done");
  4926. // If initDoneVar contains true, we jump to the "done" basic block; otherwise,
  4927. // jump to the "todo" basic block.
  4928. spvBuilder.createConditionalBranch(condition, doneBB, todoBB, loc, doneBB);
  4929. spvBuilder.addSuccessor(todoBB);
  4930. spvBuilder.addSuccessor(doneBB);
  4931. spvBuilder.setMergeTarget(doneBB);
  4932. spvBuilder.setInsertPoint(todoBB);
  4933. // Do initialization and mark done
  4934. if (varInit) {
  4935. var->setStorageClass(spv::StorageClass::Private);
  4936. storeValue(
  4937. // Static function variable are of private storage class
  4938. var, loadIfGLValue(varInit), varInit->getType(), varInit->getLocEnd());
  4939. } else {
  4940. spvBuilder.createStore(var, spvBuilder.getConstantNull(varType), loc);
  4941. }
  4942. spvBuilder.createStore(initDoneVar, spvBuilder.getConstantBool(true), loc);
  4943. spvBuilder.createBranch(doneBB, loc);
  4944. spvBuilder.addSuccessor(doneBB);
  4945. spvBuilder.setInsertPoint(doneBB);
  4946. }
  4947. bool SpirvEmitter::isVectorShuffle(const Expr *expr) {
  4948. // TODO: the following check is essentially duplicated from
  4949. // doHLSLVectorElementExpr. Should unify them.
  4950. if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  4951. const Expr *base = nullptr;
  4952. hlsl::VectorMemberAccessPositions accessor;
  4953. condenseVectorElementExpr(vecElemExpr, &base, &accessor);
  4954. const auto accessorSize = accessor.Count;
  4955. if (accessorSize == 1) {
  4956. // Selecting only one element. OpAccessChain or OpCompositeExtract for
  4957. // such cases.
  4958. return false;
  4959. }
  4960. const auto baseSize = hlsl::GetHLSLVecSize(base->getType());
  4961. if (accessorSize != baseSize)
  4962. return true;
  4963. for (uint32_t i = 0; i < accessorSize; ++i) {
  4964. uint32_t position;
  4965. accessor.GetPosition(i, &position);
  4966. if (position != i)
  4967. return true;
  4968. }
  4969. // Selecting exactly the original vector. No vector shuffle generated.
  4970. return false;
  4971. }
  4972. return false;
  4973. }
  4974. bool SpirvEmitter::isTextureMipsSampleIndexing(const CXXOperatorCallExpr *expr,
  4975. const Expr **base,
  4976. const Expr **location,
  4977. const Expr **lod) {
  4978. if (!expr)
  4979. return false;
  4980. // <object>.mips[][] consists of an outer operator[] and an inner operator[]
  4981. const CXXOperatorCallExpr *outerExpr = expr;
  4982. if (outerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4983. return false;
  4984. const Expr *arg0 = outerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4985. const CXXOperatorCallExpr *innerExpr = dyn_cast<CXXOperatorCallExpr>(arg0);
  4986. // Must have an inner operator[]
  4987. if (!innerExpr ||
  4988. innerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript) {
  4989. return false;
  4990. }
  4991. const Expr *innerArg0 =
  4992. innerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4993. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(innerArg0);
  4994. if (!memberExpr)
  4995. return false;
  4996. // Must be accessing the member named "mips" or "sample"
  4997. const auto &memberName =
  4998. memberExpr->getMemberNameInfo().getName().getAsString();
  4999. if (memberName != "mips" && memberName != "sample")
  5000. return false;
  5001. const Expr *object = memberExpr->getBase();
  5002. const auto objectType = object->getType();
  5003. if (!isTexture(objectType))
  5004. return false;
  5005. if (base)
  5006. *base = object;
  5007. if (lod)
  5008. *lod = innerExpr->getArg(1);
  5009. if (location)
  5010. *location = outerExpr->getArg(1);
  5011. return true;
  5012. }
  5013. bool SpirvEmitter::isBufferTextureIndexing(const CXXOperatorCallExpr *indexExpr,
  5014. const Expr **base,
  5015. const Expr **index) {
  5016. if (!indexExpr)
  5017. return false;
  5018. // Must be operator[]
  5019. if (indexExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  5020. return false;
  5021. const Expr *object = indexExpr->getArg(0);
  5022. const auto objectType = object->getType();
  5023. if (isBuffer(objectType) || isRWBuffer(objectType) || isTexture(objectType) ||
  5024. isRWTexture(objectType)) {
  5025. if (base)
  5026. *base = object;
  5027. if (index)
  5028. *index = indexExpr->getArg(1);
  5029. return true;
  5030. }
  5031. return false;
  5032. }
  5033. void SpirvEmitter::condenseVectorElementExpr(
  5034. const HLSLVectorElementExpr *expr, const Expr **basePtr,
  5035. hlsl::VectorMemberAccessPositions *flattenedAccessor) {
  5036. llvm::SmallVector<hlsl::VectorMemberAccessPositions, 2> accessors;
  5037. *basePtr = expr;
  5038. // Recursively descending until we find the true base vector (the base vector
  5039. // that does not have a base vector). In the meanwhile, collecting accessors
  5040. // in the reverse order.
  5041. // Example: for myVector.yxwz.yxz.xx.yx, the true base is 'myVector'.
  5042. while (const auto *vecElemBase = dyn_cast<HLSLVectorElementExpr>(*basePtr)) {
  5043. accessors.push_back(vecElemBase->getEncodedElementAccess());
  5044. *basePtr = vecElemBase->getBase();
  5045. // We need to skip any number of parentheses around swizzling at any level.
  5046. while (const auto *parenExpr = dyn_cast<ParenExpr>(*basePtr))
  5047. *basePtr = parenExpr->getSubExpr();
  5048. }
  5049. *flattenedAccessor = accessors.back();
  5050. for (int32_t i = accessors.size() - 2; i >= 0; --i) {
  5051. const auto &currentAccessor = accessors[i];
  5052. // Apply the current level of accessor to the flattened accessor of all
  5053. // previous levels of ones.
  5054. hlsl::VectorMemberAccessPositions combinedAccessor;
  5055. for (uint32_t j = 0; j < currentAccessor.Count; ++j) {
  5056. uint32_t currentPosition = 0;
  5057. currentAccessor.GetPosition(j, &currentPosition);
  5058. uint32_t previousPosition = 0;
  5059. flattenedAccessor->GetPosition(currentPosition, &previousPosition);
  5060. combinedAccessor.SetPosition(j, previousPosition);
  5061. }
  5062. combinedAccessor.Count = currentAccessor.Count;
  5063. combinedAccessor.IsValid =
  5064. flattenedAccessor->IsValid && currentAccessor.IsValid;
  5065. *flattenedAccessor = combinedAccessor;
  5066. }
  5067. }
  5068. SpirvInstruction *SpirvEmitter::createVectorSplat(const Expr *scalarExpr,
  5069. uint32_t size) {
  5070. SpirvInstruction *scalarVal = nullptr;
  5071. // Try to evaluate the element as constant first. If successful, then we
  5072. // can generate constant instructions for this vector splat.
  5073. if ((scalarVal = tryToEvaluateAsConst(scalarExpr))) {
  5074. scalarVal->setRValue();
  5075. } else {
  5076. scalarVal = loadIfGLValue(scalarExpr);
  5077. }
  5078. if (!scalarVal || size == 1) {
  5079. // Just return the scalar value for vector splat with size 1.
  5080. // Note that can be used as an lvalue, so we need to carry over
  5081. // the lvalueness for non-constant cases.
  5082. return scalarVal;
  5083. }
  5084. const auto vecType = astContext.getExtVectorType(scalarExpr->getType(), size);
  5085. // TODO: we are saying the constant has Function storage class here.
  5086. // Should find a more meaningful one.
  5087. if (auto *constVal = dyn_cast<SpirvConstant>(scalarVal)) {
  5088. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), constVal);
  5089. auto *value = spvBuilder.getConstantComposite(vecType, elements);
  5090. value->setRValue();
  5091. return value;
  5092. } else {
  5093. llvm::SmallVector<SpirvInstruction *, 4> elements(size_t(size), scalarVal);
  5094. auto *value = spvBuilder.createCompositeConstruct(
  5095. vecType, elements, scalarExpr->getLocStart());
  5096. value->setRValue();
  5097. return value;
  5098. }
  5099. }
  5100. void SpirvEmitter::splitVecLastElement(QualType vecType, SpirvInstruction *vec,
  5101. SpirvInstruction **residual,
  5102. SpirvInstruction **lastElement,
  5103. SourceLocation loc) {
  5104. assert(hlsl::IsHLSLVecType(vecType));
  5105. const uint32_t count = hlsl::GetHLSLVecSize(vecType);
  5106. assert(count > 1);
  5107. const QualType elemType = hlsl::GetHLSLVecElementType(vecType);
  5108. if (count == 2) {
  5109. *residual = spvBuilder.createCompositeExtract(elemType, vec, 0, loc);
  5110. } else {
  5111. llvm::SmallVector<uint32_t, 4> indices;
  5112. for (uint32_t i = 0; i < count - 1; ++i)
  5113. indices.push_back(i);
  5114. const QualType type = astContext.getExtVectorType(elemType, count - 1);
  5115. *residual = spvBuilder.createVectorShuffle(type, vec, vec, indices, loc);
  5116. }
  5117. *lastElement =
  5118. spvBuilder.createCompositeExtract(elemType, vec, {count - 1}, loc);
  5119. }
  5120. SpirvInstruction *SpirvEmitter::convertVectorToStruct(QualType structType,
  5121. QualType elemType,
  5122. SpirvInstruction *vector,
  5123. SourceLocation loc) {
  5124. assert(structType->isStructureType());
  5125. const auto *structDecl = structType->getAsStructureType()->getDecl();
  5126. uint32_t vectorIndex = 0;
  5127. uint32_t elemCount = 1;
  5128. llvm::SmallVector<SpirvInstruction *, 4> members;
  5129. for (const auto *field : structDecl->fields()) {
  5130. if (isScalarType(field->getType())) {
  5131. members.push_back(spvBuilder.createCompositeExtract(
  5132. elemType, vector, {vectorIndex++}, loc));
  5133. } else if (isVectorType(field->getType(), nullptr, &elemCount)) {
  5134. llvm::SmallVector<uint32_t, 4> indices;
  5135. for (uint32_t i = 0; i < elemCount; ++i)
  5136. indices.push_back(vectorIndex++);
  5137. members.push_back(spvBuilder.createVectorShuffle(
  5138. astContext.getExtVectorType(elemType, elemCount), vector, vector,
  5139. indices, loc));
  5140. } else {
  5141. assert(false && "unhandled type");
  5142. }
  5143. }
  5144. return spvBuilder.createCompositeConstruct(structType, members,
  5145. vector->getSourceLocation());
  5146. }
  5147. SpirvInstruction *
  5148. SpirvEmitter::tryToGenFloatVectorScale(const BinaryOperator *expr) {
  5149. const QualType type = expr->getType();
  5150. const SourceRange range = expr->getSourceRange();
  5151. QualType elemType = {};
  5152. // We can only translate floatN * float into OpVectorTimesScalar.
  5153. // So the result type must be floatN. Note that float1 is not a valid vector
  5154. // in SPIR-V.
  5155. if (!(isVectorType(type, &elemType) && elemType->isFloatingType()))
  5156. return nullptr;
  5157. const Expr *lhs = expr->getLHS();
  5158. const Expr *rhs = expr->getRHS();
  5159. // Multiplying a float vector with a float scalar will be represented in
  5160. // AST via a binary operation with two float vectors as operands; one of
  5161. // the operand is from an implicit cast with kind CK_HLSLVectorSplat.
  5162. // vector * scalar
  5163. if (hlsl::IsHLSLVecType(lhs->getType())) {
  5164. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  5165. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  5166. const QualType vecType = expr->getType();
  5167. if (isa<CompoundAssignOperator>(expr)) {
  5168. SpirvInstruction *lhsPtr = nullptr;
  5169. auto *result =
  5170. processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  5171. vecType, vecType, range, expr->getOperatorLoc(),
  5172. &lhsPtr, spv::Op::OpVectorTimesScalar);
  5173. return processAssignment(lhs, result, true, lhsPtr);
  5174. } else {
  5175. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  5176. vecType, vecType, range,
  5177. expr->getOperatorLoc(), nullptr,
  5178. spv::Op::OpVectorTimesScalar);
  5179. }
  5180. }
  5181. }
  5182. }
  5183. // scalar * vector
  5184. if (hlsl::IsHLSLVecType(rhs->getType())) {
  5185. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  5186. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  5187. const QualType vecType = expr->getType();
  5188. // We need to switch the positions of lhs and rhs here because
  5189. // OpVectorTimesScalar requires the first operand to be a vector and
  5190. // the second to be a scalar.
  5191. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  5192. vecType, vecType, range, expr->getOperatorLoc(),
  5193. nullptr, spv::Op::OpVectorTimesScalar);
  5194. }
  5195. }
  5196. }
  5197. return nullptr;
  5198. }
  5199. SpirvInstruction *
  5200. SpirvEmitter::tryToGenFloatMatrixScale(const BinaryOperator *expr) {
  5201. const QualType type = expr->getType();
  5202. const SourceRange range = expr->getSourceRange();
  5203. // We translate 'floatMxN * float' into OpMatrixTimesScalar.
  5204. // We translate 'floatMx1 * float' and 'float1xN * float' using
  5205. // OpVectorTimesScalar.
  5206. // So the result type can be floatMxN, floatMx1, or float1xN.
  5207. if (!hlsl::IsHLSLMatType(type) ||
  5208. !hlsl::GetHLSLMatElementType(type)->isFloatingType() || is1x1Matrix(type))
  5209. return 0;
  5210. const Expr *lhs = expr->getLHS();
  5211. const Expr *rhs = expr->getRHS();
  5212. const QualType lhsType = lhs->getType();
  5213. const QualType rhsType = rhs->getType();
  5214. const auto selectOpcode = [](const QualType ty) {
  5215. return isMx1Matrix(ty) || is1xNMatrix(ty) ? spv::Op::OpVectorTimesScalar
  5216. : spv::Op::OpMatrixTimesScalar;
  5217. };
  5218. // Multiplying a float matrix with a float scalar will be represented in
  5219. // AST via a binary operation with two float matrices as operands; one of
  5220. // the operand is from an implicit cast with kind CK_HLSLMatrixSplat.
  5221. // matrix * scalar
  5222. if (hlsl::IsHLSLMatType(lhsType)) {
  5223. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  5224. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  5225. const QualType matType = expr->getType();
  5226. const spv::Op opcode = selectOpcode(lhsType);
  5227. if (isa<CompoundAssignOperator>(expr)) {
  5228. SpirvInstruction *lhsPtr = nullptr;
  5229. auto *result = processBinaryOp(
  5230. lhs, cast->getSubExpr(), expr->getOpcode(), matType, matType,
  5231. range, expr->getOperatorLoc(), &lhsPtr, opcode);
  5232. return processAssignment(lhs, result, true, lhsPtr);
  5233. } else {
  5234. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  5235. matType, matType, range,
  5236. expr->getOperatorLoc(), nullptr, opcode);
  5237. }
  5238. }
  5239. }
  5240. }
  5241. // scalar * matrix
  5242. if (hlsl::IsHLSLMatType(rhsType)) {
  5243. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  5244. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  5245. const QualType matType = expr->getType();
  5246. const spv::Op opcode = selectOpcode(rhsType);
  5247. // We need to switch the positions of lhs and rhs here because
  5248. // OpMatrixTimesScalar requires the first operand to be a matrix and
  5249. // the second to be a scalar.
  5250. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  5251. matType, matType, range, expr->getOperatorLoc(),
  5252. nullptr, opcode);
  5253. }
  5254. }
  5255. }
  5256. return nullptr;
  5257. }
  5258. SpirvInstruction *
  5259. SpirvEmitter::tryToAssignToVectorElements(const Expr *lhs,
  5260. SpirvInstruction *rhs) {
  5261. // Assigning to a vector swizzling lhs is tricky if we are neither
  5262. // writing to one element nor all elements in their original order.
  5263. // Under such cases, we need to create a new vector swizzling involving
  5264. // both the lhs and rhs vectors and then write the result of this swizzling
  5265. // into the base vector of lhs.
  5266. // For example, for vec4.yz = vec2, we nee to do the following:
  5267. //
  5268. // %vec4Val = OpLoad %v4float %vec4
  5269. // %vec2Val = OpLoad %v2float %vec2
  5270. // %shuffle = OpVectorShuffle %v4float %vec4Val %vec2Val 0 4 5 3
  5271. // OpStore %vec4 %shuffle
  5272. //
  5273. // When doing the vector shuffle, we use the lhs base vector as the first
  5274. // vector and the rhs vector as the second vector. Therefore, all elements
  5275. // in the second vector will be selected into the shuffle result.
  5276. const auto *lhsExpr = dyn_cast<HLSLVectorElementExpr>(lhs);
  5277. if (!lhsExpr)
  5278. return 0;
  5279. // Special case for <scalar-value>.x, which will have an AST of
  5280. // HLSLVectorElementExpr whose base is an ImplicitCastExpr
  5281. // (CK_HLSLVectorSplat). We just need to assign to <scalar-value>
  5282. // for such case.
  5283. if (const auto *baseCast = dyn_cast<CastExpr>(lhsExpr->getBase()))
  5284. if (baseCast->getCastKind() == CastKind::CK_HLSLVectorSplat &&
  5285. hlsl::GetHLSLVecSize(baseCast->getType()) == 1)
  5286. return processAssignment(baseCast->getSubExpr(), rhs, false);
  5287. const Expr *base = nullptr;
  5288. hlsl::VectorMemberAccessPositions accessor;
  5289. condenseVectorElementExpr(lhsExpr, &base, &accessor);
  5290. const QualType baseType = base->getType();
  5291. assert(hlsl::IsHLSLVecType(baseType));
  5292. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  5293. const auto accessorSize = accessor.Count;
  5294. // Whether selecting the whole original vector
  5295. bool isSelectOrigin = accessorSize == baseSize;
  5296. // Assigning to one component
  5297. if (accessorSize == 1) {
  5298. if (isBufferTextureIndexing(dyn_cast_or_null<CXXOperatorCallExpr>(base))) {
  5299. // Assigning to one component of a RWBuffer/RWTexture element
  5300. // We need to use OpImageWrite here.
  5301. // Compose the new vector value first
  5302. auto *oldVec = doExpr(base);
  5303. auto *newVec = spvBuilder.createCompositeInsert(
  5304. baseType, oldVec, {accessor.Swz0}, rhs, lhs->getLocStart());
  5305. auto *result = tryToAssignToRWBufferRWTexture(base, newVec);
  5306. assert(result); // Definitely RWBuffer/RWTexture assignment
  5307. (void)result;
  5308. return rhs; // TODO: incorrect for compound assignments
  5309. } else {
  5310. // Assigning to one component of mesh out attribute/indices vector object.
  5311. SpirvInstruction *vecComponent = spvBuilder.getConstantInt(
  5312. astContext.UnsignedIntTy, llvm::APInt(32, accessor.Swz0));
  5313. if (tryToAssignToMSOutAttrsOrIndices(base, rhs, vecComponent))
  5314. return rhs;
  5315. // Assigning to one normal vector component. Nothing special, just fall
  5316. // back to the normal CodeGen path.
  5317. return nullptr;
  5318. }
  5319. }
  5320. if (isSelectOrigin) {
  5321. for (uint32_t i = 0; i < accessorSize; ++i) {
  5322. uint32_t position;
  5323. accessor.GetPosition(i, &position);
  5324. if (position != i)
  5325. isSelectOrigin = false;
  5326. }
  5327. }
  5328. // Assigning to the original vector
  5329. if (isSelectOrigin) {
  5330. // Ignore this HLSLVectorElementExpr and dispatch to base
  5331. return processAssignment(base, rhs, false);
  5332. }
  5333. if (tryToAssignToMSOutAttrsOrIndices(base, rhs, /*vecComponent=*/nullptr,
  5334. /*noWriteBack=*/true)) {
  5335. // Assigning to 'n' components of mesh out attribute/indices vector object.
  5336. const QualType elemType =
  5337. hlsl::GetHLSLVecElementType(rhs->getAstResultType());
  5338. uint32_t i = 0;
  5339. for (; i < accessor.Count; ++i) {
  5340. auto *rhsElem = spvBuilder.createCompositeExtract(elemType, rhs, {i},
  5341. lhs->getLocStart());
  5342. uint32_t position;
  5343. accessor.GetPosition(i, &position);
  5344. SpirvInstruction *vecComponent = spvBuilder.getConstantInt(
  5345. astContext.UnsignedIntTy, llvm::APInt(32, position));
  5346. if (!tryToAssignToMSOutAttrsOrIndices(base, rhsElem, vecComponent))
  5347. break;
  5348. }
  5349. assert(i == accessor.Count);
  5350. return rhs;
  5351. }
  5352. llvm::SmallVector<uint32_t, 4> selectors;
  5353. selectors.resize(baseSize);
  5354. // Assume we are selecting all original elements first.
  5355. for (uint32_t i = 0; i < baseSize; ++i) {
  5356. selectors[i] = i;
  5357. }
  5358. // Now fix up the elements that actually got overwritten by the rhs vector.
  5359. // Since we are using the rhs vector as the second vector, their index
  5360. // should be offset'ed by the size of the lhs base vector.
  5361. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5362. uint32_t position;
  5363. accessor.GetPosition(i, &position);
  5364. selectors[position] = baseSize + i;
  5365. }
  5366. auto *vec1 = doExpr(base);
  5367. auto *vec1Val = vec1->isRValue() ? vec1
  5368. : spvBuilder.createLoad(baseType, vec1,
  5369. base->getLocStart());
  5370. auto *shuffle = spvBuilder.createVectorShuffle(baseType, vec1Val, rhs,
  5371. selectors, lhs->getLocStart());
  5372. if (!tryToAssignToRWBufferRWTexture(base, shuffle))
  5373. spvBuilder.createStore(vec1, shuffle, lhs->getLocStart());
  5374. // TODO: OK, this return value is incorrect for compound assignments, for
  5375. // which cases we should return lvalues. Should at least emit errors if
  5376. // this return value is used (can be checked via ASTContext.getParents).
  5377. return rhs;
  5378. }
  5379. SpirvInstruction *
  5380. SpirvEmitter::tryToAssignToRWBufferRWTexture(const Expr *lhs,
  5381. SpirvInstruction *rhs) {
  5382. const Expr *baseExpr = nullptr;
  5383. const Expr *indexExpr = nullptr;
  5384. const auto lhsExpr = dyn_cast<CXXOperatorCallExpr>(lhs);
  5385. if (isBufferTextureIndexing(lhsExpr, &baseExpr, &indexExpr)) {
  5386. auto *loc = doExpr(indexExpr);
  5387. const QualType imageType = baseExpr->getType();
  5388. auto *baseInfo = doExpr(baseExpr);
  5389. auto *image =
  5390. spvBuilder.createLoad(imageType, baseInfo, baseExpr->getExprLoc());
  5391. spvBuilder.createImageWrite(imageType, image, loc, rhs, lhs->getExprLoc());
  5392. return rhs;
  5393. }
  5394. return nullptr;
  5395. }
  5396. SpirvInstruction *
  5397. SpirvEmitter::tryToAssignToMatrixElements(const Expr *lhs,
  5398. SpirvInstruction *rhs) {
  5399. const auto *lhsExpr = dyn_cast<ExtMatrixElementExpr>(lhs);
  5400. if (!lhsExpr)
  5401. return nullptr;
  5402. const Expr *baseMat = lhsExpr->getBase();
  5403. auto *base = doExpr(baseMat);
  5404. const QualType elemType = hlsl::GetHLSLMatElementType(baseMat->getType());
  5405. uint32_t rowCount = 0, colCount = 0;
  5406. hlsl::GetHLSLMatRowColCount(baseMat->getType(), rowCount, colCount);
  5407. // For each lhs element written to:
  5408. // 1. Extract the corresponding rhs element using OpCompositeExtract
  5409. // 2. Create access chain for the lhs element using OpAccessChain
  5410. // 3. Write using OpStore
  5411. const auto accessor = lhsExpr->getEncodedElementAccess();
  5412. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5413. uint32_t row = 0, col = 0;
  5414. accessor.GetPosition(i, &row, &col);
  5415. llvm::SmallVector<uint32_t, 2> indices;
  5416. // If the matrix only have one row/column, we are indexing into a vector
  5417. // then. Only one index is needed for such cases.
  5418. if (rowCount > 1)
  5419. indices.push_back(row);
  5420. if (colCount > 1)
  5421. indices.push_back(col);
  5422. llvm::SmallVector<SpirvInstruction *, 2> indexInstructions(indices.size(),
  5423. nullptr);
  5424. for (uint32_t i = 0; i < indices.size(); ++i)
  5425. indexInstructions[i] = spvBuilder.getConstantInt(
  5426. astContext.IntTy, llvm::APInt(32, indices[i], true));
  5427. // If we are writing to only one element, the rhs should already be a
  5428. // scalar value.
  5429. auto *rhsElem = rhs;
  5430. if (accessor.Count > 1) {
  5431. rhsElem = spvBuilder.createCompositeExtract(elemType, rhs, {i},
  5432. rhs->getSourceLocation());
  5433. }
  5434. // If the lhs is actually a matrix of size 1x1, we don't need the access
  5435. // chain. base is already the dest pointer.
  5436. auto *lhsElemPtr = base;
  5437. if (!indexInstructions.empty()) {
  5438. assert(!base->isRValue());
  5439. // Load the element via access chain
  5440. lhsElemPtr = spvBuilder.createAccessChain(
  5441. elemType, lhsElemPtr, indexInstructions, lhs->getLocStart());
  5442. }
  5443. spvBuilder.createStore(lhsElemPtr, rhsElem, lhs->getLocStart());
  5444. }
  5445. // TODO: OK, this return value is incorrect for compound assignments, for
  5446. // which cases we should return lvalues. Should at least emit errors if
  5447. // this return value is used (can be checked via ASTContext.getParents).
  5448. return rhs;
  5449. }
  5450. SpirvInstruction *SpirvEmitter::tryToAssignToMSOutAttrsOrIndices(
  5451. const Expr *lhs, SpirvInstruction *rhs, SpirvInstruction *vecComponent,
  5452. bool noWriteBack) {
  5453. // Early exit for non-mesh shaders.
  5454. if (!spvContext.isMS())
  5455. return nullptr;
  5456. llvm::SmallVector<SpirvInstruction *, 4> indices;
  5457. bool isMSOutAttribute = false;
  5458. bool isMSOutAttributeBlock = false;
  5459. bool isMSOutIndices = false;
  5460. const Expr *base = collectArrayStructIndices(lhs, /*rawIndex*/ false,
  5461. /*rawIndices*/ nullptr, &indices,
  5462. &isMSOutAttribute);
  5463. // Expecting at least one array index - early exit.
  5464. if (!base || indices.empty())
  5465. return nullptr;
  5466. const DeclaratorDecl *varDecl = nullptr;
  5467. if (isMSOutAttribute) {
  5468. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(base);
  5469. assert(memberExpr);
  5470. varDecl = cast<DeclaratorDecl>(memberExpr->getMemberDecl());
  5471. } else {
  5472. if (const auto *arg = dyn_cast<DeclRefExpr>(base)) {
  5473. if (varDecl = dyn_cast<DeclaratorDecl>(arg->getDecl())) {
  5474. if (varDecl->hasAttr<HLSLIndicesAttr>()) {
  5475. isMSOutIndices = true;
  5476. } else if (varDecl->hasAttr<HLSLVerticesAttr>() ||
  5477. varDecl->hasAttr<HLSLPrimitivesAttr>()) {
  5478. isMSOutAttributeBlock = true;
  5479. }
  5480. }
  5481. }
  5482. }
  5483. // Return if no out attribute or indices object found.
  5484. if (!(isMSOutAttribute || isMSOutAttributeBlock || isMSOutIndices)) {
  5485. return nullptr;
  5486. }
  5487. // For noWriteBack, return without generating write instructions.
  5488. if (noWriteBack) {
  5489. return rhs;
  5490. }
  5491. // Add vecComponent to indices.
  5492. if (vecComponent) {
  5493. indices.push_back(vecComponent);
  5494. }
  5495. if (isMSOutAttribute) {
  5496. assignToMSOutAttribute(varDecl, rhs, indices);
  5497. } else if (isMSOutIndices) {
  5498. assignToMSOutIndices(varDecl, rhs, indices);
  5499. } else {
  5500. assert(isMSOutAttributeBlock);
  5501. QualType type = varDecl->getType();
  5502. assert(isa<ConstantArrayType>(type));
  5503. type = astContext.getAsConstantArrayType(type)->getElementType();
  5504. assert(type->isStructureType());
  5505. // Extract subvalue and assign to its corresponding member attribute.
  5506. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  5507. for (const auto *field : structDecl->fields()) {
  5508. const auto fieldType = field->getType();
  5509. SpirvInstruction *subValue = spvBuilder.createCompositeExtract(
  5510. fieldType, rhs, {getNumBaseClasses(type) + field->getFieldIndex()},
  5511. lhs->getLocStart());
  5512. assignToMSOutAttribute(field, subValue, indices);
  5513. }
  5514. }
  5515. // TODO: OK, this return value is incorrect for compound assignments, for
  5516. // which cases we should return lvalues. Should at least emit errors if
  5517. // this return value is used (can be checked via ASTContext.getParents).
  5518. return rhs;
  5519. }
  5520. void SpirvEmitter::assignToMSOutAttribute(
  5521. const DeclaratorDecl *decl, SpirvInstruction *value,
  5522. const llvm::SmallVector<SpirvInstruction *, 4> &indices) {
  5523. assert(spvContext.isMS() && !indices.empty());
  5524. // Extract attribute index and vecComponent (if any).
  5525. SpirvInstruction *attrIndex = indices.front();
  5526. SpirvInstruction *vecComponent = nullptr;
  5527. if (indices.size() > 1) {
  5528. vecComponent = indices.back();
  5529. }
  5530. auto semanticInfo = declIdMapper.getStageVarSemantic(decl);
  5531. assert(semanticInfo.isValid());
  5532. const auto loc = decl->getLocation();
  5533. // Special handle writes to clip/cull distance attributes.
  5534. if (!declIdMapper.glPerVertex.tryToAccess(
  5535. hlsl::DXIL::SigPointKind::MSOut, semanticInfo.semantic->GetKind(),
  5536. semanticInfo.index, attrIndex, &value, /*noWriteBack=*/false,
  5537. vecComponent, loc)) {
  5538. // All other attribute writes are handled below.
  5539. auto *varInstr = declIdMapper.getStageVarInstruction(decl);
  5540. QualType valueType = value->getAstResultType();
  5541. varInstr = spvBuilder.createAccessChain(valueType, varInstr, indices, loc);
  5542. spvBuilder.createStore(varInstr, value, loc);
  5543. }
  5544. }
  5545. void SpirvEmitter::assignToMSOutIndices(
  5546. const DeclaratorDecl *decl, SpirvInstruction *value,
  5547. const llvm::SmallVector<SpirvInstruction *, 4> &indices) {
  5548. assert(spvContext.isMS() && !indices.empty());
  5549. // Extract vertex index and vecComponent (if any).
  5550. SpirvInstruction *vertIndex = indices.front();
  5551. SpirvInstruction *vecComponent = nullptr;
  5552. if (indices.size() > 1) {
  5553. vecComponent = indices.back();
  5554. }
  5555. auto *var = declIdMapper.getStageVarInstruction(decl);
  5556. const auto *varTypeDecl = astContext.getAsConstantArrayType(decl->getType());
  5557. QualType varType = varTypeDecl->getElementType();
  5558. uint32_t numVertices = 1;
  5559. if (!isVectorType(varType, nullptr, &numVertices)) {
  5560. assert(isScalarType(varType));
  5561. }
  5562. QualType valueType = value->getAstResultType();
  5563. uint32_t numValues = 1;
  5564. if (!isVectorType(valueType, nullptr, &numValues)) {
  5565. assert(isScalarType(valueType));
  5566. }
  5567. const auto loc = decl->getLocation();
  5568. if (numVertices == 1) {
  5569. // for "point" output topology.
  5570. assert(numValues == 1);
  5571. // create accesschain for PrimitiveIndicesNV[vertIndex].
  5572. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5573. {vertIndex}, loc);
  5574. // finally create store for PrimitiveIndicesNV[vertIndex] = value.
  5575. spvBuilder.createStore(ptr, value, loc);
  5576. } else {
  5577. // for "line" or "triangle" output topology.
  5578. assert(numVertices == 2 || numVertices == 3);
  5579. // set baseOffset = vertIndex * numVertices.
  5580. auto *baseOffset = spvBuilder.createBinaryOp(
  5581. spv::Op::OpIMul, astContext.UnsignedIntTy, vertIndex,
  5582. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  5583. llvm::APInt(32, numVertices)),
  5584. loc);
  5585. if (vecComponent) {
  5586. // write an individual vector component of uint2 or uint3.
  5587. assert(numValues == 1);
  5588. // set baseOffset = baseOffset + vecComponent.
  5589. baseOffset =
  5590. spvBuilder.createBinaryOp(spv::Op::OpIAdd, astContext.UnsignedIntTy,
  5591. baseOffset, vecComponent, loc);
  5592. // create accesschain for PrimitiveIndicesNV[baseOffset].
  5593. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5594. {baseOffset}, loc);
  5595. // finally create store for PrimitiveIndicesNV[baseOffset] = value.
  5596. spvBuilder.createStore(ptr, value, loc);
  5597. } else {
  5598. // write all vector components of uint2 or uint3.
  5599. assert(numValues == numVertices);
  5600. auto *curOffset = baseOffset;
  5601. for (uint32_t i = 0; i < numValues; ++i) {
  5602. if (i != 0) {
  5603. // set curOffset = baseOffset + i.
  5604. curOffset = spvBuilder.createBinaryOp(
  5605. spv::Op::OpIAdd, astContext.UnsignedIntTy, baseOffset,
  5606. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  5607. llvm::APInt(32, i)),
  5608. loc);
  5609. }
  5610. // create accesschain for PrimitiveIndicesNV[curOffset].
  5611. auto *ptr = spvBuilder.createAccessChain(astContext.UnsignedIntTy, var,
  5612. {curOffset}, loc);
  5613. // finally create store for PrimitiveIndicesNV[curOffset] = value[i].
  5614. spvBuilder.createStore(ptr,
  5615. spvBuilder.createCompositeExtract(
  5616. astContext.UnsignedIntTy, value, {i}, loc),
  5617. loc);
  5618. }
  5619. }
  5620. }
  5621. }
  5622. SpirvInstruction *SpirvEmitter::processEachVectorInMatrix(
  5623. const Expr *matrix, SpirvInstruction *matrixVal,
  5624. llvm::function_ref<SpirvInstruction *(uint32_t, QualType,
  5625. SpirvInstruction *)>
  5626. actOnEachVector,
  5627. SourceLocation loc) {
  5628. const auto matType = matrix->getType();
  5629. assert(isMxNMatrix(matType));
  5630. const QualType vecType = getComponentVectorType(astContext, matType);
  5631. uint32_t rowCount = 0, colCount = 0;
  5632. hlsl::GetHLSLMatRowColCount(matType, rowCount, colCount);
  5633. llvm::SmallVector<SpirvInstruction *, 4> vectors;
  5634. // Extract each component vector and do operation on it
  5635. for (uint32_t i = 0; i < rowCount; ++i) {
  5636. auto *lhsVec = spvBuilder.createCompositeExtract(vecType, matrixVal, {i},
  5637. matrix->getLocStart());
  5638. vectors.push_back(actOnEachVector(i, vecType, lhsVec));
  5639. }
  5640. // Construct the result matrix
  5641. auto *val = spvBuilder.createCompositeConstruct(matType, vectors, loc);
  5642. val->setRValue();
  5643. return val;
  5644. }
  5645. void SpirvEmitter::createSpecConstant(const VarDecl *varDecl) {
  5646. class SpecConstantEnvRAII {
  5647. public:
  5648. // Creates a new instance which sets mode to true on creation,
  5649. // and resets mode to false on destruction.
  5650. SpecConstantEnvRAII(bool *mode) : modeSlot(mode) { *modeSlot = true; }
  5651. ~SpecConstantEnvRAII() { *modeSlot = false; }
  5652. private:
  5653. bool *modeSlot;
  5654. };
  5655. const QualType varType = varDecl->getType();
  5656. bool hasError = false;
  5657. if (!varDecl->isExternallyVisible()) {
  5658. emitError("specialization constant must be externally visible",
  5659. varDecl->getLocation());
  5660. hasError = true;
  5661. }
  5662. if (const auto *builtinType = varType->getAs<BuiltinType>()) {
  5663. switch (builtinType->getKind()) {
  5664. case BuiltinType::Bool:
  5665. case BuiltinType::Int:
  5666. case BuiltinType::UInt:
  5667. case BuiltinType::Float:
  5668. break;
  5669. default:
  5670. emitError("unsupported specialization constant type",
  5671. varDecl->getLocStart());
  5672. hasError = true;
  5673. }
  5674. }
  5675. const auto *init = varDecl->getInit();
  5676. if (!init) {
  5677. emitError("missing default value for specialization constant",
  5678. varDecl->getLocation());
  5679. hasError = true;
  5680. } else if (!isAcceptedSpecConstantInit(init)) {
  5681. emitError("unsupported specialization constant initializer",
  5682. init->getLocStart())
  5683. << init->getSourceRange();
  5684. hasError = true;
  5685. }
  5686. if (hasError)
  5687. return;
  5688. SpecConstantEnvRAII specConstantEnvRAII(&isSpecConstantMode);
  5689. const auto specConstant = doExpr(init);
  5690. // We are not creating a variable to hold the spec constant, instead, we
  5691. // translate the varDecl directly into the spec constant here.
  5692. spvBuilder.decorateSpecId(
  5693. specConstant, varDecl->getAttr<VKConstantIdAttr>()->getSpecConstId(),
  5694. varDecl->getLocation());
  5695. specConstant->setDebugName(varDecl->getName());
  5696. declIdMapper.registerSpecConstant(varDecl, specConstant);
  5697. }
  5698. SpirvInstruction *
  5699. SpirvEmitter::processMatrixBinaryOp(const Expr *lhs, const Expr *rhs,
  5700. const BinaryOperatorKind opcode,
  5701. SourceRange range, SourceLocation loc) {
  5702. // TODO: some code are duplicated from processBinaryOp. Try to unify them.
  5703. const auto lhsType = lhs->getType();
  5704. assert(isMxNMatrix(lhsType));
  5705. const spv::Op spvOp = translateOp(opcode, lhsType);
  5706. SpirvInstruction *rhsVal = nullptr, *lhsPtr = nullptr, *lhsVal = nullptr;
  5707. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  5708. // Evalute rhs before lhs
  5709. rhsVal = doExpr(rhs);
  5710. lhsPtr = doExpr(lhs);
  5711. lhsVal = spvBuilder.createLoad(lhsType, lhsPtr, lhs->getLocStart());
  5712. } else {
  5713. // Evalute lhs before rhs
  5714. lhsVal = lhsPtr = doExpr(lhs);
  5715. rhsVal = doExpr(rhs);
  5716. }
  5717. switch (opcode) {
  5718. case BO_Add:
  5719. case BO_Sub:
  5720. case BO_Mul:
  5721. case BO_Div:
  5722. case BO_Rem:
  5723. case BO_AddAssign:
  5724. case BO_SubAssign:
  5725. case BO_MulAssign:
  5726. case BO_DivAssign:
  5727. case BO_RemAssign: {
  5728. const auto actOnEachVec = [this, spvOp, rhsVal, rhs,
  5729. loc](uint32_t index, QualType vecType,
  5730. SpirvInstruction *lhsVec) {
  5731. // For each vector of lhs, we need to load the corresponding vector of
  5732. // rhs and do the operation on them.
  5733. auto *rhsVec = spvBuilder.createCompositeExtract(vecType, rhsVal, {index},
  5734. rhs->getLocStart());
  5735. auto *val =
  5736. spvBuilder.createBinaryOp(spvOp, vecType, lhsVec, rhsVec, loc);
  5737. val->setRValue();
  5738. return val;
  5739. };
  5740. return processEachVectorInMatrix(lhs, lhsVal, actOnEachVec,
  5741. lhs->getLocStart());
  5742. }
  5743. case BO_Assign:
  5744. llvm_unreachable("assignment should not be handled here");
  5745. default:
  5746. break;
  5747. }
  5748. emitError("binary operator '%0' over matrix type unimplemented",
  5749. lhs->getExprLoc())
  5750. << BinaryOperator::getOpcodeStr(opcode) << range;
  5751. return nullptr;
  5752. }
  5753. const Expr *SpirvEmitter::collectArrayStructIndices(
  5754. const Expr *expr, bool rawIndex,
  5755. llvm::SmallVectorImpl<uint32_t> *rawIndices,
  5756. llvm::SmallVectorImpl<SpirvInstruction *> *indices,
  5757. bool *isMSOutAttribute) {
  5758. assert((rawIndex && rawIndices) || (!rawIndex && indices));
  5759. if (const auto *indexing = dyn_cast<MemberExpr>(expr)) {
  5760. // First check whether this is referring to a static member. If it is, we
  5761. // create a DeclRefExpr for it.
  5762. if (auto *varDecl = dyn_cast<VarDecl>(indexing->getMemberDecl()))
  5763. if (varDecl->isStaticDataMember())
  5764. return DeclRefExpr::Create(
  5765. astContext, NestedNameSpecifierLoc(), SourceLocation(), varDecl,
  5766. /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
  5767. varDecl->getType(), VK_LValue);
  5768. const Expr *base = collectArrayStructIndices(
  5769. indexing->getBase()->IgnoreParenNoopCasts(astContext), rawIndex,
  5770. rawIndices, indices, isMSOutAttribute);
  5771. if (isMSOutAttribute && base) {
  5772. if (const auto *arg = dyn_cast<DeclRefExpr>(base)) {
  5773. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  5774. if (varDecl->hasAttr<HLSLVerticesAttr>() ||
  5775. varDecl->hasAttr<HLSLPrimitivesAttr>()) {
  5776. assert(spvContext.isMS());
  5777. *isMSOutAttribute = true;
  5778. return expr;
  5779. }
  5780. }
  5781. }
  5782. }
  5783. // Append the index of the current level
  5784. const auto *fieldDecl = cast<FieldDecl>(indexing->getMemberDecl());
  5785. assert(fieldDecl);
  5786. // If we are accessing a derived struct, we need to account for the number
  5787. // of base structs, since they are placed as fields at the beginning of the
  5788. // derived struct.
  5789. auto baseType = indexing->getBase()->getType();
  5790. if (baseType->isPointerType()) {
  5791. baseType = baseType->getPointeeType();
  5792. }
  5793. const uint32_t index =
  5794. getNumBaseClasses(baseType) + fieldDecl->getFieldIndex();
  5795. if (rawIndex) {
  5796. rawIndices->push_back(index);
  5797. } else {
  5798. indices->push_back(spvBuilder.getConstantInt(
  5799. astContext.IntTy, llvm::APInt(32, index, true)));
  5800. }
  5801. return base;
  5802. }
  5803. if (const auto *indexing = dyn_cast<ArraySubscriptExpr>(expr)) {
  5804. if (rawIndex)
  5805. return nullptr; // TODO: handle constant array index
  5806. // The base of an ArraySubscriptExpr has a wrapping LValueToRValue implicit
  5807. // cast. We need to ingore it to avoid creating OpLoad.
  5808. const Expr *thisBase = indexing->getBase()->IgnoreParenLValueCasts();
  5809. const Expr *base = collectArrayStructIndices(thisBase, rawIndex, rawIndices,
  5810. indices, isMSOutAttribute);
  5811. // The index into an array must be an integer number.
  5812. const auto *idxExpr = indexing->getIdx();
  5813. const auto idxExprType = idxExpr->getType();
  5814. SpirvInstruction *thisIndex = doExpr(idxExpr);
  5815. if (!idxExprType->isIntegerType() || idxExprType->isBooleanType()) {
  5816. thisIndex = castToInt(thisIndex, idxExprType, astContext.UnsignedIntTy,
  5817. idxExpr->getExprLoc());
  5818. }
  5819. indices->push_back(thisIndex);
  5820. return base;
  5821. }
  5822. if (const auto *indexing = dyn_cast<CXXOperatorCallExpr>(expr))
  5823. if (indexing->getOperator() == OverloadedOperatorKind::OO_Subscript) {
  5824. if (rawIndex)
  5825. return nullptr; // TODO: handle constant array index
  5826. // If this is indexing into resources, we need specific OpImage*
  5827. // instructions for accessing. Return directly to avoid further building
  5828. // up the access chain.
  5829. if (isBufferTextureIndexing(indexing))
  5830. return indexing;
  5831. const Expr *thisBase =
  5832. indexing->getArg(0)->IgnoreParenNoopCasts(astContext);
  5833. const auto thisBaseType = thisBase->getType();
  5834. const Expr *base = collectArrayStructIndices(
  5835. thisBase, rawIndex, rawIndices, indices, isMSOutAttribute);
  5836. if (thisBaseType != base->getType() &&
  5837. isAKindOfStructuredOrByteBuffer(thisBaseType)) {
  5838. // The immediate base is a kind of structured or byte buffer. It should
  5839. // be an alias variable. Break the normal index collecting chain.
  5840. // Return the immediate base as the base so that we can apply other
  5841. // hacks for legalization over it.
  5842. //
  5843. // Note: legalization specific code
  5844. indices->clear();
  5845. base = thisBase;
  5846. }
  5847. // If the base is a StructureType, we need to push an addtional index 0
  5848. // here. This is because we created an additional OpTypeRuntimeArray
  5849. // in the structure.
  5850. if (isStructuredBuffer(thisBaseType))
  5851. indices->push_back(
  5852. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)));
  5853. if ((hlsl::IsHLSLVecType(thisBaseType) &&
  5854. (hlsl::GetHLSLVecSize(thisBaseType) == 1)) ||
  5855. is1x1Matrix(thisBaseType) || is1xNMatrix(thisBaseType)) {
  5856. // If this is a size-1 vector or 1xN matrix, ignore the index.
  5857. } else {
  5858. indices->push_back(doExpr(indexing->getArg(1)));
  5859. }
  5860. return base;
  5861. }
  5862. {
  5863. const Expr *index = nullptr;
  5864. // TODO: the following is duplicating the logic in doCXXMemberCallExpr.
  5865. if (const auto *object = isStructuredBufferLoad(expr, &index)) {
  5866. if (rawIndex)
  5867. return nullptr; // TODO: handle constant array index
  5868. // For object.Load(index), there should be no more indexing into the
  5869. // object.
  5870. indices->push_back(
  5871. spvBuilder.getConstantInt(astContext.IntTy, llvm::APInt(32, 0)));
  5872. indices->push_back(doExpr(index));
  5873. return object;
  5874. }
  5875. }
  5876. // This the deepest we can go. No more array or struct indexing.
  5877. return expr;
  5878. }
  5879. SpirvInstruction *SpirvEmitter::turnIntoElementPtr(
  5880. QualType baseType, SpirvInstruction *base, QualType elemType,
  5881. const llvm::SmallVector<SpirvInstruction *, 4> &indices,
  5882. SourceLocation loc) {
  5883. // If this is a rvalue, we need a temporary object to hold it
  5884. // so that we can get access chain from it.
  5885. const bool needTempVar = base->isRValue();
  5886. SpirvInstruction *accessChainBase = base;
  5887. if (needTempVar) {
  5888. auto varName = getAstTypeName(baseType);
  5889. const auto var = createTemporaryVar(baseType, varName, base, loc);
  5890. var->setLayoutRule(SpirvLayoutRule::Void);
  5891. var->setStorageClass(spv::StorageClass::Function);
  5892. var->setContainsAliasComponent(base->containsAliasComponent());
  5893. accessChainBase = var;
  5894. }
  5895. base = spvBuilder.createAccessChain(elemType, accessChainBase, indices, loc);
  5896. // Okay, this part seems weird, but it is intended:
  5897. // If the base is originally a rvalue, the whole AST involving the base
  5898. // is consistently set up to handle rvalues. By copying the base into
  5899. // a temporary variable and grab an access chain from it, we are breaking
  5900. // the consistency by turning the base from rvalue into lvalue. Keep in
  5901. // mind that there will be no LValueToRValue casts in the AST for us
  5902. // to rely on to load the access chain if a rvalue is expected. Therefore,
  5903. // we must do the load here. Otherwise, it's up to the consumer of this
  5904. // access chain to do the load, and that can be everywhere.
  5905. if (needTempVar) {
  5906. base = spvBuilder.createLoad(elemType, base, loc);
  5907. }
  5908. return base;
  5909. }
  5910. SpirvInstruction *SpirvEmitter::castToBool(SpirvInstruction *fromVal,
  5911. QualType fromType,
  5912. QualType toBoolType,
  5913. SourceLocation loc) {
  5914. if (isSameType(astContext, fromType, toBoolType))
  5915. return fromVal;
  5916. { // Special case handling for converting to a matrix of booleans.
  5917. QualType elemType = {};
  5918. uint32_t rowCount = 0, colCount = 0;
  5919. if (isMxNMatrix(fromType, &elemType, &rowCount, &colCount)) {
  5920. const auto fromRowQualType =
  5921. astContext.getExtVectorType(elemType, colCount);
  5922. const auto toBoolRowQualType =
  5923. astContext.getExtVectorType(astContext.BoolTy, colCount);
  5924. llvm::SmallVector<SpirvInstruction *, 4> rows;
  5925. for (uint32_t i = 0; i < rowCount; ++i) {
  5926. auto *row = spvBuilder.createCompositeExtract(fromRowQualType, fromVal,
  5927. {i}, loc);
  5928. rows.push_back(
  5929. castToBool(row, fromRowQualType, toBoolRowQualType, loc));
  5930. }
  5931. return spvBuilder.createCompositeConstruct(toBoolType, rows, loc);
  5932. }
  5933. }
  5934. // Converting to bool means comparing with value zero.
  5935. const spv::Op spvOp = translateOp(BO_NE, fromType);
  5936. auto *zeroVal = getValueZero(fromType);
  5937. return spvBuilder.createBinaryOp(spvOp, toBoolType, fromVal, zeroVal, loc);
  5938. }
  5939. SpirvInstruction *SpirvEmitter::castToInt(SpirvInstruction *fromVal,
  5940. QualType fromType, QualType toIntType,
  5941. SourceLocation srcLoc) {
  5942. if (isEnumType(fromType))
  5943. fromType = astContext.IntTy;
  5944. if (isSameType(astContext, fromType, toIntType))
  5945. return fromVal;
  5946. if (isBoolOrVecOfBoolType(fromType)) {
  5947. auto *one = getValueOne(toIntType);
  5948. auto *zero = getValueZero(toIntType);
  5949. return spvBuilder.createSelect(toIntType, fromVal, one, zero, srcLoc);
  5950. }
  5951. if (isSintOrVecOfSintType(fromType) || isUintOrVecOfUintType(fromType)) {
  5952. // First convert the source to the bitwidth of the destination if necessary.
  5953. QualType convertedType = {};
  5954. fromVal =
  5955. convertBitwidth(fromVal, srcLoc, fromType, toIntType, &convertedType);
  5956. // If bitwidth conversion was the only thing we needed to do, we're done.
  5957. if (isSameScalarOrVecType(convertedType, toIntType))
  5958. return fromVal;
  5959. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, toIntType, fromVal,
  5960. srcLoc);
  5961. }
  5962. if (isFloatOrVecOfFloatType(fromType)) {
  5963. // First convert the source to the bitwidth of the destination if necessary.
  5964. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toIntType);
  5965. if (isSintOrVecOfSintType(toIntType)) {
  5966. return spvBuilder.createUnaryOp(spv::Op::OpConvertFToS, toIntType,
  5967. fromVal, srcLoc);
  5968. } else if (isUintOrVecOfUintType(toIntType)) {
  5969. return spvBuilder.createUnaryOp(spv::Op::OpConvertFToU, toIntType,
  5970. fromVal, srcLoc);
  5971. } else {
  5972. emitError("casting from floating point to integer unimplemented", srcLoc);
  5973. }
  5974. }
  5975. {
  5976. QualType elemType = {};
  5977. uint32_t numRows = 0, numCols = 0;
  5978. if (isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  5979. // The source matrix and the target matrix must have the same dimensions.
  5980. QualType toElemType = {};
  5981. uint32_t toNumRows = 0, toNumCols = 0;
  5982. const bool isMat =
  5983. isMxNMatrix(toIntType, &toElemType, &toNumRows, &toNumCols);
  5984. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  5985. (void)isMat;
  5986. (void)toNumRows;
  5987. (void)toNumCols;
  5988. // Casting to a matrix of integers: Cast each row and construct a
  5989. // composite.
  5990. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  5991. const QualType vecType = getComponentVectorType(astContext, fromType);
  5992. const auto fromVecQualType =
  5993. astContext.getExtVectorType(elemType, numCols);
  5994. const auto toIntVecQualType =
  5995. astContext.getExtVectorType(toElemType, numCols);
  5996. for (uint32_t row = 0; row < numRows; ++row) {
  5997. auto *rowId =
  5998. spvBuilder.createCompositeExtract(vecType, fromVal, {row}, srcLoc);
  5999. castedRows.push_back(
  6000. castToInt(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  6001. }
  6002. return spvBuilder.createCompositeConstruct(toIntType, castedRows, srcLoc);
  6003. }
  6004. }
  6005. return nullptr;
  6006. }
  6007. SpirvInstruction *SpirvEmitter::convertBitwidth(SpirvInstruction *fromVal,
  6008. SourceLocation loc,
  6009. QualType fromType,
  6010. QualType toType,
  6011. QualType *resultType) {
  6012. // At the moment, we will not make bitwidth conversions to/from literal int
  6013. // and literal float types because they do not represent the intended SPIR-V
  6014. // bitwidth.
  6015. if (isLitTypeOrVecOfLitType(fromType) || isLitTypeOrVecOfLitType(toType))
  6016. return fromVal;
  6017. const auto fromBitwidth = getElementSpirvBitwidth(
  6018. astContext, fromType, spirvOptions.enable16BitTypes);
  6019. const auto toBitwidth = getElementSpirvBitwidth(
  6020. astContext, toType, spirvOptions.enable16BitTypes);
  6021. if (fromBitwidth == toBitwidth) {
  6022. if (resultType)
  6023. *resultType = fromType;
  6024. return fromVal;
  6025. }
  6026. // We want the 'fromType' with the 'toBitwidth'.
  6027. const QualType targetType =
  6028. getTypeWithCustomBitwidth(astContext, fromType, toBitwidth);
  6029. if (resultType)
  6030. *resultType = targetType;
  6031. if (isFloatOrVecOfFloatType(fromType))
  6032. return spvBuilder.createUnaryOp(spv::Op::OpFConvert, targetType, fromVal,
  6033. loc);
  6034. if (isSintOrVecOfSintType(fromType))
  6035. return spvBuilder.createUnaryOp(spv::Op::OpSConvert, targetType, fromVal,
  6036. loc);
  6037. if (isUintOrVecOfUintType(fromType))
  6038. return spvBuilder.createUnaryOp(spv::Op::OpUConvert, targetType, fromVal,
  6039. loc);
  6040. llvm_unreachable("invalid type passed to convertBitwidth");
  6041. }
  6042. SpirvInstruction *SpirvEmitter::castToFloat(SpirvInstruction *fromVal,
  6043. QualType fromType,
  6044. QualType toFloatType,
  6045. SourceLocation srcLoc) {
  6046. if (isSameType(astContext, fromType, toFloatType))
  6047. return fromVal;
  6048. if (isBoolOrVecOfBoolType(fromType)) {
  6049. auto *one = getValueOne(toFloatType);
  6050. auto *zero = getValueZero(toFloatType);
  6051. return spvBuilder.createSelect(toFloatType, fromVal, one, zero, srcLoc);
  6052. }
  6053. if (isSintOrVecOfSintType(fromType)) {
  6054. // First convert the source to the bitwidth of the destination if necessary.
  6055. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6056. return spvBuilder.createUnaryOp(spv::Op::OpConvertSToF, toFloatType,
  6057. fromVal, srcLoc);
  6058. }
  6059. if (isUintOrVecOfUintType(fromType)) {
  6060. // First convert the source to the bitwidth of the destination if necessary.
  6061. fromVal = convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6062. return spvBuilder.createUnaryOp(spv::Op::OpConvertUToF, toFloatType,
  6063. fromVal, srcLoc);
  6064. }
  6065. if (isFloatOrVecOfFloatType(fromType)) {
  6066. // This is the case of float to float conversion with different bitwidths.
  6067. return convertBitwidth(fromVal, srcLoc, fromType, toFloatType);
  6068. }
  6069. // Casting matrix types
  6070. {
  6071. QualType elemType = {};
  6072. uint32_t numRows = 0, numCols = 0;
  6073. if (isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  6074. // The source matrix and the target matrix must have the same dimensions.
  6075. QualType toElemType = {};
  6076. uint32_t toNumRows = 0, toNumCols = 0;
  6077. const auto isMat =
  6078. isMxNMatrix(toFloatType, &toElemType, &toNumRows, &toNumCols);
  6079. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  6080. (void)isMat;
  6081. (void)toNumRows;
  6082. (void)toNumCols;
  6083. // Casting to a matrix of floats: Cast each row and construct a
  6084. // composite.
  6085. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  6086. const QualType vecType = getComponentVectorType(astContext, fromType);
  6087. const auto fromVecQualType =
  6088. astContext.getExtVectorType(elemType, numCols);
  6089. const auto toIntVecQualType =
  6090. astContext.getExtVectorType(toElemType, numCols);
  6091. for (uint32_t row = 0; row < numRows; ++row) {
  6092. auto *rowId =
  6093. spvBuilder.createCompositeExtract(vecType, fromVal, {row}, srcLoc);
  6094. castedRows.push_back(
  6095. castToFloat(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  6096. }
  6097. return spvBuilder.createCompositeConstruct(toFloatType, castedRows,
  6098. srcLoc);
  6099. }
  6100. }
  6101. emitError("casting to floating point unimplemented", srcLoc);
  6102. return nullptr;
  6103. }
  6104. SpirvInstruction *
  6105. SpirvEmitter::processIntrinsicCallExpr(const CallExpr *callExpr) {
  6106. const FunctionDecl *callee = callExpr->getDirectCallee();
  6107. const SourceLocation srcLoc = callExpr->getExprLoc();
  6108. assert(hlsl::IsIntrinsicOp(callee) &&
  6109. "doIntrinsicCallExpr was called for a non-intrinsic function.");
  6110. const bool isFloatType = isFloatOrVecMatOfFloatType(callExpr->getType());
  6111. const bool isSintType = isSintOrVecMatOfSintType(callExpr->getType());
  6112. // Figure out which intrinsic function to translate.
  6113. llvm::StringRef group;
  6114. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  6115. hlsl::GetIntrinsicOp(callee, opcode, group);
  6116. GLSLstd450 glslOpcode = GLSLstd450Bad;
  6117. SpirvInstruction *retVal = nullptr;
  6118. #define INTRINSIC_SPIRV_OP_CASE(intrinsicOp, spirvOp, doEachVec) \
  6119. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6120. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  6121. doEachVec); \
  6122. } break
  6123. #define INTRINSIC_OP_CASE(intrinsicOp, glslOp, doEachVec) \
  6124. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6125. glslOpcode = GLSLstd450::GLSLstd450##glslOp; \
  6126. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6127. srcLoc); \
  6128. } break
  6129. #define INTRINSIC_OP_CASE_INT_FLOAT(intrinsicOp, glslIntOp, glslFloatOp, \
  6130. doEachVec) \
  6131. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6132. glslOpcode = isFloatType ? GLSLstd450::GLSLstd450##glslFloatOp \
  6133. : GLSLstd450::GLSLstd450##glslIntOp; \
  6134. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6135. srcLoc); \
  6136. } break
  6137. #define INTRINSIC_OP_CASE_SINT_UINT(intrinsicOp, glslSintOp, glslUintOp, \
  6138. doEachVec) \
  6139. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6140. glslOpcode = isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  6141. : GLSLstd450::GLSLstd450##glslUintOp; \
  6142. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6143. srcLoc); \
  6144. } break
  6145. #define INTRINSIC_OP_CASE_SINT_UINT_FLOAT(intrinsicOp, glslSintOp, glslUintOp, \
  6146. glslFloatOp, doEachVec) \
  6147. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  6148. glslOpcode = isFloatType \
  6149. ? GLSLstd450::GLSLstd450##glslFloatOp \
  6150. : isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  6151. : GLSLstd450::GLSLstd450##glslUintOp; \
  6152. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec, \
  6153. srcLoc); \
  6154. } break
  6155. switch (const auto hlslOpcode = static_cast<hlsl::IntrinsicOp>(opcode)) {
  6156. case hlsl::IntrinsicOp::IOP_InterlockedAdd:
  6157. case hlsl::IntrinsicOp::IOP_InterlockedAnd:
  6158. case hlsl::IntrinsicOp::IOP_InterlockedMax:
  6159. case hlsl::IntrinsicOp::IOP_InterlockedUMax:
  6160. case hlsl::IntrinsicOp::IOP_InterlockedMin:
  6161. case hlsl::IntrinsicOp::IOP_InterlockedUMin:
  6162. case hlsl::IntrinsicOp::IOP_InterlockedOr:
  6163. case hlsl::IntrinsicOp::IOP_InterlockedXor:
  6164. case hlsl::IntrinsicOp::IOP_InterlockedExchange:
  6165. case hlsl::IntrinsicOp::IOP_InterlockedCompareStore:
  6166. case hlsl::IntrinsicOp::IOP_InterlockedCompareExchange:
  6167. retVal = processIntrinsicInterlockedMethod(callExpr, hlslOpcode);
  6168. break;
  6169. case hlsl::IntrinsicOp::IOP_NonUniformResourceIndex:
  6170. retVal = processIntrinsicNonUniformResourceIndex(callExpr);
  6171. break;
  6172. case hlsl::IntrinsicOp::IOP_tex1D:
  6173. case hlsl::IntrinsicOp::IOP_tex1Dbias:
  6174. case hlsl::IntrinsicOp::IOP_tex1Dgrad:
  6175. case hlsl::IntrinsicOp::IOP_tex1Dlod:
  6176. case hlsl::IntrinsicOp::IOP_tex1Dproj:
  6177. case hlsl::IntrinsicOp::IOP_tex2D:
  6178. case hlsl::IntrinsicOp::IOP_tex2Dbias:
  6179. case hlsl::IntrinsicOp::IOP_tex2Dgrad:
  6180. case hlsl::IntrinsicOp::IOP_tex2Dlod:
  6181. case hlsl::IntrinsicOp::IOP_tex2Dproj:
  6182. case hlsl::IntrinsicOp::IOP_tex3D:
  6183. case hlsl::IntrinsicOp::IOP_tex3Dbias:
  6184. case hlsl::IntrinsicOp::IOP_tex3Dgrad:
  6185. case hlsl::IntrinsicOp::IOP_tex3Dlod:
  6186. case hlsl::IntrinsicOp::IOP_tex3Dproj:
  6187. case hlsl::IntrinsicOp::IOP_texCUBE:
  6188. case hlsl::IntrinsicOp::IOP_texCUBEbias:
  6189. case hlsl::IntrinsicOp::IOP_texCUBEgrad:
  6190. case hlsl::IntrinsicOp::IOP_texCUBElod:
  6191. case hlsl::IntrinsicOp::IOP_texCUBEproj: {
  6192. emitError("deprecated %0 intrinsic function will not be supported", srcLoc)
  6193. << callee->getName();
  6194. return nullptr;
  6195. }
  6196. case hlsl::IntrinsicOp::IOP_dot:
  6197. retVal = processIntrinsicDot(callExpr);
  6198. break;
  6199. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrier:
  6200. retVal = processIntrinsicMemoryBarrier(callExpr,
  6201. /*isDevice*/ false,
  6202. /*groupSync*/ false,
  6203. /*isAllBarrier*/ false);
  6204. break;
  6205. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  6206. retVal = processIntrinsicMemoryBarrier(callExpr,
  6207. /*isDevice*/ false,
  6208. /*groupSync*/ true,
  6209. /*isAllBarrier*/ false);
  6210. break;
  6211. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrier:
  6212. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6213. /*groupSync*/ false,
  6214. /*isAllBarrier*/ false);
  6215. break;
  6216. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  6217. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6218. /*groupSync*/ true,
  6219. /*isAllBarrier*/ false);
  6220. break;
  6221. case hlsl::IntrinsicOp::IOP_AllMemoryBarrier:
  6222. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6223. /*groupSync*/ false,
  6224. /*isAllBarrier*/ true);
  6225. break;
  6226. case hlsl::IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  6227. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  6228. /*groupSync*/ true,
  6229. /*isAllBarrier*/ true);
  6230. break;
  6231. case hlsl::IntrinsicOp::IOP_CheckAccessFullyMapped:
  6232. retVal = spvBuilder.createImageSparseTexelsResident(
  6233. doExpr(callExpr->getArg(0)), srcLoc);
  6234. break;
  6235. case hlsl::IntrinsicOp::IOP_mul:
  6236. case hlsl::IntrinsicOp::IOP_umul:
  6237. retVal = processIntrinsicMul(callExpr);
  6238. break;
  6239. case hlsl::IntrinsicOp::IOP_all:
  6240. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAll);
  6241. break;
  6242. case hlsl::IntrinsicOp::IOP_any:
  6243. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAny);
  6244. break;
  6245. case hlsl::IntrinsicOp::IOP_asdouble:
  6246. case hlsl::IntrinsicOp::IOP_asfloat:
  6247. case hlsl::IntrinsicOp::IOP_asint:
  6248. case hlsl::IntrinsicOp::IOP_asuint:
  6249. retVal = processIntrinsicAsType(callExpr);
  6250. break;
  6251. case hlsl::IntrinsicOp::IOP_clip:
  6252. retVal = processIntrinsicClip(callExpr);
  6253. break;
  6254. case hlsl::IntrinsicOp::IOP_dst:
  6255. retVal = processIntrinsicDst(callExpr);
  6256. break;
  6257. case hlsl::IntrinsicOp::IOP_clamp:
  6258. case hlsl::IntrinsicOp::IOP_uclamp:
  6259. retVal = processIntrinsicClamp(callExpr);
  6260. break;
  6261. case hlsl::IntrinsicOp::IOP_frexp:
  6262. retVal = processIntrinsicFrexp(callExpr);
  6263. break;
  6264. case hlsl::IntrinsicOp::IOP_ldexp:
  6265. retVal = processIntrinsicLdexp(callExpr);
  6266. break;
  6267. case hlsl::IntrinsicOp::IOP_lit:
  6268. retVal = processIntrinsicLit(callExpr);
  6269. break;
  6270. case hlsl::IntrinsicOp::IOP_mad:
  6271. case hlsl::IntrinsicOp::IOP_umad:
  6272. retVal = processIntrinsicMad(callExpr);
  6273. break;
  6274. case hlsl::IntrinsicOp::IOP_modf:
  6275. retVal = processIntrinsicModf(callExpr);
  6276. break;
  6277. case hlsl::IntrinsicOp::IOP_msad4:
  6278. retVal = processIntrinsicMsad4(callExpr);
  6279. break;
  6280. case hlsl::IntrinsicOp::IOP_printf:
  6281. retVal = processIntrinsicPrintf(callExpr);
  6282. break;
  6283. case hlsl::IntrinsicOp::IOP_sign: {
  6284. if (isFloatOrVecMatOfFloatType(callExpr->getArg(0)->getType()))
  6285. retVal = processIntrinsicFloatSign(callExpr);
  6286. else
  6287. retVal =
  6288. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450SSign,
  6289. /*actPerRowForMatrices*/ true, srcLoc);
  6290. } break;
  6291. case hlsl::IntrinsicOp::IOP_D3DCOLORtoUBYTE4:
  6292. retVal = processD3DCOLORtoUBYTE4(callExpr);
  6293. break;
  6294. case hlsl::IntrinsicOp::IOP_isfinite:
  6295. retVal = processIntrinsicIsFinite(callExpr);
  6296. break;
  6297. case hlsl::IntrinsicOp::IOP_sincos:
  6298. retVal = processIntrinsicSinCos(callExpr);
  6299. break;
  6300. case hlsl::IntrinsicOp::IOP_rcp:
  6301. retVal = processIntrinsicRcp(callExpr);
  6302. break;
  6303. case hlsl::IntrinsicOp::IOP_saturate:
  6304. retVal = processIntrinsicSaturate(callExpr);
  6305. break;
  6306. case hlsl::IntrinsicOp::IOP_log10:
  6307. retVal = processIntrinsicLog10(callExpr);
  6308. break;
  6309. case hlsl::IntrinsicOp::IOP_f16tof32:
  6310. retVal = processIntrinsicF16ToF32(callExpr);
  6311. break;
  6312. case hlsl::IntrinsicOp::IOP_f32tof16:
  6313. retVal = processIntrinsicF32ToF16(callExpr);
  6314. break;
  6315. case hlsl::IntrinsicOp::IOP_WaveGetLaneCount: {
  6316. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneCount",
  6317. srcLoc);
  6318. const QualType retType = callExpr->getCallReturnType(astContext);
  6319. auto *var =
  6320. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupSize, retType, srcLoc);
  6321. retVal = spvBuilder.createLoad(retType, var, srcLoc);
  6322. } break;
  6323. case hlsl::IntrinsicOp::IOP_WaveGetLaneIndex: {
  6324. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneIndex",
  6325. srcLoc);
  6326. const QualType retType = callExpr->getCallReturnType(astContext);
  6327. auto *var = declIdMapper.getBuiltinVar(
  6328. spv::BuiltIn::SubgroupLocalInvocationId, retType, srcLoc);
  6329. retVal = spvBuilder.createLoad(retType, var, srcLoc);
  6330. } break;
  6331. case hlsl::IntrinsicOp::IOP_WaveIsFirstLane:
  6332. retVal = processWaveQuery(callExpr, spv::Op::OpGroupNonUniformElect);
  6333. break;
  6334. case hlsl::IntrinsicOp::IOP_WaveActiveAllTrue:
  6335. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAll);
  6336. break;
  6337. case hlsl::IntrinsicOp::IOP_WaveActiveAnyTrue:
  6338. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAny);
  6339. break;
  6340. case hlsl::IntrinsicOp::IOP_WaveActiveBallot:
  6341. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformBallot);
  6342. break;
  6343. case hlsl::IntrinsicOp::IOP_WaveActiveAllEqual:
  6344. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAllEqual);
  6345. break;
  6346. case hlsl::IntrinsicOp::IOP_WaveActiveCountBits:
  6347. retVal = processWaveCountBits(callExpr, spv::GroupOperation::Reduce);
  6348. break;
  6349. case hlsl::IntrinsicOp::IOP_WaveActiveUSum:
  6350. case hlsl::IntrinsicOp::IOP_WaveActiveSum:
  6351. case hlsl::IntrinsicOp::IOP_WaveActiveUProduct:
  6352. case hlsl::IntrinsicOp::IOP_WaveActiveProduct:
  6353. case hlsl::IntrinsicOp::IOP_WaveActiveUMax:
  6354. case hlsl::IntrinsicOp::IOP_WaveActiveMax:
  6355. case hlsl::IntrinsicOp::IOP_WaveActiveUMin:
  6356. case hlsl::IntrinsicOp::IOP_WaveActiveMin:
  6357. case hlsl::IntrinsicOp::IOP_WaveActiveBitAnd:
  6358. case hlsl::IntrinsicOp::IOP_WaveActiveBitOr:
  6359. case hlsl::IntrinsicOp::IOP_WaveActiveBitXor: {
  6360. const auto retType = callExpr->getCallReturnType(astContext);
  6361. retVal = processWaveReductionOrPrefix(
  6362. callExpr, translateWaveOp(hlslOpcode, retType, srcLoc),
  6363. spv::GroupOperation::Reduce);
  6364. } break;
  6365. case hlsl::IntrinsicOp::IOP_WavePrefixUSum:
  6366. case hlsl::IntrinsicOp::IOP_WavePrefixSum:
  6367. case hlsl::IntrinsicOp::IOP_WavePrefixUProduct:
  6368. case hlsl::IntrinsicOp::IOP_WavePrefixProduct: {
  6369. const auto retType = callExpr->getCallReturnType(astContext);
  6370. retVal = processWaveReductionOrPrefix(
  6371. callExpr, translateWaveOp(hlslOpcode, retType, srcLoc),
  6372. spv::GroupOperation::ExclusiveScan);
  6373. } break;
  6374. case hlsl::IntrinsicOp::IOP_WavePrefixCountBits:
  6375. retVal = processWaveCountBits(callExpr, spv::GroupOperation::ExclusiveScan);
  6376. break;
  6377. case hlsl::IntrinsicOp::IOP_WaveReadLaneAt:
  6378. case hlsl::IntrinsicOp::IOP_WaveReadLaneFirst:
  6379. retVal = processWaveBroadcast(callExpr);
  6380. break;
  6381. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  6382. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  6383. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  6384. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  6385. retVal = processWaveQuadWideShuffle(callExpr, hlslOpcode);
  6386. break;
  6387. case hlsl::IntrinsicOp::IOP_abort:
  6388. case hlsl::IntrinsicOp::IOP_GetRenderTargetSampleCount:
  6389. case hlsl::IntrinsicOp::IOP_GetRenderTargetSamplePosition: {
  6390. emitError("no equivalent for %0 intrinsic function in Vulkan", srcLoc)
  6391. << callee->getName();
  6392. return 0;
  6393. }
  6394. case hlsl::IntrinsicOp::IOP_transpose: {
  6395. const Expr *mat = callExpr->getArg(0);
  6396. const QualType matType = mat->getType();
  6397. if (hlsl::GetHLSLMatElementType(matType)->isFloatingType())
  6398. retVal =
  6399. processIntrinsicUsingSpirvInst(callExpr, spv::Op::OpTranspose, false);
  6400. else
  6401. retVal = processNonFpMatrixTranspose(matType, doExpr(mat), srcLoc);
  6402. break;
  6403. }
  6404. // DXR raytracing intrinsics
  6405. case hlsl::IntrinsicOp::IOP_DispatchRaysDimensions:
  6406. case hlsl::IntrinsicOp::IOP_DispatchRaysIndex:
  6407. case hlsl::IntrinsicOp::IOP_GeometryIndex:
  6408. case hlsl::IntrinsicOp::IOP_HitKind:
  6409. case hlsl::IntrinsicOp::IOP_InstanceIndex:
  6410. case hlsl::IntrinsicOp::IOP_InstanceID:
  6411. case hlsl::IntrinsicOp::IOP_ObjectRayDirection:
  6412. case hlsl::IntrinsicOp::IOP_ObjectRayOrigin:
  6413. case hlsl::IntrinsicOp::IOP_ObjectToWorld3x4:
  6414. case hlsl::IntrinsicOp::IOP_ObjectToWorld4x3:
  6415. case hlsl::IntrinsicOp::IOP_PrimitiveIndex:
  6416. case hlsl::IntrinsicOp::IOP_RayFlags:
  6417. case hlsl::IntrinsicOp::IOP_RayTCurrent:
  6418. case hlsl::IntrinsicOp::IOP_RayTMin:
  6419. case hlsl::IntrinsicOp::IOP_WorldRayDirection:
  6420. case hlsl::IntrinsicOp::IOP_WorldRayOrigin:
  6421. case hlsl::IntrinsicOp::IOP_WorldToObject3x4:
  6422. case hlsl::IntrinsicOp::IOP_WorldToObject4x3: {
  6423. retVal = processRayBuiltins(callExpr, hlslOpcode);
  6424. break;
  6425. }
  6426. case hlsl::IntrinsicOp::IOP_AcceptHitAndEndSearch:
  6427. case hlsl::IntrinsicOp::IOP_IgnoreHit: {
  6428. // Any modifications made to the ray payload in an any hit shader are
  6429. // preserved before calling AcceptHit/IgnoreHit. Write out the results to
  6430. // the payload which is visible only in entry functions
  6431. const auto iter = functionInfoMap.find(curFunction);
  6432. if (iter != functionInfoMap.end()) {
  6433. const auto &entryInfo = iter->second;
  6434. if (entryInfo->isEntryFunction) {
  6435. const auto payloadArg = curFunction->getParamDecl(0);
  6436. const auto payloadArgInst =
  6437. declIdMapper.getDeclEvalInfo(payloadArg, payloadArg->getLocStart());
  6438. auto tempLoad = spvBuilder.createLoad(
  6439. payloadArg->getType(), payloadArgInst, payloadArg->getLocStart());
  6440. spvBuilder.createStore(currentRayPayload, tempLoad,
  6441. callExpr->getExprLoc());
  6442. }
  6443. }
  6444. spvBuilder.createRayTracingOpsNV(
  6445. hlslOpcode == hlsl::IntrinsicOp ::IOP_AcceptHitAndEndSearch
  6446. ? spv::Op::OpTerminateRayNV
  6447. : spv::Op::OpIgnoreIntersectionNV,
  6448. QualType(), {}, srcLoc);
  6449. break;
  6450. }
  6451. case hlsl::IntrinsicOp::IOP_ReportHit: {
  6452. retVal = processReportHit(callExpr);
  6453. break;
  6454. }
  6455. case hlsl::IntrinsicOp::IOP_TraceRay: {
  6456. processTraceRay(callExpr);
  6457. break;
  6458. }
  6459. case hlsl::IntrinsicOp::IOP_CallShader: {
  6460. processCallShader(callExpr);
  6461. break;
  6462. }
  6463. case hlsl::IntrinsicOp::IOP_DispatchMesh: {
  6464. processDispatchMesh(callExpr);
  6465. break;
  6466. }
  6467. case hlsl::IntrinsicOp::IOP_SetMeshOutputCounts: {
  6468. processMeshOutputCounts(callExpr);
  6469. break;
  6470. }
  6471. INTRINSIC_SPIRV_OP_CASE(ddx, DPdx, true);
  6472. INTRINSIC_SPIRV_OP_CASE(ddx_coarse, DPdxCoarse, false);
  6473. INTRINSIC_SPIRV_OP_CASE(ddx_fine, DPdxFine, false);
  6474. INTRINSIC_SPIRV_OP_CASE(ddy, DPdy, true);
  6475. INTRINSIC_SPIRV_OP_CASE(ddy_coarse, DPdyCoarse, false);
  6476. INTRINSIC_SPIRV_OP_CASE(ddy_fine, DPdyFine, false);
  6477. INTRINSIC_SPIRV_OP_CASE(countbits, BitCount, false);
  6478. INTRINSIC_SPIRV_OP_CASE(isinf, IsInf, true);
  6479. INTRINSIC_SPIRV_OP_CASE(isnan, IsNan, true);
  6480. INTRINSIC_SPIRV_OP_CASE(fmod, FMod, true);
  6481. INTRINSIC_SPIRV_OP_CASE(fwidth, Fwidth, true);
  6482. INTRINSIC_SPIRV_OP_CASE(reversebits, BitReverse, false);
  6483. INTRINSIC_OP_CASE(round, Round, true);
  6484. INTRINSIC_OP_CASE(uabs, SAbs, true);
  6485. INTRINSIC_OP_CASE_INT_FLOAT(abs, SAbs, FAbs, true);
  6486. INTRINSIC_OP_CASE(acos, Acos, true);
  6487. INTRINSIC_OP_CASE(asin, Asin, true);
  6488. INTRINSIC_OP_CASE(atan, Atan, true);
  6489. INTRINSIC_OP_CASE(atan2, Atan2, true);
  6490. INTRINSIC_OP_CASE(ceil, Ceil, true);
  6491. INTRINSIC_OP_CASE(cos, Cos, true);
  6492. INTRINSIC_OP_CASE(cosh, Cosh, true);
  6493. INTRINSIC_OP_CASE(cross, Cross, false);
  6494. INTRINSIC_OP_CASE(degrees, Degrees, true);
  6495. INTRINSIC_OP_CASE(distance, Distance, false);
  6496. INTRINSIC_OP_CASE(determinant, Determinant, false);
  6497. INTRINSIC_OP_CASE(exp, Exp, true);
  6498. INTRINSIC_OP_CASE(exp2, Exp2, true);
  6499. INTRINSIC_OP_CASE_SINT_UINT(firstbithigh, FindSMsb, FindUMsb, false);
  6500. INTRINSIC_OP_CASE_SINT_UINT(ufirstbithigh, FindSMsb, FindUMsb, false);
  6501. INTRINSIC_OP_CASE(faceforward, FaceForward, false);
  6502. INTRINSIC_OP_CASE(firstbitlow, FindILsb, false);
  6503. INTRINSIC_OP_CASE(floor, Floor, true);
  6504. INTRINSIC_OP_CASE(fma, Fma, true);
  6505. INTRINSIC_OP_CASE(frac, Fract, true);
  6506. INTRINSIC_OP_CASE(length, Length, false);
  6507. INTRINSIC_OP_CASE(lerp, FMix, true);
  6508. INTRINSIC_OP_CASE(log, Log, true);
  6509. INTRINSIC_OP_CASE(log2, Log2, true);
  6510. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(max, SMax, UMax, FMax, true);
  6511. INTRINSIC_OP_CASE(umax, UMax, true);
  6512. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(min, SMin, UMin, FMin, true);
  6513. INTRINSIC_OP_CASE(umin, UMin, true);
  6514. INTRINSIC_OP_CASE(normalize, Normalize, false);
  6515. INTRINSIC_OP_CASE(pow, Pow, true);
  6516. INTRINSIC_OP_CASE(radians, Radians, true);
  6517. INTRINSIC_OP_CASE(reflect, Reflect, false);
  6518. INTRINSIC_OP_CASE(refract, Refract, false);
  6519. INTRINSIC_OP_CASE(rsqrt, InverseSqrt, true);
  6520. INTRINSIC_OP_CASE(smoothstep, SmoothStep, true);
  6521. INTRINSIC_OP_CASE(step, Step, true);
  6522. INTRINSIC_OP_CASE(sin, Sin, true);
  6523. INTRINSIC_OP_CASE(sinh, Sinh, true);
  6524. INTRINSIC_OP_CASE(tan, Tan, true);
  6525. INTRINSIC_OP_CASE(tanh, Tanh, true);
  6526. INTRINSIC_OP_CASE(sqrt, Sqrt, true);
  6527. INTRINSIC_OP_CASE(trunc, Trunc, true);
  6528. default:
  6529. emitError("%0 intrinsic function unimplemented", srcLoc)
  6530. << callee->getName();
  6531. return 0;
  6532. }
  6533. #undef INTRINSIC_OP_CASE
  6534. #undef INTRINSIC_OP_CASE_INT_FLOAT
  6535. if (retVal)
  6536. retVal->setRValue();
  6537. return retVal;
  6538. }
  6539. SpirvInstruction *
  6540. SpirvEmitter::processIntrinsicInterlockedMethod(const CallExpr *expr,
  6541. hlsl::IntrinsicOp opcode) {
  6542. // The signature of intrinsic atomic methods are:
  6543. // void Interlocked*(in R dest, in T value);
  6544. // void Interlocked*(in R dest, in T value, out T original_value);
  6545. // Note: ALL Interlocked*() methods are forced to have an unsigned integer
  6546. // 'value'. Meaning, T is forced to be 'unsigned int'. If the provided
  6547. // parameter is not an unsigned integer, the frontend inserts an
  6548. // 'ImplicitCastExpr' to convert it to unsigned integer. OpAtomicIAdd (and
  6549. // other SPIR-V OpAtomic* instructions) require that the pointee in 'dest' to
  6550. // be of the same type as T. This will result in an invalid SPIR-V if 'dest'
  6551. // is a signed integer typed resource such as RWTexture1D<int>. For example,
  6552. // the following OpAtomicIAdd is invalid because the pointee type defined in
  6553. // %1 is a signed integer, while the value passed to atomic add (%3) is an
  6554. // unsigned integer.
  6555. //
  6556. // %_ptr_Image_int = OpTypePointer Image %int
  6557. // %1 = OpImageTexelPointer %_ptr_Image_int %RWTexture1D_int %index %uint_0
  6558. // %2 = OpLoad %int %value
  6559. // %3 = OpBitcast %uint %2 <-------- Inserted by the frontend
  6560. // %4 = OpAtomicIAdd %int %1 %uint_1 %uint_0 %3
  6561. //
  6562. // In such cases, we bypass the forced IntegralCast.
  6563. // Moreover, the frontend does not add a cast AST node to cast uint to int
  6564. // where necessary. To ensure SPIR-V validity, we add that where necessary.
  6565. auto *zero =
  6566. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  6567. const auto *dest = expr->getArg(0);
  6568. const auto srcLoc = expr->getExprLoc();
  6569. const auto baseType = dest->getType()->getCanonicalTypeUnqualified();
  6570. if (!baseType->isIntegerType()) {
  6571. emitError("can only perform atomic operations on scalar integer values",
  6572. dest->getLocStart());
  6573. return nullptr;
  6574. }
  6575. const auto doArg = [baseType, this](const CallExpr *callExpr,
  6576. uint32_t argIndex) {
  6577. const Expr *valueExpr = callExpr->getArg(argIndex);
  6578. if (const auto *castExpr = dyn_cast<ImplicitCastExpr>(valueExpr))
  6579. if (castExpr->getCastKind() == CK_IntegralCast &&
  6580. castExpr->getSubExpr()->getType() == baseType)
  6581. valueExpr = castExpr->getSubExpr();
  6582. auto *argInstr = doExpr(valueExpr);
  6583. if (valueExpr->getType() != baseType)
  6584. argInstr = castToInt(argInstr, valueExpr->getType(), baseType,
  6585. valueExpr->getExprLoc());
  6586. return argInstr;
  6587. };
  6588. const auto writeToOutputArg = [&baseType, dest,
  6589. this](SpirvInstruction *toWrite,
  6590. const CallExpr *callExpr,
  6591. uint32_t outputArgIndex) {
  6592. const auto outputArg = callExpr->getArg(outputArgIndex);
  6593. const auto outputArgType = outputArg->getType();
  6594. if (baseType != outputArgType)
  6595. toWrite =
  6596. castToInt(toWrite, baseType, outputArgType, dest->getLocStart());
  6597. spvBuilder.createStore(doExpr(outputArg), toWrite, callExpr->getExprLoc());
  6598. };
  6599. // If a vector swizzling of a texture is done as an argument of an
  6600. // interlocked method, we need to handle the access to the texture
  6601. // buffer element correctly. For example:
  6602. //
  6603. // InterlockedAdd(myRWTexture[index].r, 1);
  6604. //
  6605. // `-CallExpr
  6606. // |-ImplicitCastExpr
  6607. // | `-DeclRefExpr Function 'InterlockedAdd'
  6608. // | 'void (unsigned int &, unsigned int)'
  6609. // |-HLSLVectorElementExpr 'unsigned int' lvalue vectorcomponent r
  6610. // | `-ImplicitCastExpr 'vector<uint, 1>':'vector<unsigned int, 1>'
  6611. // | <HLSLVectorSplat>
  6612. // | `-CXXOperatorCallExpr 'unsigned int' lvalue
  6613. const auto *cxxOpCall = dyn_cast<CXXOperatorCallExpr>(dest);
  6614. if (const auto *vector = dyn_cast<HLSLVectorElementExpr>(dest)) {
  6615. const Expr *base = vector->getBase();
  6616. cxxOpCall = dyn_cast<CXXOperatorCallExpr>(base);
  6617. if (const auto *cast = dyn_cast<CastExpr>(base)) {
  6618. cxxOpCall = dyn_cast<CXXOperatorCallExpr>(cast->getSubExpr());
  6619. }
  6620. }
  6621. // If the argument is indexing into a texture/buffer, we need to create an
  6622. // OpImageTexelPointer instruction.
  6623. SpirvInstruction *ptr = nullptr;
  6624. if (cxxOpCall) {
  6625. const Expr *base = nullptr;
  6626. const Expr *index = nullptr;
  6627. if (isBufferTextureIndexing(cxxOpCall, &base, &index)) {
  6628. if (hlsl::IsHLSLResourceType(base->getType())) {
  6629. const auto resultTy = hlsl::GetHLSLResourceResultType(base->getType());
  6630. if (!isScalarType(resultTy, nullptr)) {
  6631. emitError("Interlocked operation for texture buffer whose result "
  6632. "type is non-scalar type is not allowed",
  6633. dest->getExprLoc());
  6634. return nullptr;
  6635. }
  6636. }
  6637. auto *baseInstr = doExpr(base);
  6638. if (baseInstr->isRValue()) {
  6639. // OpImageTexelPointer's Image argument must have a type of
  6640. // OpTypePointer with Type OpTypeImage. Need to create a temporary
  6641. // variable if the baseId is an rvalue.
  6642. baseInstr =
  6643. createTemporaryVar(base->getType(), getAstTypeName(base->getType()),
  6644. baseInstr, base->getExprLoc());
  6645. }
  6646. auto *coordInstr = doExpr(index);
  6647. ptr = spvBuilder.createImageTexelPointer(baseType, baseInstr, coordInstr,
  6648. zero, srcLoc);
  6649. }
  6650. }
  6651. if (!ptr) {
  6652. auto *ptrInfo = doExpr(dest);
  6653. const auto sc = ptrInfo->getStorageClass();
  6654. if (sc == spv::StorageClass::Private || sc == spv::StorageClass::Function) {
  6655. emitError("using static variable or function scope variable in "
  6656. "interlocked operation is not allowed",
  6657. dest->getExprLoc());
  6658. return nullptr;
  6659. }
  6660. ptr = ptrInfo;
  6661. }
  6662. const bool isCompareExchange =
  6663. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareExchange;
  6664. const bool isCompareStore =
  6665. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareStore;
  6666. if (isCompareExchange || isCompareStore) {
  6667. auto *comparator = doArg(expr, 1);
  6668. auto *valueInstr = doArg(expr, 2);
  6669. auto *originalVal = spvBuilder.createAtomicCompareExchange(
  6670. baseType, ptr, spv::Scope::Device, spv::MemorySemanticsMask::MaskNone,
  6671. spv::MemorySemanticsMask::MaskNone, valueInstr, comparator, srcLoc);
  6672. if (isCompareExchange)
  6673. writeToOutputArg(originalVal, expr, 3);
  6674. } else {
  6675. auto *value = doArg(expr, 1);
  6676. // Since these atomic operations write through the provided pointer, the
  6677. // signed vs. unsigned opcode must be decided based on the pointee type
  6678. // of the first argument. However, the frontend decides the opcode based on
  6679. // the second argument (value). Therefore, the HLSL opcode provided by the
  6680. // frontend may be wrong. Therefore we need the following code to make sure
  6681. // we are using the correct SPIR-V opcode.
  6682. spv::Op atomicOp = translateAtomicHlslOpcodeToSpirvOpcode(opcode);
  6683. if (atomicOp == spv::Op::OpAtomicUMax && baseType->isSignedIntegerType())
  6684. atomicOp = spv::Op::OpAtomicSMax;
  6685. if (atomicOp == spv::Op::OpAtomicSMax && baseType->isUnsignedIntegerType())
  6686. atomicOp = spv::Op::OpAtomicUMax;
  6687. if (atomicOp == spv::Op::OpAtomicUMin && baseType->isSignedIntegerType())
  6688. atomicOp = spv::Op::OpAtomicSMin;
  6689. if (atomicOp == spv::Op::OpAtomicSMin && baseType->isUnsignedIntegerType())
  6690. atomicOp = spv::Op::OpAtomicUMin;
  6691. auto *originalVal = spvBuilder.createAtomicOp(
  6692. atomicOp, baseType, ptr, spv::Scope::Device,
  6693. spv::MemorySemanticsMask::MaskNone, value, srcLoc);
  6694. if (expr->getNumArgs() > 2)
  6695. writeToOutputArg(originalVal, expr, 2);
  6696. }
  6697. return nullptr;
  6698. }
  6699. SpirvInstruction *
  6700. SpirvEmitter::processIntrinsicNonUniformResourceIndex(const CallExpr *expr) {
  6701. auto *index = doExpr(expr->getArg(0));
  6702. // Decorate the expression in NonUniformResourceIndex() with NonUniformEXT.
  6703. // Aside from this, we also need to eventually populate the NonUniformEXT
  6704. // status to the usages of this expression. This is done by the
  6705. // NonUniformVisitor class.
  6706. //
  6707. // The decoration shouldn't be applied to the operand, rather to a copy of the
  6708. // result. Even though applying the decoration to the operand may not be
  6709. // functionally incorrect (since adding NonUniform is more conservative), it
  6710. // could affect performance and isn't the intent of the shader.
  6711. auto *copyInstr =
  6712. spvBuilder.createCopyObject(expr->getType(), index, expr->getExprLoc());
  6713. copyInstr->setNonUniform();
  6714. return copyInstr;
  6715. }
  6716. SpirvInstruction *
  6717. SpirvEmitter::processIntrinsicMsad4(const CallExpr *callExpr) {
  6718. const auto loc = callExpr->getExprLoc();
  6719. if (!spirvOptions.noWarnEmulatedFeatures)
  6720. emitWarning("msad4 intrinsic function is emulated using many SPIR-V "
  6721. "instructions due to lack of direct SPIR-V equivalent",
  6722. loc);
  6723. // Compares a 4-byte reference value and an 8-byte source value and
  6724. // accumulates a vector of 4 sums. Each sum corresponds to the masked sum
  6725. // of absolute differences of a different byte alignment between the
  6726. // reference value and the source value.
  6727. // If we have:
  6728. // uint v0; // reference
  6729. // uint2 v1; // source
  6730. // uint4 v2; // accum
  6731. // uint4 o0; // result of msad4
  6732. // uint4 r0, t0; // temporary values
  6733. //
  6734. // Then msad4(v0, v1, v2) translates to the following SM5 assembly according
  6735. // to fxc:
  6736. // Step 1:
  6737. // ushr r0.xyz, v1.xxxx, l(8, 16, 24, 0)
  6738. // Step 2:
  6739. // [result], [ width ], [ offset ], [ insert ], [ base ]
  6740. // bfi t0.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), v1.yyyy , r0.xxyz
  6741. // mov t0.x, v1.x
  6742. // Step 3:
  6743. // msad o0.xyzw, v0.xxxx, t0.xyzw, v2.xyzw
  6744. const auto boolType = astContext.BoolTy;
  6745. const auto intType = astContext.IntTy;
  6746. const auto uintType = astContext.UnsignedIntTy;
  6747. const auto uint4Type = astContext.getExtVectorType(uintType, 4);
  6748. auto *reference = doExpr(callExpr->getArg(0));
  6749. auto *source = doExpr(callExpr->getArg(1));
  6750. auto *accum = doExpr(callExpr->getArg(2));
  6751. const auto uint0 =
  6752. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  6753. const auto uint8 =
  6754. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 8));
  6755. const auto uint16 =
  6756. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 16));
  6757. const auto uint24 =
  6758. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 24));
  6759. // Step 1.
  6760. auto *v1x = spvBuilder.createCompositeExtract(uintType, source, {0}, loc);
  6761. // r0.x = v1xS8 = v1.x shifted by 8 bits
  6762. auto *v1xS8 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical, uintType,
  6763. v1x, uint8, loc);
  6764. // r0.y = v1xS16 = v1.x shifted by 16 bits
  6765. auto *v1xS16 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  6766. uintType, v1x, uint16, loc);
  6767. // r0.z = v1xS24 = v1.x shifted by 24 bits
  6768. auto *v1xS24 = spvBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  6769. uintType, v1x, uint24, loc);
  6770. // Step 2.
  6771. // Do bfi 3 times. DXIL bfi is equivalent to SPIR-V OpBitFieldInsert.
  6772. auto *v1y = spvBuilder.createCompositeExtract(uintType, source, {1}, loc);
  6773. // Note that t0.x = v1.x, nothing we need to do for that.
  6774. auto *t0y =
  6775. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS8, /*insert*/ v1y,
  6776. /*offset*/ uint24,
  6777. /*width*/ uint8, loc);
  6778. auto *t0z =
  6779. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS16, /*insert*/ v1y,
  6780. /*offset*/ uint16,
  6781. /*width*/ uint16, loc);
  6782. auto *t0w =
  6783. spvBuilder.createBitFieldInsert(uintType, /*base*/ v1xS24, /*insert*/ v1y,
  6784. /*offset*/ uint8,
  6785. /*width*/ uint24, loc);
  6786. // Step 3. MSAD (Masked Sum of Absolute Differences)
  6787. // Now perform MSAD four times.
  6788. // Need to mimic this algorithm in SPIR-V!
  6789. //
  6790. // UINT msad( UINT ref, UINT src, UINT accum )
  6791. // {
  6792. // for (UINT i = 0; i < 4; i++)
  6793. // {
  6794. // BYTE refByte, srcByte, absDiff;
  6795. //
  6796. // refByte = (BYTE)(ref >> (i * 8));
  6797. // if (!refByte)
  6798. // {
  6799. // continue;
  6800. // }
  6801. //
  6802. // srcByte = (BYTE)(src >> (i * 8));
  6803. // if (refByte >= srcByte)
  6804. // {
  6805. // absDiff = refByte - srcByte;
  6806. // }
  6807. // else
  6808. // {
  6809. // absDiff = srcByte - refByte;
  6810. // }
  6811. //
  6812. // // The recommended overflow behavior for MSAD is
  6813. // // to do a 32-bit saturate. This is not
  6814. // // required, however, and wrapping is allowed.
  6815. // // So from an application point of view,
  6816. // // overflow behavior is undefined.
  6817. // if (UINT_MAX - accum < absDiff)
  6818. // {
  6819. // accum = UINT_MAX;
  6820. // break;
  6821. // }
  6822. // accum += absDiff;
  6823. // }
  6824. //
  6825. // return accum;
  6826. // }
  6827. auto *accum0 = spvBuilder.createCompositeExtract(uintType, accum, {0}, loc);
  6828. auto *accum1 = spvBuilder.createCompositeExtract(uintType, accum, {1}, loc);
  6829. auto *accum2 = spvBuilder.createCompositeExtract(uintType, accum, {2}, loc);
  6830. auto *accum3 = spvBuilder.createCompositeExtract(uintType, accum, {3}, loc);
  6831. const llvm::SmallVector<SpirvInstruction *, 4> sources = {v1x, t0y, t0z, t0w};
  6832. llvm::SmallVector<SpirvInstruction *, 4> accums = {accum0, accum1, accum2,
  6833. accum3};
  6834. llvm::SmallVector<SpirvInstruction *, 4> refBytes;
  6835. llvm::SmallVector<SpirvInstruction *, 4> signedRefBytes;
  6836. llvm::SmallVector<SpirvInstruction *, 4> isRefByteZero;
  6837. for (uint32_t i = 0; i < 4; ++i) {
  6838. refBytes.push_back(spvBuilder.createBitFieldExtract(
  6839. uintType, reference, /*offset*/
  6840. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  6841. llvm::APInt(32, i * 8)),
  6842. /*count*/ uint8, /*isSigned*/ false, loc));
  6843. signedRefBytes.push_back(spvBuilder.createUnaryOp(
  6844. spv::Op::OpBitcast, intType, refBytes.back(), loc));
  6845. isRefByteZero.push_back(spvBuilder.createBinaryOp(
  6846. spv::Op::OpIEqual, boolType, refBytes.back(), uint0, loc));
  6847. }
  6848. for (uint32_t msadNum = 0; msadNum < 4; ++msadNum) {
  6849. for (uint32_t byteCount = 0; byteCount < 4; ++byteCount) {
  6850. // 'count' is always 8 because we are extracting 8 bits out of 32.
  6851. auto *srcByte = spvBuilder.createBitFieldExtract(
  6852. uintType, sources[msadNum],
  6853. /*offset*/
  6854. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  6855. llvm::APInt(32, 8 * byteCount)),
  6856. /*count*/ uint8, /*isSigned*/ false, loc);
  6857. auto *signedSrcByte =
  6858. spvBuilder.createUnaryOp(spv::Op::OpBitcast, intType, srcByte, loc);
  6859. auto *sub = spvBuilder.createBinaryOp(spv::Op::OpISub, intType,
  6860. signedRefBytes[byteCount],
  6861. signedSrcByte, loc);
  6862. auto *absSub = spvBuilder.createGLSLExtInst(
  6863. intType, GLSLstd450::GLSLstd450SAbs, {sub}, loc);
  6864. auto *diff = spvBuilder.createSelect(
  6865. uintType, isRefByteZero[byteCount], uint0,
  6866. spvBuilder.createUnaryOp(spv::Op::OpBitcast, uintType, absSub, loc),
  6867. loc);
  6868. // As pointed out by the DXIL reference above, it is *not* required to
  6869. // saturate the output to UINT_MAX in case of overflow. Wrapping around is
  6870. // also allowed. For simplicity, we will wrap around at this point.
  6871. accums[msadNum] = spvBuilder.createBinaryOp(spv::Op::OpIAdd, uintType,
  6872. accums[msadNum], diff, loc);
  6873. }
  6874. }
  6875. return spvBuilder.createCompositeConstruct(uint4Type, accums, loc);
  6876. }
  6877. SpirvInstruction *SpirvEmitter::processWaveQuery(const CallExpr *callExpr,
  6878. spv::Op opcode) {
  6879. // Signatures:
  6880. // bool WaveIsFirstLane()
  6881. // uint WaveGetLaneCount()
  6882. // uint WaveGetLaneIndex()
  6883. assert(callExpr->getNumArgs() == 0);
  6884. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6885. callExpr->getExprLoc());
  6886. const QualType retType = callExpr->getCallReturnType(astContext);
  6887. return spvBuilder.createGroupNonUniformElect(
  6888. opcode, retType, spv::Scope::Subgroup, callExpr->getExprLoc());
  6889. }
  6890. SpirvInstruction *SpirvEmitter::processWaveVote(const CallExpr *callExpr,
  6891. spv::Op opcode) {
  6892. // Signatures:
  6893. // bool WaveActiveAnyTrue( bool expr )
  6894. // bool WaveActiveAllTrue( bool expr )
  6895. // bool uint4 WaveActiveBallot( bool expr )
  6896. assert(callExpr->getNumArgs() == 1);
  6897. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6898. callExpr->getExprLoc());
  6899. auto *predicate = doExpr(callExpr->getArg(0));
  6900. const QualType retType = callExpr->getCallReturnType(astContext);
  6901. return spvBuilder.createGroupNonUniformUnaryOp(
  6902. callExpr->getExprLoc(), opcode, retType, spv::Scope::Subgroup, predicate);
  6903. }
  6904. spv::Op SpirvEmitter::translateWaveOp(hlsl::IntrinsicOp op, QualType type,
  6905. SourceLocation srcLoc) {
  6906. const bool isSintType = isSintOrVecMatOfSintType(type);
  6907. const bool isUintType = isUintOrVecMatOfUintType(type);
  6908. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  6909. #define WAVE_OP_CASE_INT(kind, intWaveOp) \
  6910. \
  6911. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6912. if (isSintType || isUintType) { \
  6913. return spv::Op::OpGroupNonUniform##intWaveOp; \
  6914. } \
  6915. } break
  6916. #define WAVE_OP_CASE_INT_FLOAT(kind, intWaveOp, floatWaveOp) \
  6917. \
  6918. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6919. if (isSintType || isUintType) { \
  6920. return spv::Op::OpGroupNonUniform##intWaveOp; \
  6921. } \
  6922. if (isFloatType) { \
  6923. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  6924. } \
  6925. } break
  6926. #define WAVE_OP_CASE_SINT_UINT_FLOAT(kind, sintWaveOp, uintWaveOp, \
  6927. floatWaveOp) \
  6928. \
  6929. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6930. if (isSintType) { \
  6931. return spv::Op::OpGroupNonUniform##sintWaveOp; \
  6932. } \
  6933. if (isUintType) { \
  6934. return spv::Op::OpGroupNonUniform##uintWaveOp; \
  6935. } \
  6936. if (isFloatType) { \
  6937. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  6938. } \
  6939. } break
  6940. switch (op) {
  6941. WAVE_OP_CASE_INT_FLOAT(ActiveUSum, IAdd, FAdd);
  6942. WAVE_OP_CASE_INT_FLOAT(ActiveSum, IAdd, FAdd);
  6943. WAVE_OP_CASE_INT_FLOAT(ActiveUProduct, IMul, FMul);
  6944. WAVE_OP_CASE_INT_FLOAT(ActiveProduct, IMul, FMul);
  6945. WAVE_OP_CASE_INT_FLOAT(PrefixUSum, IAdd, FAdd);
  6946. WAVE_OP_CASE_INT_FLOAT(PrefixSum, IAdd, FAdd);
  6947. WAVE_OP_CASE_INT_FLOAT(PrefixUProduct, IMul, FMul);
  6948. WAVE_OP_CASE_INT_FLOAT(PrefixProduct, IMul, FMul);
  6949. WAVE_OP_CASE_INT(ActiveBitAnd, BitwiseAnd);
  6950. WAVE_OP_CASE_INT(ActiveBitOr, BitwiseOr);
  6951. WAVE_OP_CASE_INT(ActiveBitXor, BitwiseXor);
  6952. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMax, SMax, UMax, FMax);
  6953. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMax, SMax, UMax, FMax);
  6954. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMin, SMin, UMin, FMin);
  6955. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMin, SMin, UMin, FMin);
  6956. default:
  6957. // Only Simple Wave Ops are handled here.
  6958. break;
  6959. }
  6960. #undef WAVE_OP_CASE_INT_FLOAT
  6961. #undef WAVE_OP_CASE_INT
  6962. #undef WAVE_OP_CASE_SINT_UINT_FLOAT
  6963. emitError("translating wave operator '%0' unimplemented", srcLoc)
  6964. << static_cast<uint32_t>(op);
  6965. return spv::Op::OpNop;
  6966. }
  6967. SpirvInstruction *
  6968. SpirvEmitter::processWaveCountBits(const CallExpr *callExpr,
  6969. spv::GroupOperation groupOp) {
  6970. // Signatures:
  6971. // uint WaveActiveCountBits(bool bBit)
  6972. // uint WavePrefixCountBits(Bool bBit)
  6973. assert(callExpr->getNumArgs() == 1);
  6974. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6975. callExpr->getExprLoc());
  6976. auto *predicate = doExpr(callExpr->getArg(0));
  6977. const auto srcLoc = callExpr->getExprLoc();
  6978. const QualType u32Type = astContext.UnsignedIntTy;
  6979. const QualType v4u32Type = astContext.getExtVectorType(u32Type, 4);
  6980. const QualType retType = callExpr->getCallReturnType(astContext);
  6981. auto *ballot = spvBuilder.createGroupNonUniformUnaryOp(
  6982. srcLoc, spv::Op::OpGroupNonUniformBallot, v4u32Type, spv::Scope::Subgroup,
  6983. predicate);
  6984. return spvBuilder.createGroupNonUniformUnaryOp(
  6985. srcLoc, spv::Op::OpGroupNonUniformBallotBitCount, retType,
  6986. spv::Scope::Subgroup, ballot,
  6987. llvm::Optional<spv::GroupOperation>(groupOp));
  6988. }
  6989. SpirvInstruction *SpirvEmitter::processWaveReductionOrPrefix(
  6990. const CallExpr *callExpr, spv::Op opcode, spv::GroupOperation groupOp) {
  6991. // Signatures:
  6992. // bool WaveActiveAllEqual( <type> expr )
  6993. // <type> WaveActiveSum( <type> expr )
  6994. // <type> WaveActiveProduct( <type> expr )
  6995. // <int_type> WaveActiveBitAnd( <int_type> expr )
  6996. // <int_type> WaveActiveBitOr( <int_type> expr )
  6997. // <int_type> WaveActiveBitXor( <int_type> expr )
  6998. // <type> WaveActiveMin( <type> expr)
  6999. // <type> WaveActiveMax( <type> expr)
  7000. //
  7001. // <type> WavePrefixProduct(<type> value)
  7002. // <type> WavePrefixSum(<type> value)
  7003. assert(callExpr->getNumArgs() == 1);
  7004. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7005. callExpr->getExprLoc());
  7006. auto *predicate = doExpr(callExpr->getArg(0));
  7007. const QualType retType = callExpr->getCallReturnType(astContext);
  7008. return spvBuilder.createGroupNonUniformUnaryOp(
  7009. callExpr->getExprLoc(), opcode, retType, spv::Scope::Subgroup, predicate,
  7010. llvm::Optional<spv::GroupOperation>(groupOp));
  7011. }
  7012. SpirvInstruction *SpirvEmitter::processWaveBroadcast(const CallExpr *callExpr) {
  7013. // Signatures:
  7014. // <type> WaveReadLaneFirst(<type> expr)
  7015. // <type> WaveReadLaneAt(<type> expr, uint laneIndex)
  7016. const auto numArgs = callExpr->getNumArgs();
  7017. const auto srcLoc = callExpr->getExprLoc();
  7018. assert(numArgs == 1 || numArgs == 2);
  7019. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7020. callExpr->getExprLoc());
  7021. auto *value = doExpr(callExpr->getArg(0));
  7022. const QualType retType = callExpr->getCallReturnType(astContext);
  7023. if (numArgs == 2)
  7024. return spvBuilder.createGroupNonUniformBinaryOp(
  7025. spv::Op::OpGroupNonUniformBroadcast, retType, spv::Scope::Subgroup,
  7026. value, doExpr(callExpr->getArg(1)), srcLoc);
  7027. else
  7028. return spvBuilder.createGroupNonUniformUnaryOp(
  7029. srcLoc, spv::Op::OpGroupNonUniformBroadcastFirst, retType,
  7030. spv::Scope::Subgroup, value);
  7031. }
  7032. SpirvInstruction *
  7033. SpirvEmitter::processWaveQuadWideShuffle(const CallExpr *callExpr,
  7034. hlsl::IntrinsicOp op) {
  7035. // Signatures:
  7036. // <type> QuadReadAcrossX(<type> localValue)
  7037. // <type> QuadReadAcrossY(<type> localValue)
  7038. // <type> QuadReadAcrossDiagonal(<type> localValue)
  7039. // <type> QuadReadLaneAt(<type> sourceValue, uint quadLaneID)
  7040. assert(callExpr->getNumArgs() == 1 || callExpr->getNumArgs() == 2);
  7041. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  7042. callExpr->getExprLoc());
  7043. auto *value = doExpr(callExpr->getArg(0));
  7044. const auto srcLoc = callExpr->getExprLoc();
  7045. const QualType retType = callExpr->getCallReturnType(astContext);
  7046. SpirvInstruction *target = nullptr;
  7047. spv::Op opcode = spv::Op::OpGroupNonUniformQuadSwap;
  7048. switch (op) {
  7049. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  7050. target =
  7051. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  7052. break;
  7053. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  7054. target =
  7055. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 1));
  7056. break;
  7057. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  7058. target =
  7059. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 2));
  7060. break;
  7061. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  7062. target = doExpr(callExpr->getArg(1));
  7063. opcode = spv::Op::OpGroupNonUniformQuadBroadcast;
  7064. break;
  7065. default:
  7066. llvm_unreachable("case should not appear here");
  7067. }
  7068. return spvBuilder.createGroupNonUniformBinaryOp(
  7069. opcode, retType, spv::Scope::Subgroup, value, target, srcLoc);
  7070. }
  7071. SpirvInstruction *SpirvEmitter::processIntrinsicModf(const CallExpr *callExpr) {
  7072. // Signature is: ret modf(x, ip)
  7073. // [in] x: the input floating-point value.
  7074. // [out] ip: the integer portion of x.
  7075. // [out] ret: the fractional portion of x.
  7076. // All of the above must be a scalar, vector, or matrix with the same
  7077. // component types. Component types can be float or int.
  7078. // The ModfStruct SPIR-V instruction returns a struct. The first member is the
  7079. // fractional part and the second member is the integer portion.
  7080. // ModfStruct {
  7081. // <scalar or vector of float> frac;
  7082. // <scalar or vector of float> ip;
  7083. // }
  7084. // Note if the input number (x) is not a float (i.e. 'x' is an int), it is
  7085. // automatically converted to float before modf is invoked. Sadly, the 'ip'
  7086. // argument is not treated the same way. Therefore, in such cases we'll have
  7087. // to manually convert the float result into int.
  7088. const Expr *arg = callExpr->getArg(0);
  7089. const Expr *ipArg = callExpr->getArg(1);
  7090. const auto loc = callExpr->getLocStart();
  7091. const auto argType = arg->getType();
  7092. const auto ipType = ipArg->getType();
  7093. const auto returnType = callExpr->getType();
  7094. auto *argInstr = doExpr(arg);
  7095. // For scalar and vector argument types.
  7096. {
  7097. if (isScalarType(argType) || isVectorType(argType)) {
  7098. // The struct members *must* have the same type.
  7099. const auto modfStructType = spvContext.getHybridStructType(
  7100. {HybridStructType::FieldInfo(argType, "frac"),
  7101. HybridStructType::FieldInfo(argType, "ip")},
  7102. "ModfStructType");
  7103. auto *modf = spvBuilder.createGLSLExtInst(
  7104. modfStructType, GLSLstd450::GLSLstd450ModfStruct, {argInstr}, loc);
  7105. SpirvInstruction *ip =
  7106. spvBuilder.createCompositeExtract(argType, modf, {1}, loc);
  7107. // This will do nothing if the input number (x) and the ip are both of the
  7108. // same type. Otherwise, it will convert the ip into int as necessary.
  7109. ip = castToInt(ip, argType, ipType, ipArg->getLocStart());
  7110. processAssignment(ipArg, ip, false, nullptr);
  7111. return spvBuilder.createCompositeExtract(argType, modf, {0}, loc);
  7112. }
  7113. }
  7114. // For matrix argument types.
  7115. {
  7116. uint32_t rowCount = 0, colCount = 0;
  7117. QualType elemType = {};
  7118. if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7119. const auto colType = astContext.getExtVectorType(elemType, colCount);
  7120. const auto modfStructType = spvContext.getHybridStructType(
  7121. {HybridStructType::FieldInfo(colType, "frac"),
  7122. HybridStructType::FieldInfo(colType, "ip")},
  7123. "ModfStructType");
  7124. llvm::SmallVector<SpirvInstruction *, 4> fracs;
  7125. llvm::SmallVector<SpirvInstruction *, 4> ips;
  7126. for (uint32_t i = 0; i < rowCount; ++i) {
  7127. auto *curRow =
  7128. spvBuilder.createCompositeExtract(colType, argInstr, {i}, loc);
  7129. auto *modf = spvBuilder.createGLSLExtInst(
  7130. modfStructType, GLSLstd450::GLSLstd450ModfStruct, {curRow}, loc);
  7131. ips.push_back(
  7132. spvBuilder.createCompositeExtract(colType, modf, {1}, loc));
  7133. fracs.push_back(
  7134. spvBuilder.createCompositeExtract(colType, modf, {0}, loc));
  7135. }
  7136. SpirvInstruction *ip =
  7137. spvBuilder.createCompositeConstruct(argType, ips, loc);
  7138. // If the 'ip' is not a float type, the AST will not contain a CastExpr
  7139. // because this is internal to the intrinsic function. So, in such a
  7140. // case we need to cast manually.
  7141. if (!hlsl::GetHLSLMatElementType(ipType)->isFloatingType())
  7142. ip = castToInt(ip, argType, ipType, ipArg->getLocStart());
  7143. processAssignment(ipArg, ip, false, nullptr);
  7144. return spvBuilder.createCompositeConstruct(returnType, fracs, loc);
  7145. }
  7146. }
  7147. emitError("invalid argument type passed to Modf intrinsic function",
  7148. callExpr->getExprLoc());
  7149. return nullptr;
  7150. }
  7151. SpirvInstruction *SpirvEmitter::processIntrinsicMad(const CallExpr *callExpr) {
  7152. // Signature is: ret mad(a,b,c)
  7153. // All of the above must be a scalar, vector, or matrix with the same
  7154. // component types. Component types can be float or int.
  7155. // The return value is equal to "a * b + c"
  7156. // In the case of float arguments, we can use the GLSL extended instruction
  7157. // set's Fma instruction with NoContraction decoration. In the case of integer
  7158. // arguments, we'll have to manually perform an OpIMul followed by an OpIAdd
  7159. // (We should also apply NoContraction decoration to these two instructions to
  7160. // get precise arithmetic).
  7161. // TODO: We currently don't propagate the NoContraction decoration.
  7162. const auto loc = callExpr->getLocStart();
  7163. const Expr *arg0 = callExpr->getArg(0);
  7164. const Expr *arg1 = callExpr->getArg(1);
  7165. const Expr *arg2 = callExpr->getArg(2);
  7166. // All arguments and the return type are the same.
  7167. const auto argType = arg0->getType();
  7168. auto *arg0Instr = doExpr(arg0);
  7169. auto *arg1Instr = doExpr(arg1);
  7170. auto *arg2Instr = doExpr(arg2);
  7171. auto arg0Loc = arg0->getLocStart();
  7172. auto arg1Loc = arg1->getLocStart();
  7173. auto arg2Loc = arg2->getLocStart();
  7174. // For floating point arguments, we can use the extended instruction set's Fma
  7175. // instruction. Sadly we can't simply call processIntrinsicUsingGLSLInst
  7176. // because we need to specifically decorate the Fma instruction with
  7177. // NoContraction decoration.
  7178. if (isFloatOrVecMatOfFloatType(argType)) {
  7179. // For matrix cases, operate on each row of the matrix.
  7180. if (isMxNMatrix(arg0->getType())) {
  7181. const auto actOnEachVec = [this, loc, arg1Instr, arg2Instr, arg1Loc,
  7182. arg2Loc](uint32_t index, QualType vecType,
  7183. SpirvInstruction *arg0Row) {
  7184. auto *arg1Row = spvBuilder.createCompositeExtract(vecType, arg1Instr,
  7185. {index}, arg1Loc);
  7186. auto *arg2Row = spvBuilder.createCompositeExtract(vecType, arg2Instr,
  7187. {index}, arg2Loc);
  7188. auto *fma = spvBuilder.createGLSLExtInst(
  7189. vecType, GLSLstd450Fma, {arg0Row, arg1Row, arg2Row}, loc);
  7190. spvBuilder.decorateNoContraction(fma, loc);
  7191. return fma;
  7192. };
  7193. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  7194. }
  7195. // Non-matrix cases
  7196. auto *fma = spvBuilder.createGLSLExtInst(
  7197. argType, GLSLstd450Fma, {arg0Instr, arg1Instr, arg2Instr}, loc);
  7198. spvBuilder.decorateNoContraction(fma, loc);
  7199. return fma;
  7200. }
  7201. // For scalar and vector argument types.
  7202. {
  7203. if (isScalarType(argType) || isVectorType(argType)) {
  7204. auto *mul = spvBuilder.createBinaryOp(spv::Op::OpIMul, argType, arg0Instr,
  7205. arg1Instr, loc);
  7206. auto *add = spvBuilder.createBinaryOp(spv::Op::OpIAdd, argType, mul,
  7207. arg2Instr, loc);
  7208. spvBuilder.decorateNoContraction(mul, loc);
  7209. spvBuilder.decorateNoContraction(add, loc);
  7210. return add;
  7211. }
  7212. }
  7213. // For matrix argument types.
  7214. {
  7215. uint32_t rowCount = 0, colCount = 0;
  7216. QualType elemType = {};
  7217. if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7218. const auto colType = astContext.getExtVectorType(elemType, colCount);
  7219. llvm::SmallVector<SpirvInstruction *, 4> resultRows;
  7220. for (uint32_t i = 0; i < rowCount; ++i) {
  7221. auto *rowArg0 =
  7222. spvBuilder.createCompositeExtract(colType, arg0Instr, {i}, arg0Loc);
  7223. auto *rowArg1 =
  7224. spvBuilder.createCompositeExtract(colType, arg1Instr, {i}, arg1Loc);
  7225. auto *rowArg2 =
  7226. spvBuilder.createCompositeExtract(colType, arg2Instr, {i}, arg2Loc);
  7227. auto *mul = spvBuilder.createBinaryOp(spv::Op::OpIMul, colType, rowArg0,
  7228. rowArg1, loc);
  7229. auto *add = spvBuilder.createBinaryOp(spv::Op::OpIAdd, colType, mul,
  7230. rowArg2, loc);
  7231. spvBuilder.decorateNoContraction(mul, loc);
  7232. spvBuilder.decorateNoContraction(add, loc);
  7233. resultRows.push_back(add);
  7234. }
  7235. return spvBuilder.createCompositeConstruct(argType, resultRows, loc);
  7236. }
  7237. }
  7238. emitError("invalid argument type passed to mad intrinsic function",
  7239. callExpr->getExprLoc());
  7240. return 0;
  7241. }
  7242. SpirvInstruction *SpirvEmitter::processIntrinsicLit(const CallExpr *callExpr) {
  7243. // Signature is: float4 lit(float n_dot_l, float n_dot_h, float m)
  7244. //
  7245. // This function returns a lighting coefficient vector
  7246. // (ambient, diffuse, specular, 1) where:
  7247. // ambient = 1.
  7248. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l
  7249. // specular = (n_dot_l < 0 || n_dot_h < 0) ? 0 : ((n_dot_h) * m)
  7250. auto *nDotL = doExpr(callExpr->getArg(0));
  7251. auto *nDotH = doExpr(callExpr->getArg(1));
  7252. auto *m = doExpr(callExpr->getArg(2));
  7253. const auto loc = callExpr->getExprLoc();
  7254. const QualType floatType = astContext.FloatTy;
  7255. const QualType boolType = astContext.BoolTy;
  7256. SpirvInstruction *floatZero =
  7257. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.0f));
  7258. SpirvInstruction *floatOne =
  7259. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(1.0f));
  7260. const QualType retType = callExpr->getType();
  7261. auto *diffuse = spvBuilder.createGLSLExtInst(
  7262. floatType, GLSLstd450::GLSLstd450FMax, {floatZero, nDotL}, loc);
  7263. auto *min = spvBuilder.createGLSLExtInst(
  7264. floatType, GLSLstd450::GLSLstd450FMin, {nDotL, nDotH}, loc);
  7265. auto *isNeg = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  7266. min, floatZero, loc);
  7267. auto *mul =
  7268. spvBuilder.createBinaryOp(spv::Op::OpFMul, floatType, nDotH, m, loc);
  7269. auto *specular =
  7270. spvBuilder.createSelect(floatType, isNeg, floatZero, mul, loc);
  7271. return spvBuilder.createCompositeConstruct(
  7272. retType, {floatOne, diffuse, specular, floatOne}, callExpr->getLocEnd());
  7273. }
  7274. SpirvInstruction *
  7275. SpirvEmitter::processIntrinsicFrexp(const CallExpr *callExpr) {
  7276. // Signature is: ret frexp(x, exp)
  7277. // [in] x: the input floating-point value.
  7278. // [out] exp: the calculated exponent.
  7279. // [out] ret: the calculated mantissa.
  7280. // All of the above must be a scalar, vector, or matrix of *float* type.
  7281. // The FrexpStruct SPIR-V instruction returns a struct. The first
  7282. // member is the significand (mantissa) and must be of the same type as the
  7283. // input parameter, and the second member is the exponent and must always be a
  7284. // scalar or vector of 32-bit *integer* type.
  7285. // FrexpStruct {
  7286. // <scalar or vector of int/float> mantissa;
  7287. // <scalar or vector of integers> exponent;
  7288. // }
  7289. const Expr *arg = callExpr->getArg(0);
  7290. const auto argType = arg->getType();
  7291. const auto returnType = callExpr->getType();
  7292. const auto loc = callExpr->getExprLoc();
  7293. auto *argInstr = doExpr(arg);
  7294. auto *expInstr = doExpr(callExpr->getArg(1));
  7295. // For scalar and vector argument types.
  7296. {
  7297. uint32_t elemCount = 1;
  7298. if (isScalarType(argType) || isVectorType(argType, nullptr, &elemCount)) {
  7299. const QualType expType =
  7300. elemCount == 1
  7301. ? astContext.IntTy
  7302. : astContext.getExtVectorType(astContext.IntTy, elemCount);
  7303. const auto *frexpStructType = spvContext.getHybridStructType(
  7304. {HybridStructType::FieldInfo(argType, "mantissa"),
  7305. HybridStructType::FieldInfo(expType, "exponent")},
  7306. "FrexpStructType");
  7307. auto *frexp = spvBuilder.createGLSLExtInst(
  7308. frexpStructType, GLSLstd450::GLSLstd450FrexpStruct, {argInstr}, loc);
  7309. auto *exponentInt =
  7310. spvBuilder.createCompositeExtract(expType, frexp, {1}, loc);
  7311. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  7312. // expects a float, an conversion must take place before writing the
  7313. // results.
  7314. auto *exponentFloat = spvBuilder.createUnaryOp(
  7315. spv::Op::OpConvertSToF, returnType, exponentInt, loc);
  7316. spvBuilder.createStore(expInstr, exponentFloat, loc);
  7317. return spvBuilder.createCompositeExtract(argType, frexp, {0}, loc);
  7318. }
  7319. }
  7320. // For matrix argument types.
  7321. {
  7322. uint32_t rowCount = 0, colCount = 0;
  7323. if (isMxNMatrix(argType, nullptr, &rowCount, &colCount)) {
  7324. const auto expType =
  7325. astContext.getExtVectorType(astContext.IntTy, colCount);
  7326. const auto colType =
  7327. astContext.getExtVectorType(astContext.FloatTy, colCount);
  7328. const auto *frexpStructType = spvContext.getHybridStructType(
  7329. {HybridStructType::FieldInfo(colType, "mantissa"),
  7330. HybridStructType::FieldInfo(expType, "exponent")},
  7331. "FrexpStructType");
  7332. llvm::SmallVector<SpirvInstruction *, 4> exponents;
  7333. llvm::SmallVector<SpirvInstruction *, 4> mantissas;
  7334. for (uint32_t i = 0; i < rowCount; ++i) {
  7335. auto *curRow = spvBuilder.createCompositeExtract(colType, argInstr, {i},
  7336. arg->getLocStart());
  7337. auto *frexp = spvBuilder.createGLSLExtInst(
  7338. frexpStructType, GLSLstd450::GLSLstd450FrexpStruct, {curRow}, loc);
  7339. auto *exponentInt =
  7340. spvBuilder.createCompositeExtract(expType, frexp, {1}, loc);
  7341. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  7342. // expects a float, an conversion must take place before writing the
  7343. // results.
  7344. auto *exponentFloat = spvBuilder.createUnaryOp(
  7345. spv::Op::OpConvertSToF, colType, exponentInt, loc);
  7346. exponents.push_back(exponentFloat);
  7347. mantissas.push_back(
  7348. spvBuilder.createCompositeExtract(colType, frexp, {0}, loc));
  7349. }
  7350. auto *exponentsResult =
  7351. spvBuilder.createCompositeConstruct(returnType, exponents, loc);
  7352. spvBuilder.createStore(expInstr, exponentsResult, loc);
  7353. return spvBuilder.createCompositeConstruct(returnType, mantissas,
  7354. callExpr->getLocEnd());
  7355. }
  7356. }
  7357. emitError("invalid argument type passed to Frexp intrinsic function",
  7358. callExpr->getExprLoc());
  7359. return nullptr;
  7360. }
  7361. SpirvInstruction *
  7362. SpirvEmitter::processIntrinsicLdexp(const CallExpr *callExpr) {
  7363. // Signature: ret ldexp(x, exp)
  7364. // This function uses the following formula: x * 2^exp.
  7365. // Note that we cannot use GLSL extended instruction Ldexp since it requires
  7366. // the exponent to be an integer (vector) but HLSL takes an float (vector)
  7367. // exponent. So we must calculate the result manually.
  7368. const Expr *x = callExpr->getArg(0);
  7369. const auto paramType = x->getType();
  7370. auto *xInstr = doExpr(x);
  7371. auto *expInstr = doExpr(callExpr->getArg(1));
  7372. const auto loc = callExpr->getLocStart();
  7373. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  7374. // For scalar and vector argument types.
  7375. if (isScalarType(paramType) || isVectorType(paramType)) {
  7376. const auto twoExp = spvBuilder.createGLSLExtInst(
  7377. paramType, GLSLstd450::GLSLstd450Exp2, {expInstr}, loc);
  7378. return spvBuilder.createBinaryOp(spv::Op::OpFMul, paramType, xInstr, twoExp,
  7379. loc);
  7380. }
  7381. // For matrix argument types.
  7382. {
  7383. uint32_t rowCount = 0, colCount = 0;
  7384. if (isMxNMatrix(paramType, nullptr, &rowCount, &colCount)) {
  7385. const auto actOnEachVec = [this, loc, expInstr,
  7386. arg1Loc](uint32_t index, QualType vecType,
  7387. SpirvInstruction *xRowInstr) {
  7388. auto *expRowInstr = spvBuilder.createCompositeExtract(vecType, expInstr,
  7389. {index}, arg1Loc);
  7390. auto *twoExp = spvBuilder.createGLSLExtInst(
  7391. vecType, GLSLstd450::GLSLstd450Exp2, {expRowInstr}, loc);
  7392. return spvBuilder.createBinaryOp(spv::Op::OpFMul, vecType, xRowInstr,
  7393. twoExp, loc);
  7394. };
  7395. return processEachVectorInMatrix(x, xInstr, actOnEachVec, loc);
  7396. }
  7397. }
  7398. emitError("invalid argument type passed to ldexp intrinsic function",
  7399. callExpr->getExprLoc());
  7400. return nullptr;
  7401. }
  7402. SpirvInstruction *SpirvEmitter::processIntrinsicDst(const CallExpr *callExpr) {
  7403. // Signature is float4 dst(float4 src0, float4 src1)
  7404. // result.x = 1;
  7405. // result.y = src0.y * src1.y;
  7406. // result.z = src0.z;
  7407. // result.w = src1.w;
  7408. const QualType f32 = astContext.FloatTy;
  7409. auto *arg0Id = doExpr(callExpr->getArg(0));
  7410. auto *arg1Id = doExpr(callExpr->getArg(1));
  7411. auto arg0Loc = callExpr->getArg(0)->getLocStart();
  7412. auto arg1Loc = callExpr->getArg(1)->getLocStart();
  7413. auto *arg0y = spvBuilder.createCompositeExtract(f32, arg0Id, {1}, arg0Loc);
  7414. auto *arg1y = spvBuilder.createCompositeExtract(f32, arg1Id, {1}, arg1Loc);
  7415. auto *arg0z = spvBuilder.createCompositeExtract(f32, arg0Id, {2}, arg0Loc);
  7416. auto *arg1w = spvBuilder.createCompositeExtract(f32, arg1Id, {3}, arg1Loc);
  7417. auto loc = callExpr->getLocEnd();
  7418. auto *arg0yMularg1y =
  7419. spvBuilder.createBinaryOp(spv::Op::OpFMul, f32, arg0y, arg1y, loc);
  7420. return spvBuilder.createCompositeConstruct(
  7421. callExpr->getType(),
  7422. {spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(1.0f)),
  7423. arg0yMularg1y, arg0z, arg1w},
  7424. loc);
  7425. }
  7426. SpirvInstruction *SpirvEmitter::processIntrinsicClip(const CallExpr *callExpr) {
  7427. // Discards the current pixel if the specified value is less than zero.
  7428. // TODO: If the argument can be const folded and evaluated, we could
  7429. // potentially avoid creating a branch. This would be a bit challenging for
  7430. // matrix/vector arguments.
  7431. assert(callExpr->getNumArgs() == 1u);
  7432. const Expr *arg = callExpr->getArg(0);
  7433. const auto loc = callExpr->getExprLoc();
  7434. const auto argType = arg->getType();
  7435. const auto boolType = astContext.BoolTy;
  7436. SpirvInstruction *condition = nullptr;
  7437. // Could not determine the argument as a constant. We need to branch based on
  7438. // the argument. If the argument is a vector/matrix, clipping is done if *any*
  7439. // element of the vector/matrix is less than zero.
  7440. auto *argInstr = doExpr(arg);
  7441. QualType elemType = {};
  7442. uint32_t elemCount = 0, rowCount = 0, colCount = 0;
  7443. if (isScalarType(argType)) {
  7444. auto *zero = getValueZero(argType);
  7445. condition = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  7446. argInstr, zero, loc);
  7447. } else if (isVectorType(argType, nullptr, &elemCount)) {
  7448. auto *zero = getValueZero(argType);
  7449. const QualType boolVecType =
  7450. astContext.getExtVectorType(boolType, elemCount);
  7451. auto *cmp = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolVecType,
  7452. argInstr, zero, loc);
  7453. condition = spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp, loc);
  7454. } else if (isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  7455. const auto floatVecType = astContext.getExtVectorType(elemType, colCount);
  7456. auto *elemZero = getValueZero(elemType);
  7457. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(colCount), elemZero);
  7458. auto *zero = spvBuilder.getConstantComposite(floatVecType, elements);
  7459. llvm::SmallVector<SpirvInstruction *, 4> cmpResults;
  7460. for (uint32_t i = 0; i < rowCount; ++i) {
  7461. auto *lhsVec =
  7462. spvBuilder.createCompositeExtract(floatVecType, argInstr, {i}, loc);
  7463. const auto boolColType = astContext.getExtVectorType(boolType, colCount);
  7464. auto *cmp = spvBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  7465. boolColType, lhsVec, zero, loc);
  7466. auto *any = spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp, loc);
  7467. cmpResults.push_back(any);
  7468. }
  7469. const auto boolRowType = astContext.getExtVectorType(boolType, rowCount);
  7470. auto *results =
  7471. spvBuilder.createCompositeConstruct(boolRowType, cmpResults, loc);
  7472. condition =
  7473. spvBuilder.createUnaryOp(spv::Op::OpAny, boolType, results, loc);
  7474. } else {
  7475. emitError("invalid argument type passed to clip intrinsic function", loc);
  7476. return nullptr;
  7477. }
  7478. // Then we need to emit the instruction for the conditional branch.
  7479. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  7480. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  7481. // Create the branch instruction. This will end the current basic block.
  7482. spvBuilder.createConditionalBranch(condition, thenBB, mergeBB, loc, mergeBB);
  7483. spvBuilder.addSuccessor(thenBB);
  7484. spvBuilder.addSuccessor(mergeBB);
  7485. spvBuilder.setMergeTarget(mergeBB);
  7486. // Handle the then branch
  7487. spvBuilder.setInsertPoint(thenBB);
  7488. spvBuilder.createKill(loc);
  7489. spvBuilder.addSuccessor(mergeBB);
  7490. // From now on, we'll emit instructions into the merge block.
  7491. spvBuilder.setInsertPoint(mergeBB);
  7492. return nullptr;
  7493. }
  7494. SpirvInstruction *
  7495. SpirvEmitter::processIntrinsicClamp(const CallExpr *callExpr) {
  7496. // According the HLSL reference: clamp(X, Min, Max) takes 3 arguments. Each
  7497. // one may be int, uint, or float.
  7498. const QualType returnType = callExpr->getType();
  7499. GLSLstd450 glslOpcode = GLSLstd450::GLSLstd450UClamp;
  7500. if (isFloatOrVecMatOfFloatType(returnType))
  7501. glslOpcode = GLSLstd450::GLSLstd450FClamp;
  7502. else if (isSintOrVecMatOfSintType(returnType))
  7503. glslOpcode = GLSLstd450::GLSLstd450SClamp;
  7504. // Get the function parameters. Expect 3 parameters.
  7505. assert(callExpr->getNumArgs() == 3u);
  7506. const Expr *argX = callExpr->getArg(0);
  7507. const Expr *argMin = callExpr->getArg(1);
  7508. const Expr *argMax = callExpr->getArg(2);
  7509. const auto loc = callExpr->getExprLoc();
  7510. auto *argXInstr = doExpr(argX);
  7511. auto *argMinInstr = doExpr(argMin);
  7512. auto *argMaxInstr = doExpr(argMax);
  7513. const auto argMinLoc = argMin->getLocStart();
  7514. const auto argMaxLoc = argMax->getLocStart();
  7515. // FClamp, UClamp, and SClamp do not operate on matrices, so we should perform
  7516. // the operation on each vector of the matrix.
  7517. if (isMxNMatrix(argX->getType())) {
  7518. const auto actOnEachVec =
  7519. [this, loc, glslOpcode, argMinInstr, argMaxInstr, argMinLoc, argMaxLoc](
  7520. uint32_t index, QualType vecType, SpirvInstruction *curRow) {
  7521. auto *minRowInstr = spvBuilder.createCompositeExtract(
  7522. vecType, argMinInstr, {index}, argMinLoc);
  7523. auto *maxRowInstr = spvBuilder.createCompositeExtract(
  7524. vecType, argMaxInstr, {index}, argMaxLoc);
  7525. return spvBuilder.createGLSLExtInst(
  7526. vecType, glslOpcode, {curRow, minRowInstr, maxRowInstr}, loc);
  7527. };
  7528. return processEachVectorInMatrix(argX, argXInstr, actOnEachVec, loc);
  7529. }
  7530. return spvBuilder.createGLSLExtInst(
  7531. returnType, glslOpcode, {argXInstr, argMinInstr, argMaxInstr}, loc);
  7532. }
  7533. SpirvInstruction *
  7534. SpirvEmitter::processIntrinsicMemoryBarrier(const CallExpr *callExpr,
  7535. bool isDevice, bool groupSync,
  7536. bool isAllBarrier) {
  7537. // * DeviceMemoryBarrier =
  7538. // OpMemoryBarrier (memScope=Device,
  7539. // sem=Image|Uniform|AcquireRelease)
  7540. //
  7541. // * DeviceMemoryBarrierWithGroupSync =
  7542. // OpControlBarrier(execScope = Workgroup,
  7543. // memScope=Device,
  7544. // sem=Image|Uniform|AcquireRelease)
  7545. const spv::MemorySemanticsMask deviceMemoryBarrierSema =
  7546. spv::MemorySemanticsMask::ImageMemory |
  7547. spv::MemorySemanticsMask::UniformMemory |
  7548. spv::MemorySemanticsMask::AcquireRelease;
  7549. // * GroupMemoryBarrier =
  7550. // OpMemoryBarrier (memScope=Workgroup,
  7551. // sem = Workgroup|AcquireRelease)
  7552. //
  7553. // * GroupMemoryBarrierWithGroupSync =
  7554. // OpControlBarrier (execScope = Workgroup,
  7555. // memScope = Workgroup,
  7556. // sem = Workgroup|AcquireRelease)
  7557. const spv::MemorySemanticsMask groupMemoryBarrierSema =
  7558. spv::MemorySemanticsMask::WorkgroupMemory |
  7559. spv::MemorySemanticsMask::AcquireRelease;
  7560. // * AllMemoryBarrier =
  7561. // OpMemoryBarrier(memScope = Device,
  7562. // sem = Image|Uniform|Workgroup|AcquireRelease)
  7563. //
  7564. // * AllMemoryBarrierWithGroupSync =
  7565. // OpControlBarrier(execScope = Workgroup,
  7566. // memScope = Device,
  7567. // sem = Image|Uniform|Workgroup|AcquireRelease)
  7568. const spv::MemorySemanticsMask allMemoryBarrierSema =
  7569. spv::MemorySemanticsMask::ImageMemory |
  7570. spv::MemorySemanticsMask::UniformMemory |
  7571. spv::MemorySemanticsMask::WorkgroupMemory |
  7572. spv::MemorySemanticsMask::AcquireRelease;
  7573. // Get <result-id> for execution scope.
  7574. // If present, execution scope is always Workgroup!
  7575. llvm::Optional<spv::Scope> execScope = llvm::None;
  7576. if (groupSync) {
  7577. execScope = spv::Scope::Workgroup;
  7578. }
  7579. // Get <result-id> for memory scope
  7580. const spv::Scope memScope =
  7581. (isDevice || isAllBarrier) ? spv::Scope::Device : spv::Scope::Workgroup;
  7582. // Get <result-id> for memory semantics
  7583. const auto memSemaMask = isAllBarrier ? allMemoryBarrierSema
  7584. : isDevice ? deviceMemoryBarrierSema
  7585. : groupMemoryBarrierSema;
  7586. spvBuilder.createBarrier(memScope, memSemaMask, execScope,
  7587. callExpr->getExprLoc());
  7588. return nullptr;
  7589. }
  7590. SpirvInstruction *SpirvEmitter::processNonFpMatrixTranspose(
  7591. QualType matType, SpirvInstruction *matrix, SourceLocation loc) {
  7592. // Simplest way is to flatten the matrix construct a new matrix from the
  7593. // flattened elements. (for a mat4x4).
  7594. QualType elemType = {};
  7595. uint32_t numRows = 0, numCols = 0;
  7596. const bool isMat = isMxNMatrix(matType, &elemType, &numRows, &numCols);
  7597. assert(isMat && !elemType->isFloatingType());
  7598. (void)isMat;
  7599. const auto colQualType = astContext.getExtVectorType(elemType, numRows);
  7600. // You cannot perform a composite construct of an array using a few vectors.
  7601. // The number of constutients passed to OpCompositeConstruct must be equal to
  7602. // the number of array elements.
  7603. llvm::SmallVector<SpirvInstruction *, 4> elems;
  7604. for (uint32_t i = 0; i < numRows; ++i)
  7605. for (uint32_t j = 0; j < numCols; ++j)
  7606. elems.push_back(
  7607. spvBuilder.createCompositeExtract(elemType, matrix, {i, j}, loc));
  7608. llvm::SmallVector<SpirvInstruction *, 4> cols;
  7609. for (uint32_t i = 0; i < numCols; ++i) {
  7610. // The elements in the ith vector of the "transposed" array are at offset i,
  7611. // i + <original-vector-size>, ...
  7612. llvm::SmallVector<SpirvInstruction *, 4> indexes;
  7613. for (uint32_t j = 0; j < numRows; ++j)
  7614. indexes.push_back(elems[i + (j * numCols)]);
  7615. cols.push_back(
  7616. spvBuilder.createCompositeConstruct(colQualType, indexes, loc));
  7617. }
  7618. auto transposeType = astContext.getConstantArrayType(
  7619. colQualType, llvm::APInt(32, numCols), clang::ArrayType::Normal, 0);
  7620. return spvBuilder.createCompositeConstruct(transposeType, cols, loc);
  7621. }
  7622. SpirvInstruction *SpirvEmitter::processNonFpDot(SpirvInstruction *vec1Id,
  7623. SpirvInstruction *vec2Id,
  7624. uint32_t vecSize,
  7625. QualType elemType,
  7626. SourceLocation loc) {
  7627. llvm::SmallVector<SpirvInstruction *, 4> muls;
  7628. for (uint32_t i = 0; i < vecSize; ++i) {
  7629. auto *elem1 = spvBuilder.createCompositeExtract(elemType, vec1Id, {i}, loc);
  7630. auto *elem2 = spvBuilder.createCompositeExtract(elemType, vec2Id, {i}, loc);
  7631. muls.push_back(spvBuilder.createBinaryOp(translateOp(BO_Mul, elemType),
  7632. elemType, elem1, elem2, loc));
  7633. }
  7634. SpirvInstruction *sum = muls[0];
  7635. for (uint32_t i = 1; i < vecSize; ++i) {
  7636. sum = spvBuilder.createBinaryOp(translateOp(BO_Add, elemType), elemType,
  7637. sum, muls[i], loc);
  7638. }
  7639. return sum;
  7640. }
  7641. SpirvInstruction *SpirvEmitter::processNonFpScalarTimesMatrix(
  7642. QualType scalarType, SpirvInstruction *scalar, QualType matrixType,
  7643. SpirvInstruction *matrix, SourceLocation loc) {
  7644. assert(isScalarType(scalarType));
  7645. QualType elemType = {};
  7646. uint32_t numRows = 0, numCols = 0;
  7647. const bool isMat = isMxNMatrix(matrixType, &elemType, &numRows, &numCols);
  7648. assert(isMat);
  7649. assert(isSameType(astContext, scalarType, elemType));
  7650. (void)isMat;
  7651. // We need to multiply the scalar by each vector of the matrix.
  7652. // The front-end guarantees that the scalar and matrix element type are
  7653. // the same. For example, if the scalar is a float, the matrix is casted
  7654. // to a float matrix before being passed to mul(). It is also guaranteed
  7655. // that types such as bool are casted to float or int before being
  7656. // passed to mul().
  7657. const auto rowType = astContext.getExtVectorType(elemType, numCols);
  7658. llvm::SmallVector<SpirvInstruction *, 4> splat(size_t(numCols), scalar);
  7659. auto *scalarSplat = spvBuilder.createCompositeConstruct(rowType, splat, loc);
  7660. llvm::SmallVector<SpirvInstruction *, 4> mulRows;
  7661. for (uint32_t row = 0; row < numRows; ++row) {
  7662. auto *rowInstr =
  7663. spvBuilder.createCompositeExtract(rowType, matrix, {row}, loc);
  7664. mulRows.push_back(spvBuilder.createBinaryOp(
  7665. translateOp(BO_Mul, scalarType), rowType, rowInstr, scalarSplat, loc));
  7666. }
  7667. return spvBuilder.createCompositeConstruct(matrixType, mulRows, loc);
  7668. }
  7669. SpirvInstruction *SpirvEmitter::processNonFpVectorTimesMatrix(
  7670. QualType vecType, SpirvInstruction *vector, QualType matType,
  7671. SpirvInstruction *matrix, SourceLocation loc,
  7672. SpirvInstruction *matrixTranspose) {
  7673. // This function assumes that the vector element type and matrix elemet type
  7674. // are the same.
  7675. QualType vecElemType = {}, matElemType = {};
  7676. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  7677. const bool isVec = isVectorType(vecType, &vecElemType, &vecSize);
  7678. const bool isMat = isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  7679. assert(isSameType(astContext, vecElemType, matElemType));
  7680. assert(isVec);
  7681. assert(isMat);
  7682. assert(vecSize == numRows);
  7683. (void)isVec;
  7684. (void)isMat;
  7685. // When processing vector times matrix, the vector is a row vector, and it
  7686. // should be multiplied by the matrix *columns*. The most efficient way to
  7687. // handle this in SPIR-V would be to first transpose the matrix, and then use
  7688. // OpAccessChain.
  7689. if (!matrixTranspose)
  7690. matrixTranspose = processNonFpMatrixTranspose(matType, matrix, loc);
  7691. llvm::SmallVector<SpirvInstruction *, 4> resultElems;
  7692. for (uint32_t col = 0; col < numCols; ++col) {
  7693. auto *colInstr =
  7694. spvBuilder.createCompositeExtract(vecType, matrixTranspose, {col}, loc);
  7695. resultElems.push_back(
  7696. processNonFpDot(vector, colInstr, vecSize, vecElemType, loc));
  7697. }
  7698. return spvBuilder.createCompositeConstruct(
  7699. astContext.getExtVectorType(vecElemType, numCols), resultElems, loc);
  7700. }
  7701. SpirvInstruction *SpirvEmitter::processNonFpMatrixTimesVector(
  7702. QualType matType, SpirvInstruction *matrix, QualType vecType,
  7703. SpirvInstruction *vector, SourceLocation loc) {
  7704. // This function assumes that the vector element type and matrix elemet type
  7705. // are the same.
  7706. QualType vecElemType = {}, matElemType = {};
  7707. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  7708. const bool isVec = isVectorType(vecType, &vecElemType, &vecSize);
  7709. const bool isMat = isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  7710. assert(isSameType(astContext, vecElemType, matElemType));
  7711. assert(isVec);
  7712. assert(isMat);
  7713. assert(vecSize == numCols);
  7714. (void)isVec;
  7715. (void)isMat;
  7716. // When processing matrix times vector, the vector is a column vector. So we
  7717. // simply get each row of the matrix and perform a dot product with the
  7718. // vector.
  7719. llvm::SmallVector<SpirvInstruction *, 4> resultElems;
  7720. for (uint32_t row = 0; row < numRows; ++row) {
  7721. auto *rowInstr =
  7722. spvBuilder.createCompositeExtract(vecType, matrix, {row}, loc);
  7723. resultElems.push_back(
  7724. processNonFpDot(rowInstr, vector, vecSize, vecElemType, loc));
  7725. }
  7726. return spvBuilder.createCompositeConstruct(
  7727. astContext.getExtVectorType(vecElemType, numRows), resultElems, loc);
  7728. }
  7729. SpirvInstruction *SpirvEmitter::processNonFpMatrixTimesMatrix(
  7730. QualType lhsType, SpirvInstruction *lhs, QualType rhsType,
  7731. SpirvInstruction *rhs, SourceLocation loc) {
  7732. // This function assumes that the vector element type and matrix elemet type
  7733. // are the same.
  7734. QualType lhsElemType = {}, rhsElemType = {};
  7735. uint32_t lhsNumRows = 0, lhsNumCols = 0;
  7736. uint32_t rhsNumRows = 0, rhsNumCols = 0;
  7737. const bool lhsIsMat =
  7738. isMxNMatrix(lhsType, &lhsElemType, &lhsNumRows, &lhsNumCols);
  7739. const bool rhsIsMat =
  7740. isMxNMatrix(rhsType, &rhsElemType, &rhsNumRows, &rhsNumCols);
  7741. assert(isSameType(astContext, lhsElemType, rhsElemType));
  7742. assert(lhsIsMat && rhsIsMat);
  7743. assert(lhsNumCols == rhsNumRows);
  7744. (void)rhsIsMat;
  7745. (void)lhsIsMat;
  7746. auto *rhsTranspose = processNonFpMatrixTranspose(rhsType, rhs, loc);
  7747. const auto vecType = astContext.getExtVectorType(lhsElemType, lhsNumCols);
  7748. llvm::SmallVector<SpirvInstruction *, 4> resultRows;
  7749. for (uint32_t row = 0; row < lhsNumRows; ++row) {
  7750. auto *rowInstr =
  7751. spvBuilder.createCompositeExtract(vecType, lhs, {row}, loc);
  7752. resultRows.push_back(processNonFpVectorTimesMatrix(
  7753. vecType, rowInstr, rhsType, rhs, loc, rhsTranspose));
  7754. }
  7755. // The resulting matrix will have 'lhsNumRows' rows and 'rhsNumCols' columns.
  7756. const auto resultColType =
  7757. astContext.getExtVectorType(lhsElemType, rhsNumCols);
  7758. const auto resultType = astContext.getConstantArrayType(
  7759. resultColType, llvm::APInt(32, lhsNumRows), clang::ArrayType::Normal, 0);
  7760. return spvBuilder.createCompositeConstruct(resultType, resultRows, loc);
  7761. }
  7762. SpirvInstruction *SpirvEmitter::processIntrinsicMul(const CallExpr *callExpr) {
  7763. const QualType returnType = callExpr->getType();
  7764. // Get the function parameters. Expect 2 parameters.
  7765. assert(callExpr->getNumArgs() == 2u);
  7766. const Expr *arg0 = callExpr->getArg(0);
  7767. const Expr *arg1 = callExpr->getArg(1);
  7768. const QualType arg0Type = arg0->getType();
  7769. const QualType arg1Type = arg1->getType();
  7770. auto loc = callExpr->getExprLoc();
  7771. // The HLSL mul() function takes 2 arguments. Each argument may be a scalar,
  7772. // vector, or matrix. The frontend ensures that the two arguments have the
  7773. // same component type. The only allowed component types are int and float.
  7774. // mul(scalar, vector)
  7775. {
  7776. uint32_t elemCount = 0;
  7777. if (isScalarType(arg0Type) && isVectorType(arg1Type, nullptr, &elemCount)) {
  7778. auto *arg1Id = doExpr(arg1);
  7779. // We can use OpVectorTimesScalar if arguments are floats.
  7780. if (arg0Type->isFloatingType())
  7781. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  7782. returnType, arg1Id, doExpr(arg0), loc);
  7783. // Use OpIMul for integers
  7784. return spvBuilder.createBinaryOp(spv::Op::OpIMul, returnType,
  7785. createVectorSplat(arg0, elemCount),
  7786. arg1Id, loc);
  7787. }
  7788. }
  7789. // mul(vector, scalar)
  7790. {
  7791. uint32_t elemCount = 0;
  7792. if (isVectorType(arg0Type, nullptr, &elemCount) && isScalarType(arg1Type)) {
  7793. auto *arg0Id = doExpr(arg0);
  7794. // We can use OpVectorTimesScalar if arguments are floats.
  7795. if (arg1Type->isFloatingType())
  7796. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  7797. returnType, arg0Id, doExpr(arg1), loc);
  7798. // Use OpIMul for integers
  7799. return spvBuilder.createBinaryOp(spv::Op::OpIMul, returnType, arg0Id,
  7800. createVectorSplat(arg1, elemCount), loc);
  7801. }
  7802. }
  7803. // mul(vector, vector)
  7804. if (isVectorType(arg0Type) && isVectorType(arg1Type))
  7805. return processIntrinsicDot(callExpr);
  7806. // All the following cases require handling arg0 and arg1 expressions first.
  7807. auto *arg0Id = doExpr(arg0);
  7808. auto *arg1Id = doExpr(arg1);
  7809. // mul(scalar, scalar)
  7810. if (isScalarType(arg0Type) && isScalarType(arg1Type))
  7811. return spvBuilder.createBinaryOp(translateOp(BO_Mul, arg0Type), returnType,
  7812. arg0Id, arg1Id, loc);
  7813. // mul(scalar, matrix)
  7814. {
  7815. QualType elemType = {};
  7816. if (isScalarType(arg0Type) && isMxNMatrix(arg1Type, &elemType)) {
  7817. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  7818. // and the scalar type are float.
  7819. if (arg0Type->isFloatingType() && elemType->isFloatingType())
  7820. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  7821. returnType, arg1Id, arg0Id, loc);
  7822. else
  7823. return processNonFpScalarTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  7824. callExpr->getExprLoc());
  7825. }
  7826. }
  7827. // mul(matrix, scalar)
  7828. {
  7829. QualType elemType = {};
  7830. if (isScalarType(arg1Type) && isMxNMatrix(arg0Type, &elemType)) {
  7831. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  7832. // and the scalar type are float.
  7833. if (arg1Type->isFloatingType() && elemType->isFloatingType())
  7834. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  7835. returnType, arg0Id, arg1Id, loc);
  7836. else
  7837. return processNonFpScalarTimesMatrix(arg1Type, arg1Id, arg0Type, arg0Id,
  7838. callExpr->getExprLoc());
  7839. }
  7840. }
  7841. // mul(vector, matrix)
  7842. {
  7843. QualType vecElemType = {}, matElemType = {};
  7844. uint32_t elemCount = 0, numRows = 0;
  7845. if (isVectorType(arg0Type, &vecElemType, &elemCount) &&
  7846. isMxNMatrix(arg1Type, &matElemType, &numRows)) {
  7847. assert(elemCount == numRows);
  7848. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  7849. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesVector,
  7850. returnType, arg1Id, arg0Id, loc);
  7851. else
  7852. return processNonFpVectorTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  7853. callExpr->getExprLoc());
  7854. }
  7855. }
  7856. // mul(matrix, vector)
  7857. {
  7858. QualType vecElemType = {}, matElemType = {};
  7859. uint32_t elemCount = 0, numCols = 0;
  7860. if (isMxNMatrix(arg0Type, &matElemType, nullptr, &numCols) &&
  7861. isVectorType(arg1Type, &vecElemType, &elemCount)) {
  7862. assert(elemCount == numCols);
  7863. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  7864. return spvBuilder.createBinaryOp(spv::Op::OpVectorTimesMatrix,
  7865. returnType, arg1Id, arg0Id, loc);
  7866. else
  7867. return processNonFpMatrixTimesVector(arg0Type, arg0Id, arg1Type, arg1Id,
  7868. callExpr->getExprLoc());
  7869. }
  7870. }
  7871. // mul(matrix, matrix)
  7872. {
  7873. // The front-end ensures that the two matrix element types match.
  7874. QualType elemType = {};
  7875. uint32_t lhsCols = 0, rhsRows = 0;
  7876. if (isMxNMatrix(arg0Type, &elemType, nullptr, &lhsCols) &&
  7877. isMxNMatrix(arg1Type, nullptr, &rhsRows, nullptr)) {
  7878. assert(lhsCols == rhsRows);
  7879. if (elemType->isFloatingType())
  7880. return spvBuilder.createBinaryOp(spv::Op::OpMatrixTimesMatrix,
  7881. returnType, arg1Id, arg0Id, loc);
  7882. else
  7883. return processNonFpMatrixTimesMatrix(arg0Type, arg0Id, arg1Type, arg1Id,
  7884. callExpr->getExprLoc());
  7885. }
  7886. }
  7887. emitError("invalid argument type passed to mul intrinsic function",
  7888. callExpr->getExprLoc());
  7889. return nullptr;
  7890. }
  7891. SpirvInstruction *
  7892. SpirvEmitter::processIntrinsicPrintf(const CallExpr *callExpr) {
  7893. // C99, s6.5.2.2/6: "If the expression that denotes the called function has a
  7894. // type that does not include a prototype, the integer promotions are
  7895. // performed on each argument, and arguments that have type float are promoted
  7896. // to double. These are called the default argument promotions."
  7897. // C++: All the variadic parameters undergo default promotions before they're
  7898. // received by the function.
  7899. //
  7900. // Therefore by default floating point arguments will be evaluated as double
  7901. // by this function.
  7902. //
  7903. // TODO: We may want to change this behavior for SPIR-V.
  7904. const auto returnType = callExpr->getType();
  7905. const auto numArgs = callExpr->getNumArgs();
  7906. const auto loc = callExpr->getExprLoc();
  7907. assert(numArgs >= 1u);
  7908. llvm::SmallVector<SpirvInstruction *, 4> args;
  7909. for (uint32_t argIndex = 0; argIndex < numArgs; ++argIndex)
  7910. args.push_back(doExpr(callExpr->getArg(argIndex)));
  7911. return spvBuilder.createNonSemanticDebugPrintfExtInst(
  7912. returnType, NonSemanticDebugPrintfDebugPrintf, args, loc);
  7913. }
  7914. SpirvInstruction *SpirvEmitter::processIntrinsicDot(const CallExpr *callExpr) {
  7915. const QualType returnType = callExpr->getType();
  7916. // Get the function parameters. Expect 2 vectors as parameters.
  7917. assert(callExpr->getNumArgs() == 2u);
  7918. const Expr *arg0 = callExpr->getArg(0);
  7919. const Expr *arg1 = callExpr->getArg(1);
  7920. auto *arg0Id = doExpr(arg0);
  7921. auto *arg1Id = doExpr(arg1);
  7922. QualType arg0Type = arg0->getType();
  7923. QualType arg1Type = arg1->getType();
  7924. const size_t vec0Size = hlsl::GetHLSLVecSize(arg0Type);
  7925. const size_t vec1Size = hlsl::GetHLSLVecSize(arg1Type);
  7926. const QualType vec0ComponentType = hlsl::GetHLSLVecElementType(arg0Type);
  7927. const QualType vec1ComponentType = hlsl::GetHLSLVecElementType(arg1Type);
  7928. assert(returnType == vec1ComponentType);
  7929. assert(vec0ComponentType == vec1ComponentType);
  7930. assert(vec0Size == vec1Size);
  7931. assert(vec0Size >= 1 && vec0Size <= 4);
  7932. (void)vec0ComponentType;
  7933. (void)vec1ComponentType;
  7934. (void)vec1Size;
  7935. auto loc = callExpr->getLocStart();
  7936. // According to HLSL reference, the dot function only works on integers
  7937. // and floats.
  7938. assert(returnType->isFloatingType() || returnType->isIntegerType());
  7939. // Special case: dot product of two vectors, each of size 1. That is
  7940. // basically the same as regular multiplication of 2 scalars.
  7941. if (vec0Size == 1) {
  7942. const spv::Op spvOp = translateOp(BO_Mul, arg0Type);
  7943. return spvBuilder.createBinaryOp(spvOp, returnType, arg0Id, arg1Id, loc);
  7944. }
  7945. // If the vectors are of type Float, we can use OpDot.
  7946. if (returnType->isFloatingType()) {
  7947. return spvBuilder.createBinaryOp(spv::Op::OpDot, returnType, arg0Id, arg1Id,
  7948. loc);
  7949. }
  7950. // Vector component type is Integer (signed or unsigned).
  7951. // Create all instructions necessary to perform a dot product on
  7952. // two integer vectors. SPIR-V OpDot does not support integer vectors.
  7953. // Therefore, we use other SPIR-V instructions (addition and
  7954. // multiplication).
  7955. else {
  7956. SpirvInstruction *result = nullptr;
  7957. llvm::SmallVector<SpirvInstruction *, 4> multIds;
  7958. const spv::Op multSpvOp = translateOp(BO_Mul, arg0Type);
  7959. const spv::Op addSpvOp = translateOp(BO_Add, arg0Type);
  7960. // Extract members from the two vectors and multiply them.
  7961. for (unsigned int i = 0; i < vec0Size; ++i) {
  7962. auto *vec0member = spvBuilder.createCompositeExtract(
  7963. returnType, arg0Id, {i}, arg0->getLocStart());
  7964. auto *vec1member = spvBuilder.createCompositeExtract(
  7965. returnType, arg1Id, {i}, arg1->getLocStart());
  7966. auto *multId = spvBuilder.createBinaryOp(multSpvOp, returnType,
  7967. vec0member, vec1member, loc);
  7968. multIds.push_back(multId);
  7969. }
  7970. // Add all the multiplications.
  7971. result = multIds[0];
  7972. for (unsigned int i = 1; i < vec0Size; ++i) {
  7973. auto *additionId = spvBuilder.createBinaryOp(addSpvOp, returnType, result,
  7974. multIds[i], loc);
  7975. result = additionId;
  7976. }
  7977. return result;
  7978. }
  7979. }
  7980. SpirvInstruction *SpirvEmitter::processIntrinsicRcp(const CallExpr *callExpr) {
  7981. // 'rcp' takes only 1 argument that is a scalar, vector, or matrix of type
  7982. // float or double.
  7983. assert(callExpr->getNumArgs() == 1u);
  7984. const QualType returnType = callExpr->getType();
  7985. const Expr *arg = callExpr->getArg(0);
  7986. auto *argId = doExpr(arg);
  7987. const QualType argType = arg->getType();
  7988. auto loc = callExpr->getLocStart();
  7989. // For cases with matrix argument.
  7990. QualType elemType = {};
  7991. uint32_t numRows = 0, numCols = 0;
  7992. if (isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  7993. auto *vecOne = getVecValueOne(elemType, numCols);
  7994. const auto actOnEachVec = [this, vecOne, loc](uint32_t /*index*/,
  7995. QualType vecType,
  7996. SpirvInstruction *curRow) {
  7997. return spvBuilder.createBinaryOp(spv::Op::OpFDiv, vecType, vecOne, curRow,
  7998. loc);
  7999. };
  8000. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8001. }
  8002. // For cases with scalar or vector arguments.
  8003. return spvBuilder.createBinaryOp(spv::Op::OpFDiv, returnType,
  8004. getValueOne(argType), argId, loc);
  8005. }
  8006. SpirvInstruction *
  8007. SpirvEmitter::processIntrinsicAllOrAny(const CallExpr *callExpr,
  8008. spv::Op spvOp) {
  8009. // 'all' and 'any' take only 1 parameter.
  8010. assert(callExpr->getNumArgs() == 1u);
  8011. const QualType returnType = callExpr->getType();
  8012. const Expr *arg = callExpr->getArg(0);
  8013. const QualType argType = arg->getType();
  8014. const auto loc = callExpr->getExprLoc();
  8015. // Handle scalars, vectors of size 1, and 1x1 matrices as arguments.
  8016. // Optimization: can directly cast them to boolean. No need for OpAny/OpAll.
  8017. {
  8018. QualType scalarType = {};
  8019. if (isScalarType(argType, &scalarType) &&
  8020. (scalarType->isBooleanType() || scalarType->isFloatingType() ||
  8021. scalarType->isIntegerType()))
  8022. return castToBool(doExpr(arg), argType, returnType, loc);
  8023. }
  8024. // Handle vectors larger than 1, Mx1 matrices, and 1xN matrices as arguments.
  8025. // Cast the vector to a boolean vector, then run OpAny/OpAll on it.
  8026. {
  8027. QualType elemType = {};
  8028. uint32_t size = 0;
  8029. if (isVectorType(argType, &elemType, &size)) {
  8030. const QualType castToBoolType =
  8031. astContext.getExtVectorType(returnType, size);
  8032. auto *castedToBool =
  8033. castToBool(doExpr(arg), argType, castToBoolType, loc);
  8034. return spvBuilder.createUnaryOp(spvOp, returnType, castedToBool, loc);
  8035. }
  8036. }
  8037. // Handle MxN matrices as arguments.
  8038. {
  8039. QualType elemType = {};
  8040. uint32_t matRowCount = 0, matColCount = 0;
  8041. if (isMxNMatrix(argType, &elemType, &matRowCount, &matColCount)) {
  8042. auto *matrix = doExpr(arg);
  8043. const QualType vecType = getComponentVectorType(astContext, argType);
  8044. llvm::SmallVector<SpirvInstruction *, 4> rowResults;
  8045. for (uint32_t i = 0; i < matRowCount; ++i) {
  8046. // Extract the row which is a float vector of size matColCount.
  8047. auto *rowFloatVec = spvBuilder.createCompositeExtract(
  8048. vecType, matrix, {i}, arg->getLocStart());
  8049. // Cast the float vector to boolean vector.
  8050. const auto rowFloatQualType =
  8051. astContext.getExtVectorType(elemType, matColCount);
  8052. const auto rowBoolQualType =
  8053. astContext.getExtVectorType(returnType, matColCount);
  8054. auto *rowBoolVec = castToBool(rowFloatVec, rowFloatQualType,
  8055. rowBoolQualType, arg->getLocStart());
  8056. // Perform OpAny/OpAll on the boolean vector.
  8057. rowResults.push_back(
  8058. spvBuilder.createUnaryOp(spvOp, returnType, rowBoolVec, loc));
  8059. }
  8060. // Create a new vector that is the concatenation of results of all rows.
  8061. const QualType vecOfBools =
  8062. astContext.getExtVectorType(astContext.BoolTy, matRowCount);
  8063. auto *row =
  8064. spvBuilder.createCompositeConstruct(vecOfBools, rowResults, loc);
  8065. // Run OpAny/OpAll on the newly-created vector.
  8066. return spvBuilder.createUnaryOp(spvOp, returnType, row, loc);
  8067. }
  8068. }
  8069. // All types should be handled already.
  8070. llvm_unreachable("Unknown argument type passed to all()/any().");
  8071. return nullptr;
  8072. }
  8073. SpirvInstruction *
  8074. SpirvEmitter::processIntrinsicAsType(const CallExpr *callExpr) {
  8075. // This function handles 'asint', 'asuint', 'asfloat', and 'asdouble'.
  8076. // Method 1: ret asint(arg)
  8077. // arg component type = {float, uint}
  8078. // arg template type = {scalar, vector, matrix}
  8079. // ret template type = same as arg template type.
  8080. // ret component type = int
  8081. // Method 2: ret asuint(arg)
  8082. // arg component type = {float, int}
  8083. // arg template type = {scalar, vector, matrix}
  8084. // ret template type = same as arg template type.
  8085. // ret component type = uint
  8086. // Method 3: ret asfloat(arg)
  8087. // arg component type = {float, uint, int}
  8088. // arg template type = {scalar, vector, matrix}
  8089. // ret template type = same as arg template type.
  8090. // ret component type = float
  8091. // Method 4: double asdouble(uint lowbits, uint highbits)
  8092. // Method 5: double2 asdouble(uint2 lowbits, uint2 highbits)
  8093. // Method 6:
  8094. // void asuint(
  8095. // in double value,
  8096. // out uint lowbits,
  8097. // out uint highbits
  8098. // );
  8099. const QualType returnType = callExpr->getType();
  8100. const uint32_t numArgs = callExpr->getNumArgs();
  8101. const Expr *arg0 = callExpr->getArg(0);
  8102. const QualType argType = arg0->getType();
  8103. const auto loc = callExpr->getExprLoc();
  8104. // Method 3 return type may be the same as arg type, so it would be a no-op.
  8105. if (isSameType(astContext, returnType, argType))
  8106. return doExpr(arg0);
  8107. switch (numArgs) {
  8108. case 1: {
  8109. // Handling Method 1, 2, and 3.
  8110. auto *argInstr = doExpr(arg0);
  8111. QualType fromElemType = {};
  8112. uint32_t numRows = 0, numCols = 0;
  8113. // For non-matrix arguments (scalar or vector), just do an OpBitCast.
  8114. if (!isMxNMatrix(argType, &fromElemType, &numRows, &numCols)) {
  8115. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, returnType, argInstr,
  8116. loc);
  8117. }
  8118. // Input or output type is a matrix.
  8119. const QualType toElemType = hlsl::GetHLSLMatElementType(returnType);
  8120. llvm::SmallVector<SpirvInstruction *, 4> castedRows;
  8121. const auto fromVecType = astContext.getExtVectorType(fromElemType, numCols);
  8122. const auto toVecType = astContext.getExtVectorType(toElemType, numCols);
  8123. for (uint32_t row = 0; row < numRows; ++row) {
  8124. auto *rowInstr = spvBuilder.createCompositeExtract(
  8125. fromVecType, argInstr, {row}, arg0->getLocStart());
  8126. castedRows.push_back(spvBuilder.createUnaryOp(spv::Op::OpBitcast,
  8127. toVecType, rowInstr, loc));
  8128. }
  8129. return spvBuilder.createCompositeConstruct(returnType, castedRows, loc);
  8130. }
  8131. case 2: {
  8132. auto *lowbits = doExpr(arg0);
  8133. auto *highbits = doExpr(callExpr->getArg(1));
  8134. const auto uintType = astContext.UnsignedIntTy;
  8135. const auto doubleType = astContext.DoubleTy;
  8136. // Handling Method 4
  8137. if (argType->isUnsignedIntegerType()) {
  8138. const auto uintVec2Type = astContext.getExtVectorType(uintType, 2);
  8139. auto *operand = spvBuilder.createCompositeConstruct(
  8140. uintVec2Type, {lowbits, highbits}, loc);
  8141. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, doubleType, operand,
  8142. loc);
  8143. }
  8144. // Handling Method 5
  8145. else {
  8146. const auto uintVec4Type = astContext.getExtVectorType(uintType, 4);
  8147. const auto doubleVec2Type = astContext.getExtVectorType(doubleType, 2);
  8148. auto *operand = spvBuilder.createVectorShuffle(
  8149. uintVec4Type, lowbits, highbits, {0, 2, 1, 3}, loc);
  8150. return spvBuilder.createUnaryOp(spv::Op::OpBitcast, doubleVec2Type,
  8151. operand, loc);
  8152. }
  8153. }
  8154. case 3: {
  8155. // Handling Method 6.
  8156. auto *value = doExpr(arg0);
  8157. auto *lowbits = doExpr(callExpr->getArg(1));
  8158. auto *highbits = doExpr(callExpr->getArg(2));
  8159. const auto uintType = astContext.UnsignedIntTy;
  8160. const auto uintVec2Type = astContext.getExtVectorType(uintType, 2);
  8161. auto *vecResult =
  8162. spvBuilder.createUnaryOp(spv::Op::OpBitcast, uintVec2Type, value, loc);
  8163. spvBuilder.createStore(lowbits,
  8164. spvBuilder.createCompositeExtract(
  8165. uintType, vecResult, {0}, arg0->getLocStart()),
  8166. loc);
  8167. spvBuilder.createStore(highbits,
  8168. spvBuilder.createCompositeExtract(
  8169. uintType, vecResult, {1}, arg0->getLocStart()),
  8170. loc);
  8171. return nullptr;
  8172. }
  8173. default:
  8174. emitError("unrecognized signature for %0 intrinsic function", loc)
  8175. << callExpr->getDirectCallee()->getName();
  8176. return nullptr;
  8177. }
  8178. }
  8179. SpirvInstruction *
  8180. SpirvEmitter::processD3DCOLORtoUBYTE4(const CallExpr *callExpr) {
  8181. // Should take a float4 and return an int4 by doing:
  8182. // int4 result = input.zyxw * 255.001953;
  8183. // Maximum float precision makes the scaling factor 255.002.
  8184. const auto arg = callExpr->getArg(0);
  8185. auto *argId = doExpr(arg);
  8186. const auto argType = arg->getType();
  8187. auto loc = callExpr->getLocStart();
  8188. auto *swizzle =
  8189. spvBuilder.createVectorShuffle(argType, argId, argId, {2, 1, 0, 3}, loc);
  8190. auto *scaled = spvBuilder.createBinaryOp(
  8191. spv::Op::OpVectorTimesScalar, argType, swizzle,
  8192. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(255.002f)),
  8193. loc);
  8194. return castToInt(scaled, arg->getType(), callExpr->getType(), loc);
  8195. }
  8196. SpirvInstruction *
  8197. SpirvEmitter::processIntrinsicIsFinite(const CallExpr *callExpr) {
  8198. // Since OpIsFinite needs the Kernel capability, translation is instead done
  8199. // using OpIsNan and OpIsInf:
  8200. // isFinite = !(isNan || isInf)
  8201. const auto arg = doExpr(callExpr->getArg(0));
  8202. const auto returnType = callExpr->getType();
  8203. const auto loc = callExpr->getExprLoc();
  8204. const auto isNan =
  8205. spvBuilder.createUnaryOp(spv::Op::OpIsNan, returnType, arg, loc);
  8206. const auto isInf =
  8207. spvBuilder.createUnaryOp(spv::Op::OpIsInf, returnType, arg, loc);
  8208. const auto isNanOrInf = spvBuilder.createBinaryOp(
  8209. spv::Op::OpLogicalOr, returnType, isNan, isInf, loc);
  8210. return spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, returnType, isNanOrInf,
  8211. loc);
  8212. }
  8213. SpirvInstruction *
  8214. SpirvEmitter::processIntrinsicSinCos(const CallExpr *callExpr) {
  8215. // Since there is no sincos equivalent in SPIR-V, we need to perform Sin
  8216. // once and Cos once. We can reuse existing Sine/Cosine handling functions.
  8217. CallExpr *sincosExpr =
  8218. new (astContext) CallExpr(astContext, Stmt::StmtClass::NoStmtClass, {});
  8219. sincosExpr->setType(callExpr->getArg(0)->getType());
  8220. sincosExpr->setNumArgs(astContext, 1);
  8221. sincosExpr->setArg(0, const_cast<Expr *>(callExpr->getArg(0)));
  8222. const auto srcLoc = callExpr->getExprLoc();
  8223. // Perform Sin and store results in argument 1.
  8224. auto *sin =
  8225. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Sin,
  8226. /*actPerRowForMatrices*/ true, srcLoc);
  8227. spvBuilder.createStore(doExpr(callExpr->getArg(1)), sin, srcLoc);
  8228. // Perform Cos and store results in argument 2.
  8229. auto *cos =
  8230. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Cos,
  8231. /*actPerRowForMatrices*/ true, srcLoc);
  8232. spvBuilder.createStore(doExpr(callExpr->getArg(2)), cos, srcLoc);
  8233. return nullptr;
  8234. }
  8235. SpirvInstruction *
  8236. SpirvEmitter::processIntrinsicSaturate(const CallExpr *callExpr) {
  8237. const auto *arg = callExpr->getArg(0);
  8238. const auto loc = callExpr->getExprLoc();
  8239. auto *argId = doExpr(arg);
  8240. const auto argType = arg->getType();
  8241. const QualType returnType = callExpr->getType();
  8242. QualType elemType = {};
  8243. uint32_t vecSize = 0;
  8244. if (isScalarType(argType, &elemType)) {
  8245. auto *floatZero = getValueZero(elemType);
  8246. auto *floatOne = getValueOne(elemType);
  8247. return spvBuilder.createGLSLExtInst(returnType,
  8248. GLSLstd450::GLSLstd450FClamp,
  8249. {argId, floatZero, floatOne}, loc);
  8250. }
  8251. if (isVectorType(argType, &elemType, &vecSize)) {
  8252. auto *vecZero = getVecValueZero(elemType, vecSize);
  8253. auto *vecOne = getVecValueOne(elemType, vecSize);
  8254. return spvBuilder.createGLSLExtInst(returnType,
  8255. GLSLstd450::GLSLstd450FClamp,
  8256. {argId, vecZero, vecOne}, loc);
  8257. }
  8258. uint32_t numRows = 0, numCols = 0;
  8259. if (isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  8260. auto *vecZero = getVecValueZero(elemType, numCols);
  8261. auto *vecOne = getVecValueOne(elemType, numCols);
  8262. const auto actOnEachVec = [this, loc, vecZero,
  8263. vecOne](uint32_t /*index*/, QualType vecType,
  8264. SpirvInstruction *curRow) {
  8265. return spvBuilder.createGLSLExtInst(vecType, GLSLstd450::GLSLstd450FClamp,
  8266. {curRow, vecZero, vecOne}, loc);
  8267. };
  8268. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8269. }
  8270. emitError("invalid argument type passed to saturate intrinsic function",
  8271. callExpr->getExprLoc());
  8272. return nullptr;
  8273. }
  8274. SpirvInstruction *
  8275. SpirvEmitter::processIntrinsicFloatSign(const CallExpr *callExpr) {
  8276. // Import the GLSL.std.450 extended instruction set.
  8277. const Expr *arg = callExpr->getArg(0);
  8278. const auto loc = callExpr->getExprLoc();
  8279. const QualType returnType = callExpr->getType();
  8280. const QualType argType = arg->getType();
  8281. assert(isFloatOrVecMatOfFloatType(argType));
  8282. auto *argId = doExpr(arg);
  8283. SpirvInstruction *floatSign = nullptr;
  8284. // For matrices, we can perform the instruction on each vector of the matrix.
  8285. if (isMxNMatrix(argType)) {
  8286. const auto actOnEachVec = [this, loc](uint32_t /*index*/, QualType vecType,
  8287. SpirvInstruction *curRow) {
  8288. return spvBuilder.createGLSLExtInst(vecType, GLSLstd450::GLSLstd450FSign,
  8289. {curRow}, loc);
  8290. };
  8291. floatSign = processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8292. } else {
  8293. floatSign = spvBuilder.createGLSLExtInst(
  8294. argType, GLSLstd450::GLSLstd450FSign, {argId}, loc);
  8295. }
  8296. return castToInt(floatSign, arg->getType(), returnType, arg->getLocStart());
  8297. }
  8298. SpirvInstruction *
  8299. SpirvEmitter::processIntrinsicF16ToF32(const CallExpr *callExpr) {
  8300. // f16tof32() takes in (vector of) uint and returns (vector of) float.
  8301. // The frontend should guarantee that by inserting implicit casts.
  8302. const QualType f32Type = astContext.FloatTy;
  8303. const QualType u32Type = astContext.UnsignedIntTy;
  8304. const QualType v2f32Type = astContext.getExtVectorType(f32Type, 2);
  8305. const auto loc = callExpr->getExprLoc();
  8306. const auto *arg = callExpr->getArg(0);
  8307. auto *argId = doExpr(arg);
  8308. uint32_t elemCount = {};
  8309. if (isVectorType(arg->getType(), nullptr, &elemCount)) {
  8310. // The input is a vector. We need to handle each element separately.
  8311. llvm::SmallVector<SpirvInstruction *, 4> elements;
  8312. for (uint32_t i = 0; i < elemCount; ++i) {
  8313. auto *srcElem = spvBuilder.createCompositeExtract(u32Type, argId, {i},
  8314. arg->getLocStart());
  8315. auto *convert = spvBuilder.createGLSLExtInst(
  8316. v2f32Type, GLSLstd450::GLSLstd450UnpackHalf2x16, srcElem, loc);
  8317. elements.push_back(
  8318. spvBuilder.createCompositeExtract(f32Type, convert, {0}, loc));
  8319. }
  8320. return spvBuilder.createCompositeConstruct(
  8321. astContext.getExtVectorType(f32Type, elemCount), elements, loc);
  8322. }
  8323. auto *convert = spvBuilder.createGLSLExtInst(
  8324. v2f32Type, GLSLstd450::GLSLstd450UnpackHalf2x16, argId, loc);
  8325. // f16tof32() converts the float16 stored in the low-half of the uint to
  8326. // a float. So just need to return the first component.
  8327. return spvBuilder.createCompositeExtract(f32Type, convert, {0}, loc);
  8328. }
  8329. SpirvInstruction *
  8330. SpirvEmitter::processIntrinsicF32ToF16(const CallExpr *callExpr) {
  8331. // f32tof16() takes in (vector of) float and returns (vector of) uint.
  8332. // The frontend should guarantee that by inserting implicit casts.
  8333. const QualType f32Type = astContext.FloatTy;
  8334. const QualType u32Type = astContext.UnsignedIntTy;
  8335. const QualType v2f32Type = astContext.getExtVectorType(f32Type, 2);
  8336. auto *zero = spvBuilder.getConstantFloat(f32Type, llvm::APFloat(0.0f));
  8337. const auto loc = callExpr->getExprLoc();
  8338. const auto *arg = callExpr->getArg(0);
  8339. auto *argId = doExpr(arg);
  8340. uint32_t elemCount = {};
  8341. if (isVectorType(arg->getType(), nullptr, &elemCount)) {
  8342. // The input is a vector. We need to handle each element separately.
  8343. llvm::SmallVector<SpirvInstruction *, 4> elements;
  8344. for (uint32_t i = 0; i < elemCount; ++i) {
  8345. auto *srcElem = spvBuilder.createCompositeExtract(f32Type, argId, {i},
  8346. arg->getLocStart());
  8347. auto *srcVec =
  8348. spvBuilder.createCompositeConstruct(v2f32Type, {srcElem, zero}, loc);
  8349. elements.push_back(spvBuilder.createGLSLExtInst(
  8350. u32Type, GLSLstd450::GLSLstd450PackHalf2x16, srcVec, loc));
  8351. }
  8352. return spvBuilder.createCompositeConstruct(
  8353. astContext.getExtVectorType(u32Type, elemCount), elements, loc);
  8354. }
  8355. // f16tof32() stores the float into the low-half of the uint. So we need
  8356. // to supply another zero to take the other half.
  8357. auto *srcVec =
  8358. spvBuilder.createCompositeConstruct(v2f32Type, {argId, zero}, loc);
  8359. return spvBuilder.createGLSLExtInst(
  8360. u32Type, GLSLstd450::GLSLstd450PackHalf2x16, srcVec, loc);
  8361. }
  8362. SpirvInstruction *SpirvEmitter::processIntrinsicUsingSpirvInst(
  8363. const CallExpr *callExpr, spv::Op opcode, bool actPerRowForMatrices) {
  8364. // Certain opcodes are only allowed in pixel shader
  8365. if (!spvContext.isPS())
  8366. switch (opcode) {
  8367. case spv::Op::OpDPdx:
  8368. case spv::Op::OpDPdy:
  8369. case spv::Op::OpDPdxFine:
  8370. case spv::Op::OpDPdyFine:
  8371. case spv::Op::OpDPdxCoarse:
  8372. case spv::Op::OpDPdyCoarse:
  8373. case spv::Op::OpFwidth:
  8374. case spv::Op::OpFwidthFine:
  8375. case spv::Op::OpFwidthCoarse:
  8376. needsLegalization = true;
  8377. break;
  8378. default:
  8379. // Only the given opcodes need legalization. Anything else should preserve
  8380. // previous.
  8381. break;
  8382. }
  8383. const auto loc = callExpr->getExprLoc();
  8384. const QualType returnType = callExpr->getType();
  8385. if (callExpr->getNumArgs() == 1u) {
  8386. const Expr *arg = callExpr->getArg(0);
  8387. auto *argId = doExpr(arg);
  8388. // If the instruction does not operate on matrices, we can perform the
  8389. // instruction on each vector of the matrix.
  8390. if (actPerRowForMatrices && isMxNMatrix(arg->getType())) {
  8391. const auto actOnEachVec = [this, opcode, loc](uint32_t /*index*/,
  8392. QualType vecType,
  8393. SpirvInstruction *curRow) {
  8394. return spvBuilder.createUnaryOp(opcode, vecType, curRow, loc);
  8395. };
  8396. return processEachVectorInMatrix(arg, argId, actOnEachVec, loc);
  8397. }
  8398. return spvBuilder.createUnaryOp(opcode, returnType, argId, loc);
  8399. } else if (callExpr->getNumArgs() == 2u) {
  8400. const Expr *arg0 = callExpr->getArg(0);
  8401. auto *arg0Id = doExpr(arg0);
  8402. auto *arg1Id = doExpr(callExpr->getArg(1));
  8403. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8404. // If the instruction does not operate on matrices, we can perform the
  8405. // instruction on each vector of the matrix.
  8406. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8407. const auto actOnEachVec = [this, opcode, arg1Id, loc,
  8408. arg1Loc](uint32_t index, QualType vecType,
  8409. SpirvInstruction *arg0Row) {
  8410. auto *arg1Row = spvBuilder.createCompositeExtract(vecType, arg1Id,
  8411. {index}, arg1Loc);
  8412. return spvBuilder.createBinaryOp(opcode, vecType, arg0Row, arg1Row,
  8413. loc);
  8414. };
  8415. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec, loc);
  8416. }
  8417. return spvBuilder.createBinaryOp(opcode, returnType, arg0Id, arg1Id, loc);
  8418. }
  8419. emitError("unsupported %0 intrinsic function", loc)
  8420. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  8421. return nullptr;
  8422. }
  8423. SpirvInstruction *SpirvEmitter::processIntrinsicUsingGLSLInst(
  8424. const CallExpr *callExpr, GLSLstd450 opcode, bool actPerRowForMatrices,
  8425. SourceLocation loc) {
  8426. // Import the GLSL.std.450 extended instruction set.
  8427. const QualType returnType = callExpr->getType();
  8428. if (callExpr->getNumArgs() == 1u) {
  8429. const Expr *arg = callExpr->getArg(0);
  8430. auto *argInstr = doExpr(arg);
  8431. // If the instruction does not operate on matrices, we can perform the
  8432. // instruction on each vector of the matrix.
  8433. if (actPerRowForMatrices && isMxNMatrix(arg->getType())) {
  8434. const auto actOnEachVec = [this, loc,
  8435. opcode](uint32_t /*index*/, QualType vecType,
  8436. SpirvInstruction *curRowInstr) {
  8437. return spvBuilder.createGLSLExtInst(vecType, opcode, {curRowInstr},
  8438. loc);
  8439. };
  8440. return processEachVectorInMatrix(arg, argInstr, actOnEachVec, loc);
  8441. }
  8442. return spvBuilder.createGLSLExtInst(returnType, opcode, {argInstr}, loc);
  8443. } else if (callExpr->getNumArgs() == 2u) {
  8444. const Expr *arg0 = callExpr->getArg(0);
  8445. auto *arg0Instr = doExpr(arg0);
  8446. auto *arg1Instr = doExpr(callExpr->getArg(1));
  8447. const auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8448. // If the instruction does not operate on matrices, we can perform the
  8449. // instruction on each vector of the matrix.
  8450. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8451. const auto actOnEachVec = [this, loc, opcode, arg1Instr,
  8452. arg1Loc](uint32_t index, QualType vecType,
  8453. SpirvInstruction *arg0RowInstr) {
  8454. auto *arg1RowInstr = spvBuilder.createCompositeExtract(
  8455. vecType, arg1Instr, {index}, arg1Loc);
  8456. return spvBuilder.createGLSLExtInst(vecType, opcode,
  8457. {arg0RowInstr, arg1RowInstr}, loc);
  8458. };
  8459. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  8460. }
  8461. return spvBuilder.createGLSLExtInst(returnType, opcode,
  8462. {arg0Instr, arg1Instr}, loc);
  8463. } else if (callExpr->getNumArgs() == 3u) {
  8464. const Expr *arg0 = callExpr->getArg(0);
  8465. auto *arg0Instr = doExpr(arg0);
  8466. auto *arg1Instr = doExpr(callExpr->getArg(1));
  8467. auto *arg2Instr = doExpr(callExpr->getArg(2));
  8468. auto arg1Loc = callExpr->getArg(1)->getLocStart();
  8469. auto arg2Loc = callExpr->getArg(2)->getLocStart();
  8470. // If the instruction does not operate on matrices, we can perform the
  8471. // instruction on each vector of the matrix.
  8472. if (actPerRowForMatrices && isMxNMatrix(arg0->getType())) {
  8473. const auto actOnEachVec = [this, loc, opcode, arg1Instr, arg2Instr,
  8474. arg1Loc,
  8475. arg2Loc](uint32_t index, QualType vecType,
  8476. SpirvInstruction *arg0RowInstr) {
  8477. auto *arg1RowInstr = spvBuilder.createCompositeExtract(
  8478. vecType, arg1Instr, {index}, arg1Loc);
  8479. auto *arg2RowInstr = spvBuilder.createCompositeExtract(
  8480. vecType, arg2Instr, {index}, arg2Loc);
  8481. return spvBuilder.createGLSLExtInst(
  8482. vecType, opcode, {arg0RowInstr, arg1RowInstr, arg2RowInstr}, loc);
  8483. };
  8484. return processEachVectorInMatrix(arg0, arg0Instr, actOnEachVec, loc);
  8485. }
  8486. return spvBuilder.createGLSLExtInst(returnType, opcode,
  8487. {arg0Instr, arg1Instr, arg2Instr}, loc);
  8488. }
  8489. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  8490. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  8491. return nullptr;
  8492. }
  8493. SpirvInstruction *
  8494. SpirvEmitter::processIntrinsicLog10(const CallExpr *callExpr) {
  8495. // Since there is no log10 instruction in SPIR-V, we can use:
  8496. // log10(x) = log2(x) * ( 1 / log2(10) )
  8497. // 1 / log2(10) = 0.30103
  8498. auto loc = callExpr->getExprLoc();
  8499. auto *scale =
  8500. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(0.30103f));
  8501. auto *log2 = processIntrinsicUsingGLSLInst(
  8502. callExpr, GLSLstd450::GLSLstd450Log2, true, loc);
  8503. const auto returnType = callExpr->getType();
  8504. spv::Op scaleOp = isScalarType(returnType)
  8505. ? spv::Op::OpFMul
  8506. : isVectorType(returnType)
  8507. ? spv::Op::OpVectorTimesScalar
  8508. : spv::Op::OpMatrixTimesScalar;
  8509. return spvBuilder.createBinaryOp(scaleOp, returnType, log2, scale, loc);
  8510. }
  8511. SpirvInstruction *SpirvEmitter::processRayBuiltins(const CallExpr *callExpr,
  8512. hlsl::IntrinsicOp op) {
  8513. spv::BuiltIn builtin = spv::BuiltIn::Max;
  8514. bool transposeMatrix = false;
  8515. const auto loc = callExpr->getExprLoc();
  8516. switch (op) {
  8517. case hlsl::IntrinsicOp::IOP_DispatchRaysDimensions:
  8518. builtin = spv::BuiltIn::LaunchSizeNV;
  8519. break;
  8520. case hlsl::IntrinsicOp::IOP_DispatchRaysIndex:
  8521. builtin = spv::BuiltIn::LaunchIdNV;
  8522. break;
  8523. case hlsl::IntrinsicOp::IOP_RayTCurrent:
  8524. builtin = spv::BuiltIn::HitTNV;
  8525. break;
  8526. case hlsl::IntrinsicOp::IOP_RayTMin:
  8527. builtin = spv::BuiltIn::RayTminNV;
  8528. break;
  8529. case hlsl::IntrinsicOp::IOP_HitKind:
  8530. builtin = spv::BuiltIn::HitKindNV;
  8531. break;
  8532. case hlsl::IntrinsicOp::IOP_WorldRayDirection:
  8533. builtin = spv::BuiltIn::WorldRayDirectionNV;
  8534. break;
  8535. case hlsl::IntrinsicOp::IOP_WorldRayOrigin:
  8536. builtin = spv::BuiltIn::WorldRayOriginNV;
  8537. break;
  8538. case hlsl::IntrinsicOp::IOP_ObjectRayDirection:
  8539. builtin = spv::BuiltIn::ObjectRayDirectionNV;
  8540. break;
  8541. case hlsl::IntrinsicOp::IOP_ObjectRayOrigin:
  8542. builtin = spv::BuiltIn::ObjectRayOriginNV;
  8543. break;
  8544. case hlsl::IntrinsicOp::IOP_GeometryIndex:
  8545. featureManager.requestExtension(Extension::KHR_ray_tracing,
  8546. "GeometryIndex()", loc);
  8547. builtin = spv::BuiltIn::RayGeometryIndexKHR;
  8548. break;
  8549. case hlsl::IntrinsicOp::IOP_InstanceIndex:
  8550. builtin = spv::BuiltIn::InstanceId;
  8551. break;
  8552. case hlsl::IntrinsicOp::IOP_PrimitiveIndex:
  8553. builtin = spv::BuiltIn::PrimitiveId;
  8554. break;
  8555. case hlsl::IntrinsicOp::IOP_InstanceID:
  8556. builtin = spv::BuiltIn::InstanceCustomIndexNV;
  8557. break;
  8558. case hlsl::IntrinsicOp::IOP_RayFlags:
  8559. builtin = spv::BuiltIn::IncomingRayFlagsNV;
  8560. break;
  8561. case hlsl::IntrinsicOp::IOP_ObjectToWorld3x4:
  8562. transposeMatrix = true;
  8563. case hlsl::IntrinsicOp::IOP_ObjectToWorld4x3:
  8564. builtin = spv::BuiltIn::ObjectToWorldNV;
  8565. break;
  8566. case hlsl::IntrinsicOp::IOP_WorldToObject3x4:
  8567. transposeMatrix = true;
  8568. case hlsl::IntrinsicOp::IOP_WorldToObject4x3:
  8569. builtin = spv::BuiltIn::WorldToObjectNV;
  8570. break;
  8571. default:
  8572. emitError("ray intrinsic function unimplemented", loc);
  8573. return nullptr;
  8574. }
  8575. QualType builtinType = callExpr->getType();
  8576. if (transposeMatrix) {
  8577. // DXR defines ObjectToWorld3x4, WorldToObject3x4 as transposed matrices.
  8578. // SPIR-V has only non tranposed variant defined as a builtin
  8579. // So perform read of original non transposed builtin and perform transpose.
  8580. assert(hlsl::IsHLSLMatType(builtinType) && "Builtin should be matrix");
  8581. const clang::Type *type = builtinType.getCanonicalType().getTypePtr();
  8582. const RecordType *RT = cast<RecordType>(type);
  8583. const ClassTemplateSpecializationDecl *templateSpecDecl =
  8584. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  8585. ClassTemplateDecl *templateDecl =
  8586. templateSpecDecl->getSpecializedTemplate();
  8587. builtinType = getHLSLMatrixType(astContext, theCompilerInstance.getSema(),
  8588. templateDecl, astContext.FloatTy, 4, 3);
  8589. }
  8590. SpirvInstruction *retVal =
  8591. declIdMapper.getBuiltinVar(builtin, builtinType, loc);
  8592. retVal = spvBuilder.createLoad(builtinType, retVal, loc);
  8593. if (transposeMatrix)
  8594. retVal = spvBuilder.createUnaryOp(spv::Op::OpTranspose, callExpr->getType(),
  8595. retVal, loc);
  8596. return retVal;
  8597. }
  8598. SpirvInstruction *SpirvEmitter::processReportHit(const CallExpr *callExpr) {
  8599. SpirvInstruction *hitAttributeStageVar = nullptr;
  8600. const VarDecl *hitAttributeArg = nullptr;
  8601. QualType hitAttributeType;
  8602. const auto args = callExpr->getArgs();
  8603. if (callExpr->getNumArgs() != 3) {
  8604. emitError("invalid number of arguments to ReportHit",
  8605. callExpr->getExprLoc());
  8606. }
  8607. // HLSL Function :
  8608. // template<typename hitAttr>
  8609. // ReportHit(in float, in uint, in hitAttr)
  8610. if (const auto *implCastExpr = dyn_cast<CastExpr>(callExpr->getArg(2))) {
  8611. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  8612. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  8613. hitAttributeType = varDecl->getType();
  8614. hitAttributeArg = varDecl;
  8615. // Check if same type of hit attribute stage variable was already
  8616. // created, if so re-use
  8617. const auto iter = hitAttributeMap.find(hitAttributeType);
  8618. if (iter == hitAttributeMap.end()) {
  8619. hitAttributeStageVar = declIdMapper.createRayTracingNVStageVar(
  8620. spv::StorageClass::HitAttributeNV, varDecl);
  8621. hitAttributeMap[hitAttributeType] = hitAttributeStageVar;
  8622. } else {
  8623. hitAttributeStageVar = iter->second;
  8624. }
  8625. }
  8626. }
  8627. }
  8628. assert(hitAttributeStageVar && hitAttributeArg);
  8629. // Copy argument to stage variable
  8630. const auto hitAttributeArgInst =
  8631. declIdMapper.getDeclEvalInfo(hitAttributeArg, callExpr->getExprLoc());
  8632. auto tempLoad =
  8633. spvBuilder.createLoad(hitAttributeArg->getType(), hitAttributeArgInst,
  8634. hitAttributeArg->getLocStart());
  8635. spvBuilder.createStore(hitAttributeStageVar, tempLoad,
  8636. callExpr->getExprLoc());
  8637. // SPIR-V Instruction :
  8638. // bool OpReportIntersection(<id> float Hit, <id> uint HitKind)
  8639. llvm::SmallVector<SpirvInstruction *, 4> reportHitArgs;
  8640. reportHitArgs.push_back(doExpr(args[0])); // Hit
  8641. reportHitArgs.push_back(doExpr(args[1])); // HitKind
  8642. return spvBuilder.createRayTracingOpsNV(spv::Op::OpReportIntersectionNV,
  8643. astContext.BoolTy, reportHitArgs,
  8644. callExpr->getExprLoc());
  8645. }
  8646. void SpirvEmitter::processCallShader(const CallExpr *callExpr) {
  8647. SpirvInstruction *callDataLocInst = nullptr;
  8648. SpirvInstruction *callDataStageVar = nullptr;
  8649. const VarDecl *callDataArg = nullptr;
  8650. QualType callDataType;
  8651. const auto args = callExpr->getArgs();
  8652. if (callExpr->getNumArgs() != 2) {
  8653. emitError("invalid number of arguments to CallShader",
  8654. callExpr->getExprLoc());
  8655. }
  8656. // HLSL Func :
  8657. // template<typename CallData>
  8658. // void CallShader(in int sbtIndex, inout CallData arg)
  8659. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[1])) {
  8660. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  8661. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  8662. callDataType = varDecl->getType();
  8663. callDataArg = varDecl;
  8664. // Check if same type of callable data stage variable was already
  8665. // created, if so re-use
  8666. const auto callDataPair = callDataMap.find(callDataType);
  8667. if (callDataPair == callDataMap.end()) {
  8668. int numCallDataVars = callDataMap.size();
  8669. callDataStageVar = declIdMapper.createRayTracingNVStageVar(
  8670. spv::StorageClass::CallableDataNV, varDecl);
  8671. // Decorate unique location id for each created stage var
  8672. spvBuilder.decorateLocation(callDataStageVar, numCallDataVars);
  8673. callDataLocInst = spvBuilder.getConstantInt(
  8674. astContext.UnsignedIntTy, llvm::APInt(32, numCallDataVars));
  8675. callDataMap[callDataType] =
  8676. std::make_pair(callDataStageVar, callDataLocInst);
  8677. } else {
  8678. callDataStageVar = callDataPair->second.first;
  8679. callDataLocInst = callDataPair->second.second;
  8680. }
  8681. }
  8682. }
  8683. }
  8684. assert(callDataStageVar && callDataArg);
  8685. // Copy argument to stage variable
  8686. const auto callDataArgInst =
  8687. declIdMapper.getDeclEvalInfo(callDataArg, callExpr->getExprLoc());
  8688. auto tempLoad = spvBuilder.createLoad(callDataArg->getType(), callDataArgInst,
  8689. callDataArg->getLocStart());
  8690. spvBuilder.createStore(callDataStageVar, tempLoad, callExpr->getExprLoc());
  8691. // SPIR-V Instruction
  8692. // void OpExecuteCallable(<id> int SBT Index, <id> uint Callable Data Location
  8693. // Id)
  8694. llvm::SmallVector<SpirvInstruction *, 2> callShaderArgs;
  8695. callShaderArgs.push_back(doExpr(args[0]));
  8696. callShaderArgs.push_back(callDataLocInst);
  8697. spvBuilder.createRayTracingOpsNV(spv::Op::OpExecuteCallableNV, QualType(),
  8698. callShaderArgs, callExpr->getExprLoc());
  8699. // Copy data back to argument
  8700. tempLoad = spvBuilder.createLoad(callDataArg->getType(), callDataStageVar,
  8701. callDataArg->getLocStart());
  8702. spvBuilder.createStore(callDataArgInst, tempLoad, callExpr->getExprLoc());
  8703. return;
  8704. }
  8705. void SpirvEmitter::processTraceRay(const CallExpr *callExpr) {
  8706. SpirvInstruction *rayPayloadLocInst = nullptr;
  8707. SpirvInstruction *rayPayloadStageVar = nullptr;
  8708. const VarDecl *rayPayloadArg = nullptr;
  8709. QualType rayPayloadType;
  8710. const auto args = callExpr->getArgs();
  8711. if (callExpr->getNumArgs() != 8) {
  8712. emitError("invalid number of arguments to TraceRay",
  8713. callExpr->getExprLoc());
  8714. }
  8715. // HLSL Func
  8716. // template<typename RayPayload>
  8717. // void TraceRay(RaytracingAccelerationStructure rs,
  8718. // uint rayflags,
  8719. // uint InstanceInclusionMask
  8720. // uint RayContributionToHitGroupIndex,
  8721. // uint MultiplierForGeometryContributionToHitGroupIndex,
  8722. // uint MissShaderIndex,
  8723. // RayDesc ray,
  8724. // inout RayPayload p)
  8725. // where RayDesc = {float3 origin, float tMin, float3 direction, float tMax}
  8726. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[7])) {
  8727. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  8728. if (const auto *varDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  8729. rayPayloadType = varDecl->getType();
  8730. rayPayloadArg = varDecl;
  8731. const auto rayPayloadPair = rayPayloadMap.find(rayPayloadType);
  8732. // Check if same type of rayPayload stage variable was already
  8733. // created, if so re-use
  8734. if (rayPayloadPair == rayPayloadMap.end()) {
  8735. int numPayloadVars = rayPayloadMap.size();
  8736. rayPayloadStageVar = declIdMapper.createRayTracingNVStageVar(
  8737. spv::StorageClass::RayPayloadNV, varDecl);
  8738. // Decorate unique location id for each created stage var
  8739. spvBuilder.decorateLocation(rayPayloadStageVar, numPayloadVars);
  8740. rayPayloadLocInst = spvBuilder.getConstantInt(
  8741. astContext.UnsignedIntTy, llvm::APInt(32, numPayloadVars));
  8742. rayPayloadMap[rayPayloadType] =
  8743. std::make_pair(rayPayloadStageVar, rayPayloadLocInst);
  8744. } else {
  8745. rayPayloadStageVar = rayPayloadPair->second.first;
  8746. rayPayloadLocInst = rayPayloadPair->second.second;
  8747. }
  8748. }
  8749. }
  8750. }
  8751. assert(rayPayloadStageVar && rayPayloadArg);
  8752. const auto floatType = astContext.FloatTy;
  8753. const auto vecType = astContext.getExtVectorType(astContext.FloatTy, 3);
  8754. // Extract the ray description to match SPIR-V
  8755. SpirvInstruction *rayDescArg = doExpr(args[6]);
  8756. const auto loc = args[6]->getLocStart();
  8757. const auto origin =
  8758. spvBuilder.createCompositeExtract(vecType, rayDescArg, {0}, loc);
  8759. const auto tMin =
  8760. spvBuilder.createCompositeExtract(floatType, rayDescArg, {1}, loc);
  8761. const auto direction =
  8762. spvBuilder.createCompositeExtract(vecType, rayDescArg, {2}, loc);
  8763. const auto tMax =
  8764. spvBuilder.createCompositeExtract(floatType, rayDescArg, {3}, loc);
  8765. // Copy argument to stage variable
  8766. const auto rayPayloadArgInst =
  8767. declIdMapper.getDeclEvalInfo(rayPayloadArg, rayPayloadArg->getLocStart());
  8768. auto tempLoad =
  8769. spvBuilder.createLoad(rayPayloadArg->getType(), rayPayloadArgInst,
  8770. rayPayloadArg->getLocStart());
  8771. spvBuilder.createStore(rayPayloadStageVar, tempLoad, callExpr->getExprLoc());
  8772. // SPIR-V Instruction
  8773. // void OpTraceNV ( <id> AccelerationStructureNV acStruct,
  8774. // <id> uint Ray Flags,
  8775. // <id> uint Cull Mask,
  8776. // <id> uint SBT Offset,
  8777. // <id> uint SBT Stride,
  8778. // <id> uint Miss Index,
  8779. // <id> vec4 Ray Origin,
  8780. // <id> float Ray Tmin,
  8781. // <id> vec3 Ray Direction,
  8782. // <id> float Ray Tmax,
  8783. // <id> uint RayPayload number)
  8784. llvm::SmallVector<SpirvInstruction *, 8> traceArgs;
  8785. for (int ii = 0; ii < 6; ii++) {
  8786. traceArgs.push_back(doExpr(args[ii]));
  8787. }
  8788. traceArgs.push_back(origin);
  8789. traceArgs.push_back(tMin);
  8790. traceArgs.push_back(direction);
  8791. traceArgs.push_back(tMax);
  8792. traceArgs.push_back(rayPayloadLocInst);
  8793. spvBuilder.createRayTracingOpsNV(spv::Op::OpTraceNV, QualType(), traceArgs,
  8794. callExpr->getExprLoc());
  8795. // Copy arguments back to stage variable
  8796. tempLoad = spvBuilder.createLoad(rayPayloadArg->getType(), rayPayloadStageVar,
  8797. rayPayloadArg->getLocStart());
  8798. spvBuilder.createStore(rayPayloadArgInst, tempLoad, callExpr->getExprLoc());
  8799. return;
  8800. }
  8801. void SpirvEmitter::processDispatchMesh(const CallExpr *callExpr) {
  8802. // HLSL Func - void DispatchMesh(uint ThreadGroupCountX,
  8803. // uint ThreadGroupCountY,
  8804. // uint ThreadGroupCountZ,
  8805. // groupshared <structType> MeshPayload);
  8806. assert(callExpr->getNumArgs() == 4);
  8807. const auto args = callExpr->getArgs();
  8808. const auto loc = callExpr->getExprLoc();
  8809. // 1) create a barrier GroupMemoryBarrierWithGroupSync().
  8810. processIntrinsicMemoryBarrier(callExpr,
  8811. /*isDevice*/ false,
  8812. /*groupSync*/ true,
  8813. /*isAllBarrier*/ false);
  8814. // 2) set TaskCountNV = threadX * threadY * threadZ.
  8815. auto *threadX = doExpr(args[0]);
  8816. auto *threadY = doExpr(args[1]);
  8817. auto *threadZ = doExpr(args[2]);
  8818. auto *var = declIdMapper.getBuiltinVar(spv::BuiltIn::TaskCountNV,
  8819. astContext.UnsignedIntTy, loc);
  8820. auto *taskCount = spvBuilder.createBinaryOp(
  8821. spv::Op::OpIMul, astContext.UnsignedIntTy, threadX,
  8822. spvBuilder.createBinaryOp(spv::Op::OpIMul, astContext.UnsignedIntTy,
  8823. threadY, threadZ, loc),
  8824. loc);
  8825. spvBuilder.createStore(var, taskCount, loc);
  8826. // 3) create PerTaskNV out attribute block and store MeshPayload info.
  8827. const auto *sigPoint =
  8828. hlsl::SigPoint::GetSigPoint(hlsl::DXIL::SigPointKind::MSOut);
  8829. spv::StorageClass sc = spv::StorageClass::Output;
  8830. auto *payloadArg = doExpr(args[3]);
  8831. bool isValid = false;
  8832. if (const auto *implCastExpr = dyn_cast<CastExpr>(args[3])) {
  8833. if (const auto *arg = dyn_cast<DeclRefExpr>(implCastExpr->getSubExpr())) {
  8834. if (const auto *paramDecl = dyn_cast<VarDecl>(arg->getDecl())) {
  8835. if (paramDecl->hasAttr<HLSLGroupSharedAttr>()) {
  8836. isValid = declIdMapper.createPayloadStageVars(
  8837. sigPoint, sc, paramDecl, /*asInput=*/false, paramDecl->getType(),
  8838. "out.var", &payloadArg);
  8839. }
  8840. }
  8841. }
  8842. }
  8843. if (!isValid) {
  8844. emitError("expected groupshared object as argument to DispatchMesh()",
  8845. args[3]->getExprLoc());
  8846. }
  8847. }
  8848. void SpirvEmitter::processMeshOutputCounts(const CallExpr *callExpr) {
  8849. // HLSL Func - void SetMeshOutputCounts(uint numVertices, uint numPrimitives);
  8850. assert(callExpr->getNumArgs() == 2);
  8851. const auto args = callExpr->getArgs();
  8852. const auto loc = callExpr->getExprLoc();
  8853. auto *var = declIdMapper.getBuiltinVar(spv::BuiltIn::PrimitiveCountNV,
  8854. astContext.UnsignedIntTy, loc);
  8855. spvBuilder.createStore(var, doExpr(args[1]), loc);
  8856. }
  8857. SpirvConstant *SpirvEmitter::getValueZero(QualType type) {
  8858. {
  8859. QualType scalarType = {};
  8860. if (isScalarType(type, &scalarType)) {
  8861. if (scalarType->isBooleanType()) {
  8862. return spvBuilder.getConstantBool(false);
  8863. }
  8864. if (scalarType->isIntegerType()) {
  8865. return spvBuilder.getConstantInt(scalarType, llvm::APInt(32, 0));
  8866. }
  8867. if (scalarType->isFloatingType()) {
  8868. return spvBuilder.getConstantFloat(scalarType, llvm::APFloat(0.0f));
  8869. }
  8870. }
  8871. }
  8872. {
  8873. QualType elemType = {};
  8874. uint32_t size = {};
  8875. if (isVectorType(type, &elemType, &size)) {
  8876. return getVecValueZero(elemType, size);
  8877. }
  8878. }
  8879. {
  8880. QualType elemType = {};
  8881. uint32_t rowCount = 0, colCount = 0;
  8882. if (isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  8883. auto *row = getVecValueZero(elemType, colCount);
  8884. llvm::SmallVector<SpirvConstant *, 4> rows((size_t)rowCount, row);
  8885. return spvBuilder.getConstantComposite(type, rows);
  8886. }
  8887. }
  8888. emitError("getting value 0 for type %0 unimplemented", {})
  8889. << type.getAsString();
  8890. return nullptr;
  8891. }
  8892. SpirvConstant *SpirvEmitter::getVecValueZero(QualType elemType, uint32_t size) {
  8893. auto *elemZeroId = getValueZero(elemType);
  8894. if (size == 1)
  8895. return elemZeroId;
  8896. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), elemZeroId);
  8897. const QualType vecType = astContext.getExtVectorType(elemType, size);
  8898. return spvBuilder.getConstantComposite(vecType, elements);
  8899. }
  8900. SpirvConstant *SpirvEmitter::getValueOne(QualType type) {
  8901. {
  8902. QualType scalarType = {};
  8903. if (isScalarType(type, &scalarType)) {
  8904. if (scalarType->isBooleanType()) {
  8905. return spvBuilder.getConstantBool(true);
  8906. }
  8907. if (scalarType->isIntegerType()) {
  8908. return spvBuilder.getConstantInt(scalarType, llvm::APInt(32, 1));
  8909. }
  8910. if (scalarType->isFloatingType()) {
  8911. return spvBuilder.getConstantFloat(scalarType, llvm::APFloat(1.0f));
  8912. }
  8913. }
  8914. }
  8915. {
  8916. QualType elemType = {};
  8917. uint32_t size = {};
  8918. if (isVectorType(type, &elemType, &size)) {
  8919. return getVecValueOne(elemType, size);
  8920. }
  8921. }
  8922. emitError("getting value 1 for type %0 unimplemented", {}) << type;
  8923. return 0;
  8924. }
  8925. SpirvConstant *SpirvEmitter::getVecValueOne(QualType elemType, uint32_t size) {
  8926. auto *elemOne = getValueOne(elemType);
  8927. if (size == 1)
  8928. return elemOne;
  8929. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(size), elemOne);
  8930. const QualType vecType = astContext.getExtVectorType(elemType, size);
  8931. return spvBuilder.getConstantComposite(vecType, elements);
  8932. }
  8933. SpirvConstant *SpirvEmitter::getMatElemValueOne(QualType type) {
  8934. assert(hlsl::IsHLSLMatType(type));
  8935. const auto elemType = hlsl::GetHLSLMatElementType(type);
  8936. uint32_t rowCount = 0, colCount = 0;
  8937. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  8938. if (rowCount == 1 && colCount == 1)
  8939. return getValueOne(elemType);
  8940. if (colCount == 1)
  8941. return getVecValueOne(elemType, rowCount);
  8942. return getVecValueOne(elemType, colCount);
  8943. }
  8944. SpirvConstant *SpirvEmitter::getMaskForBitwidthValue(QualType type) {
  8945. QualType elemType = {};
  8946. uint32_t count = 1;
  8947. if (isScalarType(type, &elemType) || isVectorType(type, &elemType, &count)) {
  8948. const auto bitwidth = getElementSpirvBitwidth(
  8949. astContext, elemType, spirvOptions.enable16BitTypes);
  8950. SpirvConstant *mask = spvBuilder.getConstantInt(
  8951. elemType,
  8952. llvm::APInt(bitwidth, bitwidth - 1, elemType->isSignedIntegerType()));
  8953. if (count == 1)
  8954. return mask;
  8955. const QualType resultType = astContext.getExtVectorType(elemType, count);
  8956. llvm::SmallVector<SpirvConstant *, 4> elements(size_t(count), mask);
  8957. return spvBuilder.getConstantComposite(resultType, elements);
  8958. }
  8959. assert(false && "this method only supports scalars and vectors");
  8960. return nullptr;
  8961. }
  8962. SpirvConstant *SpirvEmitter::translateAPValue(const APValue &value,
  8963. const QualType targetType) {
  8964. SpirvConstant *result = nullptr;
  8965. if (targetType->isBooleanType()) {
  8966. result = spvBuilder.getConstantBool(value.getInt().getBoolValue(),
  8967. isSpecConstantMode);
  8968. } else if (targetType->isIntegerType()) {
  8969. result = translateAPInt(value.getInt(), targetType);
  8970. } else if (targetType->isFloatingType()) {
  8971. result = translateAPFloat(value.getFloat(), targetType);
  8972. } else if (hlsl::IsHLSLVecType(targetType)) {
  8973. const QualType elemType = hlsl::GetHLSLVecElementType(targetType);
  8974. const auto numElements = value.getVectorLength();
  8975. // Special case for vectors of size 1. SPIR-V doesn't support this vector
  8976. // size so we need to translate it to scalar values.
  8977. if (numElements == 1) {
  8978. result = translateAPValue(value.getVectorElt(0), elemType);
  8979. } else {
  8980. llvm::SmallVector<SpirvConstant *, 4> elements;
  8981. for (uint32_t i = 0; i < numElements; ++i) {
  8982. elements.push_back(translateAPValue(value.getVectorElt(i), elemType));
  8983. }
  8984. result = spvBuilder.getConstantComposite(targetType, elements);
  8985. }
  8986. }
  8987. if (result)
  8988. return result;
  8989. emitError("APValue of type %0 unimplemented", {}) << value.getKind();
  8990. value.dump();
  8991. return 0;
  8992. }
  8993. SpirvConstant *SpirvEmitter::translateAPInt(const llvm::APInt &intValue,
  8994. QualType targetType) {
  8995. return spvBuilder.getConstantInt(targetType, intValue, isSpecConstantMode);
  8996. }
  8997. bool SpirvEmitter::isLiteralLargerThan32Bits(const Expr *expr) {
  8998. if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  8999. const bool isSigned = expr->getType()->isSignedIntegerType();
  9000. const llvm::APInt &value = intLiteral->getValue();
  9001. return (isSigned && !value.isSignedIntN(32)) ||
  9002. (!isSigned && !value.isIntN(32));
  9003. }
  9004. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  9005. llvm::APFloat value = floatLiteral->getValue();
  9006. const auto &semantics = value.getSemantics();
  9007. // regular 'half' and 'float' can be represented in 32 bits.
  9008. if (&semantics == &llvm::APFloat::IEEEsingle ||
  9009. &semantics == &llvm::APFloat::IEEEhalf)
  9010. return true;
  9011. // See if 'double' value can be represented in 32 bits without losing info.
  9012. bool losesInfo = false;
  9013. const auto convertStatus =
  9014. value.convert(llvm::APFloat::IEEEsingle,
  9015. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  9016. if (convertStatus != llvm::APFloat::opOK &&
  9017. convertStatus != llvm::APFloat::opInexact)
  9018. return true;
  9019. }
  9020. return false;
  9021. }
  9022. SpirvConstant *SpirvEmitter::tryToEvaluateAsInt32(const llvm::APInt &intValue,
  9023. bool isSigned) {
  9024. if (isSigned && intValue.isSignedIntN(32)) {
  9025. return spvBuilder.getConstantInt(astContext.IntTy, intValue);
  9026. }
  9027. if (!isSigned && intValue.isIntN(32)) {
  9028. return spvBuilder.getConstantInt(astContext.UnsignedIntTy, intValue);
  9029. }
  9030. // Couldn't evaluate as a 32-bit int without losing information.
  9031. return nullptr;
  9032. }
  9033. SpirvConstant *
  9034. SpirvEmitter::tryToEvaluateAsFloat32(const llvm::APFloat &floatValue) {
  9035. const auto &semantics = floatValue.getSemantics();
  9036. // If the given value is already a 32-bit float, there is no need to convert.
  9037. if (&semantics == &llvm::APFloat::IEEEsingle) {
  9038. return spvBuilder.getConstantFloat(astContext.FloatTy, floatValue,
  9039. isSpecConstantMode);
  9040. }
  9041. // Try to see if this literal float can be represented in 32-bit.
  9042. // Since the convert function below may modify the fp value, we call it on a
  9043. // temporary copy.
  9044. llvm::APFloat eval = floatValue;
  9045. bool losesInfo = false;
  9046. const auto convertStatus =
  9047. eval.convert(llvm::APFloat::IEEEsingle,
  9048. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  9049. if (convertStatus == llvm::APFloat::opOK && !losesInfo)
  9050. return spvBuilder.getConstantFloat(astContext.FloatTy,
  9051. llvm::APFloat(eval.convertToFloat()));
  9052. // Couldn't evaluate as a 32-bit float without losing information.
  9053. return nullptr;
  9054. }
  9055. SpirvConstant *SpirvEmitter::translateAPFloat(llvm::APFloat floatValue,
  9056. QualType targetType) {
  9057. return spvBuilder.getConstantFloat(targetType, floatValue,
  9058. isSpecConstantMode);
  9059. }
  9060. SpirvConstant *SpirvEmitter::tryToEvaluateAsConst(const Expr *expr) {
  9061. Expr::EvalResult evalResult;
  9062. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  9063. !evalResult.HasSideEffects) {
  9064. return translateAPValue(evalResult.Val, expr->getType());
  9065. }
  9066. return nullptr;
  9067. }
  9068. hlsl::ShaderModel::Kind SpirvEmitter::getShaderModelKind(StringRef stageName) {
  9069. hlsl::ShaderModel::Kind smk;
  9070. switch (stageName[0]) {
  9071. case 'c':
  9072. switch (stageName[1]) {
  9073. case 'o':
  9074. smk = hlsl::ShaderModel::Kind::Compute;
  9075. break;
  9076. case 'l':
  9077. smk = hlsl::ShaderModel::Kind::ClosestHit;
  9078. break;
  9079. case 'a':
  9080. smk = hlsl::ShaderModel::Kind::Callable;
  9081. break;
  9082. default:
  9083. smk = hlsl::ShaderModel::Kind::Invalid;
  9084. break;
  9085. }
  9086. break;
  9087. case 'v':
  9088. smk = hlsl::ShaderModel::Kind::Vertex;
  9089. break;
  9090. case 'h':
  9091. smk = hlsl::ShaderModel::Kind::Hull;
  9092. break;
  9093. case 'd':
  9094. smk = hlsl::ShaderModel::Kind::Domain;
  9095. break;
  9096. case 'g':
  9097. smk = hlsl::ShaderModel::Kind::Geometry;
  9098. break;
  9099. case 'p':
  9100. smk = hlsl::ShaderModel::Kind::Pixel;
  9101. break;
  9102. case 'r':
  9103. smk = hlsl::ShaderModel::Kind::RayGeneration;
  9104. break;
  9105. case 'i':
  9106. smk = hlsl::ShaderModel::Kind::Intersection;
  9107. break;
  9108. case 'a':
  9109. switch (stageName[1]) {
  9110. case 'm':
  9111. smk = hlsl::ShaderModel::Kind::Amplification;
  9112. break;
  9113. case 'n':
  9114. smk = hlsl::ShaderModel::Kind::AnyHit;
  9115. break;
  9116. }
  9117. break;
  9118. case 'm':
  9119. switch (stageName[1]) {
  9120. case 'e':
  9121. smk = hlsl::ShaderModel::Kind::Mesh;
  9122. break;
  9123. case 'i':
  9124. smk = hlsl::ShaderModel::Kind::Miss;
  9125. break;
  9126. }
  9127. break;
  9128. default:
  9129. smk = hlsl::ShaderModel::Kind::Invalid;
  9130. break;
  9131. }
  9132. if (smk == hlsl::ShaderModel::Kind::Invalid) {
  9133. llvm_unreachable("unknown stage name");
  9134. }
  9135. return smk;
  9136. }
  9137. spv::ExecutionModel
  9138. SpirvEmitter::getSpirvShaderStage(hlsl::ShaderModel::Kind smk) {
  9139. switch (smk) {
  9140. case hlsl::ShaderModel::Kind::Vertex:
  9141. return spv::ExecutionModel::Vertex;
  9142. case hlsl::ShaderModel::Kind::Hull:
  9143. return spv::ExecutionModel::TessellationControl;
  9144. case hlsl::ShaderModel::Kind::Domain:
  9145. return spv::ExecutionModel::TessellationEvaluation;
  9146. case hlsl::ShaderModel::Kind::Geometry:
  9147. return spv::ExecutionModel::Geometry;
  9148. case hlsl::ShaderModel::Kind::Pixel:
  9149. return spv::ExecutionModel::Fragment;
  9150. case hlsl::ShaderModel::Kind::Compute:
  9151. return spv::ExecutionModel::GLCompute;
  9152. case hlsl::ShaderModel::Kind::RayGeneration:
  9153. return spv::ExecutionModel::RayGenerationNV;
  9154. case hlsl::ShaderModel::Kind::Intersection:
  9155. return spv::ExecutionModel::IntersectionNV;
  9156. case hlsl::ShaderModel::Kind::AnyHit:
  9157. return spv::ExecutionModel::AnyHitNV;
  9158. case hlsl::ShaderModel::Kind::ClosestHit:
  9159. return spv::ExecutionModel::ClosestHitNV;
  9160. case hlsl::ShaderModel::Kind::Miss:
  9161. return spv::ExecutionModel::MissNV;
  9162. case hlsl::ShaderModel::Kind::Callable:
  9163. return spv::ExecutionModel::CallableNV;
  9164. case hlsl::ShaderModel::Kind::Mesh:
  9165. return spv::ExecutionModel::MeshNV;
  9166. case hlsl::ShaderModel::Kind::Amplification:
  9167. return spv::ExecutionModel::TaskNV;
  9168. default:
  9169. llvm_unreachable("invalid shader model kind");
  9170. break;
  9171. }
  9172. }
  9173. bool SpirvEmitter::processGeometryShaderAttributes(const FunctionDecl *decl,
  9174. uint32_t *arraySize) {
  9175. bool success = true;
  9176. assert(spvContext.isGS());
  9177. if (auto *vcAttr = decl->getAttr<HLSLMaxVertexCountAttr>()) {
  9178. spvBuilder.addExecutionMode(
  9179. entryFunction, spv::ExecutionMode::OutputVertices,
  9180. {static_cast<uint32_t>(vcAttr->getCount())}, decl->getLocation());
  9181. }
  9182. uint32_t invocations = 1;
  9183. if (auto *instanceAttr = decl->getAttr<HLSLInstanceAttr>()) {
  9184. invocations = static_cast<uint32_t>(instanceAttr->getCount());
  9185. }
  9186. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::Invocations,
  9187. {invocations}, decl->getLocation());
  9188. // Only one primitive type is permitted for the geometry shader.
  9189. bool outPoint = false, outLine = false, outTriangle = false, inPoint = false,
  9190. inLine = false, inTriangle = false, inLineAdj = false,
  9191. inTriangleAdj = false;
  9192. for (const auto *param : decl->params()) {
  9193. // Add an execution mode based on the output stream type. Do not an
  9194. // execution mode more than once.
  9195. if (param->hasAttr<HLSLInOutAttr>()) {
  9196. const auto paramType = param->getType();
  9197. if (hlsl::IsHLSLTriangleStreamType(paramType) && !outTriangle) {
  9198. spvBuilder.addExecutionMode(entryFunction,
  9199. spv::ExecutionMode::OutputTriangleStrip, {},
  9200. param->getLocation());
  9201. outTriangle = true;
  9202. } else if (hlsl::IsHLSLLineStreamType(paramType) && !outLine) {
  9203. spvBuilder.addExecutionMode(entryFunction,
  9204. spv::ExecutionMode::OutputLineStrip, {},
  9205. param->getLocation());
  9206. outLine = true;
  9207. } else if (hlsl::IsHLSLPointStreamType(paramType) && !outPoint) {
  9208. spvBuilder.addExecutionMode(entryFunction,
  9209. spv::ExecutionMode::OutputPoints, {},
  9210. param->getLocation());
  9211. outPoint = true;
  9212. }
  9213. // An output stream parameter will not have the input primitive type
  9214. // attributes, so we can continue to the next parameter.
  9215. continue;
  9216. }
  9217. // Add an execution mode based on the input primitive type. Do not add an
  9218. // execution mode more than once.
  9219. if (param->hasAttr<HLSLPointAttr>() && !inPoint) {
  9220. spvBuilder.addExecutionMode(entryFunction,
  9221. spv::ExecutionMode::InputPoints, {},
  9222. param->getLocation());
  9223. *arraySize = 1;
  9224. inPoint = true;
  9225. } else if (param->hasAttr<HLSLLineAttr>() && !inLine) {
  9226. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::InputLines,
  9227. {}, param->getLocation());
  9228. *arraySize = 2;
  9229. inLine = true;
  9230. } else if (param->hasAttr<HLSLTriangleAttr>() && !inTriangle) {
  9231. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::Triangles,
  9232. {}, param->getLocation());
  9233. *arraySize = 3;
  9234. inTriangle = true;
  9235. } else if (param->hasAttr<HLSLLineAdjAttr>() && !inLineAdj) {
  9236. spvBuilder.addExecutionMode(entryFunction,
  9237. spv::ExecutionMode::InputLinesAdjacency, {},
  9238. param->getLocation());
  9239. *arraySize = 4;
  9240. inLineAdj = true;
  9241. } else if (param->hasAttr<HLSLTriangleAdjAttr>() && !inTriangleAdj) {
  9242. spvBuilder.addExecutionMode(entryFunction,
  9243. spv::ExecutionMode::InputTrianglesAdjacency,
  9244. {}, param->getLocation());
  9245. *arraySize = 6;
  9246. inTriangleAdj = true;
  9247. }
  9248. }
  9249. if (inPoint + inLine + inLineAdj + inTriangle + inTriangleAdj > 1) {
  9250. emitError("only one input primitive type can be specified in the geometry "
  9251. "shader",
  9252. {});
  9253. success = false;
  9254. }
  9255. if (outPoint + outTriangle + outLine > 1) {
  9256. emitError("only one output primitive type can be specified in the geometry "
  9257. "shader",
  9258. {});
  9259. success = false;
  9260. }
  9261. return success;
  9262. }
  9263. void SpirvEmitter::processPixelShaderAttributes(const FunctionDecl *decl) {
  9264. spvBuilder.addExecutionMode(entryFunction,
  9265. spv::ExecutionMode::OriginUpperLeft, {},
  9266. decl->getLocation());
  9267. if (decl->getAttr<HLSLEarlyDepthStencilAttr>()) {
  9268. spvBuilder.addExecutionMode(entryFunction,
  9269. spv::ExecutionMode::EarlyFragmentTests, {},
  9270. decl->getLocation());
  9271. }
  9272. if (decl->getAttr<VKPostDepthCoverageAttr>()) {
  9273. spvBuilder.addExecutionMode(entryFunction,
  9274. spv::ExecutionMode::PostDepthCoverage, {},
  9275. decl->getLocation());
  9276. }
  9277. }
  9278. void SpirvEmitter::processComputeShaderAttributes(const FunctionDecl *decl) {
  9279. // If not explicitly specified, x, y, and z should be defaulted to 1.
  9280. uint32_t x = 1, y = 1, z = 1;
  9281. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  9282. x = static_cast<uint32_t>(numThreadsAttr->getX());
  9283. y = static_cast<uint32_t>(numThreadsAttr->getY());
  9284. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  9285. } else {
  9286. emitError("thread group size [numthreads(x,y,z)] is missing from the "
  9287. "entry-point function",
  9288. decl->getLocation());
  9289. return;
  9290. }
  9291. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::LocalSize,
  9292. {x, y, z}, decl->getLocation());
  9293. }
  9294. bool SpirvEmitter::processTessellationShaderAttributes(
  9295. const FunctionDecl *decl, uint32_t *numOutputControlPoints) {
  9296. assert(spvContext.isHS() || spvContext.isDS());
  9297. using namespace spv;
  9298. if (auto *domain = decl->getAttr<HLSLDomainAttr>()) {
  9299. const auto domainType = domain->getDomainType().lower();
  9300. const ExecutionMode hsExecMode =
  9301. llvm::StringSwitch<ExecutionMode>(domainType)
  9302. .Case("tri", ExecutionMode::Triangles)
  9303. .Case("quad", ExecutionMode::Quads)
  9304. .Case("isoline", ExecutionMode::Isolines)
  9305. .Default(ExecutionMode::Max);
  9306. if (hsExecMode == ExecutionMode::Max) {
  9307. emitError("unknown domain type specified for entry function",
  9308. domain->getLocation());
  9309. return false;
  9310. }
  9311. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9312. decl->getLocation());
  9313. }
  9314. // Early return for domain shaders as domain shaders only takes the 'domain'
  9315. // attribute.
  9316. if (spvContext.isDS())
  9317. return true;
  9318. if (auto *partitioning = decl->getAttr<HLSLPartitioningAttr>()) {
  9319. const auto scheme = partitioning->getScheme().lower();
  9320. if (scheme == "pow2") {
  9321. emitError("pow2 partitioning scheme is not supported since there is no "
  9322. "equivalent in Vulkan",
  9323. partitioning->getLocation());
  9324. return false;
  9325. }
  9326. const ExecutionMode hsExecMode =
  9327. llvm::StringSwitch<ExecutionMode>(scheme)
  9328. .Case("fractional_even", ExecutionMode::SpacingFractionalEven)
  9329. .Case("fractional_odd", ExecutionMode::SpacingFractionalOdd)
  9330. .Case("integer", ExecutionMode::SpacingEqual)
  9331. .Default(ExecutionMode::Max);
  9332. if (hsExecMode == ExecutionMode::Max) {
  9333. emitError("unknown partitioning scheme in hull shader",
  9334. partitioning->getLocation());
  9335. return false;
  9336. }
  9337. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9338. decl->getLocation());
  9339. }
  9340. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  9341. const auto topology = outputTopology->getTopology().lower();
  9342. const ExecutionMode hsExecMode =
  9343. llvm::StringSwitch<ExecutionMode>(topology)
  9344. .Case("point", ExecutionMode::PointMode)
  9345. .Case("triangle_cw", ExecutionMode::VertexOrderCw)
  9346. .Case("triangle_ccw", ExecutionMode::VertexOrderCcw)
  9347. .Default(ExecutionMode::Max);
  9348. // TODO: There is no SPIR-V equivalent for "line" topology. Is it the
  9349. // default?
  9350. if (topology != "line") {
  9351. if (hsExecMode != spv::ExecutionMode::Max) {
  9352. spvBuilder.addExecutionMode(entryFunction, hsExecMode, {},
  9353. decl->getLocation());
  9354. } else {
  9355. emitError("unknown output topology in hull shader",
  9356. outputTopology->getLocation());
  9357. return false;
  9358. }
  9359. }
  9360. }
  9361. if (auto *controlPoints = decl->getAttr<HLSLOutputControlPointsAttr>()) {
  9362. *numOutputControlPoints = controlPoints->getCount();
  9363. spvBuilder.addExecutionMode(entryFunction,
  9364. spv::ExecutionMode::OutputVertices,
  9365. {*numOutputControlPoints}, decl->getLocation());
  9366. }
  9367. if (auto *pcf = decl->getAttr<HLSLPatchConstantFuncAttr>()) {
  9368. llvm::StringRef pcf_name = pcf->getFunctionName();
  9369. for (auto *decl : astContext.getTranslationUnitDecl()->decls())
  9370. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl))
  9371. if (astContext.IsPatchConstantFunctionDecl(funcDecl) &&
  9372. funcDecl->getName() == pcf_name)
  9373. patchConstFunc = funcDecl;
  9374. }
  9375. return true;
  9376. }
  9377. bool SpirvEmitter::emitEntryFunctionWrapperForRayTracing(
  9378. const FunctionDecl *decl, SpirvFunction *entryFuncInstr) {
  9379. // The entry basic block.
  9380. auto *entryLabel = spvBuilder.createBasicBlock();
  9381. spvBuilder.setInsertPoint(entryLabel);
  9382. // Initialize all global variables at the beginning of the wrapper
  9383. for (const VarDecl *varDecl : toInitGloalVars) {
  9384. const auto varInfo =
  9385. declIdMapper.getDeclEvalInfo(varDecl, varDecl->getLocation());
  9386. if (const auto *init = varDecl->getInit()) {
  9387. storeValue(varInfo, loadIfGLValue(init), varDecl->getType(),
  9388. init->getLocStart());
  9389. // Update counter variable associated with global variables
  9390. tryToAssignCounterVar(varDecl, init);
  9391. }
  9392. // If not explicitly initialized, initialize with their zero values if not
  9393. // resource objects
  9394. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  9395. auto *nullValue = spvBuilder.getConstantNull(varDecl->getType());
  9396. spvBuilder.createStore(varInfo, nullValue, varDecl->getLocation());
  9397. }
  9398. }
  9399. // Create temporary variables for holding function call arguments
  9400. llvm::SmallVector<SpirvInstruction *, 4> params;
  9401. llvm::SmallVector<QualType, 4> paramTypes;
  9402. llvm::SmallVector<SpirvInstruction *, 4> stageVars;
  9403. hlsl::ShaderModel::Kind sKind = spvContext.getCurrentShaderModelKind();
  9404. for (uint32_t i = 0; i < decl->getNumParams(); i++) {
  9405. const auto param = decl->getParamDecl(i);
  9406. const auto paramType = param->getType();
  9407. std::string tempVarName = "param.var." + param->getNameAsString();
  9408. auto *tempVar =
  9409. spvBuilder.addFnVar(paramType, param->getLocation(), tempVarName,
  9410. param->hasAttr<HLSLPreciseAttr>());
  9411. SpirvVariable *curStageVar = nullptr;
  9412. params.push_back(tempVar);
  9413. paramTypes.push_back(paramType);
  9414. // Order of arguments is fixed
  9415. // Any-Hit/Closest-Hit : Arg 0 = rayPayload(inout), Arg1 = attribute(in)
  9416. // Miss : Arg 0 = rayPayload(inout)
  9417. // Callable : Arg 0 = callable data(inout)
  9418. // Raygeneration/Intersection : No Args allowed
  9419. if (sKind == hlsl::ShaderModel::Kind::RayGeneration) {
  9420. assert("Raygeneration shaders have no arguments of entry function");
  9421. } else if (sKind == hlsl::ShaderModel::Kind::Intersection) {
  9422. assert("Intersection shaders have no arguments of entry function");
  9423. } else if (sKind == hlsl::ShaderModel::Kind::ClosestHit ||
  9424. sKind == hlsl::ShaderModel::Kind::AnyHit) {
  9425. // Generate rayPayloadInNV and hitAttributeNV stage variables
  9426. if (i == 0) {
  9427. // First argument is always rayPayload
  9428. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9429. spv::StorageClass::IncomingRayPayloadNV, param);
  9430. currentRayPayload = curStageVar;
  9431. } else {
  9432. // Second argument is always attribute
  9433. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9434. spv::StorageClass::HitAttributeNV, param);
  9435. }
  9436. } else if (sKind == hlsl::ShaderModel::Kind::Miss) {
  9437. // Generate rayPayloadInNV stage variable
  9438. // First and only argument is rayPayload
  9439. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9440. spv::StorageClass::IncomingRayPayloadNV, param);
  9441. } else if (sKind == hlsl::ShaderModel::Kind::Callable) {
  9442. curStageVar = declIdMapper.createRayTracingNVStageVar(
  9443. spv::StorageClass::IncomingCallableDataNV, param);
  9444. }
  9445. if (curStageVar != nullptr) {
  9446. stageVars.push_back(curStageVar);
  9447. // Copy data to temporary
  9448. auto *tempLoadInst =
  9449. spvBuilder.createLoad(paramType, curStageVar, param->getLocation());
  9450. spvBuilder.createStore(tempVar, tempLoadInst, param->getLocation());
  9451. }
  9452. }
  9453. // Call the original entry function
  9454. const QualType retType = decl->getReturnType();
  9455. spvBuilder.createFunctionCall(retType, entryFuncInstr, params,
  9456. decl->getLocStart());
  9457. // Write certain output variables back
  9458. if (sKind == hlsl::ShaderModel::Kind::ClosestHit ||
  9459. sKind == hlsl::ShaderModel::Kind::AnyHit ||
  9460. sKind == hlsl::ShaderModel::Kind::Miss ||
  9461. sKind == hlsl::ShaderModel::Kind::Callable) {
  9462. // Write back results to IncomingRayPayloadNV/IncomingCallableDataNV
  9463. auto *tempLoad = spvBuilder.createLoad(paramTypes[0], params[0],
  9464. decl->getBody()->getLocEnd());
  9465. spvBuilder.createStore(stageVars[0], tempLoad,
  9466. decl->getBody()->getLocEnd());
  9467. }
  9468. spvBuilder.createReturn(decl->getBody()->getLocEnd());
  9469. spvBuilder.endFunction();
  9470. return true;
  9471. }
  9472. bool SpirvEmitter::processMeshOrAmplificationShaderAttributes(
  9473. const FunctionDecl *decl, uint32_t *outVerticesArraySize) {
  9474. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  9475. uint32_t x, y, z;
  9476. x = static_cast<uint32_t>(numThreadsAttr->getX());
  9477. y = static_cast<uint32_t>(numThreadsAttr->getY());
  9478. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  9479. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::LocalSize,
  9480. {x, y, z}, decl->getLocation());
  9481. }
  9482. // Early return for amplification shaders as they only take the 'numthreads'
  9483. // attribute.
  9484. if (spvContext.isAS())
  9485. return true;
  9486. spv::ExecutionMode outputPrimitive = spv::ExecutionMode::Max;
  9487. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  9488. const auto topology = outputTopology->getTopology().lower();
  9489. outputPrimitive =
  9490. llvm::StringSwitch<spv::ExecutionMode>(topology)
  9491. .Case("point", spv::ExecutionMode::OutputPoints)
  9492. .Case("line", spv::ExecutionMode::OutputLinesNV)
  9493. .Case("triangle", spv::ExecutionMode::OutputTrianglesNV);
  9494. if (outputPrimitive != spv::ExecutionMode::Max) {
  9495. spvBuilder.addExecutionMode(entryFunction, outputPrimitive, {},
  9496. decl->getLocation());
  9497. } else {
  9498. emitError("unknown output topology in mesh shader",
  9499. outputTopology->getLocation());
  9500. return false;
  9501. }
  9502. }
  9503. uint32_t numVertices = 0;
  9504. uint32_t numIndices = 0;
  9505. uint32_t numPrimitives = 0;
  9506. bool payloadDeclSeen = false;
  9507. for (uint32_t i = 0; i < decl->getNumParams(); i++) {
  9508. const auto param = decl->getParamDecl(i);
  9509. const auto paramType = param->getType();
  9510. const auto paramLoc = param->getLocation();
  9511. if (param->hasAttr<HLSLVerticesAttr>() ||
  9512. param->hasAttr<HLSLIndicesAttr>() ||
  9513. param->hasAttr<HLSLPrimitivesAttr>()) {
  9514. uint32_t arraySize = 0;
  9515. if (const auto *arrayType =
  9516. astContext.getAsConstantArrayType(paramType)) {
  9517. const auto eleType =
  9518. arrayType->getElementType()->getCanonicalTypeUnqualified();
  9519. if (param->hasAttr<HLSLIndicesAttr>()) {
  9520. switch (outputPrimitive) {
  9521. case spv::ExecutionMode::OutputPoints:
  9522. if (eleType != astContext.UnsignedIntTy) {
  9523. emitError("expected 1D array of uint type", paramLoc);
  9524. return false;
  9525. }
  9526. break;
  9527. case spv::ExecutionMode::OutputLinesNV: {
  9528. QualType baseType;
  9529. uint32_t length;
  9530. if (!isVectorType(eleType, &baseType, &length) ||
  9531. baseType != astContext.UnsignedIntTy || length != 2) {
  9532. emitError("expected 1D array of uint2 type", paramLoc);
  9533. return false;
  9534. }
  9535. break;
  9536. }
  9537. case spv::ExecutionMode::OutputTrianglesNV: {
  9538. QualType baseType;
  9539. uint32_t length;
  9540. if (!isVectorType(eleType, &baseType, &length) ||
  9541. baseType != astContext.UnsignedIntTy || length != 3) {
  9542. emitError("expected 1D array of uint3 type", paramLoc);
  9543. return false;
  9544. }
  9545. break;
  9546. }
  9547. default:
  9548. assert(false && "unexpected spirv execution mode");
  9549. }
  9550. } else if (!eleType->isStructureType()) {
  9551. // vertices/primitives objects
  9552. emitError("expected 1D array of struct type", paramLoc);
  9553. return false;
  9554. }
  9555. arraySize = static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  9556. } else {
  9557. emitError("expected 1D array of indices/vertices/primitives object",
  9558. paramLoc);
  9559. return false;
  9560. }
  9561. if (param->hasAttr<HLSLVerticesAttr>()) {
  9562. if (numVertices != 0) {
  9563. emitError("only one object with 'vertices' modifier is allowed",
  9564. paramLoc);
  9565. return false;
  9566. }
  9567. numVertices = arraySize;
  9568. } else if (param->hasAttr<HLSLIndicesAttr>()) {
  9569. if (numIndices != 0) {
  9570. emitError("only one object with 'indices' modifier is allowed",
  9571. paramLoc);
  9572. return false;
  9573. }
  9574. numIndices = arraySize;
  9575. } else if (param->hasAttr<HLSLPrimitivesAttr>()) {
  9576. if (numPrimitives != 0) {
  9577. emitError("only one object with 'primitives' modifier is allowed",
  9578. paramLoc);
  9579. return false;
  9580. }
  9581. numPrimitives = arraySize;
  9582. }
  9583. } else if (param->hasAttr<HLSLPayloadAttr>()) {
  9584. if (payloadDeclSeen) {
  9585. emitError("only one object with 'payload' modifier is allowed",
  9586. paramLoc);
  9587. return false;
  9588. }
  9589. payloadDeclSeen = true;
  9590. if (!paramType->isStructureType()) {
  9591. emitError("expected payload of struct type", paramLoc);
  9592. return false;
  9593. }
  9594. }
  9595. }
  9596. // Vertex attribute array is a mandatory param to mesh entry function.
  9597. if (numVertices != 0) {
  9598. *outVerticesArraySize = numVertices;
  9599. spvBuilder.addExecutionMode(
  9600. entryFunction, spv::ExecutionMode::OutputVertices,
  9601. {static_cast<uint32_t>(numVertices)}, decl->getLocation());
  9602. } else {
  9603. emitError("expected vertices object declaration", decl->getLocation());
  9604. return false;
  9605. }
  9606. // Vertex indices array is a mandatory param to mesh entry function.
  9607. if (numIndices != 0) {
  9608. spvBuilder.addExecutionMode(
  9609. entryFunction, spv::ExecutionMode::OutputPrimitivesNV,
  9610. {static_cast<uint32_t>(numIndices)}, decl->getLocation());
  9611. // Primitive attribute array is an optional param to mesh entry function,
  9612. // but the array size should match the indices array.
  9613. if (numPrimitives != 0 && numPrimitives != numIndices) {
  9614. emitError("array size of primitives object should match 'indices' object",
  9615. decl->getLocation());
  9616. return false;
  9617. }
  9618. } else {
  9619. emitError("expected indices object declaration", decl->getLocation());
  9620. return false;
  9621. }
  9622. return true;
  9623. }
  9624. bool SpirvEmitter::emitEntryFunctionWrapper(const FunctionDecl *decl,
  9625. SpirvFunction *entryFuncInstr) {
  9626. // HS specific attributes
  9627. uint32_t numOutputControlPoints = 0;
  9628. SpirvInstruction *outputControlPointIdVal =
  9629. nullptr; // SV_OutputControlPointID value
  9630. SpirvInstruction *primitiveIdVar = nullptr; // SV_PrimitiveID variable
  9631. SpirvInstruction *viewIdVar = nullptr; // SV_ViewID variable
  9632. SpirvInstruction *hullMainInputPatchParam =
  9633. nullptr; // Temporary parameter for InputPatch<>
  9634. // The array size of per-vertex input/output variables
  9635. // Used by HS/DS/GS for the additional arrayness, zero means not an array.
  9636. uint32_t inputArraySize = 0;
  9637. uint32_t outputArraySize = 0;
  9638. // The wrapper entry function surely does not have pre-assigned <result-id>
  9639. // for it like other functions that got added to the work queue following
  9640. // function calls. And the wrapper is the entry function.
  9641. entryFunction =
  9642. spvBuilder.beginFunction(astContext.VoidTy, /* param QualTypes */ {},
  9643. decl->getLocStart(), decl->getName());
  9644. // Note this should happen before using declIdMapper for other tasks.
  9645. declIdMapper.setEntryFunction(entryFunction);
  9646. // Set entryFunction for current entry point.
  9647. auto iter = functionInfoMap.find(decl);
  9648. assert(iter != functionInfoMap.end());
  9649. auto &entryInfo = iter->second;
  9650. assert(entryInfo->isEntryFunction);
  9651. entryInfo->entryFunction = entryFunction;
  9652. if (spvContext.isRay()) {
  9653. return emitEntryFunctionWrapperForRayTracing(decl, entryFuncInstr);
  9654. }
  9655. // Handle attributes specific to each shader stage
  9656. if (spvContext.isPS()) {
  9657. processPixelShaderAttributes(decl);
  9658. } else if (spvContext.isCS()) {
  9659. processComputeShaderAttributes(decl);
  9660. } else if (spvContext.isHS()) {
  9661. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  9662. return false;
  9663. // The input array size for HS is specified in the InputPatch parameter.
  9664. for (const auto *param : decl->params())
  9665. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  9666. inputArraySize = hlsl::GetHLSLInputPatchCount(param->getType());
  9667. break;
  9668. }
  9669. outputArraySize = numOutputControlPoints;
  9670. } else if (spvContext.isDS()) {
  9671. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  9672. return false;
  9673. // The input array size for HS is specified in the OutputPatch parameter.
  9674. for (const auto *param : decl->params())
  9675. if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  9676. inputArraySize = hlsl::GetHLSLOutputPatchCount(param->getType());
  9677. break;
  9678. }
  9679. // The per-vertex output of DS is not an array.
  9680. } else if (spvContext.isGS()) {
  9681. if (!processGeometryShaderAttributes(decl, &inputArraySize))
  9682. return false;
  9683. // The per-vertex output of GS is not an array.
  9684. } else if (spvContext.isMS() || spvContext.isAS()) {
  9685. if (!processMeshOrAmplificationShaderAttributes(decl, &outputArraySize))
  9686. return false;
  9687. }
  9688. // Go through all parameters and record the declaration of SV_ClipDistance
  9689. // and SV_CullDistance. We need to do this extra step because in HLSL we
  9690. // can declare multiple SV_ClipDistance/SV_CullDistance variables of float
  9691. // or vector of float types, but we can only have one single float array
  9692. // for the ClipDistance/CullDistance builtin. So we need to group all
  9693. // SV_ClipDistance/SV_CullDistance variables into one float array, thus we
  9694. // need to calculate the total size of the array and the offset of each
  9695. // variable within that array.
  9696. // Also go through all parameters to record the semantic strings provided for
  9697. // the builtins in gl_PerVertex.
  9698. for (const auto *param : decl->params()) {
  9699. if (canActAsInParmVar(param))
  9700. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, true))
  9701. return false;
  9702. if (canActAsOutParmVar(param))
  9703. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, false))
  9704. return false;
  9705. }
  9706. // Also consider the SV_ClipDistance/SV_CullDistance in the return type
  9707. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(decl, false))
  9708. return false;
  9709. // Calculate the total size of the ClipDistance/CullDistance array and the
  9710. // offset of SV_ClipDistance/SV_CullDistance variables within the array.
  9711. declIdMapper.glPerVertex.calculateClipCullDistanceArraySize();
  9712. if (!spvContext.isCS() && !spvContext.isAS()) {
  9713. // Generate stand-alone builtins of Position, ClipDistance, and
  9714. // CullDistance, which belongs to gl_PerVertex.
  9715. declIdMapper.glPerVertex.generateVars(inputArraySize, outputArraySize);
  9716. }
  9717. // The entry basic block.
  9718. auto *entryLabel = spvBuilder.createBasicBlock();
  9719. spvBuilder.setInsertPoint(entryLabel);
  9720. // Initialize all global variables at the beginning of the wrapper
  9721. for (const VarDecl *varDecl : toInitGloalVars) {
  9722. // SPIR-V does not have string variables
  9723. if (isStringType(varDecl->getType()))
  9724. continue;
  9725. const auto varInfo =
  9726. declIdMapper.getDeclEvalInfo(varDecl, varDecl->getLocation());
  9727. if (const auto *init = varDecl->getInit()) {
  9728. storeValue(varInfo, loadIfGLValue(init), varDecl->getType(),
  9729. init->getLocStart());
  9730. // Update counter variable associated with global variables
  9731. tryToAssignCounterVar(varDecl, init);
  9732. }
  9733. // If not explicitly initialized, initialize with their zero values if not
  9734. // resource objects
  9735. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  9736. auto *nullValue = spvBuilder.getConstantNull(varDecl->getType());
  9737. spvBuilder.createStore(varInfo, nullValue, varDecl->getLocation());
  9738. }
  9739. }
  9740. // Create temporary variables for holding function call arguments
  9741. llvm::SmallVector<SpirvInstruction *, 4> params;
  9742. for (const auto *param : decl->params()) {
  9743. const auto paramType = param->getType();
  9744. std::string tempVarName = "param.var." + param->getNameAsString();
  9745. auto *tempVar =
  9746. spvBuilder.addFnVar(paramType, param->getLocation(), tempVarName,
  9747. param->hasAttr<HLSLPreciseAttr>());
  9748. params.push_back(tempVar);
  9749. // Create the stage input variable for parameter not marked as pure out and
  9750. // initialize the corresponding temporary variable
  9751. // Also do not create input variables for output stream objects of geometry
  9752. // shaders (e.g. TriangleStream) which are required to be marked as 'inout'.
  9753. if (canActAsInParmVar(param)) {
  9754. if (spvContext.isHS() && hlsl::IsHLSLInputPatchType(paramType)) {
  9755. // Record the temporary variable holding InputPatch. It may be used
  9756. // later in the patch constant function.
  9757. hullMainInputPatchParam = tempVar;
  9758. }
  9759. SpirvInstruction *loadedValue = nullptr;
  9760. if (!declIdMapper.createStageInputVar(param, &loadedValue, false))
  9761. return false;
  9762. // Only initialize the temporary variable if the parameter is indeed used.
  9763. if (param->isUsed()) {
  9764. spvBuilder.createStore(tempVar, loadedValue, param->getLocation());
  9765. }
  9766. // Record the temporary variable holding SV_OutputControlPointID,
  9767. // SV_PrimitiveID, and SV_ViewID. It may be used later in the patch
  9768. // constant function.
  9769. if (hasSemantic(param, hlsl::DXIL::SemanticKind::OutputControlPointID))
  9770. outputControlPointIdVal = loadedValue;
  9771. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID))
  9772. primitiveIdVar = tempVar;
  9773. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID))
  9774. viewIdVar = tempVar;
  9775. }
  9776. }
  9777. // Call the original entry function
  9778. const QualType retType = decl->getReturnType();
  9779. auto *retVal = spvBuilder.createFunctionCall(retType, entryFuncInstr, params,
  9780. decl->getLocStart());
  9781. // Create and write stage output variables for return value. Special case for
  9782. // Hull shaders since they operate differently in 2 ways:
  9783. // 1- Their return value is in fact an array and each invocation should write
  9784. // to the proper offset in the array.
  9785. // 2- The patch constant function must be called *once* after all invocations
  9786. // of the main entry point function is done.
  9787. if (spvContext.isHS()) {
  9788. // Create stage output variables out of the return type.
  9789. if (!declIdMapper.createStageOutputVar(decl, numOutputControlPoints,
  9790. outputControlPointIdVal, retVal))
  9791. return false;
  9792. if (!processHSEntryPointOutputAndPCF(
  9793. decl, retType, retVal, numOutputControlPoints,
  9794. outputControlPointIdVal, primitiveIdVar, viewIdVar,
  9795. hullMainInputPatchParam))
  9796. return false;
  9797. } else {
  9798. if (!declIdMapper.createStageOutputVar(decl, retVal, /*forPCF*/ false))
  9799. return false;
  9800. }
  9801. // Create and write stage output variables for parameters marked as
  9802. // out/inout
  9803. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  9804. const auto *param = decl->getParamDecl(i);
  9805. if (canActAsOutParmVar(param)) {
  9806. // Load the value from the parameter after function call
  9807. SpirvInstruction *loadedParam = nullptr;
  9808. // No need to write back the value if the parameter is not used at all in
  9809. // the original entry function.
  9810. //
  9811. // Write back of stage output variables in GS is manually controlled by
  9812. // .Append() intrinsic method. No need to load the parameter since we
  9813. // won't need to write back here.
  9814. if (param->isUsed() && !spvContext.isGS())
  9815. loadedParam = spvBuilder.createLoad(param->getType(), params[i],
  9816. param->getLocStart());
  9817. if (!declIdMapper.createStageOutputVar(param, loadedParam, false))
  9818. return false;
  9819. }
  9820. }
  9821. // For wrapper of entry point, it is better not to specify SourceLocation
  9822. // for return statement, because it is not the location of the actual
  9823. // return and emitting the location of the end of entry function makes
  9824. // us confused. It is better to emit debug line just before OpFunctionEnd.
  9825. spvBuilder.createReturn(/* SourceLocation */ {});
  9826. spvBuilder.endFunction();
  9827. // For Hull shaders, there is no explicit call to the PCF in the HLSL source.
  9828. // We should invoke a translation of the PCF manually.
  9829. if (spvContext.isHS())
  9830. doDecl(patchConstFunc);
  9831. return true;
  9832. }
  9833. bool SpirvEmitter::processHSEntryPointOutputAndPCF(
  9834. const FunctionDecl *hullMainFuncDecl, QualType retType,
  9835. SpirvInstruction *retVal, uint32_t numOutputControlPoints,
  9836. SpirvInstruction *outputControlPointId, SpirvInstruction *primitiveId,
  9837. SpirvInstruction *viewId, SpirvInstruction *hullMainInputPatch) {
  9838. // This method may only be called for Hull shaders.
  9839. assert(spvContext.isHS());
  9840. auto loc = hullMainFuncDecl->getLocation();
  9841. auto locEnd = hullMainFuncDecl->getLocEnd();
  9842. // For Hull shaders, the real output is an array of size
  9843. // numOutputControlPoints. The results of the main should be written to the
  9844. // correct offset in the array (based on InvocationID).
  9845. if (!numOutputControlPoints) {
  9846. emitError("number of output control points cannot be zero", loc);
  9847. return false;
  9848. }
  9849. // TODO: We should be able to handle cases where the SV_OutputControlPointID
  9850. // is not provided.
  9851. if (!outputControlPointId) {
  9852. emitError(
  9853. "SV_OutputControlPointID semantic must be provided in hull shader",
  9854. loc);
  9855. return false;
  9856. }
  9857. if (!patchConstFunc) {
  9858. emitError("patch constant function not defined in hull shader", loc);
  9859. return false;
  9860. }
  9861. SpirvInstruction *hullMainOutputPatch = nullptr;
  9862. // If the patch constant function (PCF) takes the result of the Hull main
  9863. // entry point, create a temporary function-scope variable and write the
  9864. // results to it, so it can be passed to the PCF.
  9865. if (patchConstFuncTakesHullOutputPatch(patchConstFunc)) {
  9866. const QualType hullMainRetType = astContext.getConstantArrayType(
  9867. retType, llvm::APInt(32, numOutputControlPoints),
  9868. clang::ArrayType::Normal, 0);
  9869. hullMainOutputPatch =
  9870. spvBuilder.addFnVar(hullMainRetType, locEnd, "temp.var.hullMainRetVal");
  9871. auto *tempLocation = spvBuilder.createAccessChain(
  9872. retType, hullMainOutputPatch, {outputControlPointId}, locEnd);
  9873. spvBuilder.createStore(tempLocation, retVal, locEnd);
  9874. }
  9875. // Now create a barrier before calling the Patch Constant Function (PCF).
  9876. // Flags are:
  9877. // Execution Barrier scope = Workgroup (2)
  9878. // Memory Barrier scope = Invocation (4)
  9879. // Memory Semantics Barrier scope = None (0)
  9880. spvBuilder.createBarrier(spv::Scope::Invocation,
  9881. spv::MemorySemanticsMask::MaskNone,
  9882. spv::Scope::Workgroup, {});
  9883. // The PCF should be called only once. Therefore, we check the invocationID,
  9884. // and we only allow ID 0 to call the PCF.
  9885. auto *condition = spvBuilder.createBinaryOp(
  9886. spv::Op::OpIEqual, astContext.BoolTy, outputControlPointId,
  9887. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0)),
  9888. loc);
  9889. auto *thenBB = spvBuilder.createBasicBlock("if.true");
  9890. auto *mergeBB = spvBuilder.createBasicBlock("if.merge");
  9891. spvBuilder.createConditionalBranch(condition, thenBB, mergeBB, loc, mergeBB);
  9892. spvBuilder.addSuccessor(thenBB);
  9893. spvBuilder.addSuccessor(mergeBB);
  9894. spvBuilder.setMergeTarget(mergeBB);
  9895. spvBuilder.setInsertPoint(thenBB);
  9896. // Call the PCF. Since the function is not explicitly called, we must first
  9897. // register an ID for it.
  9898. SpirvFunction *pcfId = declIdMapper.getOrRegisterFn(patchConstFunc);
  9899. const QualType pcfRetType = patchConstFunc->getReturnType();
  9900. std::vector<SpirvInstruction *> pcfParams;
  9901. // A lambda for creating a stage input variable and its associated temporary
  9902. // variable for function call. Also initializes the temporary variable using
  9903. // the contents loaded from the stage input variable. Returns the <result-id>
  9904. // of the temporary variable.
  9905. const auto createParmVarAndInitFromStageInputVar =
  9906. [this](const ParmVarDecl *param) {
  9907. const QualType type = param->getType();
  9908. std::string tempVarName = "param.var." + param->getNameAsString();
  9909. auto paramLoc = param->getLocation();
  9910. auto *tempVar = spvBuilder.addFnVar(type, paramLoc, tempVarName,
  9911. param->hasAttr<HLSLPreciseAttr>());
  9912. SpirvInstruction *loadedValue = nullptr;
  9913. declIdMapper.createStageInputVar(param, &loadedValue, /*forPCF*/ true);
  9914. spvBuilder.createStore(tempVar, loadedValue, paramLoc);
  9915. return tempVar;
  9916. };
  9917. for (const auto *param : patchConstFunc->parameters()) {
  9918. // Note: According to the HLSL reference, the PCF takes an InputPatch of
  9919. // ControlPoints as well as the PatchID (PrimitiveID). This does not
  9920. // necessarily mean that they are present. There is also no requirement
  9921. // for the order of parameters passed to PCF.
  9922. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  9923. pcfParams.push_back(hullMainInputPatch);
  9924. } else if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  9925. pcfParams.push_back(hullMainOutputPatch);
  9926. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID)) {
  9927. if (!primitiveId) {
  9928. primitiveId = createParmVarAndInitFromStageInputVar(param);
  9929. }
  9930. pcfParams.push_back(primitiveId);
  9931. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID)) {
  9932. if (!viewId) {
  9933. viewId = createParmVarAndInitFromStageInputVar(param);
  9934. }
  9935. pcfParams.push_back(viewId);
  9936. } else {
  9937. emitError("patch constant function parameter '%0' unknown",
  9938. param->getLocation())
  9939. << param->getName();
  9940. }
  9941. }
  9942. auto *pcfResultId = spvBuilder.createFunctionCall(
  9943. pcfRetType, pcfId, {pcfParams}, hullMainFuncDecl->getLocStart());
  9944. if (!declIdMapper.createStageOutputVar(patchConstFunc, pcfResultId,
  9945. /*forPCF*/ true))
  9946. return false;
  9947. spvBuilder.createBranch(mergeBB, locEnd);
  9948. spvBuilder.addSuccessor(mergeBB);
  9949. spvBuilder.setInsertPoint(mergeBB);
  9950. return true;
  9951. }
  9952. bool SpirvEmitter::allSwitchCasesAreIntegerLiterals(const Stmt *root) {
  9953. if (!root)
  9954. return false;
  9955. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  9956. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  9957. if (!caseStmt && !compoundStmt)
  9958. return true;
  9959. if (caseStmt) {
  9960. const Expr *caseExpr = caseStmt->getLHS();
  9961. return caseExpr && caseExpr->isEvaluatable(astContext);
  9962. }
  9963. // Recurse down if facing a compound statement.
  9964. for (auto *st : compoundStmt->body())
  9965. if (!allSwitchCasesAreIntegerLiterals(st))
  9966. return false;
  9967. return true;
  9968. }
  9969. void SpirvEmitter::discoverAllCaseStmtInSwitchStmt(
  9970. const Stmt *root, SpirvBasicBlock **defaultBB,
  9971. std::vector<std::pair<uint32_t, SpirvBasicBlock *>> *targets) {
  9972. if (!root)
  9973. return;
  9974. // A switch case can only appear in DefaultStmt, CaseStmt, or
  9975. // CompoundStmt. For the rest, we can just return.
  9976. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  9977. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  9978. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  9979. if (!defaultStmt && !caseStmt && !compoundStmt)
  9980. return;
  9981. // Recurse down if facing a compound statement.
  9982. if (compoundStmt) {
  9983. for (auto *st : compoundStmt->body())
  9984. discoverAllCaseStmtInSwitchStmt(st, defaultBB, targets);
  9985. return;
  9986. }
  9987. std::string caseLabel;
  9988. uint32_t caseValue = 0;
  9989. if (defaultStmt) {
  9990. // This is the default branch.
  9991. caseLabel = "switch.default";
  9992. } else if (caseStmt) {
  9993. // This is a non-default case.
  9994. // When using OpSwitch, we only allow integer literal cases. e.g:
  9995. // case <literal_integer>: {...; break;}
  9996. const Expr *caseExpr = caseStmt->getLHS();
  9997. assert(caseExpr && caseExpr->isEvaluatable(astContext));
  9998. auto bitWidth = astContext.getIntWidth(caseExpr->getType());
  9999. if (bitWidth != 32)
  10000. emitError(
  10001. "non-32bit integer case value in switch statement unimplemented",
  10002. caseExpr->getExprLoc());
  10003. Expr::EvalResult evalResult;
  10004. caseExpr->EvaluateAsRValue(evalResult, astContext);
  10005. const int64_t value = evalResult.Val.getInt().getSExtValue();
  10006. caseValue = static_cast<uint32_t>(value);
  10007. caseLabel = "switch." + std::string(value < 0 ? "n" : "") +
  10008. llvm::itostr(std::abs(value));
  10009. }
  10010. auto *caseBB = spvBuilder.createBasicBlock(caseLabel);
  10011. spvBuilder.addSuccessor(caseBB);
  10012. stmtBasicBlock[root] = caseBB;
  10013. // Add all cases to the 'targets' vector.
  10014. if (caseStmt)
  10015. targets->emplace_back(caseValue, caseBB);
  10016. // The default label is not part of the 'targets' vector that is passed
  10017. // to the OpSwitch instruction.
  10018. // If default statement was discovered, return its label via defaultBB.
  10019. if (defaultStmt)
  10020. *defaultBB = caseBB;
  10021. // Process cases nested in other cases. It happens when we have fall through
  10022. // cases. For example:
  10023. // case 1: case 2: ...; break;
  10024. // will result in the CaseSmt for case 2 nested in the one for case 1.
  10025. discoverAllCaseStmtInSwitchStmt(caseStmt ? caseStmt->getSubStmt()
  10026. : defaultStmt->getSubStmt(),
  10027. defaultBB, targets);
  10028. }
  10029. void SpirvEmitter::flattenSwitchStmtAST(const Stmt *root,
  10030. std::vector<const Stmt *> *flatSwitch) {
  10031. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  10032. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  10033. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  10034. if (!compoundStmt) {
  10035. flatSwitch->push_back(root);
  10036. }
  10037. if (compoundStmt) {
  10038. for (const auto *st : compoundStmt->body())
  10039. flattenSwitchStmtAST(st, flatSwitch);
  10040. } else if (caseStmt) {
  10041. flattenSwitchStmtAST(caseStmt->getSubStmt(), flatSwitch);
  10042. } else if (defaultStmt) {
  10043. flattenSwitchStmtAST(defaultStmt->getSubStmt(), flatSwitch);
  10044. }
  10045. }
  10046. void SpirvEmitter::processCaseStmtOrDefaultStmt(const Stmt *stmt) {
  10047. auto *caseStmt = dyn_cast<CaseStmt>(stmt);
  10048. auto *defaultStmt = dyn_cast<DefaultStmt>(stmt);
  10049. assert(caseStmt || defaultStmt);
  10050. auto *caseBB = stmtBasicBlock[stmt];
  10051. if (!spvBuilder.isCurrentBasicBlockTerminated()) {
  10052. // We are about to handle the case passed in as parameter. If the current
  10053. // basic block is not terminated, it means the previous case is a fall
  10054. // through case. We need to link it to the case to be processed.
  10055. spvBuilder.createBranch(caseBB, stmt->getLocStart());
  10056. spvBuilder.addSuccessor(caseBB);
  10057. }
  10058. spvBuilder.setInsertPoint(caseBB);
  10059. doStmt(caseStmt ? caseStmt->getSubStmt() : defaultStmt->getSubStmt());
  10060. }
  10061. void SpirvEmitter::processSwitchStmtUsingSpirvOpSwitch(
  10062. const SwitchStmt *switchStmt) {
  10063. const SourceLocation srcLoc = switchStmt->getSwitchLoc();
  10064. // First handle the condition variable DeclStmt if one exists.
  10065. // For example: handle 'int a = b' in the following:
  10066. // switch (int a = b) {...}
  10067. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  10068. doDeclStmt(condVarDeclStmt);
  10069. auto *selector = doExpr(switchStmt->getCond());
  10070. // We need a merge block regardless of the number of switch cases.
  10071. // Since OpSwitch always requires a default label, if the switch statement
  10072. // does not have a default branch, we use the merge block as the default
  10073. // target.
  10074. auto *mergeBB = spvBuilder.createBasicBlock("switch.merge");
  10075. spvBuilder.setMergeTarget(mergeBB);
  10076. breakStack.push(mergeBB);
  10077. auto *defaultBB = mergeBB;
  10078. // (literal, labelId) pairs to pass to the OpSwitch instruction.
  10079. std::vector<std::pair<uint32_t, SpirvBasicBlock *>> targets;
  10080. discoverAllCaseStmtInSwitchStmt(switchStmt->getBody(), &defaultBB, &targets);
  10081. // Create the OpSelectionMerge and OpSwitch.
  10082. spvBuilder.createSwitch(mergeBB, selector, defaultBB, targets, srcLoc);
  10083. // Handle the switch body.
  10084. doStmt(switchStmt->getBody());
  10085. if (!spvBuilder.isCurrentBasicBlockTerminated())
  10086. spvBuilder.createBranch(mergeBB, switchStmt->getLocEnd());
  10087. spvBuilder.setInsertPoint(mergeBB);
  10088. breakStack.pop();
  10089. }
  10090. void SpirvEmitter::processSwitchStmtUsingIfStmts(const SwitchStmt *switchStmt) {
  10091. std::vector<const Stmt *> flatSwitch;
  10092. flattenSwitchStmtAST(switchStmt->getBody(), &flatSwitch);
  10093. // First handle the condition variable DeclStmt if one exists.
  10094. // For example: handle 'int a = b' in the following:
  10095. // switch (int a = b) {...}
  10096. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  10097. doDeclStmt(condVarDeclStmt);
  10098. // Figure out the indexes of CaseStmts (and DefaultStmt if it exists) in
  10099. // the flattened switch AST.
  10100. // For instance, for the following flat vector:
  10101. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  10102. // |Case1|Stmt1|Case2|Stmt2|Break|Case3|Case4|Stmt4|Break|Default|Stmt5|
  10103. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  10104. // The indexes are: {0, 2, 5, 6, 9}
  10105. std::vector<uint32_t> caseStmtLocs;
  10106. for (uint32_t i = 0; i < flatSwitch.size(); ++i)
  10107. if (isa<CaseStmt>(flatSwitch[i]) || isa<DefaultStmt>(flatSwitch[i]))
  10108. caseStmtLocs.push_back(i);
  10109. IfStmt *prevIfStmt = nullptr;
  10110. IfStmt *rootIfStmt = nullptr;
  10111. CompoundStmt *defaultBody = nullptr;
  10112. // For each case, start at its index in the vector, and go forward
  10113. // accumulating statements until BreakStmt or end of vector is reached.
  10114. for (auto curCaseIndex : caseStmtLocs) {
  10115. const Stmt *curCase = flatSwitch[curCaseIndex];
  10116. // CompoundStmt to hold all statements for this case.
  10117. CompoundStmt *cs = new (astContext) CompoundStmt(Stmt::EmptyShell());
  10118. // Accumulate all non-case/default/break statements as the body for the
  10119. // current case.
  10120. std::vector<Stmt *> statements;
  10121. for (unsigned i = curCaseIndex + 1;
  10122. i < flatSwitch.size() && !isa<BreakStmt>(flatSwitch[i]); ++i) {
  10123. if (!isa<CaseStmt>(flatSwitch[i]) && !isa<DefaultStmt>(flatSwitch[i]))
  10124. statements.push_back(const_cast<Stmt *>(flatSwitch[i]));
  10125. }
  10126. if (!statements.empty())
  10127. cs->setStmts(astContext, statements.data(), statements.size());
  10128. // For non-default cases, generate the IfStmt that compares the switch
  10129. // value to the case value.
  10130. if (auto *caseStmt = dyn_cast<CaseStmt>(curCase)) {
  10131. IfStmt *curIf = new (astContext) IfStmt(Stmt::EmptyShell());
  10132. BinaryOperator *bo = new (astContext) BinaryOperator(Stmt::EmptyShell());
  10133. bo->setLHS(const_cast<Expr *>(switchStmt->getCond()));
  10134. bo->setRHS(const_cast<Expr *>(caseStmt->getLHS()));
  10135. bo->setOpcode(BO_EQ);
  10136. bo->setType(astContext.getLogicalOperationType());
  10137. curIf->setCond(bo);
  10138. curIf->setThen(cs);
  10139. // No conditional variable associated with this faux if statement.
  10140. curIf->setConditionVariable(astContext, nullptr);
  10141. // Each If statement is the "else" of the previous if statement.
  10142. if (prevIfStmt)
  10143. prevIfStmt->setElse(curIf);
  10144. else
  10145. rootIfStmt = curIf;
  10146. prevIfStmt = curIf;
  10147. } else {
  10148. // Record the DefaultStmt body as it will be used as the body of the
  10149. // "else" block in the if-elseif-...-else pattern.
  10150. defaultBody = cs;
  10151. }
  10152. }
  10153. // If a default case exists, it is the "else" of the last if statement.
  10154. if (prevIfStmt)
  10155. prevIfStmt->setElse(defaultBody);
  10156. // Since all else-if and else statements are the child nodes of the first
  10157. // IfStmt, we only need to call doStmt for the first IfStmt.
  10158. if (rootIfStmt)
  10159. doStmt(rootIfStmt);
  10160. // If there are no CaseStmt and there is only 1 DefaultStmt, there will be
  10161. // no if statements. The switch in that case only executes the body of the
  10162. // default case.
  10163. else if (defaultBody)
  10164. doStmt(defaultBody);
  10165. }
  10166. SpirvInstruction *SpirvEmitter::extractVecFromVec4(SpirvInstruction *from,
  10167. uint32_t targetVecSize,
  10168. QualType targetElemType,
  10169. SourceLocation loc) {
  10170. assert(targetVecSize > 0 && targetVecSize < 5);
  10171. const QualType retType =
  10172. targetVecSize == 1
  10173. ? targetElemType
  10174. : astContext.getExtVectorType(targetElemType, targetVecSize);
  10175. switch (targetVecSize) {
  10176. case 1:
  10177. return spvBuilder.createCompositeExtract(retType, from, {0}, loc);
  10178. break;
  10179. case 2:
  10180. return spvBuilder.createVectorShuffle(retType, from, from, {0, 1}, loc);
  10181. break;
  10182. case 3:
  10183. return spvBuilder.createVectorShuffle(retType, from, from, {0, 1, 2}, loc);
  10184. break;
  10185. case 4:
  10186. return from;
  10187. default:
  10188. llvm_unreachable("vector element count must be 1, 2, 3, or 4");
  10189. }
  10190. }
  10191. void SpirvEmitter::addFunctionToWorkQueue(hlsl::DXIL::ShaderKind shaderKind,
  10192. const clang::FunctionDecl *fnDecl,
  10193. bool isEntryFunction) {
  10194. // Only update the workQueue and the function info map if the given
  10195. // FunctionDecl hasn't been added already.
  10196. if (functionInfoMap.find(fnDecl) == functionInfoMap.end()) {
  10197. // Note: The function is just discovered and is being added to the
  10198. // workQueue, therefore it does not have the entryFunction SPIR-V
  10199. // instruction yet (use nullptr).
  10200. auto *fnInfo = new (spvContext) FunctionInfo(
  10201. shaderKind, fnDecl, /*entryFunction*/ nullptr, isEntryFunction);
  10202. functionInfoMap[fnDecl] = fnInfo;
  10203. workQueue.push_back(fnInfo);
  10204. }
  10205. }
  10206. SpirvInstruction *
  10207. SpirvEmitter::processTraceRayInline(const CXXMemberCallExpr *expr) {
  10208. emitWarning("SPV_KHR_ray_query is currently a provisional extension and might"
  10209. "change in ways that are not backwards compatible",
  10210. expr->getExprLoc());
  10211. const auto object = expr->getImplicitObjectArgument();
  10212. uint32_t templateFlags = hlsl::GetHLSLResourceTemplateUInt(object->getType());
  10213. const auto constFlags = spvBuilder.getConstantInt(
  10214. astContext.UnsignedIntTy, llvm::APInt(32, templateFlags));
  10215. SpirvInstruction *rayqueryObj = loadIfAliasVarRef(object);
  10216. const auto args = expr->getArgs();
  10217. if (expr->getNumArgs() != 4) {
  10218. emitError("invalid number of arguments to RayQueryInitialize",
  10219. expr->getExprLoc());
  10220. }
  10221. // HLSL Func
  10222. // void RayQuery::TraceRayInline(
  10223. // RaytracingAccelerationStructure AccelerationStructure,
  10224. // uint RayFlags,
  10225. // uint InstanceInclusionMask,
  10226. // RayDesc Ray);
  10227. // void OpRayQueryInitializeKHR ( <id> RayQuery,
  10228. // <id> Acceleration Structure
  10229. // <id> RayFlags
  10230. // <id> CullMask
  10231. // <id> RayOrigin
  10232. // <id> RayTmin
  10233. // <id> RayDirection
  10234. // <id> Ray Tmax)
  10235. const auto accelStructure = doExpr(args[0]);
  10236. SpirvInstruction *rayFlags = nullptr;
  10237. if (rayFlags = tryToEvaluateAsConst(args[1])) {
  10238. rayFlags->setRValue();
  10239. } else {
  10240. rayFlags = doExpr(args[1]);
  10241. }
  10242. if (auto constFlags = dyn_cast<SpirvConstantInteger>(rayFlags)) {
  10243. auto interRayFlags = constFlags->getValue().getZExtValue();
  10244. templateFlags |= interRayFlags;
  10245. }
  10246. bool hasCullFlags =
  10247. templateFlags & (uint32_t(hlsl::DXIL::RayFlag::SkipTriangles) |
  10248. uint32_t(hlsl::DXIL::RayFlag::SkipProceduralPrimitives));
  10249. auto loc = args[1]->getLocStart();
  10250. rayFlags =
  10251. spvBuilder.createBinaryOp(spv::Op::OpBitwiseOr, astContext.UnsignedIntTy,
  10252. constFlags, rayFlags, loc);
  10253. const auto cullMask = doExpr(args[2]);
  10254. // Extract the ray description to match SPIR-V
  10255. const auto floatType = astContext.FloatTy;
  10256. const auto vecType = astContext.getExtVectorType(astContext.FloatTy, 3);
  10257. SpirvInstruction *rayDescArg = doExpr(args[3]);
  10258. loc = args[3]->getLocStart();
  10259. const auto origin =
  10260. spvBuilder.createCompositeExtract(vecType, rayDescArg, {0}, loc);
  10261. const auto tMin =
  10262. spvBuilder.createCompositeExtract(floatType, rayDescArg, {1}, loc);
  10263. const auto direction =
  10264. spvBuilder.createCompositeExtract(vecType, rayDescArg, {2}, loc);
  10265. const auto tMax =
  10266. spvBuilder.createCompositeExtract(floatType, rayDescArg, {3}, loc);
  10267. llvm::SmallVector<SpirvInstruction *, 8> traceArgs = {
  10268. rayqueryObj, accelStructure, rayFlags, cullMask,
  10269. origin, tMin, direction, tMax};
  10270. return spvBuilder.createRayQueryOpsKHR(spv::Op::OpRayQueryInitializeKHR,
  10271. QualType(), traceArgs, hasCullFlags,
  10272. expr->getExprLoc());
  10273. }
  10274. SpirvInstruction *
  10275. SpirvEmitter::processRayQueryIntrinsics(const CXXMemberCallExpr *expr,
  10276. hlsl::IntrinsicOp opcode) {
  10277. emitWarning("SPV_KHR_ray_query is currently a provisional extension and might"
  10278. "change in ways that are not backwards compatible",
  10279. expr->getExprLoc());
  10280. const auto object = expr->getImplicitObjectArgument();
  10281. SpirvInstruction *rayqueryObj = loadIfAliasVarRef(object);
  10282. const auto args = expr->getArgs();
  10283. llvm::SmallVector<SpirvInstruction *, 8> traceArgs;
  10284. traceArgs.push_back(rayqueryObj);
  10285. for (uint32_t i = 0; i < expr->getNumArgs(); ++i) {
  10286. traceArgs.push_back(doExpr(args[i]));
  10287. }
  10288. spv::Op spvCode = spv::Op::Max;
  10289. QualType exprType = expr->getType();
  10290. exprType = exprType->isVoidType() ? QualType() : exprType;
  10291. const auto candidateIntersection =
  10292. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 0));
  10293. const auto committedIntersection =
  10294. spvBuilder.getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, 1));
  10295. bool transposeMatrix = false;
  10296. bool logicalNot = false;
  10297. using namespace hlsl;
  10298. switch (opcode) {
  10299. case IntrinsicOp::MOP_Proceed:
  10300. spvCode = spv::Op::OpRayQueryProceedKHR;
  10301. break;
  10302. case IntrinsicOp::MOP_Abort:
  10303. spvCode = spv::Op::OpRayQueryTerminateKHR;
  10304. exprType = QualType();
  10305. break;
  10306. case IntrinsicOp::MOP_CandidateGeometryIndex:
  10307. traceArgs.push_back(candidateIntersection);
  10308. spvCode = spv::Op::OpRayQueryGetIntersectionGeometryIndexKHR;
  10309. break;
  10310. case IntrinsicOp::MOP_CandidateInstanceContributionToHitGroupIndex:
  10311. traceArgs.push_back(candidateIntersection);
  10312. spvCode = spv::Op::
  10313. OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
  10314. break;
  10315. case IntrinsicOp::MOP_CandidateInstanceID:
  10316. traceArgs.push_back(candidateIntersection);
  10317. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
  10318. break;
  10319. case IntrinsicOp::MOP_CandidateInstanceIndex:
  10320. traceArgs.push_back(candidateIntersection);
  10321. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceIdKHR;
  10322. break;
  10323. case IntrinsicOp::MOP_CandidateObjectRayDirection:
  10324. traceArgs.push_back(candidateIntersection);
  10325. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayDirectionKHR;
  10326. break;
  10327. case IntrinsicOp::MOP_CandidateObjectRayOrigin:
  10328. traceArgs.push_back(candidateIntersection);
  10329. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayOriginKHR;
  10330. break;
  10331. case IntrinsicOp::MOP_CandidateObjectToWorld3x4:
  10332. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10333. traceArgs.push_back(candidateIntersection);
  10334. transposeMatrix = true;
  10335. break;
  10336. case IntrinsicOp::MOP_CandidateObjectToWorld4x3:
  10337. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10338. traceArgs.push_back(candidateIntersection);
  10339. break;
  10340. case IntrinsicOp::MOP_CandidatePrimitiveIndex:
  10341. traceArgs.push_back(candidateIntersection);
  10342. spvCode = spv::Op::OpRayQueryGetIntersectionPrimitiveIndexKHR;
  10343. break;
  10344. case IntrinsicOp::MOP_CandidateProceduralPrimitiveNonOpaque:
  10345. spvCode = spv::Op::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
  10346. logicalNot = true;
  10347. break;
  10348. case IntrinsicOp::MOP_CandidateTriangleBarycentrics:
  10349. traceArgs.push_back(candidateIntersection);
  10350. spvCode = spv::Op::OpRayQueryGetIntersectionBarycentricsKHR;
  10351. break;
  10352. case IntrinsicOp::MOP_CandidateTriangleFrontFace:
  10353. traceArgs.push_back(candidateIntersection);
  10354. spvCode = spv::Op::OpRayQueryGetIntersectionFrontFaceKHR;
  10355. break;
  10356. case IntrinsicOp::MOP_CandidateTriangleRayT:
  10357. traceArgs.push_back(candidateIntersection);
  10358. spvCode = spv::Op::OpRayQueryGetIntersectionTKHR;
  10359. break;
  10360. case IntrinsicOp::MOP_CandidateType:
  10361. spvCode = spv::Op::OpRayQueryGetIntersectionTypeKHR;
  10362. traceArgs.push_back(candidateIntersection);
  10363. break;
  10364. case IntrinsicOp::MOP_CandidateWorldToObject4x3:
  10365. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10366. traceArgs.push_back(candidateIntersection);
  10367. break;
  10368. case IntrinsicOp::MOP_CandidateWorldToObject3x4:
  10369. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10370. traceArgs.push_back(candidateIntersection);
  10371. transposeMatrix = true;
  10372. break;
  10373. case IntrinsicOp::MOP_CommitNonOpaqueTriangleHit:
  10374. spvCode = spv::Op::OpRayQueryConfirmIntersectionKHR;
  10375. exprType = QualType();
  10376. break;
  10377. case IntrinsicOp::MOP_CommitProceduralPrimitiveHit:
  10378. spvCode = spv::Op::OpRayQueryGenerateIntersectionKHR;
  10379. exprType = QualType();
  10380. break;
  10381. case IntrinsicOp::MOP_CommittedGeometryIndex:
  10382. spvCode = spv::Op::OpRayQueryGetIntersectionGeometryIndexKHR;
  10383. traceArgs.push_back(committedIntersection);
  10384. break;
  10385. case IntrinsicOp::MOP_CommittedInstanceContributionToHitGroupIndex:
  10386. spvCode = spv::Op::
  10387. OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
  10388. traceArgs.push_back(committedIntersection);
  10389. break;
  10390. case IntrinsicOp::MOP_CommittedInstanceID:
  10391. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
  10392. traceArgs.push_back(committedIntersection);
  10393. break;
  10394. case IntrinsicOp::MOP_CommittedInstanceIndex:
  10395. spvCode = spv::Op::OpRayQueryGetIntersectionInstanceIdKHR;
  10396. traceArgs.push_back(committedIntersection);
  10397. break;
  10398. case IntrinsicOp::MOP_CommittedObjectRayDirection:
  10399. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayDirectionKHR;
  10400. traceArgs.push_back(committedIntersection);
  10401. break;
  10402. case IntrinsicOp::MOP_CommittedObjectRayOrigin:
  10403. spvCode = spv::Op::OpRayQueryGetIntersectionObjectRayOriginKHR;
  10404. traceArgs.push_back(committedIntersection);
  10405. break;
  10406. case IntrinsicOp::MOP_CommittedObjectToWorld3x4:
  10407. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10408. traceArgs.push_back(committedIntersection);
  10409. transposeMatrix = true;
  10410. break;
  10411. case IntrinsicOp::MOP_CommittedObjectToWorld4x3:
  10412. spvCode = spv::Op::OpRayQueryGetIntersectionObjectToWorldKHR;
  10413. traceArgs.push_back(committedIntersection);
  10414. break;
  10415. case IntrinsicOp::MOP_CommittedPrimitiveIndex:
  10416. spvCode = spv::Op::OpRayQueryGetIntersectionPrimitiveIndexKHR;
  10417. traceArgs.push_back(committedIntersection);
  10418. break;
  10419. case IntrinsicOp::MOP_CommittedRayT:
  10420. spvCode = spv::Op::OpRayQueryGetIntersectionTKHR;
  10421. traceArgs.push_back(committedIntersection);
  10422. break;
  10423. case IntrinsicOp::MOP_CommittedStatus:
  10424. spvCode = spv::Op::OpRayQueryGetIntersectionTypeKHR;
  10425. traceArgs.push_back(committedIntersection);
  10426. break;
  10427. case IntrinsicOp::MOP_CommittedTriangleBarycentrics:
  10428. spvCode = spv::Op::OpRayQueryGetIntersectionBarycentricsKHR;
  10429. traceArgs.push_back(committedIntersection);
  10430. break;
  10431. case IntrinsicOp::MOP_CommittedTriangleFrontFace:
  10432. spvCode = spv::Op::OpRayQueryGetIntersectionFrontFaceKHR;
  10433. traceArgs.push_back(committedIntersection);
  10434. break;
  10435. case IntrinsicOp::MOP_CommittedWorldToObject3x4:
  10436. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10437. traceArgs.push_back(committedIntersection);
  10438. transposeMatrix = true;
  10439. break;
  10440. case IntrinsicOp::MOP_CommittedWorldToObject4x3:
  10441. spvCode = spv::Op::OpRayQueryGetIntersectionWorldToObjectKHR;
  10442. traceArgs.push_back(committedIntersection);
  10443. break;
  10444. case IntrinsicOp::MOP_RayFlags:
  10445. spvCode = spv::Op::OpRayQueryGetRayFlagsKHR;
  10446. break;
  10447. case IntrinsicOp::MOP_RayTMin:
  10448. spvCode = spv::Op::OpRayQueryGetRayTMinKHR;
  10449. break;
  10450. case IntrinsicOp::MOP_WorldRayDirection:
  10451. spvCode = spv::Op::OpRayQueryGetWorldRayDirectionKHR;
  10452. break;
  10453. case IntrinsicOp::MOP_WorldRayOrigin:
  10454. spvCode = spv::Op::OpRayQueryGetWorldRayOriginKHR;
  10455. break;
  10456. default:
  10457. emitError("intrinsic '%0' method unimplemented",
  10458. expr->getCallee()->getExprLoc())
  10459. << expr->getDirectCallee()->getName();
  10460. return nullptr;
  10461. }
  10462. if (transposeMatrix) {
  10463. assert(hlsl::IsHLSLMatType(exprType) && "intrinsic should be matrix");
  10464. const clang::Type *type = exprType.getCanonicalType().getTypePtr();
  10465. const RecordType *RT = cast<RecordType>(type);
  10466. const ClassTemplateSpecializationDecl *templateSpecDecl =
  10467. cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  10468. ClassTemplateDecl *templateDecl =
  10469. templateSpecDecl->getSpecializedTemplate();
  10470. const auto retType = exprType;
  10471. exprType = getHLSLMatrixType(astContext, theCompilerInstance.getSema(),
  10472. templateDecl, astContext.FloatTy, 4, 3);
  10473. }
  10474. const auto loc = expr->getExprLoc();
  10475. SpirvInstruction *retVal =
  10476. spvBuilder.createRayQueryOpsKHR(spvCode, exprType, traceArgs, false, loc);
  10477. if (transposeMatrix) {
  10478. retVal = spvBuilder.createUnaryOp(spv::Op::OpTranspose, expr->getType(),
  10479. retVal, loc);
  10480. }
  10481. if (logicalNot) {
  10482. retVal = spvBuilder.createUnaryOp(spv::Op::OpLogicalNot, expr->getType(),
  10483. retVal, loc);
  10484. }
  10485. retVal->setRValue();
  10486. return retVal;
  10487. }
  10488. } // end namespace spirv
  10489. } // end namespace clang