SPIRVEmitter.cpp 391 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771
  1. //===------- SPIRVEmitter.h - SPIR-V Binary Code Emitter --------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements a SPIR-V emitter class that takes in HLSL AST and emits
  10. // SPIR-V binary words.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "SPIRVEmitter.h"
  14. #include "dxc/HlslIntrinsicOp.h"
  15. #include "spirv-tools/optimizer.hpp"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "InitListHandler.h"
  18. namespace clang {
  19. namespace spirv {
  20. namespace {
  21. /// Returns the type of the given decl. If the given decl is a FunctionDecl,
  22. /// returns its result type.
  23. inline QualType getTypeOrFnRetType(const ValueDecl *decl) {
  24. if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  25. return funcDecl->getReturnType();
  26. }
  27. return decl->getType();
  28. }
  29. // Returns true if the given decl has the given semantic.
  30. bool hasSemantic(const DeclaratorDecl *decl,
  31. hlsl::DXIL::SemanticKind semanticKind) {
  32. using namespace hlsl;
  33. for (auto *annotation : decl->getUnusualAnnotations()) {
  34. if (auto *semanticDecl = dyn_cast<SemanticDecl>(annotation)) {
  35. llvm::StringRef semanticName;
  36. uint32_t semanticIndex = 0;
  37. Semantic::DecomposeNameAndIndex(semanticDecl->SemanticName, &semanticName,
  38. &semanticIndex);
  39. const auto *semantic = Semantic::GetByName(semanticName);
  40. if (semantic->GetKind() == semanticKind)
  41. return true;
  42. }
  43. }
  44. return false;
  45. }
  46. bool patchConstFuncTakesHullOutputPatch(FunctionDecl *pcf) {
  47. for (const auto *param : pcf->parameters())
  48. if (hlsl::IsHLSLOutputPatchType(param->getType()))
  49. return true;
  50. return false;
  51. }
  52. // TODO: Maybe we should move these type probing functions to TypeTranslator.
  53. /// Returns true if the given type is a bool or vector of bool type.
  54. bool isBoolOrVecOfBoolType(QualType type) {
  55. QualType elemType = {};
  56. return (TypeTranslator::isScalarType(type, &elemType) ||
  57. TypeTranslator::isVectorType(type, &elemType)) &&
  58. elemType->isBooleanType();
  59. }
  60. /// Returns true if the given type is a signed integer or vector of signed
  61. /// integer type.
  62. bool isSintOrVecOfSintType(QualType type) {
  63. QualType elemType = {};
  64. return (TypeTranslator::isScalarType(type, &elemType) ||
  65. TypeTranslator::isVectorType(type, &elemType)) &&
  66. elemType->isSignedIntegerType();
  67. }
  68. /// Returns true if the given type is an unsigned integer or vector of unsigned
  69. /// integer type.
  70. bool isUintOrVecOfUintType(QualType type) {
  71. QualType elemType = {};
  72. return (TypeTranslator::isScalarType(type, &elemType) ||
  73. TypeTranslator::isVectorType(type, &elemType)) &&
  74. elemType->isUnsignedIntegerType();
  75. }
  76. /// Returns true if the given type is a float or vector of float type.
  77. bool isFloatOrVecOfFloatType(QualType type) {
  78. QualType elemType = {};
  79. return (TypeTranslator::isScalarType(type, &elemType) ||
  80. TypeTranslator::isVectorType(type, &elemType)) &&
  81. elemType->isFloatingType();
  82. }
  83. /// Returns true if the given type is a bool or vector/matrix of bool type.
  84. bool isBoolOrVecMatOfBoolType(QualType type) {
  85. return isBoolOrVecOfBoolType(type) ||
  86. (hlsl::IsHLSLMatType(type) &&
  87. hlsl::GetHLSLMatElementType(type)->isBooleanType());
  88. }
  89. /// Returns true if the given type is a signed integer or vector/matrix of
  90. /// signed integer type.
  91. bool isSintOrVecMatOfSintType(QualType type) {
  92. return isSintOrVecOfSintType(type) ||
  93. (hlsl::IsHLSLMatType(type) &&
  94. hlsl::GetHLSLMatElementType(type)->isSignedIntegerType());
  95. }
  96. /// Returns true if the given type is an unsigned integer or vector/matrix of
  97. /// unsigned integer type.
  98. bool isUintOrVecMatOfUintType(QualType type) {
  99. return isUintOrVecOfUintType(type) ||
  100. (hlsl::IsHLSLMatType(type) &&
  101. hlsl::GetHLSLMatElementType(type)->isUnsignedIntegerType());
  102. }
  103. /// Returns true if the given type is a float or vector/matrix of float type.
  104. bool isFloatOrVecMatOfFloatType(QualType type) {
  105. return isFloatOrVecOfFloatType(type) ||
  106. (hlsl::IsHLSLMatType(type) &&
  107. hlsl::GetHLSLMatElementType(type)->isFloatingType());
  108. }
  109. inline bool isSpirvMatrixOp(spv::Op opcode) {
  110. return opcode == spv::Op::OpMatrixTimesMatrix ||
  111. opcode == spv::Op::OpMatrixTimesVector ||
  112. opcode == spv::Op::OpMatrixTimesScalar;
  113. }
  114. /// If expr is a (RW)StructuredBuffer.Load(), returns the object and writes
  115. /// index. Otherwiser, returns false.
  116. // TODO: The following doesn't handle Load(int, int) yet. And it is basically a
  117. // duplicate of doCXXMemberCallExpr.
  118. const Expr *isStructuredBufferLoad(const Expr *expr, const Expr **index) {
  119. using namespace hlsl;
  120. if (const auto *indexing = dyn_cast<CXXMemberCallExpr>(expr)) {
  121. const auto *callee = indexing->getDirectCallee();
  122. uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
  123. llvm::StringRef group;
  124. if (GetIntrinsicOp(callee, opcode, group)) {
  125. if (static_cast<IntrinsicOp>(opcode) == IntrinsicOp::MOP_Load) {
  126. const auto *object = indexing->getImplicitObjectArgument();
  127. if (TypeTranslator::isStructuredBuffer(object->getType())) {
  128. *index = indexing->getArg(0);
  129. return indexing->getImplicitObjectArgument();
  130. }
  131. }
  132. }
  133. }
  134. return nullptr;
  135. }
  136. /// Returns true if the given VarDecl will be translated into a SPIR-V variable
  137. /// not in the Private or Function storage class.
  138. inline bool isExternalVar(const VarDecl *var) {
  139. // Class static variables should be put in the Private storage class.
  140. // groupshared variables are allowed to be declared as "static". But we still
  141. // need to put them in the Workgroup storage class. That is, when seeing
  142. // "static groupshared", ignore "static".
  143. return var->hasExternalFormalLinkage() ? !var->isStaticDataMember()
  144. : var->getAttr<HLSLGroupSharedAttr>();
  145. }
  146. /// Returns the referenced variable's DeclContext if the given expr is
  147. /// a DeclRefExpr referencing a ConstantBuffer/TextureBuffer. Otherwise,
  148. /// returns nullptr.
  149. const DeclContext *isConstantTextureBufferDeclRef(const Expr *expr) {
  150. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr->IgnoreParenCasts()))
  151. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  152. if (TypeTranslator::isConstantTextureBuffer(varDecl))
  153. return varDecl->getType()->getAs<RecordType>()->getDecl();
  154. return nullptr;
  155. }
  156. /// Returns true if
  157. /// * the given expr is an DeclRefExpr referencing a kind of structured or byte
  158. /// buffer and it is non-alias one, or
  159. /// * the given expr is an CallExpr returning a kind of structured or byte
  160. /// buffer.
  161. ///
  162. /// Note: legalization specific code
  163. bool isReferencingNonAliasStructuredOrByteBuffer(const Expr *expr) {
  164. expr = expr->IgnoreParenCasts();
  165. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  166. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  167. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(varDecl->getType()))
  168. return isExternalVar(varDecl);
  169. } else if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  170. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(callExpr->getType()))
  171. return true;
  172. }
  173. return false;
  174. }
  175. bool spirvToolsLegalize(spv_target_env env, std::vector<uint32_t> *module,
  176. std::string *messages) {
  177. spvtools::Optimizer optimizer(env);
  178. optimizer.SetMessageConsumer(
  179. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  180. const spv_position_t & /*position*/,
  181. const char *message) { *messages += message; });
  182. optimizer.RegisterLegalizationPasses();
  183. optimizer.RegisterPass(spvtools::CreateReplaceInvalidOpcodePass());
  184. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  185. return optimizer.Run(module->data(), module->size(), module);
  186. }
  187. bool spirvToolsOptimize(spv_target_env env, std::vector<uint32_t> *module,
  188. std::string *messages) {
  189. spvtools::Optimizer optimizer(env);
  190. optimizer.SetMessageConsumer(
  191. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  192. const spv_position_t & /*position*/,
  193. const char *message) { *messages += message; });
  194. optimizer.RegisterPerformancePasses();
  195. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  196. return optimizer.Run(module->data(), module->size(), module);
  197. }
  198. bool spirvToolsValidate(spv_target_env env, std::vector<uint32_t> *module,
  199. std::string *messages, bool relaxLogicalPointer) {
  200. spvtools::SpirvTools tools(env);
  201. tools.SetMessageConsumer(
  202. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  203. const spv_position_t & /*position*/,
  204. const char *message) { *messages += message; });
  205. spvtools::ValidatorOptions options;
  206. options.SetRelaxLogicalPointer(relaxLogicalPointer);
  207. return tools.Validate(module->data(), module->size(), options);
  208. }
  209. /// Translates atomic HLSL opcodes into the equivalent SPIR-V opcode.
  210. spv::Op translateAtomicHlslOpcodeToSpirvOpcode(hlsl::IntrinsicOp opcode) {
  211. using namespace hlsl;
  212. using namespace spv;
  213. switch (opcode) {
  214. case IntrinsicOp::IOP_InterlockedAdd:
  215. case IntrinsicOp::MOP_InterlockedAdd:
  216. return Op::OpAtomicIAdd;
  217. case IntrinsicOp::IOP_InterlockedAnd:
  218. case IntrinsicOp::MOP_InterlockedAnd:
  219. return Op::OpAtomicAnd;
  220. case IntrinsicOp::IOP_InterlockedOr:
  221. case IntrinsicOp::MOP_InterlockedOr:
  222. return Op::OpAtomicOr;
  223. case IntrinsicOp::IOP_InterlockedXor:
  224. case IntrinsicOp::MOP_InterlockedXor:
  225. return Op::OpAtomicXor;
  226. case IntrinsicOp::IOP_InterlockedUMax:
  227. case IntrinsicOp::MOP_InterlockedUMax:
  228. return Op::OpAtomicUMax;
  229. case IntrinsicOp::IOP_InterlockedUMin:
  230. case IntrinsicOp::MOP_InterlockedUMin:
  231. return Op::OpAtomicUMin;
  232. case IntrinsicOp::IOP_InterlockedMax:
  233. case IntrinsicOp::MOP_InterlockedMax:
  234. return Op::OpAtomicSMax;
  235. case IntrinsicOp::IOP_InterlockedMin:
  236. case IntrinsicOp::MOP_InterlockedMin:
  237. return Op::OpAtomicSMin;
  238. case IntrinsicOp::IOP_InterlockedExchange:
  239. case IntrinsicOp::MOP_InterlockedExchange:
  240. return Op::OpAtomicExchange;
  241. }
  242. assert(false && "unimplemented hlsl intrinsic opcode");
  243. return Op::Max;
  244. }
  245. // Returns true if the given opcode is an accepted binary opcode in
  246. // OpSpecConstantOp.
  247. bool isAcceptedSpecConstantBinaryOp(spv::Op op) {
  248. switch (op) {
  249. case spv::Op::OpIAdd:
  250. case spv::Op::OpISub:
  251. case spv::Op::OpIMul:
  252. case spv::Op::OpUDiv:
  253. case spv::Op::OpSDiv:
  254. case spv::Op::OpUMod:
  255. case spv::Op::OpSRem:
  256. case spv::Op::OpSMod:
  257. case spv::Op::OpShiftRightLogical:
  258. case spv::Op::OpShiftRightArithmetic:
  259. case spv::Op::OpShiftLeftLogical:
  260. case spv::Op::OpBitwiseOr:
  261. case spv::Op::OpBitwiseXor:
  262. case spv::Op::OpBitwiseAnd:
  263. case spv::Op::OpVectorShuffle:
  264. case spv::Op::OpCompositeExtract:
  265. case spv::Op::OpCompositeInsert:
  266. case spv::Op::OpLogicalOr:
  267. case spv::Op::OpLogicalAnd:
  268. case spv::Op::OpLogicalNot:
  269. case spv::Op::OpLogicalEqual:
  270. case spv::Op::OpLogicalNotEqual:
  271. case spv::Op::OpIEqual:
  272. case spv::Op::OpINotEqual:
  273. case spv::Op::OpULessThan:
  274. case spv::Op::OpSLessThan:
  275. case spv::Op::OpUGreaterThan:
  276. case spv::Op::OpSGreaterThan:
  277. case spv::Op::OpULessThanEqual:
  278. case spv::Op::OpSLessThanEqual:
  279. case spv::Op::OpUGreaterThanEqual:
  280. case spv::Op::OpSGreaterThanEqual:
  281. return true;
  282. }
  283. return false;
  284. }
  285. /// Returns true if the given expression is an accepted initializer for a spec
  286. /// constant.
  287. bool isAcceptedSpecConstantInit(const Expr *init) {
  288. // Allow numeric casts
  289. init = init->IgnoreParenCasts();
  290. if (isa<CXXBoolLiteralExpr>(init) || isa<IntegerLiteral>(init) ||
  291. isa<FloatingLiteral>(init))
  292. return true;
  293. // Allow the minus operator which is used to specify negative values
  294. if (const auto *unaryOp = dyn_cast<UnaryOperator>(init))
  295. return unaryOp->getOpcode() == UO_Minus &&
  296. isAcceptedSpecConstantInit(unaryOp->getSubExpr());
  297. return false;
  298. }
  299. /// Returns true if the given function parameter can act as shader stage
  300. /// input parameter.
  301. inline bool canActAsInParmVar(const ParmVarDecl *param) {
  302. // If the parameter has no in/out/inout attribute, it is defaulted to
  303. // an in parameter.
  304. return !param->hasAttr<HLSLOutAttr>() &&
  305. // GS output streams are marked as inout, but it should not be
  306. // used as in parameter.
  307. !hlsl::IsHLSLStreamOutputType(param->getType());
  308. }
  309. /// Returns true if the given function parameter can act as shader stage
  310. /// output parameter.
  311. inline bool canActAsOutParmVar(const ParmVarDecl *param) {
  312. return param->hasAttr<HLSLOutAttr>() || param->hasAttr<HLSLInOutAttr>();
  313. }
  314. /// Returns true if the given expression is of builtin type and can be evaluated
  315. /// to a constant zero. Returns false otherwise.
  316. inline bool evaluatesToConstZero(const Expr *expr, ASTContext &astContext) {
  317. const auto type = expr->getType();
  318. if (!type->isBuiltinType())
  319. return false;
  320. Expr::EvalResult evalResult;
  321. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  322. !evalResult.HasSideEffects) {
  323. const auto &val = evalResult.Val;
  324. return ((type->isBooleanType() && !val.getInt().getBoolValue()) ||
  325. (type->isIntegerType() && !val.getInt().getBoolValue()) ||
  326. (type->isFloatingType() && val.getFloat().isZero()));
  327. }
  328. return false;
  329. }
  330. /// Returns the HLSLBufferDecl if the given VarDecl is inside a cbuffer/tbuffer.
  331. /// Returns nullptr otherwise, including varDecl is a ConstantBuffer or
  332. /// TextureBuffer itself.
  333. inline const HLSLBufferDecl *getCTBufferContext(const VarDecl *varDecl) {
  334. if (const auto *bufferDecl =
  335. dyn_cast<HLSLBufferDecl>(varDecl->getDeclContext()))
  336. // Filter ConstantBuffer/TextureBuffer
  337. if (!bufferDecl->isConstantBufferView())
  338. return bufferDecl;
  339. return nullptr;
  340. }
  341. /// Returns the real definition of the callee of the given CallExpr.
  342. ///
  343. /// If we are calling a forward-declared function, callee will be the
  344. /// FunctionDecl for the foward-declared function, not the actual
  345. /// definition. The foward-delcaration and defintion are two completely
  346. /// different AST nodes.
  347. inline const FunctionDecl *getCalleeDefinition(const CallExpr *expr) {
  348. const auto *callee = expr->getDirectCallee();
  349. if (callee->isThisDeclarationADefinition())
  350. return callee;
  351. // We need to update callee to the actual definition here
  352. if (!callee->isDefined(callee))
  353. return nullptr;
  354. return callee;
  355. }
  356. /// Returns the referenced definition. The given expr is expected to be a
  357. /// DeclRefExpr or CallExpr after ignoring casts. Returns nullptr otherwise.
  358. const DeclaratorDecl *getReferencedDef(const Expr *expr) {
  359. if (!expr)
  360. return nullptr;
  361. expr = expr->IgnoreParenCasts();
  362. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  363. return dyn_cast_or_null<DeclaratorDecl>(declRefExpr->getDecl());
  364. }
  365. if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  366. return getCalleeDefinition(callExpr);
  367. }
  368. return nullptr;
  369. }
  370. /// Returns the number of base classes if this type is a derived class/struct.
  371. /// Returns zero otherwise.
  372. inline uint32_t getNumBaseClasses(QualType type) {
  373. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  374. return cxxDecl->getNumBases();
  375. return 0;
  376. }
  377. /// Gets the index sequence of casting a derived object to a base object by
  378. /// following the cast chain.
  379. void getBaseClassIndices(const CastExpr *expr,
  380. llvm::SmallVectorImpl<uint32_t> *indices) {
  381. assert(expr->getCastKind() == CK_UncheckedDerivedToBase ||
  382. expr->getCastKind() == CK_HLSLDerivedToBase);
  383. indices->clear();
  384. QualType derivedType = expr->getSubExpr()->getType();
  385. const auto *derivedDecl = derivedType->getAsCXXRecordDecl();
  386. // Go through the base cast chain: for each of the derived to base cast, find
  387. // the index of the base in question in the derived's bases.
  388. for (auto pathIt = expr->path_begin(), pathIe = expr->path_end();
  389. pathIt != pathIe; ++pathIt) {
  390. // The type of the base in question
  391. const auto baseType = (*pathIt)->getType();
  392. uint32_t index = 0;
  393. for (auto baseIt = derivedDecl->bases_begin(),
  394. baseIe = derivedDecl->bases_end();
  395. baseIt != baseIe; ++baseIt, ++index)
  396. if (baseIt->getType() == baseType) {
  397. indices->push_back(index);
  398. break;
  399. }
  400. assert(index < derivedDecl->getNumBases());
  401. // Continue to proceed the next base in the chain
  402. derivedType = baseType;
  403. derivedDecl = derivedType->getAsCXXRecordDecl();
  404. }
  405. }
  406. spv::Capability getCapabilityForGroupNonUniform(spv::Op opcode) {
  407. switch (opcode) {
  408. case spv::Op::OpGroupNonUniformElect:
  409. return spv::Capability::GroupNonUniform;
  410. case spv::Op::OpGroupNonUniformAny:
  411. case spv::Op::OpGroupNonUniformAll:
  412. case spv::Op::OpGroupNonUniformAllEqual:
  413. return spv::Capability::GroupNonUniformVote;
  414. case spv::Op::OpGroupNonUniformBallot:
  415. case spv::Op::OpGroupNonUniformBallotBitCount:
  416. case spv::Op::OpGroupNonUniformBroadcast:
  417. case spv::Op::OpGroupNonUniformBroadcastFirst:
  418. return spv::Capability::GroupNonUniformBallot;
  419. case spv::Op::OpGroupNonUniformIAdd:
  420. case spv::Op::OpGroupNonUniformFAdd:
  421. case spv::Op::OpGroupNonUniformIMul:
  422. case spv::Op::OpGroupNonUniformFMul:
  423. case spv::Op::OpGroupNonUniformSMax:
  424. case spv::Op::OpGroupNonUniformUMax:
  425. case spv::Op::OpGroupNonUniformFMax:
  426. case spv::Op::OpGroupNonUniformSMin:
  427. case spv::Op::OpGroupNonUniformUMin:
  428. case spv::Op::OpGroupNonUniformFMin:
  429. case spv::Op::OpGroupNonUniformBitwiseAnd:
  430. case spv::Op::OpGroupNonUniformBitwiseOr:
  431. case spv::Op::OpGroupNonUniformBitwiseXor:
  432. return spv::Capability::GroupNonUniformArithmetic;
  433. case spv::Op::OpGroupNonUniformQuadBroadcast:
  434. case spv::Op::OpGroupNonUniformQuadSwap:
  435. return spv::Capability::GroupNonUniformQuad;
  436. }
  437. assert(false && "unhandled opcode");
  438. return spv::Capability::Max;
  439. }
  440. std::string getNamespacePrefix(const Decl *decl) {
  441. std::string nsPrefix = "";
  442. const DeclContext *dc = decl->getDeclContext();
  443. while (dc && !dc->isTranslationUnit()) {
  444. if (const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(dc)) {
  445. if (!ns->isAnonymousNamespace()) {
  446. nsPrefix = ns->getName().str() + "::" + nsPrefix;
  447. }
  448. }
  449. dc = dc->getParent();
  450. }
  451. return nsPrefix;
  452. }
  453. std::string getFnName(const FunctionDecl *fn) {
  454. // Prefix the function name with the struct name if necessary
  455. std::string classOrStructName = "";
  456. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(fn))
  457. if (const auto *st = dyn_cast<CXXRecordDecl>(memberFn->getDeclContext()))
  458. classOrStructName = st->getName().str() + ".";
  459. return getNamespacePrefix(fn) + classOrStructName + fn->getName().str();
  460. }
  461. /// Returns the capability required to non-uniformly index into the given type.
  462. spv::Capability getNonUniformCapability(QualType type) {
  463. using spv::Capability;
  464. if (type->isArrayType()) {
  465. return getNonUniformCapability(
  466. type->getAsArrayTypeUnsafe()->getElementType());
  467. }
  468. if (TypeTranslator::isTexture(type) || TypeTranslator::isSampler(type)) {
  469. return Capability::SampledImageArrayNonUniformIndexingEXT;
  470. }
  471. if (TypeTranslator::isRWTexture(type)) {
  472. return Capability::StorageImageArrayNonUniformIndexingEXT;
  473. }
  474. if (TypeTranslator::isBuffer(type)) {
  475. return Capability::UniformTexelBufferArrayNonUniformIndexingEXT;
  476. }
  477. if (TypeTranslator::isRWBuffer(type)) {
  478. return Capability::StorageTexelBufferArrayNonUniformIndexingEXT;
  479. }
  480. if (const auto *recordType = type->getAs<RecordType>()) {
  481. const auto name = recordType->getDecl()->getName();
  482. if (name == "SubpassInput" || name == "SubpassInputMS") {
  483. return Capability::InputAttachmentArrayNonUniformIndexingEXT;
  484. }
  485. }
  486. return Capability::Max;
  487. }
  488. } // namespace
  489. SPIRVEmitter::SPIRVEmitter(CompilerInstance &ci, EmitSPIRVOptions &options)
  490. : theCompilerInstance(ci), astContext(ci.getASTContext()),
  491. diags(ci.getDiagnostics()), spirvOptions(options),
  492. entryFunctionName(ci.getCodeGenOpts().HLSLEntryFunction),
  493. shaderModel(*hlsl::ShaderModel::GetByName(
  494. ci.getCodeGenOpts().HLSLProfile.c_str())),
  495. theContext(), featureManager(diags, options),
  496. theBuilder(&theContext, &featureManager, options.enableReflect),
  497. typeTranslator(astContext, theBuilder, diags, options),
  498. declIdMapper(shaderModel, astContext, theBuilder, typeTranslator,
  499. featureManager, options),
  500. entryFunctionId(0), curFunction(nullptr), curThis(0),
  501. seenPushConstantAt(), isSpecConstantMode(false),
  502. foundNonUniformResourceIndex(false), needsLegalization(false) {
  503. if (shaderModel.GetKind() == hlsl::ShaderModel::Kind::Invalid)
  504. emitError("unknown shader module: %0", {}) << shaderModel.GetName();
  505. if (options.invertY && !shaderModel.IsVS() && !shaderModel.IsDS() &&
  506. !shaderModel.IsGS())
  507. emitError("-fvk-invert-y can only be used in VS/DS/GS", {});
  508. if (options.useGlLayout && options.useDxLayout)
  509. emitError("cannot specify both -fvk-use-dx-layout and -fvk-use-gl-layout",
  510. {});
  511. options.Initialize();
  512. // Set shader module version
  513. theBuilder.setShaderModelVersion(shaderModel.GetMajor(),
  514. shaderModel.GetMinor());
  515. // Set debug info
  516. const auto &inputFiles = ci.getFrontendOpts().Inputs;
  517. if (options.enableDebugInfo && !inputFiles.empty())
  518. theBuilder.setSourceFileName(theContext.takeNextId(),
  519. inputFiles.front().getFile().str());
  520. }
  521. void SPIRVEmitter::HandleTranslationUnit(ASTContext &context) {
  522. // Stop translating if there are errors in previous compilation stages.
  523. if (context.getDiagnostics().hasErrorOccurred())
  524. return;
  525. TranslationUnitDecl *tu = context.getTranslationUnitDecl();
  526. // The entry function is the seed of the queue.
  527. for (auto *decl : tu->decls()) {
  528. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  529. if (funcDecl->getName() == entryFunctionName) {
  530. workQueue.insert(funcDecl);
  531. }
  532. } else {
  533. doDecl(decl);
  534. }
  535. }
  536. // Translate all functions reachable from the entry function.
  537. // The queue can grow in the meanwhile; so need to keep evaluating
  538. // workQueue.size().
  539. for (uint32_t i = 0; i < workQueue.size(); ++i) {
  540. doDecl(workQueue[i]);
  541. }
  542. if (context.getDiagnostics().hasErrorOccurred())
  543. return;
  544. const spv_target_env targetEnv = featureManager.getTargetEnv();
  545. AddRequiredCapabilitiesForShaderModel();
  546. // Addressing and memory model are required in a valid SPIR-V module.
  547. theBuilder.setAddressingModel(spv::AddressingModel::Logical);
  548. theBuilder.setMemoryModel(spv::MemoryModel::GLSL450);
  549. theBuilder.addEntryPoint(getSpirvShaderStage(shaderModel), entryFunctionId,
  550. entryFunctionName, declIdMapper.collectStageVars());
  551. // Add Location decorations to stage input/output variables.
  552. if (!declIdMapper.decorateStageIOLocations())
  553. return;
  554. // Add descriptor set and binding decorations to resource variables.
  555. if (!declIdMapper.decorateResourceBindings())
  556. return;
  557. // Output the constructed module.
  558. std::vector<uint32_t> m = theBuilder.takeModule();
  559. if (!spirvOptions.codeGenHighLevel) {
  560. // Run legalization passes
  561. if (needsLegalization || declIdMapper.requiresLegalization()) {
  562. std::string messages;
  563. if (!spirvToolsLegalize(targetEnv, &m, &messages)) {
  564. emitFatalError("failed to legalize SPIR-V: %0", {}) << messages;
  565. emitNote("please file a bug report on "
  566. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  567. "with source code if possible",
  568. {});
  569. return;
  570. } else if (!messages.empty()) {
  571. emitWarning("SPIR-V legalization: %0", {}) << messages;
  572. }
  573. }
  574. // Run optimization passes
  575. if (theCompilerInstance.getCodeGenOpts().OptimizationLevel > 0) {
  576. std::string messages;
  577. if (!spirvToolsOptimize(targetEnv, &m, &messages)) {
  578. emitFatalError("failed to optimize SPIR-V: %0", {}) << messages;
  579. emitNote("please file a bug report on "
  580. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  581. "with source code if possible",
  582. {});
  583. return;
  584. }
  585. }
  586. }
  587. // Validate the generated SPIR-V code
  588. if (!spirvOptions.disableValidation) {
  589. std::string messages;
  590. if (!spirvToolsValidate(targetEnv, &m, &messages,
  591. declIdMapper.requiresLegalization())) {
  592. emitFatalError("generated SPIR-V is invalid: %0", {}) << messages;
  593. emitNote("please file a bug report on "
  594. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  595. "with source code if possible",
  596. {});
  597. return;
  598. }
  599. }
  600. theCompilerInstance.getOutStream()->write(
  601. reinterpret_cast<const char *>(m.data()), m.size() * 4);
  602. }
  603. void SPIRVEmitter::doDecl(const Decl *decl) {
  604. if (decl->isImplicit() || isa<EmptyDecl>(decl) || isa<TypedefDecl>(decl))
  605. return;
  606. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  607. // We can have VarDecls inside cbuffer/tbuffer. For those VarDecls, we need
  608. // to emit their cbuffer/tbuffer as a whole and access each individual one
  609. // using access chains.
  610. if (const auto *bufferDecl = getCTBufferContext(varDecl)) {
  611. doHLSLBufferDecl(bufferDecl);
  612. } else {
  613. doVarDecl(varDecl);
  614. }
  615. } else if (const auto *namespaceDecl = dyn_cast<NamespaceDecl>(decl)) {
  616. for (auto *subDecl : namespaceDecl->decls())
  617. // Note: We only emit functions as they are discovered through the call
  618. // graph starting from the entry-point. We should not emit unused
  619. // functions inside namespaces.
  620. if (!isa<FunctionDecl>(subDecl))
  621. doDecl(subDecl);
  622. } else if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  623. doFunctionDecl(funcDecl);
  624. } else if (const auto *bufferDecl = dyn_cast<HLSLBufferDecl>(decl)) {
  625. doHLSLBufferDecl(bufferDecl);
  626. } else if (const auto *recordDecl = dyn_cast<RecordDecl>(decl)) {
  627. doRecordDecl(recordDecl);
  628. } else {
  629. emitError("decl type %0 unimplemented", decl->getLocation())
  630. << decl->getDeclKindName();
  631. }
  632. }
  633. void SPIRVEmitter::doStmt(const Stmt *stmt,
  634. llvm::ArrayRef<const Attr *> attrs) {
  635. if (const auto *compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
  636. for (auto *st : compoundStmt->body())
  637. doStmt(st);
  638. } else if (const auto *retStmt = dyn_cast<ReturnStmt>(stmt)) {
  639. doReturnStmt(retStmt);
  640. } else if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) {
  641. doDeclStmt(declStmt);
  642. } else if (const auto *ifStmt = dyn_cast<IfStmt>(stmt)) {
  643. doIfStmt(ifStmt, attrs);
  644. } else if (const auto *switchStmt = dyn_cast<SwitchStmt>(stmt)) {
  645. doSwitchStmt(switchStmt, attrs);
  646. } else if (const auto *caseStmt = dyn_cast<CaseStmt>(stmt)) {
  647. processCaseStmtOrDefaultStmt(stmt);
  648. } else if (const auto *defaultStmt = dyn_cast<DefaultStmt>(stmt)) {
  649. processCaseStmtOrDefaultStmt(stmt);
  650. } else if (const auto *breakStmt = dyn_cast<BreakStmt>(stmt)) {
  651. doBreakStmt(breakStmt);
  652. } else if (const auto *theDoStmt = dyn_cast<DoStmt>(stmt)) {
  653. doDoStmt(theDoStmt, attrs);
  654. } else if (const auto *discardStmt = dyn_cast<DiscardStmt>(stmt)) {
  655. doDiscardStmt(discardStmt);
  656. } else if (const auto *continueStmt = dyn_cast<ContinueStmt>(stmt)) {
  657. doContinueStmt(continueStmt);
  658. } else if (const auto *whileStmt = dyn_cast<WhileStmt>(stmt)) {
  659. doWhileStmt(whileStmt, attrs);
  660. } else if (const auto *forStmt = dyn_cast<ForStmt>(stmt)) {
  661. doForStmt(forStmt, attrs);
  662. } else if (const auto *nullStmt = dyn_cast<NullStmt>(stmt)) {
  663. // For the null statement ";". We don't need to do anything.
  664. } else if (const auto *expr = dyn_cast<Expr>(stmt)) {
  665. // All cases for expressions used as statements
  666. doExpr(expr);
  667. } else if (const auto *attrStmt = dyn_cast<AttributedStmt>(stmt)) {
  668. doStmt(attrStmt->getSubStmt(), attrStmt->getAttrs());
  669. } else {
  670. emitError("statement class '%0' unimplemented", stmt->getLocStart())
  671. << stmt->getStmtClassName() << stmt->getSourceRange();
  672. }
  673. }
  674. SpirvEvalInfo SPIRVEmitter::doExpr(const Expr *expr) {
  675. SpirvEvalInfo result(/*id*/ 0);
  676. // Provide a hint to the typeTranslator that if a literal is discovered, its
  677. // intended usage is as this expression type.
  678. TypeTranslator::LiteralTypeHint hint(typeTranslator, expr->getType());
  679. expr = expr->IgnoreParens();
  680. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  681. result = declIdMapper.getDeclEvalInfo(declRefExpr->getDecl());
  682. } else if (const auto *memberExpr = dyn_cast<MemberExpr>(expr)) {
  683. result = doMemberExpr(memberExpr);
  684. } else if (const auto *castExpr = dyn_cast<CastExpr>(expr)) {
  685. result = doCastExpr(castExpr);
  686. } else if (const auto *initListExpr = dyn_cast<InitListExpr>(expr)) {
  687. result = doInitListExpr(initListExpr);
  688. } else if (const auto *boolLiteral = dyn_cast<CXXBoolLiteralExpr>(expr)) {
  689. const auto value =
  690. theBuilder.getConstantBool(boolLiteral->getValue(), isSpecConstantMode);
  691. result = SpirvEvalInfo(value).setConstant().setRValue();
  692. } else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  693. const auto value = translateAPInt(intLiteral->getValue(), expr->getType());
  694. result = SpirvEvalInfo(value).setConstant().setRValue();
  695. } else if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  696. const auto value =
  697. translateAPFloat(floatLiteral->getValue(), expr->getType());
  698. result = SpirvEvalInfo(value).setConstant().setRValue();
  699. } else if (const auto *compoundAssignOp =
  700. dyn_cast<CompoundAssignOperator>(expr)) {
  701. // CompoundAssignOperator is a subclass of BinaryOperator. It should be
  702. // checked before BinaryOperator.
  703. result = doCompoundAssignOperator(compoundAssignOp);
  704. } else if (const auto *binOp = dyn_cast<BinaryOperator>(expr)) {
  705. result = doBinaryOperator(binOp);
  706. } else if (const auto *unaryOp = dyn_cast<UnaryOperator>(expr)) {
  707. result = doUnaryOperator(unaryOp);
  708. } else if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  709. result = doHLSLVectorElementExpr(vecElemExpr);
  710. } else if (const auto *matElemExpr = dyn_cast<ExtMatrixElementExpr>(expr)) {
  711. result = doExtMatrixElementExpr(matElemExpr);
  712. } else if (const auto *funcCall = dyn_cast<CallExpr>(expr)) {
  713. result = doCallExpr(funcCall);
  714. } else if (const auto *subscriptExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  715. result = doArraySubscriptExpr(subscriptExpr);
  716. } else if (const auto *condExpr = dyn_cast<ConditionalOperator>(expr)) {
  717. result = doConditionalOperator(condExpr);
  718. } else if (const auto *defaultArgExpr = dyn_cast<CXXDefaultArgExpr>(expr)) {
  719. result = doExpr(defaultArgExpr->getParam()->getDefaultArg());
  720. } else if (isa<CXXThisExpr>(expr)) {
  721. assert(curThis);
  722. result = curThis;
  723. } else {
  724. emitError("expression class '%0' unimplemented", expr->getExprLoc())
  725. << expr->getStmtClassName() << expr->getSourceRange();
  726. }
  727. return result;
  728. }
  729. SpirvEvalInfo SPIRVEmitter::loadIfGLValue(const Expr *expr) {
  730. // We are trying to load the value here, which is what an LValueToRValue
  731. // implicit cast is intended to do. We can ignore the cast if exists.
  732. expr = expr->IgnoreParenLValueCasts();
  733. return loadIfGLValue(expr, doExpr(expr));
  734. }
  735. SpirvEvalInfo SPIRVEmitter::loadIfGLValue(const Expr *expr,
  736. SpirvEvalInfo info) {
  737. // Do nothing if this is already rvalue
  738. if (info.isRValue())
  739. return info;
  740. // Check whether we are trying to load an array of opaque objects as a whole.
  741. // If true, we are likely to copy it as a whole. To assist per-element
  742. // copying, avoid the load here and return the pointer directly.
  743. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  744. if (TypeTranslator::isOpaqueArrayType(expr->getType()))
  745. return info;
  746. // Check whether we are trying to load an externally visible structured/byte
  747. // buffer as a whole. If true, it means we are creating alias for it. Avoid
  748. // the load and write the pointer directly to the alias variable then.
  749. //
  750. // Also for the case of alias function returns. If we are trying to load an
  751. // alias function return as a whole, it means we are assigning it to another
  752. // alias variable. Avoid the load and write the pointer directly.
  753. //
  754. // Note: legalization specific code
  755. if (isReferencingNonAliasStructuredOrByteBuffer(expr)) {
  756. return info.setRValue();
  757. }
  758. if (loadIfAliasVarRef(expr, info)) {
  759. // We are loading an alias variable as a whole here. This is likely for
  760. // wholesale assignments or function returns. Need to load the pointer.
  761. //
  762. // Note: legalization specific code
  763. return info;
  764. }
  765. uint32_t valType = 0;
  766. // TODO: Ouch. Very hacky. We need special path to get the value type if
  767. // we are loading a whole ConstantBuffer/TextureBuffer since the normal
  768. // type translation path won't work.
  769. if (const auto *declContext = isConstantTextureBufferDeclRef(expr)) {
  770. valType = declIdMapper.getCTBufferPushConstantTypeId(declContext);
  771. } else {
  772. valType =
  773. typeTranslator.translateType(expr->getType(), info.getLayoutRule());
  774. }
  775. uint32_t loadedId = theBuilder.createLoad(valType, info);
  776. // Decorate with NonUniformEXT if loading from a pointer with that property.
  777. // We are likely loading an element from the resource array here.
  778. if (info.isNonUniform()) {
  779. theBuilder.decorate(loadedId, spv::Decoration::NonUniformEXT);
  780. }
  781. // Special-case: According to the SPIR-V Spec: There is no physical size or
  782. // bit pattern defined for boolean type. Therefore an unsigned integer is used
  783. // to represent booleans when layout is required. In such cases, after loading
  784. // the uint, we should perform a comparison.
  785. {
  786. uint32_t vecSize = 1, numRows = 0, numCols = 0;
  787. if (info.getLayoutRule() != LayoutRule::Void &&
  788. isBoolOrVecMatOfBoolType(expr->getType())) {
  789. const auto exprType = expr->getType();
  790. QualType uintType = astContext.UnsignedIntTy;
  791. QualType boolType = astContext.BoolTy;
  792. if (TypeTranslator::isScalarType(exprType) ||
  793. TypeTranslator::isVectorType(exprType, nullptr, &vecSize)) {
  794. const auto fromType =
  795. vecSize == 1 ? uintType
  796. : astContext.getExtVectorType(uintType, vecSize);
  797. const auto toType =
  798. vecSize == 1 ? boolType
  799. : astContext.getExtVectorType(boolType, vecSize);
  800. loadedId = castToBool(loadedId, fromType, toType);
  801. } else {
  802. const bool isMat =
  803. TypeTranslator::isMxNMatrix(exprType, nullptr, &numRows, &numCols);
  804. assert(isMat);
  805. const auto uintRowQualType =
  806. astContext.getExtVectorType(uintType, numCols);
  807. const auto uintRowQualTypeId =
  808. typeTranslator.translateType(uintRowQualType);
  809. const auto boolRowQualType =
  810. astContext.getExtVectorType(boolType, numCols);
  811. const auto boolRowQualTypeId =
  812. typeTranslator.translateType(boolRowQualType);
  813. const uint32_t resultTypeId =
  814. theBuilder.getMatType(boolType, boolRowQualTypeId, numRows);
  815. llvm::SmallVector<uint32_t, 4> rows;
  816. for (uint32_t i = 0; i < numRows; ++i) {
  817. const auto row = theBuilder.createCompositeExtract(uintRowQualTypeId,
  818. loadedId, {i});
  819. rows.push_back(castToBool(row, uintRowQualType, boolRowQualType));
  820. }
  821. loadedId = theBuilder.createCompositeConstruct(resultTypeId, rows);
  822. }
  823. // Now that it is converted to Bool, it has no layout rule.
  824. // This result-id should be evaluated as bool from here on out.
  825. info.setLayoutRule(LayoutRule::Void);
  826. }
  827. }
  828. return info.setResultId(loadedId).setRValue();
  829. }
  830. SpirvEvalInfo SPIRVEmitter::loadIfAliasVarRef(const Expr *expr) {
  831. auto info = doExpr(expr);
  832. loadIfAliasVarRef(expr, info);
  833. return info;
  834. }
  835. bool SPIRVEmitter::loadIfAliasVarRef(const Expr *varExpr, SpirvEvalInfo &info) {
  836. if (info.containsAliasComponent() &&
  837. TypeTranslator::isAKindOfStructuredOrByteBuffer(varExpr->getType())) {
  838. // Aliased-to variables are all in the Uniform storage class with GLSL
  839. // std430 layout rules.
  840. const auto ptrType = typeTranslator.translateType(varExpr->getType());
  841. // Load the pointer of the aliased-to-variable if the expression has a
  842. // pointer to pointer type. That is, the expression itself is a lvalue.
  843. // (Note that we translate alias function return values as pointer types,
  844. // not pointer to pointer types.)
  845. if (varExpr->isGLValue())
  846. info.setResultId(theBuilder.createLoad(ptrType, info));
  847. info.setStorageClass(spv::StorageClass::Uniform)
  848. .setLayoutRule(spirvOptions.sBufferLayoutRule)
  849. // Now it is a pointer to the global resource, which is lvalue.
  850. .setRValue(false)
  851. // Set to false to indicate that we've performed dereference over the
  852. // pointer-to-pointer and now should fallback to the normal path
  853. .setContainsAliasComponent(false);
  854. return true;
  855. }
  856. return false;
  857. }
  858. uint32_t SPIRVEmitter::castToType(uint32_t value, QualType fromType,
  859. QualType toType, SourceLocation srcLoc) {
  860. if (isFloatOrVecOfFloatType(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 (isBoolOrVecOfBoolType(toType))
  867. return castToBool(value, fromType, toType);
  868. if (isSintOrVecOfSintType(toType) || isUintOrVecOfUintType(toType))
  869. return castToInt(value, fromType, toType, srcLoc);
  870. emitError("casting to type %0 unimplemented", {}) << toType;
  871. return 0;
  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<uint32_t>();
  893. continueStack = std::stack<uint32_t>();
  894. // This will allow the entry-point name to be something like
  895. // myNamespace::myEntrypointFunc.
  896. std::string funcName = getFnName(decl);
  897. uint32_t funcId = 0;
  898. if (funcName == entryFunctionName) {
  899. // The entry function surely does not have pre-assigned <result-id> for
  900. // it like other functions that got added to the work queue following
  901. // function calls.
  902. funcId = theContext.takeNextId();
  903. funcName = "src." + funcName;
  904. // Create wrapper for the entry function
  905. if (!emitEntryFunctionWrapper(decl, funcId))
  906. return;
  907. } else {
  908. // Non-entry functions are added to the work queue following function
  909. // calls. We have already assigned <result-id>s for it when translating
  910. // its call site. Query it here.
  911. funcId = declIdMapper.getDeclEvalInfo(decl);
  912. }
  913. const uint32_t retType =
  914. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(decl);
  915. // Construct the function signature.
  916. llvm::SmallVector<uint32_t, 4> paramTypes;
  917. bool isNonStaticMemberFn = false;
  918. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(decl)) {
  919. isNonStaticMemberFn = !memberFn->isStatic();
  920. if (isNonStaticMemberFn) {
  921. // For non-static member function, the first parameter should be the
  922. // object on which we are invoking this method.
  923. const uint32_t valueType = typeTranslator.translateType(
  924. memberFn->getThisType(astContext)->getPointeeType());
  925. const uint32_t ptrType =
  926. theBuilder.getPointerType(valueType, spv::StorageClass::Function);
  927. paramTypes.push_back(ptrType);
  928. }
  929. }
  930. for (const auto *param : decl->params()) {
  931. const uint32_t valueType =
  932. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  933. const uint32_t ptrType =
  934. theBuilder.getPointerType(valueType, spv::StorageClass::Function);
  935. paramTypes.push_back(ptrType);
  936. }
  937. const uint32_t funcType = theBuilder.getFunctionType(retType, paramTypes);
  938. theBuilder.beginFunction(funcType, retType, funcName, funcId);
  939. if (isNonStaticMemberFn) {
  940. // Remember the parameter for the this object so later we can handle
  941. // CXXThisExpr correctly.
  942. curThis = theBuilder.addFnParam(paramTypes[0], "param.this");
  943. }
  944. // Create all parameters.
  945. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  946. const ParmVarDecl *paramDecl = decl->getParamDecl(i);
  947. (void)declIdMapper.createFnParam(paramDecl);
  948. }
  949. if (decl->hasBody()) {
  950. // The entry basic block.
  951. const uint32_t entryLabel = theBuilder.createBasicBlock("bb.entry");
  952. theBuilder.setInsertPoint(entryLabel);
  953. // Process all statments in the body.
  954. doStmt(decl->getBody());
  955. // We have processed all Stmts in this function and now in the last
  956. // basic block. Make sure we have a termination instruction.
  957. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  958. const auto retType = decl->getReturnType();
  959. if (retType->isVoidType()) {
  960. theBuilder.createReturn();
  961. } else {
  962. // If the source code does not provide a proper return value for some
  963. // control flow path, it's undefined behavior. We just return null
  964. // value here.
  965. theBuilder.createReturnValue(
  966. theBuilder.getConstantNull(typeTranslator.translateType(retType)));
  967. }
  968. }
  969. }
  970. theBuilder.endFunction();
  971. }
  972. bool SPIRVEmitter::validateVKAttributes(const NamedDecl *decl) {
  973. bool success = true;
  974. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  975. const auto varType = varDecl->getType();
  976. if ((TypeTranslator::isSubpassInput(varType) ||
  977. TypeTranslator::isSubpassInputMS(varType)) &&
  978. !varDecl->hasAttr<VKInputAttachmentIndexAttr>()) {
  979. emitError("missing vk::input_attachment_index attribute",
  980. varDecl->getLocation());
  981. success = false;
  982. }
  983. }
  984. if (const auto *iaiAttr = decl->getAttr<VKInputAttachmentIndexAttr>()) {
  985. if (!shaderModel.IsPS()) {
  986. emitError("SubpassInput(MS) only allowed in pixel shader",
  987. decl->getLocation());
  988. success = false;
  989. }
  990. if (!decl->isExternallyVisible()) {
  991. emitError("SubpassInput(MS) must be externally visible",
  992. decl->getLocation());
  993. success = false;
  994. }
  995. // We only allow VKInputAttachmentIndexAttr to be attached to global
  996. // variables. So it should be fine to cast here.
  997. const auto elementType =
  998. hlsl::GetHLSLResourceResultType(cast<VarDecl>(decl)->getType());
  999. if (!TypeTranslator::isScalarType(elementType) &&
  1000. !TypeTranslator::isVectorType(elementType)) {
  1001. emitError(
  1002. "only scalar/vector types allowed as SubpassInput(MS) parameter type",
  1003. decl->getLocation());
  1004. // Return directly to avoid further type processing, which will hit
  1005. // asserts in TypeTranslator.
  1006. return false;
  1007. }
  1008. }
  1009. // The frontend will make sure that
  1010. // * vk::push_constant applies to global variables of struct type
  1011. // * vk::binding applies to global variables or cbuffers/tbuffers
  1012. // * vk::counter_binding applies to global variables of RW/Append/Consume
  1013. // StructuredBuffer
  1014. // * vk::location applies to function parameters/returns and struct fields
  1015. // So the only case we need to check co-existence is vk::push_constant and
  1016. // vk::binding.
  1017. if (const auto *pcAttr = decl->getAttr<VKPushConstantAttr>()) {
  1018. const auto loc = pcAttr->getLocation();
  1019. if (seenPushConstantAt.isInvalid()) {
  1020. seenPushConstantAt = loc;
  1021. } else {
  1022. // TODO: Actually this is slightly incorrect. The Vulkan spec says:
  1023. // There must be no more than one push constant block statically used
  1024. // per shader entry point.
  1025. // But we are checking whether there are more than one push constant
  1026. // blocks defined. Tracking usage requires more work.
  1027. emitError("cannot have more than one push constant block", loc);
  1028. emitNote("push constant block previously defined here",
  1029. seenPushConstantAt);
  1030. success = false;
  1031. }
  1032. if (decl->hasAttr<VKBindingAttr>()) {
  1033. emitError("vk::push_constant attribute cannot be used together with "
  1034. "vk::binding attribute",
  1035. loc);
  1036. success = false;
  1037. }
  1038. }
  1039. return success;
  1040. }
  1041. void SPIRVEmitter::doHLSLBufferDecl(const HLSLBufferDecl *bufferDecl) {
  1042. // This is a cbuffer/tbuffer decl.
  1043. // Check and emit warnings for member intializers which are not
  1044. // supported in Vulkan
  1045. for (const auto *member : bufferDecl->decls()) {
  1046. if (const auto *varMember = dyn_cast<VarDecl>(member)) {
  1047. if (const auto *init = varMember->getInit())
  1048. emitWarning("%select{tbuffer|cbuffer}0 member initializer "
  1049. "ignored since no Vulkan equivalent",
  1050. init->getExprLoc())
  1051. << bufferDecl->isCBuffer() << init->getSourceRange();
  1052. // We cannot handle external initialization of column-major matrices now.
  1053. if (typeTranslator.isOrContainsNonFpColMajorMatrix(varMember->getType(),
  1054. varMember)) {
  1055. emitError("externally initialized non-floating-point column-major "
  1056. "matrices not supported yet",
  1057. varMember->getLocation());
  1058. }
  1059. }
  1060. }
  1061. if (!validateVKAttributes(bufferDecl))
  1062. return;
  1063. (void)declIdMapper.createCTBuffer(bufferDecl);
  1064. }
  1065. void SPIRVEmitter::doRecordDecl(const RecordDecl *recordDecl) {
  1066. // Ignore implict records
  1067. // Somehow we'll have implicit records with:
  1068. // static const int Length = count;
  1069. // that can mess up with the normal CodeGen.
  1070. if (recordDecl->isImplicit())
  1071. return;
  1072. // Handle each static member with inline initializer.
  1073. // Each static member has a corresponding VarDecl inside the
  1074. // RecordDecl. For those defined in the translation unit,
  1075. // their VarDecls do not have initializer.
  1076. for (auto *subDecl : recordDecl->decls())
  1077. if (auto *varDecl = dyn_cast<VarDecl>(subDecl))
  1078. if (varDecl->isStaticDataMember() && varDecl->hasInit())
  1079. doVarDecl(varDecl);
  1080. }
  1081. void SPIRVEmitter::doVarDecl(const VarDecl *decl) {
  1082. if (!validateVKAttributes(decl))
  1083. return;
  1084. // We cannot handle external initialization of column-major matrices now.
  1085. if (isExternalVar(decl) &&
  1086. typeTranslator.isOrContainsNonFpColMajorMatrix(decl->getType(), decl)) {
  1087. emitError("externally initialized non-floating-point column-major "
  1088. "matrices not supported yet",
  1089. decl->getLocation());
  1090. }
  1091. if (const auto *arrayType =
  1092. astContext.getAsConstantArrayType(decl->getType())) {
  1093. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(
  1094. arrayType->getElementType())) {
  1095. emitError("arrays of structured/byte buffers unsupported",
  1096. decl->getLocation());
  1097. return;
  1098. }
  1099. }
  1100. if (decl->hasAttr<VKConstantIdAttr>()) {
  1101. // This is a VarDecl for specialization constant.
  1102. createSpecConstant(decl);
  1103. return;
  1104. }
  1105. if (decl->hasAttr<VKPushConstantAttr>()) {
  1106. // This is a VarDecl for PushConstant block.
  1107. (void)declIdMapper.createPushConstant(decl);
  1108. return;
  1109. }
  1110. if (isa<HLSLBufferDecl>(decl->getDeclContext())) {
  1111. // This is a VarDecl of a ConstantBuffer/TextureBuffer type.
  1112. (void)declIdMapper.createCTBuffer(decl);
  1113. return;
  1114. }
  1115. SpirvEvalInfo varId(0);
  1116. // The contents in externally visible variables can be updated via the
  1117. // pipeline. They should be handled differently from file and function scope
  1118. // variables.
  1119. // File scope variables (static "global" and "local" variables) belongs to
  1120. // the Private storage class, while function scope variables (normal "local"
  1121. // variables) belongs to the Function storage class.
  1122. if (isExternalVar(decl)) {
  1123. varId = declIdMapper.createExternVar(decl);
  1124. } else {
  1125. // We already know the variable is not externally visible here. If it does
  1126. // not have local storage, it should be file scope variable.
  1127. const bool isFileScopeVar = !decl->hasLocalStorage();
  1128. if (isFileScopeVar)
  1129. varId = declIdMapper.createFileVar(decl, llvm::None);
  1130. else
  1131. varId = declIdMapper.createFnVar(decl, llvm::None);
  1132. // Emit OpStore to initialize the variable
  1133. // TODO: revert back to use OpVariable initializer
  1134. // We should only evaluate the initializer once for a static variable.
  1135. if (isFileScopeVar) {
  1136. if (decl->isStaticLocal()) {
  1137. initOnce(decl->getType(), decl->getName(), varId, decl->getInit());
  1138. } else {
  1139. // Defer to initialize these global variables at the beginning of the
  1140. // entry function.
  1141. toInitGloalVars.push_back(decl);
  1142. }
  1143. }
  1144. // Function local variables. Just emit OpStore at the current insert point.
  1145. else if (const Expr *init = decl->getInit()) {
  1146. if (const auto constId = tryToEvaluateAsConst(init))
  1147. theBuilder.createStore(varId, constId);
  1148. else
  1149. storeValue(varId, loadIfGLValue(init), decl->getType());
  1150. // Update counter variable associated with local variables
  1151. tryToAssignCounterVar(decl, init);
  1152. }
  1153. // Variables that are not externally visible and of opaque types should
  1154. // request legalization.
  1155. if (!needsLegalization && TypeTranslator::isOpaqueType(decl->getType()))
  1156. needsLegalization = true;
  1157. }
  1158. if (TypeTranslator::isRelaxedPrecisionType(decl->getType(), spirvOptions)) {
  1159. theBuilder.decorate(varId, spv::Decoration::RelaxedPrecision);
  1160. }
  1161. // All variables that are of opaque struct types should request legalization.
  1162. if (!needsLegalization && TypeTranslator::isOpaqueStructType(decl->getType()))
  1163. needsLegalization = true;
  1164. }
  1165. spv::LoopControlMask SPIRVEmitter::translateLoopAttribute(const Stmt *stmt,
  1166. const Attr &attr) {
  1167. switch (attr.getKind()) {
  1168. case attr::HLSLLoop:
  1169. case attr::HLSLFastOpt:
  1170. return spv::LoopControlMask::DontUnroll;
  1171. case attr::HLSLUnroll:
  1172. return spv::LoopControlMask::Unroll;
  1173. case attr::HLSLAllowUAVCondition:
  1174. emitWarning("unsupported allow_uav_condition attribute ignored",
  1175. stmt->getLocStart());
  1176. break;
  1177. default:
  1178. llvm_unreachable("found unknown loop attribute");
  1179. }
  1180. return spv::LoopControlMask::MaskNone;
  1181. }
  1182. void SPIRVEmitter::doDiscardStmt(const DiscardStmt *discardStmt) {
  1183. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1184. theBuilder.createKill();
  1185. // Some statements that alter the control flow (break, continue, return, and
  1186. // discard), require creation of a new basic block to hold any statement that
  1187. // may follow them.
  1188. const uint32_t newBB = theBuilder.createBasicBlock();
  1189. theBuilder.setInsertPoint(newBB);
  1190. }
  1191. void SPIRVEmitter::doDoStmt(const DoStmt *theDoStmt,
  1192. llvm::ArrayRef<const Attr *> attrs) {
  1193. // do-while loops are composed of:
  1194. //
  1195. // do {
  1196. // <body>
  1197. // } while(<check>);
  1198. //
  1199. // SPIR-V requires loops to have a merge basic block as well as a continue
  1200. // basic block. Even though do-while loops do not have an explicit continue
  1201. // block as in for-loops, we still do need to create a continue block.
  1202. //
  1203. // Since SPIR-V requires structured control flow, we need two more basic
  1204. // blocks, <header> and <merge>. <header> is the block before control flow
  1205. // diverges, and <merge> is the block where control flow subsequently
  1206. // converges. The <check> can be performed in the <continue> basic block.
  1207. // The final CFG should normally be like the following. Exceptions
  1208. // will occur with non-local exits like loop breaks or early returns.
  1209. //
  1210. // +----------+
  1211. // | header | <-----------------------------------+
  1212. // +----------+ |
  1213. // | | (true)
  1214. // v |
  1215. // +------+ +--------------------+ |
  1216. // | body | ----> | continue (<check>) |-----------+
  1217. // +------+ +--------------------+
  1218. // |
  1219. // | (false)
  1220. // +-------+ |
  1221. // | merge | <-------------+
  1222. // +-------+
  1223. //
  1224. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1225. const spv::LoopControlMask loopControl =
  1226. attrs.empty() ? spv::LoopControlMask::MaskNone
  1227. : translateLoopAttribute(theDoStmt, *attrs.front());
  1228. // Create basic blocks
  1229. const uint32_t headerBB = theBuilder.createBasicBlock("do_while.header");
  1230. const uint32_t bodyBB = theBuilder.createBasicBlock("do_while.body");
  1231. const uint32_t continueBB = theBuilder.createBasicBlock("do_while.continue");
  1232. const uint32_t mergeBB = theBuilder.createBasicBlock("do_while.merge");
  1233. // Make sure any continue statements branch to the continue block, and any
  1234. // break statements branch to the merge block.
  1235. continueStack.push(continueBB);
  1236. breakStack.push(mergeBB);
  1237. // Branch from the current insert point to the header block.
  1238. theBuilder.createBranch(headerBB);
  1239. theBuilder.addSuccessor(headerBB);
  1240. // Process the <header> block
  1241. // The header block must always branch to the body.
  1242. theBuilder.setInsertPoint(headerBB);
  1243. theBuilder.createBranch(bodyBB, mergeBB, continueBB, loopControl);
  1244. theBuilder.addSuccessor(bodyBB);
  1245. // The current basic block has OpLoopMerge instruction. We need to set its
  1246. // continue and merge target.
  1247. theBuilder.setContinueTarget(continueBB);
  1248. theBuilder.setMergeTarget(mergeBB);
  1249. // Process the <body> block
  1250. theBuilder.setInsertPoint(bodyBB);
  1251. if (const Stmt *body = theDoStmt->getBody()) {
  1252. doStmt(body);
  1253. }
  1254. if (!theBuilder.isCurrentBasicBlockTerminated())
  1255. theBuilder.createBranch(continueBB);
  1256. theBuilder.addSuccessor(continueBB);
  1257. // Process the <continue> block. The check for whether the loop should
  1258. // continue lies in the continue block.
  1259. // *NOTE*: There's a SPIR-V rule that when a conditional branch is to occur in
  1260. // a continue block of a loop, there should be no OpSelectionMerge. Only an
  1261. // OpBranchConditional must be specified.
  1262. theBuilder.setInsertPoint(continueBB);
  1263. uint32_t condition = 0;
  1264. if (const Expr *check = theDoStmt->getCond()) {
  1265. condition = doExpr(check);
  1266. } else {
  1267. condition = theBuilder.getConstantBool(true);
  1268. }
  1269. theBuilder.createConditionalBranch(condition, headerBB, mergeBB);
  1270. theBuilder.addSuccessor(headerBB);
  1271. theBuilder.addSuccessor(mergeBB);
  1272. // Set insertion point to the <merge> block for subsequent statements
  1273. theBuilder.setInsertPoint(mergeBB);
  1274. // Done with the current scope's continue block and merge block.
  1275. continueStack.pop();
  1276. breakStack.pop();
  1277. }
  1278. void SPIRVEmitter::doContinueStmt(const ContinueStmt *continueStmt) {
  1279. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1280. const uint32_t continueTargetBB = continueStack.top();
  1281. theBuilder.createBranch(continueTargetBB);
  1282. theBuilder.addSuccessor(continueTargetBB);
  1283. // Some statements that alter the control flow (break, continue, return, and
  1284. // discard), require creation of a new basic block to hold any statement that
  1285. // may follow them. For example: StmtB and StmtC below are put inside a new
  1286. // basic block which is unreachable.
  1287. //
  1288. // while (true) {
  1289. // StmtA;
  1290. // continue;
  1291. // StmtB;
  1292. // StmtC;
  1293. // }
  1294. const uint32_t newBB = theBuilder.createBasicBlock();
  1295. theBuilder.setInsertPoint(newBB);
  1296. }
  1297. void SPIRVEmitter::doWhileStmt(const WhileStmt *whileStmt,
  1298. llvm::ArrayRef<const Attr *> attrs) {
  1299. // While loops are composed of:
  1300. // while (<check>) { <body> }
  1301. //
  1302. // SPIR-V requires loops to have a merge basic block as well as a continue
  1303. // basic block. Even though while loops do not have an explicit continue
  1304. // block as in for-loops, we still do need to create a continue block.
  1305. //
  1306. // Since SPIR-V requires structured control flow, we need two more basic
  1307. // blocks, <header> and <merge>. <header> is the block before control flow
  1308. // diverges, and <merge> is the block where control flow subsequently
  1309. // converges. The <check> block can take the responsibility of the <header>
  1310. // block. The final CFG should normally be like the following. Exceptions
  1311. // will occur with non-local exits like loop breaks or early returns.
  1312. //
  1313. // +----------+
  1314. // | header | <------------------+
  1315. // | (check) | |
  1316. // +----------+ |
  1317. // | |
  1318. // +-------+-------+ |
  1319. // | false | true |
  1320. // | v |
  1321. // | +------+ +------------------+
  1322. // | | body | --> | continue (no-op) |
  1323. // v +------+ +------------------+
  1324. // +-------+
  1325. // | merge |
  1326. // +-------+
  1327. //
  1328. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1329. const spv::LoopControlMask loopControl =
  1330. attrs.empty() ? spv::LoopControlMask::MaskNone
  1331. : translateLoopAttribute(whileStmt, *attrs.front());
  1332. // Create basic blocks
  1333. const uint32_t checkBB = theBuilder.createBasicBlock("while.check");
  1334. const uint32_t bodyBB = theBuilder.createBasicBlock("while.body");
  1335. const uint32_t continueBB = theBuilder.createBasicBlock("while.continue");
  1336. const uint32_t mergeBB = theBuilder.createBasicBlock("while.merge");
  1337. // Make sure any continue statements branch to the continue block, and any
  1338. // break statements branch to the merge block.
  1339. continueStack.push(continueBB);
  1340. breakStack.push(mergeBB);
  1341. // Process the <check> block
  1342. theBuilder.createBranch(checkBB);
  1343. theBuilder.addSuccessor(checkBB);
  1344. theBuilder.setInsertPoint(checkBB);
  1345. // If we have:
  1346. // while (int a = foo()) {...}
  1347. // we should evaluate 'a' by calling 'foo()' every single time the check has
  1348. // to occur.
  1349. if (const auto *condVarDecl = whileStmt->getConditionVariableDeclStmt())
  1350. doStmt(condVarDecl);
  1351. uint32_t condition = 0;
  1352. if (const Expr *check = whileStmt->getCond()) {
  1353. condition = doExpr(check);
  1354. } else {
  1355. condition = theBuilder.getConstantBool(true);
  1356. }
  1357. theBuilder.createConditionalBranch(condition, bodyBB,
  1358. /*false branch*/ mergeBB,
  1359. /*merge*/ mergeBB, continueBB,
  1360. spv::SelectionControlMask::MaskNone,
  1361. loopControl);
  1362. theBuilder.addSuccessor(bodyBB);
  1363. theBuilder.addSuccessor(mergeBB);
  1364. // The current basic block has OpLoopMerge instruction. We need to set its
  1365. // continue and merge target.
  1366. theBuilder.setContinueTarget(continueBB);
  1367. theBuilder.setMergeTarget(mergeBB);
  1368. // Process the <body> block
  1369. theBuilder.setInsertPoint(bodyBB);
  1370. if (const Stmt *body = whileStmt->getBody()) {
  1371. doStmt(body);
  1372. }
  1373. if (!theBuilder.isCurrentBasicBlockTerminated())
  1374. theBuilder.createBranch(continueBB);
  1375. theBuilder.addSuccessor(continueBB);
  1376. // Process the <continue> block. While loops do not have an explicit
  1377. // continue block. The continue block just branches to the <check> block.
  1378. theBuilder.setInsertPoint(continueBB);
  1379. theBuilder.createBranch(checkBB);
  1380. theBuilder.addSuccessor(checkBB);
  1381. // Set insertion point to the <merge> block for subsequent statements
  1382. theBuilder.setInsertPoint(mergeBB);
  1383. // Done with the current scope's continue and merge blocks.
  1384. continueStack.pop();
  1385. breakStack.pop();
  1386. }
  1387. void SPIRVEmitter::doForStmt(const ForStmt *forStmt,
  1388. llvm::ArrayRef<const Attr *> attrs) {
  1389. // for loops are composed of:
  1390. // for (<init>; <check>; <continue>) <body>
  1391. //
  1392. // To translate a for loop, we'll need to emit all <init> statements
  1393. // in the current basic block, and then have separate basic blocks for
  1394. // <check>, <continue>, and <body>. Besides, since SPIR-V requires
  1395. // structured control flow, we need two more basic blocks, <header>
  1396. // and <merge>. <header> is the block before control flow diverges,
  1397. // while <merge> is the block where control flow subsequently converges.
  1398. // The <check> block can take the responsibility of the <header> block.
  1399. // The final CFG should normally be like the following. Exceptions will
  1400. // occur with non-local exits like loop breaks or early returns.
  1401. // +--------+
  1402. // | init |
  1403. // +--------+
  1404. // |
  1405. // v
  1406. // +----------+
  1407. // | header | <---------------+
  1408. // | (check) | |
  1409. // +----------+ |
  1410. // | |
  1411. // +-------+-------+ |
  1412. // | false | true |
  1413. // | v |
  1414. // | +------+ +----------+
  1415. // | | body | --> | continue |
  1416. // v +------+ +----------+
  1417. // +-------+
  1418. // | merge |
  1419. // +-------+
  1420. //
  1421. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1422. const spv::LoopControlMask loopControl =
  1423. attrs.empty() ? spv::LoopControlMask::MaskNone
  1424. : translateLoopAttribute(forStmt, *attrs.front());
  1425. // Create basic blocks
  1426. const uint32_t checkBB = theBuilder.createBasicBlock("for.check");
  1427. const uint32_t bodyBB = theBuilder.createBasicBlock("for.body");
  1428. const uint32_t continueBB = theBuilder.createBasicBlock("for.continue");
  1429. const uint32_t mergeBB = theBuilder.createBasicBlock("for.merge");
  1430. // Make sure any continue statements branch to the continue block, and any
  1431. // break statements branch to the merge block.
  1432. continueStack.push(continueBB);
  1433. breakStack.push(mergeBB);
  1434. // Process the <init> block
  1435. if (const Stmt *initStmt = forStmt->getInit()) {
  1436. doStmt(initStmt);
  1437. }
  1438. theBuilder.createBranch(checkBB);
  1439. theBuilder.addSuccessor(checkBB);
  1440. // Process the <check> block
  1441. theBuilder.setInsertPoint(checkBB);
  1442. uint32_t condition;
  1443. if (const Expr *check = forStmt->getCond()) {
  1444. condition = doExpr(check);
  1445. } else {
  1446. condition = theBuilder.getConstantBool(true);
  1447. }
  1448. theBuilder.createConditionalBranch(condition, bodyBB,
  1449. /*false branch*/ mergeBB,
  1450. /*merge*/ mergeBB, continueBB,
  1451. spv::SelectionControlMask::MaskNone,
  1452. loopControl);
  1453. theBuilder.addSuccessor(bodyBB);
  1454. theBuilder.addSuccessor(mergeBB);
  1455. // The current basic block has OpLoopMerge instruction. We need to set its
  1456. // continue and merge target.
  1457. theBuilder.setContinueTarget(continueBB);
  1458. theBuilder.setMergeTarget(mergeBB);
  1459. // Process the <body> block
  1460. theBuilder.setInsertPoint(bodyBB);
  1461. if (const Stmt *body = forStmt->getBody()) {
  1462. doStmt(body);
  1463. }
  1464. if (!theBuilder.isCurrentBasicBlockTerminated())
  1465. theBuilder.createBranch(continueBB);
  1466. theBuilder.addSuccessor(continueBB);
  1467. // Process the <continue> block
  1468. theBuilder.setInsertPoint(continueBB);
  1469. if (const Expr *cont = forStmt->getInc()) {
  1470. doExpr(cont);
  1471. }
  1472. theBuilder.createBranch(checkBB); // <continue> should jump back to header
  1473. theBuilder.addSuccessor(checkBB);
  1474. // Set insertion point to the <merge> block for subsequent statements
  1475. theBuilder.setInsertPoint(mergeBB);
  1476. // Done with the current scope's continue block and merge block.
  1477. continueStack.pop();
  1478. breakStack.pop();
  1479. }
  1480. void SPIRVEmitter::doIfStmt(const IfStmt *ifStmt,
  1481. llvm::ArrayRef<const Attr *> attrs) {
  1482. // if statements are composed of:
  1483. // if (<check>) { <then> } else { <else> }
  1484. //
  1485. // To translate if statements, we'll need to emit the <check> expressions
  1486. // in the current basic block, and then create separate basic blocks for
  1487. // <then> and <else>. Additionally, we'll need a <merge> block as per
  1488. // SPIR-V's structured control flow requirements. Depending whether there
  1489. // exists the else branch, the final CFG should normally be like the
  1490. // following. Exceptions will occur with non-local exits like loop breaks
  1491. // or early returns.
  1492. // +-------+ +-------+
  1493. // | check | | check |
  1494. // +-------+ +-------+
  1495. // | |
  1496. // +-------+-------+ +-----+-----+
  1497. // | true | false | true | false
  1498. // v v or v |
  1499. // +------+ +------+ +------+ |
  1500. // | then | | else | | then | |
  1501. // +------+ +------+ +------+ |
  1502. // | | | v
  1503. // | +-------+ | | +-------+
  1504. // +-> | merge | <-+ +---> | merge |
  1505. // +-------+ +-------+
  1506. { // Try to see if we can const-eval the condition
  1507. bool condition = false;
  1508. if (ifStmt->getCond()->EvaluateAsBooleanCondition(condition, astContext)) {
  1509. if (condition) {
  1510. doStmt(ifStmt->getThen());
  1511. } else if (ifStmt->getElse()) {
  1512. doStmt(ifStmt->getElse());
  1513. }
  1514. return;
  1515. }
  1516. }
  1517. auto selectionControl = spv::SelectionControlMask::MaskNone;
  1518. if (!attrs.empty()) {
  1519. const Attr *attribute = attrs.front();
  1520. switch (attribute->getKind()) {
  1521. case attr::HLSLBranch:
  1522. selectionControl = spv::SelectionControlMask::DontFlatten;
  1523. break;
  1524. case attr::HLSLFlatten:
  1525. selectionControl = spv::SelectionControlMask::Flatten;
  1526. break;
  1527. default:
  1528. emitWarning("unknown if statement attribute '%0' ignored",
  1529. attribute->getLocation())
  1530. << attribute->getSpelling();
  1531. break;
  1532. }
  1533. }
  1534. if (const auto *declStmt = ifStmt->getConditionVariableDeclStmt())
  1535. doDeclStmt(declStmt);
  1536. // First emit the instruction for evaluating the condition.
  1537. const uint32_t condition = doExpr(ifStmt->getCond());
  1538. // Then we need to emit the instruction for the conditional branch.
  1539. // We'll need the <label-id> for the then/else/merge block to do so.
  1540. const bool hasElse = ifStmt->getElse() != nullptr;
  1541. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  1542. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  1543. const uint32_t elseBB =
  1544. hasElse ? theBuilder.createBasicBlock("if.false") : mergeBB;
  1545. // Create the branch instruction. This will end the current basic block.
  1546. theBuilder.createConditionalBranch(condition, thenBB, elseBB, mergeBB,
  1547. /*continue*/ 0, selectionControl);
  1548. theBuilder.addSuccessor(thenBB);
  1549. theBuilder.addSuccessor(elseBB);
  1550. // The current basic block has the OpSelectionMerge instruction. We need
  1551. // to record its merge target.
  1552. theBuilder.setMergeTarget(mergeBB);
  1553. // Handle the then branch
  1554. theBuilder.setInsertPoint(thenBB);
  1555. doStmt(ifStmt->getThen());
  1556. if (!theBuilder.isCurrentBasicBlockTerminated())
  1557. theBuilder.createBranch(mergeBB);
  1558. theBuilder.addSuccessor(mergeBB);
  1559. // Handle the else branch (if exists)
  1560. if (hasElse) {
  1561. theBuilder.setInsertPoint(elseBB);
  1562. doStmt(ifStmt->getElse());
  1563. if (!theBuilder.isCurrentBasicBlockTerminated())
  1564. theBuilder.createBranch(mergeBB);
  1565. theBuilder.addSuccessor(mergeBB);
  1566. }
  1567. // From now on, we'll emit instructions into the merge block.
  1568. theBuilder.setInsertPoint(mergeBB);
  1569. }
  1570. void SPIRVEmitter::doReturnStmt(const ReturnStmt *stmt) {
  1571. if (const auto *retVal = stmt->getRetValue()) {
  1572. // Update counter variable associated with function returns
  1573. tryToAssignCounterVar(curFunction, retVal);
  1574. const auto retInfo = loadIfGLValue(retVal);
  1575. const auto retType = retVal->getType();
  1576. if (retInfo.getStorageClass() != spv::StorageClass::Function &&
  1577. retType->isStructureType()) {
  1578. // We are returning some value from a non-Function storage class. Need to
  1579. // create a temporary variable to "convert" the value to Function storage
  1580. // class and then return.
  1581. const uint32_t valType = typeTranslator.translateType(retType);
  1582. const uint32_t tempVar = theBuilder.addFnVar(valType, "temp.var.ret");
  1583. storeValue(tempVar, retInfo, retType);
  1584. theBuilder.createReturnValue(theBuilder.createLoad(valType, tempVar));
  1585. } else {
  1586. theBuilder.createReturnValue(retInfo);
  1587. }
  1588. } else {
  1589. theBuilder.createReturn();
  1590. }
  1591. // We are translating a ReturnStmt, we should be in some function's body.
  1592. assert(curFunction->hasBody());
  1593. // If this return statement is the last statement in the function, then
  1594. // whe have no more work to do.
  1595. if (cast<CompoundStmt>(curFunction->getBody())->body_back() == stmt)
  1596. return;
  1597. // Some statements that alter the control flow (break, continue, return, and
  1598. // discard), require creation of a new basic block to hold any statement that
  1599. // may follow them. In this case, the newly created basic block will contain
  1600. // any statement that may come after an early return.
  1601. const uint32_t newBB = theBuilder.createBasicBlock();
  1602. theBuilder.setInsertPoint(newBB);
  1603. }
  1604. void SPIRVEmitter::doBreakStmt(const BreakStmt *breakStmt) {
  1605. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1606. uint32_t breakTargetBB = breakStack.top();
  1607. theBuilder.addSuccessor(breakTargetBB);
  1608. theBuilder.createBranch(breakTargetBB);
  1609. // Some statements that alter the control flow (break, continue, return, and
  1610. // discard), require creation of a new basic block to hold any statement that
  1611. // may follow them. For example: StmtB and StmtC below are put inside a new
  1612. // basic block which is unreachable.
  1613. //
  1614. // while (true) {
  1615. // StmtA;
  1616. // break;
  1617. // StmtB;
  1618. // StmtC;
  1619. // }
  1620. const uint32_t newBB = theBuilder.createBasicBlock();
  1621. theBuilder.setInsertPoint(newBB);
  1622. }
  1623. void SPIRVEmitter::doSwitchStmt(const SwitchStmt *switchStmt,
  1624. llvm::ArrayRef<const Attr *> attrs) {
  1625. // Switch statements are composed of:
  1626. // switch (<condition variable>) {
  1627. // <CaseStmt>
  1628. // <CaseStmt>
  1629. // <CaseStmt>
  1630. // <DefaultStmt> (optional)
  1631. // }
  1632. //
  1633. // +-------+
  1634. // | check |
  1635. // +-------+
  1636. // |
  1637. // +-------+-------+----------------+---------------+
  1638. // | 1 | 2 | 3 | (others)
  1639. // v v v v
  1640. // +-------+ +-------------+ +-------+ +------------+
  1641. // | case1 | | case2 | | case3 | ... | default |
  1642. // | | |(fallthrough)|---->| | | (optional) |
  1643. // +-------+ |+------------+ +-------+ +------------+
  1644. // | | |
  1645. // | | |
  1646. // | +-------+ | |
  1647. // | | | <--------------------+ |
  1648. // +-> | merge | |
  1649. // | | <-------------------------------------+
  1650. // +-------+
  1651. // If no attributes are given, or if "forcecase" attribute was provided,
  1652. // we'll do our best to use OpSwitch if possible.
  1653. // If any of the cases compares to a variable (rather than an integer
  1654. // literal), we cannot use OpSwitch because OpSwitch expects literal
  1655. // numbers as parameters.
  1656. const bool isAttrForceCase =
  1657. !attrs.empty() && attrs.front()->getKind() == attr::HLSLForceCase;
  1658. const bool canUseSpirvOpSwitch =
  1659. (attrs.empty() || isAttrForceCase) &&
  1660. allSwitchCasesAreIntegerLiterals(switchStmt->getBody());
  1661. if (isAttrForceCase && !canUseSpirvOpSwitch)
  1662. emitWarning("ignored 'forcecase' attribute for the switch statement "
  1663. "since one or more case values are not integer literals",
  1664. switchStmt->getLocStart());
  1665. if (canUseSpirvOpSwitch)
  1666. processSwitchStmtUsingSpirvOpSwitch(switchStmt);
  1667. else
  1668. processSwitchStmtUsingIfStmts(switchStmt);
  1669. }
  1670. SpirvEvalInfo
  1671. SPIRVEmitter::doArraySubscriptExpr(const ArraySubscriptExpr *expr) {
  1672. // Make sure we don't have previously unhandled NonUniformResourceIndex()
  1673. assert(!foundNonUniformResourceIndex);
  1674. llvm::SmallVector<uint32_t, 4> indices;
  1675. const auto *base = collectArrayStructIndices(expr, &indices);
  1676. auto info = loadIfAliasVarRef(base);
  1677. if (foundNonUniformResourceIndex) {
  1678. // Add the necessary capability required for indexing into this kind
  1679. // of resource
  1680. theBuilder.requireCapability(getNonUniformCapability(base->getType()));
  1681. info.setNonUniform(); // Carry forward the NonUniformEXT decoration
  1682. foundNonUniformResourceIndex = false;
  1683. }
  1684. if (!indices.empty()) {
  1685. (void)turnIntoElementPtr(info, expr->getType(), indices);
  1686. }
  1687. return info;
  1688. }
  1689. SpirvEvalInfo SPIRVEmitter::doBinaryOperator(const BinaryOperator *expr) {
  1690. const auto opcode = expr->getOpcode();
  1691. // Handle assignment first since we need to evaluate rhs before lhs.
  1692. // For other binary operations, we need to evaluate lhs before rhs.
  1693. if (opcode == BO_Assign) {
  1694. // Update counter variable associated with lhs of assignments
  1695. tryToAssignCounterVar(expr->getLHS(), expr->getRHS());
  1696. return processAssignment(expr->getLHS(), loadIfGLValue(expr->getRHS()),
  1697. /*isCompoundAssignment=*/false);
  1698. }
  1699. // Try to optimize floatMxN * float and floatN * float case
  1700. if (opcode == BO_Mul) {
  1701. if (SpirvEvalInfo result = tryToGenFloatMatrixScale(expr))
  1702. return result;
  1703. if (SpirvEvalInfo result = tryToGenFloatVectorScale(expr))
  1704. return result;
  1705. }
  1706. return processBinaryOp(expr->getLHS(), expr->getRHS(), opcode,
  1707. expr->getLHS()->getType(), expr->getType(),
  1708. expr->getSourceRange());
  1709. }
  1710. SpirvEvalInfo SPIRVEmitter::doCallExpr(const CallExpr *callExpr) {
  1711. if (const auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(callExpr))
  1712. return doCXXOperatorCallExpr(operatorCall);
  1713. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr))
  1714. return doCXXMemberCallExpr(memberCall);
  1715. // Intrinsic functions such as 'dot' or 'mul'
  1716. if (hlsl::IsIntrinsicOp(callExpr->getDirectCallee())) {
  1717. return processIntrinsicCallExpr(callExpr);
  1718. }
  1719. // Normal standalone functions
  1720. return processCall(callExpr);
  1721. }
  1722. SpirvEvalInfo SPIRVEmitter::processCall(const CallExpr *callExpr) {
  1723. const FunctionDecl *callee = getCalleeDefinition(callExpr);
  1724. // Note that we always want the defintion because Stmts/Exprs in the
  1725. // function body references the parameters in the definition.
  1726. if (!callee) {
  1727. emitError("found undefined function", callExpr->getExprLoc());
  1728. return 0;
  1729. }
  1730. const auto numParams = callee->getNumParams();
  1731. bool isNonStaticMemberCall = false;
  1732. QualType objectType = {}; // Type of the object (if exists)
  1733. SpirvEvalInfo objectEvalInfo = 0; // EvalInfo for the object (if exists)
  1734. bool needsTempVar = false; // Whether we need temporary variable.
  1735. llvm::SmallVector<uint32_t, 4> params; // Temporary variables
  1736. llvm::SmallVector<SpirvEvalInfo, 4> args; // Evaluated arguments
  1737. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr)) {
  1738. const auto *memberFn = cast<CXXMethodDecl>(memberCall->getCalleeDecl());
  1739. isNonStaticMemberCall = !memberFn->isStatic();
  1740. if (isNonStaticMemberCall) {
  1741. // For non-static member calls, evaluate the object and pass it as the
  1742. // first argument.
  1743. const auto *object = memberCall->getImplicitObjectArgument();
  1744. object = object->IgnoreParenNoopCasts(astContext);
  1745. // Update counter variable associated with the implicit object
  1746. tryToAssignCounterVar(getOrCreateDeclForMethodObject(memberFn), object);
  1747. objectType = object->getType();
  1748. objectEvalInfo = doExpr(object);
  1749. uint32_t objectId = objectEvalInfo;
  1750. // If not already a variable, we need to create a temporary variable and
  1751. // pass the object pointer to the function. Example:
  1752. // getObject().objectMethod();
  1753. // Also, any parameter passed to the member function must be of Function
  1754. // storage class.
  1755. needsTempVar =
  1756. objectEvalInfo.isRValue() ||
  1757. objectEvalInfo.getStorageClass() != spv::StorageClass::Function;
  1758. if (needsTempVar) {
  1759. objectId =
  1760. createTemporaryVar(objectType, TypeTranslator::getName(objectType),
  1761. // May need to load to use as initializer
  1762. loadIfGLValue(object, objectEvalInfo));
  1763. }
  1764. args.push_back(objectId);
  1765. // We do not need to create a new temporary variable for the this
  1766. // object. Use the evaluated argument.
  1767. params.push_back(args.back());
  1768. }
  1769. }
  1770. // Evaluate parameters
  1771. for (uint32_t i = 0; i < numParams; ++i) {
  1772. // We want the argument variable here so that we can write back to it
  1773. // later. We will do the OpLoad of this argument manually. So ingore
  1774. // the LValueToRValue implicit cast here.
  1775. auto *arg = callExpr->getArg(i)->IgnoreParenLValueCasts();
  1776. const auto *param = callee->getParamDecl(i);
  1777. // We need to create variables for holding the values to be used as
  1778. // arguments. The variables themselves are of pointer types.
  1779. const uint32_t varType =
  1780. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  1781. const std::string varName = "param.var." + param->getNameAsString();
  1782. const uint32_t tempVarId = theBuilder.addFnVar(varType, varName);
  1783. params.push_back(tempVarId);
  1784. args.push_back(doExpr(arg));
  1785. // Update counter variable associated with function parameters
  1786. tryToAssignCounterVar(param, arg);
  1787. // Manually load the argument here
  1788. const auto rhsVal = loadIfGLValue(arg, args.back());
  1789. // Initialize the temporary variables using the contents of the arguments
  1790. storeValue(tempVarId, rhsVal, param->getType());
  1791. }
  1792. // Push the callee into the work queue if it is not there.
  1793. if (!workQueue.count(callee)) {
  1794. workQueue.insert(callee);
  1795. }
  1796. const uint32_t retType =
  1797. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(callee);
  1798. // Get or forward declare the function <result-id>
  1799. const uint32_t funcId = declIdMapper.getOrRegisterFnResultId(callee);
  1800. const uint32_t retVal =
  1801. theBuilder.createFunctionCall(retType, funcId, params);
  1802. // If we created a temporary variable for the lvalue object this method is
  1803. // invoked upon, we need to copy the contents in the temporary variable back
  1804. // to the original object's variable in case there are side effects.
  1805. if (needsTempVar && !objectEvalInfo.isRValue()) {
  1806. const uint32_t typeId = typeTranslator.translateType(objectType);
  1807. const uint32_t value = theBuilder.createLoad(typeId, params.front());
  1808. storeValue(objectEvalInfo, value, objectType);
  1809. }
  1810. // Go through all parameters and write those marked as out/inout
  1811. for (uint32_t i = 0; i < numParams; ++i) {
  1812. const auto *param = callee->getParamDecl(i);
  1813. if (canActAsOutParmVar(param)) {
  1814. const auto *arg = callExpr->getArg(i);
  1815. const uint32_t index = i + isNonStaticMemberCall;
  1816. const uint32_t typeId = typeTranslator.translateType(param->getType());
  1817. const uint32_t value = theBuilder.createLoad(typeId, params[index]);
  1818. processAssignment(arg, value, false, args[index]);
  1819. }
  1820. }
  1821. // Inherit the SpirvEvalInfo from the function definition
  1822. return declIdMapper.getDeclEvalInfo(callee).setResultId(retVal);
  1823. }
  1824. SpirvEvalInfo SPIRVEmitter::doCastExpr(const CastExpr *expr) {
  1825. const Expr *subExpr = expr->getSubExpr();
  1826. const QualType subExprType = subExpr->getType();
  1827. const QualType toType = expr->getType();
  1828. // Unfortunately the front-end fails to deduce some types in certain cases.
  1829. // Provide a hint about literal type usage if possible.
  1830. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  1831. // 'literal int' to 'float' conversion. If a literal integer is to be used as
  1832. // a 32-bit float, the hint is a 32-bit integer.
  1833. if (toType->isFloatingType() &&
  1834. subExprType->isSpecificBuiltinType(BuiltinType::LitInt) &&
  1835. llvm::APFloat::getSizeInBits(astContext.getFloatTypeSemantics(toType)) ==
  1836. 32)
  1837. hint.setHint(astContext.IntTy);
  1838. // 'literal float' to 'float' conversion where intended type is float32.
  1839. if (toType->isFloatingType() &&
  1840. subExprType->isSpecificBuiltinType(BuiltinType::LitFloat) &&
  1841. llvm::APFloat::getSizeInBits(astContext.getFloatTypeSemantics(toType)) ==
  1842. 32)
  1843. hint.setHint(astContext.FloatTy);
  1844. // TODO: We could provide other useful hints. For instance:
  1845. // For the case of toType being a boolean, if the fromType is a literal float,
  1846. // we could provide a FloatTy hint and if the fromType is a literal integer,
  1847. // we could provide an IntTy hint. The front-end, however, seems to deduce the
  1848. // correct type in these cases; therefore we currently don't provide any
  1849. // additional hints.
  1850. switch (expr->getCastKind()) {
  1851. case CastKind::CK_LValueToRValue:
  1852. return loadIfGLValue(subExpr);
  1853. case CastKind::CK_NoOp:
  1854. return doExpr(subExpr);
  1855. case CastKind::CK_IntegralCast:
  1856. case CastKind::CK_FloatingToIntegral:
  1857. case CastKind::CK_HLSLCC_IntegralCast:
  1858. case CastKind::CK_HLSLCC_FloatingToIntegral: {
  1859. // Integer literals in the AST are represented using 64bit APInt
  1860. // themselves and then implicitly casted into the expected bitwidth.
  1861. // We need special treatment of integer literals here because generating
  1862. // a 64bit constant and then explicit casting in SPIR-V requires Int64
  1863. // capability. We should avoid introducing unnecessary capabilities to
  1864. // our best.
  1865. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1866. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1867. const auto valueId =
  1868. castToInt(doExpr(subExpr), subExprType, toType, subExpr->getExprLoc());
  1869. return SpirvEvalInfo(valueId).setRValue();
  1870. }
  1871. case CastKind::CK_FloatingCast:
  1872. case CastKind::CK_IntegralToFloating:
  1873. case CastKind::CK_HLSLCC_FloatingCast:
  1874. case CastKind::CK_HLSLCC_IntegralToFloating: {
  1875. // First try to see if we can do constant folding for floating point
  1876. // numbers like what we are doing for integers in the above.
  1877. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1878. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1879. const auto valueId = castToFloat(doExpr(subExpr), subExprType, toType,
  1880. subExpr->getExprLoc());
  1881. return SpirvEvalInfo(valueId).setRValue();
  1882. }
  1883. case CastKind::CK_IntegralToBoolean:
  1884. case CastKind::CK_FloatingToBoolean:
  1885. case CastKind::CK_HLSLCC_IntegralToBoolean:
  1886. case CastKind::CK_HLSLCC_FloatingToBoolean: {
  1887. // First try to see if we can do constant folding.
  1888. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1889. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1890. const auto valueId = castToBool(doExpr(subExpr), subExprType, toType);
  1891. return SpirvEvalInfo(valueId).setRValue();
  1892. }
  1893. case CastKind::CK_HLSLVectorSplat: {
  1894. const size_t size = hlsl::GetHLSLVecSize(expr->getType());
  1895. return createVectorSplat(subExpr, size);
  1896. }
  1897. case CastKind::CK_HLSLVectorTruncationCast: {
  1898. const uint32_t toVecTypeId = typeTranslator.translateType(toType);
  1899. const uint32_t elemTypeId =
  1900. typeTranslator.translateType(hlsl::GetHLSLVecElementType(toType));
  1901. const auto toSize = hlsl::GetHLSLVecSize(toType);
  1902. const uint32_t composite = doExpr(subExpr);
  1903. llvm::SmallVector<uint32_t, 4> elements;
  1904. for (uint32_t i = 0; i < toSize; ++i) {
  1905. elements.push_back(
  1906. theBuilder.createCompositeExtract(elemTypeId, composite, {i}));
  1907. }
  1908. auto valueId = elements.front();
  1909. if (toSize > 1)
  1910. valueId = theBuilder.createCompositeConstruct(toVecTypeId, elements);
  1911. return SpirvEvalInfo(valueId).setRValue();
  1912. }
  1913. case CastKind::CK_HLSLVectorToScalarCast: {
  1914. // The underlying should already be a vector of size 1.
  1915. assert(hlsl::GetHLSLVecSize(subExprType) == 1);
  1916. return doExpr(subExpr);
  1917. }
  1918. case CastKind::CK_HLSLVectorToMatrixCast: {
  1919. // If target type is already an 1xN matrix type, we just return the
  1920. // underlying vector.
  1921. if (TypeTranslator::is1xNMatrix(toType))
  1922. return doExpr(subExpr);
  1923. // A vector can have no more than 4 elements. The only remaining case
  1924. // is casting from size-4 vector to size-2-by-2 matrix.
  1925. const auto vec = loadIfGLValue(subExpr);
  1926. QualType elemType = {};
  1927. uint32_t rowCount = 0, colCount = 0;
  1928. const bool isMat =
  1929. TypeTranslator::isMxNMatrix(toType, &elemType, &rowCount, &colCount);
  1930. assert(isMat && rowCount == 2 && colCount == 2);
  1931. uint32_t vec2Type =
  1932. theBuilder.getVecType(typeTranslator.translateType(elemType), 2);
  1933. const auto subVec1 =
  1934. theBuilder.createVectorShuffle(vec2Type, vec, vec, {0, 1});
  1935. const auto subVec2 =
  1936. theBuilder.createVectorShuffle(vec2Type, vec, vec, {2, 3});
  1937. const auto mat = theBuilder.createCompositeConstruct(
  1938. theBuilder.getMatType(elemType, vec2Type, 2), {subVec1, subVec2});
  1939. return SpirvEvalInfo(mat).setRValue();
  1940. }
  1941. case CastKind::CK_HLSLMatrixSplat: {
  1942. // From scalar to matrix
  1943. uint32_t rowCount = 0, colCount = 0;
  1944. hlsl::GetHLSLMatRowColCount(toType, rowCount, colCount);
  1945. // Handle degenerated cases first
  1946. if (rowCount == 1 && colCount == 1)
  1947. return doExpr(subExpr);
  1948. if (colCount == 1)
  1949. return createVectorSplat(subExpr, rowCount);
  1950. const auto vecSplat = createVectorSplat(subExpr, colCount);
  1951. if (rowCount == 1)
  1952. return vecSplat;
  1953. const uint32_t matType = typeTranslator.translateType(toType);
  1954. llvm::SmallVector<uint32_t, 4> vectors(size_t(rowCount), vecSplat);
  1955. if (vecSplat.isConstant()) {
  1956. const auto valueId = theBuilder.getConstantComposite(matType, vectors);
  1957. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1958. } else {
  1959. const auto valueId =
  1960. theBuilder.createCompositeConstruct(matType, vectors);
  1961. return SpirvEvalInfo(valueId).setRValue();
  1962. }
  1963. }
  1964. case CastKind::CK_HLSLMatrixTruncationCast: {
  1965. const QualType srcType = subExprType;
  1966. const uint32_t srcId = doExpr(subExpr);
  1967. const QualType elemType = hlsl::GetHLSLMatElementType(srcType);
  1968. const uint32_t dstTypeId = typeTranslator.translateType(toType);
  1969. llvm::SmallVector<uint32_t, 4> indexes;
  1970. // It is possible that the source matrix is in fact a vector.
  1971. // For example: Truncate float1x3 --> float1x2.
  1972. // The front-end disallows float1x3 --> float2x1.
  1973. {
  1974. uint32_t srcVecSize = 0, dstVecSize = 0;
  1975. if (TypeTranslator::isVectorType(srcType, nullptr, &srcVecSize) &&
  1976. TypeTranslator::isVectorType(toType, nullptr, &dstVecSize)) {
  1977. for (uint32_t i = 0; i < dstVecSize; ++i)
  1978. indexes.push_back(i);
  1979. const auto valId =
  1980. theBuilder.createVectorShuffle(dstTypeId, srcId, srcId, indexes);
  1981. return SpirvEvalInfo(valId).setRValue();
  1982. }
  1983. }
  1984. uint32_t srcRows = 0, srcCols = 0, dstRows = 0, dstCols = 0;
  1985. hlsl::GetHLSLMatRowColCount(srcType, srcRows, srcCols);
  1986. hlsl::GetHLSLMatRowColCount(toType, dstRows, dstCols);
  1987. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  1988. const uint32_t srcRowType = theBuilder.getVecType(elemTypeId, srcCols);
  1989. // Indexes to pass to OpVectorShuffle
  1990. for (uint32_t i = 0; i < dstCols; ++i)
  1991. indexes.push_back(i);
  1992. llvm::SmallVector<uint32_t, 4> extractedVecs;
  1993. for (uint32_t row = 0; row < dstRows; ++row) {
  1994. // Extract a row
  1995. uint32_t rowId =
  1996. theBuilder.createCompositeExtract(srcRowType, srcId, {row});
  1997. // Extract the necessary columns from that row.
  1998. // The front-end ensures dstCols <= srcCols.
  1999. // If dstCols equals srcCols, we can use the whole row directly.
  2000. if (dstCols == 1) {
  2001. rowId = theBuilder.createCompositeExtract(elemTypeId, rowId, {0});
  2002. } else if (dstCols < srcCols) {
  2003. rowId = theBuilder.createVectorShuffle(
  2004. theBuilder.getVecType(elemTypeId, dstCols), rowId, rowId, indexes);
  2005. }
  2006. extractedVecs.push_back(rowId);
  2007. }
  2008. uint32_t valId = extractedVecs.front();
  2009. if (extractedVecs.size() > 1) {
  2010. valId = theBuilder.createCompositeConstruct(
  2011. typeTranslator.translateType(toType), extractedVecs);
  2012. }
  2013. return SpirvEvalInfo(valId).setRValue();
  2014. }
  2015. case CastKind::CK_HLSLMatrixToScalarCast: {
  2016. // The underlying should already be a matrix of 1x1.
  2017. assert(TypeTranslator::is1x1Matrix(subExprType));
  2018. return doExpr(subExpr);
  2019. }
  2020. case CastKind::CK_HLSLMatrixToVectorCast: {
  2021. // The underlying should already be a matrix of 1xN.
  2022. assert(TypeTranslator::is1xNMatrix(subExprType) ||
  2023. TypeTranslator::isMx1Matrix(subExprType));
  2024. return doExpr(subExpr);
  2025. }
  2026. case CastKind::CK_FunctionToPointerDecay:
  2027. // Just need to return the function id
  2028. return doExpr(subExpr);
  2029. case CastKind::CK_FlatConversion: {
  2030. uint32_t subExprId = 0;
  2031. QualType evalType = subExprType;
  2032. // Optimization: we can use OpConstantNull for cases where we want to
  2033. // initialize an entire data structure to zeros.
  2034. if (evaluatesToConstZero(subExpr, astContext)) {
  2035. subExprId =
  2036. theBuilder.getConstantNull(typeTranslator.translateType(toType));
  2037. return SpirvEvalInfo(subExprId).setRValue().setConstant();
  2038. }
  2039. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  2040. // Try to evaluate float literals as float rather than double.
  2041. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(subExpr)) {
  2042. subExprId = tryToEvaluateAsFloat32(floatLiteral->getValue());
  2043. if (subExprId)
  2044. evalType = astContext.FloatTy;
  2045. }
  2046. // Evaluate 'literal float' initializer type as float rather than double.
  2047. // TODO: This could result in rounding error if the initializer is a
  2048. // non-literal expression that requires larger than 32 bits and has the
  2049. // 'literal float' type.
  2050. else if (subExprType->isSpecificBuiltinType(BuiltinType::LitFloat)) {
  2051. evalType = astContext.FloatTy;
  2052. hint.setHint(astContext.FloatTy);
  2053. }
  2054. // Try to evaluate integer literals as 32-bit int rather than 64-bit int.
  2055. else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(subExpr)) {
  2056. const bool isSigned = subExprType->isSignedIntegerType();
  2057. subExprId = tryToEvaluateAsInt32(intLiteral->getValue(), isSigned);
  2058. if (subExprId)
  2059. evalType = isSigned ? astContext.IntTy : astContext.UnsignedIntTy;
  2060. }
  2061. // For assigning one array instance to another one with the same array type
  2062. // (regardless of constness and literalness), the rhs will be wrapped in a
  2063. // FlatConversion:
  2064. // |- <lhs>
  2065. // `- ImplicitCastExpr <FlatConversion>
  2066. // `- ImplicitCastExpr <LValueToRValue>
  2067. // `- <rhs>
  2068. // This FlatConversion does not affect CodeGen, so that we can ignore it.
  2069. else if (subExprType->isArrayType() &&
  2070. typeTranslator.isSameType(expr->getType(), subExprType)) {
  2071. return doExpr(subExpr);
  2072. }
  2073. if (!subExprId)
  2074. subExprId = doExpr(subExpr);
  2075. const auto valId =
  2076. processFlatConversion(toType, evalType, subExprId, expr->getExprLoc());
  2077. return SpirvEvalInfo(valId).setRValue();
  2078. }
  2079. case CastKind::CK_UncheckedDerivedToBase:
  2080. case CastKind::CK_HLSLDerivedToBase: {
  2081. // Find the index sequence of the base to which we are casting
  2082. llvm::SmallVector<uint32_t, 4> baseIndices;
  2083. getBaseClassIndices(expr, &baseIndices);
  2084. // Turn them in to SPIR-V constants
  2085. for (uint32_t i = 0; i < baseIndices.size(); ++i)
  2086. baseIndices[i] = theBuilder.getConstantUint32(baseIndices[i]);
  2087. auto derivedInfo = doExpr(subExpr);
  2088. return turnIntoElementPtr(derivedInfo, expr->getType(), baseIndices);
  2089. }
  2090. default:
  2091. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  2092. << expr->getCastKindName() << expr->getSourceRange();
  2093. expr->dump();
  2094. return 0;
  2095. }
  2096. }
  2097. uint32_t SPIRVEmitter::processFlatConversion(const QualType type,
  2098. const QualType initType,
  2099. const uint32_t initId,
  2100. SourceLocation srcLoc) {
  2101. // Try to translate the canonical type first
  2102. const auto canonicalType = type.getCanonicalType();
  2103. if (canonicalType != type)
  2104. return processFlatConversion(canonicalType, initType, initId, srcLoc);
  2105. // Primitive types
  2106. {
  2107. QualType ty = {};
  2108. if (TypeTranslator::isScalarType(type, &ty)) {
  2109. if (const auto *builtinType = ty->getAs<BuiltinType>()) {
  2110. switch (builtinType->getKind()) {
  2111. case BuiltinType::Void: {
  2112. emitError("cannot create a constant of void type", srcLoc);
  2113. return 0;
  2114. }
  2115. case BuiltinType::Bool:
  2116. return castToBool(initId, initType, ty);
  2117. // Target type is an integer variant.
  2118. case BuiltinType::Int:
  2119. case BuiltinType::Short:
  2120. case BuiltinType::Min12Int:
  2121. case BuiltinType::UShort:
  2122. case BuiltinType::UInt:
  2123. case BuiltinType::Long:
  2124. case BuiltinType::LongLong:
  2125. case BuiltinType::ULong:
  2126. case BuiltinType::ULongLong:
  2127. return castToInt(initId, initType, ty, srcLoc);
  2128. // Target type is a float variant.
  2129. case BuiltinType::Double:
  2130. case BuiltinType::Float:
  2131. case BuiltinType::Half:
  2132. case BuiltinType::Min10Float:
  2133. return castToFloat(initId, initType, ty, srcLoc);
  2134. default:
  2135. emitError("flat conversion of type %0 unimplemented", srcLoc)
  2136. << builtinType->getTypeClassName();
  2137. return 0;
  2138. }
  2139. }
  2140. }
  2141. }
  2142. // Vector types
  2143. {
  2144. QualType elemType = {};
  2145. uint32_t elemCount = {};
  2146. if (TypeTranslator::isVectorType(type, &elemType, &elemCount)) {
  2147. const uint32_t elemId =
  2148. processFlatConversion(elemType, initType, initId, srcLoc);
  2149. llvm::SmallVector<uint32_t, 4> constituents(size_t(elemCount), elemId);
  2150. return theBuilder.createCompositeConstruct(
  2151. typeTranslator.translateType(type), constituents);
  2152. }
  2153. }
  2154. // Matrix types
  2155. {
  2156. QualType elemType = {};
  2157. uint32_t rowCount = 0, colCount = 0;
  2158. if (TypeTranslator::isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  2159. // By default HLSL matrices are row major, while SPIR-V matrices are
  2160. // column major. We are mapping what HLSL semantically mean a row into a
  2161. // column here.
  2162. const uint32_t vecType = theBuilder.getVecType(
  2163. typeTranslator.translateType(elemType), colCount);
  2164. const uint32_t elemId =
  2165. processFlatConversion(elemType, initType, initId, srcLoc);
  2166. const llvm::SmallVector<uint32_t, 4> constituents(size_t(colCount),
  2167. elemId);
  2168. const uint32_t colId =
  2169. theBuilder.createCompositeConstruct(vecType, constituents);
  2170. const llvm::SmallVector<uint32_t, 4> rows(size_t(rowCount), colId);
  2171. return theBuilder.createCompositeConstruct(
  2172. typeTranslator.translateType(type), rows);
  2173. }
  2174. }
  2175. // Struct type
  2176. if (const auto *structType = type->getAs<RecordType>()) {
  2177. const auto *decl = structType->getDecl();
  2178. llvm::SmallVector<uint32_t, 4> fields;
  2179. for (const auto *field : decl->fields()) {
  2180. // There is a special case for FlatConversion. If T is a struct with only
  2181. // one member, S, then (T)<an-instance-of-S> is allowed, which essentially
  2182. // constructs a new T instance using the instance of S as its only member.
  2183. // Check whether we are handling that case here first.
  2184. if (field->getType().getCanonicalType() == initType.getCanonicalType()) {
  2185. fields.push_back(initId);
  2186. } else {
  2187. fields.push_back(
  2188. processFlatConversion(field->getType(), initType, initId, srcLoc));
  2189. }
  2190. }
  2191. return theBuilder.createCompositeConstruct(
  2192. typeTranslator.translateType(type), fields);
  2193. }
  2194. // Array type
  2195. if (const auto *arrayType = astContext.getAsConstantArrayType(type)) {
  2196. const auto size =
  2197. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  2198. const uint32_t elemId = processFlatConversion(arrayType->getElementType(),
  2199. initType, initId, srcLoc);
  2200. llvm::SmallVector<uint32_t, 4> constituents(size_t(size), elemId);
  2201. return theBuilder.createCompositeConstruct(
  2202. typeTranslator.translateType(type), constituents);
  2203. }
  2204. emitError("flat conversion of type %0 unimplemented", {})
  2205. << type->getTypeClassName();
  2206. type->dump();
  2207. return 0;
  2208. }
  2209. SpirvEvalInfo
  2210. SPIRVEmitter::doCompoundAssignOperator(const CompoundAssignOperator *expr) {
  2211. const auto opcode = expr->getOpcode();
  2212. // Try to optimize floatMxN *= float and floatN *= float case
  2213. if (opcode == BO_MulAssign) {
  2214. if (SpirvEvalInfo result = tryToGenFloatMatrixScale(expr))
  2215. return result;
  2216. if (SpirvEvalInfo result = tryToGenFloatVectorScale(expr))
  2217. return result;
  2218. }
  2219. const auto *rhs = expr->getRHS();
  2220. const auto *lhs = expr->getLHS();
  2221. SpirvEvalInfo lhsPtr = 0;
  2222. const auto result =
  2223. processBinaryOp(lhs, rhs, opcode, expr->getComputationLHSType(),
  2224. expr->getType(), expr->getSourceRange(), &lhsPtr);
  2225. return processAssignment(lhs, result, true, lhsPtr);
  2226. }
  2227. SpirvEvalInfo
  2228. SPIRVEmitter::doConditionalOperator(const ConditionalOperator *expr) {
  2229. const auto type = expr->getType();
  2230. // Enhancement for special case when the ConditionalOperator return type is a
  2231. // literal type. For example:
  2232. //
  2233. // float a = cond ? 1 : 2;
  2234. // int b = cond ? 1.5 : 2.5;
  2235. //
  2236. // There will be no indications about whether '1' and '2' should be used as
  2237. // 32-bit or 64-bit integers. Similarly, there will be no indication about
  2238. // whether '1.5' and '2.5' should be used as 32-bit or 64-bit floats.
  2239. //
  2240. // We want to avoid using 64-bit int and 64-bit float as much as possible.
  2241. //
  2242. // Note that if the literal is in fact large enough that it can't be
  2243. // represented in 32 bits (e.g. integer larger than 3e+9), we should *not*
  2244. // provide a hint.
  2245. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  2246. const bool isLitInt = type->isSpecificBuiltinType(BuiltinType::LitInt);
  2247. const bool isLitFloat = type->isSpecificBuiltinType(BuiltinType::LitFloat);
  2248. // Return type of ConditionalOperator is a 'literal int' or 'literal float'
  2249. if (isLitInt || isLitFloat) {
  2250. // There is no hint about the intended usage of the literal type.
  2251. if (typeTranslator.getIntendedLiteralType(type) == type) {
  2252. // If either branch is a literal that is larger than 32-bits, do not
  2253. // provide a hint.
  2254. if (!isLiteralLargerThan32Bits(expr->getTrueExpr()) &&
  2255. !isLiteralLargerThan32Bits(expr->getFalseExpr())) {
  2256. if (isLitInt)
  2257. hint.setHint(astContext.IntTy);
  2258. else if (isLitFloat)
  2259. hint.setHint(astContext.FloatTy);
  2260. }
  2261. }
  2262. }
  2263. // According to HLSL doc, all sides of the ?: expression are always
  2264. // evaluated.
  2265. const uint32_t typeId = typeTranslator.translateType(type);
  2266. // If we are selecting between two SampleState objects, none of the three
  2267. // operands has a LValueToRValue implicit cast.
  2268. uint32_t condition = loadIfGLValue(expr->getCond());
  2269. const auto trueBranch = loadIfGLValue(expr->getTrueExpr());
  2270. const auto falseBranch = loadIfGLValue(expr->getFalseExpr());
  2271. // For cases where the return type is a scalar or a vector, we can use
  2272. // OpSelect to choose between the two. OpSelect's return type must be either
  2273. // scalar or vector.
  2274. if (TypeTranslator::isScalarType(type) ||
  2275. TypeTranslator::isVectorType(type)) {
  2276. // The SPIR-V OpSelect instruction must have a selection argument that is
  2277. // the same size as the return type. If the return type is a vector, the
  2278. // selection must be a vector of booleans (one per output component).
  2279. uint32_t count = 0;
  2280. if (TypeTranslator::isVectorType(expr->getType(), nullptr, &count) &&
  2281. !TypeTranslator::isVectorType(expr->getCond()->getType())) {
  2282. const uint32_t condVecType =
  2283. theBuilder.getVecType(theBuilder.getBoolType(), count);
  2284. const llvm::SmallVector<uint32_t, 4> components(size_t(count), condition);
  2285. condition = theBuilder.createCompositeConstruct(condVecType, components);
  2286. }
  2287. auto valueId =
  2288. theBuilder.createSelect(typeId, condition, trueBranch, falseBranch);
  2289. return SpirvEvalInfo(valueId).setRValue();
  2290. }
  2291. // If we can't use OpSelect, we need to create if-else control flow.
  2292. const uint32_t tempVar = theBuilder.addFnVar(typeId, "temp.var.ternary");
  2293. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  2294. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  2295. const uint32_t elseBB = theBuilder.createBasicBlock("if.false");
  2296. // Create the branch instruction. This will end the current basic block.
  2297. theBuilder.createConditionalBranch(condition, thenBB, elseBB, mergeBB);
  2298. theBuilder.addSuccessor(thenBB);
  2299. theBuilder.addSuccessor(elseBB);
  2300. theBuilder.setMergeTarget(mergeBB);
  2301. // Handle the then branch
  2302. theBuilder.setInsertPoint(thenBB);
  2303. theBuilder.createStore(tempVar, trueBranch);
  2304. theBuilder.createBranch(mergeBB);
  2305. theBuilder.addSuccessor(mergeBB);
  2306. // Handle the else branch
  2307. theBuilder.setInsertPoint(elseBB);
  2308. theBuilder.createStore(tempVar, falseBranch);
  2309. theBuilder.createBranch(mergeBB);
  2310. theBuilder.addSuccessor(mergeBB);
  2311. // From now on, emit instructions into the merge block.
  2312. theBuilder.setInsertPoint(mergeBB);
  2313. return SpirvEvalInfo(theBuilder.createLoad(typeId, tempVar)).setRValue();
  2314. }
  2315. uint32_t SPIRVEmitter::processByteAddressBufferStructuredBufferGetDimensions(
  2316. const CXXMemberCallExpr *expr) {
  2317. const auto *object = expr->getImplicitObjectArgument();
  2318. const auto objectId = loadIfAliasVarRef(object);
  2319. const auto type = object->getType();
  2320. const bool isByteAddressBuffer = TypeTranslator::isByteAddressBuffer(type) ||
  2321. TypeTranslator::isRWByteAddressBuffer(type);
  2322. const bool isStructuredBuffer =
  2323. TypeTranslator::isStructuredBuffer(type) ||
  2324. TypeTranslator::isAppendStructuredBuffer(type) ||
  2325. TypeTranslator::isConsumeStructuredBuffer(type);
  2326. assert(isByteAddressBuffer || isStructuredBuffer);
  2327. // (RW)ByteAddressBuffers/(RW)StructuredBuffers are represented as a structure
  2328. // with only one member that is a runtime array. We need to perform
  2329. // OpArrayLength on member 0.
  2330. const auto uintType = theBuilder.getUint32Type();
  2331. uint32_t length =
  2332. theBuilder.createBinaryOp(spv::Op::OpArrayLength, uintType, objectId, 0);
  2333. // For (RW)ByteAddressBuffers, GetDimensions() must return the array length
  2334. // in bytes, but OpArrayLength returns the number of uints in the runtime
  2335. // array. Therefore we must multiply the results by 4.
  2336. if (isByteAddressBuffer) {
  2337. length = theBuilder.createBinaryOp(spv::Op::OpIMul, uintType, length,
  2338. theBuilder.getConstantUint32(4u));
  2339. }
  2340. theBuilder.createStore(doExpr(expr->getArg(0)), length);
  2341. if (isStructuredBuffer) {
  2342. // For (RW)StructuredBuffer, the stride of the runtime array (which is the
  2343. // size of the struct) must also be written to the second argument.
  2344. uint32_t size = 0, stride = 0;
  2345. std::tie(std::ignore, size) = typeTranslator.getAlignmentAndSize(
  2346. type, spirvOptions.sBufferLayoutRule, &stride);
  2347. const auto sizeId = theBuilder.getConstantUint32(size);
  2348. theBuilder.createStore(doExpr(expr->getArg(1)), sizeId);
  2349. }
  2350. return 0;
  2351. }
  2352. uint32_t SPIRVEmitter::processRWByteAddressBufferAtomicMethods(
  2353. hlsl::IntrinsicOp opcode, const CXXMemberCallExpr *expr) {
  2354. // The signature of RWByteAddressBuffer atomic methods are largely:
  2355. // void Interlocked*(in UINT dest, in UINT value);
  2356. // void Interlocked*(in UINT dest, in UINT value, out UINT original_value);
  2357. const auto *object = expr->getImplicitObjectArgument();
  2358. const auto objectInfo = loadIfAliasVarRef(object);
  2359. const auto uintType = theBuilder.getUint32Type();
  2360. const uint32_t zero = theBuilder.getConstantUint32(0);
  2361. const uint32_t offset = doExpr(expr->getArg(0));
  2362. // Right shift by 2 to convert the byte offset to uint32_t offset
  2363. const uint32_t address =
  2364. theBuilder.createBinaryOp(spv::Op::OpShiftRightLogical, uintType, offset,
  2365. theBuilder.getConstantUint32(2));
  2366. const auto ptrType =
  2367. theBuilder.getPointerType(uintType, objectInfo.getStorageClass());
  2368. const uint32_t ptr =
  2369. theBuilder.createAccessChain(ptrType, objectInfo, {zero, address});
  2370. const uint32_t scope = theBuilder.getConstantUint32(1); // Device
  2371. const bool isCompareExchange =
  2372. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareExchange;
  2373. const bool isCompareStore =
  2374. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareStore;
  2375. if (isCompareExchange || isCompareStore) {
  2376. const uint32_t comparator = doExpr(expr->getArg(1));
  2377. const uint32_t originalVal = theBuilder.createAtomicCompareExchange(
  2378. uintType, ptr, scope, zero, zero, doExpr(expr->getArg(2)), comparator);
  2379. if (isCompareExchange)
  2380. theBuilder.createStore(doExpr(expr->getArg(3)), originalVal);
  2381. } else {
  2382. const uint32_t value = doExpr(expr->getArg(1));
  2383. const uint32_t originalVal = theBuilder.createAtomicOp(
  2384. translateAtomicHlslOpcodeToSpirvOpcode(opcode), uintType, ptr, scope,
  2385. zero, value);
  2386. if (expr->getNumArgs() > 2)
  2387. theBuilder.createStore(doExpr(expr->getArg(2)), originalVal);
  2388. }
  2389. return 0;
  2390. }
  2391. uint32_t SPIRVEmitter::processGetSamplePosition(const CXXMemberCallExpr *expr) {
  2392. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2393. const auto sampleCount = theBuilder.createUnaryOp(
  2394. spv::Op::OpImageQuerySamples, theBuilder.getUint32Type(),
  2395. loadIfGLValue(object));
  2396. emitWarning(
  2397. "GetSamplePosition only supports standard sample settings with 1, 2, 4, "
  2398. "8, or 16 samples and will return float2(0, 0) for other cases",
  2399. expr->getCallee()->getExprLoc());
  2400. return emitGetSamplePosition(sampleCount, doExpr(expr->getArg(0)));
  2401. }
  2402. SpirvEvalInfo SPIRVEmitter::processSubpassLoad(const CXXMemberCallExpr *expr) {
  2403. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2404. const uint32_t sample = expr->getNumArgs() == 1 ? doExpr(expr->getArg(0)) : 0;
  2405. const uint32_t zero = theBuilder.getConstantInt32(0);
  2406. const uint32_t location = theBuilder.getConstantComposite(
  2407. theBuilder.getVecType(theBuilder.getInt32Type(), 2), {zero, zero});
  2408. return processBufferTextureLoad(object, location, /*constOffset*/ 0,
  2409. /*varOffset*/ 0, /*lod*/ sample,
  2410. /*residencyCode*/ 0);
  2411. }
  2412. uint32_t
  2413. SPIRVEmitter::processBufferTextureGetDimensions(const CXXMemberCallExpr *expr) {
  2414. const auto *object = expr->getImplicitObjectArgument();
  2415. const auto objectId = loadIfGLValue(object);
  2416. const auto type = object->getType();
  2417. const auto *recType = type->getAs<RecordType>();
  2418. assert(recType);
  2419. const auto typeName = recType->getDecl()->getName();
  2420. const auto numArgs = expr->getNumArgs();
  2421. const Expr *mipLevel = nullptr, *numLevels = nullptr, *numSamples = nullptr;
  2422. assert(TypeTranslator::isTexture(type) || TypeTranslator::isRWTexture(type) ||
  2423. TypeTranslator::isBuffer(type) || TypeTranslator::isRWBuffer(type));
  2424. // For Texture1D, arguments are either:
  2425. // a) width
  2426. // b) MipLevel, width, NumLevels
  2427. // For Texture1DArray, arguments are either:
  2428. // a) width, elements
  2429. // b) MipLevel, width, elements, NumLevels
  2430. // For Texture2D, arguments are either:
  2431. // a) width, height
  2432. // b) MipLevel, width, height, NumLevels
  2433. // For Texture2DArray, arguments are either:
  2434. // a) width, height, elements
  2435. // b) MipLevel, width, height, elements, NumLevels
  2436. // For Texture3D, arguments are either:
  2437. // a) width, height, depth
  2438. // b) MipLevel, width, height, depth, NumLevels
  2439. // For Texture2DMS, arguments are: width, height, NumSamples
  2440. // For Texture2DMSArray, arguments are: width, height, elements, NumSamples
  2441. // For TextureCube, arguments are either:
  2442. // a) width, height
  2443. // b) MipLevel, width, height, NumLevels
  2444. // For TextureCubeArray, arguments are either:
  2445. // a) width, height, elements
  2446. // b) MipLevel, width, height, elements, NumLevels
  2447. // Note: SPIR-V Spec requires return type of OpImageQuerySize(Lod) to be a
  2448. // scalar/vector of integers. SPIR-V Spec also requires return type of
  2449. // OpImageQueryLevels and OpImageQuerySamples to be scalar integers.
  2450. // The HLSL methods, however, have overloaded functions which have float
  2451. // output arguments. Since the AST naturally won't have casting AST nodes for
  2452. // such cases, we'll have to perform the cast ourselves.
  2453. const auto storeToOutputArg = [this](const Expr *outputArg, uint32_t id,
  2454. QualType type) {
  2455. id = castToType(id, type, outputArg->getType(), outputArg->getExprLoc());
  2456. theBuilder.createStore(doExpr(outputArg), id);
  2457. };
  2458. if ((typeName == "Texture1D" && numArgs > 1) ||
  2459. (typeName == "Texture2D" && numArgs > 2) ||
  2460. (typeName == "TextureCube" && numArgs > 2) ||
  2461. (typeName == "Texture3D" && numArgs > 3) ||
  2462. (typeName == "Texture1DArray" && numArgs > 2) ||
  2463. (typeName == "TextureCubeArray" && numArgs > 3) ||
  2464. (typeName == "Texture2DArray" && numArgs > 3)) {
  2465. mipLevel = expr->getArg(0);
  2466. numLevels = expr->getArg(numArgs - 1);
  2467. }
  2468. if (TypeTranslator::isTextureMS(type)) {
  2469. numSamples = expr->getArg(numArgs - 1);
  2470. }
  2471. uint32_t querySize = numArgs;
  2472. // If numLevels arg is present, mipLevel must also be present. These are not
  2473. // queried via ImageQuerySizeLod.
  2474. if (numLevels)
  2475. querySize -= 2;
  2476. // If numLevels arg is present, mipLevel must also be present.
  2477. else if (numSamples)
  2478. querySize -= 1;
  2479. const uint32_t uintId = theBuilder.getUint32Type();
  2480. const QualType resultQualType =
  2481. querySize == 1
  2482. ? astContext.UnsignedIntTy
  2483. : astContext.getExtVectorType(astContext.UnsignedIntTy, querySize);
  2484. const uint32_t resultTypeId = typeTranslator.translateType(resultQualType);
  2485. // Only Texture types use ImageQuerySizeLod.
  2486. // TextureMS, RWTexture, Buffers, RWBuffers use ImageQuerySize.
  2487. uint32_t lod = 0;
  2488. if (TypeTranslator::isTexture(type) && !numSamples) {
  2489. if (mipLevel) {
  2490. // For Texture types when mipLevel argument is present.
  2491. lod = doExpr(mipLevel);
  2492. } else {
  2493. // For Texture types when mipLevel argument is omitted.
  2494. lod = theBuilder.getConstantInt32(0);
  2495. }
  2496. }
  2497. const uint32_t query =
  2498. lod ? theBuilder.createBinaryOp(spv::Op::OpImageQuerySizeLod,
  2499. resultTypeId, objectId, lod)
  2500. : theBuilder.createUnaryOp(spv::Op::OpImageQuerySize, resultTypeId,
  2501. objectId);
  2502. if (querySize == 1) {
  2503. const uint32_t argIndex = mipLevel ? 1 : 0;
  2504. storeToOutputArg(expr->getArg(argIndex), query, resultQualType);
  2505. } else {
  2506. for (uint32_t i = 0; i < querySize; ++i) {
  2507. const uint32_t component =
  2508. theBuilder.createCompositeExtract(uintId, query, {i});
  2509. // If the first arg is the mipmap level, we must write the results
  2510. // starting from Arg(i+1), not Arg(i).
  2511. const uint32_t argIndex = mipLevel ? i + 1 : i;
  2512. storeToOutputArg(expr->getArg(argIndex), component,
  2513. astContext.UnsignedIntTy);
  2514. }
  2515. }
  2516. if (numLevels || numSamples) {
  2517. const Expr *numLevelsSamplesArg = numLevels ? numLevels : numSamples;
  2518. const spv::Op opcode =
  2519. numLevels ? spv::Op::OpImageQueryLevels : spv::Op::OpImageQuerySamples;
  2520. const uint32_t numLevelsSamplesQuery =
  2521. theBuilder.createUnaryOp(opcode, uintId, objectId);
  2522. storeToOutputArg(numLevelsSamplesArg, numLevelsSamplesQuery,
  2523. astContext.UnsignedIntTy);
  2524. }
  2525. return 0;
  2526. }
  2527. uint32_t
  2528. SPIRVEmitter::processTextureLevelOfDetail(const CXXMemberCallExpr *expr) {
  2529. // Possible signatures are as follows:
  2530. // Texture1D(Array).CalculateLevelOfDetail(SamplerState S, float x);
  2531. // Texture2D(Array).CalculateLevelOfDetail(SamplerState S, float2 xy);
  2532. // TextureCube(Array).CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2533. // Texture3D.CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2534. // Return type is always a single float (LOD).
  2535. assert(expr->getNumArgs() == 2u);
  2536. const auto *object = expr->getImplicitObjectArgument();
  2537. const auto objectInfo = loadIfGLValue(object);
  2538. const auto samplerState = doExpr(expr->getArg(0));
  2539. const uint32_t coordinate = doExpr(expr->getArg(1));
  2540. const uint32_t sampledImageType = theBuilder.getSampledImageType(
  2541. typeTranslator.translateType(object->getType()));
  2542. const uint32_t sampledImage = theBuilder.createBinaryOp(
  2543. spv::Op::OpSampledImage, sampledImageType, objectInfo, samplerState);
  2544. if (objectInfo.isNonUniform() || samplerState.isNonUniform()) {
  2545. // The sampled image will be used to access resource's memory, so we need
  2546. // to decorate it with NonUniformEXT.
  2547. theBuilder.decorate(sampledImage, spv::Decoration::NonUniformEXT);
  2548. }
  2549. // The result type of OpImageQueryLod must be a float2.
  2550. const uint32_t queryResultType =
  2551. theBuilder.getVecType(theBuilder.getFloat32Type(), 2u);
  2552. const uint32_t query = theBuilder.createBinaryOp(
  2553. spv::Op::OpImageQueryLod, queryResultType, sampledImage, coordinate);
  2554. // The first component of the float2 contains the mipmap array layer.
  2555. return theBuilder.createCompositeExtract(theBuilder.getFloat32Type(), query,
  2556. {0});
  2557. }
  2558. uint32_t SPIRVEmitter::processTextureGatherRGBACmpRGBA(
  2559. const CXXMemberCallExpr *expr, const bool isCmp, const uint32_t component) {
  2560. // Parameters for .Gather{Red|Green|Blue|Alpha}() are one of the following
  2561. // two sets:
  2562. // * SamplerState s, float2 location, int2 offset
  2563. // * SamplerState s, float2 location, int2 offset0, int2 offset1,
  2564. // int offset2, int2 offset3
  2565. //
  2566. // An additional 'out uint status' parameter can appear in both of the above.
  2567. //
  2568. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() are one of the following
  2569. // two sets:
  2570. // * SamplerState s, float2 location, float compare_value, int2 offset
  2571. // * SamplerState s, float2 location, float compare_value, int2 offset1,
  2572. // int2 offset2, int2 offset3, int2 offset4
  2573. //
  2574. // An additional 'out uint status' parameter can appear in both of the above.
  2575. //
  2576. // TextureCube's signature is somewhat different from the rest.
  2577. // Parameters for .Gather{Red|Green|Blue|Alpha}() for TextureCube are:
  2578. // * SamplerState s, float2 location, out uint status
  2579. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() for TextureCube are:
  2580. // * SamplerState s, float2 location, float compare_value, out uint status
  2581. //
  2582. // Return type is always a 4-component vector.
  2583. const FunctionDecl *callee = expr->getDirectCallee();
  2584. const auto numArgs = expr->getNumArgs();
  2585. const auto *imageExpr = expr->getImplicitObjectArgument();
  2586. const QualType imageType = imageExpr->getType();
  2587. const auto imageTypeId = typeTranslator.translateType(imageType);
  2588. const auto retTypeId = typeTranslator.translateType(callee->getReturnType());
  2589. // If the last arg is an unsigned integer, it must be the status.
  2590. const bool hasStatusArg =
  2591. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2592. // Subtract 1 for status arg (if it exists), subtract 1 for compare_value (if
  2593. // it exists), and subtract 2 for SamplerState and location.
  2594. const auto numOffsetArgs = numArgs - hasStatusArg - isCmp - 2;
  2595. // No offset args for TextureCube, 1 or 4 offset args for the rest.
  2596. assert(numOffsetArgs == 0 || numOffsetArgs == 1 || numOffsetArgs == 4);
  2597. const auto image = loadIfGLValue(imageExpr);
  2598. const auto sampler = doExpr(expr->getArg(0));
  2599. const uint32_t coordinate = doExpr(expr->getArg(1));
  2600. const uint32_t compareVal = isCmp ? doExpr(expr->getArg(2)) : 0;
  2601. // Handle offsets (if any).
  2602. bool needsEmulation = false;
  2603. uint32_t constOffset = 0, varOffset = 0, constOffsets = 0;
  2604. if (numOffsetArgs == 1) {
  2605. // The offset arg is not optional.
  2606. handleOffsetInMethodCall(expr, 2 + isCmp, &constOffset, &varOffset);
  2607. } else if (numOffsetArgs == 4) {
  2608. const auto offset0 = tryToEvaluateAsConst(expr->getArg(2 + isCmp));
  2609. const auto offset1 = tryToEvaluateAsConst(expr->getArg(3 + isCmp));
  2610. const auto offset2 = tryToEvaluateAsConst(expr->getArg(4 + isCmp));
  2611. const auto offset3 = tryToEvaluateAsConst(expr->getArg(5 + isCmp));
  2612. // If any of the offsets is not constant, we then need to emulate the call
  2613. // using 4 OpImageGather instructions. Otherwise, we can leverage the
  2614. // ConstOffsets image operand.
  2615. if (offset0 && offset1 && offset2 && offset3) {
  2616. const uint32_t v2i32 =
  2617. theBuilder.getVecType(theBuilder.getInt32Type(), 2);
  2618. const uint32_t offsetType =
  2619. theBuilder.getArrayType(v2i32, theBuilder.getConstantUint32(4));
  2620. constOffsets = theBuilder.getConstantComposite(
  2621. offsetType, {offset0, offset1, offset2, offset3});
  2622. } else {
  2623. needsEmulation = true;
  2624. }
  2625. }
  2626. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  2627. const bool isNonUniform = image.isNonUniform() || sampler.isNonUniform();
  2628. if (needsEmulation) {
  2629. const auto elemType = typeTranslator.translateType(
  2630. hlsl::GetHLSLVecElementType(callee->getReturnType()));
  2631. uint32_t texels[4];
  2632. for (uint32_t i = 0; i < 4; ++i) {
  2633. varOffset = doExpr(expr->getArg(2 + isCmp + i));
  2634. const uint32_t gatherRet = theBuilder.createImageGather(
  2635. retTypeId, imageTypeId, image, sampler, isNonUniform, coordinate,
  2636. theBuilder.getConstantInt32(component), compareVal, /*constOffset*/ 0,
  2637. varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0, status);
  2638. texels[i] = theBuilder.createCompositeExtract(elemType, gatherRet, {i});
  2639. }
  2640. return theBuilder.createCompositeConstruct(
  2641. retTypeId, {texels[0], texels[1], texels[2], texels[3]});
  2642. }
  2643. return theBuilder.createImageGather(
  2644. retTypeId, imageTypeId, image, sampler, isNonUniform, coordinate,
  2645. theBuilder.getConstantInt32(component), compareVal, constOffset,
  2646. varOffset, constOffsets, /*sampleNumber*/ 0, status);
  2647. }
  2648. uint32_t SPIRVEmitter::processTextureGatherCmp(const CXXMemberCallExpr *expr) {
  2649. // Signature for Texture2D/Texture2DArray:
  2650. //
  2651. // float4 GatherCmp(
  2652. // in SamplerComparisonState s,
  2653. // in float2 location,
  2654. // in float compare_value
  2655. // [,in int2 offset]
  2656. // [,out uint Status]
  2657. // );
  2658. //
  2659. // Signature for TextureCube/TextureCubeArray:
  2660. //
  2661. // float4 GatherCmp(
  2662. // in SamplerComparisonState s,
  2663. // in float2 location,
  2664. // in float compare_value,
  2665. // out uint Status
  2666. // );
  2667. //
  2668. // Other Texture types do not have the GatherCmp method.
  2669. const FunctionDecl *callee = expr->getDirectCallee();
  2670. const auto numArgs = expr->getNumArgs();
  2671. const bool hasStatusArg =
  2672. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2673. const bool hasOffsetArg = (numArgs == 5) || (numArgs == 4 && !hasStatusArg);
  2674. const auto *imageExpr = expr->getImplicitObjectArgument();
  2675. const auto image = loadIfGLValue(imageExpr);
  2676. const auto sampler = doExpr(expr->getArg(0));
  2677. const uint32_t coordinate = doExpr(expr->getArg(1));
  2678. const uint32_t comparator = doExpr(expr->getArg(2));
  2679. uint32_t constOffset = 0, varOffset = 0;
  2680. if (hasOffsetArg)
  2681. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  2682. const auto retType = typeTranslator.translateType(callee->getReturnType());
  2683. const auto imageType = typeTranslator.translateType(imageExpr->getType());
  2684. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  2685. return theBuilder.createImageGather(
  2686. retType, imageType, image, sampler,
  2687. image.isNonUniform() || sampler.isNonUniform(), coordinate,
  2688. /*component*/ 0, comparator, constOffset, varOffset, /*constOffsets*/ 0,
  2689. /*sampleNumber*/ 0, status);
  2690. }
  2691. SpirvEvalInfo SPIRVEmitter::processBufferTextureLoad(
  2692. const Expr *object, const uint32_t locationId, uint32_t constOffset,
  2693. uint32_t varOffset, uint32_t lod, uint32_t residencyCode) {
  2694. // Loading for Buffer and RWBuffer translates to an OpImageFetch.
  2695. // The result type of an OpImageFetch must be a vec4 of float or int.
  2696. const auto type = object->getType();
  2697. assert(TypeTranslator::isBuffer(type) || TypeTranslator::isRWBuffer(type) ||
  2698. TypeTranslator::isTexture(type) || TypeTranslator::isRWTexture(type) ||
  2699. TypeTranslator::isSubpassInput(type) ||
  2700. TypeTranslator::isSubpassInputMS(type));
  2701. const bool doFetch =
  2702. TypeTranslator::isBuffer(type) || TypeTranslator::isTexture(type);
  2703. const auto objectInfo = loadIfGLValue(object);
  2704. if (objectInfo.isNonUniform()) {
  2705. // Decoreate the image handle for OpImageFetch/OpImageRead
  2706. theBuilder.decorate(objectInfo, spv::Decoration::NonUniformEXT);
  2707. }
  2708. // For Texture2DMS and Texture2DMSArray, Sample must be used rather than Lod.
  2709. uint32_t sampleNumber = 0;
  2710. if (TypeTranslator::isTextureMS(type) ||
  2711. TypeTranslator::isSubpassInputMS(type)) {
  2712. sampleNumber = lod;
  2713. lod = 0;
  2714. }
  2715. const auto sampledType = hlsl::GetHLSLResourceResultType(type);
  2716. QualType elemType = sampledType;
  2717. uint32_t elemCount = 1;
  2718. uint32_t elemTypeId = 0;
  2719. (void)TypeTranslator::isVectorType(sampledType, &elemType, &elemCount);
  2720. if (elemType->isFloatingType()) {
  2721. elemTypeId = theBuilder.getFloat32Type();
  2722. } else if (elemType->isSignedIntegerType()) {
  2723. elemTypeId = theBuilder.getInt32Type();
  2724. } else if (elemType->isUnsignedIntegerType()) {
  2725. elemTypeId = theBuilder.getUint32Type();
  2726. } else {
  2727. emitError("buffer/texture type unimplemented", object->getExprLoc());
  2728. return 0;
  2729. }
  2730. // OpImageFetch and OpImageRead can only fetch a vector of 4 elements.
  2731. const uint32_t texelTypeId = theBuilder.getVecType(elemTypeId, 4u);
  2732. const uint32_t texel = theBuilder.createImageFetchOrRead(
  2733. doFetch, texelTypeId, type, objectInfo, locationId, lod, constOffset,
  2734. varOffset, /*constOffsets*/ 0, sampleNumber, residencyCode);
  2735. // If the result type is a vec1, vec2, or vec3, some extra processing
  2736. // (extraction) is required.
  2737. uint32_t retVal = extractVecFromVec4(texel, elemCount, elemTypeId);
  2738. return SpirvEvalInfo(retVal).setRValue();
  2739. }
  2740. SpirvEvalInfo SPIRVEmitter::processByteAddressBufferLoadStore(
  2741. const CXXMemberCallExpr *expr, uint32_t numWords, bool doStore) {
  2742. uint32_t resultId = 0;
  2743. const auto object = expr->getImplicitObjectArgument();
  2744. const auto type = object->getType();
  2745. const auto objectInfo = loadIfAliasVarRef(object);
  2746. assert(numWords >= 1 && numWords <= 4);
  2747. if (doStore) {
  2748. assert(typeTranslator.isRWByteAddressBuffer(type));
  2749. assert(expr->getNumArgs() == 2);
  2750. } else {
  2751. assert(typeTranslator.isRWByteAddressBuffer(type) ||
  2752. typeTranslator.isByteAddressBuffer(type));
  2753. if (expr->getNumArgs() == 2) {
  2754. emitError(
  2755. "(RW)ByteAddressBuffer::Load(in address, out status) not supported",
  2756. expr->getExprLoc());
  2757. return 0;
  2758. }
  2759. }
  2760. const Expr *addressExpr = expr->getArg(0);
  2761. const uint32_t byteAddress = doExpr(addressExpr);
  2762. const uint32_t addressTypeId =
  2763. typeTranslator.translateType(addressExpr->getType());
  2764. // Do a OpShiftRightLogical by 2 (divide by 4 to get aligned memory
  2765. // access). The AST always casts the address to unsinged integer, so shift
  2766. // by unsinged integer 2.
  2767. const uint32_t constUint2 = theBuilder.getConstantUint32(2);
  2768. const uint32_t address = theBuilder.createBinaryOp(
  2769. spv::Op::OpShiftRightLogical, addressTypeId, byteAddress, constUint2);
  2770. // Perform access chain into the RWByteAddressBuffer.
  2771. // First index must be zero (member 0 of the struct is a
  2772. // runtimeArray). The second index passed to OpAccessChain should be
  2773. // the address.
  2774. const uint32_t uintTypeId = theBuilder.getUint32Type();
  2775. const uint32_t ptrType =
  2776. theBuilder.getPointerType(uintTypeId, objectInfo.getStorageClass());
  2777. const uint32_t constUint0 = theBuilder.getConstantUint32(0);
  2778. if (doStore) {
  2779. const uint32_t valuesId = doExpr(expr->getArg(1));
  2780. uint32_t curStoreAddress = address;
  2781. for (uint32_t wordCounter = 0; wordCounter < numWords; ++wordCounter) {
  2782. // Extract a 32-bit word from the input.
  2783. const uint32_t curValue = numWords == 1
  2784. ? valuesId
  2785. : theBuilder.createCompositeExtract(
  2786. uintTypeId, valuesId, {wordCounter});
  2787. // Update the output address if necessary.
  2788. if (wordCounter > 0) {
  2789. const uint32_t offset = theBuilder.getConstantUint32(wordCounter);
  2790. curStoreAddress = theBuilder.createBinaryOp(
  2791. spv::Op::OpIAdd, addressTypeId, address, offset);
  2792. }
  2793. // Store the word to the right address at the output.
  2794. const uint32_t storePtr = theBuilder.createAccessChain(
  2795. ptrType, objectInfo, {constUint0, curStoreAddress});
  2796. theBuilder.createStore(storePtr, curValue);
  2797. }
  2798. } else {
  2799. uint32_t loadPtr = theBuilder.createAccessChain(ptrType, objectInfo,
  2800. {constUint0, address});
  2801. resultId = theBuilder.createLoad(uintTypeId, loadPtr);
  2802. if (numWords > 1) {
  2803. // Load word 2, 3, and 4 where necessary. Use OpCompositeConstruct to
  2804. // return a vector result.
  2805. llvm::SmallVector<uint32_t, 4> values;
  2806. values.push_back(resultId);
  2807. for (uint32_t wordCounter = 2; wordCounter <= numWords; ++wordCounter) {
  2808. const uint32_t offset = theBuilder.getConstantUint32(wordCounter - 1);
  2809. const uint32_t newAddress = theBuilder.createBinaryOp(
  2810. spv::Op::OpIAdd, addressTypeId, address, offset);
  2811. loadPtr = theBuilder.createAccessChain(ptrType, objectInfo,
  2812. {constUint0, newAddress});
  2813. values.push_back(theBuilder.createLoad(uintTypeId, loadPtr));
  2814. }
  2815. const uint32_t resultType =
  2816. theBuilder.getVecType(addressTypeId, numWords);
  2817. resultId = theBuilder.createCompositeConstruct(resultType, values);
  2818. }
  2819. }
  2820. return SpirvEvalInfo(resultId).setRValue();
  2821. }
  2822. SpirvEvalInfo
  2823. SPIRVEmitter::processStructuredBufferLoad(const CXXMemberCallExpr *expr) {
  2824. if (expr->getNumArgs() == 2) {
  2825. emitError(
  2826. "(RW)StructuredBuffer::Load(in location, out status) not supported",
  2827. expr->getExprLoc());
  2828. return 0;
  2829. }
  2830. const auto *buffer = expr->getImplicitObjectArgument();
  2831. auto info = loadIfAliasVarRef(buffer);
  2832. const QualType structType =
  2833. hlsl::GetHLSLResourceResultType(buffer->getType());
  2834. const uint32_t zero = theBuilder.getConstantInt32(0);
  2835. const uint32_t index = doExpr(expr->getArg(0));
  2836. return turnIntoElementPtr(info, structType, {zero, index});
  2837. }
  2838. uint32_t SPIRVEmitter::incDecRWACSBufferCounter(const CXXMemberCallExpr *expr,
  2839. bool isInc, bool loadObject) {
  2840. const uint32_t i32Type = theBuilder.getInt32Type();
  2841. const uint32_t one = theBuilder.getConstantUint32(1); // As scope: Device
  2842. const uint32_t zero = theBuilder.getConstantUint32(0); // As memory sema: None
  2843. const uint32_t sOne = theBuilder.getConstantInt32(1);
  2844. const auto *object =
  2845. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2846. if (loadObject) {
  2847. // We don't need the object's <result-id> here since counter variable is a
  2848. // separate variable. But we still need the side effects of evaluating the
  2849. // object, e.g., if the source code is foo(...).IncrementCounter(), we still
  2850. // want to emit the code for foo(...).
  2851. (void)doExpr(object);
  2852. }
  2853. const auto *counterPair = getFinalACSBufferCounter(object);
  2854. if (!counterPair) {
  2855. emitFatalError("cannot find the associated counter variable",
  2856. object->getExprLoc());
  2857. return 0;
  2858. }
  2859. const uint32_t counterPtrType = theBuilder.getPointerType(
  2860. theBuilder.getInt32Type(), spv::StorageClass::Uniform);
  2861. const uint32_t counterPtr = theBuilder.createAccessChain(
  2862. counterPtrType, counterPair->get(theBuilder, typeTranslator), {zero});
  2863. uint32_t index = 0;
  2864. if (isInc) {
  2865. index = theBuilder.createAtomicOp(spv::Op::OpAtomicIAdd, i32Type,
  2866. counterPtr, one, zero, sOne);
  2867. } else {
  2868. // Note that OpAtomicISub returns the value before the subtraction;
  2869. // so we need to do substraction again with OpAtomicISub's return value.
  2870. const auto prev = theBuilder.createAtomicOp(spv::Op::OpAtomicISub, i32Type,
  2871. counterPtr, one, zero, sOne);
  2872. index = theBuilder.createBinaryOp(spv::Op::OpISub, i32Type, prev, sOne);
  2873. }
  2874. return index;
  2875. }
  2876. bool SPIRVEmitter::tryToAssignCounterVar(const DeclaratorDecl *dstDecl,
  2877. const Expr *srcExpr) {
  2878. // We are handling associated counters here. Casts should not alter which
  2879. // associated counter to manipulate.
  2880. srcExpr = srcExpr->IgnoreParenCasts();
  2881. // For parameters of forward-declared functions. We must make sure the
  2882. // associated counter variable is created. But for forward-declared functions,
  2883. // the translation of the real definition may not be started yet.
  2884. if (const auto *param = dyn_cast<ParmVarDecl>(dstDecl))
  2885. declIdMapper.createFnParamCounterVar(param);
  2886. // For implicit objects of methods. Similar to the above.
  2887. else if (const auto *thisObject = dyn_cast<ImplicitParamDecl>(dstDecl))
  2888. declIdMapper.createFnParamCounterVar(thisObject);
  2889. // Handle AssocCounter#1 (see CounterVarFields comment)
  2890. if (const auto *dstPair = declIdMapper.getCounterIdAliasPair(dstDecl)) {
  2891. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  2892. if (!srcPair) {
  2893. emitFatalError("cannot find the associated counter variable",
  2894. srcExpr->getExprLoc());
  2895. return false;
  2896. }
  2897. dstPair->assign(*srcPair, theBuilder, typeTranslator);
  2898. return true;
  2899. }
  2900. // Handle AssocCounter#3
  2901. llvm::SmallVector<uint32_t, 4> srcIndices;
  2902. const auto *dstFields = declIdMapper.getCounterVarFields(dstDecl);
  2903. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  2904. if (dstFields && srcFields) {
  2905. if (!dstFields->assign(*srcFields, theBuilder, typeTranslator)) {
  2906. emitFatalError("cannot handle associated counter variable assignment",
  2907. srcExpr->getExprLoc());
  2908. return false;
  2909. }
  2910. return true;
  2911. }
  2912. // AssocCounter#2 and AssocCounter#4 for the lhs cannot happen since the lhs
  2913. // is a stand-alone decl in this method.
  2914. return false;
  2915. }
  2916. bool SPIRVEmitter::tryToAssignCounterVar(const Expr *dstExpr,
  2917. const Expr *srcExpr) {
  2918. dstExpr = dstExpr->IgnoreParenCasts();
  2919. srcExpr = srcExpr->IgnoreParenCasts();
  2920. const auto *dstPair = getFinalACSBufferCounter(dstExpr);
  2921. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  2922. if ((dstPair == nullptr) != (srcPair == nullptr)) {
  2923. emitFatalError("cannot handle associated counter variable assignment",
  2924. srcExpr->getExprLoc());
  2925. return false;
  2926. }
  2927. // Handle AssocCounter#1 & AssocCounter#2
  2928. if (dstPair && srcPair) {
  2929. dstPair->assign(*srcPair, theBuilder, typeTranslator);
  2930. return true;
  2931. }
  2932. // Handle AssocCounter#3 & AssocCounter#4
  2933. llvm::SmallVector<uint32_t, 4> dstIndices;
  2934. llvm::SmallVector<uint32_t, 4> srcIndices;
  2935. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  2936. const auto *dstFields = getIntermediateACSBufferCounter(dstExpr, &dstIndices);
  2937. if (dstFields && srcFields) {
  2938. return dstFields->assign(*srcFields, dstIndices, srcIndices, theBuilder,
  2939. typeTranslator);
  2940. }
  2941. return false;
  2942. }
  2943. const CounterIdAliasPair *
  2944. SPIRVEmitter::getFinalACSBufferCounter(const Expr *expr) {
  2945. // AssocCounter#1: referencing some stand-alone variable
  2946. if (const auto *decl = getReferencedDef(expr))
  2947. return declIdMapper.getCounterIdAliasPair(decl);
  2948. // AssocCounter#2: referencing some non-struct field
  2949. llvm::SmallVector<uint32_t, 4> indices;
  2950. const auto *base =
  2951. collectArrayStructIndices(expr, &indices, /*rawIndex=*/true);
  2952. const auto *decl =
  2953. (base && isa<CXXThisExpr>(base))
  2954. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  2955. : getReferencedDef(base);
  2956. return declIdMapper.getCounterIdAliasPair(decl, &indices);
  2957. }
  2958. const CounterVarFields *SPIRVEmitter::getIntermediateACSBufferCounter(
  2959. const Expr *expr, llvm::SmallVector<uint32_t, 4> *indices) {
  2960. const auto *base =
  2961. collectArrayStructIndices(expr, indices, /*rawIndex=*/true);
  2962. const auto *decl =
  2963. (base && isa<CXXThisExpr>(base))
  2964. // Use the decl we created to represent the implicit object
  2965. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  2966. // Find the referenced decl from the original source code
  2967. : getReferencedDef(base);
  2968. return declIdMapper.getCounterVarFields(decl);
  2969. }
  2970. const ImplicitParamDecl *
  2971. SPIRVEmitter::getOrCreateDeclForMethodObject(const CXXMethodDecl *method) {
  2972. const auto found = thisDecls.find(method);
  2973. if (found != thisDecls.end())
  2974. return found->second;
  2975. const std::string name = method->getName().str() + ".this";
  2976. // Create a new identifier to convey the name
  2977. auto &identifier = astContext.Idents.get(name);
  2978. return thisDecls[method] = ImplicitParamDecl::Create(
  2979. astContext, /*DC=*/nullptr, SourceLocation(), &identifier,
  2980. method->getThisType(astContext)->getPointeeType());
  2981. }
  2982. SpirvEvalInfo
  2983. SPIRVEmitter::processACSBufferAppendConsume(const CXXMemberCallExpr *expr) {
  2984. const bool isAppend = expr->getNumArgs() == 1;
  2985. const uint32_t zero = theBuilder.getConstantUint32(0);
  2986. const auto *object =
  2987. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2988. auto bufferInfo = loadIfAliasVarRef(object);
  2989. uint32_t index = incDecRWACSBufferCounter(
  2990. expr, isAppend,
  2991. // We have already translated the object in the above. Avoid duplication.
  2992. /*loadObject=*/false);
  2993. const auto bufferElemTy = hlsl::GetHLSLResourceResultType(object->getType());
  2994. (void)turnIntoElementPtr(bufferInfo, bufferElemTy, {zero, index});
  2995. if (isAppend) {
  2996. // Write out the value
  2997. storeValue(bufferInfo, doExpr(expr->getArg(0)), bufferElemTy);
  2998. return 0;
  2999. } else {
  3000. // Note that we are returning a pointer (lvalue) here inorder to further
  3001. // acess the fields in this element, e.g., buffer.Consume().a.b. So we
  3002. // cannot forcefully set all normal function calls as returning rvalue.
  3003. return bufferInfo;
  3004. }
  3005. }
  3006. uint32_t
  3007. SPIRVEmitter::processStreamOutputAppend(const CXXMemberCallExpr *expr) {
  3008. // TODO: handle multiple stream-output objects
  3009. const auto *object =
  3010. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3011. const auto *stream = cast<DeclRefExpr>(object)->getDecl();
  3012. const uint32_t value = doExpr(expr->getArg(0));
  3013. declIdMapper.writeBackOutputStream(stream, stream->getType(), value);
  3014. theBuilder.createEmitVertex();
  3015. return 0;
  3016. }
  3017. uint32_t
  3018. SPIRVEmitter::processStreamOutputRestart(const CXXMemberCallExpr *expr) {
  3019. // TODO: handle multiple stream-output objects
  3020. theBuilder.createEndPrimitive();
  3021. return 0;
  3022. }
  3023. uint32_t SPIRVEmitter::emitGetSamplePosition(const uint32_t sampleCount,
  3024. const uint32_t sampleIndex) {
  3025. struct Float2 {
  3026. float x;
  3027. float y;
  3028. };
  3029. static const Float2 pos2[] = {
  3030. {4.0 / 16.0, 4.0 / 16.0},
  3031. {-4.0 / 16.0, -4.0 / 16.0},
  3032. };
  3033. static const Float2 pos4[] = {
  3034. {-2.0 / 16.0, -6.0 / 16.0},
  3035. {6.0 / 16.0, -2.0 / 16.0},
  3036. {-6.0 / 16.0, 2.0 / 16.0},
  3037. {2.0 / 16.0, 6.0 / 16.0},
  3038. };
  3039. static const Float2 pos8[] = {
  3040. {1.0 / 16.0, -3.0 / 16.0}, {-1.0 / 16.0, 3.0 / 16.0},
  3041. {5.0 / 16.0, 1.0 / 16.0}, {-3.0 / 16.0, -5.0 / 16.0},
  3042. {-5.0 / 16.0, 5.0 / 16.0}, {-7.0 / 16.0, -1.0 / 16.0},
  3043. {3.0 / 16.0, 7.0 / 16.0}, {7.0 / 16.0, -7.0 / 16.0},
  3044. };
  3045. static const Float2 pos16[] = {
  3046. {1.0 / 16.0, 1.0 / 16.0}, {-1.0 / 16.0, -3.0 / 16.0},
  3047. {-3.0 / 16.0, 2.0 / 16.0}, {4.0 / 16.0, -1.0 / 16.0},
  3048. {-5.0 / 16.0, -2.0 / 16.0}, {2.0 / 16.0, 5.0 / 16.0},
  3049. {5.0 / 16.0, 3.0 / 16.0}, {3.0 / 16.0, -5.0 / 16.0},
  3050. {-2.0 / 16.0, 6.0 / 16.0}, {0.0 / 16.0, -7.0 / 16.0},
  3051. {-4.0 / 16.0, -6.0 / 16.0}, {-6.0 / 16.0, 4.0 / 16.0},
  3052. {-8.0 / 16.0, 0.0 / 16.0}, {7.0 / 16.0, -4.0 / 16.0},
  3053. {6.0 / 16.0, 7.0 / 16.0}, {-7.0 / 16.0, -8.0 / 16.0},
  3054. };
  3055. // We are emitting the SPIR-V for the following HLSL source code:
  3056. //
  3057. // float2 position;
  3058. //
  3059. // if (count == 2) {
  3060. // position = pos2[index];
  3061. // }
  3062. // else if (count == 4) {
  3063. // position = pos4[index];
  3064. // }
  3065. // else if (count == 8) {
  3066. // position = pos8[index];
  3067. // }
  3068. // else if (count == 16) {
  3069. // position = pos16[index];
  3070. // }
  3071. // else {
  3072. // position = float2(0.0f, 0.0f);
  3073. // }
  3074. const uint32_t boolType = theBuilder.getBoolType();
  3075. const auto v2f32Type = theBuilder.getVecType(theBuilder.getFloat32Type(), 2);
  3076. const uint32_t ptrType =
  3077. theBuilder.getPointerType(v2f32Type, spv::StorageClass::Function);
  3078. // Creates a SPIR-V function scope variable of type float2[len].
  3079. const auto createArray = [this, v2f32Type](const Float2 *ptr, uint32_t len) {
  3080. llvm::SmallVector<uint32_t, 16> components;
  3081. for (uint32_t i = 0; i < len; ++i) {
  3082. const auto x = theBuilder.getConstantFloat32(ptr[i].x);
  3083. const auto y = theBuilder.getConstantFloat32(ptr[i].y);
  3084. components.push_back(theBuilder.getConstantComposite(v2f32Type, {x, y}));
  3085. }
  3086. const auto arrType =
  3087. theBuilder.getArrayType(v2f32Type, theBuilder.getConstantUint32(len));
  3088. const auto val = theBuilder.getConstantComposite(arrType, components);
  3089. const std::string varName =
  3090. "var.GetSamplePosition.data." + std::to_string(len);
  3091. const auto var = theBuilder.addFnVar(arrType, varName);
  3092. theBuilder.createStore(var, val);
  3093. return var;
  3094. };
  3095. const uint32_t pos2Arr = createArray(pos2, 2);
  3096. const uint32_t pos4Arr = createArray(pos4, 4);
  3097. const uint32_t pos8Arr = createArray(pos8, 8);
  3098. const uint32_t pos16Arr = createArray(pos16, 16);
  3099. const uint32_t resultVar =
  3100. theBuilder.addFnVar(v2f32Type, "var.GetSamplePosition.result");
  3101. const uint32_t then2BB =
  3102. theBuilder.createBasicBlock("if.GetSamplePosition.then2");
  3103. const uint32_t then4BB =
  3104. theBuilder.createBasicBlock("if.GetSamplePosition.then4");
  3105. const uint32_t then8BB =
  3106. theBuilder.createBasicBlock("if.GetSamplePosition.then8");
  3107. const uint32_t then16BB =
  3108. theBuilder.createBasicBlock("if.GetSamplePosition.then16");
  3109. const uint32_t else2BB =
  3110. theBuilder.createBasicBlock("if.GetSamplePosition.else2");
  3111. const uint32_t else4BB =
  3112. theBuilder.createBasicBlock("if.GetSamplePosition.else4");
  3113. const uint32_t else8BB =
  3114. theBuilder.createBasicBlock("if.GetSamplePosition.else8");
  3115. const uint32_t else16BB =
  3116. theBuilder.createBasicBlock("if.GetSamplePosition.else16");
  3117. const uint32_t merge2BB =
  3118. theBuilder.createBasicBlock("if.GetSamplePosition.merge2");
  3119. const uint32_t merge4BB =
  3120. theBuilder.createBasicBlock("if.GetSamplePosition.merge4");
  3121. const uint32_t merge8BB =
  3122. theBuilder.createBasicBlock("if.GetSamplePosition.merge8");
  3123. const uint32_t merge16BB =
  3124. theBuilder.createBasicBlock("if.GetSamplePosition.merge16");
  3125. // if (count == 2) {
  3126. const auto check2 =
  3127. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3128. theBuilder.getConstantUint32(2));
  3129. theBuilder.createConditionalBranch(check2, then2BB, else2BB, merge2BB);
  3130. theBuilder.addSuccessor(then2BB);
  3131. theBuilder.addSuccessor(else2BB);
  3132. theBuilder.setMergeTarget(merge2BB);
  3133. // position = pos2[index];
  3134. // }
  3135. theBuilder.setInsertPoint(then2BB);
  3136. auto ac = theBuilder.createAccessChain(ptrType, pos2Arr, {sampleIndex});
  3137. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3138. theBuilder.createBranch(merge2BB);
  3139. theBuilder.addSuccessor(merge2BB);
  3140. // else if (count == 4) {
  3141. theBuilder.setInsertPoint(else2BB);
  3142. const auto check4 =
  3143. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3144. theBuilder.getConstantUint32(4));
  3145. theBuilder.createConditionalBranch(check4, then4BB, else4BB, merge4BB);
  3146. theBuilder.addSuccessor(then4BB);
  3147. theBuilder.addSuccessor(else4BB);
  3148. theBuilder.setMergeTarget(merge4BB);
  3149. // position = pos4[index];
  3150. // }
  3151. theBuilder.setInsertPoint(then4BB);
  3152. ac = theBuilder.createAccessChain(ptrType, pos4Arr, {sampleIndex});
  3153. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3154. theBuilder.createBranch(merge4BB);
  3155. theBuilder.addSuccessor(merge4BB);
  3156. // else if (count == 8) {
  3157. theBuilder.setInsertPoint(else4BB);
  3158. const auto check8 =
  3159. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3160. theBuilder.getConstantUint32(8));
  3161. theBuilder.createConditionalBranch(check8, then8BB, else8BB, merge8BB);
  3162. theBuilder.addSuccessor(then8BB);
  3163. theBuilder.addSuccessor(else8BB);
  3164. theBuilder.setMergeTarget(merge8BB);
  3165. // position = pos8[index];
  3166. // }
  3167. theBuilder.setInsertPoint(then8BB);
  3168. ac = theBuilder.createAccessChain(ptrType, pos8Arr, {sampleIndex});
  3169. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3170. theBuilder.createBranch(merge8BB);
  3171. theBuilder.addSuccessor(merge8BB);
  3172. // else if (count == 16) {
  3173. theBuilder.setInsertPoint(else8BB);
  3174. const auto check16 =
  3175. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3176. theBuilder.getConstantUint32(16));
  3177. theBuilder.createConditionalBranch(check16, then16BB, else16BB, merge16BB);
  3178. theBuilder.addSuccessor(then16BB);
  3179. theBuilder.addSuccessor(else16BB);
  3180. theBuilder.setMergeTarget(merge16BB);
  3181. // position = pos16[index];
  3182. // }
  3183. theBuilder.setInsertPoint(then16BB);
  3184. ac = theBuilder.createAccessChain(ptrType, pos16Arr, {sampleIndex});
  3185. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3186. theBuilder.createBranch(merge16BB);
  3187. theBuilder.addSuccessor(merge16BB);
  3188. // else {
  3189. // position = float2(0.0f, 0.0f);
  3190. // }
  3191. theBuilder.setInsertPoint(else16BB);
  3192. const auto zero = theBuilder.getConstantFloat32(0);
  3193. const auto v2f32Zero =
  3194. theBuilder.getConstantComposite(v2f32Type, {zero, zero});
  3195. theBuilder.createStore(resultVar, v2f32Zero);
  3196. theBuilder.createBranch(merge16BB);
  3197. theBuilder.addSuccessor(merge16BB);
  3198. theBuilder.setInsertPoint(merge16BB);
  3199. theBuilder.createBranch(merge8BB);
  3200. theBuilder.addSuccessor(merge8BB);
  3201. theBuilder.setInsertPoint(merge8BB);
  3202. theBuilder.createBranch(merge4BB);
  3203. theBuilder.addSuccessor(merge4BB);
  3204. theBuilder.setInsertPoint(merge4BB);
  3205. theBuilder.createBranch(merge2BB);
  3206. theBuilder.addSuccessor(merge2BB);
  3207. theBuilder.setInsertPoint(merge2BB);
  3208. return theBuilder.createLoad(v2f32Type, resultVar);
  3209. }
  3210. SpirvEvalInfo SPIRVEmitter::doCXXMemberCallExpr(const CXXMemberCallExpr *expr) {
  3211. const FunctionDecl *callee = expr->getDirectCallee();
  3212. llvm::StringRef group;
  3213. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  3214. if (hlsl::GetIntrinsicOp(callee, opcode, group)) {
  3215. return processIntrinsicMemberCall(expr,
  3216. static_cast<hlsl::IntrinsicOp>(opcode));
  3217. }
  3218. return processCall(expr);
  3219. }
  3220. void SPIRVEmitter::handleOffsetInMethodCall(const CXXMemberCallExpr *expr,
  3221. uint32_t index,
  3222. uint32_t *constOffset,
  3223. uint32_t *varOffset) {
  3224. // Ensure the given arg index is not out-of-range.
  3225. assert(index < expr->getNumArgs());
  3226. *constOffset = *varOffset = 0; // Initialize both first
  3227. if (*constOffset = tryToEvaluateAsConst(expr->getArg(index)))
  3228. return; // Constant offset
  3229. else
  3230. *varOffset = doExpr(expr->getArg(index));
  3231. };
  3232. SpirvEvalInfo
  3233. SPIRVEmitter::processIntrinsicMemberCall(const CXXMemberCallExpr *expr,
  3234. hlsl::IntrinsicOp opcode) {
  3235. using namespace hlsl;
  3236. uint32_t retVal = 0;
  3237. switch (opcode) {
  3238. case IntrinsicOp::MOP_Sample:
  3239. retVal = processTextureSampleGather(expr, /*isSample=*/true);
  3240. break;
  3241. case IntrinsicOp::MOP_Gather:
  3242. retVal = processTextureSampleGather(expr, /*isSample=*/false);
  3243. break;
  3244. case IntrinsicOp::MOP_SampleBias:
  3245. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/true);
  3246. break;
  3247. case IntrinsicOp::MOP_SampleLevel:
  3248. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/false);
  3249. break;
  3250. case IntrinsicOp::MOP_SampleGrad:
  3251. retVal = processTextureSampleGrad(expr);
  3252. break;
  3253. case IntrinsicOp::MOP_SampleCmp:
  3254. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/true);
  3255. break;
  3256. case IntrinsicOp::MOP_SampleCmpLevelZero:
  3257. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/false);
  3258. break;
  3259. case IntrinsicOp::MOP_GatherRed:
  3260. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 0);
  3261. break;
  3262. case IntrinsicOp::MOP_GatherGreen:
  3263. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 1);
  3264. break;
  3265. case IntrinsicOp::MOP_GatherBlue:
  3266. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 2);
  3267. break;
  3268. case IntrinsicOp::MOP_GatherAlpha:
  3269. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 3);
  3270. break;
  3271. case IntrinsicOp::MOP_GatherCmp:
  3272. retVal = processTextureGatherCmp(expr);
  3273. break;
  3274. case IntrinsicOp::MOP_GatherCmpRed:
  3275. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/true, 0);
  3276. break;
  3277. case IntrinsicOp::MOP_Load:
  3278. return processBufferTextureLoad(expr);
  3279. case IntrinsicOp::MOP_Load2:
  3280. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ false);
  3281. case IntrinsicOp::MOP_Load3:
  3282. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ false);
  3283. case IntrinsicOp::MOP_Load4:
  3284. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ false);
  3285. case IntrinsicOp::MOP_Store:
  3286. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ true);
  3287. case IntrinsicOp::MOP_Store2:
  3288. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ true);
  3289. case IntrinsicOp::MOP_Store3:
  3290. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ true);
  3291. case IntrinsicOp::MOP_Store4:
  3292. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ true);
  3293. case IntrinsicOp::MOP_GetDimensions:
  3294. retVal = processGetDimensions(expr);
  3295. break;
  3296. case IntrinsicOp::MOP_CalculateLevelOfDetail:
  3297. retVal = processTextureLevelOfDetail(expr);
  3298. break;
  3299. case IntrinsicOp::MOP_IncrementCounter:
  3300. retVal = theBuilder.createUnaryOp(
  3301. spv::Op::OpBitcast, theBuilder.getUint32Type(),
  3302. incDecRWACSBufferCounter(expr, /*isInc*/ true));
  3303. break;
  3304. case IntrinsicOp::MOP_DecrementCounter:
  3305. retVal = theBuilder.createUnaryOp(
  3306. spv::Op::OpBitcast, theBuilder.getUint32Type(),
  3307. incDecRWACSBufferCounter(expr, /*isInc*/ false));
  3308. break;
  3309. case IntrinsicOp::MOP_Append:
  3310. if (hlsl::IsHLSLStreamOutputType(
  3311. expr->getImplicitObjectArgument()->getType()))
  3312. return processStreamOutputAppend(expr);
  3313. else
  3314. return processACSBufferAppendConsume(expr);
  3315. case IntrinsicOp::MOP_Consume:
  3316. return processACSBufferAppendConsume(expr);
  3317. case IntrinsicOp::MOP_RestartStrip:
  3318. retVal = processStreamOutputRestart(expr);
  3319. break;
  3320. case IntrinsicOp::MOP_InterlockedAdd:
  3321. case IntrinsicOp::MOP_InterlockedAnd:
  3322. case IntrinsicOp::MOP_InterlockedOr:
  3323. case IntrinsicOp::MOP_InterlockedXor:
  3324. case IntrinsicOp::MOP_InterlockedUMax:
  3325. case IntrinsicOp::MOP_InterlockedUMin:
  3326. case IntrinsicOp::MOP_InterlockedMax:
  3327. case IntrinsicOp::MOP_InterlockedMin:
  3328. case IntrinsicOp::MOP_InterlockedExchange:
  3329. case IntrinsicOp::MOP_InterlockedCompareExchange:
  3330. case IntrinsicOp::MOP_InterlockedCompareStore:
  3331. retVal = processRWByteAddressBufferAtomicMethods(opcode, expr);
  3332. break;
  3333. case IntrinsicOp::MOP_GetSamplePosition:
  3334. retVal = processGetSamplePosition(expr);
  3335. break;
  3336. case IntrinsicOp::MOP_SubpassLoad:
  3337. retVal = processSubpassLoad(expr);
  3338. break;
  3339. case IntrinsicOp::MOP_GatherCmpGreen:
  3340. case IntrinsicOp::MOP_GatherCmpBlue:
  3341. case IntrinsicOp::MOP_GatherCmpAlpha:
  3342. case IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped:
  3343. emitError("no equivalent for %0 intrinsic method in Vulkan",
  3344. expr->getCallee()->getExprLoc())
  3345. << expr->getMethodDecl()->getName();
  3346. return 0;
  3347. default:
  3348. emitError("intrinsic '%0' method unimplemented",
  3349. expr->getCallee()->getExprLoc())
  3350. << expr->getDirectCallee()->getName();
  3351. return 0;
  3352. }
  3353. return SpirvEvalInfo(retVal).setRValue();
  3354. }
  3355. uint32_t SPIRVEmitter::createImageSample(
  3356. QualType retType, uint32_t imageType, uint32_t image, uint32_t sampler,
  3357. bool isNonUniform, uint32_t coordinate, uint32_t compareVal, uint32_t bias,
  3358. uint32_t lod, std::pair<uint32_t, uint32_t> grad, uint32_t constOffset,
  3359. uint32_t varOffset, uint32_t constOffsets, uint32_t sample, uint32_t minLod,
  3360. uint32_t residencyCodeId) {
  3361. const auto retTypeId = typeTranslator.translateType(retType);
  3362. // SampleDref* instructions in SPIR-V always return a scalar.
  3363. // They also have the correct type in HLSL.
  3364. if (compareVal) {
  3365. return theBuilder.createImageSample(
  3366. retTypeId, imageType, image, sampler, isNonUniform, coordinate,
  3367. compareVal, bias, lod, grad, constOffset, varOffset, constOffsets,
  3368. sample, minLod, residencyCodeId);
  3369. }
  3370. // Non-Dref Sample instructions in SPIR-V must always return a vec4.
  3371. auto texelTypeId = retTypeId;
  3372. QualType elemType = {};
  3373. uint32_t elemTypeId = 0;
  3374. uint32_t retVecSize = 0;
  3375. if (TypeTranslator::isVectorType(retType, &elemType, &retVecSize) &&
  3376. retVecSize != 4) {
  3377. elemTypeId = typeTranslator.translateType(elemType);
  3378. texelTypeId = theBuilder.getVecType(elemTypeId, 4);
  3379. } else if (TypeTranslator::isScalarType(retType)) {
  3380. retVecSize = 1;
  3381. elemTypeId = typeTranslator.translateType(retType);
  3382. texelTypeId = theBuilder.getVecType(elemTypeId, 4);
  3383. }
  3384. // The Lod and Grad image operands requires explicit-lod instructions.
  3385. // Otherwise we use implicit-lod instructions.
  3386. const bool isExplicit = lod || (grad.first && grad.second);
  3387. // Implicit-lod instructions are only allowed in pixel shader.
  3388. if (!shaderModel.IsPS() && !isExplicit)
  3389. needsLegalization = true;
  3390. uint32_t retVal = theBuilder.createImageSample(
  3391. texelTypeId, imageType, image, sampler, isNonUniform, coordinate,
  3392. compareVal, bias, lod, grad, constOffset, varOffset, constOffsets, sample,
  3393. minLod, residencyCodeId);
  3394. // Extract smaller vector from the vec4 result if necessary.
  3395. if (texelTypeId != retTypeId) {
  3396. retVal = extractVecFromVec4(retVal, retVecSize, elemTypeId);
  3397. }
  3398. return retVal;
  3399. }
  3400. uint32_t SPIRVEmitter::processTextureSampleGather(const CXXMemberCallExpr *expr,
  3401. const bool isSample) {
  3402. // Signatures:
  3403. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3404. // DXGI_FORMAT Object.Sample(sampler_state S,
  3405. // float Location
  3406. // [, int Offset]
  3407. // [, float Clamp]
  3408. // [, out uint Status]);
  3409. //
  3410. // For TextureCube and TextureCubeArray:
  3411. // DXGI_FORMAT Object.Sample(sampler_state S,
  3412. // float Location
  3413. // [, float Clamp]
  3414. // [, out uint Status]);
  3415. //
  3416. // For Texture2D/Texture2DArray:
  3417. // <Template Type>4 Object.Gather(sampler_state S,
  3418. // float2|3|4 Location,
  3419. // int2 Offset
  3420. // [, uint Status]);
  3421. //
  3422. // For TextureCube/TextureCubeArray:
  3423. // <Template Type>4 Object.Gather(sampler_state S,
  3424. // float2|3|4 Location
  3425. // [, uint Status]);
  3426. //
  3427. // Other Texture types do not have a Gather method.
  3428. const auto numArgs = expr->getNumArgs();
  3429. const bool hasStatusArg =
  3430. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3431. uint32_t clamp = 0;
  3432. if (numArgs > 2 && expr->getArg(2)->getType()->isFloatingType())
  3433. clamp = doExpr(expr->getArg(2));
  3434. else if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3435. clamp = doExpr(expr->getArg(3));
  3436. const bool hasClampArg = (clamp != 0);
  3437. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3438. // Subtract 1 for status (if it exists), subtract 1 for clamp (if it exists),
  3439. // and subtract 2 for sampler_state and location.
  3440. const bool hasOffsetArg = numArgs - hasStatusArg - hasClampArg - 2 > 0;
  3441. const auto *imageExpr = expr->getImplicitObjectArgument();
  3442. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3443. const auto image = loadIfGLValue(imageExpr);
  3444. const auto sampler = doExpr(expr->getArg(0));
  3445. const uint32_t coordinate = doExpr(expr->getArg(1));
  3446. // .Sample()/.Gather() may have a third optional paramter for offset.
  3447. uint32_t constOffset = 0, varOffset = 0;
  3448. if (hasOffsetArg)
  3449. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3450. const bool isNonUniform = image.isNonUniform() || sampler.isNonUniform();
  3451. const auto retType = expr->getDirectCallee()->getReturnType();
  3452. const auto retTypeId = typeTranslator.translateType(retType);
  3453. if (isSample) {
  3454. return createImageSample(
  3455. retType, imageType, image, sampler, isNonUniform, coordinate,
  3456. /*compareVal*/ 0, /*bias*/ 0, /*lod*/ 0, std::make_pair(0, 0),
  3457. constOffset, varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0,
  3458. /*minLod*/ clamp, status);
  3459. } else {
  3460. return theBuilder.createImageGather(
  3461. retTypeId, imageType, image, sampler, isNonUniform, coordinate,
  3462. // .Gather() doc says we return four components of red data.
  3463. theBuilder.getConstantInt32(0), /*compareVal*/ 0, constOffset,
  3464. varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0, status);
  3465. }
  3466. }
  3467. uint32_t
  3468. SPIRVEmitter::processTextureSampleBiasLevel(const CXXMemberCallExpr *expr,
  3469. const bool isBias) {
  3470. // Signatures:
  3471. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3472. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3473. // float Location,
  3474. // float Bias
  3475. // [, int Offset]
  3476. // [, float clamp]
  3477. // [, out uint Status]);
  3478. //
  3479. // For TextureCube and TextureCubeArray:
  3480. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3481. // float Location,
  3482. // float Bias
  3483. // [, float clamp]
  3484. // [, out uint Status]);
  3485. //
  3486. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3487. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3488. // float Location,
  3489. // float LOD
  3490. // [, int Offset]
  3491. // [, out uint Status]);
  3492. //
  3493. // For TextureCube and TextureCubeArray:
  3494. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3495. // float Location,
  3496. // float LOD
  3497. // [, out uint Status]);
  3498. const auto numArgs = expr->getNumArgs();
  3499. const bool hasStatusArg =
  3500. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3501. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3502. uint32_t clamp = 0;
  3503. // The .SampleLevel() methods do not take the clamp argument.
  3504. if (isBias) {
  3505. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3506. clamp = doExpr(expr->getArg(3));
  3507. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3508. clamp = doExpr(expr->getArg(4));
  3509. }
  3510. const bool hasClampArg = clamp != 0;
  3511. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3512. // and 3 for sampler_state, location, and Bias/LOD.
  3513. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3514. const auto *imageExpr = expr->getImplicitObjectArgument();
  3515. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3516. const auto image = loadIfGLValue(imageExpr);
  3517. const auto sampler = doExpr(expr->getArg(0));
  3518. const uint32_t coordinate = doExpr(expr->getArg(1));
  3519. uint32_t lod = 0;
  3520. uint32_t bias = 0;
  3521. if (isBias) {
  3522. bias = doExpr(expr->getArg(2));
  3523. } else {
  3524. lod = doExpr(expr->getArg(2));
  3525. }
  3526. // If offset is present in .Bias()/.SampleLevel(), it is the fourth argument.
  3527. uint32_t constOffset = 0, varOffset = 0;
  3528. if (hasOffsetArg)
  3529. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3530. const auto retType = expr->getDirectCallee()->getReturnType();
  3531. return createImageSample(
  3532. retType, imageType, image, sampler,
  3533. image.isNonUniform() || sampler.isNonUniform(), coordinate,
  3534. /*compareVal*/ 0, bias, lod, std::make_pair(0, 0), constOffset, varOffset,
  3535. /*constOffsets*/ 0, /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3536. }
  3537. uint32_t SPIRVEmitter::processTextureSampleGrad(const CXXMemberCallExpr *expr) {
  3538. // Signature:
  3539. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3540. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3541. // float Location,
  3542. // float DDX,
  3543. // float DDY
  3544. // [, int Offset]
  3545. // [, float Clamp]
  3546. // [, out uint Status]);
  3547. //
  3548. // For TextureCube and TextureCubeArray:
  3549. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3550. // float Location,
  3551. // float DDX,
  3552. // float DDY
  3553. // [, float Clamp]
  3554. // [, out uint Status]);
  3555. const auto numArgs = expr->getNumArgs();
  3556. const bool hasStatusArg =
  3557. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3558. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3559. uint32_t clamp = 0;
  3560. if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3561. clamp = doExpr(expr->getArg(4));
  3562. else if (numArgs > 5 && expr->getArg(5)->getType()->isFloatingType())
  3563. clamp = doExpr(expr->getArg(5));
  3564. const bool hasClampArg = clamp != 0;
  3565. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3566. // and 4 for sampler_state, location, DDX, and DDY;
  3567. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 4 > 0;
  3568. const auto *imageExpr = expr->getImplicitObjectArgument();
  3569. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3570. const auto image = loadIfGLValue(imageExpr);
  3571. const auto sampler = doExpr(expr->getArg(0));
  3572. const uint32_t coordinate = doExpr(expr->getArg(1));
  3573. const uint32_t ddx = doExpr(expr->getArg(2));
  3574. const uint32_t ddy = doExpr(expr->getArg(3));
  3575. // If offset is present in .SampleGrad(), it is the fifth argument.
  3576. uint32_t constOffset = 0, varOffset = 0;
  3577. if (hasOffsetArg)
  3578. handleOffsetInMethodCall(expr, 4, &constOffset, &varOffset);
  3579. const auto retType = expr->getDirectCallee()->getReturnType();
  3580. return createImageSample(
  3581. retType, imageType, image, sampler,
  3582. image.isNonUniform() || sampler.isNonUniform(), coordinate,
  3583. /*compareVal*/ 0, /*bias*/ 0, /*lod*/ 0, std::make_pair(ddx, ddy),
  3584. constOffset, varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0,
  3585. /*minLod*/ clamp, status);
  3586. }
  3587. uint32_t
  3588. SPIRVEmitter::processTextureSampleCmpCmpLevelZero(const CXXMemberCallExpr *expr,
  3589. const bool isCmp) {
  3590. // .SampleCmp() Signature:
  3591. //
  3592. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3593. // float Object.SampleCmp(
  3594. // SamplerComparisonState S,
  3595. // float Location,
  3596. // float CompareValue
  3597. // [, int Offset]
  3598. // [, float Clamp]
  3599. // [, out uint Status]
  3600. // );
  3601. //
  3602. // For TextureCube and TextureCubeArray:
  3603. // float Object.SampleCmp(
  3604. // SamplerComparisonState S,
  3605. // float Location,
  3606. // float CompareValue
  3607. // [, float Clamp]
  3608. // [, out uint Status]
  3609. // );
  3610. //
  3611. // .SampleCmpLevelZero() is identical to .SampleCmp() on mipmap level 0 only.
  3612. // It never takes a clamp argument, which is good because lod and clamp may
  3613. // not be used together.
  3614. //
  3615. // .SampleCmpLevelZero() Signature:
  3616. //
  3617. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3618. // float Object.SampleCmpLevelZero(
  3619. // SamplerComparisonState S,
  3620. // float Location,
  3621. // float CompareValue
  3622. // [, int Offset]
  3623. // [, out uint Status]
  3624. // );
  3625. //
  3626. // For TextureCube and TextureCubeArray:
  3627. // float Object.SampleCmpLevelZero(
  3628. // SamplerComparisonState S,
  3629. // float Location,
  3630. // float CompareValue
  3631. // [, out uint Status]
  3632. // );
  3633. const auto numArgs = expr->getNumArgs();
  3634. const bool hasStatusArg =
  3635. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3636. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3637. uint32_t clamp = 0;
  3638. // The .SampleCmpLevelZero() methods do not take the clamp argument.
  3639. if (isCmp) {
  3640. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3641. clamp = doExpr(expr->getArg(3));
  3642. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3643. clamp = doExpr(expr->getArg(4));
  3644. }
  3645. const bool hasClampArg = clamp != 0;
  3646. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3647. // and 3 for sampler_state, location, and compare_value.
  3648. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3649. const auto *imageExpr = expr->getImplicitObjectArgument();
  3650. const auto image = loadIfGLValue(imageExpr);
  3651. const auto sampler = doExpr(expr->getArg(0));
  3652. const uint32_t coordinate = doExpr(expr->getArg(1));
  3653. const uint32_t compareVal = doExpr(expr->getArg(2));
  3654. // If offset is present in .SampleCmp(), it will be the fourth argument.
  3655. uint32_t constOffset = 0, varOffset = 0;
  3656. if (hasOffsetArg)
  3657. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3658. const uint32_t lod = isCmp ? 0 : theBuilder.getConstantFloat32(0);
  3659. const auto retType = expr->getDirectCallee()->getReturnType();
  3660. // TODO: Hack. Drivers are expecting the Depth value in OpTypeImage to match
  3661. // the OpImageSample* instruction: Depth=0 for normal sampling, and Depth=1
  3662. // for depth-comparison sampling. That behavior is not what the spec says;
  3663. // Vulkan spec reads "The 'Depth' operand of OpTypeImage is ignored."
  3664. // We always generate OpTypeImage variables with Depth=0. Hack this only
  3665. // depth-comparison sampling code path to use Depth=1 for the OpTypeImage
  3666. // used by OpSampledImage. This causes inconsistent types in SPIR-V, but
  3667. // pleases drivers. Whatever.
  3668. const auto imageType = typeTranslator.translateResourceType(
  3669. imageExpr->getType(), LayoutRule::Void, /*isDepthCmp=*/true);
  3670. return createImageSample(
  3671. retType, imageType, image, sampler,
  3672. image.isNonUniform() || sampler.isNonUniform(), coordinate, compareVal,
  3673. /*bias*/ 0, lod, std::make_pair(0, 0), constOffset, varOffset,
  3674. /*constOffsets*/ 0, /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3675. }
  3676. SpirvEvalInfo
  3677. SPIRVEmitter::processBufferTextureLoad(const CXXMemberCallExpr *expr) {
  3678. // Signature:
  3679. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3680. // ret Object.Load(int Location
  3681. // [, int Offset]
  3682. // [, uint status]);
  3683. //
  3684. // For Texture2DMS and Texture2DMSArray, there is one additional argument:
  3685. // ret Object.Load(int Location
  3686. // [, int SampleIndex]
  3687. // [, int Offset]
  3688. // [, uint status]);
  3689. //
  3690. // For (RW)Buffer, RWTexture1D, RWTexture1DArray, RWTexture2D,
  3691. // RWTexture2DArray, RWTexture3D:
  3692. // ret Object.Load (int Location
  3693. // [, uint status]);
  3694. //
  3695. // Note: (RW)ByteAddressBuffer and (RW)StructuredBuffer types also have Load
  3696. // methods that take an additional Status argument. However, since these types
  3697. // are not represented as OpTypeImage in SPIR-V, we don't have a way of
  3698. // figuring out the Residency Code for them. Therefore having the Status
  3699. // argument for these types is not supported.
  3700. //
  3701. // For (RW)ByteAddressBuffer:
  3702. // ret Object.{Load,Load2,Load3,Load4} (int Location
  3703. // [, uint status]);
  3704. //
  3705. // For (RW)StructuredBuffer:
  3706. // ret Object.Load (int Location
  3707. // [, uint status]);
  3708. //
  3709. const auto *object = expr->getImplicitObjectArgument();
  3710. const auto objectType = object->getType();
  3711. if (typeTranslator.isRWByteAddressBuffer(objectType) ||
  3712. typeTranslator.isByteAddressBuffer(objectType))
  3713. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ false);
  3714. if (TypeTranslator::isStructuredBuffer(objectType))
  3715. return processStructuredBufferLoad(expr);
  3716. const auto numArgs = expr->getNumArgs();
  3717. const auto *location = expr->getArg(0);
  3718. const bool isTextureMS = TypeTranslator::isTextureMS(objectType);
  3719. const bool hasStatusArg =
  3720. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3721. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3722. if (TypeTranslator::isBuffer(objectType) ||
  3723. TypeTranslator::isRWBuffer(objectType) ||
  3724. TypeTranslator::isRWTexture(objectType))
  3725. return processBufferTextureLoad(object, doExpr(location), /*constOffset*/ 0,
  3726. /*varOffset*/ 0, /*lod*/ 0,
  3727. /*residencyCode*/ status);
  3728. // Subtract 1 for status (if it exists), and 1 for sampleIndex (if it exists),
  3729. // and 1 for location.
  3730. const bool hasOffsetArg = numArgs - hasStatusArg - isTextureMS - 1 > 0;
  3731. if (TypeTranslator::isTexture(objectType)) {
  3732. // .Load() has a second optional paramter for offset.
  3733. const auto locationId = doExpr(location);
  3734. uint32_t constOffset = 0, varOffset = 0;
  3735. uint32_t coordinate = locationId, lod = 0;
  3736. if (isTextureMS) {
  3737. // SampleIndex is only available when the Object is of Texture2DMS or
  3738. // Texture2DMSArray types. Under those cases, Offset will be the third
  3739. // parameter (index 2).
  3740. lod = doExpr(expr->getArg(1));
  3741. if (hasOffsetArg)
  3742. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3743. } else {
  3744. // For Texture Load() functions, the location parameter is a vector
  3745. // that consists of both the coordinate and the mipmap level (via the
  3746. // last vector element). We need to split it here since the
  3747. // OpImageFetch SPIR-V instruction encodes them as separate arguments.
  3748. splitVecLastElement(location->getType(), locationId, &coordinate, &lod);
  3749. // For textures other than Texture2DMS(Array), offset should be the
  3750. // second parameter (index 1).
  3751. if (hasOffsetArg)
  3752. handleOffsetInMethodCall(expr, 1, &constOffset, &varOffset);
  3753. }
  3754. return processBufferTextureLoad(object, coordinate, constOffset, varOffset,
  3755. lod, status);
  3756. }
  3757. emitError("Load() of the given object type unimplemented",
  3758. object->getExprLoc());
  3759. return 0;
  3760. }
  3761. uint32_t SPIRVEmitter::processGetDimensions(const CXXMemberCallExpr *expr) {
  3762. const auto objectType = expr->getImplicitObjectArgument()->getType();
  3763. if (TypeTranslator::isTexture(objectType) ||
  3764. TypeTranslator::isRWTexture(objectType) ||
  3765. TypeTranslator::isBuffer(objectType) ||
  3766. TypeTranslator::isRWBuffer(objectType)) {
  3767. return processBufferTextureGetDimensions(expr);
  3768. } else if (TypeTranslator::isByteAddressBuffer(objectType) ||
  3769. TypeTranslator::isRWByteAddressBuffer(objectType) ||
  3770. TypeTranslator::isStructuredBuffer(objectType) ||
  3771. TypeTranslator::isAppendStructuredBuffer(objectType) ||
  3772. TypeTranslator::isConsumeStructuredBuffer(objectType)) {
  3773. return processByteAddressBufferStructuredBufferGetDimensions(expr);
  3774. } else {
  3775. emitError("GetDimensions() of the given object type unimplemented",
  3776. expr->getExprLoc());
  3777. return 0;
  3778. }
  3779. }
  3780. SpirvEvalInfo
  3781. SPIRVEmitter::doCXXOperatorCallExpr(const CXXOperatorCallExpr *expr) {
  3782. { // Handle Buffer/RWBuffer/Texture/RWTexture indexing
  3783. const Expr *baseExpr = nullptr;
  3784. const Expr *indexExpr = nullptr;
  3785. const Expr *lodExpr = nullptr;
  3786. // For Textures, regular indexing (operator[]) uses slice 0.
  3787. if (isBufferTextureIndexing(expr, &baseExpr, &indexExpr)) {
  3788. const uint32_t lod = TypeTranslator::isTexture(baseExpr->getType())
  3789. ? theBuilder.getConstantUint32(0)
  3790. : 0;
  3791. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  3792. /*constOffset*/ 0, /*varOffset*/ 0, lod,
  3793. /*residencyCode*/ 0);
  3794. }
  3795. // .mips[][] or .sample[][] must use the correct slice.
  3796. if (isTextureMipsSampleIndexing(expr, &baseExpr, &indexExpr, &lodExpr)) {
  3797. const uint32_t lod = doExpr(lodExpr);
  3798. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  3799. /*constOffset*/ 0, /*varOffset*/ 0, lod,
  3800. /*residencyCode*/ 0);
  3801. }
  3802. }
  3803. llvm::SmallVector<uint32_t, 4> indices;
  3804. const Expr *baseExpr = collectArrayStructIndices(expr, &indices);
  3805. auto base = loadIfAliasVarRef(baseExpr);
  3806. if (indices.empty())
  3807. return base; // For indexing into size-1 vectors and 1xN matrices
  3808. // If we are indexing into a rvalue, to use OpAccessChain, we first need
  3809. // to create a local variable to hold the rvalue.
  3810. //
  3811. // TODO: We can optimize the codegen by emitting OpCompositeExtract if
  3812. // all indices are contant integers.
  3813. if (base.isRValue()) {
  3814. base = createTemporaryVar(baseExpr->getType(), "vector", base);
  3815. }
  3816. return turnIntoElementPtr(base, expr->getType(), indices);
  3817. }
  3818. SpirvEvalInfo
  3819. SPIRVEmitter::doExtMatrixElementExpr(const ExtMatrixElementExpr *expr) {
  3820. const Expr *baseExpr = expr->getBase();
  3821. const auto baseInfo = doExpr(baseExpr);
  3822. const auto layoutRule = baseInfo.getLayoutRule();
  3823. const auto elemType = hlsl::GetHLSLMatElementType(baseExpr->getType());
  3824. const auto accessor = expr->getEncodedElementAccess();
  3825. const uint32_t elemTypeId =
  3826. typeTranslator.translateType(elemType, layoutRule);
  3827. uint32_t rowCount = 0, colCount = 0;
  3828. hlsl::GetHLSLMatRowColCount(baseExpr->getType(), rowCount, colCount);
  3829. // Construct a temporary vector out of all elements accessed:
  3830. // 1. Create access chain for each element using OpAccessChain
  3831. // 2. Load each element using OpLoad
  3832. // 3. Create the vector using OpCompositeConstruct
  3833. llvm::SmallVector<uint32_t, 4> elements;
  3834. for (uint32_t i = 0; i < accessor.Count; ++i) {
  3835. uint32_t row = 0, col = 0, elem = 0;
  3836. accessor.GetPosition(i, &row, &col);
  3837. llvm::SmallVector<uint32_t, 2> indices;
  3838. // If the matrix only has one row/column, we are indexing into a vector
  3839. // then. Only one index is needed for such cases.
  3840. if (rowCount > 1)
  3841. indices.push_back(row);
  3842. if (colCount > 1)
  3843. indices.push_back(col);
  3844. if (baseExpr->isGLValue()) {
  3845. for (uint32_t i = 0; i < indices.size(); ++i)
  3846. indices[i] = theBuilder.getConstantInt32(indices[i]);
  3847. const uint32_t ptrType =
  3848. theBuilder.getPointerType(elemTypeId, baseInfo.getStorageClass());
  3849. if (!indices.empty()) {
  3850. assert(!baseInfo.isRValue());
  3851. // Load the element via access chain
  3852. elem = theBuilder.createAccessChain(ptrType, baseInfo, indices);
  3853. } else {
  3854. // The matrix is of size 1x1. No need to use access chain, base should
  3855. // be the source pointer.
  3856. elem = baseInfo;
  3857. }
  3858. elem = theBuilder.createLoad(elemTypeId, elem);
  3859. } else { // e.g., (mat1 + mat2)._m11
  3860. elem = theBuilder.createCompositeExtract(elemTypeId, baseInfo, indices);
  3861. }
  3862. elements.push_back(elem);
  3863. }
  3864. const auto size = elements.size();
  3865. auto valueId = elements.front();
  3866. if (size > 1) {
  3867. const uint32_t vecType = theBuilder.getVecType(elemTypeId, size);
  3868. valueId = theBuilder.createCompositeConstruct(vecType, elements);
  3869. }
  3870. // Note: Special-case: Booleans have no physical layout, and therefore when
  3871. // layout is required booleans are represented as unsigned integers.
  3872. // Therefore, after loading the uint we should convert it boolean.
  3873. if (elemType->isBooleanType() && layoutRule != LayoutRule::Void) {
  3874. const auto fromType =
  3875. size == 1 ? astContext.UnsignedIntTy
  3876. : astContext.getExtVectorType(astContext.UnsignedIntTy, size);
  3877. const auto toType =
  3878. size == 1 ? astContext.BoolTy
  3879. : astContext.getExtVectorType(astContext.BoolTy, size);
  3880. valueId = castToBool(valueId, fromType, toType);
  3881. }
  3882. return SpirvEvalInfo(valueId).setRValue();
  3883. }
  3884. SpirvEvalInfo
  3885. SPIRVEmitter::doHLSLVectorElementExpr(const HLSLVectorElementExpr *expr) {
  3886. const Expr *baseExpr = nullptr;
  3887. hlsl::VectorMemberAccessPositions accessor;
  3888. condenseVectorElementExpr(expr, &baseExpr, &accessor);
  3889. const QualType baseType = baseExpr->getType();
  3890. assert(hlsl::IsHLSLVecType(baseType));
  3891. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  3892. const auto accessorSize = static_cast<size_t>(accessor.Count);
  3893. // Depending on the number of elements selected, we emit different
  3894. // instructions.
  3895. // For vectors of size greater than 1, if we are only selecting one element,
  3896. // typical access chain or composite extraction should be fine. But if we
  3897. // are selecting more than one elements, we must resolve to vector specific
  3898. // operations.
  3899. // For size-1 vectors, if we are selecting their single elements multiple
  3900. // times, we need composite construct instructions.
  3901. if (accessorSize == 1) {
  3902. auto baseInfo = doExpr(baseExpr);
  3903. if (baseSize == 1) {
  3904. // Selecting one element from a size-1 vector. The underlying vector is
  3905. // already treated as a scalar.
  3906. return baseInfo;
  3907. }
  3908. // If the base is an lvalue, we should emit an access chain instruction
  3909. // so that we can load/store the specified element. For rvalue base,
  3910. // we should use composite extraction. We should check the immediate base
  3911. // instead of the original base here since we can have something like
  3912. // v.xyyz to turn a lvalue v into rvalue.
  3913. const auto type =
  3914. typeTranslator.translateType(expr->getType(), baseInfo.getLayoutRule());
  3915. if (!baseInfo.isRValue()) { // E.g., v.x;
  3916. const uint32_t ptrType =
  3917. theBuilder.getPointerType(type, baseInfo.getStorageClass());
  3918. const uint32_t index = theBuilder.getConstantInt32(accessor.Swz0);
  3919. // We need a lvalue here. Do not try to load.
  3920. return baseInfo.setResultId(
  3921. theBuilder.createAccessChain(ptrType, baseInfo, {index}));
  3922. } else { // E.g., (v + w).x;
  3923. // The original base vector may not be a rvalue. Need to load it if
  3924. // it is lvalue since ImplicitCastExpr (LValueToRValue) will be missing
  3925. // for that case.
  3926. auto result =
  3927. theBuilder.createCompositeExtract(type, baseInfo, {accessor.Swz0});
  3928. // Special-case: Booleans in SPIR-V do not have a physical layout. Uint is
  3929. // used to represent them when layout is required.
  3930. if (expr->getType()->isBooleanType() &&
  3931. baseInfo.getLayoutRule() != LayoutRule::Void)
  3932. result =
  3933. castToBool(result, astContext.UnsignedIntTy, astContext.BoolTy);
  3934. return baseInfo.setResultId(result);
  3935. }
  3936. }
  3937. if (baseSize == 1) {
  3938. // Selecting more than one element from a size-1 vector, for example,
  3939. // <scalar>.xx. Construct the vector.
  3940. auto info = loadIfGLValue(baseExpr);
  3941. const auto type =
  3942. typeTranslator.translateType(expr->getType(), info.getLayoutRule());
  3943. llvm::SmallVector<uint32_t, 4> components(accessorSize, info);
  3944. return info
  3945. .setResultId(theBuilder.createCompositeConstruct(type, components))
  3946. .setRValue();
  3947. }
  3948. llvm::SmallVector<uint32_t, 4> selectors;
  3949. selectors.resize(accessorSize);
  3950. // Whether we are selecting elements in the original order
  3951. bool originalOrder = baseSize == accessorSize;
  3952. for (uint32_t i = 0; i < accessorSize; ++i) {
  3953. accessor.GetPosition(i, &selectors[i]);
  3954. // We can select more elements than the vector provides. This handles
  3955. // that case too.
  3956. originalOrder &= selectors[i] == i;
  3957. }
  3958. if (originalOrder)
  3959. return doExpr(baseExpr);
  3960. auto info = loadIfGLValue(baseExpr);
  3961. const auto type =
  3962. typeTranslator.translateType(expr->getType(), info.getLayoutRule());
  3963. // Use base for both vectors. But we are only selecting values from the
  3964. // first one.
  3965. return info.setResultId(
  3966. theBuilder.createVectorShuffle(type, info, info, selectors));
  3967. }
  3968. SpirvEvalInfo SPIRVEmitter::doInitListExpr(const InitListExpr *expr) {
  3969. if (const uint32_t id = tryToEvaluateAsConst(expr))
  3970. return SpirvEvalInfo(id).setRValue();
  3971. return SpirvEvalInfo(InitListHandler(*this).process(expr)).setRValue();
  3972. }
  3973. SpirvEvalInfo SPIRVEmitter::doMemberExpr(const MemberExpr *expr) {
  3974. llvm::SmallVector<uint32_t, 4> indices;
  3975. const Expr *base = collectArrayStructIndices(expr, &indices);
  3976. auto info = loadIfAliasVarRef(base);
  3977. if (!indices.empty()) {
  3978. // Sometime we are accessing the member of a rvalue, e.g.,
  3979. // <some-function-returing-a-struct>().<some-field>
  3980. // Create a temporary variable to hold the rvalue so that we can use access
  3981. // chain to index into it.
  3982. if (info.isRValue()) {
  3983. SpirvEvalInfo tempVar = createTemporaryVar(
  3984. base->getType(), TypeTranslator::getName(base->getType()), info);
  3985. (void)turnIntoElementPtr(tempVar, expr->getType(), indices);
  3986. info.setResultId(theBuilder.createLoad(
  3987. typeTranslator.translateType(expr->getType()), tempVar));
  3988. } else {
  3989. (void)turnIntoElementPtr(info, expr->getType(), indices);
  3990. }
  3991. }
  3992. return info;
  3993. }
  3994. uint32_t SPIRVEmitter::createTemporaryVar(QualType type, llvm::StringRef name,
  3995. const SpirvEvalInfo &init) {
  3996. // We are creating a temporary variable in the Function storage class here,
  3997. // which means it has void layout rule.
  3998. const uint32_t varType = typeTranslator.translateType(type);
  3999. const std::string varName = "temp.var." + name.str();
  4000. const uint32_t varId = theBuilder.addFnVar(varType, varName);
  4001. storeValue(varId, init, type);
  4002. return varId;
  4003. }
  4004. SpirvEvalInfo SPIRVEmitter::doUnaryOperator(const UnaryOperator *expr) {
  4005. const auto opcode = expr->getOpcode();
  4006. const auto *subExpr = expr->getSubExpr();
  4007. const auto subType = subExpr->getType();
  4008. auto subValue = doExpr(subExpr);
  4009. const auto subTypeId = typeTranslator.translateType(subType);
  4010. switch (opcode) {
  4011. case UO_PreInc:
  4012. case UO_PreDec:
  4013. case UO_PostInc:
  4014. case UO_PostDec: {
  4015. const bool isPre = opcode == UO_PreInc || opcode == UO_PreDec;
  4016. const bool isInc = opcode == UO_PreInc || opcode == UO_PostInc;
  4017. const spv::Op spvOp = translateOp(isInc ? BO_Add : BO_Sub, subType);
  4018. const uint32_t originValue = theBuilder.createLoad(subTypeId, subValue);
  4019. const uint32_t one = hlsl::IsHLSLMatType(subType)
  4020. ? getMatElemValueOne(subType)
  4021. : getValueOne(subType);
  4022. uint32_t incValue = 0;
  4023. if (TypeTranslator::isMxNMatrix(subType)) {
  4024. // For matrices, we can only increment/decrement each vector of it.
  4025. const auto actOnEachVec = [this, spvOp, one](uint32_t /*index*/,
  4026. uint32_t vecType,
  4027. uint32_t lhsVec) {
  4028. const auto valId =
  4029. theBuilder.createBinaryOp(spvOp, vecType, lhsVec, one);
  4030. return SpirvEvalInfo(valId).setRValue();
  4031. };
  4032. incValue = processEachVectorInMatrix(subExpr, originValue, actOnEachVec);
  4033. } else {
  4034. incValue = theBuilder.createBinaryOp(spvOp, subTypeId, originValue, one);
  4035. }
  4036. theBuilder.createStore(subValue, incValue);
  4037. // Prefix increment/decrement operator returns a lvalue, while postfix
  4038. // increment/decrement returns a rvalue.
  4039. return isPre ? subValue : subValue.setResultId(originValue).setRValue();
  4040. }
  4041. case UO_Not: {
  4042. return subValue
  4043. .setResultId(
  4044. theBuilder.createUnaryOp(spv::Op::OpNot, subTypeId, subValue))
  4045. .setRValue();
  4046. }
  4047. case UO_LNot: {
  4048. // Parsing will do the necessary casting to make sure we are applying the
  4049. // ! operator on boolean values.
  4050. return subValue
  4051. .setResultId(theBuilder.createUnaryOp(spv::Op::OpLogicalNot, subTypeId,
  4052. subValue))
  4053. .setRValue();
  4054. }
  4055. case UO_Plus:
  4056. // No need to do anything for the prefix + operator.
  4057. return subValue;
  4058. case UO_Minus: {
  4059. // SPIR-V have two opcodes for negating values: OpSNegate and OpFNegate.
  4060. const spv::Op spvOp = isFloatOrVecOfFloatType(subType) ? spv::Op::OpFNegate
  4061. : spv::Op::OpSNegate;
  4062. return subValue
  4063. .setResultId(theBuilder.createUnaryOp(spvOp, subTypeId, subValue))
  4064. .setRValue();
  4065. }
  4066. default:
  4067. break;
  4068. }
  4069. emitError("unary operator '%0' unimplemented", expr->getExprLoc())
  4070. << expr->getOpcodeStr(opcode);
  4071. expr->dump();
  4072. return 0;
  4073. }
  4074. spv::Op SPIRVEmitter::translateOp(BinaryOperator::Opcode op, QualType type) {
  4075. const bool isSintType = isSintOrVecMatOfSintType(type);
  4076. const bool isUintType = isUintOrVecMatOfUintType(type);
  4077. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  4078. #define BIN_OP_CASE_INT_FLOAT(kind, intBinOp, floatBinOp) \
  4079. \
  4080. case BO_##kind: { \
  4081. if (isSintType || isUintType) { \
  4082. return spv::Op::Op##intBinOp; \
  4083. } \
  4084. if (isFloatType) { \
  4085. return spv::Op::Op##floatBinOp; \
  4086. } \
  4087. } break
  4088. #define BIN_OP_CASE_SINT_UINT_FLOAT(kind, sintBinOp, uintBinOp, floatBinOp) \
  4089. \
  4090. case BO_##kind: { \
  4091. if (isSintType) { \
  4092. return spv::Op::Op##sintBinOp; \
  4093. } \
  4094. if (isUintType) { \
  4095. return spv::Op::Op##uintBinOp; \
  4096. } \
  4097. if (isFloatType) { \
  4098. return spv::Op::Op##floatBinOp; \
  4099. } \
  4100. } break
  4101. #define BIN_OP_CASE_SINT_UINT(kind, sintBinOp, uintBinOp) \
  4102. \
  4103. case BO_##kind: { \
  4104. if (isSintType) { \
  4105. return spv::Op::Op##sintBinOp; \
  4106. } \
  4107. if (isUintType) { \
  4108. return spv::Op::Op##uintBinOp; \
  4109. } \
  4110. } break
  4111. switch (op) {
  4112. case BO_EQ: {
  4113. if (isBoolOrVecMatOfBoolType(type))
  4114. return spv::Op::OpLogicalEqual;
  4115. if (isSintType || isUintType)
  4116. return spv::Op::OpIEqual;
  4117. if (isFloatType)
  4118. return spv::Op::OpFOrdEqual;
  4119. } break;
  4120. case BO_NE: {
  4121. if (isBoolOrVecMatOfBoolType(type))
  4122. return spv::Op::OpLogicalNotEqual;
  4123. if (isSintType || isUintType)
  4124. return spv::Op::OpINotEqual;
  4125. if (isFloatType)
  4126. return spv::Op::OpFOrdNotEqual;
  4127. } break;
  4128. // According to HLSL doc, all sides of the && and || expression are always
  4129. // evaluated.
  4130. case BO_LAnd:
  4131. return spv::Op::OpLogicalAnd;
  4132. case BO_LOr:
  4133. return spv::Op::OpLogicalOr;
  4134. BIN_OP_CASE_INT_FLOAT(Add, IAdd, FAdd);
  4135. BIN_OP_CASE_INT_FLOAT(AddAssign, IAdd, FAdd);
  4136. BIN_OP_CASE_INT_FLOAT(Sub, ISub, FSub);
  4137. BIN_OP_CASE_INT_FLOAT(SubAssign, ISub, FSub);
  4138. BIN_OP_CASE_INT_FLOAT(Mul, IMul, FMul);
  4139. BIN_OP_CASE_INT_FLOAT(MulAssign, IMul, FMul);
  4140. BIN_OP_CASE_SINT_UINT_FLOAT(Div, SDiv, UDiv, FDiv);
  4141. BIN_OP_CASE_SINT_UINT_FLOAT(DivAssign, SDiv, UDiv, FDiv);
  4142. // According to HLSL spec, "the modulus operator returns the remainder of
  4143. // a division." "The % operator is defined only in cases where either both
  4144. // sides are positive or both sides are negative."
  4145. //
  4146. // In SPIR-V, there are two reminder operations: Op*Rem and Op*Mod. With
  4147. // the former, the sign of a non-0 result comes from Operand 1, while
  4148. // with the latter, from Operand 2.
  4149. //
  4150. // For operands with different signs, technically we can map % to either
  4151. // Op*Rem or Op*Mod since it's undefined behavior. But it is more
  4152. // consistent with C (HLSL starts as a C derivative) and Clang frontend
  4153. // const expression evaluation if we map % to Op*Rem.
  4154. //
  4155. // Note there is no OpURem in SPIR-V.
  4156. BIN_OP_CASE_SINT_UINT_FLOAT(Rem, SRem, UMod, FRem);
  4157. BIN_OP_CASE_SINT_UINT_FLOAT(RemAssign, SRem, UMod, FRem);
  4158. BIN_OP_CASE_SINT_UINT_FLOAT(LT, SLessThan, ULessThan, FOrdLessThan);
  4159. BIN_OP_CASE_SINT_UINT_FLOAT(LE, SLessThanEqual, ULessThanEqual,
  4160. FOrdLessThanEqual);
  4161. BIN_OP_CASE_SINT_UINT_FLOAT(GT, SGreaterThan, UGreaterThan,
  4162. FOrdGreaterThan);
  4163. BIN_OP_CASE_SINT_UINT_FLOAT(GE, SGreaterThanEqual, UGreaterThanEqual,
  4164. FOrdGreaterThanEqual);
  4165. BIN_OP_CASE_SINT_UINT(And, BitwiseAnd, BitwiseAnd);
  4166. BIN_OP_CASE_SINT_UINT(AndAssign, BitwiseAnd, BitwiseAnd);
  4167. BIN_OP_CASE_SINT_UINT(Or, BitwiseOr, BitwiseOr);
  4168. BIN_OP_CASE_SINT_UINT(OrAssign, BitwiseOr, BitwiseOr);
  4169. BIN_OP_CASE_SINT_UINT(Xor, BitwiseXor, BitwiseXor);
  4170. BIN_OP_CASE_SINT_UINT(XorAssign, BitwiseXor, BitwiseXor);
  4171. BIN_OP_CASE_SINT_UINT(Shl, ShiftLeftLogical, ShiftLeftLogical);
  4172. BIN_OP_CASE_SINT_UINT(ShlAssign, ShiftLeftLogical, ShiftLeftLogical);
  4173. BIN_OP_CASE_SINT_UINT(Shr, ShiftRightArithmetic, ShiftRightLogical);
  4174. BIN_OP_CASE_SINT_UINT(ShrAssign, ShiftRightArithmetic, ShiftRightLogical);
  4175. default:
  4176. break;
  4177. }
  4178. #undef BIN_OP_CASE_INT_FLOAT
  4179. #undef BIN_OP_CASE_SINT_UINT_FLOAT
  4180. #undef BIN_OP_CASE_SINT_UINT
  4181. emitError("translating binary operator '%0' unimplemented", {})
  4182. << BinaryOperator::getOpcodeStr(op);
  4183. return spv::Op::OpNop;
  4184. }
  4185. SpirvEvalInfo SPIRVEmitter::processAssignment(const Expr *lhs,
  4186. const SpirvEvalInfo &rhs,
  4187. const bool isCompoundAssignment,
  4188. SpirvEvalInfo lhsPtr) {
  4189. // Assigning to vector swizzling should be handled differently.
  4190. if (SpirvEvalInfo result = tryToAssignToVectorElements(lhs, rhs))
  4191. return result;
  4192. // Assigning to matrix swizzling should be handled differently.
  4193. if (SpirvEvalInfo result = tryToAssignToMatrixElements(lhs, rhs))
  4194. return result;
  4195. // Assigning to a RWBuffer/RWTexture should be handled differently.
  4196. if (SpirvEvalInfo result = tryToAssignToRWBufferRWTexture(lhs, rhs))
  4197. return result;
  4198. // Normal assignment procedure
  4199. if (!lhsPtr)
  4200. lhsPtr = doExpr(lhs);
  4201. storeValue(lhsPtr, rhs, lhs->getType());
  4202. // Plain assignment returns a rvalue, while compound assignment returns
  4203. // lvalue.
  4204. return isCompoundAssignment ? lhsPtr : rhs;
  4205. }
  4206. void SPIRVEmitter::storeValue(const SpirvEvalInfo &lhsPtr,
  4207. const SpirvEvalInfo &rhsVal,
  4208. const QualType lhsValType) {
  4209. QualType matElemType = {};
  4210. const bool lhsIsMat = typeTranslator.isMxNMatrix(lhsValType, &matElemType);
  4211. const bool lhsIsFloatMat = lhsIsMat && matElemType->isFloatingType();
  4212. const bool lhsIsNonFpMat = lhsIsMat && !matElemType->isFloatingType();
  4213. if (typeTranslator.isScalarType(lhsValType) ||
  4214. typeTranslator.isVectorType(lhsValType) || lhsIsFloatMat) {
  4215. uint32_t rhsValId = rhsVal;
  4216. // Special-case: According to the SPIR-V Spec: There is no physical size
  4217. // or bit pattern defined for boolean type. Therefore an unsigned integer
  4218. // is used to represent booleans when layout is required. In such cases,
  4219. // we should cast the boolean to uint before creating OpStore.
  4220. if (isBoolOrVecOfBoolType(lhsValType) &&
  4221. lhsPtr.getLayoutRule() != LayoutRule::Void) {
  4222. uint32_t vecSize = 1;
  4223. const bool isVec =
  4224. TypeTranslator::isVectorType(lhsValType, nullptr, &vecSize);
  4225. const auto toType =
  4226. isVec ? astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize)
  4227. : astContext.UnsignedIntTy;
  4228. const auto fromType =
  4229. isVec ? astContext.getExtVectorType(astContext.BoolTy, vecSize)
  4230. : astContext.BoolTy;
  4231. rhsValId = castToInt(rhsValId, fromType, toType, {});
  4232. }
  4233. theBuilder.createStore(lhsPtr, rhsValId);
  4234. } else if (TypeTranslator::isOpaqueType(lhsValType)) {
  4235. // Resource types are represented using RecordType in the AST.
  4236. // Handle them before the general RecordType.
  4237. //
  4238. // HLSL allows to put resource types that translating into SPIR-V opaque
  4239. // types in structs, or assign to variables of resource types. These can all
  4240. // result in illegal SPIR-V for Vulkan. We just translate here literally and
  4241. // let SPIRV-Tools opt to do the legalization work.
  4242. //
  4243. // Note: legalization specific code
  4244. theBuilder.createStore(lhsPtr, rhsVal);
  4245. needsLegalization = true;
  4246. } else if (TypeTranslator::isAKindOfStructuredOrByteBuffer(lhsValType)) {
  4247. // The rhs should be a pointer and the lhs should be a pointer-to-pointer.
  4248. // Directly store the pointer here and let SPIRV-Tools opt to do the clean
  4249. // up.
  4250. //
  4251. // Note: legalization specific code
  4252. theBuilder.createStore(lhsPtr, rhsVal);
  4253. needsLegalization = true;
  4254. // For ConstantBuffers/TextureBuffers, we decompose and assign each field
  4255. // recursively like normal structs using the following logic.
  4256. //
  4257. // The frontend forbids declaring ConstantBuffer<T> or TextureBuffer<T>
  4258. // variables as function parameters/returns/variables, but happily accepts
  4259. // assignments/returns from ConstantBuffer<T>/TextureBuffer<T> to function
  4260. // parameters/returns/variables of type T. And ConstantBuffer<T> is not
  4261. // represented differently as struct T.
  4262. } else if (TypeTranslator::isOpaqueArrayType(lhsValType)) {
  4263. // For opaque array types, we cannot perform OpLoad on the whole array and
  4264. // then write out as a whole; instead, we need to OpLoad each element
  4265. // using access chains. This is to influence later SPIR-V transformations
  4266. // to use access chains to access each opaque object; if we do array
  4267. // wholesale handling here, they will be in the final transformed code.
  4268. // Drivers don't like that.
  4269. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  4270. assert(lhsValType->isConstantArrayType());
  4271. assert(!rhsVal.isRValue());
  4272. const auto *arrayType = astContext.getAsConstantArrayType(lhsValType);
  4273. const auto elemType = arrayType->getElementType();
  4274. const auto arraySize =
  4275. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4276. // Do separate load of each element via access chain
  4277. llvm::SmallVector<uint32_t, 8> elements;
  4278. for (uint32_t i = 0; i < arraySize; ++i) {
  4279. const auto subRhsValType =
  4280. typeTranslator.translateType(elemType, rhsVal.getLayoutRule());
  4281. const auto subRhsPtrType =
  4282. theBuilder.getPointerType(subRhsValType, rhsVal.getStorageClass());
  4283. const auto subRhsPtr = theBuilder.createAccessChain(
  4284. subRhsPtrType, rhsVal, {theBuilder.getConstantInt32(i)});
  4285. elements.push_back(theBuilder.createLoad(subRhsValType, subRhsPtr));
  4286. }
  4287. // Create a new composite and write out once
  4288. const auto lhsValTypeId =
  4289. typeTranslator.translateType(lhsValType, lhsPtr.getLayoutRule());
  4290. theBuilder.createStore(
  4291. lhsPtr, theBuilder.createCompositeConstruct(lhsValTypeId, elements));
  4292. } else if (lhsPtr.getLayoutRule() == rhsVal.getLayoutRule()) {
  4293. // If lhs and rhs has the same memory layout, we should be safe to load
  4294. // from rhs and directly store into lhs and avoid decomposing rhs.
  4295. // Note: this check should happen after those setting needsLegalization.
  4296. // TODO: is this optimization always correct?
  4297. theBuilder.createStore(lhsPtr, rhsVal);
  4298. } else if (lhsValType->isRecordType() || lhsValType->isConstantArrayType() ||
  4299. lhsIsNonFpMat) {
  4300. theBuilder.createStore(
  4301. lhsPtr, reconstructValue(rhsVal, lhsValType, lhsPtr.getLayoutRule()));
  4302. } else {
  4303. emitError("storing value of type %0 unimplemented", {}) << lhsValType;
  4304. }
  4305. }
  4306. uint32_t SPIRVEmitter::reconstructValue(const SpirvEvalInfo &srcVal,
  4307. const QualType valType,
  4308. LayoutRule dstLR) {
  4309. // Lambda for casting scalar or vector of bool<-->uint in cases where one side
  4310. // of the reconstruction (lhs or rhs) has a layout rule.
  4311. const auto handleBooleanLayout = [this, &srcVal, dstLR](uint32_t val,
  4312. QualType valType) {
  4313. // We only need to cast if we have a scalar or vector of booleans.
  4314. if (!isBoolOrVecOfBoolType(valType))
  4315. return val;
  4316. LayoutRule srcLR = srcVal.getLayoutRule();
  4317. // Source value has a layout rule, and has therefore been represented
  4318. // as a uint. Cast it to boolean before using.
  4319. bool shouldCastToBool =
  4320. srcLR != LayoutRule::Void && dstLR == LayoutRule::Void;
  4321. // Destination has a layout rule, and should therefore be represented
  4322. // as a uint. Cast to uint before using.
  4323. bool shouldCastToUint =
  4324. srcLR == LayoutRule::Void && dstLR != LayoutRule::Void;
  4325. // No boolean layout issues to take care of.
  4326. if (!shouldCastToBool && !shouldCastToUint)
  4327. return val;
  4328. uint32_t vecSize = 1;
  4329. TypeTranslator::isVectorType(valType, nullptr, &vecSize);
  4330. QualType boolType =
  4331. vecSize == 1 ? astContext.BoolTy
  4332. : astContext.getExtVectorType(astContext.BoolTy, vecSize);
  4333. QualType uintType =
  4334. vecSize == 1
  4335. ? astContext.UnsignedIntTy
  4336. : astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize);
  4337. if (shouldCastToBool)
  4338. return castToBool(val, uintType, boolType);
  4339. if (shouldCastToUint)
  4340. return castToInt(val, boolType, uintType, {});
  4341. return val;
  4342. };
  4343. // Lambda for cases where we want to reconstruct an array
  4344. const auto reconstructArray = [this, &srcVal, valType,
  4345. dstLR](uint32_t arraySize,
  4346. QualType arrayElemType) {
  4347. llvm::SmallVector<uint32_t, 4> elements;
  4348. for (uint32_t i = 0; i < arraySize; ++i) {
  4349. const auto subSrcValType =
  4350. typeTranslator.translateType(arrayElemType, srcVal.getLayoutRule());
  4351. const auto subSrcVal =
  4352. theBuilder.createCompositeExtract(subSrcValType, srcVal, {i});
  4353. elements.push_back(reconstructValue(srcVal.substResultId(subSrcVal),
  4354. arrayElemType, dstLR));
  4355. }
  4356. const auto dstValType = typeTranslator.translateType(valType, dstLR);
  4357. return theBuilder.createCompositeConstruct(dstValType, elements);
  4358. };
  4359. // Constant arrays
  4360. if (const auto *arrayType = astContext.getAsConstantArrayType(valType)) {
  4361. const auto elemType = arrayType->getElementType();
  4362. const auto size =
  4363. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4364. return reconstructArray(size, elemType);
  4365. }
  4366. // Non-floating-point matrices
  4367. QualType matElemType = {};
  4368. uint32_t numRows = 0, numCols = 0;
  4369. const bool isNonFpMat =
  4370. typeTranslator.isMxNMatrix(valType, &matElemType, &numRows, &numCols) &&
  4371. !matElemType->isFloatingType();
  4372. if (isNonFpMat) {
  4373. // Note: This check should happen before the RecordType check.
  4374. // Non-fp matrices are represented as arrays of vectors in SPIR-V.
  4375. // Each array element is a vector. Get the QualType for the vector.
  4376. const auto elemType = astContext.getExtVectorType(matElemType, numCols);
  4377. return reconstructArray(numRows, elemType);
  4378. }
  4379. // Note: This check should happen before the RecordType check since
  4380. // vector/matrix/resource types are represented as RecordType in the AST.
  4381. if (hlsl::IsHLSLVecMatType(valType) || hlsl::IsHLSLResourceType(valType))
  4382. return handleBooleanLayout(srcVal, valType);
  4383. // Structs
  4384. if (const auto *recordType = valType->getAs<RecordType>()) {
  4385. uint32_t index = 0;
  4386. llvm::SmallVector<uint32_t, 4> elements;
  4387. for (const auto *field : recordType->getDecl()->fields()) {
  4388. const auto subSrcValType = typeTranslator.translateType(
  4389. field->getType(), srcVal.getLayoutRule());
  4390. const auto subSrcVal =
  4391. theBuilder.createCompositeExtract(subSrcValType, srcVal, {index});
  4392. elements.push_back(reconstructValue(srcVal.substResultId(subSrcVal),
  4393. field->getType(), dstLR));
  4394. ++index;
  4395. }
  4396. const auto dstValType = typeTranslator.translateType(valType, dstLR);
  4397. return theBuilder.createCompositeConstruct(dstValType, elements);
  4398. }
  4399. return handleBooleanLayout(srcVal, valType);
  4400. }
  4401. SpirvEvalInfo SPIRVEmitter::processBinaryOp(const Expr *lhs, const Expr *rhs,
  4402. const BinaryOperatorKind opcode,
  4403. const QualType computationType,
  4404. const QualType resultType,
  4405. SourceRange sourceRange,
  4406. SpirvEvalInfo *lhsInfo,
  4407. const spv::Op mandateGenOpcode) {
  4408. const QualType lhsType = lhs->getType();
  4409. const QualType rhsType = rhs->getType();
  4410. // Binary logical operations (such as ==, !=, etc) that return a boolean type
  4411. // may get a literal (e.g. 0, 1, etc.) as lhs or rhs args. Since only
  4412. // non-zero-ness of these literals matter, they can be translated as 32-bits.
  4413. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  4414. if (resultType->isBooleanType()) {
  4415. if (lhsType->isSpecificBuiltinType(BuiltinType::LitInt) ||
  4416. rhsType->isSpecificBuiltinType(BuiltinType::LitInt))
  4417. hint.setHint(astContext.IntTy);
  4418. if (lhsType->isSpecificBuiltinType(BuiltinType::LitFloat) ||
  4419. rhsType->isSpecificBuiltinType(BuiltinType::LitFloat))
  4420. hint.setHint(astContext.FloatTy);
  4421. }
  4422. // If the operands are of matrix type, we need to dispatch the operation
  4423. // onto each element vector iff the operands are not degenerated matrices
  4424. // and we don't have a matrix specific SPIR-V instruction for the operation.
  4425. if (!isSpirvMatrixOp(mandateGenOpcode) &&
  4426. TypeTranslator::isMxNMatrix(lhsType)) {
  4427. return processMatrixBinaryOp(lhs, rhs, opcode, sourceRange);
  4428. }
  4429. // Comma operator works differently from other binary operations as there is
  4430. // no SPIR-V instruction for it. For each comma, we must evaluate lhs and rhs
  4431. // respectively, and return the results of rhs.
  4432. if (opcode == BO_Comma) {
  4433. (void)doExpr(lhs);
  4434. return doExpr(rhs);
  4435. }
  4436. SpirvEvalInfo rhsVal = 0, lhsPtr = 0, lhsVal = 0;
  4437. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4438. // Evalute rhs before lhs
  4439. rhsVal = loadIfGLValue(rhs);
  4440. lhsVal = lhsPtr = doExpr(lhs);
  4441. // This is a compound assignment. We need to load the lhs value if lhs
  4442. // is not already rvalue and does not generate a vector shuffle.
  4443. if (!lhsPtr.isRValue() && !isVectorShuffle(lhs)) {
  4444. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4445. }
  4446. // For a compound assignments, the AST does not have the proper implicit
  4447. // cast if lhs and rhs have different types. So we need to manually cast lhs
  4448. // to the computation type.
  4449. if (computationType != lhsType)
  4450. lhsVal.setResultId(
  4451. castToType(lhsVal, lhsType, computationType, lhs->getExprLoc()));
  4452. } else {
  4453. // Evalute lhs before rhs
  4454. lhsPtr = doExpr(lhs);
  4455. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4456. rhsVal = loadIfGLValue(rhs);
  4457. }
  4458. if (lhsInfo)
  4459. *lhsInfo = lhsPtr;
  4460. const spv::Op spvOp = (mandateGenOpcode == spv::Op::Max)
  4461. ? translateOp(opcode, computationType)
  4462. : mandateGenOpcode;
  4463. switch (opcode) {
  4464. case BO_Shl:
  4465. case BO_Shr:
  4466. case BO_ShlAssign:
  4467. case BO_ShrAssign:
  4468. // We need to cull the RHS to make sure that we are not shifting by an
  4469. // amount that is larger than the bitwidth of the LHS.
  4470. rhsVal.setResultId(theBuilder.createBinaryOp(
  4471. spv::Op::OpBitwiseAnd, typeTranslator.translateType(computationType),
  4472. rhsVal, getMaskForBitwidthValue(rhsType)));
  4473. // Fall through
  4474. case BO_Add:
  4475. case BO_Sub:
  4476. case BO_Mul:
  4477. case BO_Div:
  4478. case BO_Rem:
  4479. case BO_LT:
  4480. case BO_LE:
  4481. case BO_GT:
  4482. case BO_GE:
  4483. case BO_EQ:
  4484. case BO_NE:
  4485. case BO_And:
  4486. case BO_Or:
  4487. case BO_Xor:
  4488. case BO_LAnd:
  4489. case BO_LOr:
  4490. case BO_AddAssign:
  4491. case BO_SubAssign:
  4492. case BO_MulAssign:
  4493. case BO_DivAssign:
  4494. case BO_RemAssign:
  4495. case BO_AndAssign:
  4496. case BO_OrAssign:
  4497. case BO_XorAssign: {
  4498. // To evaluate this expression as an OpSpecConstantOp, we need to make sure
  4499. // both operands are constant and at least one of them is a spec constant.
  4500. if (lhsVal.isConstant() && rhsVal.isConstant() &&
  4501. (lhsVal.isSpecConstant() || rhsVal.isSpecConstant()) &&
  4502. isAcceptedSpecConstantBinaryOp(spvOp)) {
  4503. const auto valId = theBuilder.createSpecConstantBinaryOp(
  4504. spvOp, typeTranslator.translateType(resultType), lhsVal, rhsVal);
  4505. return SpirvEvalInfo(valId).setRValue().setSpecConstant();
  4506. }
  4507. // Normal binary operation
  4508. uint32_t valId = 0;
  4509. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4510. valId = theBuilder.createBinaryOp(
  4511. spvOp, typeTranslator.translateType(computationType), lhsVal, rhsVal);
  4512. // For a compound assignments, the AST does not have the proper implicit
  4513. // cast if lhs and rhs have different types. So we need to manually cast
  4514. // the result back to lhs' type.
  4515. if (computationType != lhsType)
  4516. valId = castToType(valId, computationType, lhsType, lhs->getExprLoc());
  4517. } else {
  4518. valId = theBuilder.createBinaryOp(
  4519. spvOp, typeTranslator.translateType(resultType), lhsVal, rhsVal);
  4520. }
  4521. auto result = SpirvEvalInfo(valId).setRValue();
  4522. // Propagate RelaxedPrecision
  4523. if (lhsVal.isRelaxedPrecision() || rhsVal.isRelaxedPrecision())
  4524. result.setRelaxedPrecision();
  4525. // Propagate NonUniformEXT
  4526. if (lhsVal.isNonUniform() || rhsVal.isNonUniform())
  4527. result.setNonUniform();
  4528. return result;
  4529. }
  4530. case BO_Assign:
  4531. llvm_unreachable("assignment should not be handled here");
  4532. }
  4533. emitError("binary operator '%0' unimplemented", lhs->getExprLoc())
  4534. << BinaryOperator::getOpcodeStr(opcode) << sourceRange;
  4535. return 0;
  4536. }
  4537. void SPIRVEmitter::initOnce(QualType varType, std::string varName,
  4538. uint32_t varPtr, const Expr *varInit) {
  4539. // For uninitialized resource objects, we do nothing since there is no
  4540. // meaningful zero values for them.
  4541. if (!varInit && hlsl::IsHLSLResourceType(varType))
  4542. return;
  4543. const uint32_t boolType = theBuilder.getBoolType();
  4544. varName = "init.done." + varName;
  4545. // Create a file/module visible variable to hold the initialization state.
  4546. const uint32_t initDoneVar =
  4547. theBuilder.addModuleVar(boolType, spv::StorageClass::Private, varName,
  4548. theBuilder.getConstantBool(false));
  4549. const uint32_t condition = theBuilder.createLoad(boolType, initDoneVar);
  4550. const uint32_t todoBB = theBuilder.createBasicBlock("if.init.todo");
  4551. const uint32_t doneBB = theBuilder.createBasicBlock("if.init.done");
  4552. // If initDoneVar contains true, we jump to the "done" basic block; otherwise,
  4553. // jump to the "todo" basic block.
  4554. theBuilder.createConditionalBranch(condition, doneBB, todoBB, doneBB);
  4555. theBuilder.addSuccessor(todoBB);
  4556. theBuilder.addSuccessor(doneBB);
  4557. theBuilder.setMergeTarget(doneBB);
  4558. theBuilder.setInsertPoint(todoBB);
  4559. // Do initialization and mark done
  4560. if (varInit) {
  4561. storeValue(
  4562. // Static function variable are of private storage class
  4563. SpirvEvalInfo(varPtr).setStorageClass(spv::StorageClass::Private),
  4564. doExpr(varInit), varInit->getType());
  4565. } else {
  4566. const auto typeId = typeTranslator.translateType(varType);
  4567. theBuilder.createStore(varPtr, theBuilder.getConstantNull(typeId));
  4568. }
  4569. theBuilder.createStore(initDoneVar, theBuilder.getConstantBool(true));
  4570. theBuilder.createBranch(doneBB);
  4571. theBuilder.addSuccessor(doneBB);
  4572. theBuilder.setInsertPoint(doneBB);
  4573. }
  4574. bool SPIRVEmitter::isVectorShuffle(const Expr *expr) {
  4575. // TODO: the following check is essentially duplicated from
  4576. // doHLSLVectorElementExpr. Should unify them.
  4577. if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  4578. const Expr *base = nullptr;
  4579. hlsl::VectorMemberAccessPositions accessor;
  4580. condenseVectorElementExpr(vecElemExpr, &base, &accessor);
  4581. const auto accessorSize = accessor.Count;
  4582. if (accessorSize == 1) {
  4583. // Selecting only one element. OpAccessChain or OpCompositeExtract for
  4584. // such cases.
  4585. return false;
  4586. }
  4587. const auto baseSize = hlsl::GetHLSLVecSize(base->getType());
  4588. if (accessorSize != baseSize)
  4589. return true;
  4590. for (uint32_t i = 0; i < accessorSize; ++i) {
  4591. uint32_t position;
  4592. accessor.GetPosition(i, &position);
  4593. if (position != i)
  4594. return true;
  4595. }
  4596. // Selecting exactly the original vector. No vector shuffle generated.
  4597. return false;
  4598. }
  4599. return false;
  4600. }
  4601. bool SPIRVEmitter::isTextureMipsSampleIndexing(const CXXOperatorCallExpr *expr,
  4602. const Expr **base,
  4603. const Expr **location,
  4604. const Expr **lod) {
  4605. if (!expr)
  4606. return false;
  4607. // <object>.mips[][] consists of an outer operator[] and an inner operator[]
  4608. const CXXOperatorCallExpr *outerExpr = expr;
  4609. if (outerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4610. return false;
  4611. const Expr *arg0 = outerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4612. const CXXOperatorCallExpr *innerExpr = dyn_cast<CXXOperatorCallExpr>(arg0);
  4613. // Must have an inner operator[]
  4614. if (!innerExpr ||
  4615. innerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript) {
  4616. return false;
  4617. }
  4618. const Expr *innerArg0 =
  4619. innerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4620. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(innerArg0);
  4621. if (!memberExpr)
  4622. return false;
  4623. // Must be accessing the member named "mips" or "sample"
  4624. const auto &memberName =
  4625. memberExpr->getMemberNameInfo().getName().getAsString();
  4626. if (memberName != "mips" && memberName != "sample")
  4627. return false;
  4628. const Expr *object = memberExpr->getBase();
  4629. const auto objectType = object->getType();
  4630. if (!TypeTranslator::isTexture(objectType))
  4631. return false;
  4632. if (base)
  4633. *base = object;
  4634. if (lod)
  4635. *lod = innerExpr->getArg(1);
  4636. if (location)
  4637. *location = outerExpr->getArg(1);
  4638. return true;
  4639. }
  4640. bool SPIRVEmitter::isBufferTextureIndexing(const CXXOperatorCallExpr *indexExpr,
  4641. const Expr **base,
  4642. const Expr **index) {
  4643. if (!indexExpr)
  4644. return false;
  4645. // Must be operator[]
  4646. if (indexExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4647. return false;
  4648. const Expr *object = indexExpr->getArg(0);
  4649. const auto objectType = object->getType();
  4650. if (TypeTranslator::isBuffer(objectType) ||
  4651. TypeTranslator::isRWBuffer(objectType) ||
  4652. TypeTranslator::isTexture(objectType) ||
  4653. TypeTranslator::isRWTexture(objectType)) {
  4654. if (base)
  4655. *base = object;
  4656. if (index)
  4657. *index = indexExpr->getArg(1);
  4658. return true;
  4659. }
  4660. return false;
  4661. }
  4662. void SPIRVEmitter::condenseVectorElementExpr(
  4663. const HLSLVectorElementExpr *expr, const Expr **basePtr,
  4664. hlsl::VectorMemberAccessPositions *flattenedAccessor) {
  4665. llvm::SmallVector<hlsl::VectorMemberAccessPositions, 2> accessors;
  4666. accessors.push_back(expr->getEncodedElementAccess());
  4667. // Recursively descending until we find the true base vector. In the
  4668. // meanwhile, collecting accessors in the reverse order.
  4669. *basePtr = expr->getBase();
  4670. while (const auto *vecElemBase = dyn_cast<HLSLVectorElementExpr>(*basePtr)) {
  4671. accessors.push_back(vecElemBase->getEncodedElementAccess());
  4672. *basePtr = vecElemBase->getBase();
  4673. }
  4674. *flattenedAccessor = accessors.back();
  4675. for (int32_t i = accessors.size() - 2; i >= 0; --i) {
  4676. const auto &currentAccessor = accessors[i];
  4677. // Apply the current level of accessor to the flattened accessor of all
  4678. // previous levels of ones.
  4679. hlsl::VectorMemberAccessPositions combinedAccessor;
  4680. for (uint32_t j = 0; j < currentAccessor.Count; ++j) {
  4681. uint32_t currentPosition = 0;
  4682. currentAccessor.GetPosition(j, &currentPosition);
  4683. uint32_t previousPosition = 0;
  4684. flattenedAccessor->GetPosition(currentPosition, &previousPosition);
  4685. combinedAccessor.SetPosition(j, previousPosition);
  4686. }
  4687. combinedAccessor.Count = currentAccessor.Count;
  4688. combinedAccessor.IsValid =
  4689. flattenedAccessor->IsValid && currentAccessor.IsValid;
  4690. *flattenedAccessor = combinedAccessor;
  4691. }
  4692. }
  4693. SpirvEvalInfo SPIRVEmitter::createVectorSplat(const Expr *scalarExpr,
  4694. uint32_t size) {
  4695. bool isConstVal = false;
  4696. SpirvEvalInfo scalarVal = 0;
  4697. // Try to evaluate the element as constant first. If successful, then we
  4698. // can generate constant instructions for this vector splat.
  4699. if (scalarVal = tryToEvaluateAsConst(scalarExpr)) {
  4700. isConstVal = true;
  4701. } else {
  4702. scalarVal = doExpr(scalarExpr);
  4703. }
  4704. if (size == 1) {
  4705. // Just return the scalar value for vector splat with size 1.
  4706. // Note that can be used as an lvalue, so we need to carry over
  4707. // the lvalueness for non-constant cases.
  4708. return isConstVal ? scalarVal.setConstant().setRValue() : scalarVal;
  4709. }
  4710. const uint32_t vecType = theBuilder.getVecType(
  4711. typeTranslator.translateType(scalarExpr->getType()), size);
  4712. llvm::SmallVector<uint32_t, 4> elements(size_t(size), scalarVal);
  4713. // TODO: we are saying the constant has Function storage class here.
  4714. // Should find a more meaningful one.
  4715. if (isConstVal) {
  4716. const auto valueId = theBuilder.getConstantComposite(vecType, elements);
  4717. return SpirvEvalInfo(valueId).setConstant().setRValue();
  4718. } else {
  4719. const auto valueId = theBuilder.createCompositeConstruct(vecType, elements);
  4720. return SpirvEvalInfo(valueId).setRValue();
  4721. }
  4722. }
  4723. void SPIRVEmitter::splitVecLastElement(QualType vecType, uint32_t vec,
  4724. uint32_t *residual,
  4725. uint32_t *lastElement) {
  4726. assert(hlsl::IsHLSLVecType(vecType));
  4727. const uint32_t count = hlsl::GetHLSLVecSize(vecType);
  4728. assert(count > 1);
  4729. const uint32_t elemTypeId =
  4730. typeTranslator.translateType(hlsl::GetHLSLVecElementType(vecType));
  4731. if (count == 2) {
  4732. *residual = theBuilder.createCompositeExtract(elemTypeId, vec, 0);
  4733. } else {
  4734. llvm::SmallVector<uint32_t, 4> indices;
  4735. for (uint32_t i = 0; i < count - 1; ++i)
  4736. indices.push_back(i);
  4737. const uint32_t typeId = theBuilder.getVecType(elemTypeId, count - 1);
  4738. *residual = theBuilder.createVectorShuffle(typeId, vec, vec, indices);
  4739. }
  4740. *lastElement =
  4741. theBuilder.createCompositeExtract(elemTypeId, vec, {count - 1});
  4742. }
  4743. SpirvEvalInfo
  4744. SPIRVEmitter::tryToGenFloatVectorScale(const BinaryOperator *expr) {
  4745. const QualType type = expr->getType();
  4746. const SourceRange range = expr->getSourceRange();
  4747. // We can only translate floatN * float into OpVectorTimesScalar.
  4748. // So the result type must be floatN.
  4749. if (!hlsl::IsHLSLVecType(type) ||
  4750. !hlsl::GetHLSLVecElementType(type)->isFloatingType())
  4751. return 0;
  4752. const Expr *lhs = expr->getLHS();
  4753. const Expr *rhs = expr->getRHS();
  4754. // Multiplying a float vector with a float scalar will be represented in
  4755. // AST via a binary operation with two float vectors as operands; one of
  4756. // the operand is from an implicit cast with kind CK_HLSLVectorSplat.
  4757. // vector * scalar
  4758. if (hlsl::IsHLSLVecType(lhs->getType())) {
  4759. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  4760. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  4761. const QualType vecType = expr->getType();
  4762. if (isa<CompoundAssignOperator>(expr)) {
  4763. SpirvEvalInfo lhsPtr = 0;
  4764. const auto result = processBinaryOp(
  4765. lhs, cast->getSubExpr(), expr->getOpcode(), vecType, vecType,
  4766. range, &lhsPtr, spv::Op::OpVectorTimesScalar);
  4767. return processAssignment(lhs, result, true, lhsPtr);
  4768. } else {
  4769. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4770. vecType, vecType, range, nullptr,
  4771. spv::Op::OpVectorTimesScalar);
  4772. }
  4773. }
  4774. }
  4775. }
  4776. // scalar * vector
  4777. if (hlsl::IsHLSLVecType(rhs->getType())) {
  4778. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  4779. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  4780. const QualType vecType = expr->getType();
  4781. // We need to switch the positions of lhs and rhs here because
  4782. // OpVectorTimesScalar requires the first operand to be a vector and
  4783. // the second to be a scalar.
  4784. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  4785. vecType, vecType, range, nullptr,
  4786. spv::Op::OpVectorTimesScalar);
  4787. }
  4788. }
  4789. }
  4790. return 0;
  4791. }
  4792. SpirvEvalInfo
  4793. SPIRVEmitter::tryToGenFloatMatrixScale(const BinaryOperator *expr) {
  4794. const QualType type = expr->getType();
  4795. const SourceRange range = expr->getSourceRange();
  4796. // We can only translate floatMxN * float into OpMatrixTimesScalar.
  4797. // So the result type must be floatMxN.
  4798. if (!hlsl::IsHLSLMatType(type) ||
  4799. !hlsl::GetHLSLMatElementType(type)->isFloatingType())
  4800. return 0;
  4801. const Expr *lhs = expr->getLHS();
  4802. const Expr *rhs = expr->getRHS();
  4803. const QualType lhsType = lhs->getType();
  4804. const QualType rhsType = rhs->getType();
  4805. const auto selectOpcode = [](const QualType ty) {
  4806. return TypeTranslator::isMx1Matrix(ty) || TypeTranslator::is1xNMatrix(ty)
  4807. ? spv::Op::OpVectorTimesScalar
  4808. : spv::Op::OpMatrixTimesScalar;
  4809. };
  4810. // Multiplying a float matrix with a float scalar will be represented in
  4811. // AST via a binary operation with two float matrices as operands; one of
  4812. // the operand is from an implicit cast with kind CK_HLSLMatrixSplat.
  4813. // matrix * scalar
  4814. if (hlsl::IsHLSLMatType(lhsType)) {
  4815. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  4816. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  4817. const QualType matType = expr->getType();
  4818. const spv::Op opcode = selectOpcode(lhsType);
  4819. if (isa<CompoundAssignOperator>(expr)) {
  4820. SpirvEvalInfo lhsPtr = 0;
  4821. const auto result =
  4822. processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4823. matType, matType, range, &lhsPtr, opcode);
  4824. return processAssignment(lhs, result, true, lhsPtr);
  4825. } else {
  4826. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4827. matType, matType, range, nullptr, opcode);
  4828. }
  4829. }
  4830. }
  4831. }
  4832. // scalar * matrix
  4833. if (hlsl::IsHLSLMatType(rhsType)) {
  4834. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  4835. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  4836. const QualType matType = expr->getType();
  4837. const spv::Op opcode = selectOpcode(rhsType);
  4838. // We need to switch the positions of lhs and rhs here because
  4839. // OpMatrixTimesScalar requires the first operand to be a matrix and
  4840. // the second to be a scalar.
  4841. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  4842. matType, matType, range, nullptr, opcode);
  4843. }
  4844. }
  4845. }
  4846. return 0;
  4847. }
  4848. SpirvEvalInfo
  4849. SPIRVEmitter::tryToAssignToVectorElements(const Expr *lhs,
  4850. const SpirvEvalInfo &rhs) {
  4851. // Assigning to a vector swizzling lhs is tricky if we are neither
  4852. // writing to one element nor all elements in their original order.
  4853. // Under such cases, we need to create a new vector swizzling involving
  4854. // both the lhs and rhs vectors and then write the result of this swizzling
  4855. // into the base vector of lhs.
  4856. // For example, for vec4.yz = vec2, we nee to do the following:
  4857. //
  4858. // %vec4Val = OpLoad %v4float %vec4
  4859. // %vec2Val = OpLoad %v2float %vec2
  4860. // %shuffle = OpVectorShuffle %v4float %vec4Val %vec2Val 0 4 5 3
  4861. // OpStore %vec4 %shuffle
  4862. //
  4863. // When doing the vector shuffle, we use the lhs base vector as the first
  4864. // vector and the rhs vector as the second vector. Therefore, all elements
  4865. // in the second vector will be selected into the shuffle result.
  4866. const auto *lhsExpr = dyn_cast<HLSLVectorElementExpr>(lhs);
  4867. if (!lhsExpr)
  4868. return 0;
  4869. // Special case for <scalar-value>.x, which will have an AST of
  4870. // HLSLVectorElementExpr whose base is an ImplicitCastExpr
  4871. // (CK_HLSLVectorSplat). We just need to assign to <scalar-value>
  4872. // for such case.
  4873. if (const auto *baseCast = dyn_cast<CastExpr>(lhsExpr->getBase()))
  4874. if (baseCast->getCastKind() == CastKind::CK_HLSLVectorSplat &&
  4875. hlsl::GetHLSLVecSize(baseCast->getType()) == 1)
  4876. return processAssignment(baseCast->getSubExpr(), rhs, false);
  4877. const Expr *base = nullptr;
  4878. hlsl::VectorMemberAccessPositions accessor;
  4879. condenseVectorElementExpr(lhsExpr, &base, &accessor);
  4880. const QualType baseType = base->getType();
  4881. assert(hlsl::IsHLSLVecType(baseType));
  4882. const uint32_t baseTypeId = typeTranslator.translateType(baseType);
  4883. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  4884. const auto accessorSize = accessor.Count;
  4885. // Whether selecting the whole original vector
  4886. bool isSelectOrigin = accessorSize == baseSize;
  4887. // Assigning to one component
  4888. if (accessorSize == 1) {
  4889. if (isBufferTextureIndexing(dyn_cast_or_null<CXXOperatorCallExpr>(base))) {
  4890. // Assigning to one component of a RWBuffer/RWTexture element
  4891. // We need to use OpImageWrite here.
  4892. // Compose the new vector value first
  4893. const uint32_t oldVec = doExpr(base);
  4894. const uint32_t newVec = theBuilder.createCompositeInsert(
  4895. baseTypeId, oldVec, {accessor.Swz0}, rhs);
  4896. const auto result = tryToAssignToRWBufferRWTexture(base, newVec);
  4897. assert(result); // Definitely RWBuffer/RWTexture assignment
  4898. return rhs; // TODO: incorrect for compound assignments
  4899. } else {
  4900. // Assigning to one normal vector component. Nothing special, just fall
  4901. // back to the normal CodeGen path.
  4902. return 0;
  4903. }
  4904. }
  4905. if (isSelectOrigin) {
  4906. for (uint32_t i = 0; i < accessorSize; ++i) {
  4907. uint32_t position;
  4908. accessor.GetPosition(i, &position);
  4909. if (position != i)
  4910. isSelectOrigin = false;
  4911. }
  4912. }
  4913. // Assigning to the original vector
  4914. if (isSelectOrigin) {
  4915. // Ignore this HLSLVectorElementExpr and dispatch to base
  4916. return processAssignment(base, rhs, false);
  4917. }
  4918. llvm::SmallVector<uint32_t, 4> selectors;
  4919. selectors.resize(baseSize);
  4920. // Assume we are selecting all original elements first.
  4921. for (uint32_t i = 0; i < baseSize; ++i) {
  4922. selectors[i] = i;
  4923. }
  4924. // Now fix up the elements that actually got overwritten by the rhs vector.
  4925. // Since we are using the rhs vector as the second vector, their index
  4926. // should be offset'ed by the size of the lhs base vector.
  4927. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4928. uint32_t position;
  4929. accessor.GetPosition(i, &position);
  4930. selectors[position] = baseSize + i;
  4931. }
  4932. const auto vec1 = doExpr(base);
  4933. const uint32_t vec1Val =
  4934. vec1.isRValue() ? vec1 : theBuilder.createLoad(baseTypeId, vec1);
  4935. const uint32_t shuffle =
  4936. theBuilder.createVectorShuffle(baseTypeId, vec1Val, rhs, selectors);
  4937. if (!tryToAssignToRWBufferRWTexture(base, shuffle))
  4938. theBuilder.createStore(vec1, shuffle);
  4939. // TODO: OK, this return value is incorrect for compound assignments, for
  4940. // which cases we should return lvalues. Should at least emit errors if
  4941. // this return value is used (can be checked via ASTContext.getParents).
  4942. return rhs;
  4943. }
  4944. SpirvEvalInfo
  4945. SPIRVEmitter::tryToAssignToRWBufferRWTexture(const Expr *lhs,
  4946. const SpirvEvalInfo &rhs) {
  4947. const Expr *baseExpr = nullptr;
  4948. const Expr *indexExpr = nullptr;
  4949. const auto lhsExpr = dyn_cast<CXXOperatorCallExpr>(lhs);
  4950. if (isBufferTextureIndexing(lhsExpr, &baseExpr, &indexExpr)) {
  4951. const uint32_t locId = doExpr(indexExpr);
  4952. const QualType imageType = baseExpr->getType();
  4953. const auto baseInfo = doExpr(baseExpr);
  4954. const uint32_t imageId = theBuilder.createLoad(
  4955. typeTranslator.translateType(imageType), baseInfo);
  4956. theBuilder.createImageWrite(imageType, imageId, locId, rhs);
  4957. if (baseInfo.isNonUniform()) {
  4958. // Decorate the image handle for OpImageWrite
  4959. theBuilder.decorate(imageId, spv::Decoration::NonUniformEXT);
  4960. }
  4961. return rhs;
  4962. }
  4963. return 0;
  4964. }
  4965. SpirvEvalInfo
  4966. SPIRVEmitter::tryToAssignToMatrixElements(const Expr *lhs,
  4967. const SpirvEvalInfo &rhs) {
  4968. const auto *lhsExpr = dyn_cast<ExtMatrixElementExpr>(lhs);
  4969. if (!lhsExpr)
  4970. return 0;
  4971. const Expr *baseMat = lhsExpr->getBase();
  4972. const auto base = doExpr(baseMat);
  4973. const QualType elemType = hlsl::GetHLSLMatElementType(baseMat->getType());
  4974. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  4975. uint32_t rowCount = 0, colCount = 0;
  4976. hlsl::GetHLSLMatRowColCount(baseMat->getType(), rowCount, colCount);
  4977. // For each lhs element written to:
  4978. // 1. Extract the corresponding rhs element using OpCompositeExtract
  4979. // 2. Create access chain for the lhs element using OpAccessChain
  4980. // 3. Write using OpStore
  4981. const auto accessor = lhsExpr->getEncodedElementAccess();
  4982. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4983. uint32_t row = 0, col = 0;
  4984. accessor.GetPosition(i, &row, &col);
  4985. llvm::SmallVector<uint32_t, 2> indices;
  4986. // If the matrix only have one row/column, we are indexing into a vector
  4987. // then. Only one index is needed for such cases.
  4988. if (rowCount > 1)
  4989. indices.push_back(row);
  4990. if (colCount > 1)
  4991. indices.push_back(col);
  4992. for (uint32_t i = 0; i < indices.size(); ++i)
  4993. indices[i] = theBuilder.getConstantInt32(indices[i]);
  4994. // If we are writing to only one element, the rhs should already be a
  4995. // scalar value.
  4996. uint32_t rhsElem = rhs;
  4997. if (accessor.Count > 1)
  4998. rhsElem = theBuilder.createCompositeExtract(elemTypeId, rhs, {i});
  4999. const uint32_t ptrType =
  5000. theBuilder.getPointerType(elemTypeId, base.getStorageClass());
  5001. // If the lhs is actually a matrix of size 1x1, we don't need the access
  5002. // chain. base is already the dest pointer.
  5003. uint32_t lhsElemPtr = base;
  5004. if (!indices.empty()) {
  5005. assert(!base.isRValue());
  5006. // Load the element via access chain
  5007. lhsElemPtr = theBuilder.createAccessChain(ptrType, lhsElemPtr, indices);
  5008. }
  5009. theBuilder.createStore(lhsElemPtr, rhsElem);
  5010. }
  5011. // TODO: OK, this return value is incorrect for compound assignments, for
  5012. // which cases we should return lvalues. Should at least emit errors if
  5013. // this return value is used (can be checked via ASTContext.getParents).
  5014. return rhs;
  5015. }
  5016. SpirvEvalInfo SPIRVEmitter::processEachVectorInMatrix(
  5017. const Expr *matrix, const uint32_t matrixVal,
  5018. llvm::function_ref<uint32_t(uint32_t, uint32_t, uint32_t)>
  5019. actOnEachVector) {
  5020. const auto matType = matrix->getType();
  5021. assert(TypeTranslator::isMxNMatrix(matType));
  5022. const uint32_t vecType = typeTranslator.getComponentVectorType(matType);
  5023. uint32_t rowCount = 0, colCount = 0;
  5024. hlsl::GetHLSLMatRowColCount(matType, rowCount, colCount);
  5025. llvm::SmallVector<uint32_t, 4> vectors;
  5026. // Extract each component vector and do operation on it
  5027. for (uint32_t i = 0; i < rowCount; ++i) {
  5028. const uint32_t lhsVec =
  5029. theBuilder.createCompositeExtract(vecType, matrixVal, {i});
  5030. vectors.push_back(actOnEachVector(i, vecType, lhsVec));
  5031. }
  5032. // Construct the result matrix
  5033. const auto valId = theBuilder.createCompositeConstruct(
  5034. typeTranslator.translateType(matType), vectors);
  5035. return SpirvEvalInfo(valId).setRValue();
  5036. }
  5037. void SPIRVEmitter::createSpecConstant(const VarDecl *varDecl) {
  5038. class SpecConstantEnvRAII {
  5039. public:
  5040. // Creates a new instance which sets mode to true on creation,
  5041. // and resets mode to false on destruction.
  5042. SpecConstantEnvRAII(bool *mode) : modeSlot(mode) { *modeSlot = true; }
  5043. ~SpecConstantEnvRAII() { *modeSlot = false; }
  5044. private:
  5045. bool *modeSlot;
  5046. };
  5047. const QualType varType = varDecl->getType();
  5048. bool hasError = false;
  5049. if (!varDecl->isExternallyVisible()) {
  5050. emitError("specialization constant must be externally visible",
  5051. varDecl->getLocation());
  5052. hasError = true;
  5053. }
  5054. if (const auto *builtinType = varType->getAs<BuiltinType>()) {
  5055. switch (builtinType->getKind()) {
  5056. case BuiltinType::Bool:
  5057. case BuiltinType::Int:
  5058. case BuiltinType::UInt:
  5059. case BuiltinType::Float:
  5060. break;
  5061. default:
  5062. emitError("unsupported specialization constant type",
  5063. varDecl->getLocStart());
  5064. hasError = true;
  5065. }
  5066. }
  5067. const auto *init = varDecl->getInit();
  5068. if (!init) {
  5069. emitError("missing default value for specialization constant",
  5070. varDecl->getLocation());
  5071. hasError = true;
  5072. } else if (!isAcceptedSpecConstantInit(init)) {
  5073. emitError("unsupported specialization constant initializer",
  5074. init->getLocStart())
  5075. << init->getSourceRange();
  5076. hasError = true;
  5077. }
  5078. if (hasError)
  5079. return;
  5080. SpecConstantEnvRAII specConstantEnvRAII(&isSpecConstantMode);
  5081. const auto specConstant = doExpr(init);
  5082. // We are not creating a variable to hold the spec constant, instead, we
  5083. // translate the varDecl directly into the spec constant here.
  5084. theBuilder.decorateSpecId(
  5085. specConstant, varDecl->getAttr<VKConstantIdAttr>()->getSpecConstId());
  5086. declIdMapper.registerSpecConstant(varDecl, specConstant);
  5087. }
  5088. SpirvEvalInfo
  5089. SPIRVEmitter::processMatrixBinaryOp(const Expr *lhs, const Expr *rhs,
  5090. const BinaryOperatorKind opcode,
  5091. SourceRange range) {
  5092. // TODO: some code are duplicated from processBinaryOp. Try to unify them.
  5093. const auto lhsType = lhs->getType();
  5094. assert(TypeTranslator::isMxNMatrix(lhsType));
  5095. const spv::Op spvOp = translateOp(opcode, lhsType);
  5096. uint32_t rhsVal, lhsPtr, lhsVal;
  5097. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  5098. // Evalute rhs before lhs
  5099. rhsVal = doExpr(rhs);
  5100. lhsPtr = doExpr(lhs);
  5101. const uint32_t lhsTy = typeTranslator.translateType(lhsType);
  5102. lhsVal = theBuilder.createLoad(lhsTy, lhsPtr);
  5103. } else {
  5104. // Evalute lhs before rhs
  5105. lhsVal = lhsPtr = doExpr(lhs);
  5106. rhsVal = doExpr(rhs);
  5107. }
  5108. switch (opcode) {
  5109. case BO_Add:
  5110. case BO_Sub:
  5111. case BO_Mul:
  5112. case BO_Div:
  5113. case BO_Rem:
  5114. case BO_AddAssign:
  5115. case BO_SubAssign:
  5116. case BO_MulAssign:
  5117. case BO_DivAssign:
  5118. case BO_RemAssign: {
  5119. const uint32_t vecType = typeTranslator.getComponentVectorType(lhsType);
  5120. const auto actOnEachVec = [this, spvOp, rhsVal](uint32_t index,
  5121. uint32_t vecType,
  5122. uint32_t lhsVec) {
  5123. // For each vector of lhs, we need to load the corresponding vector of
  5124. // rhs and do the operation on them.
  5125. const uint32_t rhsVec =
  5126. theBuilder.createCompositeExtract(vecType, rhsVal, {index});
  5127. const auto valId =
  5128. theBuilder.createBinaryOp(spvOp, vecType, lhsVec, rhsVec);
  5129. return SpirvEvalInfo(valId).setRValue();
  5130. };
  5131. return processEachVectorInMatrix(lhs, lhsVal, actOnEachVec);
  5132. }
  5133. case BO_Assign:
  5134. llvm_unreachable("assignment should not be handled here");
  5135. default:
  5136. break;
  5137. }
  5138. emitError("binary operator '%0' over matrix type unimplemented",
  5139. lhs->getExprLoc())
  5140. << BinaryOperator::getOpcodeStr(opcode) << range;
  5141. return 0;
  5142. }
  5143. const Expr *SPIRVEmitter::collectArrayStructIndices(
  5144. const Expr *expr, llvm::SmallVectorImpl<uint32_t> *indices, bool rawIndex) {
  5145. if (const auto *indexing = dyn_cast<MemberExpr>(expr)) {
  5146. // First check whether this is referring to a static member. If it is, we
  5147. // create a DeclRefExpr for it.
  5148. if (auto *varDecl = dyn_cast<VarDecl>(indexing->getMemberDecl()))
  5149. if (varDecl->isStaticDataMember())
  5150. return DeclRefExpr::Create(
  5151. astContext, NestedNameSpecifierLoc(), SourceLocation(), varDecl,
  5152. /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
  5153. varDecl->getType(), VK_LValue);
  5154. const Expr *base = collectArrayStructIndices(
  5155. indexing->getBase()->IgnoreParenNoopCasts(astContext), indices,
  5156. rawIndex);
  5157. // Append the index of the current level
  5158. const auto *fieldDecl = cast<FieldDecl>(indexing->getMemberDecl());
  5159. assert(fieldDecl);
  5160. // If we are accessing a derived struct, we need to account for the number
  5161. // of base structs, since they are placed as fields at the beginning of the
  5162. // derived struct.
  5163. const uint32_t index = getNumBaseClasses(indexing->getBase()->getType()) +
  5164. fieldDecl->getFieldIndex();
  5165. indices->push_back(rawIndex ? index : theBuilder.getConstantInt32(index));
  5166. return base;
  5167. }
  5168. // Provide a hint to the TypeTranslator that the integer literal used to
  5169. // index into the following cases should be translated as a 32-bit integer.
  5170. TypeTranslator::LiteralTypeHint hint(typeTranslator, astContext.IntTy);
  5171. if (const auto *indexing = dyn_cast<ArraySubscriptExpr>(expr)) {
  5172. if (rawIndex)
  5173. return nullptr; // TODO: handle constant array index
  5174. // The base of an ArraySubscriptExpr has a wrapping LValueToRValue implicit
  5175. // cast. We need to ingore it to avoid creating OpLoad.
  5176. const Expr *thisBase = indexing->getBase()->IgnoreParenLValueCasts();
  5177. const Expr *base = collectArrayStructIndices(thisBase, indices, rawIndex);
  5178. indices->push_back(doExpr(indexing->getIdx()));
  5179. return base;
  5180. }
  5181. if (const auto *indexing = dyn_cast<CXXOperatorCallExpr>(expr))
  5182. if (indexing->getOperator() == OverloadedOperatorKind::OO_Subscript) {
  5183. if (rawIndex)
  5184. return nullptr; // TODO: handle constant array index
  5185. const Expr *thisBase =
  5186. indexing->getArg(0)->IgnoreParenNoopCasts(astContext);
  5187. const auto thisBaseType = thisBase->getType();
  5188. const Expr *base = collectArrayStructIndices(thisBase, indices, rawIndex);
  5189. if (thisBaseType != base->getType() &&
  5190. TypeTranslator::isAKindOfStructuredOrByteBuffer(thisBaseType)) {
  5191. // The immediate base is a kind of structured or byte buffer. It should
  5192. // be an alias variable. Break the normal index collecting chain.
  5193. // Return the immediate base as the base so that we can apply other
  5194. // hacks for legalization over it.
  5195. //
  5196. // Note: legalization specific code
  5197. indices->clear();
  5198. base = thisBase;
  5199. }
  5200. // If the base is a StructureType, we need to push an addtional index 0
  5201. // here. This is because we created an additional OpTypeRuntimeArray
  5202. // in the structure.
  5203. if (TypeTranslator::isStructuredBuffer(thisBaseType))
  5204. indices->push_back(theBuilder.getConstantInt32(0));
  5205. if ((hlsl::IsHLSLVecType(thisBaseType) &&
  5206. (hlsl::GetHLSLVecSize(thisBaseType) == 1)) ||
  5207. typeTranslator.is1x1Matrix(thisBaseType) ||
  5208. typeTranslator.is1xNMatrix(thisBaseType)) {
  5209. // If this is a size-1 vector or 1xN matrix, ignore the index.
  5210. } else {
  5211. indices->push_back(doExpr(indexing->getArg(1)));
  5212. }
  5213. return base;
  5214. }
  5215. {
  5216. const Expr *index = nullptr;
  5217. // TODO: the following is duplicating the logic in doCXXMemberCallExpr.
  5218. if (const auto *object = isStructuredBufferLoad(expr, &index)) {
  5219. if (rawIndex)
  5220. return nullptr; // TODO: handle constant array index
  5221. // For object.Load(index), there should be no more indexing into the
  5222. // object.
  5223. indices->push_back(theBuilder.getConstantInt32(0));
  5224. indices->push_back(doExpr(index));
  5225. return object;
  5226. }
  5227. }
  5228. // This the deepest we can go. No more array or struct indexing.
  5229. return expr;
  5230. }
  5231. SpirvEvalInfo &SPIRVEmitter::turnIntoElementPtr(
  5232. SpirvEvalInfo &info, QualType elemType,
  5233. const llvm::SmallVector<uint32_t, 4> &indices) {
  5234. assert(!info.isRValue());
  5235. const uint32_t ptrType = theBuilder.getPointerType(
  5236. typeTranslator.translateType(elemType, info.getLayoutRule()),
  5237. info.getStorageClass());
  5238. return info.setResultId(theBuilder.createAccessChain(ptrType, info, indices));
  5239. }
  5240. uint32_t SPIRVEmitter::castToBool(const uint32_t fromVal, QualType fromType,
  5241. QualType toBoolType) {
  5242. if (TypeTranslator::isSameScalarOrVecType(fromType, toBoolType))
  5243. return fromVal;
  5244. const uint32_t boolType = typeTranslator.translateType(toBoolType);
  5245. { // Special case handling for converting to a matrix of booleans.
  5246. QualType elemType = {};
  5247. uint32_t rowCount = 0, colCount = 0;
  5248. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &rowCount,
  5249. &colCount)) {
  5250. const auto fromRowQualType =
  5251. astContext.getExtVectorType(elemType, colCount);
  5252. const auto fromRowQualTypeId =
  5253. typeTranslator.translateType(fromRowQualType);
  5254. const auto toBoolRowQualType =
  5255. astContext.getExtVectorType(astContext.BoolTy, colCount);
  5256. llvm::SmallVector<uint32_t, 4> rows;
  5257. for (uint32_t i = 0; i < rowCount; ++i) {
  5258. const auto row =
  5259. theBuilder.createCompositeExtract(fromRowQualTypeId, fromVal, {i});
  5260. rows.push_back(castToBool(row, fromRowQualType, toBoolRowQualType));
  5261. }
  5262. return theBuilder.createCompositeConstruct(boolType, rows);
  5263. }
  5264. }
  5265. // Converting to bool means comparing with value zero.
  5266. const spv::Op spvOp = translateOp(BO_NE, fromType);
  5267. const uint32_t zeroVal = getValueZero(fromType);
  5268. return theBuilder.createBinaryOp(spvOp, boolType, fromVal, zeroVal);
  5269. }
  5270. uint32_t SPIRVEmitter::castToInt(uint32_t fromVal, QualType fromType,
  5271. QualType toIntType, SourceLocation srcLoc) {
  5272. if (TypeTranslator::isSameScalarOrVecType(fromType, toIntType))
  5273. return fromVal;
  5274. uint32_t intType = typeTranslator.translateType(toIntType);
  5275. if (isBoolOrVecOfBoolType(fromType)) {
  5276. const uint32_t one = getValueOne(toIntType);
  5277. const uint32_t zero = getValueZero(toIntType);
  5278. return theBuilder.createSelect(intType, fromVal, one, zero);
  5279. }
  5280. if (isSintOrVecOfSintType(fromType) || isUintOrVecOfUintType(fromType)) {
  5281. // First convert the source to the bitwidth of the destination if necessary.
  5282. uint32_t convertedType = 0;
  5283. fromVal = convertBitwidth(fromVal, fromType, toIntType, &convertedType);
  5284. // If bitwidth conversion was the only thing we needed to do, we're done.
  5285. if (convertedType == typeTranslator.translateType(toIntType))
  5286. return fromVal;
  5287. return theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, fromVal);
  5288. }
  5289. if (isFloatOrVecOfFloatType(fromType)) {
  5290. // First convert the source to the bitwidth of the destination if necessary.
  5291. fromVal = convertBitwidth(fromVal, fromType, toIntType);
  5292. if (isSintOrVecOfSintType(toIntType)) {
  5293. return theBuilder.createUnaryOp(spv::Op::OpConvertFToS, intType, fromVal);
  5294. } else if (isUintOrVecOfUintType(toIntType)) {
  5295. return theBuilder.createUnaryOp(spv::Op::OpConvertFToU, intType, fromVal);
  5296. } else {
  5297. emitError("casting from floating point to integer unimplemented", srcLoc);
  5298. }
  5299. }
  5300. {
  5301. QualType elemType = {};
  5302. uint32_t numRows = 0, numCols = 0;
  5303. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  5304. // The source matrix and the target matrix must have the same dimensions.
  5305. QualType toElemType = {};
  5306. uint32_t toNumRows = 0, toNumCols = 0;
  5307. const bool isMat = TypeTranslator::isMxNMatrix(toIntType, &toElemType,
  5308. &toNumRows, &toNumCols);
  5309. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  5310. (void)toNumRows;
  5311. (void)toNumCols;
  5312. // Casting to a matrix of integers: Cast each row and construct a
  5313. // composite.
  5314. llvm::SmallVector<uint32_t, 4> castedRows;
  5315. const uint32_t vecType = typeTranslator.getComponentVectorType(fromType);
  5316. const auto fromVecQualType =
  5317. astContext.getExtVectorType(elemType, numCols);
  5318. const auto toIntVecQualType =
  5319. astContext.getExtVectorType(toElemType, numCols);
  5320. for (uint32_t row = 0; row < numRows; ++row) {
  5321. const auto rowId =
  5322. theBuilder.createCompositeExtract(vecType, fromVal, {row});
  5323. castedRows.push_back(
  5324. castToInt(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  5325. }
  5326. return theBuilder.createCompositeConstruct(intType, castedRows);
  5327. }
  5328. }
  5329. return 0;
  5330. }
  5331. uint32_t SPIRVEmitter::convertBitwidth(uint32_t fromVal, QualType fromType,
  5332. QualType toType, uint32_t *resultType) {
  5333. // At the moment, we will not make bitwidth conversions for literal int and
  5334. // literal float types because they always indicate 64-bit and do not
  5335. // represent what SPIR-V was actually resolved to.
  5336. // TODO: If the evaluated type is added to SpirvEvalInfo, change 'fromVal' to
  5337. // SpirvEvalInfo and use it to handle literal types more accurately.
  5338. if (fromType->isSpecificBuiltinType(BuiltinType::LitFloat) ||
  5339. fromType->isSpecificBuiltinType(BuiltinType::LitInt))
  5340. return fromVal;
  5341. const auto fromBitwidth = typeTranslator.getElementSpirvBitwidth(fromType);
  5342. const auto toBitwidth = typeTranslator.getElementSpirvBitwidth(toType);
  5343. if (fromBitwidth == toBitwidth) {
  5344. if (resultType)
  5345. *resultType = typeTranslator.translateType(fromType);
  5346. return fromVal;
  5347. }
  5348. // We want the 'fromType' with the 'toBitwidth'.
  5349. const uint32_t targetTypeId =
  5350. typeTranslator.getTypeWithCustomBitwidth(fromType, toBitwidth);
  5351. if (resultType)
  5352. *resultType = targetTypeId;
  5353. if (isFloatOrVecOfFloatType(fromType))
  5354. return theBuilder.createUnaryOp(spv::Op::OpFConvert, targetTypeId, fromVal);
  5355. if (isSintOrVecOfSintType(fromType))
  5356. return theBuilder.createUnaryOp(spv::Op::OpSConvert, targetTypeId, fromVal);
  5357. if (isUintOrVecOfUintType(fromType))
  5358. return theBuilder.createUnaryOp(spv::Op::OpUConvert, targetTypeId, fromVal);
  5359. llvm_unreachable("invalid type passed to convertBitwidth");
  5360. }
  5361. uint32_t SPIRVEmitter::castToFloat(uint32_t fromVal, QualType fromType,
  5362. QualType toFloatType,
  5363. SourceLocation srcLoc) {
  5364. if (TypeTranslator::isSameScalarOrVecType(fromType, toFloatType))
  5365. return fromVal;
  5366. const uint32_t floatType = typeTranslator.translateType(toFloatType);
  5367. if (isBoolOrVecOfBoolType(fromType)) {
  5368. const uint32_t one = getValueOne(toFloatType);
  5369. const uint32_t zero = getValueZero(toFloatType);
  5370. return theBuilder.createSelect(floatType, fromVal, one, zero);
  5371. }
  5372. if (isSintOrVecOfSintType(fromType)) {
  5373. // First convert the source to the bitwidth of the destination if necessary.
  5374. fromVal = convertBitwidth(fromVal, fromType, toFloatType);
  5375. return theBuilder.createUnaryOp(spv::Op::OpConvertSToF, floatType, fromVal);
  5376. }
  5377. if (isUintOrVecOfUintType(fromType)) {
  5378. // First convert the source to the bitwidth of the destination if necessary.
  5379. fromVal = convertBitwidth(fromVal, fromType, toFloatType);
  5380. return theBuilder.createUnaryOp(spv::Op::OpConvertUToF, floatType, fromVal);
  5381. }
  5382. if (isFloatOrVecOfFloatType(fromType)) {
  5383. // This is the case of float to float conversion with different bitwidths.
  5384. return convertBitwidth(fromVal, fromType, toFloatType);
  5385. }
  5386. // Casting matrix types
  5387. {
  5388. QualType elemType = {};
  5389. uint32_t numRows = 0, numCols = 0;
  5390. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  5391. // The source matrix and the target matrix must have the same dimensions.
  5392. QualType toElemType = {};
  5393. uint32_t toNumRows = 0, toNumCols = 0;
  5394. const auto isMat = TypeTranslator::isMxNMatrix(toFloatType, &toElemType,
  5395. &toNumRows, &toNumCols);
  5396. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  5397. (void)toNumRows;
  5398. (void)toNumCols;
  5399. // Casting to a matrix of floats: Cast each row and construct a
  5400. // composite.
  5401. llvm::SmallVector<uint32_t, 4> castedRows;
  5402. const uint32_t vecType = typeTranslator.getComponentVectorType(fromType);
  5403. const auto fromVecQualType =
  5404. astContext.getExtVectorType(elemType, numCols);
  5405. const auto toIntVecQualType =
  5406. astContext.getExtVectorType(toElemType, numCols);
  5407. for (uint32_t row = 0; row < numRows; ++row) {
  5408. const auto rowId =
  5409. theBuilder.createCompositeExtract(vecType, fromVal, {row});
  5410. castedRows.push_back(
  5411. castToFloat(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  5412. }
  5413. return theBuilder.createCompositeConstruct(floatType, castedRows);
  5414. }
  5415. }
  5416. emitError("casting to floating point unimplemented", srcLoc);
  5417. return 0;
  5418. }
  5419. SpirvEvalInfo SPIRVEmitter::processIntrinsicCallExpr(const CallExpr *callExpr) {
  5420. const FunctionDecl *callee = callExpr->getDirectCallee();
  5421. assert(hlsl::IsIntrinsicOp(callee) &&
  5422. "doIntrinsicCallExpr was called for a non-intrinsic function.");
  5423. const bool isFloatType = isFloatOrVecMatOfFloatType(callExpr->getType());
  5424. const bool isSintType = isSintOrVecMatOfSintType(callExpr->getType());
  5425. // Figure out which intrinsic function to translate.
  5426. llvm::StringRef group;
  5427. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  5428. hlsl::GetIntrinsicOp(callee, opcode, group);
  5429. GLSLstd450 glslOpcode = GLSLstd450Bad;
  5430. uint32_t retVal = 0;
  5431. #define INTRINSIC_SPIRV_OP_WITH_CAP_CASE(intrinsicOp, spirvOp, doEachVec, cap) \
  5432. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5433. theBuilder.requireCapability(cap); \
  5434. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  5435. doEachVec); \
  5436. } break
  5437. #define INTRINSIC_SPIRV_OP_CASE(intrinsicOp, spirvOp, doEachVec) \
  5438. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5439. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  5440. doEachVec); \
  5441. } break
  5442. #define INTRINSIC_OP_CASE(intrinsicOp, glslOp, doEachVec) \
  5443. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5444. glslOpcode = GLSLstd450::GLSLstd450##glslOp; \
  5445. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5446. } break
  5447. #define INTRINSIC_OP_CASE_INT_FLOAT(intrinsicOp, glslIntOp, glslFloatOp, \
  5448. doEachVec) \
  5449. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5450. glslOpcode = isFloatType ? GLSLstd450::GLSLstd450##glslFloatOp \
  5451. : GLSLstd450::GLSLstd450##glslIntOp; \
  5452. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5453. } break
  5454. #define INTRINSIC_OP_CASE_SINT_UINT(intrinsicOp, glslSintOp, glslUintOp, \
  5455. doEachVec) \
  5456. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5457. glslOpcode = isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  5458. : GLSLstd450::GLSLstd450##glslUintOp; \
  5459. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5460. } break
  5461. #define INTRINSIC_OP_CASE_SINT_UINT_FLOAT(intrinsicOp, glslSintOp, glslUintOp, \
  5462. glslFloatOp, doEachVec) \
  5463. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5464. glslOpcode = isFloatType \
  5465. ? GLSLstd450::GLSLstd450##glslFloatOp \
  5466. : isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  5467. : GLSLstd450::GLSLstd450##glslUintOp; \
  5468. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5469. } break
  5470. switch (const auto hlslOpcode = static_cast<hlsl::IntrinsicOp>(opcode)) {
  5471. case hlsl::IntrinsicOp::IOP_InterlockedAdd:
  5472. case hlsl::IntrinsicOp::IOP_InterlockedAnd:
  5473. case hlsl::IntrinsicOp::IOP_InterlockedMax:
  5474. case hlsl::IntrinsicOp::IOP_InterlockedUMax:
  5475. case hlsl::IntrinsicOp::IOP_InterlockedMin:
  5476. case hlsl::IntrinsicOp::IOP_InterlockedUMin:
  5477. case hlsl::IntrinsicOp::IOP_InterlockedOr:
  5478. case hlsl::IntrinsicOp::IOP_InterlockedXor:
  5479. case hlsl::IntrinsicOp::IOP_InterlockedExchange:
  5480. case hlsl::IntrinsicOp::IOP_InterlockedCompareStore:
  5481. case hlsl::IntrinsicOp::IOP_InterlockedCompareExchange:
  5482. retVal = processIntrinsicInterlockedMethod(callExpr, hlslOpcode);
  5483. break;
  5484. case hlsl::IntrinsicOp::IOP_NonUniformResourceIndex:
  5485. retVal = processIntrinsicNonUniformResourceIndex(callExpr);
  5486. break;
  5487. case hlsl::IntrinsicOp::IOP_tex1D:
  5488. case hlsl::IntrinsicOp::IOP_tex1Dbias:
  5489. case hlsl::IntrinsicOp::IOP_tex1Dgrad:
  5490. case hlsl::IntrinsicOp::IOP_tex1Dlod:
  5491. case hlsl::IntrinsicOp::IOP_tex1Dproj:
  5492. case hlsl::IntrinsicOp::IOP_tex2D:
  5493. case hlsl::IntrinsicOp::IOP_tex2Dbias:
  5494. case hlsl::IntrinsicOp::IOP_tex2Dgrad:
  5495. case hlsl::IntrinsicOp::IOP_tex2Dlod:
  5496. case hlsl::IntrinsicOp::IOP_tex2Dproj:
  5497. case hlsl::IntrinsicOp::IOP_tex3D:
  5498. case hlsl::IntrinsicOp::IOP_tex3Dbias:
  5499. case hlsl::IntrinsicOp::IOP_tex3Dgrad:
  5500. case hlsl::IntrinsicOp::IOP_tex3Dlod:
  5501. case hlsl::IntrinsicOp::IOP_tex3Dproj:
  5502. case hlsl::IntrinsicOp::IOP_texCUBE:
  5503. case hlsl::IntrinsicOp::IOP_texCUBEbias:
  5504. case hlsl::IntrinsicOp::IOP_texCUBEgrad:
  5505. case hlsl::IntrinsicOp::IOP_texCUBElod:
  5506. case hlsl::IntrinsicOp::IOP_texCUBEproj: {
  5507. emitError("deprecated %0 intrinsic function will not be supported",
  5508. callExpr->getExprLoc())
  5509. << callee->getName();
  5510. return 0;
  5511. }
  5512. case hlsl::IntrinsicOp::IOP_dot:
  5513. retVal = processIntrinsicDot(callExpr);
  5514. break;
  5515. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrier:
  5516. retVal = processIntrinsicMemoryBarrier(callExpr,
  5517. /*isDevice*/ false,
  5518. /*groupSync*/ false,
  5519. /*isAllBarrier*/ false);
  5520. break;
  5521. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  5522. retVal = processIntrinsicMemoryBarrier(callExpr,
  5523. /*isDevice*/ false,
  5524. /*groupSync*/ true,
  5525. /*isAllBarrier*/ false);
  5526. break;
  5527. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrier:
  5528. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5529. /*groupSync*/ false,
  5530. /*isAllBarrier*/ false);
  5531. break;
  5532. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  5533. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5534. /*groupSync*/ true,
  5535. /*isAllBarrier*/ false);
  5536. break;
  5537. case hlsl::IntrinsicOp::IOP_AllMemoryBarrier:
  5538. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5539. /*groupSync*/ false,
  5540. /*isAllBarrier*/ true);
  5541. break;
  5542. case hlsl::IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  5543. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5544. /*groupSync*/ true,
  5545. /*isAllBarrier*/ true);
  5546. break;
  5547. case hlsl::IntrinsicOp::IOP_CheckAccessFullyMapped:
  5548. retVal =
  5549. theBuilder.createImageSparseTexelsResident(doExpr(callExpr->getArg(0)));
  5550. break;
  5551. case hlsl::IntrinsicOp::IOP_mul:
  5552. case hlsl::IntrinsicOp::IOP_umul:
  5553. retVal = processIntrinsicMul(callExpr);
  5554. break;
  5555. case hlsl::IntrinsicOp::IOP_all:
  5556. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAll);
  5557. break;
  5558. case hlsl::IntrinsicOp::IOP_any:
  5559. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAny);
  5560. break;
  5561. case hlsl::IntrinsicOp::IOP_asdouble:
  5562. case hlsl::IntrinsicOp::IOP_asfloat:
  5563. case hlsl::IntrinsicOp::IOP_asint:
  5564. case hlsl::IntrinsicOp::IOP_asuint:
  5565. retVal = processIntrinsicAsType(callExpr);
  5566. break;
  5567. case hlsl::IntrinsicOp::IOP_clip:
  5568. retVal = processIntrinsicClip(callExpr);
  5569. break;
  5570. case hlsl::IntrinsicOp::IOP_dst:
  5571. retVal = processIntrinsicDst(callExpr);
  5572. break;
  5573. case hlsl::IntrinsicOp::IOP_clamp:
  5574. case hlsl::IntrinsicOp::IOP_uclamp:
  5575. retVal = processIntrinsicClamp(callExpr);
  5576. break;
  5577. case hlsl::IntrinsicOp::IOP_frexp:
  5578. retVal = processIntrinsicFrexp(callExpr);
  5579. break;
  5580. case hlsl::IntrinsicOp::IOP_ldexp:
  5581. retVal = processIntrinsicLdexp(callExpr);
  5582. break;
  5583. case hlsl::IntrinsicOp::IOP_lit:
  5584. retVal = processIntrinsicLit(callExpr);
  5585. break;
  5586. case hlsl::IntrinsicOp::IOP_modf:
  5587. retVal = processIntrinsicModf(callExpr);
  5588. break;
  5589. case hlsl::IntrinsicOp::IOP_msad4:
  5590. retVal = processIntrinsicMsad4(callExpr);
  5591. break;
  5592. case hlsl::IntrinsicOp::IOP_sign: {
  5593. if (isFloatOrVecMatOfFloatType(callExpr->getArg(0)->getType()))
  5594. retVal = processIntrinsicFloatSign(callExpr);
  5595. else
  5596. retVal =
  5597. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450SSign,
  5598. /*actPerRowForMatrices*/ true);
  5599. } break;
  5600. case hlsl::IntrinsicOp::IOP_D3DCOLORtoUBYTE4:
  5601. retVal = processD3DCOLORtoUBYTE4(callExpr);
  5602. break;
  5603. case hlsl::IntrinsicOp::IOP_isfinite:
  5604. retVal = processIntrinsicIsFinite(callExpr);
  5605. break;
  5606. case hlsl::IntrinsicOp::IOP_sincos:
  5607. retVal = processIntrinsicSinCos(callExpr);
  5608. break;
  5609. case hlsl::IntrinsicOp::IOP_rcp:
  5610. retVal = processIntrinsicRcp(callExpr);
  5611. break;
  5612. case hlsl::IntrinsicOp::IOP_saturate:
  5613. retVal = processIntrinsicSaturate(callExpr);
  5614. break;
  5615. case hlsl::IntrinsicOp::IOP_log10:
  5616. retVal = processIntrinsicLog10(callExpr);
  5617. break;
  5618. case hlsl::IntrinsicOp::IOP_f16tof32:
  5619. retVal = processIntrinsicF16ToF32(callExpr);
  5620. break;
  5621. case hlsl::IntrinsicOp::IOP_f32tof16:
  5622. retVal = processIntrinsicF32ToF16(callExpr);
  5623. break;
  5624. case hlsl::IntrinsicOp::IOP_WaveGetLaneCount: {
  5625. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneCount",
  5626. callExpr->getExprLoc());
  5627. const uint32_t retType =
  5628. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5629. const uint32_t varId =
  5630. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupSize);
  5631. retVal = theBuilder.createLoad(retType, varId);
  5632. } break;
  5633. case hlsl::IntrinsicOp::IOP_WaveGetLaneIndex: {
  5634. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneIndex",
  5635. callExpr->getExprLoc());
  5636. const uint32_t retType =
  5637. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5638. const uint32_t varId =
  5639. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupLocalInvocationId);
  5640. retVal = theBuilder.createLoad(retType, varId);
  5641. } break;
  5642. case hlsl::IntrinsicOp::IOP_WaveIsFirstLane:
  5643. retVal = processWaveQuery(callExpr, spv::Op::OpGroupNonUniformElect);
  5644. break;
  5645. case hlsl::IntrinsicOp::IOP_WaveActiveAllTrue:
  5646. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAll);
  5647. break;
  5648. case hlsl::IntrinsicOp::IOP_WaveActiveAnyTrue:
  5649. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAny);
  5650. break;
  5651. case hlsl::IntrinsicOp::IOP_WaveActiveBallot:
  5652. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformBallot);
  5653. break;
  5654. case hlsl::IntrinsicOp::IOP_WaveActiveAllEqual:
  5655. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAllEqual);
  5656. break;
  5657. case hlsl::IntrinsicOp::IOP_WaveActiveCountBits:
  5658. retVal = processWaveReductionOrPrefix(
  5659. callExpr, spv::Op::OpGroupNonUniformBallotBitCount,
  5660. spv::GroupOperation::Reduce);
  5661. break;
  5662. case hlsl::IntrinsicOp::IOP_WaveActiveUSum:
  5663. case hlsl::IntrinsicOp::IOP_WaveActiveSum:
  5664. case hlsl::IntrinsicOp::IOP_WaveActiveUProduct:
  5665. case hlsl::IntrinsicOp::IOP_WaveActiveProduct:
  5666. case hlsl::IntrinsicOp::IOP_WaveActiveUMax:
  5667. case hlsl::IntrinsicOp::IOP_WaveActiveMax:
  5668. case hlsl::IntrinsicOp::IOP_WaveActiveUMin:
  5669. case hlsl::IntrinsicOp::IOP_WaveActiveMin:
  5670. case hlsl::IntrinsicOp::IOP_WaveActiveBitAnd:
  5671. case hlsl::IntrinsicOp::IOP_WaveActiveBitOr:
  5672. case hlsl::IntrinsicOp::IOP_WaveActiveBitXor: {
  5673. const auto retType = callExpr->getCallReturnType(astContext);
  5674. retVal = processWaveReductionOrPrefix(
  5675. callExpr, translateWaveOp(hlslOpcode, retType, callExpr->getExprLoc()),
  5676. spv::GroupOperation::Reduce);
  5677. } break;
  5678. case hlsl::IntrinsicOp::IOP_WavePrefixUSum:
  5679. case hlsl::IntrinsicOp::IOP_WavePrefixSum:
  5680. case hlsl::IntrinsicOp::IOP_WavePrefixUProduct:
  5681. case hlsl::IntrinsicOp::IOP_WavePrefixProduct: {
  5682. const auto retType = callExpr->getCallReturnType(astContext);
  5683. retVal = processWaveReductionOrPrefix(
  5684. callExpr, translateWaveOp(hlslOpcode, retType, callExpr->getExprLoc()),
  5685. spv::GroupOperation::ExclusiveScan);
  5686. } break;
  5687. case hlsl::IntrinsicOp::IOP_WavePrefixCountBits:
  5688. retVal = processWaveReductionOrPrefix(
  5689. callExpr, spv::Op::OpGroupNonUniformBallotBitCount,
  5690. spv::GroupOperation::ExclusiveScan);
  5691. break;
  5692. case hlsl::IntrinsicOp::IOP_WaveReadLaneAt:
  5693. case hlsl::IntrinsicOp::IOP_WaveReadLaneFirst:
  5694. retVal = processWaveBroadcast(callExpr);
  5695. break;
  5696. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  5697. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  5698. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  5699. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  5700. retVal = processWaveQuadWideShuffle(callExpr, hlslOpcode);
  5701. break;
  5702. case hlsl::IntrinsicOp::IOP_abort:
  5703. case hlsl::IntrinsicOp::IOP_GetRenderTargetSampleCount:
  5704. case hlsl::IntrinsicOp::IOP_GetRenderTargetSamplePosition: {
  5705. emitError("no equivalent for %0 intrinsic function in Vulkan",
  5706. callExpr->getExprLoc())
  5707. << callee->getName();
  5708. return 0;
  5709. }
  5710. case hlsl::IntrinsicOp::IOP_transpose: {
  5711. const Expr *mat = callExpr->getArg(0);
  5712. const QualType matType = mat->getType();
  5713. if (hlsl::GetHLSLMatElementType(matType)->isFloatingType())
  5714. retVal =
  5715. processIntrinsicUsingSpirvInst(callExpr, spv::Op::OpTranspose, false);
  5716. else
  5717. retVal = processNonFpMatrixTranspose(matType, doExpr(mat));
  5718. break;
  5719. }
  5720. INTRINSIC_SPIRV_OP_CASE(ddx, DPdx, true);
  5721. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddx_coarse, DPdxCoarse, false,
  5722. spv::Capability::DerivativeControl);
  5723. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddx_fine, DPdxFine, false,
  5724. spv::Capability::DerivativeControl);
  5725. INTRINSIC_SPIRV_OP_CASE(ddy, DPdy, true);
  5726. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddy_coarse, DPdyCoarse, false,
  5727. spv::Capability::DerivativeControl);
  5728. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddy_fine, DPdyFine, false,
  5729. spv::Capability::DerivativeControl);
  5730. INTRINSIC_SPIRV_OP_CASE(countbits, BitCount, false);
  5731. INTRINSIC_SPIRV_OP_CASE(isinf, IsInf, true);
  5732. INTRINSIC_SPIRV_OP_CASE(isnan, IsNan, true);
  5733. INTRINSIC_SPIRV_OP_CASE(fmod, FMod, true);
  5734. INTRINSIC_SPIRV_OP_CASE(fwidth, Fwidth, true);
  5735. INTRINSIC_SPIRV_OP_CASE(reversebits, BitReverse, false);
  5736. INTRINSIC_OP_CASE(round, Round, true);
  5737. INTRINSIC_OP_CASE_INT_FLOAT(abs, SAbs, FAbs, true);
  5738. INTRINSIC_OP_CASE(acos, Acos, true);
  5739. INTRINSIC_OP_CASE(asin, Asin, true);
  5740. INTRINSIC_OP_CASE(atan, Atan, true);
  5741. INTRINSIC_OP_CASE(atan2, Atan2, true);
  5742. INTRINSIC_OP_CASE(ceil, Ceil, true);
  5743. INTRINSIC_OP_CASE(cos, Cos, true);
  5744. INTRINSIC_OP_CASE(cosh, Cosh, true);
  5745. INTRINSIC_OP_CASE(cross, Cross, false);
  5746. INTRINSIC_OP_CASE(degrees, Degrees, true);
  5747. INTRINSIC_OP_CASE(distance, Distance, false);
  5748. INTRINSIC_OP_CASE(determinant, Determinant, false);
  5749. INTRINSIC_OP_CASE(exp, Exp, true);
  5750. INTRINSIC_OP_CASE(exp2, Exp2, true);
  5751. INTRINSIC_OP_CASE_SINT_UINT(firstbithigh, FindSMsb, FindUMsb, false);
  5752. INTRINSIC_OP_CASE_SINT_UINT(ufirstbithigh, FindSMsb, FindUMsb, false);
  5753. INTRINSIC_OP_CASE(faceforward, FaceForward, false);
  5754. INTRINSIC_OP_CASE(firstbitlow, FindILsb, false);
  5755. INTRINSIC_OP_CASE(floor, Floor, true);
  5756. INTRINSIC_OP_CASE(fma, Fma, true);
  5757. INTRINSIC_OP_CASE(frac, Fract, true);
  5758. INTRINSIC_OP_CASE(length, Length, false);
  5759. INTRINSIC_OP_CASE(lerp, FMix, true);
  5760. INTRINSIC_OP_CASE(log, Log, true);
  5761. INTRINSIC_OP_CASE(log2, Log2, true);
  5762. INTRINSIC_OP_CASE(mad, Fma, true);
  5763. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(max, SMax, UMax, FMax, true);
  5764. INTRINSIC_OP_CASE(umax, UMax, true);
  5765. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(min, SMin, UMin, FMin, true);
  5766. INTRINSIC_OP_CASE(umin, UMin, true);
  5767. INTRINSIC_OP_CASE(normalize, Normalize, false);
  5768. INTRINSIC_OP_CASE(pow, Pow, true);
  5769. INTRINSIC_OP_CASE(radians, Radians, true);
  5770. INTRINSIC_OP_CASE(reflect, Reflect, false);
  5771. INTRINSIC_OP_CASE(refract, Refract, false);
  5772. INTRINSIC_OP_CASE(rsqrt, InverseSqrt, true);
  5773. INTRINSIC_OP_CASE(smoothstep, SmoothStep, true);
  5774. INTRINSIC_OP_CASE(step, Step, true);
  5775. INTRINSIC_OP_CASE(sin, Sin, true);
  5776. INTRINSIC_OP_CASE(sinh, Sinh, true);
  5777. INTRINSIC_OP_CASE(tan, Tan, true);
  5778. INTRINSIC_OP_CASE(tanh, Tanh, true);
  5779. INTRINSIC_OP_CASE(sqrt, Sqrt, true);
  5780. INTRINSIC_OP_CASE(trunc, Trunc, true);
  5781. default:
  5782. emitError("%0 intrinsic function unimplemented", callExpr->getExprLoc())
  5783. << callee->getName();
  5784. return 0;
  5785. }
  5786. #undef INTRINSIC_OP_CASE
  5787. #undef INTRINSIC_OP_CASE_INT_FLOAT
  5788. return SpirvEvalInfo(retVal).setRValue();
  5789. }
  5790. uint32_t
  5791. SPIRVEmitter::processIntrinsicInterlockedMethod(const CallExpr *expr,
  5792. hlsl::IntrinsicOp opcode) {
  5793. // The signature of intrinsic atomic methods are:
  5794. // void Interlocked*(in R dest, in T value);
  5795. // void Interlocked*(in R dest, in T value, out T original_value);
  5796. // Note: ALL Interlocked*() methods are forced to have an unsigned integer
  5797. // 'value'. Meaning, T is forced to be 'unsigned int'. If the provided
  5798. // parameter is not an unsigned integer, the frontend inserts an
  5799. // 'ImplicitCastExpr' to convert it to unsigned integer. OpAtomicIAdd (and
  5800. // other SPIR-V OpAtomic* instructions) require that the pointee in 'dest' to
  5801. // be of the same type as T. This will result in an invalid SPIR-V if 'dest'
  5802. // is a signed integer typed resource such as RWTexture1D<int>. For example,
  5803. // the following OpAtomicIAdd is invalid because the pointee type defined in
  5804. // %1 is a signed integer, while the value passed to atomic add (%3) is an
  5805. // unsigned integer.
  5806. //
  5807. // %_ptr_Image_int = OpTypePointer Image %int
  5808. // %1 = OpImageTexelPointer %_ptr_Image_int %RWTexture1D_int %index %uint_0
  5809. // %2 = OpLoad %int %value
  5810. // %3 = OpBitcast %uint %2 <-------- Inserted by the frontend
  5811. // %4 = OpAtomicIAdd %int %1 %uint_1 %uint_0 %3
  5812. //
  5813. // In such cases, we bypass the forced IntegralCast.
  5814. // Moreover, the frontend does not add a cast AST node to cast uint to int
  5815. // where necessary. To ensure SPIR-V validity, we add that where necessary.
  5816. const uint32_t zero = theBuilder.getConstantUint32(0);
  5817. const uint32_t scope = theBuilder.getConstantUint32(1); // Device
  5818. const auto *dest = expr->getArg(0);
  5819. const auto baseType = dest->getType();
  5820. const uint32_t baseTypeId = typeTranslator.translateType(baseType);
  5821. const auto doArg = [baseType, this](const CallExpr *callExpr,
  5822. uint32_t argIndex) {
  5823. const Expr *valueExpr = callExpr->getArg(argIndex);
  5824. if (const auto *castExpr = dyn_cast<ImplicitCastExpr>(valueExpr))
  5825. if (castExpr->getCastKind() == CK_IntegralCast &&
  5826. castExpr->getSubExpr()->getType() == baseType)
  5827. valueExpr = castExpr->getSubExpr();
  5828. uint32_t argId = doExpr(valueExpr);
  5829. if (valueExpr->getType() != baseType)
  5830. argId = castToInt(argId, valueExpr->getType(), baseType,
  5831. valueExpr->getExprLoc());
  5832. return argId;
  5833. };
  5834. const auto writeToOutputArg = [&baseType, dest, this](
  5835. uint32_t toWrite, const CallExpr *callExpr,
  5836. uint32_t outputArgIndex) {
  5837. const auto outputArg = callExpr->getArg(outputArgIndex);
  5838. const auto outputArgType = outputArg->getType();
  5839. if (baseType != outputArgType)
  5840. toWrite = castToInt(toWrite, baseType, outputArgType, dest->getExprLoc());
  5841. theBuilder.createStore(doExpr(outputArg), toWrite);
  5842. };
  5843. // If the argument is indexing into a texture/buffer, we need to create an
  5844. // OpImageTexelPointer instruction.
  5845. uint32_t ptr = 0;
  5846. if (const auto *callExpr = dyn_cast<CXXOperatorCallExpr>(dest)) {
  5847. const Expr *base = nullptr;
  5848. const Expr *index = nullptr;
  5849. if (isBufferTextureIndexing(callExpr, &base, &index)) {
  5850. const auto ptrType =
  5851. theBuilder.getPointerType(baseTypeId, spv::StorageClass::Image);
  5852. auto baseId = doExpr(base);
  5853. if (baseId.isRValue()) {
  5854. // OpImageTexelPointer's Image argument must have a type of
  5855. // OpTypePointer with Type OpTypeImage. Need to create a temporary
  5856. // variable if the baseId is an rvalue.
  5857. baseId = createTemporaryVar(
  5858. base->getType(), TypeTranslator::getName(base->getType()), baseId);
  5859. }
  5860. const auto coordId = doExpr(index);
  5861. ptr = theBuilder.createImageTexelPointer(ptrType, baseId, coordId, zero);
  5862. if (baseId.isNonUniform()) {
  5863. // Image texel pointer will used to access image memory. Vulkan requires
  5864. // it to be decorated with NonUniformEXT.
  5865. theBuilder.decorate(ptr, spv::Decoration::NonUniformEXT);
  5866. }
  5867. }
  5868. }
  5869. if (!ptr)
  5870. ptr = doExpr(dest);
  5871. const bool isCompareExchange =
  5872. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareExchange;
  5873. const bool isCompareStore =
  5874. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareStore;
  5875. if (isCompareExchange || isCompareStore) {
  5876. const uint32_t comparator = doArg(expr, 1);
  5877. const uint32_t valueId = doArg(expr, 2);
  5878. const uint32_t originalVal = theBuilder.createAtomicCompareExchange(
  5879. baseTypeId, ptr, scope, zero, zero, valueId, comparator);
  5880. if (isCompareExchange)
  5881. writeToOutputArg(originalVal, expr, 3);
  5882. } else {
  5883. const uint32_t valueId = doArg(expr, 1);
  5884. // Since these atomic operations write through the provided pointer, the
  5885. // signed vs. unsigned opcode must be decided based on the pointee type
  5886. // of the first argument. However, the frontend decides the opcode based on
  5887. // the second argument (value). Therefore, the HLSL opcode provided by the
  5888. // frontend may be wrong. Therefore we need the following code to make sure
  5889. // we are using the correct SPIR-V opcode.
  5890. spv::Op atomicOp = translateAtomicHlslOpcodeToSpirvOpcode(opcode);
  5891. if (atomicOp == spv::Op::OpAtomicUMax && baseType->isSignedIntegerType())
  5892. atomicOp = spv::Op::OpAtomicSMax;
  5893. if (atomicOp == spv::Op::OpAtomicSMax && baseType->isUnsignedIntegerType())
  5894. atomicOp = spv::Op::OpAtomicUMax;
  5895. if (atomicOp == spv::Op::OpAtomicUMin && baseType->isSignedIntegerType())
  5896. atomicOp = spv::Op::OpAtomicSMin;
  5897. if (atomicOp == spv::Op::OpAtomicSMin && baseType->isUnsignedIntegerType())
  5898. atomicOp = spv::Op::OpAtomicUMin;
  5899. const uint32_t originalVal = theBuilder.createAtomicOp(
  5900. atomicOp, baseTypeId, ptr, scope, zero, valueId);
  5901. if (expr->getNumArgs() > 2)
  5902. writeToOutputArg(originalVal, expr, 2);
  5903. }
  5904. return 0;
  5905. }
  5906. SpirvEvalInfo
  5907. SPIRVEmitter::processIntrinsicNonUniformResourceIndex(const CallExpr *expr) {
  5908. foundNonUniformResourceIndex = true;
  5909. theBuilder.addExtension(Extension::EXT_descriptor_indexing,
  5910. "NonUniformResourceIndex", expr->getExprLoc());
  5911. theBuilder.requireCapability(spv::Capability::ShaderNonUniformEXT);
  5912. auto index = doExpr(expr->getArg(0)).setNonUniform();
  5913. // Decorate the expression in NonUniformResourceIndex() with NonUniformEXT.
  5914. // Aside from this, we also need to eventually populate the NonUniformEXT
  5915. // status to the usage of this expression: the "pointer" operand to a memory
  5916. // access instruction. Vulkan spec has the following rules:
  5917. //
  5918. // If an instruction loads from or stores to a resource (including atomics and
  5919. // image instructions) and the resource descriptor being accessed is not
  5920. // dynamically uniform, then the operand corresponding to that resource (e.g.
  5921. // the pointer or sampled image operand) must be decorated with NonUniformEXT.
  5922. theBuilder.decorate(index, spv::Decoration::NonUniformEXT);
  5923. return index;
  5924. }
  5925. uint32_t SPIRVEmitter::processIntrinsicMsad4(const CallExpr *callExpr) {
  5926. emitWarning("msad4 intrinsic function is emulated using many SPIR-V "
  5927. "instructions due to lack of direct SPIR-V equivalent",
  5928. callExpr->getExprLoc());
  5929. // Compares a 4-byte reference value and an 8-byte source value and
  5930. // accumulates a vector of 4 sums. Each sum corresponds to the masked sum
  5931. // of absolute differences of a different byte alignment between the
  5932. // reference value and the source value.
  5933. // If we have:
  5934. // uint v0; // reference
  5935. // uint2 v1; // source
  5936. // uint4 v2; // accum
  5937. // uint4 o0; // result of msad4
  5938. // uint4 r0, t0; // temporary values
  5939. //
  5940. // Then msad4(v0, v1, v2) translates to the following SM5 assembly according
  5941. // to fxc:
  5942. // Step 1:
  5943. // ushr r0.xyz, v1.xxxx, l(8, 16, 24, 0)
  5944. // Step 2:
  5945. // [result], [ width ], [ offset ], [ insert ], [ base ]
  5946. // bfi t0.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), v1.yyyy , r0.xxyz
  5947. // mov t0.x, v1.x
  5948. // Step 3:
  5949. // msad o0.xyzw, v0.xxxx, t0.xyzw, v2.xyzw
  5950. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  5951. const auto boolType = theBuilder.getBoolType();
  5952. const auto intType = theBuilder.getInt32Type();
  5953. const auto uintType = theBuilder.getUint32Type();
  5954. const auto uint4Type = theBuilder.getVecType(uintType, 4);
  5955. const uint32_t reference = doExpr(callExpr->getArg(0));
  5956. const uint32_t source = doExpr(callExpr->getArg(1));
  5957. const uint32_t accum = doExpr(callExpr->getArg(2));
  5958. const auto uint0 = theBuilder.getConstantUint32(0);
  5959. const auto uint8 = theBuilder.getConstantUint32(8);
  5960. const auto uint16 = theBuilder.getConstantUint32(16);
  5961. const auto uint24 = theBuilder.getConstantUint32(24);
  5962. // Step 1.
  5963. const uint32_t v1x = theBuilder.createCompositeExtract(uintType, source, {0});
  5964. // r0.x = v1xS8 = v1.x shifted by 8 bits
  5965. uint32_t v1xS8 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5966. uintType, v1x, uint8);
  5967. // r0.y = v1xS16 = v1.x shifted by 16 bits
  5968. uint32_t v1xS16 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5969. uintType, v1x, uint16);
  5970. // r0.z = v1xS24 = v1.x shifted by 24 bits
  5971. uint32_t v1xS24 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5972. uintType, v1x, uint24);
  5973. // Step 2.
  5974. // Do bfi 3 times. DXIL bfi is equivalent to SPIR-V OpBitFieldInsert.
  5975. const uint32_t v1y = theBuilder.createCompositeExtract(uintType, source, {1});
  5976. // Note that t0.x = v1.x, nothing we need to do for that.
  5977. const uint32_t t0y =
  5978. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS8, /*insert*/ v1y,
  5979. /*offset*/ uint24,
  5980. /*width*/ uint8);
  5981. const uint32_t t0z =
  5982. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS16, /*insert*/ v1y,
  5983. /*offset*/ uint16,
  5984. /*width*/ uint16);
  5985. const uint32_t t0w =
  5986. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS24, /*insert*/ v1y,
  5987. /*offset*/ uint8,
  5988. /*width*/ uint24);
  5989. // Step 3. MSAD (Masked Sum of Absolute Differences)
  5990. // Now perform MSAD four times.
  5991. // Need to mimic this algorithm in SPIR-V!
  5992. //
  5993. // UINT msad( UINT ref, UINT src, UINT accum )
  5994. // {
  5995. // for (UINT i = 0; i < 4; i++)
  5996. // {
  5997. // BYTE refByte, srcByte, absDiff;
  5998. //
  5999. // refByte = (BYTE)(ref >> (i * 8));
  6000. // if (!refByte)
  6001. // {
  6002. // continue;
  6003. // }
  6004. //
  6005. // srcByte = (BYTE)(src >> (i * 8));
  6006. // if (refByte >= srcByte)
  6007. // {
  6008. // absDiff = refByte - srcByte;
  6009. // }
  6010. // else
  6011. // {
  6012. // absDiff = srcByte - refByte;
  6013. // }
  6014. //
  6015. // // The recommended overflow behavior for MSAD is
  6016. // // to do a 32-bit saturate. This is not
  6017. // // required, however, and wrapping is allowed.
  6018. // // So from an application point of view,
  6019. // // overflow behavior is undefined.
  6020. // if (UINT_MAX - accum < absDiff)
  6021. // {
  6022. // accum = UINT_MAX;
  6023. // break;
  6024. // }
  6025. // accum += absDiff;
  6026. // }
  6027. //
  6028. // return accum;
  6029. // }
  6030. llvm::SmallVector<uint32_t, 4> result;
  6031. const uint32_t accum0 =
  6032. theBuilder.createCompositeExtract(uintType, accum, {0});
  6033. const uint32_t accum1 =
  6034. theBuilder.createCompositeExtract(uintType, accum, {1});
  6035. const uint32_t accum2 =
  6036. theBuilder.createCompositeExtract(uintType, accum, {2});
  6037. const uint32_t accum3 =
  6038. theBuilder.createCompositeExtract(uintType, accum, {3});
  6039. const llvm::SmallVector<uint32_t, 4> sources = {v1x, t0y, t0z, t0w};
  6040. llvm::SmallVector<uint32_t, 4> accums = {accum0, accum1, accum2, accum3};
  6041. llvm::SmallVector<uint32_t, 4> refBytes;
  6042. llvm::SmallVector<uint32_t, 4> signedRefBytes;
  6043. llvm::SmallVector<uint32_t, 4> isRefByteZero;
  6044. for (uint32_t i = 0; i < 4; ++i) {
  6045. refBytes.push_back(theBuilder.createBitFieldExtract(
  6046. uintType, reference, /*offset*/ theBuilder.getConstantUint32(i * 8),
  6047. /*count*/ uint8, /*isSigned*/ false));
  6048. signedRefBytes.push_back(
  6049. theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, refBytes.back()));
  6050. isRefByteZero.push_back(theBuilder.createBinaryOp(
  6051. spv::Op::OpIEqual, boolType, refBytes.back(), uint0));
  6052. }
  6053. for (uint32_t msadNum = 0; msadNum < 4; ++msadNum) {
  6054. for (uint32_t byteCount = 0; byteCount < 4; ++byteCount) {
  6055. // 'count' is always 8 because we are extracting 8 bits out of 32.
  6056. const uint32_t srcByte = theBuilder.createBitFieldExtract(
  6057. uintType, sources[msadNum],
  6058. /*offset*/ theBuilder.getConstantUint32(8 * byteCount),
  6059. /*count*/ uint8, /*isSigned*/ false);
  6060. const uint32_t signedSrcByte =
  6061. theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, srcByte);
  6062. const uint32_t sub = theBuilder.createBinaryOp(
  6063. spv::Op::OpISub, intType, signedRefBytes[byteCount], signedSrcByte);
  6064. const uint32_t absSub = theBuilder.createExtInst(
  6065. intType, glsl, GLSLstd450::GLSLstd450SAbs, {sub});
  6066. const uint32_t diff = theBuilder.createSelect(
  6067. uintType, isRefByteZero[byteCount], uint0,
  6068. theBuilder.createUnaryOp(spv::Op::OpBitcast, uintType, absSub));
  6069. // As pointed out by the DXIL reference above, it is *not* required to
  6070. // saturate the output to UINT_MAX in case of overflow. Wrapping around is
  6071. // also allowed. For simplicity, we will wrap around at this point.
  6072. accums[msadNum] = theBuilder.createBinaryOp(spv::Op::OpIAdd, uintType,
  6073. accums[msadNum], diff);
  6074. }
  6075. }
  6076. return theBuilder.createCompositeConstruct(uint4Type, accums);
  6077. }
  6078. uint32_t SPIRVEmitter::processWaveQuery(const CallExpr *callExpr,
  6079. spv::Op opcode) {
  6080. // Signatures:
  6081. // bool WaveIsFirstLane()
  6082. // uint WaveGetLaneCount()
  6083. // uint WaveGetLaneIndex()
  6084. assert(callExpr->getNumArgs() == 0);
  6085. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6086. callExpr->getExprLoc());
  6087. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  6088. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6089. const uint32_t retType =
  6090. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6091. return theBuilder.createGroupNonUniformOp(opcode, retType, subgroupScope);
  6092. }
  6093. uint32_t SPIRVEmitter::processWaveVote(const CallExpr *callExpr,
  6094. spv::Op opcode) {
  6095. // Signatures:
  6096. // bool WaveActiveAnyTrue( bool expr )
  6097. // bool WaveActiveAllTrue( bool expr )
  6098. // bool uint4 WaveActiveBallot( bool expr )
  6099. assert(callExpr->getNumArgs() == 1);
  6100. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6101. callExpr->getExprLoc());
  6102. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  6103. const uint32_t predicate = doExpr(callExpr->getArg(0));
  6104. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6105. const uint32_t retType =
  6106. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6107. return theBuilder.createGroupNonUniformUnaryOp(opcode, retType, subgroupScope,
  6108. predicate);
  6109. }
  6110. spv::Op SPIRVEmitter::translateWaveOp(hlsl::IntrinsicOp op, QualType type,
  6111. SourceLocation srcLoc) {
  6112. const bool isSintType = isSintOrVecMatOfSintType(type);
  6113. const bool isUintType = isUintOrVecMatOfUintType(type);
  6114. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  6115. #define WAVE_OP_CASE_INT(kind, intWaveOp) \
  6116. \
  6117. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6118. if (isSintType || isUintType) { \
  6119. return spv::Op::OpGroupNonUniform##intWaveOp; \
  6120. } \
  6121. } break
  6122. #define WAVE_OP_CASE_INT_FLOAT(kind, intWaveOp, floatWaveOp) \
  6123. \
  6124. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6125. if (isSintType || isUintType) { \
  6126. return spv::Op::OpGroupNonUniform##intWaveOp; \
  6127. } \
  6128. if (isFloatType) { \
  6129. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  6130. } \
  6131. } break
  6132. #define WAVE_OP_CASE_SINT_UINT_FLOAT(kind, sintWaveOp, uintWaveOp, \
  6133. floatWaveOp) \
  6134. \
  6135. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6136. if (isSintType) { \
  6137. return spv::Op::OpGroupNonUniform##sintWaveOp; \
  6138. } \
  6139. if (isUintType) { \
  6140. return spv::Op::OpGroupNonUniform##uintWaveOp; \
  6141. } \
  6142. if (isFloatType) { \
  6143. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  6144. } \
  6145. } break
  6146. switch (op) {
  6147. WAVE_OP_CASE_INT_FLOAT(ActiveUSum, IAdd, FAdd);
  6148. WAVE_OP_CASE_INT_FLOAT(ActiveSum, IAdd, FAdd);
  6149. WAVE_OP_CASE_INT_FLOAT(ActiveUProduct, IMul, FMul);
  6150. WAVE_OP_CASE_INT_FLOAT(ActiveProduct, IMul, FMul);
  6151. WAVE_OP_CASE_INT_FLOAT(PrefixUSum, IAdd, FAdd);
  6152. WAVE_OP_CASE_INT_FLOAT(PrefixSum, IAdd, FAdd);
  6153. WAVE_OP_CASE_INT_FLOAT(PrefixUProduct, IMul, FMul);
  6154. WAVE_OP_CASE_INT_FLOAT(PrefixProduct, IMul, FMul);
  6155. WAVE_OP_CASE_INT(ActiveBitAnd, BitwiseAnd);
  6156. WAVE_OP_CASE_INT(ActiveBitOr, BitwiseOr);
  6157. WAVE_OP_CASE_INT(ActiveBitXor, BitwiseXor);
  6158. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMax, SMax, UMax, FMax);
  6159. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMax, SMax, UMax, FMax);
  6160. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMin, SMin, UMin, FMin);
  6161. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMin, SMin, UMin, FMin);
  6162. }
  6163. #undef WAVE_OP_CASE_INT_FLOAT
  6164. #undef WAVE_OP_CASE_INT
  6165. #undef WAVE_OP_CASE_SINT_UINT_FLOAT
  6166. emitError("translating wave operator '%0' unimplemented", srcLoc)
  6167. << static_cast<uint32_t>(op);
  6168. return spv::Op::OpNop;
  6169. }
  6170. uint32_t SPIRVEmitter::processWaveReductionOrPrefix(
  6171. const CallExpr *callExpr, spv::Op opcode, spv::GroupOperation groupOp) {
  6172. // Signatures:
  6173. // bool WaveActiveAllEqual( <type> expr )
  6174. // uint WaveActiveCountBits( bool bBit )
  6175. // <type> WaveActiveSum( <type> expr )
  6176. // <type> WaveActiveProduct( <type> expr )
  6177. // <int_type> WaveActiveBitAnd( <int_type> expr )
  6178. // <int_type> WaveActiveBitOr( <int_type> expr )
  6179. // <int_type> WaveActiveBitXor( <int_type> expr )
  6180. // <type> WaveActiveMin( <type> expr)
  6181. // <type> WaveActiveMax( <type> expr)
  6182. //
  6183. // uint WavePrefixCountBits(Bool bBit)
  6184. // <type> WavePrefixProduct(<type> value)
  6185. // <type> WavePrefixSum(<type> value)
  6186. assert(callExpr->getNumArgs() == 1);
  6187. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6188. callExpr->getExprLoc());
  6189. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  6190. const uint32_t predicate = doExpr(callExpr->getArg(0));
  6191. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6192. const uint32_t retType =
  6193. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6194. return theBuilder.createGroupNonUniformUnaryOp(
  6195. opcode, retType, subgroupScope, predicate,
  6196. llvm::Optional<spv::GroupOperation>(groupOp));
  6197. }
  6198. uint32_t SPIRVEmitter::processWaveBroadcast(const CallExpr *callExpr) {
  6199. // Signatures:
  6200. // <type> WaveReadLaneFirst(<type> expr)
  6201. // <type> WaveReadLaneAt(<type> expr, uint laneIndex)
  6202. const auto numArgs = callExpr->getNumArgs();
  6203. assert(numArgs == 1 || numArgs == 2);
  6204. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6205. callExpr->getExprLoc());
  6206. theBuilder.requireCapability(spv::Capability::GroupNonUniformBallot);
  6207. const uint32_t value = doExpr(callExpr->getArg(0));
  6208. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6209. const uint32_t retType =
  6210. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6211. if (numArgs == 2)
  6212. return theBuilder.createGroupNonUniformBinaryOp(
  6213. spv::Op::OpGroupNonUniformBroadcast, retType, subgroupScope, value,
  6214. doExpr(callExpr->getArg(1)));
  6215. else
  6216. return theBuilder.createGroupNonUniformUnaryOp(
  6217. spv::Op::OpGroupNonUniformBroadcastFirst, retType, subgroupScope,
  6218. value);
  6219. }
  6220. uint32_t SPIRVEmitter::processWaveQuadWideShuffle(const CallExpr *callExpr,
  6221. hlsl::IntrinsicOp op) {
  6222. // Signatures:
  6223. // <type> QuadReadAcrossX(<type> localValue)
  6224. // <type> QuadReadAcrossY(<type> localValue)
  6225. // <type> QuadReadAcrossDiagonal(<type> localValue)
  6226. // <type> QuadReadLaneAt(<type> sourceValue, uint quadLaneID)
  6227. assert(callExpr->getNumArgs() == 1 || callExpr->getNumArgs() == 2);
  6228. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6229. callExpr->getExprLoc());
  6230. theBuilder.requireCapability(spv::Capability::GroupNonUniformQuad);
  6231. const uint32_t value = doExpr(callExpr->getArg(0));
  6232. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6233. const uint32_t retType =
  6234. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6235. uint32_t target = 0;
  6236. spv::Op opcode = spv::Op::OpGroupNonUniformQuadSwap;
  6237. switch (op) {
  6238. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  6239. target = theBuilder.getConstantUint32(0);
  6240. break;
  6241. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  6242. target = theBuilder.getConstantUint32(1);
  6243. break;
  6244. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  6245. target = theBuilder.getConstantUint32(2);
  6246. break;
  6247. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  6248. target = doExpr(callExpr->getArg(1));
  6249. opcode = spv::Op::OpGroupNonUniformQuadBroadcast;
  6250. break;
  6251. default:
  6252. llvm_unreachable("case should not appear here");
  6253. }
  6254. return theBuilder.createGroupNonUniformBinaryOp(opcode, retType,
  6255. subgroupScope, value, target);
  6256. }
  6257. uint32_t SPIRVEmitter::processIntrinsicModf(const CallExpr *callExpr) {
  6258. // Signature is: ret modf(x, ip)
  6259. // [in] x: the input floating-point value.
  6260. // [out] ip: the integer portion of x.
  6261. // [out] ret: the fractional portion of x.
  6262. // All of the above must be a scalar, vector, or matrix with the same
  6263. // component types. Component types can be float or int.
  6264. // The ModfStruct SPIR-V instruction returns a struct. The first member is the
  6265. // fractional part and the second member is the integer portion.
  6266. // ModfStruct {
  6267. // <scalar or vector of float> frac;
  6268. // <scalar or vector of float> ip;
  6269. // }
  6270. // Note if the input number (x) is not a float (i.e. 'x' is an int), it is
  6271. // automatically converted to float before modf is invoked. Sadly, the 'ip'
  6272. // argument is not treated the same way. Therefore, in such cases we'll have
  6273. // to manually convert the float result into int.
  6274. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6275. const Expr *arg = callExpr->getArg(0);
  6276. const Expr *ipArg = callExpr->getArg(1);
  6277. const auto argType = arg->getType();
  6278. const auto ipType = ipArg->getType();
  6279. const auto returnType = callExpr->getType();
  6280. const auto returnTypeId = typeTranslator.translateType(returnType);
  6281. const auto ipTypeId = typeTranslator.translateType(ipType);
  6282. const uint32_t argId = doExpr(arg);
  6283. const uint32_t ipId = doExpr(ipArg);
  6284. // For scalar and vector argument types.
  6285. {
  6286. if (TypeTranslator::isScalarType(argType) ||
  6287. TypeTranslator::isVectorType(argType)) {
  6288. const auto argTypeId = typeTranslator.translateType(argType);
  6289. // The struct members *must* have the same type.
  6290. const auto modfStructTypeId = theBuilder.getStructType(
  6291. {argTypeId, argTypeId}, "ModfStructType", {"frac", "ip"});
  6292. const auto modf =
  6293. theBuilder.createExtInst(modfStructTypeId, glslInstSetId,
  6294. GLSLstd450::GLSLstd450ModfStruct, {argId});
  6295. auto ip = theBuilder.createCompositeExtract(argTypeId, modf, {1});
  6296. // This will do nothing if the input number (x) and the ip are both of the
  6297. // same type. Otherwise, it will convert the ip into int as necessary.
  6298. ip = castToInt(ip, argType, ipType, arg->getExprLoc());
  6299. theBuilder.createStore(ipId, ip);
  6300. return theBuilder.createCompositeExtract(argTypeId, modf, {0});
  6301. }
  6302. }
  6303. // For matrix argument types.
  6304. {
  6305. uint32_t rowCount = 0, colCount = 0;
  6306. QualType elemType = {};
  6307. if (TypeTranslator::isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  6308. const auto elemTypeId = typeTranslator.translateType(elemType);
  6309. const auto colTypeId = theBuilder.getVecType(elemTypeId, colCount);
  6310. const auto modfStructTypeId = theBuilder.getStructType(
  6311. {colTypeId, colTypeId}, "ModfStructType", {"frac", "ip"});
  6312. llvm::SmallVector<uint32_t, 4> fracs;
  6313. llvm::SmallVector<uint32_t, 4> ips;
  6314. for (uint32_t i = 0; i < rowCount; ++i) {
  6315. const auto curRow =
  6316. theBuilder.createCompositeExtract(colTypeId, argId, {i});
  6317. const auto modf = theBuilder.createExtInst(
  6318. modfStructTypeId, glslInstSetId, GLSLstd450::GLSLstd450ModfStruct,
  6319. {curRow});
  6320. auto ip = theBuilder.createCompositeExtract(colTypeId, modf, {1});
  6321. ips.push_back(ip);
  6322. fracs.push_back(
  6323. theBuilder.createCompositeExtract(colTypeId, modf, {0}));
  6324. }
  6325. uint32_t ip = theBuilder.createCompositeConstruct(
  6326. typeTranslator.translateType(argType), ips);
  6327. // If the 'ip' is not a float type, the AST will not contain a CastExpr
  6328. // because this is internal to the intrinsic function. So, in such a
  6329. // case we need to cast manually.
  6330. if (!hlsl::GetHLSLMatElementType(ipType)->isFloatingType())
  6331. ip = castToInt(ip, argType, ipType, ipArg->getExprLoc());
  6332. theBuilder.createStore(ipId, ip);
  6333. return theBuilder.createCompositeConstruct(returnTypeId, fracs);
  6334. }
  6335. }
  6336. emitError("invalid argument type passed to Modf intrinsic function",
  6337. callExpr->getExprLoc());
  6338. return 0;
  6339. }
  6340. uint32_t SPIRVEmitter::processIntrinsicLit(const CallExpr *callExpr) {
  6341. // Signature is: float4 lit(float n_dot_l, float n_dot_h, float m)
  6342. //
  6343. // This function returns a lighting coefficient vector
  6344. // (ambient, diffuse, specular, 1) where:
  6345. // ambient = 1.
  6346. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l
  6347. // specular = (n_dot_l < 0 || n_dot_h < 0) ? 0 : ((n_dot_h) * m)
  6348. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6349. const uint32_t nDotL = doExpr(callExpr->getArg(0));
  6350. const uint32_t nDotH = doExpr(callExpr->getArg(1));
  6351. const uint32_t m = doExpr(callExpr->getArg(2));
  6352. const uint32_t floatType = theBuilder.getFloat32Type();
  6353. const uint32_t boolType = theBuilder.getBoolType();
  6354. const uint32_t floatZero = theBuilder.getConstantFloat32(0);
  6355. const uint32_t floatOne = theBuilder.getConstantFloat32(1);
  6356. const uint32_t retType = typeTranslator.translateType(callExpr->getType());
  6357. const uint32_t diffuse = theBuilder.createExtInst(
  6358. floatType, glslInstSetId, GLSLstd450::GLSLstd450FMax, {floatZero, nDotL});
  6359. const uint32_t min = theBuilder.createExtInst(
  6360. floatType, glslInstSetId, GLSLstd450::GLSLstd450FMin, {nDotL, nDotH});
  6361. const uint32_t isNeg = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6362. boolType, min, floatZero);
  6363. const uint32_t mul =
  6364. theBuilder.createBinaryOp(spv::Op::OpFMul, floatType, nDotH, m);
  6365. const uint32_t specular =
  6366. theBuilder.createSelect(floatType, isNeg, floatZero, mul);
  6367. return theBuilder.createCompositeConstruct(
  6368. retType, {floatOne, diffuse, specular, floatOne});
  6369. }
  6370. uint32_t SPIRVEmitter::processIntrinsicFrexp(const CallExpr *callExpr) {
  6371. // Signature is: ret frexp(x, exp)
  6372. // [in] x: the input floating-point value.
  6373. // [out] exp: the calculated exponent.
  6374. // [out] ret: the calculated mantissa.
  6375. // All of the above must be a scalar, vector, or matrix of *float* type.
  6376. // The FrexpStruct SPIR-V instruction returns a struct. The first
  6377. // member is the significand (mantissa) and must be of the same type as the
  6378. // input parameter, and the second member is the exponent and must always be a
  6379. // scalar or vector of 32-bit *integer* type.
  6380. // FrexpStruct {
  6381. // <scalar or vector of int/float> mantissa;
  6382. // <scalar or vector of integers> exponent;
  6383. // }
  6384. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6385. const Expr *arg = callExpr->getArg(0);
  6386. const auto argType = arg->getType();
  6387. const auto intId = theBuilder.getInt32Type();
  6388. const auto returnTypeId = typeTranslator.translateType(callExpr->getType());
  6389. const uint32_t argId = doExpr(arg);
  6390. const uint32_t expId = doExpr(callExpr->getArg(1));
  6391. // For scalar and vector argument types.
  6392. {
  6393. uint32_t elemCount = 1;
  6394. if (TypeTranslator::isScalarType(argType) ||
  6395. TypeTranslator::isVectorType(argType, nullptr, &elemCount)) {
  6396. const auto argTypeId = typeTranslator.translateType(argType);
  6397. const auto expTypeId =
  6398. elemCount == 1 ? intId : theBuilder.getVecType(intId, elemCount);
  6399. const auto frexpStructTypeId = theBuilder.getStructType(
  6400. {argTypeId, expTypeId}, "FrexpStructType", {"mantissa", "exponent"});
  6401. const auto frexp =
  6402. theBuilder.createExtInst(frexpStructTypeId, glslInstSetId,
  6403. GLSLstd450::GLSLstd450FrexpStruct, {argId});
  6404. const auto exponentInt =
  6405. theBuilder.createCompositeExtract(expTypeId, frexp, {1});
  6406. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  6407. // expects a float, an conversion must take place before writing the
  6408. // results.
  6409. const auto exponentFloat = theBuilder.createUnaryOp(
  6410. spv::Op::OpConvertSToF, returnTypeId, exponentInt);
  6411. theBuilder.createStore(expId, exponentFloat);
  6412. return theBuilder.createCompositeExtract(argTypeId, frexp, {0});
  6413. }
  6414. }
  6415. // For matrix argument types.
  6416. {
  6417. uint32_t rowCount = 0, colCount = 0;
  6418. if (TypeTranslator::isMxNMatrix(argType, nullptr, &rowCount, &colCount)) {
  6419. const auto floatId = theBuilder.getFloat32Type();
  6420. const auto expTypeId = theBuilder.getVecType(intId, colCount);
  6421. const auto colTypeId = theBuilder.getVecType(floatId, colCount);
  6422. const auto frexpStructTypeId = theBuilder.getStructType(
  6423. {colTypeId, expTypeId}, "FrexpStructType", {"mantissa", "exponent"});
  6424. llvm::SmallVector<uint32_t, 4> exponents;
  6425. llvm::SmallVector<uint32_t, 4> mantissas;
  6426. for (uint32_t i = 0; i < rowCount; ++i) {
  6427. const auto curRow =
  6428. theBuilder.createCompositeExtract(colTypeId, argId, {i});
  6429. const auto frexp = theBuilder.createExtInst(
  6430. frexpStructTypeId, glslInstSetId, GLSLstd450::GLSLstd450FrexpStruct,
  6431. {curRow});
  6432. const auto exponentInt =
  6433. theBuilder.createCompositeExtract(expTypeId, frexp, {1});
  6434. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  6435. // expects a float, an conversion must take place before writing the
  6436. // results.
  6437. const auto exponentFloat = theBuilder.createUnaryOp(
  6438. spv::Op::OpConvertSToF, colTypeId, exponentInt);
  6439. exponents.push_back(exponentFloat);
  6440. mantissas.push_back(
  6441. theBuilder.createCompositeExtract(colTypeId, frexp, {0}));
  6442. }
  6443. const auto exponentsResultId =
  6444. theBuilder.createCompositeConstruct(returnTypeId, exponents);
  6445. theBuilder.createStore(expId, exponentsResultId);
  6446. return theBuilder.createCompositeConstruct(returnTypeId, mantissas);
  6447. }
  6448. }
  6449. emitError("invalid argument type passed to Frexp intrinsic function",
  6450. callExpr->getExprLoc());
  6451. return 0;
  6452. }
  6453. uint32_t SPIRVEmitter::processIntrinsicLdexp(const CallExpr *callExpr) {
  6454. // Signature: ret ldexp(x, exp)
  6455. // This function uses the following formula: x * 2^exp.
  6456. // Note that we cannot use GLSL extended instruction Ldexp since it requires
  6457. // the exponent to be an integer (vector) but HLSL takes an float (vector)
  6458. // exponent. So we must calculate the result manually.
  6459. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  6460. const Expr *x = callExpr->getArg(0);
  6461. const auto paramType = x->getType();
  6462. const uint32_t xId = doExpr(x);
  6463. const uint32_t expId = doExpr(callExpr->getArg(1));
  6464. // For scalar and vector argument types.
  6465. if (TypeTranslator::isScalarType(paramType) ||
  6466. TypeTranslator::isVectorType(paramType)) {
  6467. const auto paramTypeId = typeTranslator.translateType(paramType);
  6468. const auto twoExp = theBuilder.createExtInst(
  6469. paramTypeId, glsl, GLSLstd450::GLSLstd450Exp2, {expId});
  6470. return theBuilder.createBinaryOp(spv::Op::OpFMul, paramTypeId, xId, twoExp);
  6471. }
  6472. // For matrix argument types.
  6473. {
  6474. uint32_t rowCount = 0, colCount = 0;
  6475. if (TypeTranslator::isMxNMatrix(paramType, nullptr, &rowCount, &colCount)) {
  6476. const auto actOnEachVec = [this, glsl, expId](uint32_t index,
  6477. uint32_t vecType,
  6478. uint32_t xRowId) {
  6479. const auto expRowId =
  6480. theBuilder.createCompositeExtract(vecType, expId, {index});
  6481. const auto twoExp = theBuilder.createExtInst(
  6482. vecType, glsl, GLSLstd450::GLSLstd450Exp2, {expRowId});
  6483. return theBuilder.createBinaryOp(spv::Op::OpFMul, vecType, xRowId,
  6484. twoExp);
  6485. };
  6486. return processEachVectorInMatrix(x, xId, actOnEachVec);
  6487. }
  6488. }
  6489. emitError("invalid argument type passed to ldexp intrinsic function",
  6490. callExpr->getExprLoc());
  6491. return 0;
  6492. }
  6493. uint32_t SPIRVEmitter::processIntrinsicDst(const CallExpr *callExpr) {
  6494. // Signature is float4 dst(float4 src0, float4 src1)
  6495. // result.x = 1;
  6496. // result.y = src0.y * src1.y;
  6497. // result.z = src0.z;
  6498. // result.w = src1.w;
  6499. const auto floatId = theBuilder.getFloat32Type();
  6500. const auto arg0Id = doExpr(callExpr->getArg(0));
  6501. const auto arg1Id = doExpr(callExpr->getArg(1));
  6502. const auto arg0y = theBuilder.createCompositeExtract(floatId, arg0Id, {1});
  6503. const auto arg1y = theBuilder.createCompositeExtract(floatId, arg1Id, {1});
  6504. const auto arg0z = theBuilder.createCompositeExtract(floatId, arg0Id, {2});
  6505. const auto arg1w = theBuilder.createCompositeExtract(floatId, arg1Id, {3});
  6506. const auto arg0yMularg1y =
  6507. theBuilder.createBinaryOp(spv::Op::OpFMul, floatId, arg0y, arg1y);
  6508. return theBuilder.createCompositeConstruct(
  6509. typeTranslator.translateType(callExpr->getType()),
  6510. {theBuilder.getConstantFloat32(1.0), arg0yMularg1y, arg0z, arg1w});
  6511. }
  6512. uint32_t SPIRVEmitter::processIntrinsicClip(const CallExpr *callExpr) {
  6513. // Discards the current pixel if the specified value is less than zero.
  6514. // TODO: If the argument can be const folded and evaluated, we could
  6515. // potentially avoid creating a branch. This would be a bit challenging for
  6516. // matrix/vector arguments.
  6517. assert(callExpr->getNumArgs() == 1u);
  6518. const Expr *arg = callExpr->getArg(0);
  6519. const auto argType = arg->getType();
  6520. const auto boolType = theBuilder.getBoolType();
  6521. uint32_t condition = 0;
  6522. // Could not determine the argument as a constant. We need to branch based on
  6523. // the argument. If the argument is a vector/matrix, clipping is done if *any*
  6524. // element of the vector/matrix is less than zero.
  6525. const uint32_t argId = doExpr(arg);
  6526. QualType elemType = {};
  6527. uint32_t elemCount = 0, rowCount = 0, colCount = 0;
  6528. if (TypeTranslator::isScalarType(argType)) {
  6529. const auto zero = getValueZero(argType);
  6530. condition = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  6531. argId, zero);
  6532. } else if (TypeTranslator::isVectorType(argType, nullptr, &elemCount)) {
  6533. const auto zero = getValueZero(argType);
  6534. const auto boolVecType = theBuilder.getVecType(boolType, elemCount);
  6535. const auto cmp = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6536. boolVecType, argId, zero);
  6537. condition = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp);
  6538. } else if (TypeTranslator::isMxNMatrix(argType, &elemType, &rowCount,
  6539. &colCount)) {
  6540. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  6541. const uint32_t floatVecType = theBuilder.getVecType(elemTypeId, colCount);
  6542. const uint32_t elemZeroId = getValueZero(elemType);
  6543. llvm::SmallVector<uint32_t, 4> elements(size_t(colCount), elemZeroId);
  6544. const auto zero = theBuilder.getConstantComposite(floatVecType, elements);
  6545. llvm::SmallVector<uint32_t, 4> cmpResults;
  6546. for (uint32_t i = 0; i < rowCount; ++i) {
  6547. const uint32_t lhsVec =
  6548. theBuilder.createCompositeExtract(floatVecType, argId, {i});
  6549. const auto boolColType = theBuilder.getVecType(boolType, colCount);
  6550. const auto cmp = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6551. boolColType, lhsVec, zero);
  6552. const auto any = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp);
  6553. cmpResults.push_back(any);
  6554. }
  6555. const auto boolRowType = theBuilder.getVecType(boolType, rowCount);
  6556. const auto results =
  6557. theBuilder.createCompositeConstruct(boolRowType, cmpResults);
  6558. condition = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, results);
  6559. } else {
  6560. emitError("invalid argument type passed to clip intrinsic function",
  6561. callExpr->getExprLoc());
  6562. return 0;
  6563. }
  6564. // Then we need to emit the instruction for the conditional branch.
  6565. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  6566. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  6567. // Create the branch instruction. This will end the current basic block.
  6568. theBuilder.createConditionalBranch(condition, thenBB, mergeBB, mergeBB);
  6569. theBuilder.addSuccessor(thenBB);
  6570. theBuilder.addSuccessor(mergeBB);
  6571. theBuilder.setMergeTarget(mergeBB);
  6572. // Handle the then branch
  6573. theBuilder.setInsertPoint(thenBB);
  6574. theBuilder.createKill();
  6575. theBuilder.addSuccessor(mergeBB);
  6576. // From now on, we'll emit instructions into the merge block.
  6577. theBuilder.setInsertPoint(mergeBB);
  6578. return 0;
  6579. }
  6580. uint32_t SPIRVEmitter::processIntrinsicClamp(const CallExpr *callExpr) {
  6581. // According the HLSL reference: clamp(X, Min, Max) takes 3 arguments. Each
  6582. // one may be int, uint, or float.
  6583. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6584. const QualType returnType = callExpr->getType();
  6585. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  6586. GLSLstd450 glslOpcode = GLSLstd450::GLSLstd450UClamp;
  6587. if (isFloatOrVecMatOfFloatType(returnType))
  6588. glslOpcode = GLSLstd450::GLSLstd450FClamp;
  6589. else if (isSintOrVecMatOfSintType(returnType))
  6590. glslOpcode = GLSLstd450::GLSLstd450SClamp;
  6591. // Get the function parameters. Expect 3 parameters.
  6592. assert(callExpr->getNumArgs() == 3u);
  6593. const Expr *argX = callExpr->getArg(0);
  6594. const Expr *argMin = callExpr->getArg(1);
  6595. const Expr *argMax = callExpr->getArg(2);
  6596. const uint32_t argXId = doExpr(argX);
  6597. const uint32_t argMinId = doExpr(argMin);
  6598. const uint32_t argMaxId = doExpr(argMax);
  6599. // FClamp, UClamp, and SClamp do not operate on matrices, so we should perform
  6600. // the operation on each vector of the matrix.
  6601. if (TypeTranslator::isMxNMatrix(argX->getType())) {
  6602. const auto actOnEachVec = [this, glslInstSetId, glslOpcode, argMinId,
  6603. argMaxId](uint32_t index, uint32_t vecType,
  6604. uint32_t curRowId) {
  6605. const auto minRowId =
  6606. theBuilder.createCompositeExtract(vecType, argMinId, {index});
  6607. const auto maxRowId =
  6608. theBuilder.createCompositeExtract(vecType, argMaxId, {index});
  6609. return theBuilder.createExtInst(vecType, glslInstSetId, glslOpcode,
  6610. {curRowId, minRowId, maxRowId});
  6611. };
  6612. return processEachVectorInMatrix(argX, argXId, actOnEachVec);
  6613. }
  6614. return theBuilder.createExtInst(returnTypeId, glslInstSetId, glslOpcode,
  6615. {argXId, argMinId, argMaxId});
  6616. }
  6617. uint32_t SPIRVEmitter::processIntrinsicMemoryBarrier(const CallExpr *callExpr,
  6618. bool isDevice,
  6619. bool groupSync,
  6620. bool isAllBarrier) {
  6621. // * DeviceMemoryBarrier =
  6622. // OpMemoryBarrier (memScope=Device,
  6623. // sem=Image|Uniform|AcquireRelease)
  6624. //
  6625. // * DeviceMemoryBarrierWithGroupSync =
  6626. // OpControlBarrier(execScope = Workgroup,
  6627. // memScope=Device,
  6628. // sem=Image|Uniform|AcquireRelease)
  6629. const spv::MemorySemanticsMask deviceMemoryBarrierSema =
  6630. spv::MemorySemanticsMask::ImageMemory |
  6631. spv::MemorySemanticsMask::UniformMemory |
  6632. spv::MemorySemanticsMask::AcquireRelease;
  6633. // * GroupMemoryBarrier =
  6634. // OpMemoryBarrier (memScope=Workgroup,
  6635. // sem = Workgroup|AcquireRelease)
  6636. //
  6637. // * GroupMemoryBarrierWithGroupSync =
  6638. // OpControlBarrier (execScope = Workgroup,
  6639. // memScope = Workgroup,
  6640. // sem = Workgroup|AcquireRelease)
  6641. const spv::MemorySemanticsMask groupMemoryBarrierSema =
  6642. spv::MemorySemanticsMask::WorkgroupMemory |
  6643. spv::MemorySemanticsMask::AcquireRelease;
  6644. // * AllMemoryBarrier =
  6645. // OpMemoryBarrier(memScope = Device,
  6646. // sem = Image|Uniform|Workgroup|AcquireRelease)
  6647. //
  6648. // * AllMemoryBarrierWithGroupSync =
  6649. // OpControlBarrier(execScope = Workgroup,
  6650. // memScope = Device,
  6651. // sem = Image|Uniform|Workgroup|AcquireRelease)
  6652. const spv::MemorySemanticsMask allMemoryBarrierSema =
  6653. spv::MemorySemanticsMask::ImageMemory |
  6654. spv::MemorySemanticsMask::UniformMemory |
  6655. spv::MemorySemanticsMask::WorkgroupMemory |
  6656. spv::MemorySemanticsMask::AtomicCounterMemory |
  6657. spv::MemorySemanticsMask::AcquireRelease;
  6658. // Get <result-id> for execution scope.
  6659. // If present, execution scope is always Workgroup!
  6660. const uint32_t execScopeId =
  6661. groupSync ? theBuilder.getConstantUint32(
  6662. static_cast<uint32_t>(spv::Scope::Workgroup))
  6663. : 0;
  6664. // Get <result-id> for memory scope
  6665. const spv::Scope memScope =
  6666. (isDevice || isAllBarrier) ? spv::Scope::Device : spv::Scope::Workgroup;
  6667. const uint32_t memScopeId =
  6668. theBuilder.getConstantUint32(static_cast<uint32_t>(memScope));
  6669. // Get <result-id> for memory semantics
  6670. const auto memSemaMask = isAllBarrier ? allMemoryBarrierSema
  6671. : isDevice ? deviceMemoryBarrierSema
  6672. : groupMemoryBarrierSema;
  6673. const uint32_t memSema =
  6674. theBuilder.getConstantUint32(static_cast<uint32_t>(memSemaMask));
  6675. theBuilder.createBarrier(execScopeId, memScopeId, memSema);
  6676. return 0;
  6677. }
  6678. uint32_t SPIRVEmitter::processNonFpMatrixTranspose(QualType matType,
  6679. uint32_t matId) {
  6680. // Simplest way is to flatten the matrix construct a new matrix from the
  6681. // flattened elements. (for a mat4x4).
  6682. QualType elemType = {};
  6683. uint32_t numRows = 0, numCols = 0;
  6684. const bool isMat =
  6685. TypeTranslator::isMxNMatrix(matType, &elemType, &numRows, &numCols);
  6686. assert(isMat && !elemType->isFloatingType());
  6687. const auto rowQualType = astContext.getExtVectorType(elemType, numCols);
  6688. const auto colQualType = astContext.getExtVectorType(elemType, numRows);
  6689. const uint32_t rowTypeId = typeTranslator.translateType(rowQualType);
  6690. const uint32_t colTypeId = typeTranslator.translateType(colQualType);
  6691. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  6692. // You cannot perform a composite construct of an array using a few vectors.
  6693. // The number of constutients passed to OpCompositeConstruct must be equal to
  6694. // the number of array elements.
  6695. llvm::SmallVector<uint32_t, 4> elems;
  6696. for (uint32_t i = 0; i < numRows; ++i)
  6697. for (uint32_t j = 0; j < numCols; ++j)
  6698. elems.push_back(
  6699. theBuilder.createCompositeExtract(elemTypeId, matId, {i, j}));
  6700. llvm::SmallVector<uint32_t, 4> cols;
  6701. for (uint32_t i = 0; i < numCols; ++i) {
  6702. // The elements in the ith vector of the "transposed" array are at offset i,
  6703. // i + <original-vector-size>, ...
  6704. llvm::SmallVector<uint32_t, 4> indexes;
  6705. for (uint32_t j = 0; j < numRows; ++j)
  6706. indexes.push_back(elems[i + (j * numCols)]);
  6707. cols.push_back(theBuilder.createCompositeConstruct(colTypeId, indexes));
  6708. }
  6709. const auto transposeTypeId =
  6710. theBuilder.getArrayType(colTypeId, theBuilder.getConstantUint32(numCols));
  6711. return theBuilder.createCompositeConstruct(transposeTypeId, cols);
  6712. }
  6713. uint32_t SPIRVEmitter::processNonFpDot(uint32_t vec1Id, uint32_t vec2Id,
  6714. uint32_t vecSize, QualType elemType) {
  6715. const auto elemTypeId = typeTranslator.translateType(elemType);
  6716. llvm::SmallVector<uint32_t, 4> muls;
  6717. for (uint32_t i = 0; i < vecSize; ++i) {
  6718. const auto elem1 =
  6719. theBuilder.createCompositeExtract(elemTypeId, vec1Id, {i});
  6720. const auto elem2 =
  6721. theBuilder.createCompositeExtract(elemTypeId, vec2Id, {i});
  6722. muls.push_back(theBuilder.createBinaryOp(translateOp(BO_Mul, elemType),
  6723. elemTypeId, elem1, elem2));
  6724. }
  6725. uint32_t sum = muls[0];
  6726. for (uint32_t i = 1; i < vecSize; ++i) {
  6727. sum = theBuilder.createBinaryOp(translateOp(BO_Add, elemType), elemTypeId,
  6728. sum, muls[i]);
  6729. }
  6730. return sum;
  6731. }
  6732. uint32_t SPIRVEmitter::processNonFpScalarTimesMatrix(QualType scalarType,
  6733. uint32_t scalarId,
  6734. QualType matrixType,
  6735. uint32_t matrixId) {
  6736. assert(TypeTranslator::isScalarType(scalarType));
  6737. QualType elemType = {};
  6738. uint32_t numRows = 0, numCols = 0;
  6739. const bool isMat =
  6740. TypeTranslator::isMxNMatrix(matrixType, &elemType, &numRows, &numCols);
  6741. assert(isMat);
  6742. assert(typeTranslator.isSameType(scalarType, elemType));
  6743. // We need to multiply the scalar by each vector of the matrix.
  6744. // The front-end guarantees that the scalar and matrix element type are
  6745. // the same. For example, if the scalar is a float, the matrix is casted
  6746. // to a float matrix before being passed to mul(). It is also guaranteed
  6747. // that types such as bool are casted to float or int before being
  6748. // passed to mul().
  6749. const auto rowType = astContext.getExtVectorType(elemType, numCols);
  6750. const auto rowTypeId = typeTranslator.translateType(rowType);
  6751. llvm::SmallVector<uint32_t, 4> splat(size_t(numCols), scalarId);
  6752. const auto scalarSplat =
  6753. theBuilder.createCompositeConstruct(rowTypeId, splat);
  6754. llvm::SmallVector<uint32_t, 4> mulRows;
  6755. for (uint32_t row = 0; row < numRows; ++row) {
  6756. const auto rowId =
  6757. theBuilder.createCompositeExtract(rowTypeId, matrixId, {row});
  6758. mulRows.push_back(theBuilder.createBinaryOp(translateOp(BO_Mul, scalarType),
  6759. rowTypeId, rowId, scalarSplat));
  6760. }
  6761. return theBuilder.createCompositeConstruct(
  6762. typeTranslator.translateType(matrixType), mulRows);
  6763. }
  6764. uint32_t SPIRVEmitter::processNonFpVectorTimesMatrix(QualType vecType,
  6765. uint32_t vecId,
  6766. QualType matType,
  6767. uint32_t matId,
  6768. uint32_t matTransposeId) {
  6769. // This function assumes that the vector element type and matrix elemet type
  6770. // are the same.
  6771. QualType vecElemType = {}, matElemType = {};
  6772. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  6773. const bool isVec =
  6774. TypeTranslator::isVectorType(vecType, &vecElemType, &vecSize);
  6775. const bool isMat =
  6776. TypeTranslator::isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  6777. assert(typeTranslator.isSameType(vecElemType, matElemType));
  6778. assert(isVec);
  6779. assert(isMat);
  6780. assert(vecSize == numRows);
  6781. // When processing vector times matrix, the vector is a row vector, and it
  6782. // should be multiplied by the matrix *columns*. The most efficient way to
  6783. // handle this in SPIR-V would be to first transpose the matrix, and then use
  6784. // OpAccessChain.
  6785. if (!matTransposeId)
  6786. matTransposeId = processNonFpMatrixTranspose(matType, matId);
  6787. const auto vecTypeId = typeTranslator.translateType(vecType);
  6788. llvm::SmallVector<uint32_t, 4> resultElems;
  6789. for (uint32_t col = 0; col < numCols; ++col) {
  6790. const auto colId =
  6791. theBuilder.createCompositeExtract(vecTypeId, matTransposeId, {col});
  6792. resultElems.push_back(processNonFpDot(vecId, colId, vecSize, vecElemType));
  6793. }
  6794. return theBuilder.createCompositeConstruct(
  6795. typeTranslator.translateType(
  6796. astContext.getExtVectorType(vecElemType, numCols)),
  6797. resultElems);
  6798. }
  6799. uint32_t SPIRVEmitter::processNonFpMatrixTimesVector(QualType matType,
  6800. uint32_t matId,
  6801. QualType vecType,
  6802. uint32_t vecId) {
  6803. // This function assumes that the vector element type and matrix elemet type
  6804. // are the same.
  6805. QualType vecElemType = {}, matElemType = {};
  6806. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  6807. const bool isVec =
  6808. TypeTranslator::isVectorType(vecType, &vecElemType, &vecSize);
  6809. const bool isMat =
  6810. TypeTranslator::isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  6811. assert(typeTranslator.isSameType(vecElemType, matElemType));
  6812. assert(isVec);
  6813. assert(isMat);
  6814. assert(vecSize == numCols);
  6815. // When processing matrix times vector, the vector is a column vector. So we
  6816. // simply get each row of the matrix and perform a dot product with the
  6817. // vector.
  6818. const auto vecTypeId = typeTranslator.translateType(vecType);
  6819. llvm::SmallVector<uint32_t, 4> resultElems;
  6820. for (uint32_t row = 0; row < numRows; ++row) {
  6821. const auto rowId =
  6822. theBuilder.createCompositeExtract(vecTypeId, matId, {row});
  6823. resultElems.push_back(processNonFpDot(rowId, vecId, vecSize, vecElemType));
  6824. }
  6825. return theBuilder.createCompositeConstruct(
  6826. typeTranslator.translateType(
  6827. astContext.getExtVectorType(vecElemType, numRows)),
  6828. resultElems);
  6829. }
  6830. uint32_t SPIRVEmitter::processNonFpMatrixTimesMatrix(QualType lhsType,
  6831. uint32_t lhsId,
  6832. QualType rhsType,
  6833. uint32_t rhsId) {
  6834. // This function assumes that the vector element type and matrix elemet type
  6835. // are the same.
  6836. QualType lhsElemType = {}, rhsElemType = {};
  6837. uint32_t lhsNumRows = 0, lhsNumCols = 0;
  6838. uint32_t rhsNumRows = 0, rhsNumCols = 0;
  6839. const bool lhsIsMat = TypeTranslator::isMxNMatrix(lhsType, &lhsElemType,
  6840. &lhsNumRows, &lhsNumCols);
  6841. const bool rhsIsMat = TypeTranslator::isMxNMatrix(rhsType, &rhsElemType,
  6842. &rhsNumRows, &rhsNumCols);
  6843. assert(typeTranslator.isSameType(lhsElemType, rhsElemType));
  6844. assert(lhsIsMat && rhsIsMat);
  6845. assert(lhsNumCols == rhsNumRows);
  6846. const uint32_t rhsTranspose = processNonFpMatrixTranspose(rhsType, rhsId);
  6847. const auto vecType = astContext.getExtVectorType(lhsElemType, lhsNumCols);
  6848. const auto vecTypeId = typeTranslator.translateType(vecType);
  6849. llvm::SmallVector<uint32_t, 4> resultRows;
  6850. for (uint32_t row = 0; row < lhsNumRows; ++row) {
  6851. const auto rowId =
  6852. theBuilder.createCompositeExtract(vecTypeId, lhsId, {row});
  6853. resultRows.push_back(processNonFpVectorTimesMatrix(vecType, rowId, rhsType,
  6854. rhsId, rhsTranspose));
  6855. }
  6856. // The resulting matrix will have 'lhsNumRows' rows and 'rhsNumCols' columns.
  6857. const auto elemTypeId = typeTranslator.translateType(lhsElemType);
  6858. const auto resultNumRows = theBuilder.getConstantUint32(lhsNumRows);
  6859. const auto resultColType = theBuilder.getVecType(elemTypeId, rhsNumCols);
  6860. const auto resultType = theBuilder.getArrayType(resultColType, resultNumRows);
  6861. return theBuilder.createCompositeConstruct(resultType, resultRows);
  6862. }
  6863. uint32_t SPIRVEmitter::processIntrinsicMul(const CallExpr *callExpr) {
  6864. const QualType returnType = callExpr->getType();
  6865. const uint32_t returnTypeId =
  6866. typeTranslator.translateType(callExpr->getType());
  6867. // Get the function parameters. Expect 2 parameters.
  6868. assert(callExpr->getNumArgs() == 2u);
  6869. const Expr *arg0 = callExpr->getArg(0);
  6870. const Expr *arg1 = callExpr->getArg(1);
  6871. const QualType arg0Type = arg0->getType();
  6872. const QualType arg1Type = arg1->getType();
  6873. // The HLSL mul() function takes 2 arguments. Each argument may be a scalar,
  6874. // vector, or matrix. The frontend ensures that the two arguments have the
  6875. // same component type. The only allowed component types are int and float.
  6876. // mul(scalar, vector)
  6877. {
  6878. uint32_t elemCount = 0;
  6879. if (TypeTranslator::isScalarType(arg0Type) &&
  6880. TypeTranslator::isVectorType(arg1Type, nullptr, &elemCount)) {
  6881. const uint32_t arg1Id = doExpr(arg1);
  6882. // We can use OpVectorTimesScalar if arguments are floats.
  6883. if (arg0Type->isFloatingType())
  6884. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  6885. returnTypeId, arg1Id, doExpr(arg0));
  6886. // Use OpIMul for integers
  6887. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId,
  6888. createVectorSplat(arg0, elemCount),
  6889. arg1Id);
  6890. }
  6891. }
  6892. // mul(vector, scalar)
  6893. {
  6894. uint32_t elemCount = 0;
  6895. if (TypeTranslator::isVectorType(arg0Type, nullptr, &elemCount) &&
  6896. TypeTranslator::isScalarType(arg1Type)) {
  6897. const uint32_t arg0Id = doExpr(arg0);
  6898. // We can use OpVectorTimesScalar if arguments are floats.
  6899. if (arg1Type->isFloatingType())
  6900. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  6901. returnTypeId, arg0Id, doExpr(arg1));
  6902. // Use OpIMul for integers
  6903. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId, arg0Id,
  6904. createVectorSplat(arg1, elemCount));
  6905. }
  6906. }
  6907. // mul(vector, vector)
  6908. if (TypeTranslator::isVectorType(arg0Type) &&
  6909. TypeTranslator::isVectorType(arg1Type))
  6910. return processIntrinsicDot(callExpr);
  6911. // All the following cases require handling arg0 and arg1 expressions first.
  6912. const uint32_t arg0Id = doExpr(arg0);
  6913. const uint32_t arg1Id = doExpr(arg1);
  6914. // mul(scalar, scalar)
  6915. if (TypeTranslator::isScalarType(arg0Type) &&
  6916. TypeTranslator::isScalarType(arg1Type))
  6917. return theBuilder.createBinaryOp(translateOp(BO_Mul, arg0Type),
  6918. returnTypeId, arg0Id, arg1Id);
  6919. // mul(scalar, matrix)
  6920. {
  6921. QualType elemType = {};
  6922. if (TypeTranslator::isScalarType(arg0Type) &&
  6923. TypeTranslator::isMxNMatrix(arg1Type, &elemType)) {
  6924. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  6925. // and the scalar type are float.
  6926. if (arg0Type->isFloatingType() && elemType->isFloatingType())
  6927. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  6928. returnTypeId, arg1Id, arg0Id);
  6929. else
  6930. return processNonFpScalarTimesMatrix(arg0Type, arg0Id, arg1Type,
  6931. arg1Id);
  6932. }
  6933. }
  6934. // mul(matrix, scalar)
  6935. {
  6936. QualType elemType = {};
  6937. if (TypeTranslator::isScalarType(arg1Type) &&
  6938. TypeTranslator::isMxNMatrix(arg0Type, &elemType)) {
  6939. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  6940. // and the scalar type are float.
  6941. if (arg1Type->isFloatingType() && elemType->isFloatingType())
  6942. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  6943. returnTypeId, arg0Id, arg1Id);
  6944. else
  6945. return processNonFpScalarTimesMatrix(arg1Type, arg1Id, arg0Type,
  6946. arg0Id);
  6947. }
  6948. }
  6949. // mul(vector, matrix)
  6950. {
  6951. QualType vecElemType = {}, matElemType = {};
  6952. uint32_t elemCount = 0, numRows = 0;
  6953. if (TypeTranslator::isVectorType(arg0Type, &vecElemType, &elemCount) &&
  6954. TypeTranslator::isMxNMatrix(arg1Type, &matElemType, &numRows)) {
  6955. assert(elemCount == numRows);
  6956. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  6957. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesVector,
  6958. returnTypeId, arg1Id, arg0Id);
  6959. else
  6960. return processNonFpVectorTimesMatrix(arg0Type, arg0Id, arg1Type,
  6961. arg1Id);
  6962. }
  6963. }
  6964. // mul(matrix, vector)
  6965. {
  6966. QualType vecElemType = {}, matElemType = {};
  6967. uint32_t elemCount = 0, numCols = 0;
  6968. if (TypeTranslator::isMxNMatrix(arg0Type, &matElemType, nullptr,
  6969. &numCols) &&
  6970. TypeTranslator::isVectorType(arg1Type, &vecElemType, &elemCount)) {
  6971. assert(elemCount == numCols);
  6972. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  6973. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesMatrix,
  6974. returnTypeId, arg1Id, arg0Id);
  6975. else
  6976. return processNonFpMatrixTimesVector(arg0Type, arg0Id, arg1Type,
  6977. arg1Id);
  6978. }
  6979. }
  6980. // mul(matrix, matrix)
  6981. {
  6982. // The front-end ensures that the two matrix element types match.
  6983. QualType elemType = {};
  6984. uint32_t lhsCols = 0, rhsRows = 0;
  6985. if (TypeTranslator::isMxNMatrix(arg0Type, &elemType, nullptr, &lhsCols) &&
  6986. TypeTranslator::isMxNMatrix(arg1Type, nullptr, &rhsRows, nullptr)) {
  6987. assert(lhsCols == rhsRows);
  6988. if (elemType->isFloatingType())
  6989. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesMatrix,
  6990. returnTypeId, arg1Id, arg0Id);
  6991. else
  6992. return processNonFpMatrixTimesMatrix(arg0Type, arg0Id, arg1Type,
  6993. arg1Id);
  6994. }
  6995. }
  6996. emitError("invalid argument type passed to mul intrinsic function",
  6997. callExpr->getExprLoc());
  6998. return 0;
  6999. }
  7000. uint32_t SPIRVEmitter::processIntrinsicDot(const CallExpr *callExpr) {
  7001. const QualType returnType = callExpr->getType();
  7002. const uint32_t returnTypeId =
  7003. typeTranslator.translateType(callExpr->getType());
  7004. // Get the function parameters. Expect 2 vectors as parameters.
  7005. assert(callExpr->getNumArgs() == 2u);
  7006. const Expr *arg0 = callExpr->getArg(0);
  7007. const Expr *arg1 = callExpr->getArg(1);
  7008. const uint32_t arg0Id = doExpr(arg0);
  7009. const uint32_t arg1Id = doExpr(arg1);
  7010. QualType arg0Type = arg0->getType();
  7011. QualType arg1Type = arg1->getType();
  7012. const size_t vec0Size = hlsl::GetHLSLVecSize(arg0Type);
  7013. const size_t vec1Size = hlsl::GetHLSLVecSize(arg1Type);
  7014. const QualType vec0ComponentType = hlsl::GetHLSLVecElementType(arg0Type);
  7015. const QualType vec1ComponentType = hlsl::GetHLSLVecElementType(arg1Type);
  7016. assert(returnType == vec1ComponentType);
  7017. assert(vec0ComponentType == vec1ComponentType);
  7018. assert(vec0Size == vec1Size);
  7019. assert(vec0Size >= 1 && vec0Size <= 4);
  7020. // According to HLSL reference, the dot function only works on integers
  7021. // and floats.
  7022. assert(returnType->isFloatingType() || returnType->isIntegerType());
  7023. // Special case: dot product of two vectors, each of size 1. That is
  7024. // basically the same as regular multiplication of 2 scalars.
  7025. if (vec0Size == 1) {
  7026. const spv::Op spvOp = translateOp(BO_Mul, arg0Type);
  7027. return theBuilder.createBinaryOp(spvOp, returnTypeId, arg0Id, arg1Id);
  7028. }
  7029. // If the vectors are of type Float, we can use OpDot.
  7030. if (returnType->isFloatingType()) {
  7031. return theBuilder.createBinaryOp(spv::Op::OpDot, returnTypeId, arg0Id,
  7032. arg1Id);
  7033. }
  7034. // Vector component type is Integer (signed or unsigned).
  7035. // Create all instructions necessary to perform a dot product on
  7036. // two integer vectors. SPIR-V OpDot does not support integer vectors.
  7037. // Therefore, we use other SPIR-V instructions (addition and
  7038. // multiplication).
  7039. else {
  7040. uint32_t result = 0;
  7041. llvm::SmallVector<uint32_t, 4> multIds;
  7042. const spv::Op multSpvOp = translateOp(BO_Mul, arg0Type);
  7043. const spv::Op addSpvOp = translateOp(BO_Add, arg0Type);
  7044. // Extract members from the two vectors and multiply them.
  7045. for (unsigned int i = 0; i < vec0Size; ++i) {
  7046. const uint32_t vec0member =
  7047. theBuilder.createCompositeExtract(returnTypeId, arg0Id, {i});
  7048. const uint32_t vec1member =
  7049. theBuilder.createCompositeExtract(returnTypeId, arg1Id, {i});
  7050. const uint32_t multId = theBuilder.createBinaryOp(multSpvOp, returnTypeId,
  7051. vec0member, vec1member);
  7052. multIds.push_back(multId);
  7053. }
  7054. // Add all the multiplications.
  7055. result = multIds[0];
  7056. for (unsigned int i = 1; i < vec0Size; ++i) {
  7057. const uint32_t additionId =
  7058. theBuilder.createBinaryOp(addSpvOp, returnTypeId, result, multIds[i]);
  7059. result = additionId;
  7060. }
  7061. return result;
  7062. }
  7063. }
  7064. uint32_t SPIRVEmitter::processIntrinsicRcp(const CallExpr *callExpr) {
  7065. // 'rcp' takes only 1 argument that is a scalar, vector, or matrix of type
  7066. // float or double.
  7067. assert(callExpr->getNumArgs() == 1u);
  7068. const QualType returnType = callExpr->getType();
  7069. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  7070. const Expr *arg = callExpr->getArg(0);
  7071. const uint32_t argId = doExpr(arg);
  7072. const QualType argType = arg->getType();
  7073. // For cases with matrix argument.
  7074. QualType elemType = {};
  7075. uint32_t numRows = 0, numCols = 0;
  7076. if (TypeTranslator::isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  7077. const uint32_t vecOne = getVecValueOne(elemType, numCols);
  7078. const auto actOnEachVec = [this, vecOne](uint32_t /*index*/,
  7079. uint32_t vecType,
  7080. uint32_t curRowId) {
  7081. return theBuilder.createBinaryOp(spv::Op::OpFDiv, vecType, vecOne,
  7082. curRowId);
  7083. };
  7084. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7085. }
  7086. // For cases with scalar or vector arguments.
  7087. return theBuilder.createBinaryOp(spv::Op::OpFDiv, returnTypeId,
  7088. getValueOne(argType), argId);
  7089. }
  7090. uint32_t SPIRVEmitter::processIntrinsicAllOrAny(const CallExpr *callExpr,
  7091. spv::Op spvOp) {
  7092. // 'all' and 'any' take only 1 parameter.
  7093. assert(callExpr->getNumArgs() == 1u);
  7094. const QualType returnType = callExpr->getType();
  7095. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  7096. const Expr *arg = callExpr->getArg(0);
  7097. const QualType argType = arg->getType();
  7098. // Handle scalars, vectors of size 1, and 1x1 matrices as arguments.
  7099. // Optimization: can directly cast them to boolean. No need for OpAny/OpAll.
  7100. {
  7101. QualType scalarType = {};
  7102. if (TypeTranslator::isScalarType(argType, &scalarType) &&
  7103. (scalarType->isBooleanType() || scalarType->isFloatingType() ||
  7104. scalarType->isIntegerType()))
  7105. return castToBool(doExpr(arg), argType, returnType);
  7106. }
  7107. // Handle vectors larger than 1, Mx1 matrices, and 1xN matrices as arguments.
  7108. // Cast the vector to a boolean vector, then run OpAny/OpAll on it.
  7109. {
  7110. QualType elemType = {};
  7111. uint32_t size = 0;
  7112. if (TypeTranslator::isVectorType(argType, &elemType, &size)) {
  7113. const QualType castToBoolType =
  7114. astContext.getExtVectorType(returnType, size);
  7115. uint32_t castedToBoolId =
  7116. castToBool(doExpr(arg), argType, castToBoolType);
  7117. return theBuilder.createUnaryOp(spvOp, returnTypeId, castedToBoolId);
  7118. }
  7119. }
  7120. // Handle MxN matrices as arguments.
  7121. {
  7122. QualType elemType = {};
  7123. uint32_t matRowCount = 0, matColCount = 0;
  7124. if (TypeTranslator::isMxNMatrix(argType, &elemType, &matRowCount,
  7125. &matColCount)) {
  7126. uint32_t matrixId = doExpr(arg);
  7127. const uint32_t vecType = typeTranslator.getComponentVectorType(argType);
  7128. llvm::SmallVector<uint32_t, 4> rowResults;
  7129. for (uint32_t i = 0; i < matRowCount; ++i) {
  7130. // Extract the row which is a float vector of size matColCount.
  7131. const uint32_t rowFloatVec =
  7132. theBuilder.createCompositeExtract(vecType, matrixId, {i});
  7133. // Cast the float vector to boolean vector.
  7134. const auto rowFloatQualType =
  7135. astContext.getExtVectorType(elemType, matColCount);
  7136. const auto rowBoolQualType =
  7137. astContext.getExtVectorType(returnType, matColCount);
  7138. const uint32_t rowBoolVec =
  7139. castToBool(rowFloatVec, rowFloatQualType, rowBoolQualType);
  7140. // Perform OpAny/OpAll on the boolean vector.
  7141. rowResults.push_back(
  7142. theBuilder.createUnaryOp(spvOp, returnTypeId, rowBoolVec));
  7143. }
  7144. // Create a new vector that is the concatenation of results of all rows.
  7145. uint32_t boolId = theBuilder.getBoolType();
  7146. uint32_t vecOfBoolsId = theBuilder.getVecType(boolId, matRowCount);
  7147. const uint32_t rowResultsId =
  7148. theBuilder.createCompositeConstruct(vecOfBoolsId, rowResults);
  7149. // Run OpAny/OpAll on the newly-created vector.
  7150. return theBuilder.createUnaryOp(spvOp, returnTypeId, rowResultsId);
  7151. }
  7152. }
  7153. // All types should be handled already.
  7154. llvm_unreachable("Unknown argument type passed to all()/any().");
  7155. return 0;
  7156. }
  7157. uint32_t SPIRVEmitter::processIntrinsicAsType(const CallExpr *callExpr) {
  7158. // This function handles 'asint', 'asuint', 'asfloat', and 'asdouble'.
  7159. // Method 1: ret asint(arg)
  7160. // arg component type = {float, uint}
  7161. // arg template type = {scalar, vector, matrix}
  7162. // ret template type = same as arg template type.
  7163. // ret component type = int
  7164. // Method 2: ret asuint(arg)
  7165. // arg component type = {float, int}
  7166. // arg template type = {scalar, vector, matrix}
  7167. // ret template type = same as arg template type.
  7168. // ret component type = uint
  7169. // Method 3: ret asfloat(arg)
  7170. // arg component type = {float, uint, int}
  7171. // arg template type = {scalar, vector, matrix}
  7172. // ret template type = same as arg template type.
  7173. // ret component type = float
  7174. // Method 4: double asdouble(uint lowbits, uint highbits)
  7175. // Method 5: double2 asdouble(uint2 lowbits, uint2 highbits)
  7176. // Method 6:
  7177. // void asuint(
  7178. // in double value,
  7179. // out uint lowbits,
  7180. // out uint highbits
  7181. // );
  7182. const QualType returnType = callExpr->getType();
  7183. const uint32_t numArgs = callExpr->getNumArgs();
  7184. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  7185. const Expr *arg0 = callExpr->getArg(0);
  7186. const QualType argType = arg0->getType();
  7187. // Method 3 return type may be the same as arg type, so it would be a no-op.
  7188. if (typeTranslator.isSameType(returnType, argType))
  7189. return doExpr(arg0);
  7190. switch (numArgs) {
  7191. case 1: {
  7192. // Handling Method 1, 2, and 3.
  7193. const auto argId = doExpr(arg0);
  7194. QualType fromElemType = {};
  7195. uint32_t numRows = 0, numCols = 0;
  7196. // For non-matrix arguments (scalar or vector), just do an OpBitCast.
  7197. if (!TypeTranslator::isMxNMatrix(argType, &fromElemType, &numRows,
  7198. &numCols)) {
  7199. return theBuilder.createUnaryOp(spv::Op::OpBitcast, returnTypeId, argId);
  7200. }
  7201. // Input or output type is a matrix.
  7202. const QualType toElemType = hlsl::GetHLSLMatElementType(returnType);
  7203. llvm::SmallVector<uint32_t, 4> castedRows;
  7204. const auto fromVecQualType =
  7205. astContext.getExtVectorType(fromElemType, numCols);
  7206. const auto toVecQualType = astContext.getExtVectorType(toElemType, numCols);
  7207. const auto fromVecTypeId = typeTranslator.translateType(fromVecQualType);
  7208. const auto toVecTypeId = typeTranslator.translateType(toVecQualType);
  7209. for (uint32_t row = 0; row < numRows; ++row) {
  7210. const auto rowId =
  7211. theBuilder.createCompositeExtract(fromVecTypeId, argId, {row});
  7212. castedRows.push_back(
  7213. theBuilder.createUnaryOp(spv::Op::OpBitcast, toVecTypeId, rowId));
  7214. }
  7215. return theBuilder.createCompositeConstruct(returnTypeId, castedRows);
  7216. }
  7217. case 2: {
  7218. const uint32_t lowbits = doExpr(arg0);
  7219. const uint32_t highbits = doExpr(callExpr->getArg(1));
  7220. const uint32_t uintType = theBuilder.getUint32Type();
  7221. const uint32_t doubleType = theBuilder.getFloat64Type();
  7222. // Handling Method 4
  7223. if (argType->isUnsignedIntegerType()) {
  7224. const uint32_t uintVec2Type = theBuilder.getVecType(uintType, 2);
  7225. const uint32_t operand = theBuilder.createCompositeConstruct(
  7226. uintVec2Type, {lowbits, highbits});
  7227. return theBuilder.createUnaryOp(spv::Op::OpBitcast, doubleType, operand);
  7228. }
  7229. // Handling Method 5
  7230. else {
  7231. const uint32_t uintVec4Type = theBuilder.getVecType(uintType, 4);
  7232. const uint32_t doubleVec2Type = theBuilder.getVecType(doubleType, 2);
  7233. const uint32_t operand = theBuilder.createVectorShuffle(
  7234. uintVec4Type, lowbits, highbits, {0, 2, 1, 3});
  7235. return theBuilder.createUnaryOp(spv::Op::OpBitcast, doubleVec2Type,
  7236. operand);
  7237. }
  7238. }
  7239. case 3: {
  7240. // Handling Method 6.
  7241. const uint32_t value = doExpr(arg0);
  7242. const uint32_t lowbits = doExpr(callExpr->getArg(1));
  7243. const uint32_t highbits = doExpr(callExpr->getArg(2));
  7244. const uint32_t uintType = theBuilder.getUint32Type();
  7245. const uint32_t uintVec2Type = theBuilder.getVecType(uintType, 2);
  7246. const uint32_t vecResult =
  7247. theBuilder.createUnaryOp(spv::Op::OpBitcast, uintVec2Type, value);
  7248. theBuilder.createStore(
  7249. lowbits, theBuilder.createCompositeExtract(uintType, vecResult, {0}));
  7250. theBuilder.createStore(
  7251. highbits, theBuilder.createCompositeExtract(uintType, vecResult, {1}));
  7252. return 0;
  7253. }
  7254. default:
  7255. emitError("unrecognized signature for %0 intrinsic function",
  7256. callExpr->getExprLoc())
  7257. << callExpr->getDirectCallee()->getName();
  7258. return 0;
  7259. }
  7260. }
  7261. uint32_t SPIRVEmitter::processD3DCOLORtoUBYTE4(const CallExpr *callExpr) {
  7262. // Should take a float4 and return an int4 by doing:
  7263. // int4 result = input.zyxw * 255.001953;
  7264. // Maximum float precision makes the scaling factor 255.002.
  7265. const auto arg = callExpr->getArg(0);
  7266. const auto argId = doExpr(arg);
  7267. const auto argTypeId = typeTranslator.translateType(arg->getType());
  7268. const auto swizzle =
  7269. theBuilder.createVectorShuffle(argTypeId, argId, argId, {2, 1, 0, 3});
  7270. const auto scaled = theBuilder.createBinaryOp(
  7271. spv::Op::OpVectorTimesScalar, argTypeId, swizzle,
  7272. theBuilder.getConstantFloat32(255.002f));
  7273. return castToInt(scaled, arg->getType(), callExpr->getType(),
  7274. callExpr->getExprLoc());
  7275. }
  7276. uint32_t SPIRVEmitter::processIntrinsicIsFinite(const CallExpr *callExpr) {
  7277. // Since OpIsFinite needs the Kernel capability, translation is instead done
  7278. // using OpIsNan and OpIsInf:
  7279. // isFinite = !(isNan || isInf)
  7280. const auto arg = doExpr(callExpr->getArg(0));
  7281. const auto returnType = typeTranslator.translateType(callExpr->getType());
  7282. const auto isNan =
  7283. theBuilder.createUnaryOp(spv::Op::OpIsNan, returnType, arg);
  7284. const auto isInf =
  7285. theBuilder.createUnaryOp(spv::Op::OpIsInf, returnType, arg);
  7286. const auto isNanOrInf =
  7287. theBuilder.createBinaryOp(spv::Op::OpLogicalOr, returnType, isNan, isInf);
  7288. return theBuilder.createUnaryOp(spv::Op::OpLogicalNot, returnType,
  7289. isNanOrInf);
  7290. }
  7291. uint32_t SPIRVEmitter::processIntrinsicSinCos(const CallExpr *callExpr) {
  7292. // Since there is no sincos equivalent in SPIR-V, we need to perform Sin
  7293. // once and Cos once. We can reuse existing Sine/Cosine handling functions.
  7294. CallExpr *sincosExpr =
  7295. new (astContext) CallExpr(astContext, Stmt::StmtClass::NoStmtClass, {});
  7296. sincosExpr->setType(callExpr->getArg(0)->getType());
  7297. sincosExpr->setNumArgs(astContext, 1);
  7298. sincosExpr->setArg(0, const_cast<Expr *>(callExpr->getArg(0)));
  7299. // Perform Sin and store results in argument 1.
  7300. const uint32_t sin =
  7301. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Sin,
  7302. /*actPerRowForMatrices*/ true);
  7303. theBuilder.createStore(doExpr(callExpr->getArg(1)), sin);
  7304. // Perform Cos and store results in argument 2.
  7305. const uint32_t cos =
  7306. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Cos,
  7307. /*actPerRowForMatrices*/ true);
  7308. theBuilder.createStore(doExpr(callExpr->getArg(2)), cos);
  7309. return 0;
  7310. }
  7311. uint32_t SPIRVEmitter::processIntrinsicSaturate(const CallExpr *callExpr) {
  7312. const auto *arg = callExpr->getArg(0);
  7313. const auto argId = doExpr(arg);
  7314. const auto argType = arg->getType();
  7315. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  7316. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  7317. if (argType->isFloatingType()) {
  7318. const uint32_t floatZero = getValueZero(argType);
  7319. const uint32_t floatOne = getValueOne(argType);
  7320. return theBuilder.createExtInst(returnType, glslInstSetId,
  7321. GLSLstd450::GLSLstd450FClamp,
  7322. {argId, floatZero, floatOne});
  7323. }
  7324. QualType elemType = {};
  7325. uint32_t vecSize = 0;
  7326. if (TypeTranslator::isVectorType(argType, &elemType, &vecSize)) {
  7327. const uint32_t vecZero = getVecValueZero(elemType, vecSize);
  7328. const uint32_t vecOne = getVecValueOne(elemType, vecSize);
  7329. return theBuilder.createExtInst(returnType, glslInstSetId,
  7330. GLSLstd450::GLSLstd450FClamp,
  7331. {argId, vecZero, vecOne});
  7332. }
  7333. uint32_t numRows = 0, numCols = 0;
  7334. if (TypeTranslator::isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  7335. const uint32_t vecZero = getVecValueZero(elemType, numCols);
  7336. const uint32_t vecOne = getVecValueOne(elemType, numCols);
  7337. const auto actOnEachVec = [this, vecZero, vecOne, glslInstSetId](
  7338. uint32_t /*index*/, uint32_t vecType,
  7339. uint32_t curRowId) {
  7340. return theBuilder.createExtInst(vecType, glslInstSetId,
  7341. GLSLstd450::GLSLstd450FClamp,
  7342. {curRowId, vecZero, vecOne});
  7343. };
  7344. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7345. }
  7346. emitError("invalid argument type passed to saturate intrinsic function",
  7347. callExpr->getExprLoc());
  7348. return 0;
  7349. }
  7350. uint32_t SPIRVEmitter::processIntrinsicFloatSign(const CallExpr *callExpr) {
  7351. // Import the GLSL.std.450 extended instruction set.
  7352. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  7353. const Expr *arg = callExpr->getArg(0);
  7354. const QualType returnType = callExpr->getType();
  7355. const QualType argType = arg->getType();
  7356. assert(isFloatOrVecMatOfFloatType(argType));
  7357. const uint32_t argTypeId = typeTranslator.translateType(argType);
  7358. const uint32_t argId = doExpr(arg);
  7359. uint32_t floatSignResultId = 0;
  7360. // For matrices, we can perform the instruction on each vector of the matrix.
  7361. if (TypeTranslator::isMxNMatrix(argType)) {
  7362. const auto actOnEachVec = [this, glslInstSetId](uint32_t /*index*/,
  7363. uint32_t vecType,
  7364. uint32_t curRowId) {
  7365. return theBuilder.createExtInst(vecType, glslInstSetId,
  7366. GLSLstd450::GLSLstd450FSign, {curRowId});
  7367. };
  7368. floatSignResultId = processEachVectorInMatrix(arg, argId, actOnEachVec);
  7369. } else {
  7370. floatSignResultId = theBuilder.createExtInst(
  7371. argTypeId, glslInstSetId, GLSLstd450::GLSLstd450FSign, {argId});
  7372. }
  7373. return castToInt(floatSignResultId, arg->getType(), returnType,
  7374. arg->getExprLoc());
  7375. }
  7376. uint32_t SPIRVEmitter::processIntrinsicF16ToF32(const CallExpr *callExpr) {
  7377. // f16tof32() takes in (vector of) uint and returns (vector of) float.
  7378. // The frontend should guarantee that by inserting implicit casts.
  7379. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  7380. const uint32_t f32TypeId = theBuilder.getFloat32Type();
  7381. const uint32_t u32TypeId = theBuilder.getUint32Type();
  7382. const uint32_t v2f32TypeId = theBuilder.getVecType(f32TypeId, 2);
  7383. const auto *arg = callExpr->getArg(0);
  7384. const uint32_t argId = doExpr(arg);
  7385. uint32_t elemCount = {};
  7386. if (TypeTranslator::isVectorType(arg->getType(), nullptr, &elemCount)) {
  7387. // The input is a vector. We need to handle each element separately.
  7388. llvm::SmallVector<uint32_t, 4> elements;
  7389. for (uint32_t i = 0; i < elemCount; ++i) {
  7390. const uint32_t srcElem =
  7391. theBuilder.createCompositeExtract(u32TypeId, argId, {i});
  7392. const uint32_t convert = theBuilder.createExtInst(
  7393. v2f32TypeId, glsl, GLSLstd450::GLSLstd450UnpackHalf2x16, srcElem);
  7394. elements.push_back(
  7395. theBuilder.createCompositeExtract(f32TypeId, convert, {0}));
  7396. }
  7397. return theBuilder.createCompositeConstruct(
  7398. theBuilder.getVecType(f32TypeId, elemCount), elements);
  7399. }
  7400. const uint32_t convert = theBuilder.createExtInst(
  7401. v2f32TypeId, glsl, GLSLstd450::GLSLstd450UnpackHalf2x16, argId);
  7402. // f16tof32() converts the float16 stored in the low-half of the uint to
  7403. // a float. So just need to return the first component.
  7404. return theBuilder.createCompositeExtract(f32TypeId, convert, {0});
  7405. }
  7406. uint32_t SPIRVEmitter::processIntrinsicF32ToF16(const CallExpr *callExpr) {
  7407. // f32tof16() takes in (vector of) float and returns (vector of) uint.
  7408. // The frontend should guarantee that by inserting implicit casts.
  7409. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  7410. const uint32_t f32TypeId = theBuilder.getFloat32Type();
  7411. const uint32_t u32TypeId = theBuilder.getUint32Type();
  7412. const uint32_t v2f32TypeId = theBuilder.getVecType(f32TypeId, 2);
  7413. const uint32_t zero = theBuilder.getConstantFloat32(0);
  7414. const auto *arg = callExpr->getArg(0);
  7415. const uint32_t argId = doExpr(arg);
  7416. uint32_t elemCount = {};
  7417. if (TypeTranslator::isVectorType(arg->getType(), nullptr, &elemCount)) {
  7418. // The input is a vector. We need to handle each element separately.
  7419. llvm::SmallVector<uint32_t, 4> elements;
  7420. for (uint32_t i = 0; i < elemCount; ++i) {
  7421. const uint32_t srcElem =
  7422. theBuilder.createCompositeExtract(f32TypeId, argId, {i});
  7423. const uint32_t srcVec =
  7424. theBuilder.createCompositeConstruct(v2f32TypeId, {srcElem, zero});
  7425. elements.push_back(theBuilder.createExtInst(
  7426. u32TypeId, glsl, GLSLstd450::GLSLstd450PackHalf2x16, srcVec));
  7427. }
  7428. return theBuilder.createCompositeConstruct(
  7429. theBuilder.getVecType(u32TypeId, elemCount), elements);
  7430. }
  7431. // f16tof32() stores the float into the low-half of the uint. So we need
  7432. // to supply another zero to take the other half.
  7433. const uint32_t srcVec =
  7434. theBuilder.createCompositeConstruct(v2f32TypeId, {argId, zero});
  7435. return theBuilder.createExtInst(u32TypeId, glsl,
  7436. GLSLstd450::GLSLstd450PackHalf2x16, srcVec);
  7437. }
  7438. uint32_t SPIRVEmitter::processIntrinsicUsingSpirvInst(
  7439. const CallExpr *callExpr, spv::Op opcode, bool actPerRowForMatrices) {
  7440. // Certain opcodes are only allowed in pixel shader
  7441. if (!shaderModel.IsPS())
  7442. switch (opcode) {
  7443. case spv::Op::OpDPdx:
  7444. case spv::Op::OpDPdy:
  7445. case spv::Op::OpDPdxFine:
  7446. case spv::Op::OpDPdyFine:
  7447. case spv::Op::OpDPdxCoarse:
  7448. case spv::Op::OpDPdyCoarse:
  7449. case spv::Op::OpFwidth:
  7450. case spv::Op::OpFwidthFine:
  7451. case spv::Op::OpFwidthCoarse:
  7452. needsLegalization = true;
  7453. }
  7454. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  7455. if (callExpr->getNumArgs() == 1u) {
  7456. const Expr *arg = callExpr->getArg(0);
  7457. const uint32_t argId = doExpr(arg);
  7458. // If the instruction does not operate on matrices, we can perform the
  7459. // instruction on each vector of the matrix.
  7460. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg->getType())) {
  7461. const auto actOnEachVec = [this, opcode](uint32_t /*index*/,
  7462. uint32_t vecType,
  7463. uint32_t curRowId) {
  7464. return theBuilder.createUnaryOp(opcode, vecType, {curRowId});
  7465. };
  7466. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7467. }
  7468. return theBuilder.createUnaryOp(opcode, returnType, {argId});
  7469. } else if (callExpr->getNumArgs() == 2u) {
  7470. const Expr *arg0 = callExpr->getArg(0);
  7471. const uint32_t arg0Id = doExpr(arg0);
  7472. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7473. // If the instruction does not operate on matrices, we can perform the
  7474. // instruction on each vector of the matrix.
  7475. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7476. const auto actOnEachVec = [this, opcode, arg1Id](uint32_t index,
  7477. uint32_t vecType,
  7478. uint32_t arg0RowId) {
  7479. const uint32_t arg1RowId =
  7480. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7481. return theBuilder.createBinaryOp(opcode, vecType, arg0RowId, arg1RowId);
  7482. };
  7483. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7484. }
  7485. return theBuilder.createBinaryOp(opcode, returnType, arg0Id, arg1Id);
  7486. }
  7487. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  7488. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  7489. return 0;
  7490. }
  7491. uint32_t SPIRVEmitter::processIntrinsicUsingGLSLInst(
  7492. const CallExpr *callExpr, GLSLstd450 opcode, bool actPerRowForMatrices) {
  7493. // Import the GLSL.std.450 extended instruction set.
  7494. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  7495. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  7496. if (callExpr->getNumArgs() == 1u) {
  7497. const Expr *arg = callExpr->getArg(0);
  7498. const uint32_t argId = doExpr(arg);
  7499. // If the instruction does not operate on matrices, we can perform the
  7500. // instruction on each vector of the matrix.
  7501. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg->getType())) {
  7502. const auto actOnEachVec = [this, glslInstSetId,
  7503. opcode](uint32_t /*index*/, uint32_t vecType,
  7504. uint32_t curRowId) {
  7505. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7506. {curRowId});
  7507. };
  7508. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7509. }
  7510. return theBuilder.createExtInst(returnType, glslInstSetId, opcode, {argId});
  7511. } else if (callExpr->getNumArgs() == 2u) {
  7512. const Expr *arg0 = callExpr->getArg(0);
  7513. const uint32_t arg0Id = doExpr(arg0);
  7514. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7515. // If the instruction does not operate on matrices, we can perform the
  7516. // instruction on each vector of the matrix.
  7517. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7518. const auto actOnEachVec = [this, glslInstSetId, opcode,
  7519. arg1Id](uint32_t index, uint32_t vecType,
  7520. uint32_t arg0RowId) {
  7521. const uint32_t arg1RowId =
  7522. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7523. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7524. {arg0RowId, arg1RowId});
  7525. };
  7526. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7527. }
  7528. return theBuilder.createExtInst(returnType, glslInstSetId, opcode,
  7529. {arg0Id, arg1Id});
  7530. } else if (callExpr->getNumArgs() == 3u) {
  7531. const Expr *arg0 = callExpr->getArg(0);
  7532. const uint32_t arg0Id = doExpr(arg0);
  7533. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7534. const uint32_t arg2Id = doExpr(callExpr->getArg(2));
  7535. // If the instruction does not operate on matrices, we can perform the
  7536. // instruction on each vector of the matrix.
  7537. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7538. const auto actOnEachVec = [this, glslInstSetId, opcode, arg0Id, arg1Id,
  7539. arg2Id](uint32_t index, uint32_t vecType,
  7540. uint32_t arg0RowId) {
  7541. const uint32_t arg1RowId =
  7542. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7543. const uint32_t arg2RowId =
  7544. theBuilder.createCompositeExtract(vecType, arg2Id, {index});
  7545. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7546. {arg0RowId, arg1RowId, arg2RowId});
  7547. };
  7548. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7549. }
  7550. return theBuilder.createExtInst(returnType, glslInstSetId, opcode,
  7551. {arg0Id, arg1Id, arg2Id});
  7552. }
  7553. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  7554. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  7555. return 0;
  7556. }
  7557. uint32_t SPIRVEmitter::processIntrinsicLog10(const CallExpr *callExpr) {
  7558. // Since there is no log10 instruction in SPIR-V, we can use:
  7559. // log10(x) = log2(x) * ( 1 / log2(10) )
  7560. // 1 / log2(10) = 0.30103
  7561. const auto scale = theBuilder.getConstantFloat32(0.30103f);
  7562. const auto log2 =
  7563. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450Log2, true);
  7564. const auto returnType = callExpr->getType();
  7565. const auto returnTypeId = typeTranslator.translateType(returnType);
  7566. spv::Op scaleOp = TypeTranslator::isScalarType(returnType)
  7567. ? spv::Op::OpFMul
  7568. : TypeTranslator::isVectorType(returnType)
  7569. ? spv::Op::OpVectorTimesScalar
  7570. : spv::Op::OpMatrixTimesScalar;
  7571. return theBuilder.createBinaryOp(scaleOp, returnTypeId, log2, scale);
  7572. }
  7573. uint32_t SPIRVEmitter::getValueZero(QualType type) {
  7574. {
  7575. QualType scalarType = {};
  7576. if (TypeTranslator::isScalarType(type, &scalarType)) {
  7577. if (scalarType->isSignedIntegerType()) {
  7578. return theBuilder.getConstantInt32(0);
  7579. }
  7580. if (scalarType->isUnsignedIntegerType()) {
  7581. return theBuilder.getConstantUint32(0);
  7582. }
  7583. if (scalarType->isFloatingType()) {
  7584. return theBuilder.getConstantFloat32(0.0);
  7585. }
  7586. }
  7587. }
  7588. {
  7589. QualType elemType = {};
  7590. uint32_t size = {};
  7591. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  7592. return getVecValueZero(elemType, size);
  7593. }
  7594. }
  7595. {
  7596. QualType elemType = {};
  7597. uint32_t rowCount = 0, colCount = 0;
  7598. if (TypeTranslator::isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  7599. const auto row = getVecValueZero(elemType, colCount);
  7600. llvm::SmallVector<uint32_t, 4> rows((size_t)rowCount, row);
  7601. return theBuilder.createCompositeConstruct(
  7602. typeTranslator.translateType(type), rows);
  7603. }
  7604. }
  7605. emitError("getting value 0 for type %0 unimplemented", {})
  7606. << type.getAsString();
  7607. return 0;
  7608. }
  7609. uint32_t SPIRVEmitter::getVecValueZero(QualType elemType, uint32_t size) {
  7610. const uint32_t elemZeroId = getValueZero(elemType);
  7611. if (size == 1)
  7612. return elemZeroId;
  7613. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemZeroId);
  7614. const uint32_t vecType =
  7615. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  7616. return theBuilder.getConstantComposite(vecType, elements);
  7617. }
  7618. uint32_t SPIRVEmitter::getValueOne(QualType type) {
  7619. {
  7620. QualType scalarType = {};
  7621. if (TypeTranslator::isScalarType(type, &scalarType)) {
  7622. // TODO: Support other types such as short, half, etc.
  7623. if (scalarType->isSignedIntegerType()) {
  7624. return theBuilder.getConstantInt32(1);
  7625. }
  7626. if (scalarType->isUnsignedIntegerType()) {
  7627. return theBuilder.getConstantUint32(1);
  7628. }
  7629. if (scalarType->isSpecificBuiltinType(BuiltinType::LitFloat))
  7630. scalarType = typeTranslator.getIntendedLiteralType(scalarType);
  7631. if (const auto *builtinType = scalarType->getAs<BuiltinType>()) {
  7632. // TODO: Add support for other types that are not covered yet.
  7633. switch (builtinType->getKind()) {
  7634. case BuiltinType::Double:
  7635. return theBuilder.getConstantFloat64(1.0);
  7636. case BuiltinType::Float:
  7637. return theBuilder.getConstantFloat32(1.0);
  7638. }
  7639. }
  7640. }
  7641. }
  7642. {
  7643. QualType elemType = {};
  7644. uint32_t size = {};
  7645. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  7646. return getVecValueOne(elemType, size);
  7647. }
  7648. }
  7649. emitError("getting value 1 for type %0 unimplemented", {}) << type;
  7650. return 0;
  7651. }
  7652. uint32_t SPIRVEmitter::getVecValueOne(QualType elemType, uint32_t size) {
  7653. const uint32_t elemOneId = getValueOne(elemType);
  7654. if (size == 1)
  7655. return elemOneId;
  7656. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemOneId);
  7657. const uint32_t vecType =
  7658. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  7659. return theBuilder.getConstantComposite(vecType, elements);
  7660. }
  7661. uint32_t SPIRVEmitter::getMatElemValueOne(QualType type) {
  7662. assert(hlsl::IsHLSLMatType(type));
  7663. const auto elemType = hlsl::GetHLSLMatElementType(type);
  7664. uint32_t rowCount = 0, colCount = 0;
  7665. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  7666. if (rowCount == 1 && colCount == 1)
  7667. return getValueOne(elemType);
  7668. if (colCount == 1)
  7669. return getVecValueOne(elemType, rowCount);
  7670. return getVecValueOne(elemType, colCount);
  7671. }
  7672. uint32_t SPIRVEmitter::getMaskForBitwidthValue(QualType type) {
  7673. QualType elemType = {};
  7674. uint32_t count = 1;
  7675. if (TypeTranslator::isScalarType(type, &elemType) ||
  7676. TypeTranslator::isVectorType(type, &elemType, &count)) {
  7677. const auto bitwidth = typeTranslator.getElementSpirvBitwidth(elemType);
  7678. uint32_t mask = 0;
  7679. uint32_t elemTypeId = 0;
  7680. switch (bitwidth) {
  7681. case 16:
  7682. mask = theBuilder.getConstantUint16(bitwidth - 1);
  7683. elemTypeId = theBuilder.getUint16Type();
  7684. break;
  7685. case 32:
  7686. mask = theBuilder.getConstantUint32(bitwidth - 1);
  7687. elemTypeId = theBuilder.getUint32Type();
  7688. break;
  7689. case 64:
  7690. mask = theBuilder.getConstantUint64(bitwidth - 1);
  7691. elemTypeId = theBuilder.getUint64Type();
  7692. break;
  7693. default:
  7694. assert(false && "this method only supports 16-, 32-, and 64-bit types");
  7695. }
  7696. if (count == 1)
  7697. return mask;
  7698. const uint32_t typeId = theBuilder.getVecType(elemTypeId, count);
  7699. llvm::SmallVector<uint32_t, 4> elements(size_t(count), mask);
  7700. return theBuilder.getConstantComposite(typeId, elements);
  7701. }
  7702. assert(false && "this method only supports scalars and vectors");
  7703. return 0;
  7704. }
  7705. uint32_t SPIRVEmitter::translateAPValue(const APValue &value,
  7706. const QualType targetType) {
  7707. uint32_t result = 0;
  7708. // Provide a hint to the typeTranslator that if a literal is discovered, its
  7709. // intended usage is targetType.
  7710. TypeTranslator::LiteralTypeHint hint(typeTranslator, targetType);
  7711. if (targetType->isBooleanType()) {
  7712. result = theBuilder.getConstantBool(value.getInt().getBoolValue(),
  7713. isSpecConstantMode);
  7714. } else if (targetType->isIntegerType()) {
  7715. result = translateAPInt(value.getInt(), targetType);
  7716. } else if (targetType->isFloatingType()) {
  7717. result = translateAPFloat(value.getFloat(), targetType);
  7718. } else if (hlsl::IsHLSLVecType(targetType)) {
  7719. const uint32_t vecType = typeTranslator.translateType(targetType);
  7720. const QualType elemType = hlsl::GetHLSLVecElementType(targetType);
  7721. const auto numElements = value.getVectorLength();
  7722. // Special case for vectors of size 1. SPIR-V doesn't support this vector
  7723. // size so we need to translate it to scalar values.
  7724. if (numElements == 1) {
  7725. result = translateAPValue(value.getVectorElt(0), elemType);
  7726. } else {
  7727. llvm::SmallVector<uint32_t, 4> elements;
  7728. for (uint32_t i = 0; i < numElements; ++i) {
  7729. elements.push_back(translateAPValue(value.getVectorElt(i), elemType));
  7730. }
  7731. result = theBuilder.getConstantComposite(vecType, elements);
  7732. }
  7733. }
  7734. if (result)
  7735. return result;
  7736. emitError("APValue of type %0 unimplemented", {}) << value.getKind();
  7737. value.dump();
  7738. return 0;
  7739. }
  7740. uint32_t SPIRVEmitter::translateAPInt(const llvm::APInt &intValue,
  7741. QualType targetType) {
  7742. targetType = typeTranslator.getIntendedLiteralType(targetType);
  7743. const auto targetTypeBitWidth = astContext.getTypeSize(targetType);
  7744. const bool isSigned = targetType->isSignedIntegerType();
  7745. switch (targetTypeBitWidth) {
  7746. case 16: {
  7747. if (spirvOptions.enable16BitTypes) {
  7748. if (isSigned) {
  7749. return theBuilder.getConstantInt16(
  7750. static_cast<int16_t>(intValue.getSExtValue()));
  7751. } else {
  7752. return theBuilder.getConstantUint16(
  7753. static_cast<uint16_t>(intValue.getZExtValue()));
  7754. }
  7755. } else {
  7756. // If enable16BitTypes option is not true, treat as 32-bit integer.
  7757. if (isSigned)
  7758. return theBuilder.getConstantInt32(
  7759. static_cast<int32_t>(intValue.getSExtValue()), isSpecConstantMode);
  7760. else
  7761. return theBuilder.getConstantUint32(
  7762. static_cast<uint32_t>(intValue.getZExtValue()), isSpecConstantMode);
  7763. }
  7764. }
  7765. case 32: {
  7766. if (isSigned) {
  7767. if (!intValue.isSignedIntN(32)) {
  7768. emitError("evaluating integer literal %0 as a 32-bit integer loses "
  7769. "inforamtion",
  7770. {})
  7771. << std::to_string(intValue.getSExtValue());
  7772. return 0;
  7773. }
  7774. return theBuilder.getConstantInt32(
  7775. static_cast<int32_t>(intValue.getSExtValue()), isSpecConstantMode);
  7776. } else {
  7777. if (!intValue.isIntN(32)) {
  7778. emitError("evaluating integer literal %0 as a 32-bit integer loses "
  7779. "inforamtion",
  7780. {})
  7781. << std::to_string(intValue.getZExtValue());
  7782. return 0;
  7783. }
  7784. return theBuilder.getConstantUint32(
  7785. static_cast<uint32_t>(intValue.getZExtValue()), isSpecConstantMode);
  7786. }
  7787. }
  7788. case 64: {
  7789. if (isSigned)
  7790. return theBuilder.getConstantInt64(intValue.getSExtValue());
  7791. else
  7792. return theBuilder.getConstantUint64(intValue.getZExtValue());
  7793. }
  7794. }
  7795. emitError("APInt for target bitwidth %0 unimplemented", {})
  7796. << astContext.getIntWidth(targetType);
  7797. return 0;
  7798. }
  7799. bool SPIRVEmitter::isLiteralLargerThan32Bits(const Expr *expr) {
  7800. if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  7801. const bool isSigned = expr->getType()->isSignedIntegerType();
  7802. const llvm::APInt &value = intLiteral->getValue();
  7803. return (isSigned && !value.isSignedIntN(32)) ||
  7804. (!isSigned && !value.isIntN(32));
  7805. }
  7806. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  7807. llvm::APFloat value = floatLiteral->getValue();
  7808. const auto &semantics = value.getSemantics();
  7809. // regular 'half' and 'float' can be represented in 32 bits.
  7810. if (&semantics == &llvm::APFloat::IEEEsingle ||
  7811. &semantics == &llvm::APFloat::IEEEhalf)
  7812. return true;
  7813. // See if 'double' value can be represented in 32 bits without losing info.
  7814. bool losesInfo = false;
  7815. const auto convertStatus =
  7816. value.convert(llvm::APFloat::IEEEsingle,
  7817. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  7818. if (convertStatus != llvm::APFloat::opOK &&
  7819. convertStatus != llvm::APFloat::opInexact)
  7820. return true;
  7821. }
  7822. return false;
  7823. }
  7824. uint32_t SPIRVEmitter::tryToEvaluateAsInt32(const llvm::APInt &intValue,
  7825. bool isSigned) {
  7826. if (isSigned && intValue.isSignedIntN(32)) {
  7827. return theBuilder.getConstantInt32(
  7828. static_cast<int32_t>(intValue.getSExtValue()));
  7829. }
  7830. if (!isSigned && intValue.isIntN(32)) {
  7831. return theBuilder.getConstantUint32(
  7832. static_cast<uint32_t>(intValue.getZExtValue()));
  7833. }
  7834. // Couldn't evaluate as a 32-bit int without losing information.
  7835. return 0;
  7836. }
  7837. uint32_t SPIRVEmitter::tryToEvaluateAsFloat32(const llvm::APFloat &floatValue) {
  7838. const auto &semantics = floatValue.getSemantics();
  7839. // If the given value is already a 32-bit float, there is no need to convert.
  7840. if (&semantics == &llvm::APFloat::IEEEsingle) {
  7841. return theBuilder.getConstantFloat32(floatValue.convertToFloat(),
  7842. isSpecConstantMode);
  7843. }
  7844. // Try to see if this literal float can be represented in 32-bit.
  7845. // Since the convert function below may modify the fp value, we call it on a
  7846. // temporary copy.
  7847. llvm::APFloat eval = floatValue;
  7848. bool losesInfo = false;
  7849. const auto convertStatus =
  7850. eval.convert(llvm::APFloat::IEEEsingle,
  7851. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  7852. if (convertStatus == llvm::APFloat::opOK && !losesInfo)
  7853. return theBuilder.getConstantFloat32(eval.convertToFloat());
  7854. // Couldn't evaluate as a 32-bit float without losing information.
  7855. return 0;
  7856. }
  7857. uint32_t SPIRVEmitter::translateAPFloat(llvm::APFloat floatValue,
  7858. QualType targetType) {
  7859. using llvm::APFloat;
  7860. const auto originalValue = floatValue;
  7861. const auto valueBitwidth = APFloat::getSizeInBits(floatValue.getSemantics());
  7862. // Find out the target bitwidth.
  7863. targetType = typeTranslator.getIntendedLiteralType(targetType);
  7864. auto targetBitwidth =
  7865. APFloat::getSizeInBits(astContext.getFloatTypeSemantics(targetType));
  7866. // If 16-bit types are not enabled, treat them as 32-bit float.
  7867. if (targetBitwidth == 16 && !spirvOptions.enable16BitTypes)
  7868. targetBitwidth = 32;
  7869. if (targetBitwidth != valueBitwidth) {
  7870. bool losesInfo = false;
  7871. const llvm::fltSemantics &targetSemantics =
  7872. targetBitwidth == 16
  7873. ? APFloat::IEEEhalf
  7874. : targetBitwidth == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble;
  7875. const auto status = floatValue.convert(
  7876. targetSemantics, APFloat::roundingMode::rmTowardZero, &losesInfo);
  7877. if (status != APFloat::opStatus::opOK &&
  7878. status != APFloat::opStatus::opInexact) {
  7879. emitError(
  7880. "evaluating float literal %0 at a lower bitwidth loses information",
  7881. {})
  7882. // Converting from 16bit to 32/64-bit won't lose information.
  7883. // So only 32/64-bit values can reach here.
  7884. << std::to_string(valueBitwidth == 32
  7885. ? originalValue.convertToFloat()
  7886. : originalValue.convertToDouble());
  7887. return 0;
  7888. }
  7889. }
  7890. switch (targetBitwidth) {
  7891. case 16:
  7892. return theBuilder.getConstantFloat16(
  7893. static_cast<uint16_t>(floatValue.bitcastToAPInt().getZExtValue()));
  7894. case 32:
  7895. return theBuilder.getConstantFloat32(floatValue.convertToFloat(),
  7896. isSpecConstantMode);
  7897. case 64:
  7898. return theBuilder.getConstantFloat64(floatValue.convertToDouble());
  7899. default:
  7900. break;
  7901. }
  7902. emitError("APFloat for target bitwidth %0 unimplemented", {})
  7903. << targetBitwidth;
  7904. return 0;
  7905. }
  7906. uint32_t SPIRVEmitter::tryToEvaluateAsConst(const Expr *expr) {
  7907. Expr::EvalResult evalResult;
  7908. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  7909. !evalResult.HasSideEffects) {
  7910. return translateAPValue(evalResult.Val, expr->getType());
  7911. }
  7912. return 0;
  7913. }
  7914. spv::ExecutionModel
  7915. SPIRVEmitter::getSpirvShaderStage(const hlsl::ShaderModel &model) {
  7916. // DXIL Models are:
  7917. // Profile (DXIL Model) : HLSL Shader Kind : SPIR-V Shader Stage
  7918. // vs_<version> : Vertex Shader : Vertex Shader
  7919. // hs_<version> : Hull Shader : Tassellation Control Shader
  7920. // ds_<version> : Domain Shader : Tessellation Evaluation Shader
  7921. // gs_<version> : Geometry Shader : Geometry Shader
  7922. // ps_<version> : Pixel Shader : Fragment Shader
  7923. // cs_<version> : Compute Shader : Compute Shader
  7924. switch (model.GetKind()) {
  7925. case hlsl::ShaderModel::Kind::Vertex:
  7926. return spv::ExecutionModel::Vertex;
  7927. case hlsl::ShaderModel::Kind::Hull:
  7928. return spv::ExecutionModel::TessellationControl;
  7929. case hlsl::ShaderModel::Kind::Domain:
  7930. return spv::ExecutionModel::TessellationEvaluation;
  7931. case hlsl::ShaderModel::Kind::Geometry:
  7932. return spv::ExecutionModel::Geometry;
  7933. case hlsl::ShaderModel::Kind::Pixel:
  7934. return spv::ExecutionModel::Fragment;
  7935. case hlsl::ShaderModel::Kind::Compute:
  7936. return spv::ExecutionModel::GLCompute;
  7937. default:
  7938. break;
  7939. }
  7940. llvm_unreachable("unknown shader model");
  7941. }
  7942. void SPIRVEmitter::AddRequiredCapabilitiesForShaderModel() {
  7943. if (shaderModel.IsHS() || shaderModel.IsDS()) {
  7944. theBuilder.requireCapability(spv::Capability::Tessellation);
  7945. } else if (shaderModel.IsGS()) {
  7946. theBuilder.requireCapability(spv::Capability::Geometry);
  7947. } else {
  7948. theBuilder.requireCapability(spv::Capability::Shader);
  7949. }
  7950. }
  7951. bool SPIRVEmitter::processGeometryShaderAttributes(const FunctionDecl *decl,
  7952. uint32_t *arraySize) {
  7953. bool success = true;
  7954. assert(shaderModel.IsGS());
  7955. if (auto *vcAttr = decl->getAttr<HLSLMaxVertexCountAttr>()) {
  7956. theBuilder.addExecutionMode(entryFunctionId,
  7957. spv::ExecutionMode::OutputVertices,
  7958. {static_cast<uint32_t>(vcAttr->getCount())});
  7959. }
  7960. uint32_t invocations = 1;
  7961. if (auto *instanceAttr = decl->getAttr<HLSLInstanceAttr>()) {
  7962. invocations = static_cast<uint32_t>(instanceAttr->getCount());
  7963. }
  7964. theBuilder.addExecutionMode(entryFunctionId, spv::ExecutionMode::Invocations,
  7965. {invocations});
  7966. // Only one primitive type is permitted for the geometry shader.
  7967. bool outPoint = false, outLine = false, outTriangle = false, inPoint = false,
  7968. inLine = false, inTriangle = false, inLineAdj = false,
  7969. inTriangleAdj = false;
  7970. for (const auto *param : decl->params()) {
  7971. // Add an execution mode based on the output stream type. Do not an
  7972. // execution mode more than once.
  7973. if (param->hasAttr<HLSLInOutAttr>()) {
  7974. const auto paramType = param->getType();
  7975. if (hlsl::IsHLSLTriangleStreamType(paramType) && !outTriangle) {
  7976. theBuilder.addExecutionMode(
  7977. entryFunctionId, spv::ExecutionMode::OutputTriangleStrip, {});
  7978. outTriangle = true;
  7979. } else if (hlsl::IsHLSLLineStreamType(paramType) && !outLine) {
  7980. theBuilder.addExecutionMode(entryFunctionId,
  7981. spv::ExecutionMode::OutputLineStrip, {});
  7982. outLine = true;
  7983. } else if (hlsl::IsHLSLPointStreamType(paramType) && !outPoint) {
  7984. theBuilder.addExecutionMode(entryFunctionId,
  7985. spv::ExecutionMode::OutputPoints, {});
  7986. outPoint = true;
  7987. }
  7988. // An output stream parameter will not have the input primitive type
  7989. // attributes, so we can continue to the next parameter.
  7990. continue;
  7991. }
  7992. // Add an execution mode based on the input primitive type. Do not add an
  7993. // execution mode more than once.
  7994. if (param->hasAttr<HLSLPointAttr>() && !inPoint) {
  7995. theBuilder.addExecutionMode(entryFunctionId,
  7996. spv::ExecutionMode::InputPoints, {});
  7997. *arraySize = 1;
  7998. inPoint = true;
  7999. } else if (param->hasAttr<HLSLLineAttr>() && !inLine) {
  8000. theBuilder.addExecutionMode(entryFunctionId,
  8001. spv::ExecutionMode::InputLines, {});
  8002. *arraySize = 2;
  8003. inLine = true;
  8004. } else if (param->hasAttr<HLSLTriangleAttr>() && !inTriangle) {
  8005. theBuilder.addExecutionMode(entryFunctionId,
  8006. spv::ExecutionMode::Triangles, {});
  8007. *arraySize = 3;
  8008. inTriangle = true;
  8009. } else if (param->hasAttr<HLSLLineAdjAttr>() && !inLineAdj) {
  8010. theBuilder.addExecutionMode(entryFunctionId,
  8011. spv::ExecutionMode::InputLinesAdjacency, {});
  8012. *arraySize = 4;
  8013. inLineAdj = true;
  8014. } else if (param->hasAttr<HLSLTriangleAdjAttr>() && !inTriangleAdj) {
  8015. theBuilder.addExecutionMode(
  8016. entryFunctionId, spv::ExecutionMode::InputTrianglesAdjacency, {});
  8017. *arraySize = 6;
  8018. inTriangleAdj = true;
  8019. }
  8020. }
  8021. if (inPoint + inLine + inLineAdj + inTriangle + inTriangleAdj > 1) {
  8022. emitError("only one input primitive type can be specified in the geometry "
  8023. "shader",
  8024. {});
  8025. success = false;
  8026. }
  8027. if (outPoint + outTriangle + outLine > 1) {
  8028. emitError("only one output primitive type can be specified in the geometry "
  8029. "shader",
  8030. {});
  8031. success = false;
  8032. }
  8033. return success;
  8034. }
  8035. void SPIRVEmitter::processPixelShaderAttributes(const FunctionDecl *decl) {
  8036. theBuilder.addExecutionMode(entryFunctionId,
  8037. spv::ExecutionMode::OriginUpperLeft, {});
  8038. if (auto *numThreadsAttr = decl->getAttr<HLSLEarlyDepthStencilAttr>()) {
  8039. theBuilder.addExecutionMode(entryFunctionId,
  8040. spv::ExecutionMode::EarlyFragmentTests, {});
  8041. }
  8042. }
  8043. void SPIRVEmitter::processComputeShaderAttributes(const FunctionDecl *decl) {
  8044. // If not explicitly specified, x, y, and z should be defaulted to 1.
  8045. uint32_t x = 1, y = 1, z = 1;
  8046. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  8047. x = static_cast<uint32_t>(numThreadsAttr->getX());
  8048. y = static_cast<uint32_t>(numThreadsAttr->getY());
  8049. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  8050. }
  8051. theBuilder.addExecutionMode(entryFunctionId, spv::ExecutionMode::LocalSize,
  8052. {x, y, z});
  8053. }
  8054. bool SPIRVEmitter::processTessellationShaderAttributes(
  8055. const FunctionDecl *decl, uint32_t *numOutputControlPoints) {
  8056. assert(shaderModel.IsHS() || shaderModel.IsDS());
  8057. using namespace spv;
  8058. if (auto *domain = decl->getAttr<HLSLDomainAttr>()) {
  8059. const auto domainType = domain->getDomainType().lower();
  8060. const ExecutionMode hsExecMode =
  8061. llvm::StringSwitch<ExecutionMode>(domainType)
  8062. .Case("tri", ExecutionMode::Triangles)
  8063. .Case("quad", ExecutionMode::Quads)
  8064. .Case("isoline", ExecutionMode::Isolines)
  8065. .Default(ExecutionMode::Max);
  8066. if (hsExecMode == ExecutionMode::Max) {
  8067. emitError("unknown domain type specified for entry function",
  8068. domain->getLocation());
  8069. return false;
  8070. }
  8071. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  8072. }
  8073. // Early return for domain shaders as domain shaders only takes the 'domain'
  8074. // attribute.
  8075. if (shaderModel.IsDS())
  8076. return true;
  8077. if (auto *partitioning = decl->getAttr<HLSLPartitioningAttr>()) {
  8078. const auto scheme = partitioning->getScheme().lower();
  8079. if (scheme == "pow2") {
  8080. emitError("pow2 partitioning scheme is not supported since there is no "
  8081. "equivalent in Vulkan",
  8082. partitioning->getLocation());
  8083. return false;
  8084. }
  8085. const ExecutionMode hsExecMode =
  8086. llvm::StringSwitch<ExecutionMode>(scheme)
  8087. .Case("fractional_even", ExecutionMode::SpacingFractionalEven)
  8088. .Case("fractional_odd", ExecutionMode::SpacingFractionalOdd)
  8089. .Case("integer", ExecutionMode::SpacingEqual)
  8090. .Default(ExecutionMode::Max);
  8091. if (hsExecMode == ExecutionMode::Max) {
  8092. emitError("unknown partitioning scheme in hull shader",
  8093. partitioning->getLocation());
  8094. return false;
  8095. }
  8096. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  8097. }
  8098. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  8099. const auto topology = outputTopology->getTopology().lower();
  8100. const ExecutionMode hsExecMode =
  8101. llvm::StringSwitch<ExecutionMode>(topology)
  8102. .Case("point", ExecutionMode::PointMode)
  8103. .Case("triangle_cw", ExecutionMode::VertexOrderCw)
  8104. .Case("triangle_ccw", ExecutionMode::VertexOrderCcw)
  8105. .Default(ExecutionMode::Max);
  8106. // TODO: There is no SPIR-V equivalent for "line" topology. Is it the
  8107. // default?
  8108. if (topology != "line") {
  8109. if (hsExecMode != spv::ExecutionMode::Max) {
  8110. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  8111. } else {
  8112. emitError("unknown output topology in hull shader",
  8113. outputTopology->getLocation());
  8114. return false;
  8115. }
  8116. }
  8117. }
  8118. if (auto *controlPoints = decl->getAttr<HLSLOutputControlPointsAttr>()) {
  8119. *numOutputControlPoints = controlPoints->getCount();
  8120. theBuilder.addExecutionMode(entryFunctionId,
  8121. spv::ExecutionMode::OutputVertices,
  8122. {*numOutputControlPoints});
  8123. }
  8124. if (auto *pcf = decl->getAttr<HLSLPatchConstantFuncAttr>()) {
  8125. llvm::StringRef pcf_name = pcf->getFunctionName();
  8126. for (auto *decl : astContext.getTranslationUnitDecl()->decls())
  8127. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl))
  8128. if (astContext.IsPatchConstantFunctionDecl(funcDecl) &&
  8129. funcDecl->getName() == pcf_name)
  8130. patchConstFunc = funcDecl;
  8131. }
  8132. return true;
  8133. }
  8134. bool SPIRVEmitter::emitEntryFunctionWrapper(const FunctionDecl *decl,
  8135. const uint32_t entryFuncId) {
  8136. // HS specific attributes
  8137. uint32_t numOutputControlPoints = 0;
  8138. uint32_t outputControlPointIdVal = 0; // SV_OutputControlPointID value
  8139. uint32_t primitiveIdVar = 0; // SV_PrimitiveID variable
  8140. uint32_t viewIdVar = 0; // SV_ViewID variable
  8141. uint32_t hullMainInputPatchParam = 0; // Temporary parameter for InputPatch<>
  8142. // The array size of per-vertex input/output variables
  8143. // Used by HS/DS/GS for the additional arrayness, zero means not an array.
  8144. uint32_t inputArraySize = 0;
  8145. uint32_t outputArraySize = 0;
  8146. // Construct the wrapper function signature.
  8147. const uint32_t voidType = theBuilder.getVoidType();
  8148. const uint32_t funcType = theBuilder.getFunctionType(voidType, {});
  8149. // The wrapper entry function surely does not have pre-assigned <result-id>
  8150. // for it like other functions that got added to the work queue following
  8151. // function calls. And the wrapper is the entry function.
  8152. entryFunctionId =
  8153. theBuilder.beginFunction(funcType, voidType, decl->getName());
  8154. // Note this should happen before using declIdMapper for other tasks.
  8155. declIdMapper.setEntryFunctionId(entryFunctionId);
  8156. // Handle attributes specific to each shader stage
  8157. if (shaderModel.IsPS()) {
  8158. processPixelShaderAttributes(decl);
  8159. } else if (shaderModel.IsCS()) {
  8160. processComputeShaderAttributes(decl);
  8161. } else if (shaderModel.IsHS()) {
  8162. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  8163. return false;
  8164. // The input array size for HS is specified in the InputPatch parameter.
  8165. for (const auto *param : decl->params())
  8166. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  8167. inputArraySize = hlsl::GetHLSLInputPatchCount(param->getType());
  8168. break;
  8169. }
  8170. outputArraySize = numOutputControlPoints;
  8171. } else if (shaderModel.IsDS()) {
  8172. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  8173. return false;
  8174. // The input array size for HS is specified in the OutputPatch parameter.
  8175. for (const auto *param : decl->params())
  8176. if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  8177. inputArraySize = hlsl::GetHLSLOutputPatchCount(param->getType());
  8178. break;
  8179. }
  8180. // The per-vertex output of DS is not an array.
  8181. } else if (shaderModel.IsGS()) {
  8182. if (!processGeometryShaderAttributes(decl, &inputArraySize))
  8183. return false;
  8184. // The per-vertex output of GS is not an array.
  8185. }
  8186. // Go through all parameters and record the declaration of SV_ClipDistance
  8187. // and SV_CullDistance. We need to do this extra step because in HLSL we
  8188. // can declare multiple SV_ClipDistance/SV_CullDistance variables of float
  8189. // or vector of float types, but we can only have one single float array
  8190. // for the ClipDistance/CullDistance builtin. So we need to group all
  8191. // SV_ClipDistance/SV_CullDistance variables into one float array, thus we
  8192. // need to calculate the total size of the array and the offset of each
  8193. // variable within that array.
  8194. // Also go through all parameters to record the semantic strings provided for
  8195. // the builtins in gl_PerVertex.
  8196. for (const auto *param : decl->params()) {
  8197. if (canActAsInParmVar(param))
  8198. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, true))
  8199. return false;
  8200. if (canActAsOutParmVar(param))
  8201. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, false))
  8202. return false;
  8203. }
  8204. // Also consider the SV_ClipDistance/SV_CullDistance in the return type
  8205. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(decl, false))
  8206. return false;
  8207. // Calculate the total size of the ClipDistance/CullDistance array and the
  8208. // offset of SV_ClipDistance/SV_CullDistance variables within the array.
  8209. declIdMapper.glPerVertex.calculateClipCullDistanceArraySize();
  8210. if (!shaderModel.IsCS()) {
  8211. // Generate the gl_PerVertex structs or stand-alone builtins of
  8212. // Position, ClipDistance, and CullDistance.
  8213. declIdMapper.glPerVertex.generateVars(inputArraySize, outputArraySize);
  8214. }
  8215. // Require the ClipDistance/CullDistance capability if necessary.
  8216. // It is legal to just use the ClipDistance/CullDistance builtin without
  8217. // requiring the ClipDistance/CullDistance capability, as long as we don't
  8218. // read or write the builtin variable.
  8219. // For our CodeGen, that corresponds to not seeing SV_ClipDistance or
  8220. // SV_CullDistance at all. If we see them, we will generate code to read
  8221. // them to initialize temporary variable for calling the source code entry
  8222. // function or write to them after calling the source code entry function.
  8223. declIdMapper.glPerVertex.requireCapabilityIfNecessary();
  8224. // The entry basic block.
  8225. const uint32_t entryLabel = theBuilder.createBasicBlock();
  8226. theBuilder.setInsertPoint(entryLabel);
  8227. // Initialize all global variables at the beginning of the wrapper
  8228. for (const VarDecl *varDecl : toInitGloalVars) {
  8229. const auto varInfo = declIdMapper.getDeclEvalInfo(varDecl);
  8230. if (const auto *init = varDecl->getInit()) {
  8231. storeValue(varInfo, doExpr(init), varDecl->getType());
  8232. // Update counter variable associated with global variables
  8233. tryToAssignCounterVar(varDecl, init);
  8234. }
  8235. // If not explicitly initialized, initialize with their zero values if not
  8236. // resource objects
  8237. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  8238. const auto typeId = typeTranslator.translateType(varDecl->getType());
  8239. theBuilder.createStore(varInfo, theBuilder.getConstantNull(typeId));
  8240. }
  8241. }
  8242. // Create temporary variables for holding function call arguments
  8243. llvm::SmallVector<uint32_t, 4> params;
  8244. for (const auto *param : decl->params()) {
  8245. const auto paramType = param->getType();
  8246. const uint32_t typeId = typeTranslator.translateType(paramType);
  8247. std::string tempVarName = "param.var." + param->getNameAsString();
  8248. const uint32_t tempVar = theBuilder.addFnVar(typeId, tempVarName);
  8249. params.push_back(tempVar);
  8250. // Create the stage input variable for parameter not marked as pure out and
  8251. // initialize the corresponding temporary variable
  8252. // Also do not create input variables for output stream objects of geometry
  8253. // shaders (e.g. TriangleStream) which are required to be marked as 'inout'.
  8254. if (canActAsInParmVar(param)) {
  8255. if (shaderModel.IsHS() && hlsl::IsHLSLInputPatchType(paramType)) {
  8256. // Record the temporary variable holding InputPatch. It may be used
  8257. // later in the patch constant function.
  8258. hullMainInputPatchParam = tempVar;
  8259. }
  8260. uint32_t loadedValue = 0;
  8261. if (!declIdMapper.createStageInputVar(param, &loadedValue, false))
  8262. return false;
  8263. theBuilder.createStore(tempVar, loadedValue);
  8264. // Record the temporary variable holding SV_OutputControlPointID,
  8265. // SV_PrimitiveID, and SV_ViewID. It may be used later in the patch
  8266. // constant function.
  8267. if (hasSemantic(param, hlsl::DXIL::SemanticKind::OutputControlPointID))
  8268. outputControlPointIdVal = loadedValue;
  8269. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID))
  8270. primitiveIdVar = tempVar;
  8271. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID))
  8272. viewIdVar = tempVar;
  8273. }
  8274. }
  8275. // Call the original entry function
  8276. const uint32_t retType = typeTranslator.translateType(decl->getReturnType());
  8277. const uint32_t retVal =
  8278. theBuilder.createFunctionCall(retType, entryFuncId, params);
  8279. // Create and write stage output variables for return value. Special case for
  8280. // Hull shaders since they operate differently in 2 ways:
  8281. // 1- Their return value is in fact an array and each invocation should write
  8282. // to the proper offset in the array.
  8283. // 2- The patch constant function must be called *once* after all invocations
  8284. // of the main entry point function is done.
  8285. if (shaderModel.IsHS()) {
  8286. // Create stage output variables out of the return type.
  8287. if (!declIdMapper.createStageOutputVar(decl, numOutputControlPoints,
  8288. outputControlPointIdVal, retVal))
  8289. return false;
  8290. if (!processHSEntryPointOutputAndPCF(
  8291. decl, retType, retVal, numOutputControlPoints,
  8292. outputControlPointIdVal, primitiveIdVar, viewIdVar,
  8293. hullMainInputPatchParam))
  8294. return false;
  8295. } else {
  8296. if (!declIdMapper.createStageOutputVar(decl, retVal, /*forPCF*/ false))
  8297. return false;
  8298. }
  8299. // Create and write stage output variables for parameters marked as
  8300. // out/inout
  8301. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  8302. const auto *param = decl->getParamDecl(i);
  8303. if (canActAsOutParmVar(param)) {
  8304. // Load the value from the parameter after function call
  8305. const uint32_t typeId = typeTranslator.translateType(param->getType());
  8306. uint32_t loadedParam = 0;
  8307. // Write back of stage output variables in GS is manually controlled by
  8308. // .Append() intrinsic method. No need to load the parameter since we
  8309. // won't need to write back here.
  8310. if (!shaderModel.IsGS())
  8311. loadedParam = theBuilder.createLoad(typeId, params[i]);
  8312. if (!declIdMapper.createStageOutputVar(param, loadedParam, false))
  8313. return false;
  8314. }
  8315. }
  8316. theBuilder.createReturn();
  8317. theBuilder.endFunction();
  8318. // For Hull shaders, there is no explicit call to the PCF in the HLSL source.
  8319. // We should invoke a translation of the PCF manually.
  8320. if (shaderModel.IsHS())
  8321. doDecl(patchConstFunc);
  8322. return true;
  8323. }
  8324. bool SPIRVEmitter::processHSEntryPointOutputAndPCF(
  8325. const FunctionDecl *hullMainFuncDecl, uint32_t retType, uint32_t retVal,
  8326. uint32_t numOutputControlPoints, uint32_t outputControlPointId,
  8327. uint32_t primitiveId, uint32_t viewId, uint32_t hullMainInputPatch) {
  8328. // This method may only be called for Hull shaders.
  8329. assert(shaderModel.IsHS());
  8330. // For Hull shaders, the real output is an array of size
  8331. // numOutputControlPoints. The results of the main should be written to the
  8332. // correct offset in the array (based on InvocationID).
  8333. if (!numOutputControlPoints) {
  8334. emitError("number of output control points cannot be zero",
  8335. hullMainFuncDecl->getLocation());
  8336. return false;
  8337. }
  8338. // TODO: We should be able to handle cases where the SV_OutputControlPointID
  8339. // is not provided.
  8340. if (!outputControlPointId) {
  8341. emitError(
  8342. "SV_OutputControlPointID semantic must be provided in hull shader",
  8343. hullMainFuncDecl->getLocation());
  8344. return false;
  8345. }
  8346. if (!patchConstFunc) {
  8347. emitError("patch constant function not defined in hull shader",
  8348. hullMainFuncDecl->getLocation());
  8349. return false;
  8350. }
  8351. uint32_t hullMainOutputPatch = 0;
  8352. // If the patch constant function (PCF) takes the result of the Hull main
  8353. // entry point, create a temporary function-scope variable and write the
  8354. // results to it, so it can be passed to the PCF.
  8355. if (patchConstFuncTakesHullOutputPatch(patchConstFunc)) {
  8356. const uint32_t hullMainRetType = theBuilder.getArrayType(
  8357. retType, theBuilder.getConstantUint32(numOutputControlPoints));
  8358. hullMainOutputPatch =
  8359. theBuilder.addFnVar(hullMainRetType, "temp.var.hullMainRetVal");
  8360. const auto tempLocation = theBuilder.createAccessChain(
  8361. theBuilder.getPointerType(retType, spv::StorageClass::Function),
  8362. hullMainOutputPatch, {outputControlPointId});
  8363. theBuilder.createStore(tempLocation, retVal);
  8364. }
  8365. // Now create a barrier before calling the Patch Constant Function (PCF).
  8366. // Flags are:
  8367. // Execution Barrier scope = Workgroup (2)
  8368. // Memory Barrier scope = Device (1)
  8369. // Memory Semantics Barrier scope = None (0)
  8370. theBuilder.createBarrier(theBuilder.getConstantUint32(2),
  8371. theBuilder.getConstantUint32(4),
  8372. theBuilder.getConstantUint32(0));
  8373. // The PCF should be called only once. Therefore, we check the invocationID,
  8374. // and we only allow ID 0 to call the PCF.
  8375. const uint32_t condition = theBuilder.createBinaryOp(
  8376. spv::Op::OpIEqual, theBuilder.getBoolType(), outputControlPointId,
  8377. theBuilder.getConstantUint32(0));
  8378. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  8379. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  8380. theBuilder.createConditionalBranch(condition, thenBB, mergeBB, mergeBB);
  8381. theBuilder.addSuccessor(thenBB);
  8382. theBuilder.addSuccessor(mergeBB);
  8383. theBuilder.setMergeTarget(mergeBB);
  8384. theBuilder.setInsertPoint(thenBB);
  8385. // Call the PCF. Since the function is not explicitly called, we must first
  8386. // register an ID for it.
  8387. const uint32_t pcfId = declIdMapper.getOrRegisterFnResultId(patchConstFunc);
  8388. const uint32_t pcfRetType =
  8389. typeTranslator.translateType(patchConstFunc->getReturnType());
  8390. std::vector<uint32_t> pcfParams;
  8391. // A lambda for creating a stage input variable and its associated temporary
  8392. // variable for function call. Also initializes the temporary variable using
  8393. // the contents loaded from the stage input variable. Returns the <result-id>
  8394. // of the temporary variable.
  8395. const auto createParmVarAndInitFromStageInputVar =
  8396. [this](const ParmVarDecl *param) {
  8397. const uint32_t typeId = typeTranslator.translateType(param->getType());
  8398. std::string tempVarName = "param.var." + param->getNameAsString();
  8399. const uint32_t tempVar = theBuilder.addFnVar(typeId, tempVarName);
  8400. uint32_t loadedValue = 0;
  8401. declIdMapper.createStageInputVar(param, &loadedValue, /*forPCF*/ true);
  8402. theBuilder.createStore(tempVar, loadedValue);
  8403. return tempVar;
  8404. };
  8405. for (const auto *param : patchConstFunc->parameters()) {
  8406. // Note: According to the HLSL reference, the PCF takes an InputPatch of
  8407. // ControlPoints as well as the PatchID (PrimitiveID). This does not
  8408. // necessarily mean that they are present. There is also no requirement
  8409. // for the order of parameters passed to PCF.
  8410. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  8411. pcfParams.push_back(hullMainInputPatch);
  8412. } else if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  8413. pcfParams.push_back(hullMainOutputPatch);
  8414. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID)) {
  8415. if (!primitiveId) {
  8416. primitiveId = createParmVarAndInitFromStageInputVar(param);
  8417. }
  8418. pcfParams.push_back(primitiveId);
  8419. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID)) {
  8420. if (!viewId) {
  8421. viewId = createParmVarAndInitFromStageInputVar(param);
  8422. }
  8423. pcfParams.push_back(viewId);
  8424. } else {
  8425. emitError("patch constant function parameter '%0' unknown",
  8426. param->getLocation())
  8427. << param->getName();
  8428. }
  8429. }
  8430. const uint32_t pcfResultId =
  8431. theBuilder.createFunctionCall(pcfRetType, pcfId, {pcfParams});
  8432. if (!declIdMapper.createStageOutputVar(patchConstFunc, pcfResultId,
  8433. /*forPCF*/ true))
  8434. return false;
  8435. theBuilder.createBranch(mergeBB);
  8436. theBuilder.addSuccessor(mergeBB);
  8437. theBuilder.setInsertPoint(mergeBB);
  8438. return true;
  8439. }
  8440. bool SPIRVEmitter::allSwitchCasesAreIntegerLiterals(const Stmt *root) {
  8441. if (!root)
  8442. return false;
  8443. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8444. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8445. if (!caseStmt && !compoundStmt)
  8446. return true;
  8447. if (caseStmt) {
  8448. const Expr *caseExpr = caseStmt->getLHS();
  8449. return caseExpr && caseExpr->isEvaluatable(astContext);
  8450. }
  8451. // Recurse down if facing a compound statement.
  8452. for (auto *st : compoundStmt->body())
  8453. if (!allSwitchCasesAreIntegerLiterals(st))
  8454. return false;
  8455. return true;
  8456. }
  8457. void SPIRVEmitter::discoverAllCaseStmtInSwitchStmt(
  8458. const Stmt *root, uint32_t *defaultBB,
  8459. std::vector<std::pair<uint32_t, uint32_t>> *targets) {
  8460. if (!root)
  8461. return;
  8462. // A switch case can only appear in DefaultStmt, CaseStmt, or
  8463. // CompoundStmt. For the rest, we can just return.
  8464. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  8465. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8466. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8467. if (!defaultStmt && !caseStmt && !compoundStmt)
  8468. return;
  8469. // Recurse down if facing a compound statement.
  8470. if (compoundStmt) {
  8471. for (auto *st : compoundStmt->body())
  8472. discoverAllCaseStmtInSwitchStmt(st, defaultBB, targets);
  8473. return;
  8474. }
  8475. std::string caseLabel;
  8476. uint32_t caseValue = 0;
  8477. if (defaultStmt) {
  8478. // This is the default branch.
  8479. caseLabel = "switch.default";
  8480. } else if (caseStmt) {
  8481. // This is a non-default case.
  8482. // When using OpSwitch, we only allow integer literal cases. e.g:
  8483. // case <literal_integer>: {...; break;}
  8484. const Expr *caseExpr = caseStmt->getLHS();
  8485. assert(caseExpr && caseExpr->isEvaluatable(astContext));
  8486. auto bitWidth = astContext.getIntWidth(caseExpr->getType());
  8487. if (bitWidth != 32)
  8488. emitError(
  8489. "non-32bit integer case value in switch statement unimplemented",
  8490. caseExpr->getExprLoc());
  8491. Expr::EvalResult evalResult;
  8492. caseExpr->EvaluateAsRValue(evalResult, astContext);
  8493. const int64_t value = evalResult.Val.getInt().getSExtValue();
  8494. caseValue = static_cast<uint32_t>(value);
  8495. caseLabel = "switch." + std::string(value < 0 ? "n" : "") +
  8496. llvm::itostr(std::abs(value));
  8497. }
  8498. const uint32_t caseBB = theBuilder.createBasicBlock(caseLabel);
  8499. theBuilder.addSuccessor(caseBB);
  8500. stmtBasicBlock[root] = caseBB;
  8501. // Add all cases to the 'targets' vector.
  8502. if (caseStmt)
  8503. targets->emplace_back(caseValue, caseBB);
  8504. // The default label is not part of the 'targets' vector that is passed
  8505. // to the OpSwitch instruction.
  8506. // If default statement was discovered, return its label via defaultBB.
  8507. if (defaultStmt)
  8508. *defaultBB = caseBB;
  8509. // Process cases nested in other cases. It happens when we have fall through
  8510. // cases. For example:
  8511. // case 1: case 2: ...; break;
  8512. // will result in the CaseSmt for case 2 nested in the one for case 1.
  8513. discoverAllCaseStmtInSwitchStmt(caseStmt ? caseStmt->getSubStmt()
  8514. : defaultStmt->getSubStmt(),
  8515. defaultBB, targets);
  8516. }
  8517. void SPIRVEmitter::flattenSwitchStmtAST(const Stmt *root,
  8518. std::vector<const Stmt *> *flatSwitch) {
  8519. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8520. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8521. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  8522. if (!compoundStmt) {
  8523. flatSwitch->push_back(root);
  8524. }
  8525. if (compoundStmt) {
  8526. for (const auto *st : compoundStmt->body())
  8527. flattenSwitchStmtAST(st, flatSwitch);
  8528. } else if (caseStmt) {
  8529. flattenSwitchStmtAST(caseStmt->getSubStmt(), flatSwitch);
  8530. } else if (defaultStmt) {
  8531. flattenSwitchStmtAST(defaultStmt->getSubStmt(), flatSwitch);
  8532. }
  8533. }
  8534. void SPIRVEmitter::processCaseStmtOrDefaultStmt(const Stmt *stmt) {
  8535. auto *caseStmt = dyn_cast<CaseStmt>(stmt);
  8536. auto *defaultStmt = dyn_cast<DefaultStmt>(stmt);
  8537. assert(caseStmt || defaultStmt);
  8538. uint32_t caseBB = stmtBasicBlock[stmt];
  8539. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  8540. // We are about to handle the case passed in as parameter. If the current
  8541. // basic block is not terminated, it means the previous case is a fall
  8542. // through case. We need to link it to the case to be processed.
  8543. theBuilder.createBranch(caseBB);
  8544. theBuilder.addSuccessor(caseBB);
  8545. }
  8546. theBuilder.setInsertPoint(caseBB);
  8547. doStmt(caseStmt ? caseStmt->getSubStmt() : defaultStmt->getSubStmt());
  8548. }
  8549. void SPIRVEmitter::processSwitchStmtUsingSpirvOpSwitch(
  8550. const SwitchStmt *switchStmt) {
  8551. // First handle the condition variable DeclStmt if one exists.
  8552. // For example: handle 'int a = b' in the following:
  8553. // switch (int a = b) {...}
  8554. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  8555. doDeclStmt(condVarDeclStmt);
  8556. const uint32_t selector = doExpr(switchStmt->getCond());
  8557. // We need a merge block regardless of the number of switch cases.
  8558. // Since OpSwitch always requires a default label, if the switch statement
  8559. // does not have a default branch, we use the merge block as the default
  8560. // target.
  8561. const uint32_t mergeBB = theBuilder.createBasicBlock("switch.merge");
  8562. theBuilder.setMergeTarget(mergeBB);
  8563. breakStack.push(mergeBB);
  8564. uint32_t defaultBB = mergeBB;
  8565. // (literal, labelId) pairs to pass to the OpSwitch instruction.
  8566. std::vector<std::pair<uint32_t, uint32_t>> targets;
  8567. discoverAllCaseStmtInSwitchStmt(switchStmt->getBody(), &defaultBB, &targets);
  8568. // Create the OpSelectionMerge and OpSwitch.
  8569. theBuilder.createSwitch(mergeBB, selector, defaultBB, targets);
  8570. // Handle the switch body.
  8571. doStmt(switchStmt->getBody());
  8572. if (!theBuilder.isCurrentBasicBlockTerminated())
  8573. theBuilder.createBranch(mergeBB);
  8574. theBuilder.setInsertPoint(mergeBB);
  8575. breakStack.pop();
  8576. }
  8577. void SPIRVEmitter::processSwitchStmtUsingIfStmts(const SwitchStmt *switchStmt) {
  8578. std::vector<const Stmt *> flatSwitch;
  8579. flattenSwitchStmtAST(switchStmt->getBody(), &flatSwitch);
  8580. // First handle the condition variable DeclStmt if one exists.
  8581. // For example: handle 'int a = b' in the following:
  8582. // switch (int a = b) {...}
  8583. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  8584. doDeclStmt(condVarDeclStmt);
  8585. // Figure out the indexes of CaseStmts (and DefaultStmt if it exists) in
  8586. // the flattened switch AST.
  8587. // For instance, for the following flat vector:
  8588. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  8589. // |Case1|Stmt1|Case2|Stmt2|Break|Case3|Case4|Stmt4|Break|Default|Stmt5|
  8590. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  8591. // The indexes are: {0, 2, 5, 6, 9}
  8592. std::vector<uint32_t> caseStmtLocs;
  8593. for (uint32_t i = 0; i < flatSwitch.size(); ++i)
  8594. if (isa<CaseStmt>(flatSwitch[i]) || isa<DefaultStmt>(flatSwitch[i]))
  8595. caseStmtLocs.push_back(i);
  8596. IfStmt *prevIfStmt = nullptr;
  8597. IfStmt *rootIfStmt = nullptr;
  8598. CompoundStmt *defaultBody = nullptr;
  8599. // For each case, start at its index in the vector, and go forward
  8600. // accumulating statements until BreakStmt or end of vector is reached.
  8601. for (auto curCaseIndex : caseStmtLocs) {
  8602. const Stmt *curCase = flatSwitch[curCaseIndex];
  8603. // CompoundStmt to hold all statements for this case.
  8604. CompoundStmt *cs = new (astContext) CompoundStmt(Stmt::EmptyShell());
  8605. // Accumulate all non-case/default/break statements as the body for the
  8606. // current case.
  8607. std::vector<Stmt *> statements;
  8608. for (int i = curCaseIndex + 1;
  8609. i < flatSwitch.size() && !isa<BreakStmt>(flatSwitch[i]); ++i) {
  8610. if (!isa<CaseStmt>(flatSwitch[i]) && !isa<DefaultStmt>(flatSwitch[i]))
  8611. statements.push_back(const_cast<Stmt *>(flatSwitch[i]));
  8612. }
  8613. if (!statements.empty())
  8614. cs->setStmts(astContext, statements.data(), statements.size());
  8615. // For non-default cases, generate the IfStmt that compares the switch
  8616. // value to the case value.
  8617. if (auto *caseStmt = dyn_cast<CaseStmt>(curCase)) {
  8618. IfStmt *curIf = new (astContext) IfStmt(Stmt::EmptyShell());
  8619. BinaryOperator *bo = new (astContext) BinaryOperator(Stmt::EmptyShell());
  8620. bo->setLHS(const_cast<Expr *>(switchStmt->getCond()));
  8621. bo->setRHS(const_cast<Expr *>(caseStmt->getLHS()));
  8622. bo->setOpcode(BO_EQ);
  8623. bo->setType(astContext.getLogicalOperationType());
  8624. curIf->setCond(bo);
  8625. curIf->setThen(cs);
  8626. // No conditional variable associated with this faux if statement.
  8627. curIf->setConditionVariable(astContext, nullptr);
  8628. // Each If statement is the "else" of the previous if statement.
  8629. if (prevIfStmt)
  8630. prevIfStmt->setElse(curIf);
  8631. else
  8632. rootIfStmt = curIf;
  8633. prevIfStmt = curIf;
  8634. } else {
  8635. // Record the DefaultStmt body as it will be used as the body of the
  8636. // "else" block in the if-elseif-...-else pattern.
  8637. defaultBody = cs;
  8638. }
  8639. }
  8640. // If a default case exists, it is the "else" of the last if statement.
  8641. if (prevIfStmt)
  8642. prevIfStmt->setElse(defaultBody);
  8643. // Since all else-if and else statements are the child nodes of the first
  8644. // IfStmt, we only need to call doStmt for the first IfStmt.
  8645. if (rootIfStmt)
  8646. doStmt(rootIfStmt);
  8647. // If there are no CaseStmt and there is only 1 DefaultStmt, there will be
  8648. // no if statements. The switch in that case only executes the body of the
  8649. // default case.
  8650. else if (defaultBody)
  8651. doStmt(defaultBody);
  8652. }
  8653. uint32_t SPIRVEmitter::extractVecFromVec4(uint32_t fromId,
  8654. uint32_t targetVecSize,
  8655. uint32_t targetElemTypeId) {
  8656. assert(targetVecSize > 0 && targetVecSize < 5);
  8657. const uint32_t retType =
  8658. targetVecSize == 1
  8659. ? targetElemTypeId
  8660. : theBuilder.getVecType(targetElemTypeId, targetVecSize);
  8661. switch (targetVecSize) {
  8662. case 1:
  8663. return theBuilder.createCompositeExtract(retType, fromId, {0});
  8664. break;
  8665. case 2:
  8666. return theBuilder.createVectorShuffle(retType, fromId, fromId, {0, 1});
  8667. break;
  8668. case 3:
  8669. return theBuilder.createVectorShuffle(retType, fromId, fromId, {0, 1, 2});
  8670. break;
  8671. case 4:
  8672. return fromId;
  8673. default:
  8674. llvm_unreachable("vector element count must be 1, 2, 3, or 4");
  8675. }
  8676. }
  8677. } // end namespace spirv
  8678. } // end namespace clang