spirv_msl.cpp 732 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527
  1. /*
  2. * Copyright 2016-2021 The Brenwill Workshop Ltd.
  3. * SPDX-License-Identifier: Apache-2.0 OR MIT
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*
  18. * At your option, you may choose to accept this material under either:
  19. * 1. The Apache License, Version 2.0, found at <http://www.apache.org/licenses/LICENSE-2.0>, or
  20. * 2. The MIT License, found at <http://opensource.org/licenses/MIT>.
  21. */
  22. #include "spirv_msl.hpp"
  23. #include "GLSL.std.450.h"
  24. #include <algorithm>
  25. #include <assert.h>
  26. #include <numeric>
  27. using namespace SPIRV_CROSS_SPV_HEADER_NAMESPACE;
  28. using namespace SPIRV_CROSS_NAMESPACE;
  29. using namespace std;
  30. static const uint32_t k_unknown_location = ~0u;
  31. static const uint32_t k_unknown_component = ~0u;
  32. static const char *force_inline = "static inline __attribute__((always_inline))";
  33. CompilerMSL::CompilerMSL(std::vector<uint32_t> spirv_)
  34. : CompilerGLSL(std::move(spirv_))
  35. {
  36. }
  37. CompilerMSL::CompilerMSL(const uint32_t *ir_, size_t word_count)
  38. : CompilerGLSL(ir_, word_count)
  39. {
  40. }
  41. CompilerMSL::CompilerMSL(const ParsedIR &ir_)
  42. : CompilerGLSL(ir_)
  43. {
  44. }
  45. CompilerMSL::CompilerMSL(ParsedIR &&ir_)
  46. : CompilerGLSL(std::move(ir_))
  47. {
  48. }
  49. void CompilerMSL::add_msl_shader_input(const MSLShaderInterfaceVariable &si)
  50. {
  51. inputs_by_location[{si.location, si.component}] = si;
  52. if (si.builtin != BuiltInMax && !inputs_by_builtin.count(si.builtin))
  53. inputs_by_builtin[si.builtin] = si;
  54. }
  55. void CompilerMSL::add_msl_shader_output(const MSLShaderInterfaceVariable &so)
  56. {
  57. outputs_by_location[{so.location, so.component}] = so;
  58. if (so.builtin != BuiltInMax && !outputs_by_builtin.count(so.builtin))
  59. outputs_by_builtin[so.builtin] = so;
  60. }
  61. void CompilerMSL::add_msl_resource_binding(const MSLResourceBinding &binding)
  62. {
  63. StageSetBinding tuple = { binding.stage, binding.desc_set, binding.binding };
  64. resource_bindings[tuple] = { binding, false };
  65. // If we might need to pad argument buffer members to positionally align
  66. // arg buffer indexes, also maintain a lookup by argument buffer index.
  67. if (msl_options.pad_argument_buffer_resources)
  68. {
  69. StageSetBinding arg_idx_tuple = { binding.stage, binding.desc_set, k_unknown_component };
  70. #define ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(rez) \
  71. arg_idx_tuple.binding = binding.msl_##rez; \
  72. resource_arg_buff_idx_to_binding_number[arg_idx_tuple] = binding.binding
  73. switch (binding.basetype)
  74. {
  75. case SPIRType::Void:
  76. case SPIRType::Boolean:
  77. case SPIRType::SByte:
  78. case SPIRType::UByte:
  79. case SPIRType::Short:
  80. case SPIRType::UShort:
  81. case SPIRType::Int:
  82. case SPIRType::UInt:
  83. case SPIRType::Int64:
  84. case SPIRType::UInt64:
  85. case SPIRType::AtomicCounter:
  86. case SPIRType::Half:
  87. case SPIRType::Float:
  88. case SPIRType::Double:
  89. ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(buffer);
  90. break;
  91. case SPIRType::Image:
  92. ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(texture);
  93. break;
  94. case SPIRType::Sampler:
  95. ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(sampler);
  96. break;
  97. case SPIRType::SampledImage:
  98. ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(texture);
  99. ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(sampler);
  100. break;
  101. default:
  102. SPIRV_CROSS_THROW("Unexpected argument buffer resource base type. When padding argument buffer elements, "
  103. "all descriptor set resources must be supplied with a base type by the app.");
  104. }
  105. #undef ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP
  106. }
  107. }
  108. void CompilerMSL::add_dynamic_buffer(uint32_t desc_set, uint32_t binding, uint32_t index)
  109. {
  110. SetBindingPair pair = { desc_set, binding };
  111. buffers_requiring_dynamic_offset[pair] = { index, 0, "" };
  112. }
  113. void CompilerMSL::add_inline_uniform_block(uint32_t desc_set, uint32_t binding)
  114. {
  115. SetBindingPair pair = { desc_set, binding };
  116. inline_uniform_blocks.insert(pair);
  117. }
  118. void CompilerMSL::add_discrete_descriptor_set(uint32_t desc_set)
  119. {
  120. if (desc_set < kMaxArgumentBuffers)
  121. argument_buffer_discrete_mask |= 1u << desc_set;
  122. }
  123. void CompilerMSL::set_argument_buffer_device_address_space(uint32_t desc_set, bool device_storage)
  124. {
  125. if (desc_set < kMaxArgumentBuffers)
  126. {
  127. if (device_storage)
  128. argument_buffer_device_storage_mask |= 1u << desc_set;
  129. else
  130. argument_buffer_device_storage_mask &= ~(1u << desc_set);
  131. }
  132. }
  133. bool CompilerMSL::is_msl_shader_input_used(uint32_t location)
  134. {
  135. // Don't report internal location allocations to app.
  136. return location_inputs_in_use.count(location) != 0 &&
  137. location_inputs_in_use_fallback.count(location) == 0;
  138. }
  139. bool CompilerMSL::is_msl_shader_output_used(uint32_t location)
  140. {
  141. // Don't report internal location allocations to app.
  142. return location_outputs_in_use.count(location) != 0 &&
  143. location_outputs_in_use_fallback.count(location) == 0;
  144. }
  145. uint32_t CompilerMSL::get_automatic_builtin_input_location(BuiltIn builtin) const
  146. {
  147. auto itr = builtin_to_automatic_input_location.find(builtin);
  148. if (itr == builtin_to_automatic_input_location.end())
  149. return k_unknown_location;
  150. else
  151. return itr->second;
  152. }
  153. uint32_t CompilerMSL::get_automatic_builtin_output_location(BuiltIn builtin) const
  154. {
  155. auto itr = builtin_to_automatic_output_location.find(builtin);
  156. if (itr == builtin_to_automatic_output_location.end())
  157. return k_unknown_location;
  158. else
  159. return itr->second;
  160. }
  161. bool CompilerMSL::is_msl_resource_binding_used(ExecutionModel model, uint32_t desc_set, uint32_t binding) const
  162. {
  163. StageSetBinding tuple = { model, desc_set, binding };
  164. auto itr = resource_bindings.find(tuple);
  165. return itr != end(resource_bindings) && itr->second.second;
  166. }
  167. bool CompilerMSL::is_var_runtime_size_array(const SPIRVariable &var) const
  168. {
  169. auto& type = get_variable_data_type(var);
  170. return is_runtime_size_array(type) && get_resource_array_size(type, var.self) == 0;
  171. }
  172. // Returns the size of the array of resources used by the variable with the specified type and id.
  173. // The size is first retrieved from the type, but in the case of runtime array sizing,
  174. // the size is retrieved from the resource binding added using add_msl_resource_binding().
  175. uint32_t CompilerMSL::get_resource_array_size(const SPIRType &type, uint32_t id) const
  176. {
  177. uint32_t array_size = to_array_size_literal(type);
  178. if (id == 0)
  179. return array_size;
  180. // If we have argument buffers, we need to honor the ABI by using the correct array size
  181. // from the layout. Only use shader declared size if we're not using argument buffers.
  182. uint32_t desc_set = get_decoration(id, DecorationDescriptorSet);
  183. if (!descriptor_set_is_argument_buffer(desc_set) && array_size)
  184. return array_size;
  185. StageSetBinding tuple = { get_entry_point().model, desc_set,
  186. get_decoration(id, DecorationBinding) };
  187. auto itr = resource_bindings.find(tuple);
  188. return itr != end(resource_bindings) ? itr->second.first.count : array_size;
  189. }
  190. uint32_t CompilerMSL::get_automatic_msl_resource_binding(uint32_t id) const
  191. {
  192. return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexPrimary);
  193. }
  194. uint32_t CompilerMSL::get_automatic_msl_resource_binding_secondary(uint32_t id) const
  195. {
  196. return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexSecondary);
  197. }
  198. uint32_t CompilerMSL::get_automatic_msl_resource_binding_tertiary(uint32_t id) const
  199. {
  200. return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexTertiary);
  201. }
  202. uint32_t CompilerMSL::get_automatic_msl_resource_binding_quaternary(uint32_t id) const
  203. {
  204. return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexQuaternary);
  205. }
  206. void CompilerMSL::set_fragment_output_components(uint32_t location, uint32_t components)
  207. {
  208. fragment_output_components[location] = components;
  209. }
  210. bool CompilerMSL::builtin_translates_to_nonarray(BuiltIn builtin) const
  211. {
  212. return (builtin == BuiltInSampleMask);
  213. }
  214. void CompilerMSL::build_implicit_builtins()
  215. {
  216. bool need_sample_pos = active_input_builtins.get(BuiltInSamplePosition);
  217. bool need_vertex_params = capture_output_to_buffer && get_execution_model() == ExecutionModelVertex &&
  218. !msl_options.vertex_for_tessellation;
  219. bool need_tesc_params = is_tesc_shader();
  220. bool need_tese_params = is_tese_shader() && msl_options.raw_buffer_tese_input;
  221. bool need_subgroup_mask =
  222. active_input_builtins.get(BuiltInSubgroupEqMask) || active_input_builtins.get(BuiltInSubgroupGeMask) ||
  223. active_input_builtins.get(BuiltInSubgroupGtMask) || active_input_builtins.get(BuiltInSubgroupLeMask) ||
  224. active_input_builtins.get(BuiltInSubgroupLtMask);
  225. bool need_subgroup_ge_mask = !msl_options.is_ios() && (active_input_builtins.get(BuiltInSubgroupGeMask) ||
  226. active_input_builtins.get(BuiltInSubgroupGtMask));
  227. bool need_multiview = get_execution_model() == ExecutionModelVertex && !msl_options.view_index_from_device_index &&
  228. msl_options.multiview_layered_rendering &&
  229. (msl_options.multiview || active_input_builtins.get(BuiltInViewIndex));
  230. bool need_dispatch_base =
  231. msl_options.dispatch_base && get_execution_model() == ExecutionModelGLCompute &&
  232. (active_input_builtins.get(BuiltInWorkgroupId) || active_input_builtins.get(BuiltInGlobalInvocationId));
  233. bool need_grid_params = get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation;
  234. bool need_vertex_base_params =
  235. need_grid_params &&
  236. (active_input_builtins.get(BuiltInVertexId) || active_input_builtins.get(BuiltInVertexIndex) ||
  237. active_input_builtins.get(BuiltInBaseVertex) || active_input_builtins.get(BuiltInInstanceId) ||
  238. active_input_builtins.get(BuiltInInstanceIndex) || active_input_builtins.get(BuiltInBaseInstance));
  239. bool need_local_invocation_index =
  240. (msl_options.emulate_subgroups && active_input_builtins.get(BuiltInSubgroupId)) || is_mesh_shader() ||
  241. needs_workgroup_zero_init || needs_local_invocation_index;
  242. bool need_workgroup_size = msl_options.emulate_subgroups && active_input_builtins.get(BuiltInNumSubgroups);
  243. bool force_frag_depth_passthrough =
  244. get_execution_model() == ExecutionModelFragment && !uses_explicit_early_fragment_test() && need_subpass_input &&
  245. msl_options.enable_frag_depth_builtin && msl_options.input_attachment_is_ds_attachment;
  246. needs_point_size_output =
  247. msl_options.enable_point_size_builtin && msl_options.enable_point_size_default &&
  248. entry_point_is_vertex();
  249. if (need_subpass_input || need_sample_pos || need_subgroup_mask || need_vertex_params || need_tesc_params ||
  250. need_tese_params || need_multiview || need_dispatch_base || need_vertex_base_params || need_grid_params ||
  251. needs_sample_id || needs_subgroup_invocation_id || needs_subgroup_size || needs_helper_invocation ||
  252. has_additional_fixed_sample_mask() || need_local_invocation_index || need_workgroup_size ||
  253. force_frag_depth_passthrough || needs_point_size_output || is_mesh_shader())
  254. {
  255. bool has_frag_coord = false;
  256. bool has_sample_id = false;
  257. bool has_vertex_idx = false;
  258. bool has_base_vertex = false;
  259. bool has_instance_idx = false;
  260. bool has_base_instance = false;
  261. bool has_invocation_id = false;
  262. bool has_primitive_id = false;
  263. bool has_subgroup_invocation_id = false;
  264. bool has_subgroup_size = false;
  265. bool has_view_idx = false;
  266. bool has_layer = false;
  267. bool has_helper_invocation = false;
  268. bool has_local_invocation_index = false;
  269. bool has_workgroup_size = false;
  270. bool has_frag_depth = false;
  271. bool has_point_size = false;
  272. uint32_t workgroup_id_type = 0;
  273. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
  274. if (var.storage != StorageClassInput && var.storage != StorageClassOutput)
  275. return;
  276. if (!interface_variable_exists_in_entry_point(var.self))
  277. return;
  278. auto &type = this->get<SPIRType>(var.basetype);
  279. if (needs_point_size_output && has_decoration(type.self, DecorationBlock))
  280. {
  281. const auto member_count = static_cast<uint32_t>(type.member_types.size());
  282. for (uint32_t i = 0; i < member_count; i++)
  283. {
  284. if (get_member_decoration(type.self, i, DecorationBuiltIn) == BuiltInPointSize)
  285. {
  286. has_point_size = true;
  287. active_output_builtins.set(BuiltInPointSize);
  288. break;
  289. }
  290. }
  291. }
  292. if (!has_decoration(var.self, DecorationBuiltIn))
  293. return;
  294. BuiltIn builtin = ir.meta[var.self].decoration.builtin_type;
  295. if (var.storage == StorageClassOutput)
  296. {
  297. if (has_additional_fixed_sample_mask() && builtin == BuiltInSampleMask)
  298. {
  299. builtin_sample_mask_id = var.self;
  300. mark_implicit_builtin(StorageClassOutput, BuiltInSampleMask, var.self);
  301. does_shader_write_sample_mask = true;
  302. }
  303. if (force_frag_depth_passthrough && builtin == BuiltInFragDepth)
  304. {
  305. builtin_frag_depth_id = var.self;
  306. mark_implicit_builtin(StorageClassOutput, BuiltInFragDepth, var.self);
  307. has_frag_depth = true;
  308. }
  309. }
  310. if (builtin == BuiltInPointSize)
  311. {
  312. has_point_size = true;
  313. active_output_builtins.set(BuiltInPointSize);
  314. }
  315. if (builtin == BuiltInPrimitivePointIndicesEXT ||
  316. builtin == BuiltInPrimitiveLineIndicesEXT ||
  317. builtin == BuiltInPrimitiveTriangleIndicesEXT)
  318. {
  319. builtin_mesh_primitive_indices_id = var.self;
  320. }
  321. if (var.storage != StorageClassInput)
  322. return;
  323. // Use Metal's native frame-buffer fetch API for subpass inputs.
  324. if (need_subpass_input && (!msl_options.use_framebuffer_fetch_subpasses))
  325. {
  326. switch (builtin)
  327. {
  328. case BuiltInFragCoord:
  329. mark_implicit_builtin(StorageClassInput, BuiltInFragCoord, var.self);
  330. builtin_frag_coord_id = var.self;
  331. has_frag_coord = true;
  332. break;
  333. case BuiltInLayer:
  334. if (!msl_options.arrayed_subpass_input || msl_options.multiview)
  335. break;
  336. mark_implicit_builtin(StorageClassInput, BuiltInLayer, var.self);
  337. builtin_layer_id = var.self;
  338. has_layer = true;
  339. break;
  340. case BuiltInViewIndex:
  341. if (!msl_options.multiview)
  342. break;
  343. mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var.self);
  344. builtin_view_idx_id = var.self;
  345. has_view_idx = true;
  346. break;
  347. default:
  348. break;
  349. }
  350. }
  351. if ((need_sample_pos || needs_sample_id) && builtin == BuiltInSampleId)
  352. {
  353. builtin_sample_id_id = var.self;
  354. mark_implicit_builtin(StorageClassInput, BuiltInSampleId, var.self);
  355. has_sample_id = true;
  356. }
  357. if (need_vertex_params)
  358. {
  359. switch (builtin)
  360. {
  361. case BuiltInVertexIndex:
  362. builtin_vertex_idx_id = var.self;
  363. mark_implicit_builtin(StorageClassInput, BuiltInVertexIndex, var.self);
  364. has_vertex_idx = true;
  365. break;
  366. case BuiltInBaseVertex:
  367. builtin_base_vertex_id = var.self;
  368. mark_implicit_builtin(StorageClassInput, BuiltInBaseVertex, var.self);
  369. has_base_vertex = true;
  370. break;
  371. case BuiltInInstanceIndex:
  372. builtin_instance_idx_id = var.self;
  373. mark_implicit_builtin(StorageClassInput, BuiltInInstanceIndex, var.self);
  374. has_instance_idx = true;
  375. break;
  376. case BuiltInBaseInstance:
  377. builtin_base_instance_id = var.self;
  378. mark_implicit_builtin(StorageClassInput, BuiltInBaseInstance, var.self);
  379. has_base_instance = true;
  380. break;
  381. default:
  382. break;
  383. }
  384. }
  385. if (need_tesc_params && builtin == BuiltInInvocationId)
  386. {
  387. builtin_invocation_id_id = var.self;
  388. mark_implicit_builtin(StorageClassInput, BuiltInInvocationId, var.self);
  389. has_invocation_id = true;
  390. }
  391. if ((need_tesc_params || need_tese_params) && builtin == BuiltInPrimitiveId)
  392. {
  393. builtin_primitive_id_id = var.self;
  394. mark_implicit_builtin(StorageClassInput, BuiltInPrimitiveId, var.self);
  395. has_primitive_id = true;
  396. }
  397. if (need_tese_params && builtin == BuiltInTessLevelOuter)
  398. {
  399. tess_level_outer_var_id = var.self;
  400. }
  401. if (need_tese_params && builtin == BuiltInTessLevelInner)
  402. {
  403. tess_level_inner_var_id = var.self;
  404. }
  405. if ((need_subgroup_mask || needs_subgroup_invocation_id) && builtin == BuiltInSubgroupLocalInvocationId)
  406. {
  407. builtin_subgroup_invocation_id_id = var.self;
  408. mark_implicit_builtin(StorageClassInput, BuiltInSubgroupLocalInvocationId, var.self);
  409. has_subgroup_invocation_id = true;
  410. }
  411. if ((need_subgroup_ge_mask || needs_subgroup_size) && builtin == BuiltInSubgroupSize)
  412. {
  413. builtin_subgroup_size_id = var.self;
  414. mark_implicit_builtin(StorageClassInput, BuiltInSubgroupSize, var.self);
  415. has_subgroup_size = true;
  416. }
  417. if (need_multiview)
  418. {
  419. switch (builtin)
  420. {
  421. case BuiltInInstanceIndex:
  422. // The view index here is derived from the instance index.
  423. builtin_instance_idx_id = var.self;
  424. mark_implicit_builtin(StorageClassInput, BuiltInInstanceIndex, var.self);
  425. has_instance_idx = true;
  426. break;
  427. case BuiltInBaseInstance:
  428. // If a non-zero base instance is used, we need to adjust for it when calculating the view index.
  429. builtin_base_instance_id = var.self;
  430. mark_implicit_builtin(StorageClassInput, BuiltInBaseInstance, var.self);
  431. has_base_instance = true;
  432. break;
  433. case BuiltInViewIndex:
  434. builtin_view_idx_id = var.self;
  435. mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var.self);
  436. has_view_idx = true;
  437. break;
  438. default:
  439. break;
  440. }
  441. }
  442. if (needs_helper_invocation && builtin == BuiltInHelperInvocation)
  443. {
  444. builtin_helper_invocation_id = var.self;
  445. mark_implicit_builtin(StorageClassInput, BuiltInHelperInvocation, var.self);
  446. has_helper_invocation = true;
  447. }
  448. if (need_local_invocation_index && builtin == BuiltInLocalInvocationIndex)
  449. {
  450. builtin_local_invocation_index_id = var.self;
  451. mark_implicit_builtin(StorageClassInput, BuiltInLocalInvocationIndex, var.self);
  452. has_local_invocation_index = true;
  453. }
  454. if (need_workgroup_size && builtin == BuiltInWorkgroupSize)
  455. {
  456. builtin_workgroup_size_id = var.self;
  457. mark_implicit_builtin(StorageClassInput, BuiltInWorkgroupSize, var.self);
  458. has_workgroup_size = true;
  459. }
  460. // The base workgroup needs to have the same type and vector size
  461. // as the workgroup or invocation ID, so keep track of the type that
  462. // was used.
  463. if (need_dispatch_base && workgroup_id_type == 0 &&
  464. (builtin == BuiltInWorkgroupId || builtin == BuiltInGlobalInvocationId))
  465. workgroup_id_type = var.basetype;
  466. });
  467. // Use Metal's native frame-buffer fetch API for subpass inputs.
  468. if ((!has_frag_coord || (msl_options.multiview && !has_view_idx) ||
  469. (msl_options.arrayed_subpass_input && !msl_options.multiview && !has_layer)) &&
  470. (!msl_options.use_framebuffer_fetch_subpasses) && need_subpass_input)
  471. {
  472. if (!has_frag_coord)
  473. {
  474. uint32_t offset = ir.increase_bound_by(3);
  475. uint32_t type_id = offset;
  476. uint32_t type_ptr_id = offset + 1;
  477. uint32_t var_id = offset + 2;
  478. // Create gl_FragCoord.
  479. SPIRType vec4_type { OpTypeVector };
  480. vec4_type.basetype = SPIRType::Float;
  481. vec4_type.width = 32;
  482. vec4_type.vecsize = 4;
  483. set<SPIRType>(type_id, vec4_type);
  484. SPIRType vec4_type_ptr = vec4_type;
  485. vec4_type_ptr.op = OpTypePointer;
  486. vec4_type_ptr.pointer = true;
  487. vec4_type_ptr.pointer_depth++;
  488. vec4_type_ptr.parent_type = type_id;
  489. vec4_type_ptr.storage = StorageClassInput;
  490. auto &ptr_type = set<SPIRType>(type_ptr_id, vec4_type_ptr);
  491. ptr_type.self = type_id;
  492. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  493. set_decoration(var_id, DecorationBuiltIn, BuiltInFragCoord);
  494. builtin_frag_coord_id = var_id;
  495. mark_implicit_builtin(StorageClassInput, BuiltInFragCoord, var_id);
  496. }
  497. if (!has_layer && msl_options.arrayed_subpass_input && !msl_options.multiview)
  498. {
  499. uint32_t offset = ir.increase_bound_by(2);
  500. uint32_t type_ptr_id = offset;
  501. uint32_t var_id = offset + 1;
  502. // Create gl_Layer.
  503. SPIRType uint_type_ptr = get_uint_type();
  504. uint_type_ptr.op = OpTypePointer;
  505. uint_type_ptr.pointer = true;
  506. uint_type_ptr.pointer_depth++;
  507. uint_type_ptr.parent_type = get_uint_type_id();
  508. uint_type_ptr.storage = StorageClassInput;
  509. auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
  510. ptr_type.self = get_uint_type_id();
  511. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  512. set_decoration(var_id, DecorationBuiltIn, BuiltInLayer);
  513. builtin_layer_id = var_id;
  514. mark_implicit_builtin(StorageClassInput, BuiltInLayer, var_id);
  515. }
  516. if (!has_view_idx && msl_options.multiview)
  517. {
  518. uint32_t offset = ir.increase_bound_by(2);
  519. uint32_t type_ptr_id = offset;
  520. uint32_t var_id = offset + 1;
  521. // Create gl_ViewIndex.
  522. SPIRType uint_type_ptr = get_uint_type();
  523. uint_type_ptr.op = OpTypePointer;
  524. uint_type_ptr.pointer = true;
  525. uint_type_ptr.pointer_depth++;
  526. uint_type_ptr.parent_type = get_uint_type_id();
  527. uint_type_ptr.storage = StorageClassInput;
  528. auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
  529. ptr_type.self = get_uint_type_id();
  530. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  531. set_decoration(var_id, DecorationBuiltIn, BuiltInViewIndex);
  532. builtin_view_idx_id = var_id;
  533. mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var_id);
  534. }
  535. }
  536. if (!has_sample_id && (need_sample_pos || needs_sample_id))
  537. {
  538. uint32_t offset = ir.increase_bound_by(2);
  539. uint32_t type_ptr_id = offset;
  540. uint32_t var_id = offset + 1;
  541. // Create gl_SampleID.
  542. SPIRType uint_type_ptr = get_uint_type();
  543. uint_type_ptr.op = OpTypePointer;
  544. uint_type_ptr.pointer = true;
  545. uint_type_ptr.pointer_depth++;
  546. uint_type_ptr.parent_type = get_uint_type_id();
  547. uint_type_ptr.storage = StorageClassInput;
  548. auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
  549. ptr_type.self = get_uint_type_id();
  550. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  551. set_decoration(var_id, DecorationBuiltIn, BuiltInSampleId);
  552. builtin_sample_id_id = var_id;
  553. mark_implicit_builtin(StorageClassInput, BuiltInSampleId, var_id);
  554. }
  555. if ((need_vertex_params && (!has_vertex_idx || !has_base_vertex || !has_instance_idx || !has_base_instance)) ||
  556. (need_multiview && (!has_instance_idx || !has_base_instance || !has_view_idx)))
  557. {
  558. uint32_t type_ptr_id = ir.increase_bound_by(1);
  559. SPIRType uint_type_ptr = get_uint_type();
  560. uint_type_ptr.op = OpTypePointer;
  561. uint_type_ptr.pointer = true;
  562. uint_type_ptr.pointer_depth++;
  563. uint_type_ptr.parent_type = get_uint_type_id();
  564. uint_type_ptr.storage = StorageClassInput;
  565. auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
  566. ptr_type.self = get_uint_type_id();
  567. if (need_vertex_params && !has_vertex_idx)
  568. {
  569. uint32_t var_id = ir.increase_bound_by(1);
  570. // Create gl_VertexIndex.
  571. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  572. set_decoration(var_id, DecorationBuiltIn, BuiltInVertexIndex);
  573. builtin_vertex_idx_id = var_id;
  574. mark_implicit_builtin(StorageClassInput, BuiltInVertexIndex, var_id);
  575. }
  576. if (need_vertex_params && !has_base_vertex)
  577. {
  578. uint32_t var_id = ir.increase_bound_by(1);
  579. // Create gl_BaseVertex.
  580. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  581. set_decoration(var_id, DecorationBuiltIn, BuiltInBaseVertex);
  582. builtin_base_vertex_id = var_id;
  583. mark_implicit_builtin(StorageClassInput, BuiltInBaseVertex, var_id);
  584. }
  585. if (!has_instance_idx) // Needed by both multiview and tessellation
  586. {
  587. uint32_t var_id = ir.increase_bound_by(1);
  588. // Create gl_InstanceIndex.
  589. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  590. set_decoration(var_id, DecorationBuiltIn, BuiltInInstanceIndex);
  591. builtin_instance_idx_id = var_id;
  592. mark_implicit_builtin(StorageClassInput, BuiltInInstanceIndex, var_id);
  593. }
  594. if (!has_base_instance) // Needed by both multiview and tessellation
  595. {
  596. uint32_t var_id = ir.increase_bound_by(1);
  597. // Create gl_BaseInstance.
  598. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  599. set_decoration(var_id, DecorationBuiltIn, BuiltInBaseInstance);
  600. builtin_base_instance_id = var_id;
  601. mark_implicit_builtin(StorageClassInput, BuiltInBaseInstance, var_id);
  602. }
  603. if (need_multiview && !has_view_idx)
  604. {
  605. uint32_t var_id = ir.increase_bound_by(1);
  606. // Create gl_ViewIndex.
  607. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  608. set_decoration(var_id, DecorationBuiltIn, BuiltInViewIndex);
  609. builtin_view_idx_id = var_id;
  610. mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var_id);
  611. }
  612. }
  613. if (need_multiview)
  614. {
  615. // Multiview shaders are not allowed to write to gl_Layer, ostensibly because
  616. // it is implicitly written from gl_ViewIndex, but we have to do that explicitly.
  617. // Note that we can't just abuse gl_ViewIndex for this purpose: it's an input, but
  618. // gl_Layer is an output in vertex-pipeline shaders.
  619. uint32_t type_ptr_out_id = ir.increase_bound_by(2);
  620. SPIRType uint_type_ptr_out = get_uint_type();
  621. uint_type_ptr_out.op = OpTypePointer;
  622. uint_type_ptr_out.pointer = true;
  623. uint_type_ptr_out.pointer_depth++;
  624. uint_type_ptr_out.parent_type = get_uint_type_id();
  625. uint_type_ptr_out.storage = StorageClassOutput;
  626. auto &ptr_out_type = set<SPIRType>(type_ptr_out_id, uint_type_ptr_out);
  627. ptr_out_type.self = get_uint_type_id();
  628. uint32_t var_id = type_ptr_out_id + 1;
  629. set<SPIRVariable>(var_id, type_ptr_out_id, StorageClassOutput);
  630. set_decoration(var_id, DecorationBuiltIn, BuiltInLayer);
  631. builtin_layer_id = var_id;
  632. mark_implicit_builtin(StorageClassOutput, BuiltInLayer, var_id);
  633. }
  634. if ((need_tesc_params && (msl_options.multi_patch_workgroup || !has_invocation_id || !has_primitive_id)) ||
  635. (need_tese_params && !has_primitive_id) || need_grid_params)
  636. {
  637. uint32_t type_ptr_id = ir.increase_bound_by(1);
  638. SPIRType uint_type_ptr = get_uint_type();
  639. uint_type_ptr.op = OpTypePointer;
  640. uint_type_ptr.pointer = true;
  641. uint_type_ptr.pointer_depth++;
  642. uint_type_ptr.parent_type = get_uint_type_id();
  643. uint_type_ptr.storage = StorageClassInput;
  644. auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
  645. ptr_type.self = get_uint_type_id();
  646. if ((need_tesc_params && msl_options.multi_patch_workgroup) || need_grid_params)
  647. {
  648. uint32_t var_id = ir.increase_bound_by(1);
  649. // Create gl_GlobalInvocationID.
  650. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  651. set_decoration(var_id, DecorationBuiltIn, BuiltInGlobalInvocationId);
  652. builtin_invocation_id_id = var_id;
  653. mark_implicit_builtin(StorageClassInput, BuiltInGlobalInvocationId, var_id);
  654. }
  655. else if (need_tesc_params && !has_invocation_id)
  656. {
  657. uint32_t var_id = ir.increase_bound_by(1);
  658. // Create gl_InvocationID.
  659. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  660. set_decoration(var_id, DecorationBuiltIn, BuiltInInvocationId);
  661. builtin_invocation_id_id = var_id;
  662. mark_implicit_builtin(StorageClassInput, BuiltInInvocationId, var_id);
  663. }
  664. if ((need_tesc_params || need_tese_params) && !has_primitive_id)
  665. {
  666. uint32_t var_id = ir.increase_bound_by(1);
  667. // Create gl_PrimitiveID.
  668. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  669. set_decoration(var_id, DecorationBuiltIn, BuiltInPrimitiveId);
  670. builtin_primitive_id_id = var_id;
  671. mark_implicit_builtin(StorageClassInput, BuiltInPrimitiveId, var_id);
  672. }
  673. if (need_grid_params)
  674. {
  675. uint32_t var_id = ir.increase_bound_by(1);
  676. set<SPIRVariable>(var_id, build_extended_vector_type(get_uint_type_id(), 3), StorageClassInput);
  677. set_extended_decoration(var_id, SPIRVCrossDecorationBuiltInStageInputSize);
  678. get_entry_point().interface_variables.push_back(var_id);
  679. set_name(var_id, "spvStageInputSize");
  680. builtin_stage_input_size_id = var_id;
  681. }
  682. }
  683. if (!has_subgroup_invocation_id && (need_subgroup_mask || needs_subgroup_invocation_id))
  684. {
  685. uint32_t offset = ir.increase_bound_by(2);
  686. uint32_t type_ptr_id = offset;
  687. uint32_t var_id = offset + 1;
  688. // Create gl_SubgroupInvocationID.
  689. SPIRType uint_type_ptr = get_uint_type();
  690. uint_type_ptr.op = OpTypePointer;
  691. uint_type_ptr.pointer = true;
  692. uint_type_ptr.pointer_depth++;
  693. uint_type_ptr.parent_type = get_uint_type_id();
  694. uint_type_ptr.storage = StorageClassInput;
  695. auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
  696. ptr_type.self = get_uint_type_id();
  697. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  698. set_decoration(var_id, DecorationBuiltIn, BuiltInSubgroupLocalInvocationId);
  699. builtin_subgroup_invocation_id_id = var_id;
  700. mark_implicit_builtin(StorageClassInput, BuiltInSubgroupLocalInvocationId, var_id);
  701. }
  702. if (!has_subgroup_size && (need_subgroup_ge_mask || needs_subgroup_size))
  703. {
  704. uint32_t offset = ir.increase_bound_by(2);
  705. uint32_t type_ptr_id = offset;
  706. uint32_t var_id = offset + 1;
  707. // Create gl_SubgroupSize.
  708. SPIRType uint_type_ptr = get_uint_type();
  709. uint_type_ptr.op = OpTypePointer;
  710. uint_type_ptr.pointer = true;
  711. uint_type_ptr.pointer_depth++;
  712. uint_type_ptr.parent_type = get_uint_type_id();
  713. uint_type_ptr.storage = StorageClassInput;
  714. auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
  715. ptr_type.self = get_uint_type_id();
  716. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  717. set_decoration(var_id, DecorationBuiltIn, BuiltInSubgroupSize);
  718. builtin_subgroup_size_id = var_id;
  719. mark_implicit_builtin(StorageClassInput, BuiltInSubgroupSize, var_id);
  720. }
  721. if (need_dispatch_base || need_vertex_base_params)
  722. {
  723. if (workgroup_id_type == 0)
  724. workgroup_id_type = build_extended_vector_type(get_uint_type_id(), 3);
  725. uint32_t var_id;
  726. if (msl_options.supports_msl_version(1, 2))
  727. {
  728. // If we have MSL 1.2, we can (ab)use the [[grid_origin]] builtin
  729. // to convey this information and save a buffer slot.
  730. uint32_t offset = ir.increase_bound_by(1);
  731. var_id = offset;
  732. set<SPIRVariable>(var_id, workgroup_id_type, StorageClassInput);
  733. set_extended_decoration(var_id, SPIRVCrossDecorationBuiltInDispatchBase);
  734. get_entry_point().interface_variables.push_back(var_id);
  735. }
  736. else
  737. {
  738. // Otherwise, we need to fall back to a good ol' fashioned buffer.
  739. uint32_t offset = ir.increase_bound_by(2);
  740. var_id = offset;
  741. uint32_t type_id = offset + 1;
  742. SPIRType var_type = get<SPIRType>(workgroup_id_type);
  743. var_type.storage = StorageClassUniform;
  744. set<SPIRType>(type_id, var_type);
  745. set<SPIRVariable>(var_id, type_id, StorageClassUniform);
  746. // This should never match anything.
  747. set_decoration(var_id, DecorationDescriptorSet, ~(5u));
  748. set_decoration(var_id, DecorationBinding, msl_options.indirect_params_buffer_index);
  749. set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary,
  750. msl_options.indirect_params_buffer_index);
  751. }
  752. set_name(var_id, "spvDispatchBase");
  753. builtin_dispatch_base_id = var_id;
  754. }
  755. if (has_additional_fixed_sample_mask() && !does_shader_write_sample_mask)
  756. {
  757. uint32_t offset = ir.increase_bound_by(2);
  758. uint32_t var_id = offset + 1;
  759. // Create gl_SampleMask.
  760. SPIRType uint_type_ptr_out = get_uint_type();
  761. uint_type_ptr_out.op = OpTypePointer;
  762. uint_type_ptr_out.pointer = true;
  763. uint_type_ptr_out.pointer_depth++;
  764. uint_type_ptr_out.parent_type = get_uint_type_id();
  765. uint_type_ptr_out.storage = StorageClassOutput;
  766. auto &ptr_out_type = set<SPIRType>(offset, uint_type_ptr_out);
  767. ptr_out_type.self = get_uint_type_id();
  768. set<SPIRVariable>(var_id, offset, StorageClassOutput);
  769. set_decoration(var_id, DecorationBuiltIn, BuiltInSampleMask);
  770. builtin_sample_mask_id = var_id;
  771. mark_implicit_builtin(StorageClassOutput, BuiltInSampleMask, var_id);
  772. }
  773. if (!has_helper_invocation && needs_helper_invocation)
  774. {
  775. uint32_t offset = ir.increase_bound_by(3);
  776. uint32_t type_id = offset;
  777. uint32_t type_ptr_id = offset + 1;
  778. uint32_t var_id = offset + 2;
  779. // Create gl_HelperInvocation.
  780. SPIRType bool_type { OpTypeBool };
  781. bool_type.basetype = SPIRType::Boolean;
  782. bool_type.width = 8;
  783. bool_type.vecsize = 1;
  784. set<SPIRType>(type_id, bool_type);
  785. SPIRType bool_type_ptr_in = bool_type;
  786. bool_type_ptr_in.op = OpTypePointer;
  787. bool_type_ptr_in.pointer = true;
  788. bool_type_ptr_in.pointer_depth++;
  789. bool_type_ptr_in.parent_type = type_id;
  790. bool_type_ptr_in.storage = StorageClassInput;
  791. auto &ptr_in_type = set<SPIRType>(type_ptr_id, bool_type_ptr_in);
  792. ptr_in_type.self = type_id;
  793. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  794. set_decoration(var_id, DecorationBuiltIn, BuiltInHelperInvocation);
  795. builtin_helper_invocation_id = var_id;
  796. mark_implicit_builtin(StorageClassInput, BuiltInHelperInvocation, var_id);
  797. }
  798. if (need_local_invocation_index && !has_local_invocation_index)
  799. {
  800. uint32_t offset = ir.increase_bound_by(2);
  801. uint32_t type_ptr_id = offset;
  802. uint32_t var_id = offset + 1;
  803. // Create gl_LocalInvocationIndex.
  804. SPIRType uint_type_ptr = get_uint_type();
  805. uint_type_ptr.op = OpTypePointer;
  806. uint_type_ptr.pointer = true;
  807. uint_type_ptr.pointer_depth++;
  808. uint_type_ptr.parent_type = get_uint_type_id();
  809. uint_type_ptr.storage = StorageClassInput;
  810. auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
  811. ptr_type.self = get_uint_type_id();
  812. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  813. set_decoration(var_id, DecorationBuiltIn, BuiltInLocalInvocationIndex);
  814. builtin_local_invocation_index_id = var_id;
  815. mark_implicit_builtin(StorageClassInput, BuiltInLocalInvocationIndex, var_id);
  816. }
  817. if (need_workgroup_size && !has_workgroup_size)
  818. {
  819. auto &execution = get_entry_point();
  820. // First, check if the workgroup size _constant_ were defined.
  821. // If it were, we don't need to do--in fact, shouldn't do--anything.
  822. builtin_workgroup_size_id = execution.workgroup_size.constant;
  823. if (builtin_workgroup_size_id == 0)
  824. {
  825. uint32_t var_id = ir.increase_bound_by(1);
  826. // Create gl_WorkgroupSize.
  827. uint32_t type_id = build_extended_vector_type(get_uint_type_id(), 3);
  828. // If we have LocalSize or LocalSizeId, use those to define the workgroup size.
  829. if (execution.flags.get(ExecutionModeLocalSizeId))
  830. {
  831. const SPIRConstant *init[] = { &get<SPIRConstant>(execution.workgroup_size.id_x),
  832. &get<SPIRConstant>(execution.workgroup_size.id_y),
  833. &get<SPIRConstant>(execution.workgroup_size.id_z) };
  834. bool specialized = init[0]->specialization || init[1]->specialization || init[2]->specialization;
  835. set<SPIRConstant>(var_id, type_id, init, 3, specialized);
  836. execution.workgroup_size.constant = var_id;
  837. }
  838. else if (execution.flags.get(ExecutionModeLocalSize))
  839. {
  840. uint32_t offset = ir.increase_bound_by(3);
  841. const SPIRConstant *init[] = {
  842. &set<SPIRConstant>(offset, get_uint_type_id(), execution.workgroup_size.x, false),
  843. &set<SPIRConstant>(offset + 1, get_uint_type_id(), execution.workgroup_size.y, false),
  844. &set<SPIRConstant>(offset + 2, get_uint_type_id(), execution.workgroup_size.z, false)
  845. };
  846. set<SPIRConstant>(var_id, type_id, init, 3, false);
  847. execution.workgroup_size.constant = var_id;
  848. }
  849. else
  850. {
  851. uint32_t type_ptr_id = ir.increase_bound_by(1);
  852. SPIRType uint_type_ptr = get<SPIRType>(type_id);
  853. uint_type_ptr.op = OpTypePointer;
  854. uint_type_ptr.pointer = true;
  855. uint_type_ptr.pointer_depth++;
  856. uint_type_ptr.parent_type = type_id;
  857. uint_type_ptr.storage = StorageClassInput;
  858. auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
  859. ptr_type.self = type_id;
  860. set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
  861. mark_implicit_builtin(StorageClassInput, BuiltInWorkgroupSize, var_id);
  862. }
  863. set_decoration(var_id, DecorationBuiltIn, BuiltInWorkgroupSize);
  864. builtin_workgroup_size_id = var_id;
  865. }
  866. }
  867. if (!has_frag_depth && force_frag_depth_passthrough)
  868. {
  869. uint32_t offset = ir.increase_bound_by(3);
  870. uint32_t type_id = offset;
  871. uint32_t type_ptr_id = offset + 1;
  872. uint32_t var_id = offset + 2;
  873. // Create gl_FragDepth
  874. SPIRType float_type { OpTypeFloat };
  875. float_type.basetype = SPIRType::Float;
  876. float_type.width = 32;
  877. float_type.vecsize = 1;
  878. set<SPIRType>(type_id, float_type);
  879. SPIRType float_type_ptr_in = float_type;
  880. float_type_ptr_in.op = OpTypePointer;
  881. float_type_ptr_in.pointer = true;
  882. float_type_ptr_in.pointer_depth++;
  883. float_type_ptr_in.parent_type = type_id;
  884. float_type_ptr_in.storage = StorageClassOutput;
  885. auto &ptr_in_type = set<SPIRType>(type_ptr_id, float_type_ptr_in);
  886. ptr_in_type.self = type_id;
  887. set<SPIRVariable>(var_id, type_ptr_id, StorageClassOutput);
  888. set_decoration(var_id, DecorationBuiltIn, BuiltInFragDepth);
  889. builtin_frag_depth_id = var_id;
  890. mark_implicit_builtin(StorageClassOutput, BuiltInFragDepth, var_id);
  891. active_output_builtins.set(BuiltInFragDepth);
  892. }
  893. if (!has_point_size && needs_point_size_output)
  894. {
  895. uint32_t offset = ir.increase_bound_by(3);
  896. uint32_t type_id = offset;
  897. uint32_t type_ptr_id = offset + 1;
  898. uint32_t var_id = offset + 2;
  899. // Create gl_PointSize
  900. SPIRType float_type { OpTypeFloat };
  901. float_type.basetype = SPIRType::Float;
  902. float_type.width = 32;
  903. float_type.vecsize = 1;
  904. set<SPIRType>(type_id, float_type);
  905. SPIRType float_type_ptr_in = float_type;
  906. float_type_ptr_in.op = OpTypePointer;
  907. float_type_ptr_in.pointer = true;
  908. float_type_ptr_in.pointer_depth++;
  909. float_type_ptr_in.parent_type = type_id;
  910. float_type_ptr_in.storage = StorageClassOutput;
  911. auto &ptr_in_type = set<SPIRType>(type_ptr_id, float_type_ptr_in);
  912. ptr_in_type.self = type_id;
  913. set<SPIRVariable>(var_id, type_ptr_id, StorageClassOutput);
  914. set_decoration(var_id, DecorationBuiltIn, BuiltInPointSize);
  915. mark_implicit_builtin(StorageClassOutput, BuiltInPointSize, var_id);
  916. }
  917. }
  918. if (needs_swizzle_buffer_def)
  919. {
  920. uint32_t var_id = build_constant_uint_array_pointer();
  921. set_name(var_id, "spvSwizzleConstants");
  922. // This should never match anything.
  923. set_decoration(var_id, DecorationDescriptorSet, kSwizzleBufferBinding);
  924. set_decoration(var_id, DecorationBinding, msl_options.swizzle_buffer_index);
  925. set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary, msl_options.swizzle_buffer_index);
  926. swizzle_buffer_id = var_id;
  927. }
  928. if (needs_buffer_size_buffer())
  929. {
  930. uint32_t var_id = build_constant_uint_array_pointer();
  931. set_name(var_id, "spvBufferSizeConstants");
  932. // This should never match anything.
  933. set_decoration(var_id, DecorationDescriptorSet, kBufferSizeBufferBinding);
  934. set_decoration(var_id, DecorationBinding, msl_options.buffer_size_buffer_index);
  935. set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary, msl_options.buffer_size_buffer_index);
  936. buffer_size_buffer_id = var_id;
  937. }
  938. if (needs_view_mask_buffer())
  939. {
  940. uint32_t var_id = build_constant_uint_array_pointer();
  941. set_name(var_id, "spvViewMask");
  942. // This should never match anything.
  943. set_decoration(var_id, DecorationDescriptorSet, ~(4u));
  944. set_decoration(var_id, DecorationBinding, msl_options.view_mask_buffer_index);
  945. set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary, msl_options.view_mask_buffer_index);
  946. view_mask_buffer_id = var_id;
  947. }
  948. if (!buffers_requiring_dynamic_offset.empty())
  949. {
  950. uint32_t var_id = build_constant_uint_array_pointer();
  951. set_name(var_id, "spvDynamicOffsets");
  952. // This should never match anything.
  953. set_decoration(var_id, DecorationDescriptorSet, ~(5u));
  954. set_decoration(var_id, DecorationBinding, msl_options.dynamic_offsets_buffer_index);
  955. set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary,
  956. msl_options.dynamic_offsets_buffer_index);
  957. dynamic_offsets_buffer_id = var_id;
  958. }
  959. // If we're returning a struct from a vertex-like entry point, we must return a position attribute.
  960. bool need_position = (get_execution_model() == ExecutionModelVertex || is_tese_shader()) &&
  961. !capture_output_to_buffer && !get_is_rasterization_disabled() &&
  962. !msl_options.auto_disable_rasterization &&
  963. !active_output_builtins.get(BuiltInPosition);
  964. if (need_position)
  965. {
  966. // If we can get away with returning void from entry point, we don't need to care.
  967. // If there is at least one other stage output, we need to return [[position]],
  968. // so we need to create one if it doesn't appear in the SPIR-V. Before adding the
  969. // implicit variable, check if it actually exists already, but just has not been used
  970. // or initialized, and if so, mark it as active, and do not create the implicit variable.
  971. bool has_output = false;
  972. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
  973. if (var.storage == StorageClassOutput && interface_variable_exists_in_entry_point(var.self))
  974. {
  975. has_output = true;
  976. // Check if the var is the Position builtin
  977. if (has_decoration(var.self, DecorationBuiltIn) && get_decoration(var.self, DecorationBuiltIn) == BuiltInPosition)
  978. active_output_builtins.set(BuiltInPosition);
  979. // If the var is a struct, check if any members is the Position builtin
  980. auto &var_type = get_variable_element_type(var);
  981. if (var_type.basetype == SPIRType::Struct)
  982. {
  983. auto mbr_cnt = var_type.member_types.size();
  984. for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
  985. {
  986. auto builtin = BuiltInMax;
  987. bool is_builtin = is_member_builtin(var_type, mbr_idx, &builtin);
  988. if (is_builtin && builtin == BuiltInPosition)
  989. active_output_builtins.set(BuiltInPosition);
  990. }
  991. }
  992. }
  993. });
  994. need_position = has_output && !active_output_builtins.get(BuiltInPosition);
  995. }
  996. else if (!active_output_builtins.get(BuiltInPosition) && msl_options.auto_disable_rasterization)
  997. {
  998. is_rasterization_disabled = true;
  999. }
  1000. if (need_position)
  1001. {
  1002. uint32_t offset = ir.increase_bound_by(3);
  1003. uint32_t type_id = offset;
  1004. uint32_t type_ptr_id = offset + 1;
  1005. uint32_t var_id = offset + 2;
  1006. // Create gl_Position.
  1007. SPIRType vec4_type { OpTypeVector };
  1008. vec4_type.basetype = SPIRType::Float;
  1009. vec4_type.width = 32;
  1010. vec4_type.vecsize = 4;
  1011. set<SPIRType>(type_id, vec4_type);
  1012. SPIRType vec4_type_ptr = vec4_type;
  1013. vec4_type_ptr.op = OpTypePointer;
  1014. vec4_type_ptr.pointer = true;
  1015. vec4_type_ptr.pointer_depth++;
  1016. vec4_type_ptr.parent_type = type_id;
  1017. vec4_type_ptr.storage = StorageClassOutput;
  1018. auto &ptr_type = set<SPIRType>(type_ptr_id, vec4_type_ptr);
  1019. ptr_type.self = type_id;
  1020. set<SPIRVariable>(var_id, type_ptr_id, StorageClassOutput);
  1021. set_decoration(var_id, DecorationBuiltIn, BuiltInPosition);
  1022. mark_implicit_builtin(StorageClassOutput, BuiltInPosition, var_id);
  1023. }
  1024. if (is_mesh_shader())
  1025. {
  1026. uint32_t offset = ir.increase_bound_by(2);
  1027. uint32_t type_ptr_id = offset;
  1028. uint32_t var_id = offset + 1;
  1029. // Create variable to store meshlet size.
  1030. uint32_t type_id = build_extended_vector_type(get_uint_type_id(), 2);
  1031. SPIRType uint_type_ptr = get<SPIRType>(type_id);
  1032. uint_type_ptr.op = OpTypePointer;
  1033. uint_type_ptr.pointer = true;
  1034. uint_type_ptr.pointer_depth++;
  1035. uint_type_ptr.parent_type = type_id;
  1036. uint_type_ptr.storage = StorageClassWorkgroup;
  1037. auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
  1038. ptr_type.self = type_id;
  1039. set<SPIRVariable>(var_id, type_ptr_id, StorageClassWorkgroup);
  1040. set_name(var_id, "spvMeshSizes");
  1041. builtin_mesh_sizes_id = var_id;
  1042. }
  1043. if (get_execution_model() == ExecutionModelTaskEXT)
  1044. {
  1045. uint32_t offset = ir.increase_bound_by(3);
  1046. uint32_t type_id = offset;
  1047. uint32_t type_ptr_id = offset + 1;
  1048. uint32_t var_id = offset + 2;
  1049. SPIRType mesh_grid_type { OpTypeStruct };
  1050. mesh_grid_type.basetype = SPIRType::MeshGridProperties;
  1051. set<SPIRType>(type_id, mesh_grid_type);
  1052. SPIRType mesh_grid_type_ptr = mesh_grid_type;
  1053. mesh_grid_type_ptr.op = OpTypePointer;
  1054. mesh_grid_type_ptr.pointer = true;
  1055. mesh_grid_type_ptr.pointer_depth++;
  1056. mesh_grid_type_ptr.parent_type = type_id;
  1057. mesh_grid_type_ptr.storage = StorageClassOutput;
  1058. auto &ptr_in_type = set<SPIRType>(type_ptr_id, mesh_grid_type_ptr);
  1059. ptr_in_type.self = type_id;
  1060. set<SPIRVariable>(var_id, type_ptr_id, StorageClassOutput);
  1061. set_name(var_id, "spvMgp");
  1062. builtin_task_grid_id = var_id;
  1063. }
  1064. }
  1065. // Checks if the specified builtin variable (e.g. gl_InstanceIndex) is marked as active.
  1066. // If not, it marks it as active and forces a recompilation.
  1067. // This might be used when the optimization of inactive builtins was too optimistic (e.g. when "spvOut" is emitted).
  1068. void CompilerMSL::ensure_builtin(StorageClass storage, BuiltIn builtin)
  1069. {
  1070. Bitset *active_builtins = nullptr;
  1071. switch (storage)
  1072. {
  1073. case StorageClassInput:
  1074. active_builtins = &active_input_builtins;
  1075. break;
  1076. case StorageClassOutput:
  1077. active_builtins = &active_output_builtins;
  1078. break;
  1079. default:
  1080. break;
  1081. }
  1082. // At this point, the specified builtin variable must have already been declared in the entry point.
  1083. // If not, mark as active and force recompile.
  1084. if (active_builtins != nullptr && !active_builtins->get(builtin))
  1085. {
  1086. active_builtins->set(builtin);
  1087. force_recompile();
  1088. }
  1089. }
  1090. void CompilerMSL::mark_implicit_builtin(StorageClass storage, BuiltIn builtin, uint32_t id)
  1091. {
  1092. Bitset *active_builtins = nullptr;
  1093. switch (storage)
  1094. {
  1095. case StorageClassInput:
  1096. active_builtins = &active_input_builtins;
  1097. break;
  1098. case StorageClassOutput:
  1099. active_builtins = &active_output_builtins;
  1100. break;
  1101. default:
  1102. break;
  1103. }
  1104. assert(active_builtins != nullptr);
  1105. active_builtins->set(builtin);
  1106. auto &var = get_entry_point().interface_variables;
  1107. if (find(begin(var), end(var), VariableID(id)) == end(var))
  1108. var.push_back(id);
  1109. }
  1110. uint32_t CompilerMSL::build_constant_uint_array_pointer()
  1111. {
  1112. uint32_t offset = ir.increase_bound_by(3);
  1113. uint32_t type_ptr_id = offset;
  1114. uint32_t type_ptr_ptr_id = offset + 1;
  1115. uint32_t var_id = offset + 2;
  1116. // Create a buffer to hold extra data, including the swizzle constants.
  1117. SPIRType uint_type_pointer = get_uint_type();
  1118. uint_type_pointer.op = OpTypePointer;
  1119. uint_type_pointer.pointer = true;
  1120. uint_type_pointer.pointer_depth++;
  1121. uint_type_pointer.parent_type = get_uint_type_id();
  1122. uint_type_pointer.storage = StorageClassUniform;
  1123. set<SPIRType>(type_ptr_id, uint_type_pointer);
  1124. set_decoration(type_ptr_id, DecorationArrayStride, 4);
  1125. SPIRType uint_type_pointer2 = uint_type_pointer;
  1126. uint_type_pointer2.pointer_depth++;
  1127. uint_type_pointer2.parent_type = type_ptr_id;
  1128. set<SPIRType>(type_ptr_ptr_id, uint_type_pointer2);
  1129. set<SPIRVariable>(var_id, type_ptr_ptr_id, StorageClassUniformConstant);
  1130. return var_id;
  1131. }
  1132. static string create_sampler_address(const char *prefix, MSLSamplerAddress addr)
  1133. {
  1134. switch (addr)
  1135. {
  1136. case MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE:
  1137. return join(prefix, "address::clamp_to_edge");
  1138. case MSL_SAMPLER_ADDRESS_CLAMP_TO_ZERO:
  1139. return join(prefix, "address::clamp_to_zero");
  1140. case MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER:
  1141. return join(prefix, "address::clamp_to_border");
  1142. case MSL_SAMPLER_ADDRESS_REPEAT:
  1143. return join(prefix, "address::repeat");
  1144. case MSL_SAMPLER_ADDRESS_MIRRORED_REPEAT:
  1145. return join(prefix, "address::mirrored_repeat");
  1146. default:
  1147. SPIRV_CROSS_THROW("Invalid sampler addressing mode.");
  1148. }
  1149. }
  1150. SPIRType &CompilerMSL::get_stage_in_struct_type()
  1151. {
  1152. auto &si_var = get<SPIRVariable>(stage_in_var_id);
  1153. return get_variable_data_type(si_var);
  1154. }
  1155. SPIRType &CompilerMSL::get_stage_out_struct_type()
  1156. {
  1157. auto &so_var = get<SPIRVariable>(stage_out_var_id);
  1158. return get_variable_data_type(so_var);
  1159. }
  1160. SPIRType &CompilerMSL::get_patch_stage_in_struct_type()
  1161. {
  1162. auto &si_var = get<SPIRVariable>(patch_stage_in_var_id);
  1163. return get_variable_data_type(si_var);
  1164. }
  1165. SPIRType &CompilerMSL::get_patch_stage_out_struct_type()
  1166. {
  1167. auto &so_var = get<SPIRVariable>(patch_stage_out_var_id);
  1168. return get_variable_data_type(so_var);
  1169. }
  1170. std::string CompilerMSL::get_tess_factor_struct_name()
  1171. {
  1172. if (is_tessellating_triangles())
  1173. return "MTLTriangleTessellationFactorsHalf";
  1174. return "MTLQuadTessellationFactorsHalf";
  1175. }
  1176. SPIRType &CompilerMSL::get_uint_type()
  1177. {
  1178. return get<SPIRType>(get_uint_type_id());
  1179. }
  1180. uint32_t CompilerMSL::get_uint_type_id()
  1181. {
  1182. if (uint_type_id != 0)
  1183. return uint_type_id;
  1184. uint_type_id = ir.increase_bound_by(1);
  1185. SPIRType type { OpTypeInt };
  1186. type.basetype = SPIRType::UInt;
  1187. type.width = 32;
  1188. set<SPIRType>(uint_type_id, type);
  1189. return uint_type_id;
  1190. }
  1191. void CompilerMSL::emit_entry_point_declarations()
  1192. {
  1193. // FIXME: Get test coverage here ...
  1194. // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries
  1195. declare_complex_constant_arrays();
  1196. // Emit constexpr samplers here.
  1197. for (auto &samp : constexpr_samplers_by_id)
  1198. {
  1199. auto &var = get<SPIRVariable>(samp.first);
  1200. auto &type = get<SPIRType>(var.basetype);
  1201. if (type.basetype == SPIRType::Sampler)
  1202. add_resource_name(samp.first);
  1203. SmallVector<string> args;
  1204. auto &s = samp.second;
  1205. if (s.coord != MSL_SAMPLER_COORD_NORMALIZED)
  1206. args.push_back("coord::pixel");
  1207. if (s.min_filter == s.mag_filter)
  1208. {
  1209. if (s.min_filter != MSL_SAMPLER_FILTER_NEAREST)
  1210. args.push_back("filter::linear");
  1211. }
  1212. else
  1213. {
  1214. if (s.min_filter != MSL_SAMPLER_FILTER_NEAREST)
  1215. args.push_back("min_filter::linear");
  1216. if (s.mag_filter != MSL_SAMPLER_FILTER_NEAREST)
  1217. args.push_back("mag_filter::linear");
  1218. }
  1219. switch (s.mip_filter)
  1220. {
  1221. case MSL_SAMPLER_MIP_FILTER_NONE:
  1222. // Default
  1223. break;
  1224. case MSL_SAMPLER_MIP_FILTER_NEAREST:
  1225. args.push_back("mip_filter::nearest");
  1226. break;
  1227. case MSL_SAMPLER_MIP_FILTER_LINEAR:
  1228. args.push_back("mip_filter::linear");
  1229. break;
  1230. default:
  1231. SPIRV_CROSS_THROW("Invalid mip filter.");
  1232. }
  1233. if (s.s_address == s.t_address && s.s_address == s.r_address)
  1234. {
  1235. if (s.s_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE)
  1236. args.push_back(create_sampler_address("", s.s_address));
  1237. }
  1238. else
  1239. {
  1240. if (s.s_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE)
  1241. args.push_back(create_sampler_address("s_", s.s_address));
  1242. if (s.t_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE)
  1243. args.push_back(create_sampler_address("t_", s.t_address));
  1244. if (s.r_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE)
  1245. args.push_back(create_sampler_address("r_", s.r_address));
  1246. }
  1247. if (s.compare_enable)
  1248. {
  1249. switch (s.compare_func)
  1250. {
  1251. case MSL_SAMPLER_COMPARE_FUNC_ALWAYS:
  1252. args.push_back("compare_func::always");
  1253. break;
  1254. case MSL_SAMPLER_COMPARE_FUNC_NEVER:
  1255. args.push_back("compare_func::never");
  1256. break;
  1257. case MSL_SAMPLER_COMPARE_FUNC_EQUAL:
  1258. args.push_back("compare_func::equal");
  1259. break;
  1260. case MSL_SAMPLER_COMPARE_FUNC_NOT_EQUAL:
  1261. args.push_back("compare_func::not_equal");
  1262. break;
  1263. case MSL_SAMPLER_COMPARE_FUNC_LESS:
  1264. args.push_back("compare_func::less");
  1265. break;
  1266. case MSL_SAMPLER_COMPARE_FUNC_LESS_EQUAL:
  1267. args.push_back("compare_func::less_equal");
  1268. break;
  1269. case MSL_SAMPLER_COMPARE_FUNC_GREATER:
  1270. args.push_back("compare_func::greater");
  1271. break;
  1272. case MSL_SAMPLER_COMPARE_FUNC_GREATER_EQUAL:
  1273. args.push_back("compare_func::greater_equal");
  1274. break;
  1275. default:
  1276. SPIRV_CROSS_THROW("Invalid sampler compare function.");
  1277. }
  1278. }
  1279. if (s.s_address == MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER || s.t_address == MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER ||
  1280. s.r_address == MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER)
  1281. {
  1282. switch (s.border_color)
  1283. {
  1284. case MSL_SAMPLER_BORDER_COLOR_OPAQUE_BLACK:
  1285. args.push_back("border_color::opaque_black");
  1286. break;
  1287. case MSL_SAMPLER_BORDER_COLOR_OPAQUE_WHITE:
  1288. args.push_back("border_color::opaque_white");
  1289. break;
  1290. case MSL_SAMPLER_BORDER_COLOR_TRANSPARENT_BLACK:
  1291. args.push_back("border_color::transparent_black");
  1292. break;
  1293. default:
  1294. SPIRV_CROSS_THROW("Invalid sampler border color.");
  1295. }
  1296. }
  1297. if (s.anisotropy_enable)
  1298. args.push_back(join("max_anisotropy(", s.max_anisotropy, ")"));
  1299. if (s.lod_clamp_enable)
  1300. {
  1301. args.push_back(join("lod_clamp(", format_float(s.lod_clamp_min), ", ", format_float(s.lod_clamp_max), ")"));
  1302. }
  1303. // If we would emit no arguments, then omit the parentheses entirely. Otherwise,
  1304. // we'll wind up with a "most vexing parse" situation.
  1305. if (args.empty())
  1306. statement("constexpr sampler ",
  1307. type.basetype == SPIRType::SampledImage ? to_sampler_expression(samp.first) : to_name(samp.first),
  1308. ";");
  1309. else
  1310. statement("constexpr sampler ",
  1311. type.basetype == SPIRType::SampledImage ? to_sampler_expression(samp.first) : to_name(samp.first),
  1312. "(", merge(args), ");");
  1313. }
  1314. // Emit dynamic buffers here.
  1315. for (auto &dynamic_buffer : buffers_requiring_dynamic_offset)
  1316. {
  1317. if (!dynamic_buffer.second.var_id)
  1318. {
  1319. // Could happen if no buffer was used at requested binding point.
  1320. continue;
  1321. }
  1322. const auto &var = get<SPIRVariable>(dynamic_buffer.second.var_id);
  1323. uint32_t var_id = var.self;
  1324. const auto &type = get_variable_data_type(var);
  1325. add_local_variable_name(var.self);
  1326. string name = to_name(var.self);
  1327. uint32_t desc_set = get_decoration(var.self, DecorationDescriptorSet);
  1328. uint32_t arg_id = argument_buffer_ids[desc_set];
  1329. uint32_t base_index = dynamic_buffer.second.base_index;
  1330. if (is_array(type))
  1331. {
  1332. is_using_builtin_array = true;
  1333. statement(get_variable_address_space(var), " ", type_to_glsl(type), "* ", to_restrict(var_id, true), name,
  1334. type_to_array_glsl(type, var_id), " =");
  1335. uint32_t array_size = get_resource_array_size(type, var_id);
  1336. if (array_size == 0)
  1337. SPIRV_CROSS_THROW("Size of runtime array with dynamic offset could not be determined from resource bindings.");
  1338. begin_scope();
  1339. for (uint32_t i = 0; i < array_size; i++)
  1340. {
  1341. statement("(", get_variable_address_space(var), " ", type_to_glsl(type), "* ",
  1342. to_restrict(var_id, false), ")((", get_variable_address_space(var), " char* ",
  1343. to_restrict(var_id, false), ")", to_name(arg_id), ".", dynamic_buffer.second.mbr_name,
  1344. "[", i, "]", " + ", to_name(dynamic_offsets_buffer_id), "[", base_index + i, "]),");
  1345. }
  1346. end_scope_decl();
  1347. statement_no_indent("");
  1348. is_using_builtin_array = false;
  1349. }
  1350. else
  1351. {
  1352. statement(get_variable_address_space(var), " auto& ", to_restrict(var_id, true), name, " = *(",
  1353. get_variable_address_space(var), " ", type_to_glsl(type), "* ", to_restrict(var_id, false), ")((",
  1354. get_variable_address_space(var), " char* ", to_restrict(var_id, false), ")", to_name(arg_id), ".",
  1355. dynamic_buffer.second.mbr_name, " + ", to_name(dynamic_offsets_buffer_id), "[", base_index, "]);");
  1356. }
  1357. }
  1358. bool has_runtime_array_declaration = false;
  1359. for (SPIRVariable *arg : entry_point_bindings)
  1360. {
  1361. const auto &var = *arg;
  1362. const auto &type = get_variable_data_type(var);
  1363. const auto &buffer_type = get_variable_element_type(var);
  1364. // This has already been added as a resource name.
  1365. const string name = to_name(var.self);
  1366. if (is_var_runtime_size_array(var))
  1367. {
  1368. if (msl_options.argument_buffers_tier < Options::ArgumentBuffersTier::Tier2)
  1369. {
  1370. SPIRV_CROSS_THROW("Unsized array of descriptors requires argument buffer tier 2");
  1371. }
  1372. string resource_name;
  1373. if (descriptor_set_is_argument_buffer(get_decoration(var.self, DecorationDescriptorSet)))
  1374. {
  1375. resource_name = ir.meta[var.self].decoration.qualified_alias;
  1376. }
  1377. else
  1378. {
  1379. bool is_aliased = std::find_if(buffer_aliases_discrete.begin(), buffer_aliases_discrete.end(),
  1380. [&](uint32_t id) { return var.self == id; }) != buffer_aliases_discrete.end();
  1381. uint32_t desc_set = get_decoration(var.self, DecorationDescriptorSet);
  1382. uint32_t desc_binding = get_decoration(var.self, DecorationBinding);
  1383. if (is_aliased)
  1384. resource_name = join("spvBufferAliasSet", desc_set, "Binding", desc_binding);
  1385. else
  1386. resource_name = join("spvDescriptorSet", desc_set, "Binding", desc_binding);
  1387. }
  1388. switch (type.basetype)
  1389. {
  1390. case SPIRType::Image:
  1391. case SPIRType::Sampler:
  1392. case SPIRType::AccelerationStructure:
  1393. statement("spvDescriptorArray<", type_to_glsl(buffer_type, var.self), "> ", name, " {", resource_name, "};");
  1394. break;
  1395. case SPIRType::SampledImage:
  1396. statement("spvDescriptorArray<", type_to_glsl(buffer_type, var.self), "> ", name, " {", resource_name, "};");
  1397. // Unsupported with argument buffer for now.
  1398. statement("spvDescriptorArray<sampler> ", name, "Smplr {", resource_name, "Smplr};");
  1399. break;
  1400. case SPIRType::Struct:
  1401. statement("spvDescriptorArray<", get_variable_address_space(var), " ", type_to_glsl(buffer_type), "*> ",
  1402. name, " {", resource_name, "};");
  1403. break;
  1404. default:
  1405. break;
  1406. }
  1407. has_runtime_array_declaration = true;
  1408. }
  1409. else if (!type.array.empty() && type.basetype == SPIRType::Struct)
  1410. {
  1411. // Emit only buffer arrays here.
  1412. statement(get_variable_address_space(var), " ", type_to_glsl(buffer_type), "* ",
  1413. to_restrict(var.self, true), name, "[] =");
  1414. begin_scope();
  1415. uint32_t array_size = get_resource_array_size(type, var.self);
  1416. for (uint32_t i = 0; i < array_size; ++i)
  1417. statement(name, "_", i, ",");
  1418. end_scope_decl();
  1419. statement_no_indent("");
  1420. }
  1421. }
  1422. if (has_runtime_array_declaration)
  1423. statement_no_indent("");
  1424. // Emit buffer aliases here.
  1425. for (auto &var_id : buffer_aliases_discrete)
  1426. {
  1427. const auto &var = get<SPIRVariable>(var_id);
  1428. // We already declare this alias in a different way.
  1429. if (is_var_runtime_size_array(var))
  1430. continue;
  1431. const auto &type = get_variable_data_type(var);
  1432. auto addr_space = get_variable_address_space(var);
  1433. // This resource name has already been added.
  1434. auto name = to_name(var_id);
  1435. uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
  1436. uint32_t desc_binding = get_decoration(var_id, DecorationBinding);
  1437. auto alias_name = join("spvBufferAliasSet", desc_set, "Binding", desc_binding);
  1438. statement(addr_space, " auto& ", to_restrict(var_id, true),
  1439. name,
  1440. " = *(", addr_space, " ", type_to_glsl(type), "*)", alias_name, ";");
  1441. }
  1442. // Discrete descriptors are processed in entry point emission every compiler iteration.
  1443. buffer_aliases_discrete.clear();
  1444. // Emit disabled fragment outputs.
  1445. std::sort(disabled_frag_outputs.begin(), disabled_frag_outputs.end());
  1446. for (uint32_t var_id : disabled_frag_outputs)
  1447. {
  1448. auto &var = get<SPIRVariable>(var_id);
  1449. add_local_variable_name(var_id);
  1450. statement(CompilerGLSL::variable_decl(var), ";");
  1451. var.deferred_declaration = false;
  1452. }
  1453. // Holds SetMeshOutputsEXT information. Threadgroup since first thread wins.
  1454. if (processing_entry_point && is_mesh_shader())
  1455. statement("threadgroup uint2 spvMeshSizes;");
  1456. }
  1457. string CompilerMSL::compile()
  1458. {
  1459. replace_illegal_entry_point_names();
  1460. ir.fixup_reserved_names();
  1461. // Do not deal with GLES-isms like precision, older extensions and such.
  1462. options.vulkan_semantics = true;
  1463. options.es = false;
  1464. options.version = 450;
  1465. backend.null_pointer_literal = "nullptr";
  1466. backend.float_literal_suffix = false;
  1467. backend.uint32_t_literal_suffix = true;
  1468. backend.int16_t_literal_suffix = "";
  1469. backend.uint16_t_literal_suffix = "";
  1470. backend.basic_int_type = "int";
  1471. backend.basic_uint_type = "uint";
  1472. backend.basic_int8_type = "char";
  1473. backend.basic_uint8_type = "uchar";
  1474. backend.basic_int16_type = "short";
  1475. backend.basic_uint16_type = "ushort";
  1476. backend.boolean_mix_function = "select";
  1477. backend.printf_function = "os_log_default.log";
  1478. backend.swizzle_is_function = false;
  1479. backend.shared_is_implied = false;
  1480. backend.use_initializer_list = true;
  1481. backend.use_typed_initializer_list = true;
  1482. backend.native_row_major_matrix = false;
  1483. backend.unsized_array_supported = false;
  1484. backend.can_declare_arrays_inline = false;
  1485. backend.allow_truncated_access_chain = true;
  1486. backend.comparison_image_samples_scalar = true;
  1487. backend.native_pointers = true;
  1488. backend.nonuniform_qualifier = "";
  1489. backend.support_small_type_sampling_result = true;
  1490. backend.force_merged_mesh_block = false;
  1491. backend.force_gl_in_out_block = false;
  1492. backend.supports_empty_struct = true;
  1493. backend.support_64bit_switch = true;
  1494. backend.boolean_in_struct_remapped_type = SPIRType::Short;
  1495. // Allow Metal to use the array<T> template unless we force it off.
  1496. backend.can_return_array = !msl_options.force_native_arrays;
  1497. backend.array_is_value_type = !msl_options.force_native_arrays;
  1498. // Arrays which are part of buffer objects are never considered to be value types (just plain C-style).
  1499. backend.array_is_value_type_in_buffer_blocks = false;
  1500. backend.support_pointer_to_pointer = true;
  1501. backend.implicit_c_integer_promotion_rules = true;
  1502. backend.supports_spec_constant_array_size = false;
  1503. capture_output_to_buffer = msl_options.capture_output_to_buffer;
  1504. is_rasterization_disabled = msl_options.disable_rasterization || capture_output_to_buffer;
  1505. if (is_mesh_shader() && !get_entry_point().flags.get(ExecutionModeOutputPoints))
  1506. msl_options.enable_point_size_builtin = false;
  1507. // Initialize array here rather than constructor, MSVC 2013 workaround.
  1508. for (auto &id : next_metal_resource_ids)
  1509. id = 0;
  1510. fixup_anonymous_struct_names();
  1511. fixup_type_alias();
  1512. replace_illegal_names();
  1513. if (get_execution_model() == ExecutionModelMeshEXT)
  1514. {
  1515. // Emit proxy entry-point for the sake of copy-pass
  1516. emit_mesh_entry_point();
  1517. }
  1518. sync_entry_point_aliases_and_names();
  1519. build_function_control_flow_graphs_and_analyze();
  1520. update_active_builtins();
  1521. analyze_image_and_sampler_usage();
  1522. analyze_sampled_image_usage();
  1523. analyze_interlocked_resource_usage();
  1524. analyze_workgroup_variables();
  1525. preprocess_op_codes();
  1526. build_implicit_builtins();
  1527. if (needs_manual_helper_invocation_updates() && needs_helper_invocation)
  1528. {
  1529. string builtin_helper_invocation = builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput);
  1530. string discard_expr = join(builtin_helper_invocation, " = true, discard_fragment()");
  1531. if (msl_options.force_fragment_with_side_effects_execution)
  1532. discard_expr = join("!", builtin_helper_invocation, " ? (", discard_expr, ") : (void)0");
  1533. backend.discard_literal = discard_expr;
  1534. backend.demote_literal = discard_expr;
  1535. }
  1536. else
  1537. {
  1538. backend.discard_literal = "discard_fragment()";
  1539. backend.demote_literal = "discard_fragment()";
  1540. }
  1541. fixup_image_load_store_access();
  1542. set_enabled_interface_variables(get_active_interface_variables());
  1543. if (msl_options.force_active_argument_buffer_resources)
  1544. activate_argument_buffer_resources();
  1545. if (swizzle_buffer_id)
  1546. add_active_interface_variable(swizzle_buffer_id);
  1547. if (buffer_size_buffer_id)
  1548. add_active_interface_variable(buffer_size_buffer_id);
  1549. if (view_mask_buffer_id)
  1550. add_active_interface_variable(view_mask_buffer_id);
  1551. if (dynamic_offsets_buffer_id)
  1552. add_active_interface_variable(dynamic_offsets_buffer_id);
  1553. if (builtin_layer_id)
  1554. add_active_interface_variable(builtin_layer_id);
  1555. if (builtin_dispatch_base_id && !msl_options.supports_msl_version(1, 2))
  1556. add_active_interface_variable(builtin_dispatch_base_id);
  1557. if (builtin_sample_mask_id)
  1558. add_active_interface_variable(builtin_sample_mask_id);
  1559. if (builtin_frag_depth_id)
  1560. add_active_interface_variable(builtin_frag_depth_id);
  1561. // Create structs to hold input, output and uniform variables.
  1562. // Do output first to ensure out. is declared at top of entry function.
  1563. qual_pos_var_name = "";
  1564. if (is_mesh_shader())
  1565. {
  1566. fixup_implicit_builtin_block_names(get_execution_model());
  1567. }
  1568. else
  1569. {
  1570. stage_out_var_id = add_interface_block(StorageClassOutput);
  1571. patch_stage_out_var_id = add_interface_block(StorageClassOutput, true);
  1572. stage_in_var_id = add_interface_block(StorageClassInput);
  1573. }
  1574. if (is_tese_shader())
  1575. patch_stage_in_var_id = add_interface_block(StorageClassInput, true);
  1576. if (is_tesc_shader())
  1577. stage_out_ptr_var_id = add_interface_block_pointer(stage_out_var_id, StorageClassOutput);
  1578. if (is_tessellation_shader())
  1579. stage_in_ptr_var_id = add_interface_block_pointer(stage_in_var_id, StorageClassInput);
  1580. if (is_mesh_shader())
  1581. {
  1582. mesh_out_per_vertex = add_meshlet_block(false);
  1583. mesh_out_per_primitive = add_meshlet_block(true);
  1584. }
  1585. // Metal vertex functions that define no output must disable rasterization and return void.
  1586. if (!stage_out_var_id)
  1587. is_rasterization_disabled = true;
  1588. // Convert the use of global variables to recursively-passed function parameters
  1589. localize_global_variables();
  1590. extract_global_variables_from_functions();
  1591. // Mark any non-stage-in structs to be tightly packed.
  1592. mark_packable_structs();
  1593. reorder_type_alias();
  1594. // Add fixup hooks required by shader inputs and outputs. This needs to happen before
  1595. // the loop, so the hooks aren't added multiple times.
  1596. fix_up_shader_inputs_outputs();
  1597. // If we are using argument buffers, we create argument buffer structures for them here.
  1598. // These buffers will be used in the entry point, not the individual resources.
  1599. if (msl_options.argument_buffers)
  1600. {
  1601. if (!msl_options.supports_msl_version(2, 0))
  1602. SPIRV_CROSS_THROW("Argument buffers can only be used with MSL 2.0 and up.");
  1603. analyze_argument_buffers();
  1604. }
  1605. uint32_t pass_count = 0;
  1606. do
  1607. {
  1608. reset(pass_count);
  1609. // Start bindings at zero.
  1610. next_metal_resource_index_buffer = 0;
  1611. next_metal_resource_index_texture = 0;
  1612. next_metal_resource_index_sampler = 0;
  1613. for (auto &id : next_metal_resource_ids)
  1614. id = 0;
  1615. // Move constructor for this type is broken on GCC 4.9 ...
  1616. buffer.reset();
  1617. emit_header();
  1618. emit_custom_templates();
  1619. emit_custom_functions();
  1620. emit_specialization_constants_and_structs();
  1621. emit_resources();
  1622. emit_function(get<SPIRFunction>(ir.default_entry_point), Bitset());
  1623. pass_count++;
  1624. } while (is_forcing_recompilation());
  1625. return buffer.str();
  1626. }
  1627. // Register the need to output any custom functions.
  1628. void CompilerMSL::preprocess_op_codes()
  1629. {
  1630. OpCodePreprocessor preproc(*this);
  1631. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), preproc);
  1632. suppress_missing_prototypes = preproc.suppress_missing_prototypes;
  1633. if (preproc.uses_atomics)
  1634. {
  1635. add_header_line("#include <metal_atomic>");
  1636. add_pragma_line("#pragma clang diagnostic ignored \"-Wunused-variable\"", false);
  1637. }
  1638. // Before MSL 2.1 (2.2 for textures), Metal vertex functions that write to
  1639. // resources must disable rasterization and return void.
  1640. if ((preproc.uses_buffer_write && !msl_options.supports_msl_version(2, 1)) ||
  1641. (preproc.uses_image_write && !msl_options.supports_msl_version(2, 2)))
  1642. is_rasterization_disabled = true;
  1643. // FIXME: This currently does not consider BDA side effects, so we cannot deduce const device for BDA.
  1644. has_descriptor_side_effects_buffer = preproc.uses_buffer_write;
  1645. // Tessellation control shaders are run as compute functions in Metal, and so
  1646. // must capture their output to a buffer.
  1647. if (is_tesc_shader() || (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation))
  1648. {
  1649. is_rasterization_disabled = true;
  1650. capture_output_to_buffer = true;
  1651. }
  1652. if (preproc.needs_local_invocation_index)
  1653. needs_local_invocation_index = true;
  1654. if (preproc.needs_subgroup_invocation_id)
  1655. needs_subgroup_invocation_id = true;
  1656. if (preproc.needs_subgroup_size)
  1657. needs_subgroup_size = true;
  1658. // build_implicit_builtins() hasn't run yet, and in fact, this needs to execute
  1659. // before then so that gl_SampleID will get added; so we also need to check if
  1660. // that function would add gl_FragCoord.
  1661. if (preproc.needs_sample_id || msl_options.force_sample_rate_shading ||
  1662. (is_sample_rate() && (active_input_builtins.get(BuiltInFragCoord) ||
  1663. (need_subpass_input_ms && !msl_options.use_framebuffer_fetch_subpasses))))
  1664. needs_sample_id = true;
  1665. if (preproc.needs_helper_invocation || active_input_builtins.get(BuiltInHelperInvocation))
  1666. needs_helper_invocation = true;
  1667. // OpKill is removed by the parser, so we need to identify those by inspecting
  1668. // blocks.
  1669. ir.for_each_typed_id<SPIRBlock>([&preproc](uint32_t, SPIRBlock &block) {
  1670. if (block.terminator == SPIRBlock::Kill)
  1671. preproc.uses_discard = true;
  1672. });
  1673. // Fragment shaders that both write to storage resources and discard fragments
  1674. // need checks on the writes, to work around Metal allowing these writes despite
  1675. // the fragment being dead. We also require to force Metal to execute fragment
  1676. // shaders instead of being prematurely discarded.
  1677. if (preproc.uses_discard && (preproc.uses_buffer_write || preproc.uses_image_write))
  1678. {
  1679. bool should_enable = (msl_options.check_discarded_frag_stores || msl_options.force_fragment_with_side_effects_execution);
  1680. frag_shader_needs_discard_checks |= msl_options.check_discarded_frag_stores;
  1681. needs_helper_invocation |= should_enable;
  1682. // Fragment discard store checks imply manual HelperInvocation updates.
  1683. msl_options.manual_helper_invocation_updates |= should_enable;
  1684. }
  1685. if (is_intersection_query())
  1686. {
  1687. add_header_line("#if __METAL_VERSION__ >= 230");
  1688. add_header_line("#include <metal_raytracing>");
  1689. add_header_line("using namespace metal::raytracing;");
  1690. add_header_line("#endif");
  1691. }
  1692. }
  1693. // Move the Private and Workgroup global variables to the entry function.
  1694. // Non-constant variables cannot have global scope in Metal.
  1695. void CompilerMSL::localize_global_variables()
  1696. {
  1697. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  1698. auto iter = global_variables.begin();
  1699. while (iter != global_variables.end())
  1700. {
  1701. uint32_t v_id = *iter;
  1702. auto &var = get<SPIRVariable>(v_id);
  1703. if (var.storage == StorageClassPrivate || var.storage == StorageClassWorkgroup ||
  1704. var.storage == StorageClassTaskPayloadWorkgroupEXT)
  1705. {
  1706. if (!variable_is_lut(var))
  1707. entry_func.add_local_variable(v_id);
  1708. iter = global_variables.erase(iter);
  1709. }
  1710. else if (var.storage == StorageClassOutput && is_mesh_shader())
  1711. {
  1712. entry_func.add_local_variable(v_id);
  1713. iter = global_variables.erase(iter);
  1714. }
  1715. else
  1716. iter++;
  1717. }
  1718. }
  1719. // For any global variable accessed directly by a function,
  1720. // extract that variable and add it as an argument to that function.
  1721. void CompilerMSL::extract_global_variables_from_functions()
  1722. {
  1723. // Uniforms
  1724. unordered_set<uint32_t> global_var_ids;
  1725. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
  1726. // Some builtins resolve directly to a function call which does not need any declared variables.
  1727. // Skip these.
  1728. if (var.storage == StorageClassInput && has_decoration(var.self, DecorationBuiltIn))
  1729. {
  1730. auto bi_type = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
  1731. if (bi_type == BuiltInHelperInvocation && !needs_manual_helper_invocation_updates())
  1732. return;
  1733. if (bi_type == BuiltInHelperInvocation && needs_manual_helper_invocation_updates())
  1734. {
  1735. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
  1736. SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.3 on iOS.");
  1737. else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1))
  1738. SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.1 on macOS.");
  1739. // Make sure this is declared and initialized.
  1740. // Force this to have the proper name.
  1741. set_name(var.self, builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput));
  1742. auto &entry_func = this->get<SPIRFunction>(ir.default_entry_point);
  1743. entry_func.add_local_variable(var.self);
  1744. vars_needing_early_declaration.push_back(var.self);
  1745. entry_func.fixup_hooks_in.push_back([this, &var]()
  1746. { statement(to_name(var.self), " = simd_is_helper_thread();"); });
  1747. }
  1748. }
  1749. if (var.storage == StorageClassInput || var.storage == StorageClassOutput ||
  1750. var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant ||
  1751. var.storage == StorageClassPushConstant || var.storage == StorageClassStorageBuffer)
  1752. {
  1753. global_var_ids.insert(var.self);
  1754. }
  1755. });
  1756. // Local vars that are declared in the main function and accessed directly by a function
  1757. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  1758. for (auto &var : entry_func.local_variables)
  1759. if (get<SPIRVariable>(var).storage != StorageClassFunction)
  1760. global_var_ids.insert(var);
  1761. std::set<uint32_t> added_arg_ids;
  1762. unordered_set<uint32_t> processed_func_ids;
  1763. extract_global_variables_from_function(ir.default_entry_point, added_arg_ids, global_var_ids, processed_func_ids);
  1764. }
  1765. // MSL does not support the use of global variables for shader input content.
  1766. // For any global variable accessed directly by the specified function, extract that variable,
  1767. // add it as an argument to that function, and the arg to the added_arg_ids collection.
  1768. void CompilerMSL::extract_global_variables_from_function(uint32_t func_id, std::set<uint32_t> &added_arg_ids,
  1769. unordered_set<uint32_t> &global_var_ids,
  1770. unordered_set<uint32_t> &processed_func_ids)
  1771. {
  1772. // Avoid processing a function more than once
  1773. if (processed_func_ids.find(func_id) != processed_func_ids.end())
  1774. {
  1775. // Return function global variables
  1776. added_arg_ids = function_global_vars[func_id];
  1777. return;
  1778. }
  1779. processed_func_ids.insert(func_id);
  1780. auto &func = get<SPIRFunction>(func_id);
  1781. // Recursively establish global args added to functions on which we depend.
  1782. for (auto block : func.blocks)
  1783. {
  1784. auto &b = get<SPIRBlock>(block);
  1785. for (auto &i : b.ops)
  1786. {
  1787. auto ops = stream(i);
  1788. auto op = static_cast<Op>(i.op);
  1789. switch (op)
  1790. {
  1791. case OpLoad:
  1792. case OpInBoundsAccessChain:
  1793. case OpAccessChain:
  1794. case OpPtrAccessChain:
  1795. case OpArrayLength:
  1796. {
  1797. uint32_t base_id = ops[2];
  1798. if (global_var_ids.find(base_id) != global_var_ids.end())
  1799. added_arg_ids.insert(base_id);
  1800. // Use Metal's native frame-buffer fetch API for subpass inputs.
  1801. auto &type = get<SPIRType>(ops[0]);
  1802. if (type.basetype == SPIRType::Image && type.image.dim == DimSubpassData &&
  1803. (!msl_options.use_framebuffer_fetch_subpasses))
  1804. {
  1805. // Implicitly reads gl_FragCoord.
  1806. assert(builtin_frag_coord_id != 0);
  1807. added_arg_ids.insert(builtin_frag_coord_id);
  1808. if (msl_options.multiview)
  1809. {
  1810. // Implicitly reads gl_ViewIndex.
  1811. assert(builtin_view_idx_id != 0);
  1812. added_arg_ids.insert(builtin_view_idx_id);
  1813. }
  1814. else if (msl_options.arrayed_subpass_input)
  1815. {
  1816. // Implicitly reads gl_Layer.
  1817. assert(builtin_layer_id != 0);
  1818. added_arg_ids.insert(builtin_layer_id);
  1819. }
  1820. }
  1821. break;
  1822. }
  1823. case OpFunctionCall:
  1824. {
  1825. // First see if any of the function call args are globals
  1826. for (uint32_t arg_idx = 3; arg_idx < i.length; arg_idx++)
  1827. {
  1828. uint32_t arg_id = ops[arg_idx];
  1829. if (global_var_ids.find(arg_id) != global_var_ids.end())
  1830. added_arg_ids.insert(arg_id);
  1831. }
  1832. // Then recurse into the function itself to extract globals used internally in the function
  1833. uint32_t inner_func_id = ops[2];
  1834. std::set<uint32_t> inner_func_args;
  1835. extract_global_variables_from_function(inner_func_id, inner_func_args, global_var_ids,
  1836. processed_func_ids);
  1837. added_arg_ids.insert(inner_func_args.begin(), inner_func_args.end());
  1838. break;
  1839. }
  1840. case OpStore:
  1841. {
  1842. uint32_t base_id = ops[0];
  1843. if (global_var_ids.find(base_id) != global_var_ids.end())
  1844. {
  1845. added_arg_ids.insert(base_id);
  1846. if (msl_options.input_attachment_is_ds_attachment && base_id == builtin_frag_depth_id)
  1847. writes_to_depth = true;
  1848. }
  1849. uint32_t rvalue_id = ops[1];
  1850. if (global_var_ids.find(rvalue_id) != global_var_ids.end())
  1851. added_arg_ids.insert(rvalue_id);
  1852. if (needs_frag_discard_checks())
  1853. added_arg_ids.insert(builtin_helper_invocation_id);
  1854. break;
  1855. }
  1856. case OpSelect:
  1857. {
  1858. uint32_t base_id = ops[3];
  1859. if (global_var_ids.find(base_id) != global_var_ids.end())
  1860. added_arg_ids.insert(base_id);
  1861. base_id = ops[4];
  1862. if (global_var_ids.find(base_id) != global_var_ids.end())
  1863. added_arg_ids.insert(base_id);
  1864. break;
  1865. }
  1866. case OpAtomicExchange:
  1867. case OpAtomicCompareExchange:
  1868. case OpAtomicStore:
  1869. case OpAtomicIIncrement:
  1870. case OpAtomicIDecrement:
  1871. case OpAtomicIAdd:
  1872. case OpAtomicFAddEXT:
  1873. case OpAtomicISub:
  1874. case OpAtomicSMin:
  1875. case OpAtomicUMin:
  1876. case OpAtomicSMax:
  1877. case OpAtomicUMax:
  1878. case OpAtomicAnd:
  1879. case OpAtomicOr:
  1880. case OpAtomicXor:
  1881. case OpImageWrite:
  1882. {
  1883. if (needs_frag_discard_checks())
  1884. added_arg_ids.insert(builtin_helper_invocation_id);
  1885. uint32_t ptr = 0;
  1886. if (op == OpAtomicStore || op == OpImageWrite)
  1887. ptr = ops[0];
  1888. else
  1889. ptr = ops[2];
  1890. if (global_var_ids.find(ptr) != global_var_ids.end())
  1891. added_arg_ids.insert(ptr);
  1892. break;
  1893. }
  1894. // Emulate texture2D atomic operations
  1895. case OpImageTexelPointer:
  1896. {
  1897. // When using the pointer, we need to know which variable it is actually loaded from.
  1898. uint32_t base_id = ops[2];
  1899. auto *var = maybe_get_backing_variable(base_id);
  1900. if (var)
  1901. {
  1902. if (atomic_image_vars_emulated.count(var->self) &&
  1903. !get<SPIRType>(var->basetype).array.empty())
  1904. {
  1905. SPIRV_CROSS_THROW(
  1906. "Cannot emulate array of storage images with atomics. Use MSL 3.1 for native support.");
  1907. }
  1908. if (global_var_ids.find(base_id) != global_var_ids.end())
  1909. added_arg_ids.insert(base_id);
  1910. }
  1911. break;
  1912. }
  1913. case OpExtInst:
  1914. {
  1915. uint32_t extension_set = ops[2];
  1916. if (get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
  1917. {
  1918. auto op_450 = static_cast<GLSLstd450>(ops[3]);
  1919. switch (op_450)
  1920. {
  1921. case GLSLstd450InterpolateAtCentroid:
  1922. case GLSLstd450InterpolateAtSample:
  1923. case GLSLstd450InterpolateAtOffset:
  1924. {
  1925. // For these, we really need the stage-in block. It is theoretically possible to pass the
  1926. // interpolant object, but a) doing so would require us to create an entirely new variable
  1927. // with Interpolant type, and b) if we have a struct or array, handling all the members and
  1928. // elements could get unwieldy fast.
  1929. added_arg_ids.insert(stage_in_var_id);
  1930. break;
  1931. }
  1932. case GLSLstd450Modf:
  1933. case GLSLstd450Frexp:
  1934. {
  1935. uint32_t base_id = ops[5];
  1936. if (global_var_ids.find(base_id) != global_var_ids.end())
  1937. added_arg_ids.insert(base_id);
  1938. break;
  1939. }
  1940. default:
  1941. break;
  1942. }
  1943. }
  1944. break;
  1945. }
  1946. case OpGroupNonUniformInverseBallot:
  1947. {
  1948. added_arg_ids.insert(builtin_subgroup_invocation_id_id);
  1949. break;
  1950. }
  1951. case OpGroupNonUniformBallotFindLSB:
  1952. case OpGroupNonUniformBallotFindMSB:
  1953. {
  1954. added_arg_ids.insert(builtin_subgroup_size_id);
  1955. break;
  1956. }
  1957. case OpGroupNonUniformBallotBitCount:
  1958. {
  1959. auto operation = static_cast<GroupOperation>(ops[3]);
  1960. switch (operation)
  1961. {
  1962. case GroupOperationReduce:
  1963. added_arg_ids.insert(builtin_subgroup_size_id);
  1964. break;
  1965. case GroupOperationInclusiveScan:
  1966. case GroupOperationExclusiveScan:
  1967. added_arg_ids.insert(builtin_subgroup_invocation_id_id);
  1968. break;
  1969. default:
  1970. break;
  1971. }
  1972. break;
  1973. }
  1974. case OpGroupNonUniformRotateKHR:
  1975. {
  1976. // Add the correct invocation ID for calculating clustered rotate case.
  1977. if (i.length > 5)
  1978. added_arg_ids.insert(static_cast<Scope>(evaluate_constant_u32(ops[2])) == ScopeSubgroup
  1979. ? builtin_subgroup_invocation_id_id : builtin_local_invocation_index_id);
  1980. break;
  1981. }
  1982. case OpGroupNonUniformFAdd:
  1983. case OpGroupNonUniformFMul:
  1984. case OpGroupNonUniformFMin:
  1985. case OpGroupNonUniformFMax:
  1986. case OpGroupNonUniformIAdd:
  1987. case OpGroupNonUniformIMul:
  1988. case OpGroupNonUniformSMin:
  1989. case OpGroupNonUniformSMax:
  1990. case OpGroupNonUniformUMin:
  1991. case OpGroupNonUniformUMax:
  1992. case OpGroupNonUniformBitwiseAnd:
  1993. case OpGroupNonUniformBitwiseOr:
  1994. case OpGroupNonUniformBitwiseXor:
  1995. case OpGroupNonUniformLogicalAnd:
  1996. case OpGroupNonUniformLogicalOr:
  1997. case OpGroupNonUniformLogicalXor:
  1998. if ((get_execution_model() != ExecutionModelFragment || msl_options.supports_msl_version(2, 2)) &&
  1999. ops[3] == GroupOperationClusteredReduce)
  2000. added_arg_ids.insert(builtin_subgroup_invocation_id_id);
  2001. break;
  2002. case OpDemoteToHelperInvocation:
  2003. if (needs_manual_helper_invocation_updates() && needs_helper_invocation)
  2004. added_arg_ids.insert(builtin_helper_invocation_id);
  2005. break;
  2006. case OpIsHelperInvocationEXT:
  2007. if (needs_manual_helper_invocation_updates())
  2008. added_arg_ids.insert(builtin_helper_invocation_id);
  2009. break;
  2010. case OpRayQueryInitializeKHR:
  2011. case OpRayQueryProceedKHR:
  2012. case OpRayQueryTerminateKHR:
  2013. case OpRayQueryGenerateIntersectionKHR:
  2014. case OpRayQueryConfirmIntersectionKHR:
  2015. {
  2016. // Ray query accesses memory directly, need check pass down object if using Private storage class.
  2017. uint32_t base_id = ops[0];
  2018. if (global_var_ids.find(base_id) != global_var_ids.end())
  2019. added_arg_ids.insert(base_id);
  2020. break;
  2021. }
  2022. case OpRayQueryGetRayTMinKHR:
  2023. case OpRayQueryGetRayFlagsKHR:
  2024. case OpRayQueryGetWorldRayOriginKHR:
  2025. case OpRayQueryGetWorldRayDirectionKHR:
  2026. case OpRayQueryGetIntersectionCandidateAABBOpaqueKHR:
  2027. case OpRayQueryGetIntersectionTypeKHR:
  2028. case OpRayQueryGetIntersectionTKHR:
  2029. case OpRayQueryGetIntersectionInstanceCustomIndexKHR:
  2030. case OpRayQueryGetIntersectionInstanceIdKHR:
  2031. case OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR:
  2032. case OpRayQueryGetIntersectionGeometryIndexKHR:
  2033. case OpRayQueryGetIntersectionPrimitiveIndexKHR:
  2034. case OpRayQueryGetIntersectionBarycentricsKHR:
  2035. case OpRayQueryGetIntersectionFrontFaceKHR:
  2036. case OpRayQueryGetIntersectionObjectRayDirectionKHR:
  2037. case OpRayQueryGetIntersectionObjectRayOriginKHR:
  2038. case OpRayQueryGetIntersectionObjectToWorldKHR:
  2039. case OpRayQueryGetIntersectionWorldToObjectKHR:
  2040. {
  2041. // Ray query accesses memory directly, need check pass down object if using Private storage class.
  2042. uint32_t base_id = ops[2];
  2043. if (global_var_ids.find(base_id) != global_var_ids.end())
  2044. added_arg_ids.insert(base_id);
  2045. break;
  2046. }
  2047. case OpSetMeshOutputsEXT:
  2048. {
  2049. if (builtin_local_invocation_index_id != 0)
  2050. added_arg_ids.insert(builtin_local_invocation_index_id);
  2051. if (builtin_mesh_sizes_id != 0)
  2052. added_arg_ids.insert(builtin_mesh_sizes_id);
  2053. break;
  2054. }
  2055. default:
  2056. break;
  2057. }
  2058. if (needs_manual_helper_invocation_updates() && b.terminator == SPIRBlock::Kill &&
  2059. needs_helper_invocation)
  2060. added_arg_ids.insert(builtin_helper_invocation_id);
  2061. // TODO: Add all other operations which can affect memory.
  2062. // We should consider a more unified system here to reduce boiler-plate.
  2063. // This kind of analysis is done in several places ...
  2064. }
  2065. if (b.terminator == SPIRBlock::EmitMeshTasks && builtin_task_grid_id != 0)
  2066. added_arg_ids.insert(builtin_task_grid_id);
  2067. }
  2068. function_global_vars[func_id] = added_arg_ids;
  2069. // Add the global variables as arguments to the function
  2070. if (func_id != ir.default_entry_point)
  2071. {
  2072. bool control_point_added_in = false;
  2073. bool control_point_added_out = false;
  2074. bool patch_added_in = false;
  2075. bool patch_added_out = false;
  2076. for (uint32_t arg_id : added_arg_ids)
  2077. {
  2078. auto &var = get<SPIRVariable>(arg_id);
  2079. uint32_t type_id = var.basetype;
  2080. auto *p_type = &get<SPIRType>(type_id);
  2081. BuiltIn bi_type = BuiltIn(get_decoration(arg_id, DecorationBuiltIn));
  2082. bool is_patch = has_decoration(arg_id, DecorationPatch) || is_patch_block(*p_type);
  2083. bool is_block = has_decoration(p_type->self, DecorationBlock);
  2084. bool is_control_point_storage =
  2085. !is_patch && ((is_tessellation_shader() && var.storage == StorageClassInput) ||
  2086. (is_tesc_shader() && var.storage == StorageClassOutput));
  2087. bool is_patch_block_storage = is_patch && is_block && var.storage == StorageClassOutput;
  2088. bool is_builtin = is_builtin_variable(var);
  2089. bool variable_is_stage_io =
  2090. !is_builtin || bi_type == BuiltInPosition || bi_type == BuiltInPointSize ||
  2091. bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance ||
  2092. p_type->basetype == SPIRType::Struct;
  2093. bool is_redirected_to_global_stage_io = (is_control_point_storage || is_patch_block_storage) &&
  2094. variable_is_stage_io;
  2095. // If output is masked it is not considered part of the global stage IO interface.
  2096. if (is_redirected_to_global_stage_io && var.storage == StorageClassOutput)
  2097. is_redirected_to_global_stage_io = !is_stage_output_variable_masked(var);
  2098. if (is_redirected_to_global_stage_io)
  2099. {
  2100. // Tessellation control shaders see inputs and per-point outputs as arrays.
  2101. // Similarly, tessellation evaluation shaders see per-point inputs as arrays.
  2102. // We collected them into a structure; we must pass the array of this
  2103. // structure to the function.
  2104. std::string name;
  2105. if (is_patch)
  2106. name = var.storage == StorageClassInput ? patch_stage_in_var_name : patch_stage_out_var_name;
  2107. else
  2108. name = var.storage == StorageClassInput ? "gl_in" : "gl_out";
  2109. if (var.storage == StorageClassOutput && has_decoration(p_type->self, DecorationBlock))
  2110. {
  2111. // If we're redirecting a block, we might still need to access the original block
  2112. // variable if we're masking some members.
  2113. for (uint32_t mbr_idx = 0; mbr_idx < uint32_t(p_type->member_types.size()); mbr_idx++)
  2114. {
  2115. if (is_stage_output_block_member_masked(var, mbr_idx, true))
  2116. {
  2117. func.add_parameter(var.basetype, var.self, true);
  2118. break;
  2119. }
  2120. }
  2121. }
  2122. if (var.storage == StorageClassInput)
  2123. {
  2124. auto &added_in = is_patch ? patch_added_in : control_point_added_in;
  2125. if (added_in)
  2126. continue;
  2127. arg_id = is_patch ? patch_stage_in_var_id : stage_in_ptr_var_id;
  2128. added_in = true;
  2129. }
  2130. else if (var.storage == StorageClassOutput)
  2131. {
  2132. auto &added_out = is_patch ? patch_added_out : control_point_added_out;
  2133. if (added_out)
  2134. continue;
  2135. arg_id = is_patch ? patch_stage_out_var_id : stage_out_ptr_var_id;
  2136. added_out = true;
  2137. }
  2138. type_id = get<SPIRVariable>(arg_id).basetype;
  2139. uint32_t next_id = ir.increase_bound_by(1);
  2140. func.add_parameter(type_id, next_id, true);
  2141. set<SPIRVariable>(next_id, type_id, StorageClassFunction, 0, arg_id);
  2142. set_name(next_id, name);
  2143. if (is_tese_shader() && msl_options.raw_buffer_tese_input && var.storage == StorageClassInput)
  2144. set_decoration(next_id, DecorationNonWritable);
  2145. }
  2146. else if (is_builtin && is_mesh_shader())
  2147. {
  2148. uint32_t next_id = ir.increase_bound_by(1);
  2149. func.add_parameter(type_id, next_id, true);
  2150. auto &v = set<SPIRVariable>(next_id, type_id, StorageClassFunction, 0, arg_id);
  2151. v.storage = StorageClassWorkgroup;
  2152. // Ensure the existing variable has a valid name and the new variable has all the same meta info
  2153. if (ir.meta[arg_id].decoration.builtin)
  2154. {
  2155. set_name(arg_id, builtin_to_glsl(bi_type, var.storage));
  2156. }
  2157. else
  2158. {
  2159. set_name(arg_id, ensure_valid_name(to_name(arg_id), "v"));
  2160. }
  2161. ir.meta[next_id] = ir.meta[arg_id];
  2162. }
  2163. else if (is_builtin && has_decoration(p_type->self, DecorationBlock))
  2164. {
  2165. // Get the pointee type
  2166. type_id = get_pointee_type_id(type_id);
  2167. p_type = &get<SPIRType>(type_id);
  2168. uint32_t mbr_idx = 0;
  2169. for (auto &mbr_type_id : p_type->member_types)
  2170. {
  2171. BuiltIn builtin = BuiltInMax;
  2172. is_builtin = is_member_builtin(*p_type, mbr_idx, &builtin);
  2173. if (is_builtin && has_active_builtin(builtin, var.storage))
  2174. {
  2175. // Add a arg variable with the same type and decorations as the member
  2176. uint32_t next_ids = ir.increase_bound_by(2);
  2177. uint32_t ptr_type_id = next_ids + 0;
  2178. uint32_t var_id = next_ids + 1;
  2179. // Make sure we have an actual pointer type,
  2180. // so that we will get the appropriate address space when declaring these builtins.
  2181. auto &ptr = set<SPIRType>(ptr_type_id, get<SPIRType>(mbr_type_id));
  2182. ptr.self = mbr_type_id;
  2183. ptr.storage = var.storage;
  2184. ptr.pointer = true;
  2185. ptr.pointer_depth++;
  2186. ptr.parent_type = mbr_type_id;
  2187. func.add_parameter(mbr_type_id, var_id, true);
  2188. set<SPIRVariable>(var_id, ptr_type_id, StorageClassFunction);
  2189. ir.meta[var_id].decoration = ir.meta[type_id].members[mbr_idx];
  2190. }
  2191. mbr_idx++;
  2192. }
  2193. }
  2194. else
  2195. {
  2196. uint32_t next_id = ir.increase_bound_by(1);
  2197. func.add_parameter(type_id, next_id, true);
  2198. set<SPIRVariable>(next_id, type_id, StorageClassFunction, 0, arg_id);
  2199. // Ensure the new variable has all the same meta info
  2200. ir.meta[next_id] = ir.meta[arg_id];
  2201. }
  2202. }
  2203. }
  2204. }
  2205. // For all variables that are some form of non-input-output interface block, mark that all the structs
  2206. // that are recursively contained within the type referenced by that variable should be packed tightly.
  2207. void CompilerMSL::mark_packable_structs()
  2208. {
  2209. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
  2210. if (var.storage != StorageClassFunction && !is_hidden_variable(var))
  2211. {
  2212. auto &type = this->get<SPIRType>(var.basetype);
  2213. if (type.pointer &&
  2214. (type.storage == StorageClassUniform || type.storage == StorageClassUniformConstant ||
  2215. type.storage == StorageClassPushConstant || type.storage == StorageClassStorageBuffer) &&
  2216. (has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock)))
  2217. mark_as_packable(type);
  2218. }
  2219. if (var.storage == StorageClassWorkgroup)
  2220. {
  2221. auto *type = &this->get<SPIRType>(var.basetype);
  2222. if (type->basetype == SPIRType::Struct)
  2223. mark_as_workgroup_struct(*type);
  2224. }
  2225. });
  2226. // Physical storage buffer pointers can appear outside of the context of a variable, if the address
  2227. // is calculated from a ulong or uvec2 and cast to a pointer, so check if they need to be packed too.
  2228. ir.for_each_typed_id<SPIRType>([&](uint32_t, SPIRType &type) {
  2229. if (type.basetype == SPIRType::Struct && type.pointer && type.storage == StorageClassPhysicalStorageBuffer)
  2230. mark_as_packable(type);
  2231. });
  2232. }
  2233. // If the specified type is a struct, it and any nested structs
  2234. // are marked as packable with the SPIRVCrossDecorationBufferBlockRepacked decoration,
  2235. void CompilerMSL::mark_as_packable(SPIRType &type)
  2236. {
  2237. // If this is not the base type (eg. it's a pointer or array), tunnel down
  2238. if (type.parent_type)
  2239. {
  2240. mark_as_packable(get<SPIRType>(type.parent_type));
  2241. return;
  2242. }
  2243. // Handle possible recursion when a struct contains a pointer to its own type nested somewhere.
  2244. if (type.basetype == SPIRType::Struct && !has_extended_decoration(type.self, SPIRVCrossDecorationBufferBlockRepacked))
  2245. {
  2246. set_extended_decoration(type.self, SPIRVCrossDecorationBufferBlockRepacked);
  2247. // Recurse
  2248. uint32_t mbr_cnt = uint32_t(type.member_types.size());
  2249. for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
  2250. {
  2251. uint32_t mbr_type_id = type.member_types[mbr_idx];
  2252. auto &mbr_type = get<SPIRType>(mbr_type_id);
  2253. mark_as_packable(mbr_type);
  2254. if (mbr_type.type_alias)
  2255. {
  2256. auto &mbr_type_alias = get<SPIRType>(mbr_type.type_alias);
  2257. mark_as_packable(mbr_type_alias);
  2258. }
  2259. }
  2260. }
  2261. }
  2262. // If the specified type is a struct, it and any nested structs
  2263. // are marked as used with workgroup storage using the SPIRVCrossDecorationWorkgroupStruct decoration.
  2264. void CompilerMSL::mark_as_workgroup_struct(SPIRType &type)
  2265. {
  2266. // If this is not the base type (eg. it's a pointer or array), tunnel down
  2267. if (type.parent_type)
  2268. {
  2269. mark_as_workgroup_struct(get<SPIRType>(type.parent_type));
  2270. return;
  2271. }
  2272. // Handle possible recursion when a struct contains a pointer to its own type nested somewhere.
  2273. if (type.basetype == SPIRType::Struct && !has_extended_decoration(type.self, SPIRVCrossDecorationWorkgroupStruct))
  2274. {
  2275. set_extended_decoration(type.self, SPIRVCrossDecorationWorkgroupStruct);
  2276. // Recurse
  2277. uint32_t mbr_cnt = uint32_t(type.member_types.size());
  2278. for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
  2279. {
  2280. uint32_t mbr_type_id = type.member_types[mbr_idx];
  2281. auto &mbr_type = get<SPIRType>(mbr_type_id);
  2282. mark_as_workgroup_struct(mbr_type);
  2283. if (mbr_type.type_alias)
  2284. {
  2285. auto &mbr_type_alias = get<SPIRType>(mbr_type.type_alias);
  2286. mark_as_workgroup_struct(mbr_type_alias);
  2287. }
  2288. }
  2289. }
  2290. }
  2291. // If a shader input exists at the location, it is marked as being used by this shader
  2292. void CompilerMSL::mark_location_as_used_by_shader(uint32_t location, const SPIRType &type,
  2293. StorageClass storage, bool fallback)
  2294. {
  2295. uint32_t count = type_to_location_count(type);
  2296. switch (storage)
  2297. {
  2298. case StorageClassInput:
  2299. for (uint32_t i = 0; i < count; i++)
  2300. {
  2301. location_inputs_in_use.insert(location + i);
  2302. if (fallback)
  2303. location_inputs_in_use_fallback.insert(location + i);
  2304. }
  2305. break;
  2306. case StorageClassOutput:
  2307. for (uint32_t i = 0; i < count; i++)
  2308. {
  2309. location_outputs_in_use.insert(location + i);
  2310. if (fallback)
  2311. location_outputs_in_use_fallback.insert(location + i);
  2312. }
  2313. break;
  2314. default:
  2315. return;
  2316. }
  2317. }
  2318. uint32_t CompilerMSL::get_target_components_for_fragment_location(uint32_t location) const
  2319. {
  2320. auto itr = fragment_output_components.find(location);
  2321. if (itr == end(fragment_output_components))
  2322. return 4;
  2323. else
  2324. return itr->second;
  2325. }
  2326. uint32_t CompilerMSL::build_extended_vector_type(uint32_t type_id, uint32_t components, SPIRType::BaseType basetype)
  2327. {
  2328. assert(components > 1);
  2329. uint32_t new_type_id = ir.increase_bound_by(1);
  2330. const auto *p_old_type = &get<SPIRType>(type_id);
  2331. const SPIRType *old_ptr_t = nullptr;
  2332. const SPIRType *old_array_t = nullptr;
  2333. if (is_pointer(*p_old_type))
  2334. {
  2335. old_ptr_t = p_old_type;
  2336. p_old_type = &get_pointee_type(*old_ptr_t);
  2337. }
  2338. if (is_array(*p_old_type))
  2339. {
  2340. old_array_t = p_old_type;
  2341. p_old_type = &get_type(old_array_t->parent_type);
  2342. }
  2343. auto *type = &set<SPIRType>(new_type_id, *p_old_type);
  2344. assert(is_scalar(*type) || is_vector(*type));
  2345. type->op = OpTypeVector;
  2346. type->vecsize = components;
  2347. if (basetype != SPIRType::Unknown)
  2348. type->basetype = basetype;
  2349. type->self = new_type_id;
  2350. // We want parent type to point to the scalar type.
  2351. type->parent_type = is_scalar(*p_old_type) ? TypeID(p_old_type->self) : p_old_type->parent_type;
  2352. assert(is_scalar(get<SPIRType>(type->parent_type)));
  2353. type->array.clear();
  2354. type->array_size_literal.clear();
  2355. type->pointer = false;
  2356. if (old_array_t)
  2357. {
  2358. uint32_t array_type_id = ir.increase_bound_by(1);
  2359. type = &set<SPIRType>(array_type_id, *type);
  2360. type->op = OpTypeArray;
  2361. type->parent_type = new_type_id;
  2362. type->array = old_array_t->array;
  2363. type->array_size_literal = old_array_t->array_size_literal;
  2364. new_type_id = array_type_id;
  2365. }
  2366. if (old_ptr_t)
  2367. {
  2368. uint32_t ptr_type_id = ir.increase_bound_by(1);
  2369. type = &set<SPIRType>(ptr_type_id, *type);
  2370. type->op = OpTypePointer;
  2371. type->parent_type = new_type_id;
  2372. type->storage = old_ptr_t->storage;
  2373. type->pointer = true;
  2374. type->pointer_depth++;
  2375. new_type_id = ptr_type_id;
  2376. }
  2377. return new_type_id;
  2378. }
  2379. uint32_t CompilerMSL::build_msl_interpolant_type(uint32_t type_id, bool is_noperspective)
  2380. {
  2381. uint32_t new_type_id = ir.increase_bound_by(1);
  2382. SPIRType &type = set<SPIRType>(new_type_id, get<SPIRType>(type_id));
  2383. type.basetype = SPIRType::Interpolant;
  2384. type.parent_type = type_id;
  2385. // In Metal, the pull-model interpolant type encodes perspective-vs-no-perspective in the type itself.
  2386. // Add this decoration so we know which argument to pass to the template.
  2387. if (is_noperspective)
  2388. set_decoration(new_type_id, DecorationNoPerspective);
  2389. return new_type_id;
  2390. }
  2391. bool CompilerMSL::add_component_variable_to_interface_block(StorageClass storage, const std::string &ib_var_ref,
  2392. SPIRVariable &var,
  2393. const SPIRType &type,
  2394. InterfaceBlockMeta &meta)
  2395. {
  2396. // Deal with Component decorations.
  2397. const InterfaceBlockMeta::LocationMeta *location_meta = nullptr;
  2398. uint32_t location = ~0u;
  2399. if (has_decoration(var.self, DecorationLocation))
  2400. {
  2401. location = get_decoration(var.self, DecorationLocation);
  2402. auto location_meta_itr = meta.location_meta.find(location);
  2403. if (location_meta_itr != end(meta.location_meta))
  2404. location_meta = &location_meta_itr->second;
  2405. }
  2406. // Check if we need to pad fragment output to match a certain number of components.
  2407. if (location_meta)
  2408. {
  2409. bool pad_fragment_output = has_decoration(var.self, DecorationLocation) &&
  2410. msl_options.pad_fragment_output_components &&
  2411. get_entry_point().model == ExecutionModelFragment && storage == StorageClassOutput;
  2412. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  2413. uint32_t start_component = get_decoration(var.self, DecorationComponent);
  2414. uint32_t type_components = type.vecsize;
  2415. uint32_t num_components = location_meta->num_components;
  2416. if (pad_fragment_output)
  2417. {
  2418. uint32_t locn = get_decoration(var.self, DecorationLocation);
  2419. num_components = max<uint32_t>(num_components, get_target_components_for_fragment_location(locn));
  2420. }
  2421. // We have already declared an IO block member as m_location_N.
  2422. // Just emit an early-declared variable and fixup as needed.
  2423. // Arrays need to be unrolled here since each location might need a different number of components.
  2424. entry_func.add_local_variable(var.self);
  2425. vars_needing_early_declaration.push_back(var.self);
  2426. if (var.storage == StorageClassInput)
  2427. {
  2428. entry_func.fixup_hooks_in.push_back([=, &type, &var]() {
  2429. if (!type.array.empty())
  2430. {
  2431. uint32_t array_size = to_array_size_literal(type);
  2432. for (uint32_t loc_off = 0; loc_off < array_size; loc_off++)
  2433. {
  2434. statement(to_name(var.self), "[", loc_off, "]", " = ", ib_var_ref,
  2435. ".m_location_", location + loc_off,
  2436. vector_swizzle(type_components, start_component), ";");
  2437. }
  2438. }
  2439. else
  2440. {
  2441. statement(to_name(var.self), " = ", ib_var_ref, ".m_location_", location,
  2442. vector_swizzle(type_components, start_component), ";");
  2443. }
  2444. });
  2445. }
  2446. else
  2447. {
  2448. entry_func.fixup_hooks_out.push_back([=, &type, &var]() {
  2449. if (!type.array.empty())
  2450. {
  2451. uint32_t array_size = to_array_size_literal(type);
  2452. for (uint32_t loc_off = 0; loc_off < array_size; loc_off++)
  2453. {
  2454. statement(ib_var_ref, ".m_location_", location + loc_off,
  2455. vector_swizzle(type_components, start_component), " = ",
  2456. to_name(var.self), "[", loc_off, "];");
  2457. }
  2458. }
  2459. else
  2460. {
  2461. statement(ib_var_ref, ".m_location_", location,
  2462. vector_swizzle(type_components, start_component), " = ", to_name(var.self), ";");
  2463. }
  2464. });
  2465. }
  2466. return true;
  2467. }
  2468. else
  2469. return false;
  2470. }
  2471. void CompilerMSL::add_plain_variable_to_interface_block(StorageClass storage, const string &ib_var_ref,
  2472. SPIRType &ib_type, SPIRVariable &var, InterfaceBlockMeta &meta)
  2473. {
  2474. bool is_builtin = is_builtin_variable(var);
  2475. BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
  2476. bool is_flat = has_decoration(var.self, DecorationFlat);
  2477. bool is_noperspective = has_decoration(var.self, DecorationNoPerspective);
  2478. bool is_centroid = has_decoration(var.self, DecorationCentroid);
  2479. bool is_sample = has_decoration(var.self, DecorationSample);
  2480. // Add a reference to the variable type to the interface struct.
  2481. uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
  2482. uint32_t type_id = ensure_correct_builtin_type(var.basetype, builtin);
  2483. var.basetype = type_id;
  2484. type_id = get_pointee_type_id(var.basetype);
  2485. if (meta.strip_array && is_array(get<SPIRType>(type_id)))
  2486. type_id = get<SPIRType>(type_id).parent_type;
  2487. auto &type = get<SPIRType>(type_id);
  2488. uint32_t target_components = 0;
  2489. uint32_t type_components = type.vecsize;
  2490. bool padded_output = false;
  2491. bool padded_input = false;
  2492. uint32_t start_component = 0;
  2493. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  2494. if (add_component_variable_to_interface_block(storage, ib_var_ref, var, type, meta))
  2495. return;
  2496. bool pad_fragment_output = has_decoration(var.self, DecorationLocation) &&
  2497. msl_options.pad_fragment_output_components &&
  2498. get_entry_point().model == ExecutionModelFragment && storage == StorageClassOutput;
  2499. if (pad_fragment_output)
  2500. {
  2501. uint32_t locn = get_decoration(var.self, DecorationLocation);
  2502. target_components = get_target_components_for_fragment_location(locn);
  2503. if (type_components < target_components)
  2504. {
  2505. // Make a new type here.
  2506. type_id = build_extended_vector_type(type_id, target_components);
  2507. padded_output = true;
  2508. }
  2509. }
  2510. if (storage == StorageClassInput && pull_model_inputs.count(var.self))
  2511. ib_type.member_types.push_back(build_msl_interpolant_type(type_id, is_noperspective));
  2512. else
  2513. ib_type.member_types.push_back(type_id);
  2514. // Give the member a name
  2515. string mbr_name = ensure_valid_name(to_expression(var.self), "m");
  2516. set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
  2517. // Update the original variable reference to include the structure reference
  2518. string qual_var_name = ib_var_ref + "." + mbr_name;
  2519. // If using pull-model interpolation, need to add a call to the correct interpolation method.
  2520. if (storage == StorageClassInput && pull_model_inputs.count(var.self))
  2521. {
  2522. if (is_centroid)
  2523. qual_var_name += ".interpolate_at_centroid()";
  2524. else if (is_sample)
  2525. qual_var_name += join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")");
  2526. else
  2527. qual_var_name += ".interpolate_at_center()";
  2528. }
  2529. if (padded_output || padded_input)
  2530. {
  2531. entry_func.add_local_variable(var.self);
  2532. vars_needing_early_declaration.push_back(var.self);
  2533. if (padded_output)
  2534. {
  2535. entry_func.fixup_hooks_out.push_back([=, &var]() {
  2536. statement(qual_var_name, vector_swizzle(type_components, start_component), " = ", to_name(var.self),
  2537. ";");
  2538. });
  2539. }
  2540. else
  2541. {
  2542. entry_func.fixup_hooks_in.push_back([=, &var]() {
  2543. statement(to_name(var.self), " = ", qual_var_name, vector_swizzle(type_components, start_component),
  2544. ";");
  2545. });
  2546. }
  2547. }
  2548. else if (!meta.strip_array)
  2549. ir.meta[var.self].decoration.qualified_alias = qual_var_name;
  2550. if (var.storage == StorageClassOutput && var.initializer != ID(0))
  2551. {
  2552. if (padded_output || padded_input)
  2553. {
  2554. entry_func.fixup_hooks_in.push_back(
  2555. [=, &var]() { statement(to_name(var.self), " = ", to_expression(var.initializer), ";"); });
  2556. }
  2557. else
  2558. {
  2559. if (meta.strip_array)
  2560. {
  2561. entry_func.fixup_hooks_in.push_back([=, &var]() {
  2562. uint32_t index = get_extended_decoration(var.self, SPIRVCrossDecorationInterfaceMemberIndex);
  2563. auto invocation = to_tesc_invocation_id();
  2564. statement(to_expression(stage_out_ptr_var_id), "[",
  2565. invocation, "].",
  2566. to_member_name(ib_type, index), " = ", to_expression(var.initializer), "[",
  2567. invocation, "];");
  2568. });
  2569. }
  2570. else
  2571. {
  2572. entry_func.fixup_hooks_in.push_back([=, &var]() {
  2573. statement(qual_var_name, " = ", to_expression(var.initializer), ";");
  2574. });
  2575. }
  2576. }
  2577. }
  2578. // Copy the variable location from the original variable to the member
  2579. if (get_decoration_bitset(var.self).get(DecorationLocation))
  2580. {
  2581. uint32_t locn = get_decoration(var.self, DecorationLocation);
  2582. uint32_t comp = get_decoration(var.self, DecorationComponent);
  2583. if (storage == StorageClassInput)
  2584. {
  2585. type_id = ensure_correct_input_type(var.basetype, locn, comp, 0, meta.strip_array);
  2586. var.basetype = type_id;
  2587. type_id = get_pointee_type_id(type_id);
  2588. if (meta.strip_array && is_array(get<SPIRType>(type_id)))
  2589. type_id = get<SPIRType>(type_id).parent_type;
  2590. if (pull_model_inputs.count(var.self))
  2591. ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(type_id, is_noperspective);
  2592. else
  2593. ib_type.member_types[ib_mbr_idx] = type_id;
  2594. }
  2595. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
  2596. if (comp)
  2597. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, comp);
  2598. mark_location_as_used_by_shader(locn, get<SPIRType>(type_id), storage);
  2599. }
  2600. else if (is_builtin && is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin))
  2601. {
  2602. uint32_t locn = inputs_by_builtin[builtin].location;
  2603. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
  2604. mark_location_as_used_by_shader(locn, type, storage);
  2605. }
  2606. else if (is_builtin && capture_output_to_buffer && storage == StorageClassOutput && outputs_by_builtin.count(builtin))
  2607. {
  2608. uint32_t locn = outputs_by_builtin[builtin].location;
  2609. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
  2610. mark_location_as_used_by_shader(locn, type, storage);
  2611. }
  2612. if (get_decoration_bitset(var.self).get(DecorationComponent))
  2613. {
  2614. uint32_t component = get_decoration(var.self, DecorationComponent);
  2615. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, component);
  2616. }
  2617. if (get_decoration_bitset(var.self).get(DecorationIndex))
  2618. {
  2619. uint32_t index = get_decoration(var.self, DecorationIndex);
  2620. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, index);
  2621. }
  2622. // Mark the member as builtin if needed
  2623. if (is_builtin)
  2624. {
  2625. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
  2626. if (builtin == BuiltInPosition && storage == StorageClassOutput)
  2627. qual_pos_var_name = qual_var_name;
  2628. }
  2629. // Copy interpolation decorations if needed
  2630. if (storage != StorageClassInput || !pull_model_inputs.count(var.self))
  2631. {
  2632. if (is_flat)
  2633. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat);
  2634. if (is_noperspective)
  2635. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective);
  2636. if (is_centroid)
  2637. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid);
  2638. if (is_sample)
  2639. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample);
  2640. }
  2641. set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self);
  2642. }
  2643. void CompilerMSL::add_composite_variable_to_interface_block(StorageClass storage, const string &ib_var_ref,
  2644. SPIRType &ib_type, SPIRVariable &var,
  2645. InterfaceBlockMeta &meta)
  2646. {
  2647. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  2648. auto &var_type = meta.strip_array ? get_variable_element_type(var) : get_variable_data_type(var);
  2649. uint32_t elem_cnt = 0;
  2650. if (add_component_variable_to_interface_block(storage, ib_var_ref, var, var_type, meta))
  2651. return;
  2652. if (is_matrix(var_type))
  2653. {
  2654. if (is_array(var_type))
  2655. SPIRV_CROSS_THROW("MSL cannot emit arrays-of-matrices in input and output variables.");
  2656. elem_cnt = var_type.columns;
  2657. }
  2658. else if (is_array(var_type))
  2659. {
  2660. if (var_type.array.size() != 1)
  2661. SPIRV_CROSS_THROW("MSL cannot emit arrays-of-arrays in input and output variables.");
  2662. elem_cnt = to_array_size_literal(var_type);
  2663. }
  2664. bool is_builtin = is_builtin_variable(var);
  2665. BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
  2666. bool is_flat = has_decoration(var.self, DecorationFlat);
  2667. bool is_noperspective = has_decoration(var.self, DecorationNoPerspective);
  2668. bool is_centroid = has_decoration(var.self, DecorationCentroid);
  2669. bool is_sample = has_decoration(var.self, DecorationSample);
  2670. auto *usable_type = &var_type;
  2671. if (usable_type->pointer)
  2672. usable_type = &get<SPIRType>(usable_type->parent_type);
  2673. while (is_array(*usable_type) || is_matrix(*usable_type))
  2674. usable_type = &get<SPIRType>(usable_type->parent_type);
  2675. // If a builtin, force it to have the proper name.
  2676. if (is_builtin)
  2677. set_name(var.self, builtin_to_glsl(builtin, StorageClassFunction));
  2678. bool flatten_from_ib_var = false;
  2679. string flatten_from_ib_mbr_name;
  2680. if (storage == StorageClassOutput && is_builtin && builtin == BuiltInClipDistance)
  2681. {
  2682. // Also declare [[clip_distance]] attribute here.
  2683. uint32_t clip_array_mbr_idx = uint32_t(ib_type.member_types.size());
  2684. ib_type.member_types.push_back(get_variable_data_type_id(var));
  2685. set_member_decoration(ib_type.self, clip_array_mbr_idx, DecorationBuiltIn, BuiltInClipDistance);
  2686. flatten_from_ib_mbr_name = builtin_to_glsl(BuiltInClipDistance, StorageClassOutput);
  2687. set_member_name(ib_type.self, clip_array_mbr_idx, flatten_from_ib_mbr_name);
  2688. // When we flatten, we flatten directly from the "out" struct,
  2689. // not from a function variable.
  2690. flatten_from_ib_var = true;
  2691. if (!msl_options.enable_clip_distance_user_varying)
  2692. return;
  2693. }
  2694. else if (!meta.strip_array)
  2695. {
  2696. // Only flatten/unflatten IO composites for non-tessellation cases where arrays are not stripped.
  2697. entry_func.add_local_variable(var.self);
  2698. // We need to declare the variable early and at entry-point scope.
  2699. vars_needing_early_declaration.push_back(var.self);
  2700. }
  2701. for (uint32_t i = 0; i < elem_cnt; i++)
  2702. {
  2703. // Add a reference to the variable type to the interface struct.
  2704. uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
  2705. uint32_t target_components = 0;
  2706. bool padded_output = false;
  2707. uint32_t type_id = usable_type->self;
  2708. // Check if we need to pad fragment output to match a certain number of components.
  2709. if (get_decoration_bitset(var.self).get(DecorationLocation) && msl_options.pad_fragment_output_components &&
  2710. get_entry_point().model == ExecutionModelFragment && storage == StorageClassOutput)
  2711. {
  2712. uint32_t locn = get_decoration(var.self, DecorationLocation) + i;
  2713. target_components = get_target_components_for_fragment_location(locn);
  2714. if (usable_type->vecsize < target_components)
  2715. {
  2716. // Make a new type here.
  2717. type_id = build_extended_vector_type(usable_type->self, target_components);
  2718. padded_output = true;
  2719. }
  2720. }
  2721. if (storage == StorageClassInput && pull_model_inputs.count(var.self))
  2722. ib_type.member_types.push_back(build_msl_interpolant_type(get_pointee_type_id(type_id), is_noperspective));
  2723. else
  2724. ib_type.member_types.push_back(get_pointee_type_id(type_id));
  2725. // Give the member a name
  2726. string mbr_name = ensure_valid_name(join(to_expression(var.self), "_", i), "m");
  2727. set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
  2728. // There is no qualified alias since we need to flatten the internal array on return.
  2729. if (get_decoration_bitset(var.self).get(DecorationLocation))
  2730. {
  2731. uint32_t locn = get_decoration(var.self, DecorationLocation) + i;
  2732. uint32_t comp = get_decoration(var.self, DecorationComponent);
  2733. if (storage == StorageClassInput)
  2734. {
  2735. var.basetype = ensure_correct_input_type(var.basetype, locn, comp, 0, meta.strip_array);
  2736. uint32_t mbr_type_id = ensure_correct_input_type(usable_type->self, locn, comp, 0, meta.strip_array);
  2737. if (storage == StorageClassInput && pull_model_inputs.count(var.self))
  2738. ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(mbr_type_id, is_noperspective);
  2739. else
  2740. ib_type.member_types[ib_mbr_idx] = mbr_type_id;
  2741. }
  2742. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
  2743. if (comp)
  2744. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, comp);
  2745. mark_location_as_used_by_shader(locn, *usable_type, storage);
  2746. }
  2747. else if (is_builtin && is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin))
  2748. {
  2749. uint32_t locn = inputs_by_builtin[builtin].location + i;
  2750. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
  2751. mark_location_as_used_by_shader(locn, *usable_type, storage);
  2752. }
  2753. else if (is_builtin && capture_output_to_buffer && storage == StorageClassOutput && outputs_by_builtin.count(builtin))
  2754. {
  2755. uint32_t locn = outputs_by_builtin[builtin].location + i;
  2756. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
  2757. mark_location_as_used_by_shader(locn, *usable_type, storage);
  2758. }
  2759. else if (is_builtin && (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance))
  2760. {
  2761. // Declare the Clip/CullDistance as [[user(clip/cullN)]].
  2762. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
  2763. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, i);
  2764. }
  2765. if (get_decoration_bitset(var.self).get(DecorationIndex))
  2766. {
  2767. uint32_t index = get_decoration(var.self, DecorationIndex);
  2768. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, index);
  2769. }
  2770. if (storage != StorageClassInput || !pull_model_inputs.count(var.self))
  2771. {
  2772. // Copy interpolation decorations if needed
  2773. if (is_flat)
  2774. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat);
  2775. if (is_noperspective)
  2776. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective);
  2777. if (is_centroid)
  2778. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid);
  2779. if (is_sample)
  2780. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample);
  2781. }
  2782. set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self);
  2783. // Only flatten/unflatten IO composites for non-tessellation cases where arrays are not stripped.
  2784. if (!meta.strip_array)
  2785. {
  2786. switch (storage)
  2787. {
  2788. case StorageClassInput:
  2789. entry_func.fixup_hooks_in.push_back([=, &var]() {
  2790. if (pull_model_inputs.count(var.self))
  2791. {
  2792. string lerp_call;
  2793. if (is_centroid)
  2794. lerp_call = ".interpolate_at_centroid()";
  2795. else if (is_sample)
  2796. lerp_call = join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")");
  2797. else
  2798. lerp_call = ".interpolate_at_center()";
  2799. statement(to_name(var.self), "[", i, "] = ", ib_var_ref, ".", mbr_name, lerp_call, ";");
  2800. }
  2801. else
  2802. {
  2803. statement(to_name(var.self), "[", i, "] = ", ib_var_ref, ".", mbr_name, ";");
  2804. }
  2805. });
  2806. break;
  2807. case StorageClassOutput:
  2808. entry_func.fixup_hooks_out.push_back([=, &var]() {
  2809. if (padded_output)
  2810. {
  2811. auto &padded_type = this->get<SPIRType>(type_id);
  2812. statement(
  2813. ib_var_ref, ".", mbr_name, " = ",
  2814. remap_swizzle(padded_type, usable_type->vecsize, join(to_name(var.self), "[", i, "]")),
  2815. ";");
  2816. }
  2817. else if (flatten_from_ib_var)
  2818. statement(ib_var_ref, ".", mbr_name, " = ", ib_var_ref, ".", flatten_from_ib_mbr_name, "[", i,
  2819. "];");
  2820. else
  2821. statement(ib_var_ref, ".", mbr_name, " = ", to_name(var.self), "[", i, "];");
  2822. });
  2823. break;
  2824. default:
  2825. break;
  2826. }
  2827. }
  2828. }
  2829. }
  2830. void CompilerMSL::add_composite_member_variable_to_interface_block(StorageClass storage,
  2831. const string &ib_var_ref, SPIRType &ib_type,
  2832. SPIRVariable &var, SPIRType &var_type,
  2833. uint32_t mbr_idx, InterfaceBlockMeta &meta,
  2834. const string &mbr_name_qual,
  2835. const string &var_chain_qual,
  2836. uint32_t &location, uint32_t &var_mbr_idx,
  2837. const Bitset &interpolation_qual)
  2838. {
  2839. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  2840. BuiltIn builtin = BuiltInMax;
  2841. bool is_builtin = is_member_builtin(var_type, mbr_idx, &builtin);
  2842. bool is_flat = interpolation_qual.get(DecorationFlat) ||
  2843. has_member_decoration(var_type.self, mbr_idx, DecorationFlat) ||
  2844. has_decoration(var.self, DecorationFlat);
  2845. bool is_noperspective = interpolation_qual.get(DecorationNoPerspective) ||
  2846. has_member_decoration(var_type.self, mbr_idx, DecorationNoPerspective) ||
  2847. has_decoration(var.self, DecorationNoPerspective);
  2848. bool is_centroid = interpolation_qual.get(DecorationCentroid) ||
  2849. has_member_decoration(var_type.self, mbr_idx, DecorationCentroid) ||
  2850. has_decoration(var.self, DecorationCentroid);
  2851. bool is_sample = interpolation_qual.get(DecorationSample) ||
  2852. has_member_decoration(var_type.self, mbr_idx, DecorationSample) ||
  2853. has_decoration(var.self, DecorationSample);
  2854. Bitset inherited_qual;
  2855. if (is_flat)
  2856. inherited_qual.set(DecorationFlat);
  2857. if (is_noperspective)
  2858. inherited_qual.set(DecorationNoPerspective);
  2859. if (is_centroid)
  2860. inherited_qual.set(DecorationCentroid);
  2861. if (is_sample)
  2862. inherited_qual.set(DecorationSample);
  2863. uint32_t mbr_type_id = var_type.member_types[mbr_idx];
  2864. auto &mbr_type = get<SPIRType>(mbr_type_id);
  2865. bool mbr_is_indexable = false;
  2866. uint32_t elem_cnt = 1;
  2867. if (is_matrix(mbr_type))
  2868. {
  2869. if (is_array(mbr_type))
  2870. SPIRV_CROSS_THROW("MSL cannot emit arrays-of-matrices in input and output variables.");
  2871. mbr_is_indexable = true;
  2872. elem_cnt = mbr_type.columns;
  2873. }
  2874. else if (is_array(mbr_type))
  2875. {
  2876. if (mbr_type.array.size() != 1)
  2877. SPIRV_CROSS_THROW("MSL cannot emit arrays-of-arrays in input and output variables.");
  2878. mbr_is_indexable = true;
  2879. elem_cnt = to_array_size_literal(mbr_type);
  2880. }
  2881. auto *usable_type = &mbr_type;
  2882. if (usable_type->pointer)
  2883. usable_type = &get<SPIRType>(usable_type->parent_type);
  2884. while (is_array(*usable_type) || is_matrix(*usable_type))
  2885. usable_type = &get<SPIRType>(usable_type->parent_type);
  2886. bool flatten_from_ib_var = false;
  2887. string flatten_from_ib_mbr_name;
  2888. if (storage == StorageClassOutput && is_builtin && builtin == BuiltInClipDistance)
  2889. {
  2890. // Also declare [[clip_distance]] attribute here.
  2891. uint32_t clip_array_mbr_idx = uint32_t(ib_type.member_types.size());
  2892. ib_type.member_types.push_back(mbr_type_id);
  2893. set_member_decoration(ib_type.self, clip_array_mbr_idx, DecorationBuiltIn, BuiltInClipDistance);
  2894. flatten_from_ib_mbr_name = builtin_to_glsl(BuiltInClipDistance, StorageClassOutput);
  2895. set_member_name(ib_type.self, clip_array_mbr_idx, flatten_from_ib_mbr_name);
  2896. // When we flatten, we flatten directly from the "out" struct,
  2897. // not from a function variable.
  2898. flatten_from_ib_var = true;
  2899. if (!msl_options.enable_clip_distance_user_varying)
  2900. return;
  2901. }
  2902. // Recursively handle nested structures.
  2903. if (mbr_type.basetype == SPIRType::Struct)
  2904. {
  2905. for (uint32_t i = 0; i < elem_cnt; i++)
  2906. {
  2907. string mbr_name = append_member_name(mbr_name_qual, var_type, mbr_idx) + (mbr_is_indexable ? join("_", i) : "");
  2908. string var_chain = join(var_chain_qual, ".", to_member_name(var_type, mbr_idx), (mbr_is_indexable ? join("[", i, "]") : ""));
  2909. uint32_t sub_mbr_cnt = uint32_t(mbr_type.member_types.size());
  2910. for (uint32_t sub_mbr_idx = 0; sub_mbr_idx < sub_mbr_cnt; sub_mbr_idx++)
  2911. {
  2912. add_composite_member_variable_to_interface_block(storage, ib_var_ref, ib_type,
  2913. var, mbr_type, sub_mbr_idx,
  2914. meta, mbr_name, var_chain,
  2915. location, var_mbr_idx, inherited_qual);
  2916. // FIXME: Recursive structs and tessellation breaks here.
  2917. var_mbr_idx++;
  2918. }
  2919. }
  2920. return;
  2921. }
  2922. for (uint32_t i = 0; i < elem_cnt; i++)
  2923. {
  2924. // Add a reference to the variable type to the interface struct.
  2925. uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
  2926. if (storage == StorageClassInput && pull_model_inputs.count(var.self))
  2927. ib_type.member_types.push_back(build_msl_interpolant_type(usable_type->self, is_noperspective));
  2928. else
  2929. ib_type.member_types.push_back(usable_type->self);
  2930. // Give the member a name
  2931. string mbr_name = ensure_valid_name(append_member_name(mbr_name_qual, var_type, mbr_idx) + (mbr_is_indexable ? join("_", i) : ""), "m");
  2932. set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
  2933. // The SPIRV location of interface variable, used to obtain the initial
  2934. // MSL location (the location variable) and interface matching
  2935. uint32_t ir_location = UINT32_MAX;
  2936. bool has_member_loc_decor = has_member_decoration(var_type.self, mbr_idx, DecorationLocation);
  2937. bool has_var_loc_decor = has_decoration(var.self, DecorationLocation);
  2938. uint32_t orig_vecsize = UINT32_MAX;
  2939. // If we haven't established a location base yet, do so here.
  2940. if (location == UINT32_MAX)
  2941. {
  2942. if (has_member_loc_decor)
  2943. ir_location = get_member_decoration(var_type.self, mbr_idx, DecorationLocation);
  2944. else if (has_var_loc_decor)
  2945. ir_location = get_accumulated_member_location(var, mbr_idx, meta.strip_array);
  2946. else if (is_builtin)
  2947. {
  2948. if (is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin))
  2949. ir_location = inputs_by_builtin[builtin].location;
  2950. else if (capture_output_to_buffer && storage == StorageClassOutput && outputs_by_builtin.count(builtin))
  2951. ir_location = outputs_by_builtin[builtin].location;
  2952. }
  2953. }
  2954. // Once we determine the location of the first member within nested structures,
  2955. // from a var of the topmost structure, the remaining flattened members of
  2956. // the nested structures will have consecutive location values. At this point,
  2957. // we've recursively tunnelled into structs, arrays, and matrices, and are
  2958. // down to a single location for each member now.
  2959. if (location == UINT32_MAX && ir_location != UINT32_MAX)
  2960. location = ir_location + i;
  2961. if (storage == StorageClassInput && (has_member_loc_decor || has_var_loc_decor))
  2962. {
  2963. uint32_t component = 0;
  2964. uint32_t orig_mbr_type_id = usable_type->self;
  2965. if (has_member_loc_decor)
  2966. component = get_member_decoration(var_type.self, mbr_idx, DecorationComponent);
  2967. var.basetype = ensure_correct_input_type(var.basetype, location, component, 0, meta.strip_array);
  2968. mbr_type_id = ensure_correct_input_type(usable_type->self, location, component, 0, meta.strip_array);
  2969. // For members of the composite interface block, we only change the interface block type
  2970. // when interface matching happens. In the meantime, we store the original vector size
  2971. // and insert a swizzle when loading from metal interface block (see fixup below)
  2972. if (mbr_type_id != orig_mbr_type_id)
  2973. orig_vecsize = get<SPIRType>(orig_mbr_type_id).vecsize;
  2974. if (storage == StorageClassInput && pull_model_inputs.count(var.self))
  2975. ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(mbr_type_id, is_noperspective);
  2976. else
  2977. ib_type.member_types[ib_mbr_idx] = mbr_type_id;
  2978. }
  2979. if ((!is_builtin && location != UINT32_MAX) || (is_builtin && ir_location != UINT32_MAX))
  2980. {
  2981. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, location);
  2982. mark_location_as_used_by_shader(location, *usable_type, storage);
  2983. location++;
  2984. }
  2985. else if (is_builtin && (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance))
  2986. {
  2987. // Declare the Clip/CullDistance as [[user(clip/cullN)]].
  2988. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
  2989. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, i);
  2990. }
  2991. if (has_member_decoration(var_type.self, mbr_idx, DecorationComponent))
  2992. SPIRV_CROSS_THROW("DecorationComponent on matrices and arrays is not supported.");
  2993. if (storage != StorageClassInput || !pull_model_inputs.count(var.self))
  2994. {
  2995. // Copy interpolation decorations if needed
  2996. if (is_flat)
  2997. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat);
  2998. if (is_noperspective)
  2999. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective);
  3000. if (is_centroid)
  3001. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid);
  3002. if (is_sample)
  3003. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample);
  3004. }
  3005. set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self);
  3006. set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex, var_mbr_idx);
  3007. // Unflatten or flatten from [[stage_in]] or [[stage_out]] as appropriate.
  3008. if (!meta.strip_array && meta.allow_local_declaration)
  3009. {
  3010. string var_chain = join(var_chain_qual, ".", to_member_name(var_type, mbr_idx), (mbr_is_indexable ? join("[", i, "]") : ""));
  3011. switch (storage)
  3012. {
  3013. case StorageClassInput:
  3014. entry_func.fixup_hooks_in.push_back([=, &var]() {
  3015. string lerp_call;
  3016. string swizzle;
  3017. if (pull_model_inputs.count(var.self))
  3018. {
  3019. if (is_centroid)
  3020. lerp_call = ".interpolate_at_centroid()";
  3021. else if (is_sample)
  3022. lerp_call = join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")");
  3023. else
  3024. lerp_call = ".interpolate_at_center()";
  3025. }
  3026. if (orig_vecsize != UINT32_MAX)
  3027. swizzle = vector_swizzle(orig_vecsize, 0);
  3028. statement(var_chain, " = ", ib_var_ref, ".", mbr_name, lerp_call, swizzle, ";");
  3029. });
  3030. break;
  3031. case StorageClassOutput:
  3032. entry_func.fixup_hooks_out.push_back([=]() {
  3033. if (flatten_from_ib_var)
  3034. statement(ib_var_ref, ".", mbr_name, " = ", ib_var_ref, ".", flatten_from_ib_mbr_name, "[", i, "];");
  3035. else
  3036. statement(ib_var_ref, ".", mbr_name, " = ", var_chain, ";");
  3037. });
  3038. break;
  3039. default:
  3040. break;
  3041. }
  3042. }
  3043. }
  3044. }
  3045. void CompilerMSL::add_plain_member_variable_to_interface_block(StorageClass storage,
  3046. const string &ib_var_ref, SPIRType &ib_type,
  3047. SPIRVariable &var, SPIRType &var_type,
  3048. uint32_t mbr_idx, InterfaceBlockMeta &meta,
  3049. const string &mbr_name_qual,
  3050. const string &var_chain_qual,
  3051. uint32_t &location, uint32_t &var_mbr_idx)
  3052. {
  3053. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  3054. BuiltIn builtin = BuiltInMax;
  3055. bool is_builtin = is_member_builtin(var_type, mbr_idx, &builtin);
  3056. bool is_flat =
  3057. has_member_decoration(var_type.self, mbr_idx, DecorationFlat) || has_decoration(var.self, DecorationFlat);
  3058. bool is_noperspective = has_member_decoration(var_type.self, mbr_idx, DecorationNoPerspective) ||
  3059. has_decoration(var.self, DecorationNoPerspective);
  3060. bool is_centroid = has_member_decoration(var_type.self, mbr_idx, DecorationCentroid) ||
  3061. has_decoration(var.self, DecorationCentroid);
  3062. bool is_sample =
  3063. has_member_decoration(var_type.self, mbr_idx, DecorationSample) || has_decoration(var.self, DecorationSample);
  3064. // Add a reference to the member to the interface struct.
  3065. uint32_t mbr_type_id = var_type.member_types[mbr_idx];
  3066. uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
  3067. mbr_type_id = ensure_correct_builtin_type(mbr_type_id, builtin);
  3068. var_type.member_types[mbr_idx] = mbr_type_id;
  3069. if (storage == StorageClassInput && pull_model_inputs.count(var.self))
  3070. ib_type.member_types.push_back(build_msl_interpolant_type(mbr_type_id, is_noperspective));
  3071. else
  3072. ib_type.member_types.push_back(mbr_type_id);
  3073. // Give the member a name
  3074. string mbr_name = ensure_valid_name(append_member_name(mbr_name_qual, var_type, mbr_idx), "m");
  3075. set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
  3076. // Update the original variable reference to include the structure reference
  3077. string qual_var_name = ib_var_ref + "." + mbr_name;
  3078. // If using pull-model interpolation, need to add a call to the correct interpolation method.
  3079. if (storage == StorageClassInput && pull_model_inputs.count(var.self))
  3080. {
  3081. if (is_centroid)
  3082. qual_var_name += ".interpolate_at_centroid()";
  3083. else if (is_sample)
  3084. qual_var_name += join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")");
  3085. else
  3086. qual_var_name += ".interpolate_at_center()";
  3087. }
  3088. // The SPIRV location of interface variable, used to obtain the initial
  3089. // MSL location (the location variable) and interface matching
  3090. uint32_t ir_location = UINT32_MAX;
  3091. bool has_member_loc_decor = has_member_decoration(var_type.self, mbr_idx, DecorationLocation);
  3092. bool has_var_loc_decor = has_decoration(var.self, DecorationLocation);
  3093. uint32_t orig_vecsize = UINT32_MAX;
  3094. if (has_member_loc_decor)
  3095. ir_location = get_member_decoration(var_type.self, mbr_idx, DecorationLocation);
  3096. else if (has_var_loc_decor)
  3097. ir_location = get_accumulated_member_location(var, mbr_idx, meta.strip_array);
  3098. else if (is_builtin)
  3099. {
  3100. if (is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin))
  3101. ir_location = inputs_by_builtin[builtin].location;
  3102. else if (capture_output_to_buffer && storage == StorageClassOutput && outputs_by_builtin.count(builtin))
  3103. ir_location = outputs_by_builtin[builtin].location;
  3104. }
  3105. // Once we determine the location of the first member within nested structures,
  3106. // from a var of the topmost structure, the remaining flattened members of
  3107. // the nested structures will have consecutive location values. At this point,
  3108. // we've recursively tunnelled into structs, arrays, and matrices, and are
  3109. // down to a single location for each member now.
  3110. if (location == UINT32_MAX && ir_location != UINT32_MAX)
  3111. location = ir_location;
  3112. if (storage == StorageClassInput && (has_member_loc_decor || has_var_loc_decor))
  3113. {
  3114. uint32_t component = 0;
  3115. uint32_t orig_mbr_type_id = mbr_type_id;
  3116. if (has_member_loc_decor)
  3117. component = get_member_decoration(var_type.self, mbr_idx, DecorationComponent);
  3118. mbr_type_id = ensure_correct_input_type(mbr_type_id, location, component, 0, meta.strip_array);
  3119. // For members of the composite interface block, we only change the interface block type
  3120. // when interface matching happens. In the meantime, we store the original vector size
  3121. // and insert a swizzle when loading from metal interface block (see fixup below)
  3122. if (mbr_type_id != orig_mbr_type_id)
  3123. orig_vecsize = get<SPIRType>(orig_mbr_type_id).vecsize;
  3124. if (storage == StorageClassInput && pull_model_inputs.count(var.self))
  3125. ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(mbr_type_id, is_noperspective);
  3126. else
  3127. ib_type.member_types[ib_mbr_idx] = mbr_type_id;
  3128. }
  3129. bool flatten_stage_out = false;
  3130. string var_chain = var_chain_qual + "." + to_member_name(var_type, mbr_idx);
  3131. if (is_builtin && !meta.strip_array)
  3132. {
  3133. // For the builtin gl_PerVertex, we cannot treat it as a block anyways,
  3134. // so redirect to qualified name.
  3135. set_member_qualified_name(var_type.self, mbr_idx, qual_var_name);
  3136. }
  3137. else if (!meta.strip_array && meta.allow_local_declaration)
  3138. {
  3139. // Unflatten or flatten from [[stage_in]] or [[stage_out]] as appropriate.
  3140. switch (storage)
  3141. {
  3142. case StorageClassInput:
  3143. entry_func.fixup_hooks_in.push_back([=]() {
  3144. string swizzle;
  3145. // Insert swizzle for widened interface block vector from interface matching
  3146. if (orig_vecsize != UINT32_MAX)
  3147. swizzle = vector_swizzle(orig_vecsize, 0);
  3148. statement(var_chain, " = ", qual_var_name, swizzle, ";");
  3149. });
  3150. break;
  3151. case StorageClassOutput:
  3152. flatten_stage_out = true;
  3153. entry_func.fixup_hooks_out.push_back([=]() {
  3154. statement(qual_var_name, " = ", var_chain, ";");
  3155. });
  3156. break;
  3157. default:
  3158. break;
  3159. }
  3160. }
  3161. if ((!is_builtin && location != UINT32_MAX) || (is_builtin && ir_location != UINT32_MAX))
  3162. {
  3163. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, location);
  3164. mark_location_as_used_by_shader(location, get<SPIRType>(mbr_type_id), storage);
  3165. location += type_to_location_count(get<SPIRType>(mbr_type_id));
  3166. }
  3167. // Copy the component location, if present.
  3168. if (has_member_decoration(var_type.self, mbr_idx, DecorationComponent))
  3169. {
  3170. uint32_t comp = get_member_decoration(var_type.self, mbr_idx, DecorationComponent);
  3171. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, comp);
  3172. }
  3173. // Mark the member as builtin if needed
  3174. if (is_builtin)
  3175. {
  3176. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
  3177. if (builtin == BuiltInPosition && storage == StorageClassOutput)
  3178. qual_pos_var_name = qual_var_name;
  3179. }
  3180. const SPIRConstant *c = nullptr;
  3181. if (!flatten_stage_out && var.storage == StorageClassOutput &&
  3182. var.initializer != ID(0) && (c = maybe_get<SPIRConstant>(var.initializer)))
  3183. {
  3184. if (meta.strip_array)
  3185. {
  3186. entry_func.fixup_hooks_in.push_back([=, &var]() {
  3187. auto &type = this->get<SPIRType>(var.basetype);
  3188. uint32_t index = get_extended_member_decoration(var.self, mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex);
  3189. auto invocation = to_tesc_invocation_id();
  3190. auto constant_chain = join(to_expression(var.initializer), "[", invocation, "]");
  3191. statement(to_expression(stage_out_ptr_var_id), "[",
  3192. invocation, "].",
  3193. to_member_name(ib_type, index), " = ",
  3194. constant_chain, ".", to_member_name(type, mbr_idx), ";");
  3195. });
  3196. }
  3197. else
  3198. {
  3199. entry_func.fixup_hooks_in.push_back([=]() {
  3200. statement(qual_var_name, " = ", constant_expression(
  3201. this->get<SPIRConstant>(c->subconstants[mbr_idx])), ";");
  3202. });
  3203. }
  3204. }
  3205. if (storage != StorageClassInput || !pull_model_inputs.count(var.self))
  3206. {
  3207. // Copy interpolation decorations if needed
  3208. if (is_flat)
  3209. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat);
  3210. if (is_noperspective)
  3211. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective);
  3212. if (is_centroid)
  3213. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid);
  3214. if (is_sample)
  3215. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample);
  3216. }
  3217. set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self);
  3218. set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex, var_mbr_idx);
  3219. }
  3220. // In Metal, the tessellation levels are stored as tightly packed half-precision floating point values.
  3221. // But, stage-in attribute offsets and strides must be multiples of four, so we can't pass the levels
  3222. // individually. Therefore, we must pass them as vectors. Triangles get a single float4, with the outer
  3223. // levels in 'xyz' and the inner level in 'w'. Quads get a float4 containing the outer levels and a
  3224. // float2 containing the inner levels.
  3225. void CompilerMSL::add_tess_level_input_to_interface_block(const std::string &ib_var_ref, SPIRType &ib_type,
  3226. SPIRVariable &var)
  3227. {
  3228. auto &var_type = get_variable_element_type(var);
  3229. BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
  3230. bool triangles = is_tessellating_triangles();
  3231. string mbr_name;
  3232. // Add a reference to the variable type to the interface struct.
  3233. uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
  3234. const auto mark_locations = [&](const SPIRType &new_var_type) {
  3235. if (get_decoration_bitset(var.self).get(DecorationLocation))
  3236. {
  3237. uint32_t locn = get_decoration(var.self, DecorationLocation);
  3238. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
  3239. mark_location_as_used_by_shader(locn, new_var_type, StorageClassInput);
  3240. }
  3241. else if (inputs_by_builtin.count(builtin))
  3242. {
  3243. uint32_t locn = inputs_by_builtin[builtin].location;
  3244. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
  3245. mark_location_as_used_by_shader(locn, new_var_type, StorageClassInput);
  3246. }
  3247. };
  3248. if (triangles)
  3249. {
  3250. // Triangles are tricky, because we want only one member in the struct.
  3251. mbr_name = "gl_TessLevel";
  3252. // If we already added the other one, we can skip this step.
  3253. if (!added_builtin_tess_level)
  3254. {
  3255. uint32_t type_id = build_extended_vector_type(var_type.self, 4);
  3256. ib_type.member_types.push_back(type_id);
  3257. // Give the member a name
  3258. set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
  3259. // We cannot decorate both, but the important part is that
  3260. // it's marked as builtin so we can get automatic attribute assignment if needed.
  3261. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
  3262. mark_locations(var_type);
  3263. added_builtin_tess_level = true;
  3264. }
  3265. }
  3266. else
  3267. {
  3268. mbr_name = builtin_to_glsl(builtin, StorageClassFunction);
  3269. uint32_t type_id = build_extended_vector_type(var_type.self, builtin == BuiltInTessLevelOuter ? 4 : 2);
  3270. uint32_t ptr_type_id = ir.increase_bound_by(1);
  3271. auto &new_var_type = set<SPIRType>(ptr_type_id, get<SPIRType>(type_id));
  3272. new_var_type.pointer = true;
  3273. new_var_type.pointer_depth++;
  3274. new_var_type.storage = StorageClassInput;
  3275. new_var_type.parent_type = type_id;
  3276. ib_type.member_types.push_back(type_id);
  3277. // Give the member a name
  3278. set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
  3279. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
  3280. mark_locations(new_var_type);
  3281. }
  3282. add_tess_level_input(ib_var_ref, mbr_name, var);
  3283. }
  3284. void CompilerMSL::add_tess_level_input(const std::string &base_ref, const std::string &mbr_name, SPIRVariable &var)
  3285. {
  3286. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  3287. BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
  3288. // Force the variable to have the proper name.
  3289. string var_name = builtin_to_glsl(builtin, StorageClassFunction);
  3290. set_name(var.self, var_name);
  3291. // We need to declare the variable early and at entry-point scope.
  3292. entry_func.add_local_variable(var.self);
  3293. vars_needing_early_declaration.push_back(var.self);
  3294. bool triangles = is_tessellating_triangles();
  3295. if (builtin == BuiltInTessLevelOuter)
  3296. {
  3297. entry_func.fixup_hooks_in.push_back(
  3298. [=]()
  3299. {
  3300. statement(var_name, "[0] = ", base_ref, ".", mbr_name, "[0];");
  3301. statement(var_name, "[1] = ", base_ref, ".", mbr_name, "[1];");
  3302. statement(var_name, "[2] = ", base_ref, ".", mbr_name, "[2];");
  3303. if (!triangles)
  3304. statement(var_name, "[3] = ", base_ref, ".", mbr_name, "[3];");
  3305. });
  3306. }
  3307. else
  3308. {
  3309. entry_func.fixup_hooks_in.push_back([=]() {
  3310. if (triangles)
  3311. {
  3312. if (msl_options.raw_buffer_tese_input)
  3313. statement(var_name, "[0] = ", base_ref, ".", mbr_name, ";");
  3314. else
  3315. statement(var_name, "[0] = ", base_ref, ".", mbr_name, "[3];");
  3316. }
  3317. else
  3318. {
  3319. statement(var_name, "[0] = ", base_ref, ".", mbr_name, "[0];");
  3320. statement(var_name, "[1] = ", base_ref, ".", mbr_name, "[1];");
  3321. }
  3322. });
  3323. }
  3324. }
  3325. bool CompilerMSL::variable_storage_requires_stage_io(StorageClass storage) const
  3326. {
  3327. if (storage == StorageClassOutput)
  3328. return !capture_output_to_buffer;
  3329. else if (storage == StorageClassInput)
  3330. return !(is_tesc_shader() && msl_options.multi_patch_workgroup) &&
  3331. !(is_tese_shader() && msl_options.raw_buffer_tese_input);
  3332. else
  3333. return false;
  3334. }
  3335. string CompilerMSL::to_tesc_invocation_id()
  3336. {
  3337. if (msl_options.multi_patch_workgroup)
  3338. {
  3339. // n.b. builtin_invocation_id_id here is the dispatch global invocation ID,
  3340. // not the TC invocation ID.
  3341. return join(to_expression(builtin_invocation_id_id), ".x % ", get_entry_point().output_vertices);
  3342. }
  3343. else
  3344. return builtin_to_glsl(BuiltInInvocationId, StorageClassInput);
  3345. }
  3346. void CompilerMSL::emit_local_masked_variable(const SPIRVariable &masked_var, bool strip_array)
  3347. {
  3348. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  3349. bool threadgroup_storage = variable_decl_is_remapped_storage(masked_var, StorageClassWorkgroup);
  3350. if (threadgroup_storage && msl_options.multi_patch_workgroup)
  3351. {
  3352. // We need one threadgroup block per patch, so fake this.
  3353. entry_func.fixup_hooks_in.push_back([this, &masked_var]() {
  3354. auto &type = get_variable_data_type(masked_var);
  3355. add_local_variable_name(masked_var.self);
  3356. const uint32_t max_control_points_per_patch = 32u;
  3357. uint32_t max_num_instances =
  3358. (max_control_points_per_patch + get_entry_point().output_vertices - 1u) /
  3359. get_entry_point().output_vertices;
  3360. statement("threadgroup ", type_to_glsl(type), " ",
  3361. "spvStorage", to_name(masked_var.self), "[", max_num_instances, "]",
  3362. type_to_array_glsl(type, 0), ";");
  3363. // Assign a threadgroup slice to each PrimitiveID.
  3364. // We assume here that workgroup size is rounded to 32,
  3365. // since that's the maximum number of control points per patch.
  3366. // We cannot size the array based on fixed dispatch parameters,
  3367. // since Metal does not allow that. :(
  3368. // FIXME: We will likely need an option to support passing down target workgroup size,
  3369. // so we can emit appropriate size here.
  3370. statement("threadgroup auto ",
  3371. "&", to_name(masked_var.self),
  3372. " = spvStorage", to_name(masked_var.self), "[",
  3373. "(", to_expression(builtin_invocation_id_id), ".x / ",
  3374. get_entry_point().output_vertices, ") % ",
  3375. max_num_instances, "];");
  3376. });
  3377. }
  3378. else
  3379. {
  3380. entry_func.add_local_variable(masked_var.self);
  3381. }
  3382. if (!threadgroup_storage)
  3383. {
  3384. vars_needing_early_declaration.push_back(masked_var.self);
  3385. }
  3386. else if (masked_var.initializer)
  3387. {
  3388. // Cannot directly initialize threadgroup variables. Need fixup hooks.
  3389. ID initializer = masked_var.initializer;
  3390. if (strip_array)
  3391. {
  3392. entry_func.fixup_hooks_in.push_back([this, &masked_var, initializer]() {
  3393. auto invocation = to_tesc_invocation_id();
  3394. statement(to_expression(masked_var.self), "[",
  3395. invocation, "] = ",
  3396. to_expression(initializer), "[",
  3397. invocation, "];");
  3398. });
  3399. }
  3400. else
  3401. {
  3402. entry_func.fixup_hooks_in.push_back([this, &masked_var, initializer]() {
  3403. statement(to_expression(masked_var.self), " = ", to_expression(initializer), ";");
  3404. });
  3405. }
  3406. }
  3407. }
  3408. void CompilerMSL::add_variable_to_interface_block(StorageClass storage, const string &ib_var_ref, SPIRType &ib_type,
  3409. SPIRVariable &var, InterfaceBlockMeta &meta)
  3410. {
  3411. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  3412. // Tessellation control I/O variables and tessellation evaluation per-point inputs are
  3413. // usually declared as arrays. In these cases, we want to add the element type to the
  3414. // interface block, since in Metal it's the interface block itself which is arrayed.
  3415. auto &var_type = meta.strip_array ? get_variable_element_type(var) : get_variable_data_type(var);
  3416. bool is_builtin = is_builtin_variable(var);
  3417. auto builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
  3418. bool is_block = has_decoration(var_type.self, DecorationBlock);
  3419. // If stage variables are masked out, emit them as plain variables instead.
  3420. // For builtins, we query them one by one later.
  3421. // IO blocks are not masked here, we need to mask them per-member instead.
  3422. if (storage == StorageClassOutput && is_stage_output_variable_masked(var))
  3423. {
  3424. // If we ignore an output, we must still emit it, since it might be used by app.
  3425. // Instead, just emit it as early declaration.
  3426. emit_local_masked_variable(var, meta.strip_array);
  3427. return;
  3428. }
  3429. // Tesselation stages pass I/O via buffer content which may contain nested structs.
  3430. // Ensure the vector sizes of any nested struct members within these input variables match
  3431. // the vector sizes of the corresponding output variables from the previous pipeline stage.
  3432. // This adjustment is handled here instead of ensure_correct_input_type() in order to
  3433. // perform the necessary recursive processing.
  3434. if (storage == StorageClassInput && var_type.basetype == SPIRType::Struct &&
  3435. ((is_tesc_shader() && msl_options.multi_patch_workgroup) ||
  3436. (is_tese_shader() && msl_options.raw_buffer_tese_input)) &&
  3437. has_decoration(var.self, DecorationLocation))
  3438. {
  3439. uint32_t locn = get_decoration(var.self, DecorationLocation);
  3440. ensure_struct_members_valid_vecsizes(get_variable_data_type(var), locn);
  3441. }
  3442. if (storage == StorageClassInput && has_decoration(var.self, DecorationPerVertexKHR))
  3443. SPIRV_CROSS_THROW("PerVertexKHR decoration is not supported in MSL.");
  3444. // If variable names alias, they will end up with wrong names in the interface struct, because
  3445. // there might be aliases in the member name cache and there would be a mismatch in fixup_in code.
  3446. // Make sure to register the variables as unique resource names ahead of time.
  3447. // This would normally conflict with the name cache when emitting local variables,
  3448. // but this happens in the setup stage, before we hit compilation loops.
  3449. // The name cache is cleared before we actually emit code, so this is safe.
  3450. add_resource_name(var.self);
  3451. if (var_type.basetype == SPIRType::Struct)
  3452. {
  3453. bool block_requires_flattening =
  3454. variable_storage_requires_stage_io(storage) || (is_block && var_type.array.empty());
  3455. bool needs_local_declaration = !is_builtin && block_requires_flattening && meta.allow_local_declaration;
  3456. if (needs_local_declaration)
  3457. {
  3458. // For I/O blocks or structs, we will need to pass the block itself around
  3459. // to functions if they are used globally in leaf functions.
  3460. // Rather than passing down member by member,
  3461. // we unflatten I/O blocks while running the shader,
  3462. // and pass the actual struct type down to leaf functions.
  3463. // We then unflatten inputs, and flatten outputs in the "fixup" stages.
  3464. emit_local_masked_variable(var, meta.strip_array);
  3465. }
  3466. if (!block_requires_flattening)
  3467. {
  3468. // In Metal tessellation shaders, the interface block itself is arrayed. This makes things
  3469. // very complicated, since stage-in structures in MSL don't support nested structures.
  3470. // Luckily, for stage-out when capturing output, we can avoid this and just add
  3471. // composite members directly, because the stage-out structure is stored to a buffer,
  3472. // not returned.
  3473. add_plain_variable_to_interface_block(storage, ib_var_ref, ib_type, var, meta);
  3474. }
  3475. else
  3476. {
  3477. bool masked_block = false;
  3478. uint32_t location = UINT32_MAX;
  3479. uint32_t var_mbr_idx = 0;
  3480. uint32_t elem_cnt = 1;
  3481. if (is_matrix(var_type))
  3482. {
  3483. if (is_array(var_type))
  3484. SPIRV_CROSS_THROW("MSL cannot emit arrays-of-matrices in input and output variables.");
  3485. elem_cnt = var_type.columns;
  3486. }
  3487. else if (is_array(var_type))
  3488. {
  3489. if (var_type.array.size() != 1)
  3490. SPIRV_CROSS_THROW("MSL cannot emit arrays-of-arrays in input and output variables.");
  3491. elem_cnt = to_array_size_literal(var_type);
  3492. }
  3493. for (uint32_t elem_idx = 0; elem_idx < elem_cnt; elem_idx++)
  3494. {
  3495. // Flatten the struct members into the interface struct
  3496. for (uint32_t mbr_idx = 0; mbr_idx < uint32_t(var_type.member_types.size()); mbr_idx++)
  3497. {
  3498. builtin = BuiltInMax;
  3499. is_builtin = is_member_builtin(var_type, mbr_idx, &builtin);
  3500. auto &mbr_type = get<SPIRType>(var_type.member_types[mbr_idx]);
  3501. if (storage == StorageClassOutput && is_stage_output_block_member_masked(var, mbr_idx, meta.strip_array))
  3502. {
  3503. location = UINT32_MAX; // Skip this member and resolve location again on next var member
  3504. if (is_block)
  3505. masked_block = true;
  3506. // Non-builtin block output variables are just ignored, since they will still access
  3507. // the block variable as-is. They're just not flattened.
  3508. if (is_builtin && !meta.strip_array)
  3509. {
  3510. // Emit a fake variable instead.
  3511. uint32_t ids = ir.increase_bound_by(2);
  3512. uint32_t ptr_type_id = ids + 0;
  3513. uint32_t var_id = ids + 1;
  3514. auto ptr_type = mbr_type;
  3515. ptr_type.pointer = true;
  3516. ptr_type.pointer_depth++;
  3517. ptr_type.parent_type = var_type.member_types[mbr_idx];
  3518. ptr_type.storage = StorageClassOutput;
  3519. uint32_t initializer = 0;
  3520. if (var.initializer)
  3521. if (auto *c = maybe_get<SPIRConstant>(var.initializer))
  3522. initializer = c->subconstants[mbr_idx];
  3523. set<SPIRType>(ptr_type_id, ptr_type);
  3524. set<SPIRVariable>(var_id, ptr_type_id, StorageClassOutput, initializer);
  3525. entry_func.add_local_variable(var_id);
  3526. vars_needing_early_declaration.push_back(var_id);
  3527. set_name(var_id, builtin_to_glsl(builtin, StorageClassOutput));
  3528. set_decoration(var_id, DecorationBuiltIn, builtin);
  3529. }
  3530. }
  3531. else if (!is_builtin || has_active_builtin(builtin, storage))
  3532. {
  3533. bool is_composite_type = is_matrix(mbr_type) || is_array(mbr_type) || mbr_type.basetype == SPIRType::Struct;
  3534. bool attribute_load_store =
  3535. storage == StorageClassInput && get_execution_model() != ExecutionModelFragment;
  3536. bool storage_is_stage_io = variable_storage_requires_stage_io(storage);
  3537. // Clip/CullDistance always need to be declared as user attributes.
  3538. if (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance)
  3539. is_builtin = false;
  3540. const string var_name = to_name(var.self);
  3541. string mbr_name_qual = var_name;
  3542. string var_chain_qual = var_name;
  3543. if (elem_cnt > 1)
  3544. {
  3545. mbr_name_qual += join("_", elem_idx);
  3546. var_chain_qual += join("[", elem_idx, "]");
  3547. }
  3548. if ((!is_builtin || attribute_load_store) && storage_is_stage_io && is_composite_type)
  3549. {
  3550. add_composite_member_variable_to_interface_block(storage, ib_var_ref, ib_type,
  3551. var, var_type, mbr_idx, meta,
  3552. mbr_name_qual, var_chain_qual,
  3553. location, var_mbr_idx, {});
  3554. }
  3555. else
  3556. {
  3557. add_plain_member_variable_to_interface_block(storage, ib_var_ref, ib_type,
  3558. var, var_type, mbr_idx, meta,
  3559. mbr_name_qual, var_chain_qual,
  3560. location, var_mbr_idx);
  3561. }
  3562. }
  3563. var_mbr_idx++;
  3564. }
  3565. }
  3566. // If we're redirecting a block, we might still need to access the original block
  3567. // variable if we're masking some members.
  3568. if (masked_block && !needs_local_declaration && (!is_builtin_variable(var) || is_tesc_shader()))
  3569. {
  3570. if (is_builtin_variable(var))
  3571. {
  3572. // Ensure correct names for the block members if we're actually going to
  3573. // declare gl_PerVertex.
  3574. for (uint32_t mbr_idx = 0; mbr_idx < uint32_t(var_type.member_types.size()); mbr_idx++)
  3575. {
  3576. set_member_name(var_type.self, mbr_idx, builtin_to_glsl(
  3577. BuiltIn(get_member_decoration(var_type.self, mbr_idx, DecorationBuiltIn)),
  3578. StorageClassOutput));
  3579. }
  3580. set_name(var_type.self, "gl_PerVertex");
  3581. set_name(var.self, "gl_out_masked");
  3582. stage_out_masked_builtin_type_id = var_type.self;
  3583. }
  3584. emit_local_masked_variable(var, meta.strip_array);
  3585. }
  3586. }
  3587. }
  3588. else if (is_tese_shader() && storage == StorageClassInput && !meta.strip_array && is_builtin &&
  3589. (builtin == BuiltInTessLevelOuter || builtin == BuiltInTessLevelInner))
  3590. {
  3591. add_tess_level_input_to_interface_block(ib_var_ref, ib_type, var);
  3592. }
  3593. else if (var_type.basetype == SPIRType::Boolean || var_type.basetype == SPIRType::Char ||
  3594. type_is_integral(var_type) || type_is_floating_point(var_type))
  3595. {
  3596. if (!is_builtin || has_active_builtin(builtin, storage))
  3597. {
  3598. bool is_composite_type = is_matrix(var_type) || is_array(var_type);
  3599. bool storage_is_stage_io = variable_storage_requires_stage_io(storage);
  3600. bool attribute_load_store = storage == StorageClassInput && get_execution_model() != ExecutionModelFragment;
  3601. // Clip/CullDistance always needs to be declared as user attributes.
  3602. if (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance)
  3603. is_builtin = false;
  3604. // MSL does not allow matrices or arrays in input or output variables, so need to handle it specially.
  3605. if ((!is_builtin || attribute_load_store) && storage_is_stage_io && is_composite_type)
  3606. {
  3607. add_composite_variable_to_interface_block(storage, ib_var_ref, ib_type, var, meta);
  3608. }
  3609. else
  3610. {
  3611. add_plain_variable_to_interface_block(storage, ib_var_ref, ib_type, var, meta);
  3612. }
  3613. }
  3614. }
  3615. }
  3616. // Recursively iterate into the input struct type, and adjust the vecsize
  3617. // of any nested members, based on location info provided through the API.
  3618. // The location parameter is modified recursively.
  3619. void CompilerMSL::ensure_struct_members_valid_vecsizes(SPIRType &struct_type, uint32_t &location)
  3620. {
  3621. assert(struct_type.basetype == SPIRType::Struct);
  3622. auto mbr_cnt = struct_type.member_types.size();
  3623. for (size_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
  3624. {
  3625. auto mbr_type_id = struct_type.member_types[mbr_idx];
  3626. auto &mbr_type = get<SPIRType>(mbr_type_id);
  3627. if (mbr_type.basetype == SPIRType::Struct)
  3628. ensure_struct_members_valid_vecsizes(mbr_type, location);
  3629. else
  3630. {
  3631. auto p_va = inputs_by_location.find({location, 0});
  3632. if (p_va != end(inputs_by_location) && p_va->second.vecsize > mbr_type.vecsize)
  3633. {
  3634. // Set a new member type into the struct type, and all its parent types.
  3635. auto new_mbr_type_id = build_extended_vector_type(mbr_type_id, p_va->second.vecsize);
  3636. for (auto *p_type = &struct_type; p_type; p_type = maybe_get<SPIRType>(p_type->parent_type))
  3637. p_type->member_types[mbr_idx] = new_mbr_type_id;
  3638. }
  3639. // Calc location of next member
  3640. uint32_t loc_cnt = mbr_type.columns;
  3641. auto dim_cnt = mbr_type.array.size();
  3642. for (uint32_t i = 0; i < dim_cnt; i++)
  3643. loc_cnt *= to_array_size_literal(mbr_type, i);
  3644. location += loc_cnt;
  3645. }
  3646. }
  3647. }
  3648. // Fix up the mapping of variables to interface member indices, which is used to compile access chains
  3649. // for per-vertex variables in a tessellation control shader.
  3650. void CompilerMSL::fix_up_interface_member_indices(StorageClass storage, uint32_t ib_type_id)
  3651. {
  3652. // Only needed for tessellation shaders and pull-model interpolants.
  3653. // Need to redirect interface indices back to variables themselves.
  3654. // For structs, each member of the struct need a separate instance.
  3655. if (!is_tesc_shader() && !(is_tese_shader() && storage == StorageClassInput) &&
  3656. !(get_execution_model() == ExecutionModelFragment && storage == StorageClassInput &&
  3657. !pull_model_inputs.empty()))
  3658. return;
  3659. auto mbr_cnt = uint32_t(ir.meta[ib_type_id].members.size());
  3660. for (uint32_t i = 0; i < mbr_cnt; i++)
  3661. {
  3662. uint32_t var_id = get_extended_member_decoration(ib_type_id, i, SPIRVCrossDecorationInterfaceOrigID);
  3663. if (!var_id)
  3664. continue;
  3665. auto &var = get<SPIRVariable>(var_id);
  3666. auto &type = get_variable_element_type(var);
  3667. bool flatten_composites = variable_storage_requires_stage_io(var.storage);
  3668. bool is_block = has_decoration(type.self, DecorationBlock);
  3669. uint32_t mbr_idx = uint32_t(-1);
  3670. if (type.basetype == SPIRType::Struct && (flatten_composites || is_block))
  3671. mbr_idx = get_extended_member_decoration(ib_type_id, i, SPIRVCrossDecorationInterfaceMemberIndex);
  3672. if (mbr_idx != uint32_t(-1))
  3673. {
  3674. // Only set the lowest InterfaceMemberIndex for each variable member.
  3675. // IB struct members will be emitted in-order w.r.t. interface member index.
  3676. if (!has_extended_member_decoration(var_id, mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex))
  3677. set_extended_member_decoration(var_id, mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex, i);
  3678. }
  3679. else
  3680. {
  3681. // Only set the lowest InterfaceMemberIndex for each variable.
  3682. // IB struct members will be emitted in-order w.r.t. interface member index.
  3683. if (!has_extended_decoration(var_id, SPIRVCrossDecorationInterfaceMemberIndex))
  3684. set_extended_decoration(var_id, SPIRVCrossDecorationInterfaceMemberIndex, i);
  3685. }
  3686. }
  3687. }
  3688. // Add an interface structure for the type of storage, which is either StorageClassInput or StorageClassOutput.
  3689. // Returns the ID of the newly added variable, or zero if no variable was added.
  3690. uint32_t CompilerMSL::add_interface_block(StorageClass storage, bool patch)
  3691. {
  3692. // Accumulate the variables that should appear in the interface struct.
  3693. SmallVector<SPIRVariable *> vars;
  3694. bool incl_builtins = storage == StorageClassOutput || is_tessellation_shader();
  3695. bool has_seen_barycentric = false;
  3696. InterfaceBlockMeta meta;
  3697. // Varying interfaces between stages which use "user()" attribute can be dealt with
  3698. // without explicit packing and unpacking of components. For any variables which link against the runtime
  3699. // in some way (vertex attributes, fragment output, etc), we'll need to deal with it somehow.
  3700. bool pack_components =
  3701. (storage == StorageClassInput && get_execution_model() == ExecutionModelVertex) ||
  3702. (storage == StorageClassOutput && get_execution_model() == ExecutionModelFragment) ||
  3703. (storage == StorageClassOutput && get_execution_model() == ExecutionModelVertex && capture_output_to_buffer);
  3704. ir.for_each_typed_id<SPIRVariable>([&](uint32_t var_id, SPIRVariable &var) {
  3705. if (var.storage != storage)
  3706. return;
  3707. auto &type = this->get<SPIRType>(var.basetype);
  3708. bool is_builtin = is_builtin_variable(var);
  3709. bool is_block = has_decoration(type.self, DecorationBlock);
  3710. auto bi_type = BuiltInMax;
  3711. bool builtin_is_gl_in_out = false;
  3712. if (is_builtin && !is_block)
  3713. {
  3714. bi_type = BuiltIn(get_decoration(var_id, DecorationBuiltIn));
  3715. builtin_is_gl_in_out = bi_type == BuiltInPosition || bi_type == BuiltInPointSize ||
  3716. bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance;
  3717. }
  3718. if (is_builtin && is_block)
  3719. builtin_is_gl_in_out = true;
  3720. uint32_t location = get_decoration(var_id, DecorationLocation);
  3721. bool builtin_is_stage_in_out = builtin_is_gl_in_out ||
  3722. bi_type == BuiltInLayer || bi_type == BuiltInViewportIndex ||
  3723. bi_type == BuiltInBaryCoordKHR || bi_type == BuiltInBaryCoordNoPerspKHR ||
  3724. bi_type == BuiltInFragDepth ||
  3725. bi_type == BuiltInFragStencilRefEXT || bi_type == BuiltInSampleMask;
  3726. // These builtins are part of the stage in/out structs.
  3727. bool is_interface_block_builtin =
  3728. builtin_is_stage_in_out || (is_tese_shader() && !msl_options.raw_buffer_tese_input &&
  3729. (bi_type == BuiltInTessLevelOuter || bi_type == BuiltInTessLevelInner));
  3730. bool is_active = interface_variable_exists_in_entry_point(var.self);
  3731. if (is_builtin && is_active)
  3732. {
  3733. // Only emit the builtin if it's active in this entry point. Interface variable list might lie.
  3734. if (is_block)
  3735. {
  3736. // If any builtin is active, the block is active.
  3737. uint32_t mbr_cnt = uint32_t(type.member_types.size());
  3738. for (uint32_t i = 0; !is_active && i < mbr_cnt; i++)
  3739. is_active = has_active_builtin(BuiltIn(get_member_decoration(type.self, i, DecorationBuiltIn)), storage);
  3740. }
  3741. else
  3742. {
  3743. is_active = has_active_builtin(bi_type, storage);
  3744. }
  3745. }
  3746. bool filter_patch_decoration = (has_decoration(var_id, DecorationPatch) || is_patch_block(type)) == patch;
  3747. bool hidden = is_hidden_variable(var, incl_builtins);
  3748. // ClipDistance is never hidden, we need to emulate it when used as an input.
  3749. if (bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance)
  3750. hidden = false;
  3751. // It's not enough to simply avoid marking fragment outputs if the pipeline won't
  3752. // accept them. We can't put them in the struct at all, or otherwise the compiler
  3753. // complains that the outputs weren't explicitly marked.
  3754. // Frag depth and stencil outputs are incompatible with explicit early fragment tests.
  3755. // In GLSL, depth and stencil outputs are just ignored when explicit early fragment tests are required.
  3756. // In Metal, it's a compilation error, so we need to exclude them from the output struct.
  3757. if (get_execution_model() == ExecutionModelFragment && storage == StorageClassOutput && !patch &&
  3758. ((is_builtin && ((bi_type == BuiltInFragDepth && (!msl_options.enable_frag_depth_builtin || uses_explicit_early_fragment_test())) ||
  3759. (bi_type == BuiltInFragStencilRefEXT && (!msl_options.enable_frag_stencil_ref_builtin || uses_explicit_early_fragment_test())))) ||
  3760. (!is_builtin && !(msl_options.enable_frag_output_mask & (1 << location)))))
  3761. {
  3762. hidden = true;
  3763. disabled_frag_outputs.push_back(var_id);
  3764. // If a builtin, force it to have the proper name, and mark it as not part of the output struct.
  3765. if (is_builtin)
  3766. {
  3767. set_name(var_id, builtin_to_glsl(bi_type, StorageClassFunction));
  3768. mask_stage_output_by_builtin(bi_type);
  3769. }
  3770. }
  3771. // Barycentric inputs must be emitted in stage-in, because they can have interpolation arguments.
  3772. if (is_active && (bi_type == BuiltInBaryCoordKHR || bi_type == BuiltInBaryCoordNoPerspKHR))
  3773. {
  3774. if (has_seen_barycentric)
  3775. SPIRV_CROSS_THROW("Cannot declare both BaryCoordNV and BaryCoordNoPerspNV in same shader in MSL.");
  3776. has_seen_barycentric = true;
  3777. hidden = false;
  3778. }
  3779. if (is_active && !hidden && type.pointer && filter_patch_decoration &&
  3780. (!is_builtin || is_interface_block_builtin))
  3781. {
  3782. vars.push_back(&var);
  3783. if (!is_builtin)
  3784. {
  3785. // Need to deal specially with DecorationComponent.
  3786. // Multiple variables can alias the same Location, and try to make sure each location is declared only once.
  3787. // We will swizzle data in and out to make this work.
  3788. // This is only relevant for vertex inputs and fragment outputs.
  3789. // Technically tessellation as well, but it is too complicated to support.
  3790. uint32_t component = get_decoration(var_id, DecorationComponent);
  3791. if (component != 0)
  3792. {
  3793. if (is_tessellation_shader())
  3794. SPIRV_CROSS_THROW("Component decoration is not supported in tessellation shaders.");
  3795. else if (pack_components)
  3796. {
  3797. uint32_t array_size = 1;
  3798. if (!type.array.empty())
  3799. array_size = to_array_size_literal(type);
  3800. for (uint32_t location_offset = 0; location_offset < array_size; location_offset++)
  3801. {
  3802. auto &location_meta = meta.location_meta[location + location_offset];
  3803. location_meta.num_components = max<uint32_t>(location_meta.num_components, component + type.vecsize);
  3804. // For variables sharing location, decorations and base type must match.
  3805. location_meta.base_type_id = type.self;
  3806. location_meta.flat = has_decoration(var.self, DecorationFlat);
  3807. location_meta.noperspective = has_decoration(var.self, DecorationNoPerspective);
  3808. location_meta.centroid = has_decoration(var.self, DecorationCentroid);
  3809. location_meta.sample = has_decoration(var.self, DecorationSample);
  3810. }
  3811. }
  3812. }
  3813. }
  3814. }
  3815. if (is_tese_shader() && msl_options.raw_buffer_tese_input && patch && storage == StorageClassInput &&
  3816. (bi_type == BuiltInTessLevelOuter || bi_type == BuiltInTessLevelInner))
  3817. {
  3818. // In this case, we won't add the builtin to the interface struct,
  3819. // but we still need the hook to run to populate the arrays.
  3820. string base_ref = join(tess_factor_buffer_var_name, "[", to_expression(builtin_primitive_id_id), "]");
  3821. const char *mbr_name =
  3822. bi_type == BuiltInTessLevelOuter ? "edgeTessellationFactor" : "insideTessellationFactor";
  3823. add_tess_level_input(base_ref, mbr_name, var);
  3824. if (inputs_by_builtin.count(bi_type))
  3825. {
  3826. uint32_t locn = inputs_by_builtin[bi_type].location;
  3827. mark_location_as_used_by_shader(locn, type, StorageClassInput);
  3828. }
  3829. }
  3830. });
  3831. // If no variables qualify, leave.
  3832. // For patch input in a tessellation evaluation shader, the per-vertex stage inputs
  3833. // are included in a special patch control point array.
  3834. if (vars.empty() &&
  3835. !(!msl_options.raw_buffer_tese_input && storage == StorageClassInput && patch && stage_in_var_id))
  3836. return 0;
  3837. // Add a new typed variable for this interface structure.
  3838. // The initializer expression is allocated here, but populated when the function
  3839. // declaraion is emitted, because it is cleared after each compilation pass.
  3840. uint32_t next_id = ir.increase_bound_by(3);
  3841. uint32_t ib_type_id = next_id++;
  3842. auto &ib_type = set<SPIRType>(ib_type_id, OpTypeStruct);
  3843. ib_type.basetype = SPIRType::Struct;
  3844. ib_type.storage = storage;
  3845. set_decoration(ib_type_id, DecorationBlock);
  3846. uint32_t ib_var_id = next_id++;
  3847. auto &var = set<SPIRVariable>(ib_var_id, ib_type_id, storage, 0);
  3848. var.initializer = next_id++;
  3849. string ib_var_ref;
  3850. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  3851. switch (storage)
  3852. {
  3853. case StorageClassInput:
  3854. ib_var_ref = patch ? patch_stage_in_var_name : stage_in_var_name;
  3855. switch (get_execution_model())
  3856. {
  3857. case ExecutionModelTessellationControl:
  3858. // Add a hook to populate the shared workgroup memory containing the gl_in array.
  3859. entry_func.fixup_hooks_in.push_back([=]() {
  3860. // Can't use PatchVertices, PrimitiveId, or InvocationId yet; the hooks for those may not have run yet.
  3861. if (msl_options.multi_patch_workgroup)
  3862. {
  3863. // n.b. builtin_invocation_id_id here is the dispatch global invocation ID,
  3864. // not the TC invocation ID.
  3865. statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "* gl_in = &",
  3866. input_buffer_var_name, "[min(", to_expression(builtin_invocation_id_id), ".x / ",
  3867. get_entry_point().output_vertices,
  3868. ", spvIndirectParams[1] - 1) * spvIndirectParams[0]];");
  3869. }
  3870. else
  3871. {
  3872. // It's safe to use InvocationId here because it's directly mapped to a
  3873. // Metal builtin, and therefore doesn't need a hook.
  3874. statement("if (", to_expression(builtin_invocation_id_id), " < spvIndirectParams[0])");
  3875. statement(" ", input_wg_var_name, "[", to_expression(builtin_invocation_id_id),
  3876. "] = ", ib_var_ref, ";");
  3877. statement("threadgroup_barrier(mem_flags::mem_threadgroup);");
  3878. statement("if (", to_expression(builtin_invocation_id_id),
  3879. " >= ", get_entry_point().output_vertices, ")");
  3880. statement(" return;");
  3881. }
  3882. });
  3883. break;
  3884. case ExecutionModelTessellationEvaluation:
  3885. if (!msl_options.raw_buffer_tese_input)
  3886. break;
  3887. if (patch)
  3888. {
  3889. entry_func.fixup_hooks_in.push_back(
  3890. [=]()
  3891. {
  3892. statement("const device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref,
  3893. " = ", patch_input_buffer_var_name, "[", to_expression(builtin_primitive_id_id),
  3894. "];");
  3895. });
  3896. }
  3897. else
  3898. {
  3899. entry_func.fixup_hooks_in.push_back(
  3900. [=]()
  3901. {
  3902. statement("const device ", to_name(ir.default_entry_point), "_", ib_var_ref, "* gl_in = &",
  3903. input_buffer_var_name, "[", to_expression(builtin_primitive_id_id), " * ",
  3904. get_entry_point().output_vertices, "];");
  3905. });
  3906. }
  3907. break;
  3908. default:
  3909. break;
  3910. }
  3911. break;
  3912. case StorageClassOutput:
  3913. {
  3914. ib_var_ref = patch ? patch_stage_out_var_name : stage_out_var_name;
  3915. // Add the output interface struct as a local variable to the entry function.
  3916. // If the entry point should return the output struct, set the entry function
  3917. // to return the output interface struct, otherwise to return nothing.
  3918. // Watch out for the rare case where the terminator of the last entry point block is a
  3919. // Kill or Unreachable, instead of a Return. Based on SPIR-V's block-domination rules,
  3920. // we assume that any block that has a Kill will also have a terminating Return, except
  3921. // the last block.
  3922. // Indicate the output var requires early initialization.
  3923. bool ep_should_return_output = !get_is_rasterization_disabled();
  3924. uint32_t rtn_id = ep_should_return_output ? ib_var_id : 0;
  3925. if (!capture_output_to_buffer)
  3926. {
  3927. entry_func.add_local_variable(ib_var_id);
  3928. for (auto &blk_id : entry_func.blocks)
  3929. {
  3930. auto &blk = get<SPIRBlock>(blk_id);
  3931. auto last_blk_return = blk.terminator == SPIRBlock::Kill || blk.terminator == SPIRBlock::Unreachable;
  3932. if (blk.terminator == SPIRBlock::Return || (last_blk_return && blk_id == entry_func.blocks.back()))
  3933. blk.return_value = rtn_id;
  3934. }
  3935. vars_needing_early_declaration.push_back(ib_var_id);
  3936. }
  3937. else
  3938. {
  3939. switch (get_execution_model())
  3940. {
  3941. case ExecutionModelVertex:
  3942. case ExecutionModelTessellationEvaluation:
  3943. // Instead of declaring a struct variable to hold the output and then
  3944. // copying that to the output buffer, we'll declare the output variable
  3945. // as a reference to the final output element in the buffer. Then we can
  3946. // avoid the extra copy.
  3947. entry_func.fixup_hooks_in.push_back([=]() {
  3948. if (stage_out_var_id)
  3949. {
  3950. // The first member of the indirect buffer is always the number of vertices
  3951. // to draw.
  3952. // We zero-base the InstanceID & VertexID variables for HLSL emulation elsewhere, so don't do it twice
  3953. if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation)
  3954. {
  3955. statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref,
  3956. " = ", output_buffer_var_name, "[", to_expression(builtin_invocation_id_id),
  3957. ".y * ", to_expression(builtin_stage_input_size_id), ".x + ",
  3958. to_expression(builtin_invocation_id_id), ".x];");
  3959. }
  3960. else if (msl_options.enable_base_index_zero)
  3961. {
  3962. statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref,
  3963. " = ", output_buffer_var_name, "[", to_expression(builtin_instance_idx_id),
  3964. " * spvIndirectParams[0] + ", to_expression(builtin_vertex_idx_id), "];");
  3965. }
  3966. else
  3967. {
  3968. statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref,
  3969. " = ", output_buffer_var_name, "[(", to_expression(builtin_instance_idx_id),
  3970. " - ", to_expression(builtin_base_instance_id), ") * spvIndirectParams[0] + ",
  3971. to_expression(builtin_vertex_idx_id), " - ",
  3972. to_expression(builtin_base_vertex_id), "];");
  3973. }
  3974. }
  3975. });
  3976. break;
  3977. case ExecutionModelTessellationControl:
  3978. if (msl_options.multi_patch_workgroup)
  3979. {
  3980. // We cannot use PrimitiveId here, because the hook may not have run yet.
  3981. if (patch)
  3982. {
  3983. entry_func.fixup_hooks_in.push_back([=]() {
  3984. statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref,
  3985. " = ", patch_output_buffer_var_name, "[", to_expression(builtin_invocation_id_id),
  3986. ".x / ", get_entry_point().output_vertices, "];");
  3987. });
  3988. }
  3989. else
  3990. {
  3991. entry_func.fixup_hooks_in.push_back([=]() {
  3992. statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "* gl_out = &",
  3993. output_buffer_var_name, "[", to_expression(builtin_invocation_id_id), ".x - ",
  3994. to_expression(builtin_invocation_id_id), ".x % ",
  3995. get_entry_point().output_vertices, "];");
  3996. });
  3997. }
  3998. }
  3999. else
  4000. {
  4001. if (patch)
  4002. {
  4003. entry_func.fixup_hooks_in.push_back([=]() {
  4004. statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref,
  4005. " = ", patch_output_buffer_var_name, "[", to_expression(builtin_primitive_id_id),
  4006. "];");
  4007. });
  4008. }
  4009. else
  4010. {
  4011. entry_func.fixup_hooks_in.push_back([=]() {
  4012. statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "* gl_out = &",
  4013. output_buffer_var_name, "[", to_expression(builtin_primitive_id_id), " * ",
  4014. get_entry_point().output_vertices, "];");
  4015. });
  4016. }
  4017. }
  4018. break;
  4019. default:
  4020. break;
  4021. }
  4022. }
  4023. break;
  4024. }
  4025. default:
  4026. break;
  4027. }
  4028. set_name(ib_type_id, to_name(ir.default_entry_point) + "_" + ib_var_ref);
  4029. set_name(ib_var_id, ib_var_ref);
  4030. for (auto *p_var : vars)
  4031. {
  4032. bool strip_array = (is_tesc_shader() || (is_tese_shader() && storage == StorageClassInput)) && !patch;
  4033. // Fixing up flattened stores in TESC is impossible since the memory is group shared either via
  4034. // device (not masked) or threadgroup (masked) storage classes and it's race condition city.
  4035. meta.strip_array = strip_array;
  4036. meta.allow_local_declaration = !strip_array && !(is_tesc_shader() && storage == StorageClassOutput);
  4037. add_variable_to_interface_block(storage, ib_var_ref, ib_type, *p_var, meta);
  4038. }
  4039. if (((is_tesc_shader() && msl_options.multi_patch_workgroup) ||
  4040. (is_tese_shader() && msl_options.raw_buffer_tese_input)) &&
  4041. storage == StorageClassInput)
  4042. {
  4043. // For tessellation inputs, add all outputs from the previous stage to ensure
  4044. // the struct containing them is the correct size and layout.
  4045. for (auto &input : inputs_by_location)
  4046. {
  4047. if (location_inputs_in_use.count(input.first.location) != 0)
  4048. continue;
  4049. if (patch != (input.second.rate == MSL_SHADER_VARIABLE_RATE_PER_PATCH))
  4050. continue;
  4051. // Tessellation levels have their own struct, so there's no need to add them here.
  4052. if (input.second.builtin == BuiltInTessLevelOuter || input.second.builtin == BuiltInTessLevelInner)
  4053. continue;
  4054. // Create a fake variable to put at the location.
  4055. uint32_t offset = ir.increase_bound_by(5);
  4056. uint32_t type_id = offset;
  4057. uint32_t vec_type_id = offset + 1;
  4058. uint32_t array_type_id = offset + 2;
  4059. uint32_t ptr_type_id = offset + 3;
  4060. uint32_t var_id = offset + 4;
  4061. SPIRType type { OpTypeInt };
  4062. switch (input.second.format)
  4063. {
  4064. case MSL_SHADER_VARIABLE_FORMAT_UINT16:
  4065. case MSL_SHADER_VARIABLE_FORMAT_ANY16:
  4066. type.basetype = SPIRType::UShort;
  4067. type.width = 16;
  4068. break;
  4069. case MSL_SHADER_VARIABLE_FORMAT_ANY32:
  4070. default:
  4071. type.basetype = SPIRType::UInt;
  4072. type.width = 32;
  4073. break;
  4074. }
  4075. set<SPIRType>(type_id, type);
  4076. if (input.second.vecsize > 1)
  4077. {
  4078. type.op = OpTypeVector;
  4079. type.vecsize = input.second.vecsize;
  4080. set<SPIRType>(vec_type_id, type);
  4081. type_id = vec_type_id;
  4082. }
  4083. type.op = OpTypeArray;
  4084. type.array.push_back(0);
  4085. type.array_size_literal.push_back(true);
  4086. type.parent_type = type_id;
  4087. set<SPIRType>(array_type_id, type);
  4088. type.self = type_id;
  4089. type.op = OpTypePointer;
  4090. type.pointer = true;
  4091. type.pointer_depth++;
  4092. type.parent_type = array_type_id;
  4093. type.storage = storage;
  4094. auto &ptr_type = set<SPIRType>(ptr_type_id, type);
  4095. ptr_type.self = array_type_id;
  4096. auto &fake_var = set<SPIRVariable>(var_id, ptr_type_id, storage);
  4097. set_decoration(var_id, DecorationLocation, input.first.location);
  4098. if (input.first.component)
  4099. set_decoration(var_id, DecorationComponent, input.first.component);
  4100. meta.strip_array = true;
  4101. meta.allow_local_declaration = false;
  4102. add_variable_to_interface_block(storage, ib_var_ref, ib_type, fake_var, meta);
  4103. }
  4104. }
  4105. if (capture_output_to_buffer && storage == StorageClassOutput)
  4106. {
  4107. // For captured output, add all inputs from the next stage to ensure
  4108. // the struct containing them is the correct size and layout. This is
  4109. // necessary for certain implicit builtins that may nonetheless be read,
  4110. // even when they aren't written.
  4111. for (auto &output : outputs_by_location)
  4112. {
  4113. if (location_outputs_in_use.count(output.first.location) != 0)
  4114. continue;
  4115. // Create a fake variable to put at the location.
  4116. uint32_t offset = ir.increase_bound_by(5);
  4117. uint32_t type_id = offset;
  4118. uint32_t vec_type_id = offset + 1;
  4119. uint32_t array_type_id = offset + 2;
  4120. uint32_t ptr_type_id = offset + 3;
  4121. uint32_t var_id = offset + 4;
  4122. SPIRType type { OpTypeInt };
  4123. switch (output.second.format)
  4124. {
  4125. case MSL_SHADER_VARIABLE_FORMAT_UINT16:
  4126. case MSL_SHADER_VARIABLE_FORMAT_ANY16:
  4127. type.basetype = SPIRType::UShort;
  4128. type.width = 16;
  4129. break;
  4130. case MSL_SHADER_VARIABLE_FORMAT_ANY32:
  4131. default:
  4132. type.basetype = SPIRType::UInt;
  4133. type.width = 32;
  4134. break;
  4135. }
  4136. set<SPIRType>(type_id, type);
  4137. if (output.second.vecsize > 1)
  4138. {
  4139. type.op = OpTypeVector;
  4140. type.vecsize = output.second.vecsize;
  4141. set<SPIRType>(vec_type_id, type);
  4142. type_id = vec_type_id;
  4143. }
  4144. if (is_tesc_shader())
  4145. {
  4146. type.op = OpTypeArray;
  4147. type.array.push_back(0);
  4148. type.array_size_literal.push_back(true);
  4149. type.parent_type = type_id;
  4150. set<SPIRType>(array_type_id, type);
  4151. }
  4152. type.op = OpTypePointer;
  4153. type.pointer = true;
  4154. type.pointer_depth++;
  4155. type.parent_type = is_tesc_shader() ? array_type_id : type_id;
  4156. type.storage = storage;
  4157. auto &ptr_type = set<SPIRType>(ptr_type_id, type);
  4158. ptr_type.self = type.parent_type;
  4159. auto &fake_var = set<SPIRVariable>(var_id, ptr_type_id, storage);
  4160. set_decoration(var_id, DecorationLocation, output.first.location);
  4161. if (output.first.component)
  4162. set_decoration(var_id, DecorationComponent, output.first.component);
  4163. meta.strip_array = true;
  4164. meta.allow_local_declaration = false;
  4165. add_variable_to_interface_block(storage, ib_var_ref, ib_type, fake_var, meta);
  4166. }
  4167. }
  4168. // When multiple variables need to access same location,
  4169. // unroll locations one by one and we will flatten output or input as necessary.
  4170. for (auto &loc : meta.location_meta)
  4171. {
  4172. uint32_t location = loc.first;
  4173. auto &location_meta = loc.second;
  4174. uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
  4175. uint32_t type_id = build_extended_vector_type(location_meta.base_type_id, location_meta.num_components);
  4176. ib_type.member_types.push_back(type_id);
  4177. set_member_name(ib_type.self, ib_mbr_idx, join("m_location_", location));
  4178. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, location);
  4179. mark_location_as_used_by_shader(location, get<SPIRType>(type_id), storage);
  4180. if (location_meta.flat)
  4181. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat);
  4182. if (location_meta.noperspective)
  4183. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective);
  4184. if (location_meta.centroid)
  4185. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid);
  4186. if (location_meta.sample)
  4187. set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample);
  4188. }
  4189. // Sort the members of the structure by their locations.
  4190. MemberSorter member_sorter(ib_type, ir.meta[ib_type_id], MemberSorter::LocationThenBuiltInType);
  4191. member_sorter.sort();
  4192. // The member indices were saved to the original variables, but after the members
  4193. // were sorted, those indices are now likely incorrect. Fix those up now.
  4194. fix_up_interface_member_indices(storage, ib_type_id);
  4195. // For patch inputs, add one more member, holding the array of control point data.
  4196. if (is_tese_shader() && !msl_options.raw_buffer_tese_input && storage == StorageClassInput && patch &&
  4197. stage_in_var_id)
  4198. {
  4199. uint32_t pcp_type_id = ir.increase_bound_by(1);
  4200. auto &pcp_type = set<SPIRType>(pcp_type_id, ib_type);
  4201. pcp_type.basetype = SPIRType::ControlPointArray;
  4202. pcp_type.parent_type = pcp_type.type_alias = get_stage_in_struct_type().self;
  4203. pcp_type.storage = storage;
  4204. ir.meta[pcp_type_id] = ir.meta[ib_type.self];
  4205. uint32_t mbr_idx = uint32_t(ib_type.member_types.size());
  4206. ib_type.member_types.push_back(pcp_type_id);
  4207. set_member_name(ib_type.self, mbr_idx, "gl_in");
  4208. }
  4209. if (storage == StorageClassInput)
  4210. set_decoration(ib_var_id, DecorationNonWritable);
  4211. return ib_var_id;
  4212. }
  4213. uint32_t CompilerMSL::add_interface_block_pointer(uint32_t ib_var_id, StorageClass storage)
  4214. {
  4215. if (!ib_var_id)
  4216. return 0;
  4217. uint32_t ib_ptr_var_id;
  4218. uint32_t next_id = ir.increase_bound_by(3);
  4219. auto &ib_type = expression_type(ib_var_id);
  4220. if (is_tesc_shader() || (is_tese_shader() && msl_options.raw_buffer_tese_input))
  4221. {
  4222. // Tessellation control per-vertex I/O is presented as an array, so we must
  4223. // do the same with our struct here.
  4224. uint32_t ib_ptr_type_id = next_id++;
  4225. auto &ib_ptr_type = set<SPIRType>(ib_ptr_type_id, ib_type);
  4226. ib_ptr_type.op = OpTypePointer;
  4227. ib_ptr_type.parent_type = ib_ptr_type.type_alias = ib_type.self;
  4228. ib_ptr_type.pointer = true;
  4229. ib_ptr_type.pointer_depth++;
  4230. ib_ptr_type.storage = storage == StorageClassInput ?
  4231. ((is_tesc_shader() && msl_options.multi_patch_workgroup) ||
  4232. (is_tese_shader() && msl_options.raw_buffer_tese_input) ?
  4233. StorageClassStorageBuffer :
  4234. StorageClassWorkgroup) :
  4235. StorageClassStorageBuffer;
  4236. ir.meta[ib_ptr_type_id] = ir.meta[ib_type.self];
  4237. // To ensure that get_variable_data_type() doesn't strip off the pointer,
  4238. // which we need, use another pointer.
  4239. uint32_t ib_ptr_ptr_type_id = next_id++;
  4240. auto &ib_ptr_ptr_type = set<SPIRType>(ib_ptr_ptr_type_id, ib_ptr_type);
  4241. ib_ptr_ptr_type.parent_type = ib_ptr_type_id;
  4242. ib_ptr_ptr_type.type_alias = ib_type.self;
  4243. ib_ptr_ptr_type.storage = StorageClassFunction;
  4244. ir.meta[ib_ptr_ptr_type_id] = ir.meta[ib_type.self];
  4245. ib_ptr_var_id = next_id;
  4246. set<SPIRVariable>(ib_ptr_var_id, ib_ptr_ptr_type_id, StorageClassFunction, 0);
  4247. set_name(ib_ptr_var_id, storage == StorageClassInput ? "gl_in" : "gl_out");
  4248. if (storage == StorageClassInput)
  4249. set_decoration(ib_ptr_var_id, DecorationNonWritable);
  4250. }
  4251. else
  4252. {
  4253. // Tessellation evaluation per-vertex inputs are also presented as arrays.
  4254. // But, in Metal, this array uses a very special type, 'patch_control_point<T>',
  4255. // which is a container that can be used to access the control point data.
  4256. // To represent this, a special 'ControlPointArray' type has been added to the
  4257. // SPIRV-Cross type system. It should only be generated by and seen in the MSL
  4258. // backend (i.e. this one).
  4259. uint32_t pcp_type_id = next_id++;
  4260. auto &pcp_type = set<SPIRType>(pcp_type_id, ib_type);
  4261. pcp_type.basetype = SPIRType::ControlPointArray;
  4262. pcp_type.parent_type = pcp_type.type_alias = ib_type.self;
  4263. pcp_type.storage = storage;
  4264. ir.meta[pcp_type_id] = ir.meta[ib_type.self];
  4265. ib_ptr_var_id = next_id;
  4266. set<SPIRVariable>(ib_ptr_var_id, pcp_type_id, storage, 0);
  4267. set_name(ib_ptr_var_id, "gl_in");
  4268. ir.meta[ib_ptr_var_id].decoration.qualified_alias = join(patch_stage_in_var_name, ".gl_in");
  4269. }
  4270. return ib_ptr_var_id;
  4271. }
  4272. uint32_t CompilerMSL::add_meshlet_block(bool per_primitive)
  4273. {
  4274. // Accumulate the variables that should appear in the interface struct.
  4275. SmallVector<SPIRVariable *> vars;
  4276. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
  4277. if (var.storage != StorageClassOutput || var.self == builtin_mesh_primitive_indices_id)
  4278. return;
  4279. if (is_per_primitive_variable(var) != per_primitive)
  4280. return;
  4281. vars.push_back(&var);
  4282. });
  4283. if (vars.empty())
  4284. return 0;
  4285. uint32_t next_id = ir.increase_bound_by(1);
  4286. auto &type = set<SPIRType>(next_id, SPIRType(OpTypeStruct));
  4287. type.basetype = SPIRType::Struct;
  4288. InterfaceBlockMeta meta;
  4289. for (auto *p_var : vars)
  4290. {
  4291. meta.strip_array = true;
  4292. meta.allow_local_declaration = false;
  4293. add_variable_to_interface_block(StorageClassOutput, "", type, *p_var, meta);
  4294. }
  4295. if (per_primitive)
  4296. set_name(type.self, "spvPerPrimitive");
  4297. else
  4298. set_name(type.self, "spvPerVertex");
  4299. return next_id;
  4300. }
  4301. // Ensure that the type is compatible with the builtin.
  4302. // If it is, simply return the given type ID.
  4303. // Otherwise, create a new type, and return it's ID.
  4304. uint32_t CompilerMSL::ensure_correct_builtin_type(uint32_t type_id, BuiltIn builtin)
  4305. {
  4306. auto &type = get<SPIRType>(type_id);
  4307. auto &pointee_type = get_pointee_type(type);
  4308. if ((builtin == BuiltInSampleMask && is_array(pointee_type)) ||
  4309. ((builtin == BuiltInLayer || builtin == BuiltInViewportIndex || builtin == BuiltInFragStencilRefEXT) &&
  4310. pointee_type.basetype != SPIRType::UInt))
  4311. {
  4312. uint32_t next_id = ir.increase_bound_by(is_pointer(type) ? 2 : 1);
  4313. uint32_t base_type_id = next_id++;
  4314. auto &base_type = set<SPIRType>(base_type_id, OpTypeInt);
  4315. base_type.basetype = SPIRType::UInt;
  4316. base_type.width = 32;
  4317. if (!is_pointer(type))
  4318. return base_type_id;
  4319. uint32_t ptr_type_id = next_id++;
  4320. auto &ptr_type = set<SPIRType>(ptr_type_id, base_type);
  4321. ptr_type.op = OpTypePointer;
  4322. ptr_type.pointer = true;
  4323. ptr_type.pointer_depth++;
  4324. ptr_type.storage = type.storage;
  4325. ptr_type.parent_type = base_type_id;
  4326. return ptr_type_id;
  4327. }
  4328. return type_id;
  4329. }
  4330. // Ensure that the type is compatible with the shader input.
  4331. // If it is, simply return the given type ID.
  4332. // Otherwise, create a new type, and return its ID.
  4333. uint32_t CompilerMSL::ensure_correct_input_type(uint32_t type_id, uint32_t location, uint32_t component, uint32_t num_components, bool strip_array)
  4334. {
  4335. auto &type = get<SPIRType>(type_id);
  4336. uint32_t max_array_dimensions = strip_array ? 1 : 0;
  4337. // Struct and array types must match exactly.
  4338. if (type.basetype == SPIRType::Struct || type.array.size() > max_array_dimensions)
  4339. return type_id;
  4340. auto p_va = inputs_by_location.find({location, component});
  4341. if (p_va == end(inputs_by_location))
  4342. {
  4343. if (num_components > type.vecsize)
  4344. return build_extended_vector_type(type_id, num_components);
  4345. else
  4346. return type_id;
  4347. }
  4348. if (num_components == 0)
  4349. num_components = p_va->second.vecsize;
  4350. switch (p_va->second.format)
  4351. {
  4352. case MSL_SHADER_VARIABLE_FORMAT_UINT8:
  4353. {
  4354. switch (type.basetype)
  4355. {
  4356. case SPIRType::UByte:
  4357. case SPIRType::UShort:
  4358. case SPIRType::UInt:
  4359. if (num_components > type.vecsize)
  4360. return build_extended_vector_type(type_id, num_components);
  4361. else
  4362. return type_id;
  4363. case SPIRType::Short:
  4364. return build_extended_vector_type(type_id, num_components > type.vecsize ? num_components : type.vecsize,
  4365. SPIRType::UShort);
  4366. case SPIRType::Int:
  4367. return build_extended_vector_type(type_id, num_components > type.vecsize ? num_components : type.vecsize,
  4368. SPIRType::UInt);
  4369. default:
  4370. SPIRV_CROSS_THROW("Vertex attribute type mismatch between host and shader");
  4371. }
  4372. }
  4373. case MSL_SHADER_VARIABLE_FORMAT_UINT16:
  4374. {
  4375. switch (type.basetype)
  4376. {
  4377. case SPIRType::UShort:
  4378. case SPIRType::UInt:
  4379. if (num_components > type.vecsize)
  4380. return build_extended_vector_type(type_id, num_components);
  4381. else
  4382. return type_id;
  4383. case SPIRType::Int:
  4384. return build_extended_vector_type(type_id, num_components > type.vecsize ? num_components : type.vecsize,
  4385. SPIRType::UInt);
  4386. default:
  4387. SPIRV_CROSS_THROW("Vertex attribute type mismatch between host and shader");
  4388. }
  4389. }
  4390. default:
  4391. if (num_components > type.vecsize)
  4392. type_id = build_extended_vector_type(type_id, num_components);
  4393. break;
  4394. }
  4395. return type_id;
  4396. }
  4397. void CompilerMSL::mark_struct_members_packed(const SPIRType &type)
  4398. {
  4399. // Handle possible recursion when a struct contains a pointer to its own type nested somewhere.
  4400. if (has_extended_decoration(type.self, SPIRVCrossDecorationPhysicalTypePacked))
  4401. return;
  4402. set_extended_decoration(type.self, SPIRVCrossDecorationPhysicalTypePacked);
  4403. // Problem case! Struct needs to be placed at an awkward alignment.
  4404. // Mark every member of the child struct as packed.
  4405. uint32_t mbr_cnt = uint32_t(type.member_types.size());
  4406. for (uint32_t i = 0; i < mbr_cnt; i++)
  4407. {
  4408. auto &mbr_type = get<SPIRType>(type.member_types[i]);
  4409. if (mbr_type.basetype == SPIRType::Struct)
  4410. {
  4411. // Recursively mark structs as packed.
  4412. auto *struct_type = &mbr_type;
  4413. while (!struct_type->array.empty())
  4414. struct_type = &get<SPIRType>(struct_type->parent_type);
  4415. mark_struct_members_packed(*struct_type);
  4416. }
  4417. else if (!is_scalar(mbr_type))
  4418. set_extended_member_decoration(type.self, i, SPIRVCrossDecorationPhysicalTypePacked);
  4419. }
  4420. }
  4421. void CompilerMSL::mark_scalar_layout_structs(const SPIRType &type)
  4422. {
  4423. uint32_t mbr_cnt = uint32_t(type.member_types.size());
  4424. for (uint32_t i = 0; i < mbr_cnt; i++)
  4425. {
  4426. // Handle possible recursion when a struct contains a pointer to its own type nested somewhere.
  4427. auto &mbr_type = get<SPIRType>(type.member_types[i]);
  4428. if (mbr_type.basetype == SPIRType::Struct && !(mbr_type.pointer && mbr_type.storage == StorageClassPhysicalStorageBuffer))
  4429. {
  4430. auto *struct_type = &mbr_type;
  4431. while (!struct_type->array.empty())
  4432. struct_type = &get<SPIRType>(struct_type->parent_type);
  4433. if (has_extended_decoration(struct_type->self, SPIRVCrossDecorationPhysicalTypePacked))
  4434. continue;
  4435. uint32_t msl_alignment = get_declared_struct_member_alignment_msl(type, i);
  4436. uint32_t msl_size = get_declared_struct_member_size_msl(type, i);
  4437. uint32_t spirv_offset = type_struct_member_offset(type, i);
  4438. uint32_t spirv_offset_next;
  4439. if (i + 1 < mbr_cnt)
  4440. spirv_offset_next = type_struct_member_offset(type, i + 1);
  4441. else
  4442. spirv_offset_next = spirv_offset + msl_size;
  4443. // Both are complicated cases. In scalar layout, a struct of float3 might just consume 12 bytes,
  4444. // and the next member will be placed at offset 12.
  4445. bool struct_is_misaligned = (spirv_offset % msl_alignment) != 0;
  4446. bool struct_is_too_large = spirv_offset + msl_size > spirv_offset_next;
  4447. uint32_t array_stride = 0;
  4448. bool struct_needs_explicit_padding = false;
  4449. // Verify that if a struct is used as an array that ArrayStride matches the effective size of the struct.
  4450. if (!mbr_type.array.empty())
  4451. {
  4452. array_stride = type_struct_member_array_stride(type, i);
  4453. uint32_t dimensions = uint32_t(mbr_type.array.size() - 1);
  4454. for (uint32_t dim = 0; dim < dimensions; dim++)
  4455. {
  4456. uint32_t array_size = to_array_size_literal(mbr_type, dim);
  4457. array_stride /= max<uint32_t>(array_size, 1u);
  4458. }
  4459. // Set expected struct size based on ArrayStride.
  4460. struct_needs_explicit_padding = true;
  4461. // If struct size is larger than array stride, we might be able to fit, if we tightly pack.
  4462. if (get_declared_struct_size_msl(*struct_type) > array_stride)
  4463. struct_is_too_large = true;
  4464. }
  4465. if (struct_is_misaligned || struct_is_too_large)
  4466. mark_struct_members_packed(*struct_type);
  4467. mark_scalar_layout_structs(*struct_type);
  4468. if (struct_needs_explicit_padding)
  4469. {
  4470. msl_size = get_declared_struct_size_msl(*struct_type, true, true);
  4471. if (array_stride < msl_size)
  4472. {
  4473. SPIRV_CROSS_THROW("Cannot express an array stride smaller than size of struct type.");
  4474. }
  4475. else
  4476. {
  4477. if (has_extended_decoration(struct_type->self, SPIRVCrossDecorationPaddingTarget))
  4478. {
  4479. if (array_stride !=
  4480. get_extended_decoration(struct_type->self, SPIRVCrossDecorationPaddingTarget))
  4481. SPIRV_CROSS_THROW(
  4482. "A struct is used with different array strides. Cannot express this in MSL.");
  4483. }
  4484. else
  4485. set_extended_decoration(struct_type->self, SPIRVCrossDecorationPaddingTarget, array_stride);
  4486. }
  4487. }
  4488. }
  4489. }
  4490. }
  4491. // Sort the members of the struct type by offset, and pack and then pad members where needed
  4492. // to align MSL members with SPIR-V offsets. The struct members are iterated twice. Packing
  4493. // occurs first, followed by padding, because packing a member reduces both its size and its
  4494. // natural alignment, possibly requiring a padding member to be added ahead of it.
  4495. void CompilerMSL::align_struct(SPIRType &ib_type, unordered_set<uint32_t> &aligned_structs)
  4496. {
  4497. // We align structs recursively, so stop any redundant work.
  4498. ID &ib_type_id = ib_type.self;
  4499. if (aligned_structs.count(ib_type_id))
  4500. return;
  4501. aligned_structs.insert(ib_type_id);
  4502. // Sort the members of the interface structure by their offset.
  4503. // They should already be sorted per SPIR-V spec anyway.
  4504. MemberSorter member_sorter(ib_type, ir.meta[ib_type_id], MemberSorter::Offset);
  4505. member_sorter.sort();
  4506. auto mbr_cnt = uint32_t(ib_type.member_types.size());
  4507. for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
  4508. {
  4509. // Pack any dependent struct types before we pack a parent struct.
  4510. auto &mbr_type = get<SPIRType>(ib_type.member_types[mbr_idx]);
  4511. if (mbr_type.basetype == SPIRType::Struct)
  4512. align_struct(mbr_type, aligned_structs);
  4513. }
  4514. // Test the alignment of each member, and if a member should be closer to the previous
  4515. // member than the default spacing expects, it is likely that the previous member is in
  4516. // a packed format. If so, and the previous member is packable, pack it.
  4517. // For example ... this applies to any 3-element vector that is followed by a scalar.
  4518. uint32_t msl_offset = 0;
  4519. for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
  4520. {
  4521. // This checks the member in isolation, if the member needs some kind of type remapping to conform to SPIR-V
  4522. // offsets, array strides and matrix strides.
  4523. ensure_member_packing_rules_msl(ib_type, mbr_idx);
  4524. // Align current offset to the current member's default alignment. If the member was packed, it will observe
  4525. // the updated alignment here.
  4526. uint32_t msl_align_mask = get_declared_struct_member_alignment_msl(ib_type, mbr_idx) - 1;
  4527. uint32_t aligned_msl_offset = (msl_offset + msl_align_mask) & ~msl_align_mask;
  4528. // Fetch the member offset as declared in the SPIRV.
  4529. uint32_t spirv_mbr_offset = get_member_decoration(ib_type_id, mbr_idx, DecorationOffset);
  4530. if (spirv_mbr_offset > aligned_msl_offset)
  4531. {
  4532. // Since MSL and SPIR-V have slightly different struct member alignment and
  4533. // size rules, we'll pad to standard C-packing rules with a char[] array. If the member is farther
  4534. // away than C-packing, expects, add an inert padding member before the the member.
  4535. uint32_t padding_bytes = spirv_mbr_offset - aligned_msl_offset;
  4536. set_extended_member_decoration(ib_type_id, mbr_idx, SPIRVCrossDecorationPaddingTarget, padding_bytes);
  4537. // Re-align as a sanity check that aligning post-padding matches up.
  4538. msl_offset += padding_bytes;
  4539. aligned_msl_offset = (msl_offset + msl_align_mask) & ~msl_align_mask;
  4540. }
  4541. else if (spirv_mbr_offset < aligned_msl_offset)
  4542. {
  4543. // This should not happen, but deal with unexpected scenarios.
  4544. // It *might* happen if a sub-struct has a larger alignment requirement in MSL than SPIR-V.
  4545. SPIRV_CROSS_THROW("Cannot represent buffer block correctly in MSL.");
  4546. }
  4547. assert(aligned_msl_offset == spirv_mbr_offset);
  4548. // Increment the current offset to be positioned immediately after the current member.
  4549. // Don't do this for the last member since it can be unsized, and it is not relevant for padding purposes here.
  4550. if (mbr_idx + 1 < mbr_cnt)
  4551. msl_offset = aligned_msl_offset + get_declared_struct_member_size_msl(ib_type, mbr_idx);
  4552. }
  4553. }
  4554. bool CompilerMSL::validate_member_packing_rules_msl(const SPIRType &type, uint32_t index) const
  4555. {
  4556. auto &mbr_type = get<SPIRType>(type.member_types[index]);
  4557. uint32_t spirv_offset = get_member_decoration(type.self, index, DecorationOffset);
  4558. if (index + 1 < type.member_types.size())
  4559. {
  4560. // First, we will check offsets. If SPIR-V offset + MSL size > SPIR-V offset of next member,
  4561. // we *must* perform some kind of remapping, no way getting around it.
  4562. // We can always pad after this member if necessary, so that case is fine.
  4563. uint32_t spirv_offset_next = get_member_decoration(type.self, index + 1, DecorationOffset);
  4564. assert(spirv_offset_next >= spirv_offset);
  4565. uint32_t maximum_size = spirv_offset_next - spirv_offset;
  4566. uint32_t msl_mbr_size = get_declared_struct_member_size_msl(type, index);
  4567. if (msl_mbr_size > maximum_size)
  4568. return false;
  4569. }
  4570. if (is_array(mbr_type))
  4571. {
  4572. // If we have an array type, array stride must match exactly with SPIR-V.
  4573. // An exception to this requirement is if we have one array element.
  4574. // This comes from DX scalar layout workaround.
  4575. // If app tries to be cheeky and access the member out of bounds, this will not work, but this is the best we can do.
  4576. // In OpAccessChain with logical memory models, access chains must be in-bounds in SPIR-V specification.
  4577. bool relax_array_stride = mbr_type.array.back() == 1 && mbr_type.array_size_literal.back();
  4578. if (!relax_array_stride)
  4579. {
  4580. uint32_t spirv_array_stride = type_struct_member_array_stride(type, index);
  4581. uint32_t msl_array_stride = get_declared_struct_member_array_stride_msl(type, index);
  4582. if (spirv_array_stride != msl_array_stride)
  4583. return false;
  4584. }
  4585. }
  4586. if (is_matrix(mbr_type))
  4587. {
  4588. // Need to check MatrixStride as well.
  4589. uint32_t spirv_matrix_stride = type_struct_member_matrix_stride(type, index);
  4590. uint32_t msl_matrix_stride = get_declared_struct_member_matrix_stride_msl(type, index);
  4591. if (spirv_matrix_stride != msl_matrix_stride)
  4592. return false;
  4593. }
  4594. // Now, we check alignment.
  4595. uint32_t msl_alignment = get_declared_struct_member_alignment_msl(type, index);
  4596. if ((spirv_offset % msl_alignment) != 0)
  4597. return false;
  4598. // We're in the clear.
  4599. return true;
  4600. }
  4601. // Here we need to verify that the member type we declare conforms to Offset, ArrayStride or MatrixStride restrictions.
  4602. // If there is a mismatch, we need to emit remapped types, either normal types, or "packed_X" types.
  4603. // In odd cases we need to emit packed and remapped types, for e.g. weird matrices or arrays with weird array strides.
  4604. void CompilerMSL::ensure_member_packing_rules_msl(SPIRType &ib_type, uint32_t index)
  4605. {
  4606. if (validate_member_packing_rules_msl(ib_type, index))
  4607. return;
  4608. // We failed validation.
  4609. // This case will be nightmare-ish to deal with. This could possibly happen if struct alignment does not quite
  4610. // match up with what we want. Scalar block layout comes to mind here where we might have to work around the rule
  4611. // that struct alignment == max alignment of all members and struct size depends on this alignment.
  4612. // Can't repack structs, but can repack pointers to structs.
  4613. auto &mbr_type = get<SPIRType>(ib_type.member_types[index]);
  4614. bool is_buff_ptr = mbr_type.pointer && mbr_type.storage == StorageClassPhysicalStorageBuffer;
  4615. if (mbr_type.basetype == SPIRType::Struct && !is_buff_ptr)
  4616. SPIRV_CROSS_THROW("Cannot perform any repacking for structs when it is used as a member of another struct.");
  4617. // Perform remapping here.
  4618. // There is nothing to be gained by using packed scalars, so don't attempt it.
  4619. if (!is_scalar(ib_type))
  4620. set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked);
  4621. // Try validating again, now with packed.
  4622. if (validate_member_packing_rules_msl(ib_type, index))
  4623. return;
  4624. // We're in deep trouble, and we need to create a new PhysicalType which matches up with what we expect.
  4625. // A lot of work goes here ...
  4626. // We will need remapping on Load and Store to translate the types between Logical and Physical.
  4627. // First, we check if we have small vector std140 array.
  4628. // We detect this if we have an array of vectors, and array stride is greater than number of elements.
  4629. if (!mbr_type.array.empty() && !is_matrix(mbr_type))
  4630. {
  4631. uint32_t array_stride = type_struct_member_array_stride(ib_type, index);
  4632. // Hack off array-of-arrays until we find the array stride per element we must have to make it work.
  4633. uint32_t dimensions = uint32_t(mbr_type.array.size() - 1);
  4634. for (uint32_t dim = 0; dim < dimensions; dim++)
  4635. array_stride /= max<uint32_t>(to_array_size_literal(mbr_type, dim), 1u);
  4636. // Pointers are 8 bytes
  4637. uint32_t mbr_width_in_bytes = is_buff_ptr ? 8 : (mbr_type.width / 8);
  4638. uint32_t elems_per_stride = array_stride / mbr_width_in_bytes;
  4639. if (elems_per_stride == 3)
  4640. SPIRV_CROSS_THROW("Cannot use ArrayStride of 3 elements in remapping scenarios.");
  4641. else if (elems_per_stride > 4 && elems_per_stride != 8)
  4642. SPIRV_CROSS_THROW("Cannot represent vectors with more than 4 elements in MSL.");
  4643. if (elems_per_stride == 8)
  4644. {
  4645. if (mbr_type.width == 16)
  4646. add_spv_func_and_recompile(SPVFuncImplPaddedStd140);
  4647. else
  4648. SPIRV_CROSS_THROW("Unexpected type in std140 wide array resolve.");
  4649. }
  4650. auto physical_type = mbr_type;
  4651. physical_type.vecsize = elems_per_stride;
  4652. physical_type.parent_type = 0;
  4653. // If this is a physical buffer pointer, replace type with a ulongn vector.
  4654. if (is_buff_ptr)
  4655. {
  4656. physical_type.width = 64;
  4657. physical_type.basetype = to_unsigned_basetype(physical_type.width);
  4658. physical_type.pointer = false;
  4659. physical_type.pointer_depth = false;
  4660. physical_type.forward_pointer = false;
  4661. }
  4662. uint32_t type_id = ir.increase_bound_by(1);
  4663. set<SPIRType>(type_id, physical_type);
  4664. set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID, type_id);
  4665. set_decoration(type_id, DecorationArrayStride, array_stride);
  4666. // Remove packed_ for vectors of size 1, 2 and 4.
  4667. unset_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked);
  4668. }
  4669. else if (is_matrix(mbr_type))
  4670. {
  4671. // MatrixStride might be std140-esque.
  4672. uint32_t matrix_stride = type_struct_member_matrix_stride(ib_type, index);
  4673. uint32_t elems_per_stride = matrix_stride / (mbr_type.width / 8);
  4674. if (elems_per_stride == 3)
  4675. SPIRV_CROSS_THROW("Cannot use ArrayStride of 3 elements in remapping scenarios.");
  4676. else if (elems_per_stride > 4 && elems_per_stride != 8)
  4677. SPIRV_CROSS_THROW("Cannot represent vectors with more than 4 elements in MSL.");
  4678. if (elems_per_stride == 8)
  4679. {
  4680. if (mbr_type.basetype != SPIRType::Half)
  4681. SPIRV_CROSS_THROW("Unexpected type in std140 wide matrix stride resolve.");
  4682. add_spv_func_and_recompile(SPVFuncImplPaddedStd140);
  4683. }
  4684. bool row_major = has_member_decoration(ib_type.self, index, DecorationRowMajor);
  4685. auto physical_type = mbr_type;
  4686. physical_type.parent_type = 0;
  4687. if (row_major)
  4688. physical_type.columns = elems_per_stride;
  4689. else
  4690. physical_type.vecsize = elems_per_stride;
  4691. uint32_t type_id = ir.increase_bound_by(1);
  4692. set<SPIRType>(type_id, physical_type);
  4693. set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID, type_id);
  4694. // Remove packed_ for vectors of size 1, 2 and 4.
  4695. unset_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked);
  4696. }
  4697. else
  4698. SPIRV_CROSS_THROW("Found a buffer packing case which we cannot represent in MSL.");
  4699. // Try validating again, now with physical type remapping.
  4700. if (validate_member_packing_rules_msl(ib_type, index))
  4701. return;
  4702. // We might have a particular odd scalar layout case where the last element of an array
  4703. // does not take up as much space as the ArrayStride or MatrixStride. This can happen with DX cbuffers.
  4704. // The "proper" workaround for this is extremely painful and essentially impossible in the edge case of float3[],
  4705. // so we hack around it by declaring the offending array or matrix with one less array size/col/row,
  4706. // and rely on padding to get the correct value. We will technically access arrays out of bounds into the padding region,
  4707. // but it should spill over gracefully without too much trouble. We rely on behavior like this for unsized arrays anyways.
  4708. // E.g. we might observe a physical layout of:
  4709. // { float2 a[2]; float b; } in cbuffer layout where ArrayStride of a is 16, but offset of b is 24, packed right after a[1] ...
  4710. uint32_t type_id = get_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID);
  4711. auto &type = get<SPIRType>(type_id);
  4712. // Modify the physical type in-place. This is safe since each physical type workaround is a copy.
  4713. if (is_array(type))
  4714. {
  4715. if (type.array.back() > 1)
  4716. {
  4717. if (!type.array_size_literal.back())
  4718. SPIRV_CROSS_THROW("Cannot apply scalar layout workaround with spec constant array size.");
  4719. type.array.back() -= 1;
  4720. }
  4721. else
  4722. {
  4723. // We have an array of size 1, so we cannot decrement that. Our only option now is to
  4724. // force a packed layout instead, and drop the physical type remap since ArrayStride is meaningless now.
  4725. unset_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID);
  4726. set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked);
  4727. }
  4728. }
  4729. else if (is_matrix(type))
  4730. {
  4731. bool row_major = has_member_decoration(ib_type.self, index, DecorationRowMajor);
  4732. if (!row_major)
  4733. {
  4734. // Slice off one column. If we only have 2 columns, this might turn the matrix into a vector with one array element instead.
  4735. if (type.columns > 2)
  4736. {
  4737. type.columns--;
  4738. }
  4739. else if (type.columns == 2)
  4740. {
  4741. type.columns = 1;
  4742. assert(type.array.empty());
  4743. type.op = OpTypeArray;
  4744. type.array.push_back(1);
  4745. type.array_size_literal.push_back(true);
  4746. }
  4747. }
  4748. else
  4749. {
  4750. // Slice off one row. If we only have 2 rows, this might turn the matrix into a vector with one array element instead.
  4751. if (type.vecsize > 2)
  4752. {
  4753. type.vecsize--;
  4754. }
  4755. else if (type.vecsize == 2)
  4756. {
  4757. type.vecsize = type.columns;
  4758. type.columns = 1;
  4759. assert(type.array.empty());
  4760. type.op = OpTypeArray;
  4761. type.array.push_back(1);
  4762. type.array_size_literal.push_back(true);
  4763. }
  4764. }
  4765. }
  4766. // This better validate now, or we must fail gracefully.
  4767. if (!validate_member_packing_rules_msl(ib_type, index))
  4768. SPIRV_CROSS_THROW("Found a buffer packing case which we cannot represent in MSL.");
  4769. }
  4770. void CompilerMSL::emit_store_statement(uint32_t lhs_expression, uint32_t rhs_expression)
  4771. {
  4772. auto &type = expression_type(rhs_expression);
  4773. bool lhs_remapped_type = has_extended_decoration(lhs_expression, SPIRVCrossDecorationPhysicalTypeID);
  4774. bool lhs_packed_type = has_extended_decoration(lhs_expression, SPIRVCrossDecorationPhysicalTypePacked);
  4775. auto *lhs_e = maybe_get<SPIRExpression>(lhs_expression);
  4776. auto *rhs_e = maybe_get<SPIRExpression>(rhs_expression);
  4777. bool transpose = lhs_e && lhs_e->need_transpose;
  4778. if (has_decoration(lhs_expression, DecorationBuiltIn) &&
  4779. BuiltIn(get_decoration(lhs_expression, DecorationBuiltIn)) == BuiltInSampleMask &&
  4780. is_array(type))
  4781. {
  4782. // Storing an array to SampleMask, have to remove the array-ness before storing.
  4783. statement(to_expression(lhs_expression), " = ", to_enclosed_unpacked_expression(rhs_expression), "[0];");
  4784. register_write(lhs_expression);
  4785. }
  4786. else if (!lhs_remapped_type && !lhs_packed_type)
  4787. {
  4788. // No physical type remapping, and no packed type, so can just emit a store directly.
  4789. // We might not be dealing with remapped physical types or packed types,
  4790. // but we might be doing a clean store to a row-major matrix.
  4791. // In this case, we just flip transpose states, and emit the store, a transpose must be in the RHS expression, if any.
  4792. if (is_matrix(type) && lhs_e && lhs_e->need_transpose)
  4793. {
  4794. lhs_e->need_transpose = false;
  4795. if (rhs_e && rhs_e->need_transpose)
  4796. {
  4797. // Direct copy, but might need to unpack RHS.
  4798. // Skip the transpose, as we will transpose when writing to LHS and transpose(transpose(T)) == T.
  4799. rhs_e->need_transpose = false;
  4800. statement(to_expression(lhs_expression), " = ", to_unpacked_row_major_matrix_expression(rhs_expression),
  4801. ";");
  4802. rhs_e->need_transpose = true;
  4803. }
  4804. else
  4805. statement(to_expression(lhs_expression), " = transpose(", to_unpacked_expression(rhs_expression), ");");
  4806. lhs_e->need_transpose = true;
  4807. register_write(lhs_expression);
  4808. }
  4809. else if (lhs_e && lhs_e->need_transpose)
  4810. {
  4811. lhs_e->need_transpose = false;
  4812. // Storing a column to a row-major matrix. Unroll the write.
  4813. for (uint32_t c = 0; c < type.vecsize; c++)
  4814. {
  4815. auto lhs_expr = to_dereferenced_expression(lhs_expression);
  4816. auto column_index = lhs_expr.find_last_of('[');
  4817. if (column_index != string::npos)
  4818. {
  4819. statement(lhs_expr.insert(column_index, join('[', c, ']')), " = ",
  4820. to_extract_component_expression(rhs_expression, c), ";");
  4821. }
  4822. }
  4823. lhs_e->need_transpose = true;
  4824. register_write(lhs_expression);
  4825. }
  4826. else
  4827. CompilerGLSL::emit_store_statement(lhs_expression, rhs_expression);
  4828. }
  4829. else if (!lhs_remapped_type && !is_matrix(type) && !transpose)
  4830. {
  4831. // Even if the target type is packed, we can directly store to it. We cannot store to packed matrices directly,
  4832. // since they are declared as array of vectors instead, and we need the fallback path below.
  4833. CompilerGLSL::emit_store_statement(lhs_expression, rhs_expression);
  4834. }
  4835. else
  4836. {
  4837. // Special handling when storing to a remapped physical type.
  4838. // This is mostly to deal with std140 padded matrices or vectors.
  4839. TypeID physical_type_id = lhs_remapped_type ?
  4840. ID(get_extended_decoration(lhs_expression, SPIRVCrossDecorationPhysicalTypeID)) :
  4841. type.self;
  4842. auto &physical_type = get<SPIRType>(physical_type_id);
  4843. string cast_addr_space = "thread";
  4844. auto *p_var_lhs = maybe_get_backing_variable(lhs_expression);
  4845. if (p_var_lhs)
  4846. cast_addr_space = get_type_address_space(get<SPIRType>(p_var_lhs->basetype), lhs_expression);
  4847. if (is_matrix(type))
  4848. {
  4849. const char *packed_pfx = lhs_packed_type ? "packed_" : "";
  4850. // Packed matrices are stored as arrays of packed vectors, so we need
  4851. // to assign the vectors one at a time.
  4852. // For row-major matrices, we need to transpose the *right-hand* side,
  4853. // not the left-hand side.
  4854. // Lots of cases to cover here ...
  4855. bool rhs_transpose = rhs_e && rhs_e->need_transpose;
  4856. SPIRType write_type = type;
  4857. string cast_expr;
  4858. // We're dealing with transpose manually.
  4859. if (rhs_transpose)
  4860. rhs_e->need_transpose = false;
  4861. if (transpose)
  4862. {
  4863. // We're dealing with transpose manually.
  4864. lhs_e->need_transpose = false;
  4865. write_type.vecsize = type.columns;
  4866. write_type.columns = 1;
  4867. if (physical_type.columns != type.columns)
  4868. cast_expr = join("(", cast_addr_space, " ", packed_pfx, type_to_glsl(write_type), "&)");
  4869. if (rhs_transpose)
  4870. {
  4871. // If RHS is also transposed, we can just copy row by row.
  4872. for (uint32_t i = 0; i < type.vecsize; i++)
  4873. {
  4874. statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ",
  4875. to_unpacked_row_major_matrix_expression(rhs_expression), "[", i, "];");
  4876. }
  4877. }
  4878. else
  4879. {
  4880. auto vector_type = expression_type(rhs_expression);
  4881. vector_type.vecsize = vector_type.columns;
  4882. vector_type.columns = 1;
  4883. // Transpose on the fly. Emitting a lot of full transpose() ops and extracting lanes seems very bad,
  4884. // so pick out individual components instead.
  4885. for (uint32_t i = 0; i < type.vecsize; i++)
  4886. {
  4887. string rhs_row = type_to_glsl_constructor(vector_type) + "(";
  4888. for (uint32_t j = 0; j < vector_type.vecsize; j++)
  4889. {
  4890. rhs_row += join(to_enclosed_unpacked_expression(rhs_expression), "[", j, "][", i, "]");
  4891. if (j + 1 < vector_type.vecsize)
  4892. rhs_row += ", ";
  4893. }
  4894. rhs_row += ")";
  4895. statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ", rhs_row, ";");
  4896. }
  4897. }
  4898. // We're dealing with transpose manually.
  4899. lhs_e->need_transpose = true;
  4900. }
  4901. else
  4902. {
  4903. write_type.columns = 1;
  4904. if (physical_type.vecsize != type.vecsize)
  4905. cast_expr = join("(", cast_addr_space, " ", packed_pfx, type_to_glsl(write_type), "&)");
  4906. if (rhs_transpose)
  4907. {
  4908. auto vector_type = expression_type(rhs_expression);
  4909. vector_type.columns = 1;
  4910. // Transpose on the fly. Emitting a lot of full transpose() ops and extracting lanes seems very bad,
  4911. // so pick out individual components instead.
  4912. for (uint32_t i = 0; i < type.columns; i++)
  4913. {
  4914. string rhs_row = type_to_glsl_constructor(vector_type) + "(";
  4915. for (uint32_t j = 0; j < vector_type.vecsize; j++)
  4916. {
  4917. // Need to explicitly unpack expression since we've mucked with transpose state.
  4918. auto unpacked_expr = to_unpacked_row_major_matrix_expression(rhs_expression);
  4919. rhs_row += join(unpacked_expr, "[", j, "][", i, "]");
  4920. if (j + 1 < vector_type.vecsize)
  4921. rhs_row += ", ";
  4922. }
  4923. rhs_row += ")";
  4924. statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ", rhs_row, ";");
  4925. }
  4926. }
  4927. else
  4928. {
  4929. // Copy column-by-column.
  4930. for (uint32_t i = 0; i < type.columns; i++)
  4931. {
  4932. statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ",
  4933. to_enclosed_unpacked_expression(rhs_expression), "[", i, "];");
  4934. }
  4935. }
  4936. }
  4937. // We're dealing with transpose manually.
  4938. if (rhs_transpose)
  4939. rhs_e->need_transpose = true;
  4940. }
  4941. else if (transpose)
  4942. {
  4943. lhs_e->need_transpose = false;
  4944. SPIRType write_type = type;
  4945. write_type.vecsize = 1;
  4946. write_type.columns = 1;
  4947. // Storing a column to a row-major matrix. Unroll the write.
  4948. for (uint32_t c = 0; c < type.vecsize; c++)
  4949. {
  4950. auto lhs_expr = to_enclosed_expression(lhs_expression);
  4951. auto column_index = lhs_expr.find_last_of('[');
  4952. // Get rid of any ".data" half8 handling here, we're casting to scalar anyway.
  4953. auto end_column_index = lhs_expr.find_last_of(']');
  4954. auto end_dot_index = lhs_expr.find_last_of('.');
  4955. if (end_dot_index != string::npos && end_dot_index > end_column_index)
  4956. lhs_expr.resize(end_dot_index);
  4957. if (column_index != string::npos)
  4958. {
  4959. statement("((", cast_addr_space, " ", type_to_glsl(write_type), "*)&",
  4960. lhs_expr.insert(column_index, join('[', c, ']', ")")), " = ",
  4961. to_extract_component_expression(rhs_expression, c), ";");
  4962. }
  4963. }
  4964. lhs_e->need_transpose = true;
  4965. }
  4966. else if ((is_matrix(physical_type) || is_array(physical_type)) &&
  4967. physical_type.vecsize <= 4 &&
  4968. physical_type.vecsize > type.vecsize)
  4969. {
  4970. assert(type.vecsize >= 1 && type.vecsize <= 3);
  4971. // If we have packed types, we cannot use swizzled stores.
  4972. // We could technically unroll the store for each element if needed.
  4973. // When remapping to a std140 physical type, we always get float4,
  4974. // and the packed decoration should always be removed.
  4975. assert(!lhs_packed_type);
  4976. string lhs = to_dereferenced_expression(lhs_expression);
  4977. string rhs = to_pointer_expression(rhs_expression);
  4978. // Unpack the expression so we can store to it with a float or float2.
  4979. // It's still an l-value, so it's fine. Most other unpacking of expressions turn them into r-values instead.
  4980. lhs = join("(", cast_addr_space, " ", type_to_glsl(type), "&)", enclose_expression(lhs));
  4981. if (!optimize_read_modify_write(expression_type(rhs_expression), lhs, rhs))
  4982. statement(lhs, " = ", rhs, ";");
  4983. }
  4984. else if (!is_matrix(type))
  4985. {
  4986. string lhs = to_dereferenced_expression(lhs_expression);
  4987. string rhs = to_pointer_expression(rhs_expression);
  4988. if (!optimize_read_modify_write(expression_type(rhs_expression), lhs, rhs))
  4989. statement(lhs, " = ", rhs, ";");
  4990. }
  4991. register_write(lhs_expression);
  4992. }
  4993. }
  4994. static bool expression_ends_with(const string &expr_str, const std::string &ending)
  4995. {
  4996. if (expr_str.length() >= ending.length())
  4997. return (expr_str.compare(expr_str.length() - ending.length(), ending.length(), ending) == 0);
  4998. else
  4999. return false;
  5000. }
  5001. // Converts the format of the current expression from packed to unpacked,
  5002. // by wrapping the expression in a constructor of the appropriate type.
  5003. // Also, handle special physical ID remapping scenarios, similar to emit_store_statement().
  5004. string CompilerMSL::unpack_expression_type(string expr_str, const SPIRType &type, uint32_t physical_type_id,
  5005. bool packed, bool row_major)
  5006. {
  5007. // Trivial case, nothing to do.
  5008. if (physical_type_id == 0 && !packed)
  5009. return expr_str;
  5010. const SPIRType *physical_type = nullptr;
  5011. if (physical_type_id)
  5012. physical_type = &get<SPIRType>(physical_type_id);
  5013. static const char *swizzle_lut[] = {
  5014. ".x",
  5015. ".xy",
  5016. ".xyz",
  5017. "",
  5018. };
  5019. // TODO: Move everything to the template wrapper?
  5020. bool uses_std140_wrapper = physical_type && physical_type->vecsize > 4;
  5021. if (physical_type && is_vector(*physical_type) && is_array(*physical_type) &&
  5022. !uses_std140_wrapper &&
  5023. physical_type->vecsize > type.vecsize && !expression_ends_with(expr_str, swizzle_lut[type.vecsize - 1]))
  5024. {
  5025. // std140 array cases for vectors.
  5026. assert(type.vecsize >= 1 && type.vecsize <= 3);
  5027. return enclose_expression(expr_str) + swizzle_lut[type.vecsize - 1];
  5028. }
  5029. else if (physical_type && is_matrix(*physical_type) && is_vector(type) &&
  5030. !uses_std140_wrapper &&
  5031. physical_type->vecsize > type.vecsize)
  5032. {
  5033. // Extract column from padded matrix.
  5034. assert(type.vecsize >= 1 && type.vecsize <= 4);
  5035. return enclose_expression(expr_str) + swizzle_lut[type.vecsize - 1];
  5036. }
  5037. else if (is_matrix(type))
  5038. {
  5039. // Packed matrices are stored as arrays of packed vectors. Unfortunately,
  5040. // we can't just pass the array straight to the matrix constructor. We have to
  5041. // pass each vector individually, so that they can be unpacked to normal vectors.
  5042. if (!physical_type)
  5043. physical_type = &type;
  5044. uint32_t vecsize = type.vecsize;
  5045. uint32_t columns = type.columns;
  5046. if (row_major)
  5047. swap(vecsize, columns);
  5048. uint32_t physical_vecsize = row_major ? physical_type->columns : physical_type->vecsize;
  5049. const char *base_type = type.width == 16 ? "half" : "float";
  5050. string unpack_expr = join(base_type, columns, "x", vecsize, "(");
  5051. const char *load_swiz = "";
  5052. const char *data_swiz = physical_vecsize > 4 ? ".data" : "";
  5053. if (physical_vecsize != vecsize)
  5054. load_swiz = swizzle_lut[vecsize - 1];
  5055. for (uint32_t i = 0; i < columns; i++)
  5056. {
  5057. if (i > 0)
  5058. unpack_expr += ", ";
  5059. if (packed)
  5060. unpack_expr += join(base_type, physical_vecsize, "(", expr_str, "[", i, "]", ")", load_swiz);
  5061. else
  5062. unpack_expr += join(expr_str, "[", i, "]", data_swiz, load_swiz);
  5063. }
  5064. unpack_expr += ")";
  5065. return unpack_expr;
  5066. }
  5067. else
  5068. {
  5069. return join(type_to_glsl(type), "(", expr_str, ")");
  5070. }
  5071. }
  5072. // Emits the file header info
  5073. void CompilerMSL::emit_header()
  5074. {
  5075. // This particular line can be overridden during compilation, so make it a flag and not a pragma line.
  5076. if (suppress_missing_prototypes)
  5077. add_pragma_line("#pragma clang diagnostic ignored \"-Wmissing-prototypes\"", false);
  5078. if (suppress_incompatible_pointer_types_discard_qualifiers)
  5079. add_pragma_line("#pragma clang diagnostic ignored \"-Wincompatible-pointer-types-discards-qualifiers\"", false);
  5080. // Disable warning about "sometimes unitialized" when zero-initializing simple threadgroup variables
  5081. if (suppress_sometimes_unitialized)
  5082. add_pragma_line("#pragma clang diagnostic ignored \"-Wsometimes-uninitialized\"", false);
  5083. // Disable warning about missing braces for array<T> template to make arrays a value type
  5084. if (spv_function_implementations.count(SPVFuncImplUnsafeArray) != 0)
  5085. add_pragma_line("#pragma clang diagnostic ignored \"-Wmissing-braces\"", false);
  5086. // Floating point fast math compile declarations
  5087. if (msl_options.use_fast_math_pragmas && msl_options.supports_msl_version(3, 2))
  5088. {
  5089. uint32_t contract_mask = FPFastMathModeAllowContractMask;
  5090. uint32_t relax_mask = (FPFastMathModeNSZMask | FPFastMathModeAllowRecipMask | FPFastMathModeAllowReassocMask);
  5091. uint32_t fast_mask = (relax_mask | FPFastMathModeNotNaNMask | FPFastMathModeNotInfMask);
  5092. // FP math mode
  5093. uint32_t fp_flags = get_fp_fast_math_flags(true);
  5094. const char *math_mode = "safe";
  5095. if ((fp_flags & fast_mask) == fast_mask) // Must have all flags
  5096. math_mode = "fast";
  5097. else if ((fp_flags & relax_mask) == relax_mask) // Must have all flags
  5098. math_mode = "relaxed";
  5099. add_pragma_line(join("#pragma metal fp math_mode(", math_mode, ")"), false);
  5100. // FP contraction
  5101. const char *contract_mode = ((fp_flags & contract_mask) == contract_mask) ? "fast" : "off";
  5102. add_pragma_line(join("#pragma metal fp contract(", contract_mode, ")"), false);
  5103. }
  5104. for (auto &pragma : pragma_lines)
  5105. statement(pragma);
  5106. if (!pragma_lines.empty())
  5107. statement("");
  5108. statement("#include <metal_stdlib>");
  5109. statement("#include <simd/simd.h>");
  5110. for (auto &header : header_lines)
  5111. statement(header);
  5112. statement("");
  5113. statement("using namespace metal;");
  5114. statement("");
  5115. for (auto &td : typedef_lines)
  5116. statement(td);
  5117. if (!typedef_lines.empty())
  5118. statement("");
  5119. }
  5120. void CompilerMSL::add_pragma_line(const string &line, bool recompile_on_unique)
  5121. {
  5122. if (std::find(pragma_lines.begin(), pragma_lines.end(), line) == pragma_lines.end())
  5123. {
  5124. pragma_lines.push_back(line);
  5125. if (recompile_on_unique)
  5126. force_recompile();
  5127. }
  5128. }
  5129. void CompilerMSL::add_typedef_line(const string &line)
  5130. {
  5131. if (std::find(typedef_lines.begin(), typedef_lines.end(), line) == typedef_lines.end())
  5132. {
  5133. typedef_lines.push_back(line);
  5134. force_recompile();
  5135. }
  5136. }
  5137. // Template struct like spvUnsafeArray<> need to be declared *before* any resources are declared
  5138. void CompilerMSL::emit_custom_templates()
  5139. {
  5140. static const char * const address_spaces[] = {
  5141. "thread", "constant", "device", "threadgroup", "threadgroup_imageblock", "ray_data", "object_data"
  5142. };
  5143. for (const auto &spv_func : spv_function_implementations)
  5144. {
  5145. switch (spv_func)
  5146. {
  5147. case SPVFuncImplUnsafeArray:
  5148. statement("template<typename T, size_t Num>");
  5149. statement("struct spvUnsafeArray");
  5150. begin_scope();
  5151. statement("T elements[Num ? Num : 1];");
  5152. statement("");
  5153. statement("thread T& operator [] (size_t pos) thread");
  5154. begin_scope();
  5155. statement("return elements[pos];");
  5156. end_scope();
  5157. statement("constexpr const thread T& operator [] (size_t pos) const thread");
  5158. begin_scope();
  5159. statement("return elements[pos];");
  5160. end_scope();
  5161. statement("");
  5162. statement("device T& operator [] (size_t pos) device");
  5163. begin_scope();
  5164. statement("return elements[pos];");
  5165. end_scope();
  5166. statement("constexpr const device T& operator [] (size_t pos) const device");
  5167. begin_scope();
  5168. statement("return elements[pos];");
  5169. end_scope();
  5170. statement("");
  5171. statement("constexpr const constant T& operator [] (size_t pos) const constant");
  5172. begin_scope();
  5173. statement("return elements[pos];");
  5174. end_scope();
  5175. statement("");
  5176. statement("threadgroup T& operator [] (size_t pos) threadgroup");
  5177. begin_scope();
  5178. statement("return elements[pos];");
  5179. end_scope();
  5180. statement("constexpr const threadgroup T& operator [] (size_t pos) const threadgroup");
  5181. begin_scope();
  5182. statement("return elements[pos];");
  5183. end_scope();
  5184. if (get_execution_model() == ExecutionModelMeshEXT ||
  5185. get_execution_model() == ExecutionModelTaskEXT)
  5186. {
  5187. statement("");
  5188. statement("object_data T& operator [] (size_t pos) object_data");
  5189. begin_scope();
  5190. statement("return elements[pos];");
  5191. end_scope();
  5192. statement("constexpr const object_data T& operator [] (size_t pos) const object_data");
  5193. begin_scope();
  5194. statement("return elements[pos];");
  5195. end_scope();
  5196. }
  5197. end_scope_decl();
  5198. statement("");
  5199. break;
  5200. case SPVFuncImplStorageMatrix:
  5201. statement("template<typename T, int Cols, int Rows=Cols>");
  5202. statement("struct spvStorageMatrix");
  5203. begin_scope();
  5204. statement("vec<T, Rows> columns[Cols];");
  5205. statement("");
  5206. for (size_t method_idx = 0; method_idx < sizeof(address_spaces) / sizeof(address_spaces[0]); ++method_idx)
  5207. {
  5208. // Some address spaces require particular features.
  5209. if (method_idx == 4) // threadgroup_imageblock
  5210. statement("#ifdef __HAVE_IMAGEBLOCKS__");
  5211. else if (method_idx == 5) // ray_data
  5212. statement("#ifdef __HAVE_RAYTRACING__");
  5213. else if (method_idx == 6) // object_data
  5214. statement("#ifdef __HAVE_MESH__");
  5215. const string &method_as = address_spaces[method_idx];
  5216. statement("spvStorageMatrix() ", method_as, " = default;");
  5217. if (method_idx != 1) // constant
  5218. {
  5219. statement(method_as, " spvStorageMatrix& operator=(initializer_list<vec<T, Rows>> cols) ",
  5220. method_as);
  5221. begin_scope();
  5222. statement("size_t i;");
  5223. statement("thread vec<T, Rows>* col;");
  5224. statement("for (i = 0, col = cols.begin(); i < Cols; ++i, ++col)");
  5225. statement(" columns[i] = *col;");
  5226. statement("return *this;");
  5227. end_scope();
  5228. }
  5229. statement("");
  5230. for (size_t param_idx = 0; param_idx < sizeof(address_spaces) / sizeof(address_spaces[0]); ++param_idx)
  5231. {
  5232. if (param_idx != method_idx)
  5233. {
  5234. if (param_idx == 4) // threadgroup_imageblock
  5235. statement("#ifdef __HAVE_IMAGEBLOCKS__");
  5236. else if (param_idx == 5) // ray_data
  5237. statement("#ifdef __HAVE_RAYTRACING__");
  5238. else if (param_idx == 6) // object_data
  5239. statement("#ifdef __HAVE_MESH__");
  5240. }
  5241. const string &param_as = address_spaces[param_idx];
  5242. statement("spvStorageMatrix(const ", param_as, " matrix<T, Cols, Rows>& m) ", method_as);
  5243. begin_scope();
  5244. statement("for (size_t i = 0; i < Cols; ++i)");
  5245. statement(" columns[i] = m.columns[i];");
  5246. end_scope();
  5247. statement("spvStorageMatrix(const ", param_as, " spvStorageMatrix& m) ", method_as, " = default;");
  5248. if (method_idx != 1) // constant
  5249. {
  5250. statement(method_as, " spvStorageMatrix& operator=(const ", param_as,
  5251. " matrix<T, Cols, Rows>& m) ", method_as);
  5252. begin_scope();
  5253. statement("for (size_t i = 0; i < Cols; ++i)");
  5254. statement(" columns[i] = m.columns[i];");
  5255. statement("return *this;");
  5256. end_scope();
  5257. statement(method_as, " spvStorageMatrix& operator=(const ", param_as, " spvStorageMatrix& m) ",
  5258. method_as, " = default;");
  5259. }
  5260. if (param_idx != method_idx && param_idx >= 4)
  5261. statement("#endif");
  5262. statement("");
  5263. }
  5264. statement("operator matrix<T, Cols, Rows>() const ", method_as);
  5265. begin_scope();
  5266. statement("matrix<T, Cols, Rows> m;");
  5267. statement("for (int i = 0; i < Cols; ++i)");
  5268. statement(" m.columns[i] = columns[i];");
  5269. statement("return m;");
  5270. end_scope();
  5271. statement("");
  5272. statement("vec<T, Rows> operator[](size_t idx) const ", method_as);
  5273. begin_scope();
  5274. statement("return columns[idx];");
  5275. end_scope();
  5276. if (method_idx != 1) // constant
  5277. {
  5278. statement(method_as, " vec<T, Rows>& operator[](size_t idx) ", method_as);
  5279. begin_scope();
  5280. statement("return columns[idx];");
  5281. end_scope();
  5282. }
  5283. if (method_idx >= 4)
  5284. statement("#endif");
  5285. statement("");
  5286. }
  5287. end_scope_decl();
  5288. statement("");
  5289. statement("template<typename T, int Cols, int Rows>");
  5290. statement("matrix<T, Rows, Cols> transpose(spvStorageMatrix<T, Cols, Rows> m)");
  5291. begin_scope();
  5292. statement("return transpose(matrix<T, Cols, Rows>(m));");
  5293. end_scope();
  5294. statement("");
  5295. statement("typedef spvStorageMatrix<half, 2, 2> spvStorage_half2x2;");
  5296. statement("typedef spvStorageMatrix<half, 2, 3> spvStorage_half2x3;");
  5297. statement("typedef spvStorageMatrix<half, 2, 4> spvStorage_half2x4;");
  5298. statement("typedef spvStorageMatrix<half, 3, 2> spvStorage_half3x2;");
  5299. statement("typedef spvStorageMatrix<half, 3, 3> spvStorage_half3x3;");
  5300. statement("typedef spvStorageMatrix<half, 3, 4> spvStorage_half3x4;");
  5301. statement("typedef spvStorageMatrix<half, 4, 2> spvStorage_half4x2;");
  5302. statement("typedef spvStorageMatrix<half, 4, 3> spvStorage_half4x3;");
  5303. statement("typedef spvStorageMatrix<half, 4, 4> spvStorage_half4x4;");
  5304. statement("typedef spvStorageMatrix<float, 2, 2> spvStorage_float2x2;");
  5305. statement("typedef spvStorageMatrix<float, 2, 3> spvStorage_float2x3;");
  5306. statement("typedef spvStorageMatrix<float, 2, 4> spvStorage_float2x4;");
  5307. statement("typedef spvStorageMatrix<float, 3, 2> spvStorage_float3x2;");
  5308. statement("typedef spvStorageMatrix<float, 3, 3> spvStorage_float3x3;");
  5309. statement("typedef spvStorageMatrix<float, 3, 4> spvStorage_float3x4;");
  5310. statement("typedef spvStorageMatrix<float, 4, 2> spvStorage_float4x2;");
  5311. statement("typedef spvStorageMatrix<float, 4, 3> spvStorage_float4x3;");
  5312. statement("typedef spvStorageMatrix<float, 4, 4> spvStorage_float4x4;");
  5313. statement("");
  5314. break;
  5315. default:
  5316. break;
  5317. }
  5318. }
  5319. }
  5320. // Emits any needed custom function bodies.
  5321. // Metal helper functions must be static force-inline, i.e. static inline __attribute__((always_inline))
  5322. // otherwise they will cause problems when linked together in a single Metallib.
  5323. void CompilerMSL::emit_custom_functions()
  5324. {
  5325. // Use when outputting overloaded functions to cover different address spaces.
  5326. static const char *texture_addr_spaces[] = { "device", "constant", "thread" };
  5327. static uint32_t texture_addr_space_count = sizeof(texture_addr_spaces) / sizeof(char*);
  5328. if (spv_function_implementations.count(SPVFuncImplArrayCopyMultidim))
  5329. spv_function_implementations.insert(SPVFuncImplArrayCopy);
  5330. if (spv_function_implementations.count(SPVFuncImplDynamicImageSampler))
  5331. {
  5332. // Unfortunately, this one needs a lot of the other functions to compile OK.
  5333. if (!msl_options.supports_msl_version(2))
  5334. SPIRV_CROSS_THROW(
  5335. "spvDynamicImageSampler requires default-constructible texture objects, which require MSL 2.0.");
  5336. spv_function_implementations.insert(SPVFuncImplTextureSwizzle);
  5337. if (msl_options.swizzle_texture_samples)
  5338. spv_function_implementations.insert(SPVFuncImplGatherSwizzle);
  5339. for (uint32_t i = SPVFuncImplChromaReconstructNearest2Plane;
  5340. i <= SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane; i++)
  5341. spv_function_implementations.insert(static_cast<SPVFuncImpl>(i));
  5342. spv_function_implementations.insert(SPVFuncImplExpandITUFullRange);
  5343. spv_function_implementations.insert(SPVFuncImplExpandITUNarrowRange);
  5344. spv_function_implementations.insert(SPVFuncImplConvertYCbCrBT709);
  5345. spv_function_implementations.insert(SPVFuncImplConvertYCbCrBT601);
  5346. spv_function_implementations.insert(SPVFuncImplConvertYCbCrBT2020);
  5347. }
  5348. if (spv_function_implementations.count(SPVFuncImplGatherSwizzle) ||
  5349. spv_function_implementations.count(SPVFuncImplGatherConstOffsets))
  5350. {
  5351. spv_function_implementations.insert(SPVFuncImplGatherReturn);
  5352. }
  5353. if (spv_function_implementations.count(SPVFuncImplGatherCompareSwizzle) ||
  5354. spv_function_implementations.count(SPVFuncImplGatherCompareConstOffsets))
  5355. {
  5356. spv_function_implementations.insert(SPVFuncImplGatherCompareReturn);
  5357. }
  5358. if (spv_function_implementations.count(SPVFuncImplTextureSwizzle) ||
  5359. spv_function_implementations.count(SPVFuncImplGatherSwizzle) ||
  5360. spv_function_implementations.count(SPVFuncImplGatherCompareSwizzle))
  5361. {
  5362. spv_function_implementations.insert(SPVFuncImplGetSwizzle);
  5363. }
  5364. for (const auto &spv_func : spv_function_implementations)
  5365. {
  5366. switch (spv_func)
  5367. {
  5368. case SPVFuncImplSMod:
  5369. statement("// Implementation of signed integer mod accurate to SPIR-V specification");
  5370. statement("template<typename Tx, typename Ty>");
  5371. statement("inline Tx spvSMod(Tx x, Ty y)");
  5372. begin_scope();
  5373. statement("Tx remainder = x - y * (x / y);");
  5374. statement("return select(Tx(remainder + y), remainder, remainder == 0 || (x >= 0) == (y >= 0));");
  5375. end_scope();
  5376. statement("");
  5377. break;
  5378. case SPVFuncImplMod:
  5379. statement("// Implementation of the GLSL mod() function, which is slightly different than Metal fmod()");
  5380. statement("template<typename Tx, typename Ty>");
  5381. statement("inline Tx mod(Tx x, Ty y)");
  5382. begin_scope();
  5383. statement("return x - y * floor(x / y);");
  5384. end_scope();
  5385. statement("");
  5386. break;
  5387. case SPVFuncImplRadians:
  5388. statement("// Implementation of the GLSL radians() function");
  5389. statement("template<typename T>");
  5390. statement("inline T radians(T d)");
  5391. begin_scope();
  5392. statement("return d * T(0.01745329251);");
  5393. end_scope();
  5394. statement("");
  5395. break;
  5396. case SPVFuncImplDegrees:
  5397. statement("// Implementation of the GLSL degrees() function");
  5398. statement("template<typename T>");
  5399. statement("inline T degrees(T r)");
  5400. begin_scope();
  5401. statement("return r * T(57.2957795131);");
  5402. end_scope();
  5403. statement("");
  5404. break;
  5405. case SPVFuncImplFindILsb:
  5406. statement("// Implementation of the GLSL findLSB() function");
  5407. statement("template<typename T>");
  5408. statement("inline T spvFindLSB(T x)");
  5409. begin_scope();
  5410. statement("return select(ctz(x), T(-1), x == T(0));");
  5411. end_scope();
  5412. statement("");
  5413. break;
  5414. case SPVFuncImplFindUMsb:
  5415. statement("// Implementation of the unsigned GLSL findMSB() function");
  5416. statement("template<typename T>");
  5417. statement("inline T spvFindUMSB(T x)");
  5418. begin_scope();
  5419. statement("return select(clz(T(0)) - (clz(x) + T(1)), T(-1), x == T(0));");
  5420. end_scope();
  5421. statement("");
  5422. break;
  5423. case SPVFuncImplFindSMsb:
  5424. statement("// Implementation of the signed GLSL findMSB() function");
  5425. statement("template<typename T>");
  5426. statement("inline T spvFindSMSB(T x)");
  5427. begin_scope();
  5428. statement("T v = select(x, T(-1) - x, x < T(0));");
  5429. statement("return select(clz(T(0)) - (clz(v) + T(1)), T(-1), v == T(0));");
  5430. end_scope();
  5431. statement("");
  5432. break;
  5433. case SPVFuncImplSSign:
  5434. statement("// Implementation of the GLSL sign() function for integer types");
  5435. statement("template<typename T, typename E = typename enable_if<is_integral<T>::value>::type>");
  5436. statement("inline T sign(T x)");
  5437. begin_scope();
  5438. statement("return select(select(select(x, T(0), x == T(0)), T(1), x > T(0)), T(-1), x < T(0));");
  5439. end_scope();
  5440. statement("");
  5441. break;
  5442. case SPVFuncImplArrayCopy:
  5443. case SPVFuncImplArrayCopyMultidim:
  5444. {
  5445. // Unfortunately we cannot template on the address space, so combinatorial explosion it is.
  5446. static const char *function_name_tags[] = {
  5447. "FromConstantToStack", "FromConstantToThreadGroup", "FromStackToStack",
  5448. "FromStackToThreadGroup", "FromThreadGroupToStack", "FromThreadGroupToThreadGroup",
  5449. "FromDeviceToDevice", "FromConstantToDevice", "FromStackToDevice",
  5450. "FromThreadGroupToDevice", "FromDeviceToStack", "FromDeviceToThreadGroup",
  5451. };
  5452. static const char *src_address_space[] = {
  5453. "constant", "constant", "thread const", "thread const",
  5454. "threadgroup const", "threadgroup const", "device const", "constant",
  5455. "thread const", "threadgroup const", "device const", "device const",
  5456. };
  5457. static const char *dst_address_space[] = {
  5458. "thread", "threadgroup", "thread", "threadgroup", "thread", "threadgroup",
  5459. "device", "device", "device", "device", "thread", "threadgroup",
  5460. };
  5461. static const bool src_is_physical_with_mismatch[] = {
  5462. true, true, false,
  5463. false, false, false,
  5464. false, false, false,
  5465. false, true, true,
  5466. };
  5467. static const bool dst_is_physical_with_mismatch[] = {
  5468. false, false, false,
  5469. false, false, false,
  5470. false, false, true,
  5471. true, false, false,
  5472. };
  5473. for (uint32_t variant = 0; variant < 12; variant++)
  5474. {
  5475. assert(!src_is_physical_with_mismatch[variant] || !dst_is_physical_with_mismatch[variant]);
  5476. bool is_multidim = spv_func == SPVFuncImplArrayCopyMultidim;
  5477. const char *dim = is_multidim ? "[N][M]" : "[N]";
  5478. // Simple base case.
  5479. statement("template<typename T, uint N", is_multidim ? ", uint M>" : ">");
  5480. statement("inline void spvArrayCopy", function_name_tags[variant], "(",
  5481. dst_address_space[variant], " T (&dst)", dim, ", ",
  5482. src_address_space[variant], " T (&src)", dim, ")");
  5483. begin_scope();
  5484. statement("for (uint i = 0; i < N; i++)");
  5485. begin_scope();
  5486. if (is_multidim)
  5487. statement("spvArrayCopy", function_name_tags[variant], "(dst[i], src[i]);");
  5488. else
  5489. statement("dst[i] = src[i];");
  5490. end_scope();
  5491. end_scope();
  5492. if (spv_function_implementations.count(SPVFuncImplArrayCopyExtendedSrc) &&
  5493. src_is_physical_with_mismatch[variant])
  5494. {
  5495. // 1st overload, src can be magic vector where dst is a scalar.
  5496. // Need reinterpret casts to be memory model correct. LLVM vectors are broken otherwise.
  5497. statement("template<typename T, uint V, uint N", is_multidim ? ", uint M>" : ">");
  5498. statement("inline void spvArrayCopy", function_name_tags[variant], "(",
  5499. dst_address_space[variant], " T (&dst)", dim, ", ",
  5500. src_address_space[variant], " vec<T, V> (&src)", dim, ")");
  5501. begin_scope();
  5502. statement("for (uint i = 0; i < N; i++)");
  5503. begin_scope();
  5504. if (is_multidim)
  5505. statement("spvArrayCopy", function_name_tags[variant], "(dst[i], src[i]);");
  5506. else
  5507. statement("dst[i] = reinterpret_cast<", src_address_space[variant], " T &>(src[i]);");
  5508. end_scope();
  5509. end_scope();
  5510. statement("");
  5511. // 2nd overload, both are vectors, but need SFINAE magic to avoid ambiguous case.
  5512. statement("template<typename T, uint Vdst, uint Vsrc, uint N", is_multidim ? ", uint M>" : ">");
  5513. statement("inline enable_if_t<Vdst != Vsrc> spvArrayCopy", function_name_tags[variant], "(",
  5514. dst_address_space[variant], " vec<T, Vdst> (&dst)", dim, ", ",
  5515. src_address_space[variant], " vec<T, Vsrc> (&src)", dim, ")");
  5516. begin_scope();
  5517. statement("for (uint i = 0; i < N; i++)");
  5518. begin_scope();
  5519. if (is_multidim)
  5520. statement("spvArrayCopy", function_name_tags[variant], "(dst[i], src[i]);");
  5521. else
  5522. statement("dst[i] = reinterpret_cast<", src_address_space[variant], " vec<T, Vdst> &>(src[i]);");
  5523. end_scope();
  5524. end_scope();
  5525. }
  5526. if (spv_function_implementations.count(SPVFuncImplArrayCopyExtendedDst) &&
  5527. dst_is_physical_with_mismatch[variant])
  5528. {
  5529. // 1st overload, src can be magic vector where dst is a scalar.
  5530. // Need reinterpret casts to be memory model correct. LLVM vectors are broken otherwise.
  5531. statement("template<typename T, uint V, uint N", is_multidim ? ", uint M>" : ">");
  5532. statement("inline void spvArrayCopy", function_name_tags[variant], "(",
  5533. dst_address_space[variant], " vec<T, V> (&dst)", dim, ", ",
  5534. src_address_space[variant], " T (&src)", dim, ")");
  5535. begin_scope();
  5536. statement("for (uint i = 0; i < N; i++)");
  5537. begin_scope();
  5538. if (is_multidim)
  5539. statement("spvArrayCopy", function_name_tags[variant], "(dst[i], src[i]);");
  5540. else
  5541. statement("reinterpret_cast<", dst_address_space[variant], " T &>(dst[i]) = src[i];");
  5542. end_scope();
  5543. end_scope();
  5544. statement("");
  5545. // 2nd overload, both are vectors, but need SFINAE magic to avoid ambiguous case.
  5546. statement("template<typename T, uint Vdst, uint Vsrc, uint N", is_multidim ? ", uint M>" : ">");
  5547. statement("inline enable_if_t<Vdst != Vsrc> spvArrayCopy", function_name_tags[variant], "(",
  5548. dst_address_space[variant], " vec<T, Vdst> (&dst)", dim, ", ",
  5549. src_address_space[variant], " vec<T, Vsrc> (&src)", dim, ")");
  5550. begin_scope();
  5551. statement("for (uint i = 0; i < N; i++)");
  5552. begin_scope();
  5553. if (is_multidim)
  5554. statement("spvArrayCopy", function_name_tags[variant], "(dst[i], src[i]);");
  5555. else
  5556. statement("reinterpret_cast<", dst_address_space[variant], " vec<T, Vsrc> &>(dst[i]) = src[i];");
  5557. end_scope();
  5558. end_scope();
  5559. }
  5560. statement("");
  5561. }
  5562. break;
  5563. }
  5564. // Support for Metal 2.1's new texture_buffer type.
  5565. case SPVFuncImplTexelBufferCoords:
  5566. {
  5567. if (msl_options.texel_buffer_texture_width > 0)
  5568. {
  5569. string tex_width_str = convert_to_string(msl_options.texel_buffer_texture_width);
  5570. statement("// Returns 2D texture coords corresponding to 1D texel buffer coords");
  5571. statement(force_inline);
  5572. statement("uint2 spvTexelBufferCoord(uint tc)");
  5573. begin_scope();
  5574. statement(join("return uint2(tc % ", tex_width_str, ", tc / ", tex_width_str, ");"));
  5575. end_scope();
  5576. statement("");
  5577. }
  5578. else
  5579. {
  5580. statement("// Returns 2D texture coords corresponding to 1D texel buffer coords");
  5581. statement(
  5582. "#define spvTexelBufferCoord(tc, tex) uint2((tc) % (tex).get_width(), (tc) / (tex).get_width())");
  5583. statement("");
  5584. }
  5585. break;
  5586. }
  5587. // Emulate texture2D atomic operations
  5588. case SPVFuncImplImage2DAtomicCoords:
  5589. {
  5590. if (msl_options.supports_msl_version(1, 2))
  5591. {
  5592. statement("// The required alignment of a linear texture of R32Uint format.");
  5593. statement("constant uint spvLinearTextureAlignmentOverride [[function_constant(",
  5594. msl_options.r32ui_alignment_constant_id, ")]];");
  5595. statement("constant uint spvLinearTextureAlignment = ",
  5596. "is_function_constant_defined(spvLinearTextureAlignmentOverride) ? ",
  5597. "spvLinearTextureAlignmentOverride : ", msl_options.r32ui_linear_texture_alignment, ";");
  5598. }
  5599. else
  5600. {
  5601. statement("// The required alignment of a linear texture of R32Uint format.");
  5602. statement("constant uint spvLinearTextureAlignment = ", msl_options.r32ui_linear_texture_alignment,
  5603. ";");
  5604. }
  5605. statement("// Returns buffer coords corresponding to 2D texture coords for emulating 2D texture atomics");
  5606. statement("#define spvImage2DAtomicCoord(tc, tex) (((((tex).get_width() + ",
  5607. " spvLinearTextureAlignment / 4 - 1) & ~(",
  5608. " spvLinearTextureAlignment / 4 - 1)) * (tc).y) + (tc).x)");
  5609. statement("");
  5610. break;
  5611. }
  5612. // Fix up gradient vectors when sampling a cube texture for Apple Silicon.
  5613. // h/t Alexey Knyazev (https://github.com/KhronosGroup/MoltenVK/issues/2068#issuecomment-1817799067) for the code.
  5614. case SPVFuncImplGradientCube:
  5615. statement("static inline gradientcube spvGradientCube(float3 P, float3 dPdx, float3 dPdy)");
  5616. begin_scope();
  5617. statement("// Major axis selection");
  5618. statement("float3 absP = abs(P);");
  5619. statement("bool xMajor = absP.x >= max(absP.y, absP.z);");
  5620. statement("bool yMajor = absP.y >= absP.z;");
  5621. statement("float3 Q = xMajor ? P.yzx : (yMajor ? P.xzy : P);");
  5622. statement("float3 dQdx = xMajor ? dPdx.yzx : (yMajor ? dPdx.xzy : dPdx);");
  5623. statement("float3 dQdy = xMajor ? dPdy.yzx : (yMajor ? dPdy.xzy : dPdy);");
  5624. statement_no_indent("");
  5625. statement("// Skip a couple of operations compared to usual projection");
  5626. statement("float4 d = float4(dQdx.xy, dQdy.xy) - (Q.xy / Q.z).xyxy * float4(dQdx.zz, dQdy.zz);");
  5627. statement_no_indent("");
  5628. statement("// Final swizzle to put the intermediate values into non-ignored components");
  5629. statement("// X major: X and Z");
  5630. statement("// Y major: X and Y");
  5631. statement("// Z major: Y and Z");
  5632. statement("return gradientcube(xMajor ? d.xxy : d.xyx, xMajor ? d.zzw : d.zwz);");
  5633. end_scope();
  5634. statement("");
  5635. break;
  5636. // "fadd" intrinsic support
  5637. case SPVFuncImplFAdd:
  5638. statement("template<typename T>");
  5639. statement("[[clang::optnone]] T spvFAdd(T l, T r)");
  5640. begin_scope();
  5641. statement("return fma(T(1), l, r);");
  5642. end_scope();
  5643. statement("");
  5644. break;
  5645. // "fsub" intrinsic support
  5646. case SPVFuncImplFSub:
  5647. statement("template<typename T>");
  5648. statement("[[clang::optnone]] T spvFSub(T l, T r)");
  5649. begin_scope();
  5650. statement("return fma(T(-1), r, l);");
  5651. end_scope();
  5652. statement("");
  5653. break;
  5654. // "fmul' intrinsic support
  5655. case SPVFuncImplFMul:
  5656. statement("template<typename T>");
  5657. statement("[[clang::optnone]] T spvFMul(T l, T r)");
  5658. begin_scope();
  5659. statement("return fma(l, r, T(0));");
  5660. end_scope();
  5661. statement("");
  5662. statement("template<typename T, int Cols, int Rows>");
  5663. statement("[[clang::optnone]] vec<T, Cols> spvFMulVectorMatrix(vec<T, Rows> v, matrix<T, Cols, Rows> m)");
  5664. begin_scope();
  5665. statement("vec<T, Cols> res = vec<T, Cols>(0);");
  5666. statement("for (uint i = Rows; i > 0; --i)");
  5667. begin_scope();
  5668. statement("vec<T, Cols> tmp(0);");
  5669. statement("for (uint j = 0; j < Cols; ++j)");
  5670. begin_scope();
  5671. statement("tmp[j] = m[j][i - 1];");
  5672. end_scope();
  5673. statement("res = fma(tmp, vec<T, Cols>(v[i - 1]), res);");
  5674. end_scope();
  5675. statement("return res;");
  5676. end_scope();
  5677. statement("");
  5678. statement("template<typename T, int Cols, int Rows>");
  5679. statement("[[clang::optnone]] vec<T, Rows> spvFMulMatrixVector(matrix<T, Cols, Rows> m, vec<T, Cols> v)");
  5680. begin_scope();
  5681. statement("vec<T, Rows> res = vec<T, Rows>(0);");
  5682. statement("for (uint i = Cols; i > 0; --i)");
  5683. begin_scope();
  5684. statement("res = fma(m[i - 1], vec<T, Rows>(v[i - 1]), res);");
  5685. end_scope();
  5686. statement("return res;");
  5687. end_scope();
  5688. statement("");
  5689. statement("template<typename T, int LCols, int LRows, int RCols, int RRows>");
  5690. statement("[[clang::optnone]] matrix<T, RCols, LRows> spvFMulMatrixMatrix(matrix<T, LCols, LRows> l, matrix<T, RCols, RRows> r)");
  5691. begin_scope();
  5692. statement("matrix<T, RCols, LRows> res;");
  5693. statement("for (uint i = 0; i < RCols; i++)");
  5694. begin_scope();
  5695. statement("vec<T, RCols> tmp(0);");
  5696. statement("for (uint j = 0; j < LCols; j++)");
  5697. begin_scope();
  5698. statement("tmp = fma(vec<T, RCols>(r[i][j]), l[j], tmp);");
  5699. end_scope();
  5700. statement("res[i] = tmp;");
  5701. end_scope();
  5702. statement("return res;");
  5703. end_scope();
  5704. statement("");
  5705. break;
  5706. case SPVFuncImplQuantizeToF16:
  5707. // Ensure fast-math is disabled to match Vulkan results.
  5708. // SpvHalfTypeSelector is used to match the half* template type to the float* template type.
  5709. // Depending on GPU, MSL does not always flush converted subnormal halfs to zero,
  5710. // as required by OpQuantizeToF16, so check for subnormals and flush them to zero.
  5711. statement("template <typename F> struct SpvHalfTypeSelector;");
  5712. statement("template <> struct SpvHalfTypeSelector<float> { public: using H = half; };");
  5713. statement("template<uint N> struct SpvHalfTypeSelector<vec<float, N>> { using H = vec<half, N>; };");
  5714. statement("template<typename F, typename H = typename SpvHalfTypeSelector<F>::H>");
  5715. statement("[[clang::optnone]] F spvQuantizeToF16(F fval)");
  5716. begin_scope();
  5717. statement("H hval = H(fval);");
  5718. statement("hval = select(copysign(H(0), hval), hval, isnormal(hval) || isinf(hval) || isnan(hval));");
  5719. statement("return F(hval);");
  5720. end_scope();
  5721. statement("");
  5722. break;
  5723. // Emulate texturecube_array with texture2d_array for iOS where this type is not available
  5724. case SPVFuncImplCubemapTo2DArrayFace:
  5725. statement(force_inline);
  5726. statement("float3 spvCubemapTo2DArrayFace(float3 P)");
  5727. begin_scope();
  5728. statement("float3 Coords = abs(P.xyz);");
  5729. statement("float CubeFace = 0;");
  5730. statement("float ProjectionAxis = 0;");
  5731. statement("float u = 0;");
  5732. statement("float v = 0;");
  5733. statement("if (Coords.x >= Coords.y && Coords.x >= Coords.z)");
  5734. begin_scope();
  5735. statement("CubeFace = P.x >= 0 ? 0 : 1;");
  5736. statement("ProjectionAxis = Coords.x;");
  5737. statement("u = P.x >= 0 ? -P.z : P.z;");
  5738. statement("v = -P.y;");
  5739. end_scope();
  5740. statement("else if (Coords.y >= Coords.x && Coords.y >= Coords.z)");
  5741. begin_scope();
  5742. statement("CubeFace = P.y >= 0 ? 2 : 3;");
  5743. statement("ProjectionAxis = Coords.y;");
  5744. statement("u = P.x;");
  5745. statement("v = P.y >= 0 ? P.z : -P.z;");
  5746. end_scope();
  5747. statement("else");
  5748. begin_scope();
  5749. statement("CubeFace = P.z >= 0 ? 4 : 5;");
  5750. statement("ProjectionAxis = Coords.z;");
  5751. statement("u = P.z >= 0 ? P.x : -P.x;");
  5752. statement("v = -P.y;");
  5753. end_scope();
  5754. statement("u = 0.5 * (u/ProjectionAxis + 1);");
  5755. statement("v = 0.5 * (v/ProjectionAxis + 1);");
  5756. statement("return float3(u, v, CubeFace);");
  5757. end_scope();
  5758. statement("");
  5759. break;
  5760. case SPVFuncImplInverse4x4:
  5761. statement("// Returns the determinant of a 2x2 matrix.");
  5762. statement(force_inline);
  5763. statement("float spvDet2x2(float a1, float a2, float b1, float b2)");
  5764. begin_scope();
  5765. statement("return a1 * b2 - b1 * a2;");
  5766. end_scope();
  5767. statement("");
  5768. statement("// Returns the determinant of a 3x3 matrix.");
  5769. statement(force_inline);
  5770. statement("float spvDet3x3(float a1, float a2, float a3, float b1, float b2, float b3, float c1, "
  5771. "float c2, float c3)");
  5772. begin_scope();
  5773. statement("return a1 * spvDet2x2(b2, b3, c2, c3) - b1 * spvDet2x2(a2, a3, c2, c3) + c1 * spvDet2x2(a2, a3, "
  5774. "b2, b3);");
  5775. end_scope();
  5776. statement("");
  5777. statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
  5778. statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
  5779. statement(force_inline);
  5780. statement("float4x4 spvInverse4x4(float4x4 m)");
  5781. begin_scope();
  5782. statement("float4x4 adj; // The adjoint matrix (inverse after dividing by determinant)");
  5783. statement_no_indent("");
  5784. statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
  5785. statement("adj[0][0] = spvDet3x3(m[1][1], m[1][2], m[1][3], m[2][1], m[2][2], m[2][3], m[3][1], m[3][2], "
  5786. "m[3][3]);");
  5787. statement("adj[0][1] = -spvDet3x3(m[0][1], m[0][2], m[0][3], m[2][1], m[2][2], m[2][3], m[3][1], m[3][2], "
  5788. "m[3][3]);");
  5789. statement("adj[0][2] = spvDet3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2], m[1][3], m[3][1], m[3][2], "
  5790. "m[3][3]);");
  5791. statement("adj[0][3] = -spvDet3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2], m[1][3], m[2][1], m[2][2], "
  5792. "m[2][3]);");
  5793. statement_no_indent("");
  5794. statement("adj[1][0] = -spvDet3x3(m[1][0], m[1][2], m[1][3], m[2][0], m[2][2], m[2][3], m[3][0], m[3][2], "
  5795. "m[3][3]);");
  5796. statement("adj[1][1] = spvDet3x3(m[0][0], m[0][2], m[0][3], m[2][0], m[2][2], m[2][3], m[3][0], m[3][2], "
  5797. "m[3][3]);");
  5798. statement("adj[1][2] = -spvDet3x3(m[0][0], m[0][2], m[0][3], m[1][0], m[1][2], m[1][3], m[3][0], m[3][2], "
  5799. "m[3][3]);");
  5800. statement("adj[1][3] = spvDet3x3(m[0][0], m[0][2], m[0][3], m[1][0], m[1][2], m[1][3], m[2][0], m[2][2], "
  5801. "m[2][3]);");
  5802. statement_no_indent("");
  5803. statement("adj[2][0] = spvDet3x3(m[1][0], m[1][1], m[1][3], m[2][0], m[2][1], m[2][3], m[3][0], m[3][1], "
  5804. "m[3][3]);");
  5805. statement("adj[2][1] = -spvDet3x3(m[0][0], m[0][1], m[0][3], m[2][0], m[2][1], m[2][3], m[3][0], m[3][1], "
  5806. "m[3][3]);");
  5807. statement("adj[2][2] = spvDet3x3(m[0][0], m[0][1], m[0][3], m[1][0], m[1][1], m[1][3], m[3][0], m[3][1], "
  5808. "m[3][3]);");
  5809. statement("adj[2][3] = -spvDet3x3(m[0][0], m[0][1], m[0][3], m[1][0], m[1][1], m[1][3], m[2][0], m[2][1], "
  5810. "m[2][3]);");
  5811. statement_no_indent("");
  5812. statement("adj[3][0] = -spvDet3x3(m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2], m[3][0], m[3][1], "
  5813. "m[3][2]);");
  5814. statement("adj[3][1] = spvDet3x3(m[0][0], m[0][1], m[0][2], m[2][0], m[2][1], m[2][2], m[3][0], m[3][1], "
  5815. "m[3][2]);");
  5816. statement("adj[3][2] = -spvDet3x3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[3][0], m[3][1], "
  5817. "m[3][2]);");
  5818. statement("adj[3][3] = spvDet3x3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], "
  5819. "m[2][2]);");
  5820. statement_no_indent("");
  5821. statement("// Calculate the determinant as a combination of the cofactors of the first row.");
  5822. statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]) + (adj[0][2] * m[2][0]) + (adj[0][3] "
  5823. "* m[3][0]);");
  5824. statement_no_indent("");
  5825. statement("// Divide the classical adjoint matrix by the determinant.");
  5826. statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
  5827. statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
  5828. end_scope();
  5829. statement("");
  5830. break;
  5831. case SPVFuncImplInverse3x3:
  5832. if (spv_function_implementations.count(SPVFuncImplInverse4x4) == 0)
  5833. {
  5834. statement("// Returns the determinant of a 2x2 matrix.");
  5835. statement(force_inline);
  5836. statement("float spvDet2x2(float a1, float a2, float b1, float b2)");
  5837. begin_scope();
  5838. statement("return a1 * b2 - b1 * a2;");
  5839. end_scope();
  5840. statement("");
  5841. }
  5842. statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
  5843. statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
  5844. statement(force_inline);
  5845. statement("float3x3 spvInverse3x3(float3x3 m)");
  5846. begin_scope();
  5847. statement("float3x3 adj; // The adjoint matrix (inverse after dividing by determinant)");
  5848. statement_no_indent("");
  5849. statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
  5850. statement("adj[0][0] = spvDet2x2(m[1][1], m[1][2], m[2][1], m[2][2]);");
  5851. statement("adj[0][1] = -spvDet2x2(m[0][1], m[0][2], m[2][1], m[2][2]);");
  5852. statement("adj[0][2] = spvDet2x2(m[0][1], m[0][2], m[1][1], m[1][2]);");
  5853. statement_no_indent("");
  5854. statement("adj[1][0] = -spvDet2x2(m[1][0], m[1][2], m[2][0], m[2][2]);");
  5855. statement("adj[1][1] = spvDet2x2(m[0][0], m[0][2], m[2][0], m[2][2]);");
  5856. statement("adj[1][2] = -spvDet2x2(m[0][0], m[0][2], m[1][0], m[1][2]);");
  5857. statement_no_indent("");
  5858. statement("adj[2][0] = spvDet2x2(m[1][0], m[1][1], m[2][0], m[2][1]);");
  5859. statement("adj[2][1] = -spvDet2x2(m[0][0], m[0][1], m[2][0], m[2][1]);");
  5860. statement("adj[2][2] = spvDet2x2(m[0][0], m[0][1], m[1][0], m[1][1]);");
  5861. statement_no_indent("");
  5862. statement("// Calculate the determinant as a combination of the cofactors of the first row.");
  5863. statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]) + (adj[0][2] * m[2][0]);");
  5864. statement_no_indent("");
  5865. statement("// Divide the classical adjoint matrix by the determinant.");
  5866. statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
  5867. statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
  5868. end_scope();
  5869. statement("");
  5870. break;
  5871. case SPVFuncImplInverse2x2:
  5872. statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
  5873. statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
  5874. statement(force_inline);
  5875. statement("float2x2 spvInverse2x2(float2x2 m)");
  5876. begin_scope();
  5877. statement("float2x2 adj; // The adjoint matrix (inverse after dividing by determinant)");
  5878. statement_no_indent("");
  5879. statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
  5880. statement("adj[0][0] = m[1][1];");
  5881. statement("adj[0][1] = -m[0][1];");
  5882. statement_no_indent("");
  5883. statement("adj[1][0] = -m[1][0];");
  5884. statement("adj[1][1] = m[0][0];");
  5885. statement_no_indent("");
  5886. statement("// Calculate the determinant as a combination of the cofactors of the first row.");
  5887. statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]);");
  5888. statement_no_indent("");
  5889. statement("// Divide the classical adjoint matrix by the determinant.");
  5890. statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
  5891. statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
  5892. end_scope();
  5893. statement("");
  5894. break;
  5895. case SPVFuncImplGetSwizzle:
  5896. statement("enum class spvSwizzle : uint");
  5897. begin_scope();
  5898. statement("none = 0,");
  5899. statement("zero,");
  5900. statement("one,");
  5901. statement("red,");
  5902. statement("green,");
  5903. statement("blue,");
  5904. statement("alpha");
  5905. end_scope_decl();
  5906. statement("");
  5907. statement("template<typename T>");
  5908. statement("inline T spvGetSwizzle(vec<T, 4> x, T c, spvSwizzle s)");
  5909. begin_scope();
  5910. statement("switch (s)");
  5911. begin_scope();
  5912. statement("case spvSwizzle::none:");
  5913. statement(" return c;");
  5914. statement("case spvSwizzle::zero:");
  5915. statement(" return 0;");
  5916. statement("case spvSwizzle::one:");
  5917. statement(" return 1;");
  5918. statement("case spvSwizzle::red:");
  5919. statement(" return x.r;");
  5920. statement("case spvSwizzle::green:");
  5921. statement(" return x.g;");
  5922. statement("case spvSwizzle::blue:");
  5923. statement(" return x.b;");
  5924. statement("case spvSwizzle::alpha:");
  5925. statement(" return x.a;");
  5926. end_scope();
  5927. end_scope();
  5928. statement("");
  5929. break;
  5930. case SPVFuncImplTextureSwizzle:
  5931. statement("// Wrapper function that swizzles texture samples and fetches.");
  5932. statement("template<typename T>");
  5933. statement("inline vec<T, 4> spvTextureSwizzle(vec<T, 4> x, uint s)");
  5934. begin_scope();
  5935. statement("if (!s)");
  5936. statement(" return x;");
  5937. statement("return vec<T, 4>(spvGetSwizzle(x, x.r, spvSwizzle((s >> 0) & 0xFF)), "
  5938. "spvGetSwizzle(x, x.g, spvSwizzle((s >> 8) & 0xFF)), spvGetSwizzle(x, x.b, spvSwizzle((s >> 16) "
  5939. "& 0xFF)), "
  5940. "spvGetSwizzle(x, x.a, spvSwizzle((s >> 24) & 0xFF)));");
  5941. end_scope();
  5942. statement("");
  5943. statement("template<typename T>");
  5944. statement("inline T spvTextureSwizzle(T x, uint s)");
  5945. begin_scope();
  5946. statement("return spvTextureSwizzle(vec<T, 4>(x, 0, 0, 1), s).x;");
  5947. end_scope();
  5948. statement("");
  5949. break;
  5950. case SPVFuncImplGatherReturn:
  5951. statement("template<typename Tex, typename... Tp>");
  5952. statement("using spvGatherReturn = decltype(declval<Tex>().gather(declval<sampler>(), declval<Tp>()...));");
  5953. statement("");
  5954. break;
  5955. case SPVFuncImplGatherCompareReturn:
  5956. statement("template<typename Tex, typename... Tp>");
  5957. statement("using spvGatherCompareReturn = decltype(declval<Tex>().gather_compare(declval<sampler>(), declval<Tp>()...));");
  5958. statement("");
  5959. break;
  5960. case SPVFuncImplGatherSwizzle:
  5961. statement("// Wrapper function that swizzles texture gathers.");
  5962. statement("template<typename Tex, typename... Ts>");
  5963. statement("inline spvGatherReturn<Tex, Ts...> spvGatherSwizzle(const thread Tex& t, sampler s, "
  5964. "uint sw, component c, Ts... params) METAL_CONST_ARG(c)");
  5965. begin_scope();
  5966. statement("if (sw)");
  5967. begin_scope();
  5968. statement("switch (spvSwizzle((sw >> (uint(c) * 8)) & 0xFF))");
  5969. begin_scope();
  5970. statement("case spvSwizzle::none:");
  5971. statement(" break;");
  5972. statement("case spvSwizzle::zero:");
  5973. statement(" return spvGatherReturn<Tex, Ts...>(0, 0, 0, 0);");
  5974. statement("case spvSwizzle::one:");
  5975. statement(" return spvGatherReturn<Tex, Ts...>(1, 1, 1, 1);");
  5976. statement("case spvSwizzle::red:");
  5977. statement(" return t.gather(s, params..., component::x);");
  5978. statement("case spvSwizzle::green:");
  5979. statement(" return t.gather(s, params..., component::y);");
  5980. statement("case spvSwizzle::blue:");
  5981. statement(" return t.gather(s, params..., component::z);");
  5982. statement("case spvSwizzle::alpha:");
  5983. statement(" return t.gather(s, params..., component::w);");
  5984. end_scope();
  5985. end_scope();
  5986. // texture::gather insists on its component parameter being a constant
  5987. // expression, so we need this silly workaround just to compile the shader.
  5988. statement("switch (c)");
  5989. begin_scope();
  5990. statement("case component::x:");
  5991. statement(" return t.gather(s, params..., component::x);");
  5992. statement("case component::y:");
  5993. statement(" return t.gather(s, params..., component::y);");
  5994. statement("case component::z:");
  5995. statement(" return t.gather(s, params..., component::z);");
  5996. statement("case component::w:");
  5997. statement(" return t.gather(s, params..., component::w);");
  5998. end_scope();
  5999. end_scope();
  6000. statement("");
  6001. break;
  6002. case SPVFuncImplGatherCompareSwizzle:
  6003. statement("// Wrapper function that swizzles depth texture gathers.");
  6004. statement("template<typename Tex, typename... Ts>");
  6005. statement("inline spvGatherCompareReturn<Tex, Ts...> spvGatherCompareSwizzle(const thread Tex& t, sampler s, uint sw, Ts... params)");
  6006. begin_scope();
  6007. statement("if (sw)");
  6008. begin_scope();
  6009. statement("switch (spvSwizzle(sw & 0xFF))");
  6010. begin_scope();
  6011. statement("case spvSwizzle::none:");
  6012. statement("case spvSwizzle::red:");
  6013. statement(" break;");
  6014. statement("case spvSwizzle::zero:");
  6015. statement("case spvSwizzle::green:");
  6016. statement("case spvSwizzle::blue:");
  6017. statement("case spvSwizzle::alpha:");
  6018. statement(" return spvGatherCompareReturn<Tex, Ts...>(0, 0, 0, 0);");
  6019. statement("case spvSwizzle::one:");
  6020. statement(" return spvGatherCompareReturn<Tex, Ts...>(1, 1, 1, 1);");
  6021. end_scope();
  6022. end_scope();
  6023. statement("return t.gather_compare(s, params...);");
  6024. end_scope();
  6025. statement("");
  6026. break;
  6027. case SPVFuncImplGatherConstOffsets:
  6028. // Because we are passing a texture reference, we have to output an overloaded version of this function for each address space.
  6029. for (uint32_t i = 0; i < texture_addr_space_count; i++)
  6030. {
  6031. statement("// Wrapper function that processes a ", texture_addr_spaces[i], " texture gather with a constant offset array.");
  6032. statement("template<typename Tex, typename Toff, typename... Tp>");
  6033. statement("inline spvGatherReturn<Tex, Tp...> spvGatherConstOffsets(const ", texture_addr_spaces[i], " Tex& t, sampler s, "
  6034. "Toff coffsets, component c, Tp... params) METAL_CONST_ARG(c)");
  6035. begin_scope();
  6036. statement("spvGatherReturn<Tex, Tp...> rslts[4];");
  6037. statement("for (uint i = 0; i < 4; i++)");
  6038. begin_scope();
  6039. statement("switch (c)");
  6040. begin_scope();
  6041. // Work around texture::gather() requiring its component parameter to be a constant expression
  6042. statement("case component::x:");
  6043. statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::x);");
  6044. statement(" break;");
  6045. statement("case component::y:");
  6046. statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::y);");
  6047. statement(" break;");
  6048. statement("case component::z:");
  6049. statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::z);");
  6050. statement(" break;");
  6051. statement("case component::w:");
  6052. statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::w);");
  6053. statement(" break;");
  6054. end_scope();
  6055. end_scope();
  6056. // Pull all values from the i0j0 component of each gather footprint
  6057. statement("return spvGatherReturn<Tex, Tp...>(rslts[0].w, rslts[1].w, rslts[2].w, rslts[3].w);");
  6058. end_scope();
  6059. statement("");
  6060. }
  6061. break;
  6062. case SPVFuncImplGatherCompareConstOffsets:
  6063. // Because we are passing a texture reference, we have to output an overloaded version of this function for each address space.
  6064. for (uint32_t i = 0; i < texture_addr_space_count; i++)
  6065. {
  6066. statement("// Wrapper function that processes a ", texture_addr_spaces[i], " texture gather with a constant offset array.");
  6067. statement("template<typename Tex, typename Toff, typename... Tp>");
  6068. statement("inline spvGatherCompareReturn<Tex, Tp...> spvGatherCompareConstOffsets(const ", texture_addr_spaces[i], " Tex& t, sampler s, "
  6069. "Toff coffsets, Tp... params)");
  6070. begin_scope();
  6071. statement("spvGatherCompareReturn<Tex, Tp...> rslts[4];");
  6072. statement("for (uint i = 0; i < 4; i++)");
  6073. begin_scope();
  6074. statement(" rslts[i] = t.gather_compare(s, params..., coffsets[i]);");
  6075. end_scope();
  6076. // Pull all values from the i0j0 component of each gather footprint
  6077. statement("return spvGatherCompareReturn<Tex, Tp...>(rslts[0].w, rslts[1].w, rslts[2].w, rslts[3].w);");
  6078. end_scope();
  6079. statement("");
  6080. }
  6081. break;
  6082. case SPVFuncImplSubgroupBroadcast:
  6083. // Metal doesn't allow broadcasting boolean values directly, but we can work around that by broadcasting
  6084. // them as integers.
  6085. statement("template<typename T>");
  6086. statement("inline T spvSubgroupBroadcast(T value, ushort lane)");
  6087. begin_scope();
  6088. if (msl_options.use_quadgroup_operation())
  6089. statement("return quad_broadcast(value, lane);");
  6090. else
  6091. statement("return simd_broadcast(value, lane);");
  6092. end_scope();
  6093. statement("");
  6094. statement("template<>");
  6095. statement("inline bool spvSubgroupBroadcast(bool value, ushort lane)");
  6096. begin_scope();
  6097. if (msl_options.use_quadgroup_operation())
  6098. statement("return !!quad_broadcast((ushort)value, lane);");
  6099. else
  6100. statement("return !!simd_broadcast((ushort)value, lane);");
  6101. end_scope();
  6102. statement("");
  6103. statement("template<uint N>");
  6104. statement("inline vec<bool, N> spvSubgroupBroadcast(vec<bool, N> value, ushort lane)");
  6105. begin_scope();
  6106. if (msl_options.use_quadgroup_operation())
  6107. statement("return (vec<bool, N>)quad_broadcast((vec<ushort, N>)value, lane);");
  6108. else
  6109. statement("return (vec<bool, N>)simd_broadcast((vec<ushort, N>)value, lane);");
  6110. end_scope();
  6111. statement("");
  6112. break;
  6113. case SPVFuncImplSubgroupBroadcastFirst:
  6114. statement("template<typename T>");
  6115. statement("inline T spvSubgroupBroadcastFirst(T value)");
  6116. begin_scope();
  6117. if (msl_options.use_quadgroup_operation())
  6118. statement("return quad_broadcast_first(value);");
  6119. else
  6120. statement("return simd_broadcast_first(value);");
  6121. end_scope();
  6122. statement("");
  6123. statement("template<>");
  6124. statement("inline bool spvSubgroupBroadcastFirst(bool value)");
  6125. begin_scope();
  6126. if (msl_options.use_quadgroup_operation())
  6127. statement("return !!quad_broadcast_first((ushort)value);");
  6128. else
  6129. statement("return !!simd_broadcast_first((ushort)value);");
  6130. end_scope();
  6131. statement("");
  6132. statement("template<uint N>");
  6133. statement("inline vec<bool, N> spvSubgroupBroadcastFirst(vec<bool, N> value)");
  6134. begin_scope();
  6135. if (msl_options.use_quadgroup_operation())
  6136. statement("return (vec<bool, N>)quad_broadcast_first((vec<ushort, N>)value);");
  6137. else
  6138. statement("return (vec<bool, N>)simd_broadcast_first((vec<ushort, N>)value);");
  6139. end_scope();
  6140. statement("");
  6141. break;
  6142. case SPVFuncImplSubgroupBallot:
  6143. statement("inline uint4 spvSubgroupBallot(bool value)");
  6144. begin_scope();
  6145. if (msl_options.use_quadgroup_operation())
  6146. {
  6147. statement("return uint4((quad_vote::vote_t)quad_ballot(value), 0, 0, 0);");
  6148. }
  6149. else if (msl_options.is_ios())
  6150. {
  6151. // The current simd_vote on iOS uses a 32-bit integer-like object.
  6152. statement("return uint4((simd_vote::vote_t)simd_ballot(value), 0, 0, 0);");
  6153. }
  6154. else
  6155. {
  6156. statement("simd_vote vote = simd_ballot(value);");
  6157. statement("// simd_ballot() returns a 64-bit integer-like object, but");
  6158. statement("// SPIR-V callers expect a uint4. We must convert.");
  6159. statement("// FIXME: This won't include higher bits if Apple ever supports");
  6160. statement("// 128 lanes in an SIMD-group.");
  6161. statement("return uint4(as_type<uint2>((simd_vote::vote_t)vote), 0, 0);");
  6162. }
  6163. end_scope();
  6164. statement("");
  6165. break;
  6166. case SPVFuncImplSubgroupBallotBitExtract:
  6167. statement("inline bool spvSubgroupBallotBitExtract(uint4 ballot, uint bit)");
  6168. begin_scope();
  6169. statement("return !!extract_bits(ballot[bit / 32], bit % 32, 1);");
  6170. end_scope();
  6171. statement("");
  6172. break;
  6173. case SPVFuncImplSubgroupBallotFindLSB:
  6174. statement("inline uint spvSubgroupBallotFindLSB(uint4 ballot, uint gl_SubgroupSize)");
  6175. begin_scope();
  6176. if (msl_options.is_ios())
  6177. {
  6178. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));");
  6179. }
  6180. else
  6181. {
  6182. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), "
  6183. "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));");
  6184. }
  6185. statement("ballot &= mask;");
  6186. statement("return select(ctz(ballot.x), select(32 + ctz(ballot.y), select(64 + ctz(ballot.z), select(96 + "
  6187. "ctz(ballot.w), uint(-1), ballot.w == 0), ballot.z == 0), ballot.y == 0), ballot.x == 0);");
  6188. end_scope();
  6189. statement("");
  6190. break;
  6191. case SPVFuncImplSubgroupBallotFindMSB:
  6192. statement("inline uint spvSubgroupBallotFindMSB(uint4 ballot, uint gl_SubgroupSize)");
  6193. begin_scope();
  6194. if (msl_options.is_ios())
  6195. {
  6196. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));");
  6197. }
  6198. else
  6199. {
  6200. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), "
  6201. "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));");
  6202. }
  6203. statement("ballot &= mask;");
  6204. statement("return select(128 - (clz(ballot.w) + 1), select(96 - (clz(ballot.z) + 1), select(64 - "
  6205. "(clz(ballot.y) + 1), select(32 - (clz(ballot.x) + 1), uint(-1), ballot.x == 0), ballot.y == 0), "
  6206. "ballot.z == 0), ballot.w == 0);");
  6207. end_scope();
  6208. statement("");
  6209. break;
  6210. case SPVFuncImplSubgroupBallotBitCount:
  6211. statement("inline uint spvPopCount4(uint4 ballot)");
  6212. begin_scope();
  6213. statement("return popcount(ballot.x) + popcount(ballot.y) + popcount(ballot.z) + popcount(ballot.w);");
  6214. end_scope();
  6215. statement("");
  6216. statement("inline uint spvSubgroupBallotBitCount(uint4 ballot, uint gl_SubgroupSize)");
  6217. begin_scope();
  6218. if (msl_options.is_ios())
  6219. {
  6220. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));");
  6221. }
  6222. else
  6223. {
  6224. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), "
  6225. "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));");
  6226. }
  6227. statement("return spvPopCount4(ballot & mask);");
  6228. end_scope();
  6229. statement("");
  6230. statement("inline uint spvSubgroupBallotInclusiveBitCount(uint4 ballot, uint gl_SubgroupInvocationID)");
  6231. begin_scope();
  6232. if (msl_options.is_ios())
  6233. {
  6234. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupInvocationID + 1), uint3(0));");
  6235. }
  6236. else
  6237. {
  6238. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupInvocationID + 1, 32u)), "
  6239. "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupInvocationID + 1 - 32, 0)), "
  6240. "uint2(0));");
  6241. }
  6242. statement("return spvPopCount4(ballot & mask);");
  6243. end_scope();
  6244. statement("");
  6245. statement("inline uint spvSubgroupBallotExclusiveBitCount(uint4 ballot, uint gl_SubgroupInvocationID)");
  6246. begin_scope();
  6247. if (msl_options.is_ios())
  6248. {
  6249. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupInvocationID), uint2(0));");
  6250. }
  6251. else
  6252. {
  6253. statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupInvocationID, 32u)), "
  6254. "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupInvocationID - 32, 0)), uint2(0));");
  6255. }
  6256. statement("return spvPopCount4(ballot & mask);");
  6257. end_scope();
  6258. statement("");
  6259. break;
  6260. case SPVFuncImplSubgroupAllEqual:
  6261. // Metal doesn't provide a function to evaluate this directly. But, we can
  6262. // implement this by comparing every thread's value to one thread's value
  6263. // (in this case, the value of the first active thread). Then, by the transitive
  6264. // property of equality, if all comparisons return true, then they are all equal.
  6265. statement("template<typename T>");
  6266. statement("inline bool spvSubgroupAllEqual(T value)");
  6267. begin_scope();
  6268. if (msl_options.use_quadgroup_operation())
  6269. statement("return quad_all(all(value == quad_broadcast_first(value)));");
  6270. else
  6271. statement("return simd_all(all(value == simd_broadcast_first(value)));");
  6272. end_scope();
  6273. statement("");
  6274. statement("template<>");
  6275. statement("inline bool spvSubgroupAllEqual(bool value)");
  6276. begin_scope();
  6277. if (msl_options.use_quadgroup_operation())
  6278. statement("return quad_all(value) || !quad_any(value);");
  6279. else
  6280. statement("return simd_all(value) || !simd_any(value);");
  6281. end_scope();
  6282. statement("");
  6283. statement("template<uint N>");
  6284. statement("inline bool spvSubgroupAllEqual(vec<bool, N> value)");
  6285. begin_scope();
  6286. if (msl_options.use_quadgroup_operation())
  6287. statement("return quad_all(all(value == (vec<bool, N>)quad_broadcast_first((vec<ushort, N>)value)));");
  6288. else
  6289. statement("return simd_all(all(value == (vec<bool, N>)simd_broadcast_first((vec<ushort, N>)value)));");
  6290. end_scope();
  6291. statement("");
  6292. break;
  6293. case SPVFuncImplSubgroupShuffle:
  6294. statement("template<typename T>");
  6295. statement("inline T spvSubgroupShuffle(T value, ushort lane)");
  6296. begin_scope();
  6297. if (msl_options.use_quadgroup_operation())
  6298. statement("return quad_shuffle(value, lane);");
  6299. else
  6300. statement("return simd_shuffle(value, lane);");
  6301. end_scope();
  6302. statement("");
  6303. statement("template<>");
  6304. statement("inline bool spvSubgroupShuffle(bool value, ushort lane)");
  6305. begin_scope();
  6306. if (msl_options.use_quadgroup_operation())
  6307. statement("return !!quad_shuffle((ushort)value, lane);");
  6308. else
  6309. statement("return !!simd_shuffle((ushort)value, lane);");
  6310. end_scope();
  6311. statement("");
  6312. statement("template<uint N>");
  6313. statement("inline vec<bool, N> spvSubgroupShuffle(vec<bool, N> value, ushort lane)");
  6314. begin_scope();
  6315. if (msl_options.use_quadgroup_operation())
  6316. statement("return (vec<bool, N>)quad_shuffle((vec<ushort, N>)value, lane);");
  6317. else
  6318. statement("return (vec<bool, N>)simd_shuffle((vec<ushort, N>)value, lane);");
  6319. end_scope();
  6320. statement("");
  6321. if (msl_options.supports_msl_version(2, 2))
  6322. {
  6323. // Despite being a template in MSL, it does not support 64-bit shuffles.
  6324. // Unsure if there's a cleaner way to statically unroll based on vec<> template, but this will do.
  6325. statement("template<>");
  6326. statement("inline ulong spvSubgroupShuffle(ulong value, ushort lane)");
  6327. begin_scope();
  6328. statement("return as_type<ulong>(spvSubgroupShuffle(as_type<uint2>(value), lane));");
  6329. end_scope();
  6330. statement("");
  6331. statement("template<>");
  6332. statement("inline ulong2 spvSubgroupShuffle(ulong2 value, ushort lane)");
  6333. begin_scope();
  6334. statement("return ulong2(spvSubgroupShuffle(value.x, lane), spvSubgroupShuffle(value.y, lane));");
  6335. end_scope();
  6336. statement("");
  6337. statement("inline ulong3 spvSubgroupShuffle(ulong3 value, ushort lane)");
  6338. begin_scope();
  6339. statement("return ulong3(spvSubgroupShuffle(value.xy, lane), spvSubgroupShuffle(value.z, lane));");
  6340. end_scope();
  6341. statement("");
  6342. statement("inline ulong4 spvSubgroupShuffle(ulong4 value, ushort lane)");
  6343. begin_scope();
  6344. statement("return ulong4(spvSubgroupShuffle(value.xy, lane), spvSubgroupShuffle(value.zw, lane));");
  6345. end_scope();
  6346. statement("");
  6347. statement("template<uint N>");
  6348. statement("inline vec<long, N> spvSubgroupShuffle(vec<long, N> value, ushort lane)");
  6349. begin_scope();
  6350. statement("return vec<long, N>(spvSubgroupShuffle(vec<ulong, N>(value), lane));");
  6351. end_scope();
  6352. statement("");
  6353. }
  6354. break;
  6355. case SPVFuncImplSubgroupShuffleXor:
  6356. statement("template<typename T>");
  6357. statement("inline T spvSubgroupShuffleXor(T value, ushort mask)");
  6358. begin_scope();
  6359. if (msl_options.use_quadgroup_operation())
  6360. statement("return quad_shuffle_xor(value, mask);");
  6361. else
  6362. statement("return simd_shuffle_xor(value, mask);");
  6363. end_scope();
  6364. statement("");
  6365. statement("template<>");
  6366. statement("inline bool spvSubgroupShuffleXor(bool value, ushort mask)");
  6367. begin_scope();
  6368. if (msl_options.use_quadgroup_operation())
  6369. statement("return !!quad_shuffle_xor((ushort)value, mask);");
  6370. else
  6371. statement("return !!simd_shuffle_xor((ushort)value, mask);");
  6372. end_scope();
  6373. statement("");
  6374. statement("template<uint N>");
  6375. statement("inline vec<bool, N> spvSubgroupShuffleXor(vec<bool, N> value, ushort mask)");
  6376. begin_scope();
  6377. if (msl_options.use_quadgroup_operation())
  6378. statement("return (vec<bool, N>)quad_shuffle_xor((vec<ushort, N>)value, mask);");
  6379. else
  6380. statement("return (vec<bool, N>)simd_shuffle_xor((vec<ushort, N>)value, mask);");
  6381. end_scope();
  6382. statement("");
  6383. break;
  6384. case SPVFuncImplSubgroupShuffleUp:
  6385. statement("template<typename T>");
  6386. statement("inline T spvSubgroupShuffleUp(T value, ushort delta)");
  6387. begin_scope();
  6388. if (msl_options.use_quadgroup_operation())
  6389. statement("return quad_shuffle_up(value, delta);");
  6390. else
  6391. statement("return simd_shuffle_up(value, delta);");
  6392. end_scope();
  6393. statement("");
  6394. statement("template<>");
  6395. statement("inline bool spvSubgroupShuffleUp(bool value, ushort delta)");
  6396. begin_scope();
  6397. if (msl_options.use_quadgroup_operation())
  6398. statement("return !!quad_shuffle_up((ushort)value, delta);");
  6399. else
  6400. statement("return !!simd_shuffle_up((ushort)value, delta);");
  6401. end_scope();
  6402. statement("");
  6403. statement("template<uint N>");
  6404. statement("inline vec<bool, N> spvSubgroupShuffleUp(vec<bool, N> value, ushort delta)");
  6405. begin_scope();
  6406. if (msl_options.use_quadgroup_operation())
  6407. statement("return (vec<bool, N>)quad_shuffle_up((vec<ushort, N>)value, delta);");
  6408. else
  6409. statement("return (vec<bool, N>)simd_shuffle_up((vec<ushort, N>)value, delta);");
  6410. end_scope();
  6411. statement("");
  6412. break;
  6413. case SPVFuncImplSubgroupShuffleDown:
  6414. statement("template<typename T>");
  6415. statement("inline T spvSubgroupShuffleDown(T value, ushort delta)");
  6416. begin_scope();
  6417. if (msl_options.use_quadgroup_operation())
  6418. statement("return quad_shuffle_down(value, delta);");
  6419. else
  6420. statement("return simd_shuffle_down(value, delta);");
  6421. end_scope();
  6422. statement("");
  6423. statement("template<>");
  6424. statement("inline bool spvSubgroupShuffleDown(bool value, ushort delta)");
  6425. begin_scope();
  6426. if (msl_options.use_quadgroup_operation())
  6427. statement("return !!quad_shuffle_down((ushort)value, delta);");
  6428. else
  6429. statement("return !!simd_shuffle_down((ushort)value, delta);");
  6430. end_scope();
  6431. statement("");
  6432. statement("template<uint N>");
  6433. statement("inline vec<bool, N> spvSubgroupShuffleDown(vec<bool, N> value, ushort delta)");
  6434. begin_scope();
  6435. if (msl_options.use_quadgroup_operation())
  6436. statement("return (vec<bool, N>)quad_shuffle_down((vec<ushort, N>)value, delta);");
  6437. else
  6438. statement("return (vec<bool, N>)simd_shuffle_down((vec<ushort, N>)value, delta);");
  6439. end_scope();
  6440. statement("");
  6441. break;
  6442. case SPVFuncImplSubgroupRotate:
  6443. statement("template<typename T>");
  6444. statement("inline T spvSubgroupRotate(T value, ushort delta)");
  6445. begin_scope();
  6446. if (msl_options.use_quadgroup_operation())
  6447. statement("return quad_shuffle_rotate_down(value, delta);");
  6448. else
  6449. statement("return simd_shuffle_rotate_down(value, delta);");
  6450. end_scope();
  6451. statement("");
  6452. statement("template<>");
  6453. statement("inline bool spvSubgroupRotate(bool value, ushort delta)");
  6454. begin_scope();
  6455. if (msl_options.use_quadgroup_operation())
  6456. statement("return !!quad_shuffle_rotate_down((ushort)value, delta);");
  6457. else
  6458. statement("return !!simd_shuffle_rotate_down((ushort)value, delta);");
  6459. end_scope();
  6460. statement("");
  6461. statement("template<uint N>");
  6462. statement("inline vec<bool, N> spvSubgroupRotate(vec<bool, N> value, ushort delta)");
  6463. begin_scope();
  6464. if (msl_options.use_quadgroup_operation())
  6465. statement("return (vec<bool, N>)quad_shuffle_rotate_down((vec<ushort, N>)value, delta);");
  6466. else
  6467. statement("return (vec<bool, N>)simd_shuffle_rotate_down((vec<ushort, N>)value, delta);");
  6468. end_scope();
  6469. statement("");
  6470. break;
  6471. // C++ disallows partial specializations of function templates,
  6472. // hence the use of a struct.
  6473. // clang-format off
  6474. #define FUNC_SUBGROUP_CLUSTERED(spv, msl, combine, op, ident) \
  6475. case SPVFuncImplSubgroupClustered##spv: \
  6476. statement("template<uint N, uint offset>"); \
  6477. statement("struct spvClustered" #spv "Detail;"); \
  6478. statement(""); \
  6479. statement("// Base cases"); \
  6480. statement("template<>"); \
  6481. statement("struct spvClustered" #spv "Detail<1, 0>"); \
  6482. begin_scope(); \
  6483. statement("template<typename T>"); \
  6484. statement("static T op(T value, uint)"); \
  6485. begin_scope(); \
  6486. statement("return value;"); \
  6487. end_scope(); \
  6488. end_scope_decl(); \
  6489. statement(""); \
  6490. statement("template<uint offset>"); \
  6491. statement("struct spvClustered" #spv "Detail<1, offset>"); \
  6492. begin_scope(); \
  6493. statement("template<typename T>"); \
  6494. statement("static T op(T value, uint lid)"); \
  6495. begin_scope(); \
  6496. statement("// If the target lane is inactive, then return identity."); \
  6497. if (msl_options.use_quadgroup_operation()) \
  6498. statement("if (!extract_bits((quad_vote::vote_t)quad_active_threads_mask(), (lid ^ offset), 1))"); \
  6499. else \
  6500. statement("if (!extract_bits(as_type<uint2>((simd_vote::vote_t)simd_active_threads_mask())[(lid ^ offset) / 32], (lid ^ offset) % 32, 1))"); \
  6501. statement(" return " #ident ";"); \
  6502. if (msl_options.use_quadgroup_operation()) \
  6503. statement("return quad_shuffle_xor(value, offset);"); \
  6504. else \
  6505. statement("return simd_shuffle_xor(value, offset);"); \
  6506. end_scope(); \
  6507. end_scope_decl(); \
  6508. statement(""); \
  6509. statement("template<>"); \
  6510. statement("struct spvClustered" #spv "Detail<4, 0>"); \
  6511. begin_scope(); \
  6512. statement("template<typename T>"); \
  6513. statement("static T op(T value, uint)"); \
  6514. begin_scope(); \
  6515. statement("return quad_" #msl "(value);"); \
  6516. end_scope(); \
  6517. end_scope_decl(); \
  6518. statement(""); \
  6519. statement("template<uint offset>"); \
  6520. statement("struct spvClustered" #spv "Detail<4, offset>"); \
  6521. begin_scope(); \
  6522. statement("template<typename T>"); \
  6523. statement("static T op(T value, uint lid)"); \
  6524. begin_scope(); \
  6525. statement("// Here, we care if any of the lanes in the quad are active."); \
  6526. statement("uint quad_mask = extract_bits(as_type<uint2>((simd_vote::vote_t)simd_active_threads_mask())[(lid ^ offset) / 32], ((lid ^ offset) % 32) & ~3, 4);"); \
  6527. statement("if (!quad_mask)"); \
  6528. statement(" return " #ident ";"); \
  6529. statement("// But we need to make sure we shuffle from an active lane."); \
  6530. if (msl_options.use_quadgroup_operation()) \
  6531. SPIRV_CROSS_THROW("Subgroup size with quadgroup operation cannot exceed 4."); \
  6532. else \
  6533. statement("return simd_shuffle(quad_" #msl "(value), ((lid ^ offset) & ~3) | ctz(quad_mask));"); \
  6534. end_scope(); \
  6535. end_scope_decl(); \
  6536. statement(""); \
  6537. statement("// General case"); \
  6538. statement("template<uint N, uint offset>"); \
  6539. statement("struct spvClustered" #spv "Detail"); \
  6540. begin_scope(); \
  6541. statement("template<typename T>"); \
  6542. statement("static T op(T value, uint lid)"); \
  6543. begin_scope(); \
  6544. statement("return " combine(msl, op, "spvClustered" #spv "Detail<N/2, offset>::op(value, lid)", "spvClustered" #spv "Detail<N/2, offset + N/2>::op(value, lid)") ";"); \
  6545. end_scope(); \
  6546. end_scope_decl(); \
  6547. statement(""); \
  6548. statement("template<uint N, typename T>"); \
  6549. statement("T spvClustered_" #msl "(T value, uint lid)"); \
  6550. begin_scope(); \
  6551. statement("return spvClustered" #spv "Detail<N, 0>::op(value, lid);"); \
  6552. end_scope(); \
  6553. statement(""); \
  6554. break
  6555. #define BINOP(msl, op, l, r) l " " #op " " r
  6556. #define BINFUNC(msl, op, l, r) #msl "(" l ", " r ")"
  6557. FUNC_SUBGROUP_CLUSTERED(Add, sum, BINOP, +, 0);
  6558. FUNC_SUBGROUP_CLUSTERED(Mul, product, BINOP, *, 1);
  6559. FUNC_SUBGROUP_CLUSTERED(Min, min, BINFUNC, , numeric_limits<T>::max());
  6560. FUNC_SUBGROUP_CLUSTERED(Max, max, BINFUNC, , numeric_limits<T>::min());
  6561. FUNC_SUBGROUP_CLUSTERED(And, and, BINOP, &, ~T(0));
  6562. FUNC_SUBGROUP_CLUSTERED(Or, or, BINOP, |, 0);
  6563. FUNC_SUBGROUP_CLUSTERED(Xor, xor, BINOP, ^, 0);
  6564. // clang-format on
  6565. #undef FUNC_SUBGROUP_CLUSTERED
  6566. #undef BINOP
  6567. #undef BINFUNC
  6568. case SPVFuncImplQuadBroadcast:
  6569. statement("template<typename T>");
  6570. statement("inline T spvQuadBroadcast(T value, uint lane)");
  6571. begin_scope();
  6572. statement("return quad_broadcast(value, lane);");
  6573. end_scope();
  6574. statement("");
  6575. statement("template<>");
  6576. statement("inline bool spvQuadBroadcast(bool value, uint lane)");
  6577. begin_scope();
  6578. statement("return !!quad_broadcast((ushort)value, lane);");
  6579. end_scope();
  6580. statement("");
  6581. statement("template<uint N>");
  6582. statement("inline vec<bool, N> spvQuadBroadcast(vec<bool, N> value, uint lane)");
  6583. begin_scope();
  6584. statement("return (vec<bool, N>)quad_broadcast((vec<ushort, N>)value, lane);");
  6585. end_scope();
  6586. statement("");
  6587. break;
  6588. case SPVFuncImplQuadSwap:
  6589. // We can implement this easily based on the following table giving
  6590. // the target lane ID from the direction and current lane ID:
  6591. // Direction
  6592. // | 0 | 1 | 2 |
  6593. // ---+---+---+---+
  6594. // L 0 | 1 2 3
  6595. // a 1 | 0 3 2
  6596. // n 2 | 3 0 1
  6597. // e 3 | 2 1 0
  6598. // Notice that target = source ^ (direction + 1).
  6599. statement("template<typename T>");
  6600. statement("inline T spvQuadSwap(T value, uint dir)");
  6601. begin_scope();
  6602. statement("return quad_shuffle_xor(value, dir + 1);");
  6603. end_scope();
  6604. statement("");
  6605. statement("template<>");
  6606. statement("inline bool spvQuadSwap(bool value, uint dir)");
  6607. begin_scope();
  6608. statement("return !!quad_shuffle_xor((ushort)value, dir + 1);");
  6609. end_scope();
  6610. statement("");
  6611. statement("template<uint N>");
  6612. statement("inline vec<bool, N> spvQuadSwap(vec<bool, N> value, uint dir)");
  6613. begin_scope();
  6614. statement("return (vec<bool, N>)quad_shuffle_xor((vec<ushort, N>)value, dir + 1);");
  6615. end_scope();
  6616. statement("");
  6617. break;
  6618. case SPVFuncImplReflectScalar:
  6619. // Metal does not support scalar versions of these functions.
  6620. // Ensure fast-math is disabled to match Vulkan results.
  6621. statement("template<typename T>");
  6622. statement("[[clang::optnone]] T spvReflect(T i, T n)");
  6623. begin_scope();
  6624. statement("return i - T(2) * i * n * n;");
  6625. end_scope();
  6626. statement("");
  6627. break;
  6628. case SPVFuncImplRefractScalar:
  6629. // Metal does not support scalar versions of these functions.
  6630. statement("template<typename T>");
  6631. statement("inline T spvRefract(T i, T n, T eta)");
  6632. begin_scope();
  6633. statement("T NoI = n * i;");
  6634. statement("T NoI2 = NoI * NoI;");
  6635. statement("T k = T(1) - eta * eta * (T(1) - NoI2);");
  6636. statement("if (k < T(0))");
  6637. begin_scope();
  6638. statement("return T(0);");
  6639. end_scope();
  6640. statement("else");
  6641. begin_scope();
  6642. statement("return eta * i - (eta * NoI + sqrt(k)) * n;");
  6643. end_scope();
  6644. end_scope();
  6645. statement("");
  6646. break;
  6647. case SPVFuncImplFaceForwardScalar:
  6648. // Metal does not support scalar versions of these functions.
  6649. statement("template<typename T>");
  6650. statement("inline T spvFaceForward(T n, T i, T nref)");
  6651. begin_scope();
  6652. statement("return i * nref < T(0) ? n : -n;");
  6653. end_scope();
  6654. statement("");
  6655. break;
  6656. case SPVFuncImplChromaReconstructNearest2Plane:
  6657. statement("template<typename T, typename... LodOptions>");
  6658. statement("inline vec<T, 4> spvChromaReconstructNearest(texture2d<T> plane0, texture2d<T> plane1, sampler "
  6659. "samp, float2 coord, LodOptions... options)");
  6660. begin_scope();
  6661. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6662. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6663. statement("ycbcr.br = plane1.sample(samp, coord, options...).rg;");
  6664. statement("return ycbcr;");
  6665. end_scope();
  6666. statement("");
  6667. break;
  6668. case SPVFuncImplChromaReconstructNearest3Plane:
  6669. statement("template<typename T, typename... LodOptions>");
  6670. statement("inline vec<T, 4> spvChromaReconstructNearest(texture2d<T> plane0, texture2d<T> plane1, "
  6671. "texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6672. begin_scope();
  6673. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6674. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6675. statement("ycbcr.b = plane1.sample(samp, coord, options...).r;");
  6676. statement("ycbcr.r = plane2.sample(samp, coord, options...).r;");
  6677. statement("return ycbcr;");
  6678. end_scope();
  6679. statement("");
  6680. break;
  6681. case SPVFuncImplChromaReconstructLinear422CositedEven2Plane:
  6682. statement("template<typename T, typename... LodOptions>");
  6683. statement("inline vec<T, 4> spvChromaReconstructLinear422CositedEven(texture2d<T> plane0, texture2d<T> "
  6684. "plane1, sampler samp, float2 coord, LodOptions... options)");
  6685. begin_scope();
  6686. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6687. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6688. statement("if (fract(coord.x * plane1.get_width()) != 0.0)");
  6689. begin_scope();
  6690. statement("ycbcr.br = vec<T, 2>(mix(plane1.sample(samp, coord, options...), "
  6691. "plane1.sample(samp, coord, options..., int2(1, 0)), 0.5).rg);");
  6692. end_scope();
  6693. statement("else");
  6694. begin_scope();
  6695. statement("ycbcr.br = plane1.sample(samp, coord, options...).rg;");
  6696. end_scope();
  6697. statement("return ycbcr;");
  6698. end_scope();
  6699. statement("");
  6700. break;
  6701. case SPVFuncImplChromaReconstructLinear422CositedEven3Plane:
  6702. statement("template<typename T, typename... LodOptions>");
  6703. statement("inline vec<T, 4> spvChromaReconstructLinear422CositedEven(texture2d<T> plane0, texture2d<T> "
  6704. "plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6705. begin_scope();
  6706. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6707. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6708. statement("if (fract(coord.x * plane1.get_width()) != 0.0)");
  6709. begin_scope();
  6710. statement("ycbcr.b = T(mix(plane1.sample(samp, coord, options...), "
  6711. "plane1.sample(samp, coord, options..., int2(1, 0)), 0.5).r);");
  6712. statement("ycbcr.r = T(mix(plane2.sample(samp, coord, options...), "
  6713. "plane2.sample(samp, coord, options..., int2(1, 0)), 0.5).r);");
  6714. end_scope();
  6715. statement("else");
  6716. begin_scope();
  6717. statement("ycbcr.b = plane1.sample(samp, coord, options...).r;");
  6718. statement("ycbcr.r = plane2.sample(samp, coord, options...).r;");
  6719. end_scope();
  6720. statement("return ycbcr;");
  6721. end_scope();
  6722. statement("");
  6723. break;
  6724. case SPVFuncImplChromaReconstructLinear422Midpoint2Plane:
  6725. statement("template<typename T, typename... LodOptions>");
  6726. statement("inline vec<T, 4> spvChromaReconstructLinear422Midpoint(texture2d<T> plane0, texture2d<T> "
  6727. "plane1, sampler samp, float2 coord, LodOptions... options)");
  6728. begin_scope();
  6729. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6730. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6731. statement("int2 offs = int2(fract(coord.x * plane1.get_width()) != 0.0 ? 1 : -1, 0);");
  6732. statement("ycbcr.br = vec<T, 2>(mix(plane1.sample(samp, coord, options...), "
  6733. "plane1.sample(samp, coord, options..., offs), 0.25).rg);");
  6734. statement("return ycbcr;");
  6735. end_scope();
  6736. statement("");
  6737. break;
  6738. case SPVFuncImplChromaReconstructLinear422Midpoint3Plane:
  6739. statement("template<typename T, typename... LodOptions>");
  6740. statement("inline vec<T, 4> spvChromaReconstructLinear422Midpoint(texture2d<T> plane0, texture2d<T> "
  6741. "plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6742. begin_scope();
  6743. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6744. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6745. statement("int2 offs = int2(fract(coord.x * plane1.get_width()) != 0.0 ? 1 : -1, 0);");
  6746. statement("ycbcr.b = T(mix(plane1.sample(samp, coord, options...), "
  6747. "plane1.sample(samp, coord, options..., offs), 0.25).r);");
  6748. statement("ycbcr.r = T(mix(plane2.sample(samp, coord, options...), "
  6749. "plane2.sample(samp, coord, options..., offs), 0.25).r);");
  6750. statement("return ycbcr;");
  6751. end_scope();
  6752. statement("");
  6753. break;
  6754. case SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven2Plane:
  6755. statement("template<typename T, typename... LodOptions>");
  6756. statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYCositedEven(texture2d<T> plane0, "
  6757. "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
  6758. begin_scope();
  6759. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6760. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6761. statement("float2 ab = fract(round(coord * float2(plane0.get_width(), plane0.get_height())) * 0.5);");
  6762. statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), "
  6763. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6764. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6765. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);");
  6766. statement("return ycbcr;");
  6767. end_scope();
  6768. statement("");
  6769. break;
  6770. case SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven3Plane:
  6771. statement("template<typename T, typename... LodOptions>");
  6772. statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYCositedEven(texture2d<T> plane0, "
  6773. "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6774. begin_scope();
  6775. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6776. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6777. statement("float2 ab = fract(round(coord * float2(plane0.get_width(), plane0.get_height())) * 0.5);");
  6778. statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), "
  6779. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6780. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6781. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6782. statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), "
  6783. "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6784. "mix(plane2.sample(samp, coord, options..., int2(0, 1)), "
  6785. "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6786. statement("return ycbcr;");
  6787. end_scope();
  6788. statement("");
  6789. break;
  6790. case SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven2Plane:
  6791. statement("template<typename T, typename... LodOptions>");
  6792. statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYCositedEven(texture2d<T> plane0, "
  6793. "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
  6794. begin_scope();
  6795. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6796. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6797. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
  6798. "0)) * 0.5);");
  6799. statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), "
  6800. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6801. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6802. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);");
  6803. statement("return ycbcr;");
  6804. end_scope();
  6805. statement("");
  6806. break;
  6807. case SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven3Plane:
  6808. statement("template<typename T, typename... LodOptions>");
  6809. statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYCositedEven(texture2d<T> plane0, "
  6810. "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6811. begin_scope();
  6812. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6813. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6814. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
  6815. "0)) * 0.5);");
  6816. statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), "
  6817. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6818. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6819. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6820. statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), "
  6821. "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6822. "mix(plane2.sample(samp, coord, options..., int2(0, 1)), "
  6823. "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6824. statement("return ycbcr;");
  6825. end_scope();
  6826. statement("");
  6827. break;
  6828. case SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint2Plane:
  6829. statement("template<typename T, typename... LodOptions>");
  6830. statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYMidpoint(texture2d<T> plane0, "
  6831. "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
  6832. begin_scope();
  6833. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6834. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6835. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0, "
  6836. "0.5)) * 0.5);");
  6837. statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), "
  6838. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6839. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6840. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);");
  6841. statement("return ycbcr;");
  6842. end_scope();
  6843. statement("");
  6844. break;
  6845. case SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint3Plane:
  6846. statement("template<typename T, typename... LodOptions>");
  6847. statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYMidpoint(texture2d<T> plane0, "
  6848. "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6849. begin_scope();
  6850. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6851. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6852. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0, "
  6853. "0.5)) * 0.5);");
  6854. statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), "
  6855. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6856. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6857. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6858. statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), "
  6859. "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6860. "mix(plane2.sample(samp, coord, options..., int2(0, 1)), "
  6861. "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6862. statement("return ycbcr;");
  6863. end_scope();
  6864. statement("");
  6865. break;
  6866. case SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint2Plane:
  6867. statement("template<typename T, typename... LodOptions>");
  6868. statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYMidpoint(texture2d<T> plane0, "
  6869. "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
  6870. begin_scope();
  6871. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6872. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6873. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
  6874. "0.5)) * 0.5);");
  6875. statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), "
  6876. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6877. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6878. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);");
  6879. statement("return ycbcr;");
  6880. end_scope();
  6881. statement("");
  6882. break;
  6883. case SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane:
  6884. statement("template<typename T, typename... LodOptions>");
  6885. statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYMidpoint(texture2d<T> plane0, "
  6886. "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
  6887. begin_scope();
  6888. statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
  6889. statement("ycbcr.g = plane0.sample(samp, coord, options...).r;");
  6890. statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
  6891. "0.5)) * 0.5);");
  6892. statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), "
  6893. "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6894. "mix(plane1.sample(samp, coord, options..., int2(0, 1)), "
  6895. "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6896. statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), "
  6897. "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), "
  6898. "mix(plane2.sample(samp, coord, options..., int2(0, 1)), "
  6899. "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);");
  6900. statement("return ycbcr;");
  6901. end_scope();
  6902. statement("");
  6903. break;
  6904. case SPVFuncImplExpandITUFullRange:
  6905. statement("template<typename T>");
  6906. statement("inline vec<T, 4> spvExpandITUFullRange(vec<T, 4> ycbcr, int n)");
  6907. begin_scope();
  6908. statement("ycbcr.br -= exp2(T(n-1))/(exp2(T(n))-1);");
  6909. statement("return ycbcr;");
  6910. end_scope();
  6911. statement("");
  6912. break;
  6913. case SPVFuncImplExpandITUNarrowRange:
  6914. statement("template<typename T>");
  6915. statement("inline vec<T, 4> spvExpandITUNarrowRange(vec<T, 4> ycbcr, int n)");
  6916. begin_scope();
  6917. statement("ycbcr.g = (ycbcr.g * (exp2(T(n)) - 1) - ldexp(T(16), n - 8))/ldexp(T(219), n - 8);");
  6918. statement("ycbcr.br = (ycbcr.br * (exp2(T(n)) - 1) - ldexp(T(128), n - 8))/ldexp(T(224), n - 8);");
  6919. statement("return ycbcr;");
  6920. end_scope();
  6921. statement("");
  6922. break;
  6923. case SPVFuncImplConvertYCbCrBT709:
  6924. statement("// cf. Khronos Data Format Specification, section 15.1.1");
  6925. statement("constant float3x3 spvBT709Factors = {{1, 1, 1}, {0, -0.13397432/0.7152, 1.8556}, {1.5748, "
  6926. "-0.33480248/0.7152, 0}};");
  6927. statement("");
  6928. statement("template<typename T>");
  6929. statement("inline vec<T, 4> spvConvertYCbCrBT709(vec<T, 4> ycbcr)");
  6930. begin_scope();
  6931. statement("vec<T, 4> rgba;");
  6932. statement("rgba.rgb = vec<T, 3>(spvBT709Factors * ycbcr.gbr);");
  6933. statement("rgba.a = ycbcr.a;");
  6934. statement("return rgba;");
  6935. end_scope();
  6936. statement("");
  6937. break;
  6938. case SPVFuncImplConvertYCbCrBT601:
  6939. statement("// cf. Khronos Data Format Specification, section 15.1.2");
  6940. statement("constant float3x3 spvBT601Factors = {{1, 1, 1}, {0, -0.202008/0.587, 1.772}, {1.402, "
  6941. "-0.419198/0.587, 0}};");
  6942. statement("");
  6943. statement("template<typename T>");
  6944. statement("inline vec<T, 4> spvConvertYCbCrBT601(vec<T, 4> ycbcr)");
  6945. begin_scope();
  6946. statement("vec<T, 4> rgba;");
  6947. statement("rgba.rgb = vec<T, 3>(spvBT601Factors * ycbcr.gbr);");
  6948. statement("rgba.a = ycbcr.a;");
  6949. statement("return rgba;");
  6950. end_scope();
  6951. statement("");
  6952. break;
  6953. case SPVFuncImplConvertYCbCrBT2020:
  6954. statement("// cf. Khronos Data Format Specification, section 15.1.3");
  6955. statement("constant float3x3 spvBT2020Factors = {{1, 1, 1}, {0, -0.11156702/0.6780, 1.8814}, {1.4746, "
  6956. "-0.38737742/0.6780, 0}};");
  6957. statement("");
  6958. statement("template<typename T>");
  6959. statement("inline vec<T, 4> spvConvertYCbCrBT2020(vec<T, 4> ycbcr)");
  6960. begin_scope();
  6961. statement("vec<T, 4> rgba;");
  6962. statement("rgba.rgb = vec<T, 3>(spvBT2020Factors * ycbcr.gbr);");
  6963. statement("rgba.a = ycbcr.a;");
  6964. statement("return rgba;");
  6965. end_scope();
  6966. statement("");
  6967. break;
  6968. case SPVFuncImplDynamicImageSampler:
  6969. statement("enum class spvFormatResolution");
  6970. begin_scope();
  6971. statement("_444 = 0,");
  6972. statement("_422,");
  6973. statement("_420");
  6974. end_scope_decl();
  6975. statement("");
  6976. statement("enum class spvChromaFilter");
  6977. begin_scope();
  6978. statement("nearest = 0,");
  6979. statement("linear");
  6980. end_scope_decl();
  6981. statement("");
  6982. statement("enum class spvXChromaLocation");
  6983. begin_scope();
  6984. statement("cosited_even = 0,");
  6985. statement("midpoint");
  6986. end_scope_decl();
  6987. statement("");
  6988. statement("enum class spvYChromaLocation");
  6989. begin_scope();
  6990. statement("cosited_even = 0,");
  6991. statement("midpoint");
  6992. end_scope_decl();
  6993. statement("");
  6994. statement("enum class spvYCbCrModelConversion");
  6995. begin_scope();
  6996. statement("rgb_identity = 0,");
  6997. statement("ycbcr_identity,");
  6998. statement("ycbcr_bt_709,");
  6999. statement("ycbcr_bt_601,");
  7000. statement("ycbcr_bt_2020");
  7001. end_scope_decl();
  7002. statement("");
  7003. statement("enum class spvYCbCrRange");
  7004. begin_scope();
  7005. statement("itu_full = 0,");
  7006. statement("itu_narrow");
  7007. end_scope_decl();
  7008. statement("");
  7009. statement("struct spvComponentBits");
  7010. begin_scope();
  7011. statement("constexpr explicit spvComponentBits(int v) thread : value(v) {}");
  7012. statement("uchar value : 6;");
  7013. end_scope_decl();
  7014. statement("// A class corresponding to metal::sampler which holds sampler");
  7015. statement("// Y'CbCr conversion info.");
  7016. statement("struct spvYCbCrSampler");
  7017. begin_scope();
  7018. statement("constexpr spvYCbCrSampler() thread : val(build()) {}");
  7019. statement("template<typename... Ts>");
  7020. statement("constexpr spvYCbCrSampler(Ts... t) thread : val(build(t...)) {}");
  7021. statement("constexpr spvYCbCrSampler(const thread spvYCbCrSampler& s) thread = default;");
  7022. statement("");
  7023. statement("spvFormatResolution get_resolution() const thread");
  7024. begin_scope();
  7025. statement("return spvFormatResolution((val & resolution_mask) >> resolution_base);");
  7026. end_scope();
  7027. statement("spvChromaFilter get_chroma_filter() const thread");
  7028. begin_scope();
  7029. statement("return spvChromaFilter((val & chroma_filter_mask) >> chroma_filter_base);");
  7030. end_scope();
  7031. statement("spvXChromaLocation get_x_chroma_offset() const thread");
  7032. begin_scope();
  7033. statement("return spvXChromaLocation((val & x_chroma_off_mask) >> x_chroma_off_base);");
  7034. end_scope();
  7035. statement("spvYChromaLocation get_y_chroma_offset() const thread");
  7036. begin_scope();
  7037. statement("return spvYChromaLocation((val & y_chroma_off_mask) >> y_chroma_off_base);");
  7038. end_scope();
  7039. statement("spvYCbCrModelConversion get_ycbcr_model() const thread");
  7040. begin_scope();
  7041. statement("return spvYCbCrModelConversion((val & ycbcr_model_mask) >> ycbcr_model_base);");
  7042. end_scope();
  7043. statement("spvYCbCrRange get_ycbcr_range() const thread");
  7044. begin_scope();
  7045. statement("return spvYCbCrRange((val & ycbcr_range_mask) >> ycbcr_range_base);");
  7046. end_scope();
  7047. statement("int get_bpc() const thread { return (val & bpc_mask) >> bpc_base; }");
  7048. statement("");
  7049. statement("private:");
  7050. statement("ushort val;");
  7051. statement("");
  7052. statement("constexpr static constant ushort resolution_bits = 2;");
  7053. statement("constexpr static constant ushort chroma_filter_bits = 2;");
  7054. statement("constexpr static constant ushort x_chroma_off_bit = 1;");
  7055. statement("constexpr static constant ushort y_chroma_off_bit = 1;");
  7056. statement("constexpr static constant ushort ycbcr_model_bits = 3;");
  7057. statement("constexpr static constant ushort ycbcr_range_bit = 1;");
  7058. statement("constexpr static constant ushort bpc_bits = 6;");
  7059. statement("");
  7060. statement("constexpr static constant ushort resolution_base = 0;");
  7061. statement("constexpr static constant ushort chroma_filter_base = 2;");
  7062. statement("constexpr static constant ushort x_chroma_off_base = 4;");
  7063. statement("constexpr static constant ushort y_chroma_off_base = 5;");
  7064. statement("constexpr static constant ushort ycbcr_model_base = 6;");
  7065. statement("constexpr static constant ushort ycbcr_range_base = 9;");
  7066. statement("constexpr static constant ushort bpc_base = 10;");
  7067. statement("");
  7068. statement(
  7069. "constexpr static constant ushort resolution_mask = ((1 << resolution_bits) - 1) << resolution_base;");
  7070. statement("constexpr static constant ushort chroma_filter_mask = ((1 << chroma_filter_bits) - 1) << "
  7071. "chroma_filter_base;");
  7072. statement("constexpr static constant ushort x_chroma_off_mask = ((1 << x_chroma_off_bit) - 1) << "
  7073. "x_chroma_off_base;");
  7074. statement("constexpr static constant ushort y_chroma_off_mask = ((1 << y_chroma_off_bit) - 1) << "
  7075. "y_chroma_off_base;");
  7076. statement("constexpr static constant ushort ycbcr_model_mask = ((1 << ycbcr_model_bits) - 1) << "
  7077. "ycbcr_model_base;");
  7078. statement("constexpr static constant ushort ycbcr_range_mask = ((1 << ycbcr_range_bit) - 1) << "
  7079. "ycbcr_range_base;");
  7080. statement("constexpr static constant ushort bpc_mask = ((1 << bpc_bits) - 1) << bpc_base;");
  7081. statement("");
  7082. statement("static constexpr ushort build()");
  7083. begin_scope();
  7084. statement("return 0;");
  7085. end_scope();
  7086. statement("");
  7087. statement("template<typename... Ts>");
  7088. statement("static constexpr ushort build(spvFormatResolution res, Ts... t)");
  7089. begin_scope();
  7090. statement("return (ushort(res) << resolution_base) | (build(t...) & ~resolution_mask);");
  7091. end_scope();
  7092. statement("");
  7093. statement("template<typename... Ts>");
  7094. statement("static constexpr ushort build(spvChromaFilter filt, Ts... t)");
  7095. begin_scope();
  7096. statement("return (ushort(filt) << chroma_filter_base) | (build(t...) & ~chroma_filter_mask);");
  7097. end_scope();
  7098. statement("");
  7099. statement("template<typename... Ts>");
  7100. statement("static constexpr ushort build(spvXChromaLocation loc, Ts... t)");
  7101. begin_scope();
  7102. statement("return (ushort(loc) << x_chroma_off_base) | (build(t...) & ~x_chroma_off_mask);");
  7103. end_scope();
  7104. statement("");
  7105. statement("template<typename... Ts>");
  7106. statement("static constexpr ushort build(spvYChromaLocation loc, Ts... t)");
  7107. begin_scope();
  7108. statement("return (ushort(loc) << y_chroma_off_base) | (build(t...) & ~y_chroma_off_mask);");
  7109. end_scope();
  7110. statement("");
  7111. statement("template<typename... Ts>");
  7112. statement("static constexpr ushort build(spvYCbCrModelConversion model, Ts... t)");
  7113. begin_scope();
  7114. statement("return (ushort(model) << ycbcr_model_base) | (build(t...) & ~ycbcr_model_mask);");
  7115. end_scope();
  7116. statement("");
  7117. statement("template<typename... Ts>");
  7118. statement("static constexpr ushort build(spvYCbCrRange range, Ts... t)");
  7119. begin_scope();
  7120. statement("return (ushort(range) << ycbcr_range_base) | (build(t...) & ~ycbcr_range_mask);");
  7121. end_scope();
  7122. statement("");
  7123. statement("template<typename... Ts>");
  7124. statement("static constexpr ushort build(spvComponentBits bpc, Ts... t)");
  7125. begin_scope();
  7126. statement("return (ushort(bpc.value) << bpc_base) | (build(t...) & ~bpc_mask);");
  7127. end_scope();
  7128. end_scope_decl();
  7129. statement("");
  7130. statement("// A class which can hold up to three textures and a sampler, including");
  7131. statement("// Y'CbCr conversion info, used to pass combined image-samplers");
  7132. statement("// dynamically to functions.");
  7133. statement("template<typename T>");
  7134. statement("struct spvDynamicImageSampler");
  7135. begin_scope();
  7136. statement("texture2d<T> plane0;");
  7137. statement("texture2d<T> plane1;");
  7138. statement("texture2d<T> plane2;");
  7139. statement("sampler samp;");
  7140. statement("spvYCbCrSampler ycbcr_samp;");
  7141. statement("uint swizzle = 0;");
  7142. statement("");
  7143. if (msl_options.swizzle_texture_samples)
  7144. {
  7145. statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp, uint sw) thread :");
  7146. statement(" plane0(tex), samp(samp), swizzle(sw) {}");
  7147. }
  7148. else
  7149. {
  7150. statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp) thread :");
  7151. statement(" plane0(tex), samp(samp) {}");
  7152. }
  7153. statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp, spvYCbCrSampler ycbcr_samp, "
  7154. "uint sw) thread :");
  7155. statement(" plane0(tex), samp(samp), ycbcr_samp(ycbcr_samp), swizzle(sw) {}");
  7156. statement("constexpr spvDynamicImageSampler(texture2d<T> plane0, texture2d<T> plane1,");
  7157. statement(" sampler samp, spvYCbCrSampler ycbcr_samp, uint sw) thread :");
  7158. statement(" plane0(plane0), plane1(plane1), samp(samp), ycbcr_samp(ycbcr_samp), swizzle(sw) {}");
  7159. statement(
  7160. "constexpr spvDynamicImageSampler(texture2d<T> plane0, texture2d<T> plane1, texture2d<T> plane2,");
  7161. statement(" sampler samp, spvYCbCrSampler ycbcr_samp, uint sw) thread :");
  7162. statement(" plane0(plane0), plane1(plane1), plane2(plane2), samp(samp), ycbcr_samp(ycbcr_samp), "
  7163. "swizzle(sw) {}");
  7164. statement("");
  7165. // XXX This is really hard to follow... I've left comments to make it a bit easier.
  7166. statement("template<typename... LodOptions>");
  7167. statement("vec<T, 4> do_sample(float2 coord, LodOptions... options) const thread");
  7168. begin_scope();
  7169. statement("if (!is_null_texture(plane1))");
  7170. begin_scope();
  7171. statement("if (ycbcr_samp.get_resolution() == spvFormatResolution::_444 ||");
  7172. statement(" ycbcr_samp.get_chroma_filter() == spvChromaFilter::nearest)");
  7173. begin_scope();
  7174. statement("if (!is_null_texture(plane2))");
  7175. statement(" return spvChromaReconstructNearest(plane0, plane1, plane2, samp, coord, options...);");
  7176. statement("return spvChromaReconstructNearest(plane0, plane1, samp, coord, options...);");
  7177. end_scope(); // if (resolution == 422 || chroma_filter == nearest)
  7178. statement("switch (ycbcr_samp.get_resolution())");
  7179. begin_scope();
  7180. statement("case spvFormatResolution::_444: break;");
  7181. statement("case spvFormatResolution::_422:");
  7182. begin_scope();
  7183. statement("switch (ycbcr_samp.get_x_chroma_offset())");
  7184. begin_scope();
  7185. statement("case spvXChromaLocation::cosited_even:");
  7186. statement(" if (!is_null_texture(plane2))");
  7187. statement(" return spvChromaReconstructLinear422CositedEven(");
  7188. statement(" plane0, plane1, plane2, samp,");
  7189. statement(" coord, options...);");
  7190. statement(" return spvChromaReconstructLinear422CositedEven(");
  7191. statement(" plane0, plane1, samp, coord,");
  7192. statement(" options...);");
  7193. statement("case spvXChromaLocation::midpoint:");
  7194. statement(" if (!is_null_texture(plane2))");
  7195. statement(" return spvChromaReconstructLinear422Midpoint(");
  7196. statement(" plane0, plane1, plane2, samp,");
  7197. statement(" coord, options...);");
  7198. statement(" return spvChromaReconstructLinear422Midpoint(");
  7199. statement(" plane0, plane1, samp, coord,");
  7200. statement(" options...);");
  7201. end_scope(); // switch (x_chroma_offset)
  7202. end_scope(); // case 422:
  7203. statement("case spvFormatResolution::_420:");
  7204. begin_scope();
  7205. statement("switch (ycbcr_samp.get_x_chroma_offset())");
  7206. begin_scope();
  7207. statement("case spvXChromaLocation::cosited_even:");
  7208. begin_scope();
  7209. statement("switch (ycbcr_samp.get_y_chroma_offset())");
  7210. begin_scope();
  7211. statement("case spvYChromaLocation::cosited_even:");
  7212. statement(" if (!is_null_texture(plane2))");
  7213. statement(" return spvChromaReconstructLinear420XCositedEvenYCositedEven(");
  7214. statement(" plane0, plane1, plane2, samp,");
  7215. statement(" coord, options...);");
  7216. statement(" return spvChromaReconstructLinear420XCositedEvenYCositedEven(");
  7217. statement(" plane0, plane1, samp, coord,");
  7218. statement(" options...);");
  7219. statement("case spvYChromaLocation::midpoint:");
  7220. statement(" if (!is_null_texture(plane2))");
  7221. statement(" return spvChromaReconstructLinear420XCositedEvenYMidpoint(");
  7222. statement(" plane0, plane1, plane2, samp,");
  7223. statement(" coord, options...);");
  7224. statement(" return spvChromaReconstructLinear420XCositedEvenYMidpoint(");
  7225. statement(" plane0, plane1, samp, coord,");
  7226. statement(" options...);");
  7227. end_scope(); // switch (y_chroma_offset)
  7228. end_scope(); // case x::cosited_even:
  7229. statement("case spvXChromaLocation::midpoint:");
  7230. begin_scope();
  7231. statement("switch (ycbcr_samp.get_y_chroma_offset())");
  7232. begin_scope();
  7233. statement("case spvYChromaLocation::cosited_even:");
  7234. statement(" if (!is_null_texture(plane2))");
  7235. statement(" return spvChromaReconstructLinear420XMidpointYCositedEven(");
  7236. statement(" plane0, plane1, plane2, samp,");
  7237. statement(" coord, options...);");
  7238. statement(" return spvChromaReconstructLinear420XMidpointYCositedEven(");
  7239. statement(" plane0, plane1, samp, coord,");
  7240. statement(" options...);");
  7241. statement("case spvYChromaLocation::midpoint:");
  7242. statement(" if (!is_null_texture(plane2))");
  7243. statement(" return spvChromaReconstructLinear420XMidpointYMidpoint(");
  7244. statement(" plane0, plane1, plane2, samp,");
  7245. statement(" coord, options...);");
  7246. statement(" return spvChromaReconstructLinear420XMidpointYMidpoint(");
  7247. statement(" plane0, plane1, samp, coord,");
  7248. statement(" options...);");
  7249. end_scope(); // switch (y_chroma_offset)
  7250. end_scope(); // case x::midpoint
  7251. end_scope(); // switch (x_chroma_offset)
  7252. end_scope(); // case 420:
  7253. end_scope(); // switch (resolution)
  7254. end_scope(); // if (multiplanar)
  7255. statement("return plane0.sample(samp, coord, options...);");
  7256. end_scope(); // do_sample()
  7257. statement("template <typename... LodOptions>");
  7258. statement("vec<T, 4> sample(float2 coord, LodOptions... options) const thread");
  7259. begin_scope();
  7260. statement("vec<T, 4> s = spvTextureSwizzle(do_sample(coord, options...), swizzle);");
  7261. statement("if (ycbcr_samp.get_ycbcr_model() == spvYCbCrModelConversion::rgb_identity)");
  7262. statement(" return s;");
  7263. statement("");
  7264. statement("switch (ycbcr_samp.get_ycbcr_range())");
  7265. begin_scope();
  7266. statement("case spvYCbCrRange::itu_full:");
  7267. statement(" s = spvExpandITUFullRange(s, ycbcr_samp.get_bpc());");
  7268. statement(" break;");
  7269. statement("case spvYCbCrRange::itu_narrow:");
  7270. statement(" s = spvExpandITUNarrowRange(s, ycbcr_samp.get_bpc());");
  7271. statement(" break;");
  7272. end_scope();
  7273. statement("");
  7274. statement("switch (ycbcr_samp.get_ycbcr_model())");
  7275. begin_scope();
  7276. statement("case spvYCbCrModelConversion::rgb_identity:"); // Silence Clang warning
  7277. statement("case spvYCbCrModelConversion::ycbcr_identity:");
  7278. statement(" return s;");
  7279. statement("case spvYCbCrModelConversion::ycbcr_bt_709:");
  7280. statement(" return spvConvertYCbCrBT709(s);");
  7281. statement("case spvYCbCrModelConversion::ycbcr_bt_601:");
  7282. statement(" return spvConvertYCbCrBT601(s);");
  7283. statement("case spvYCbCrModelConversion::ycbcr_bt_2020:");
  7284. statement(" return spvConvertYCbCrBT2020(s);");
  7285. end_scope();
  7286. end_scope();
  7287. statement("");
  7288. // Sampler Y'CbCr conversion forbids offsets.
  7289. statement("vec<T, 4> sample(float2 coord, int2 offset) const thread");
  7290. begin_scope();
  7291. if (msl_options.swizzle_texture_samples)
  7292. statement("return spvTextureSwizzle(plane0.sample(samp, coord, offset), swizzle);");
  7293. else
  7294. statement("return plane0.sample(samp, coord, offset);");
  7295. end_scope();
  7296. statement("template<typename lod_options>");
  7297. statement("vec<T, 4> sample(float2 coord, lod_options options, int2 offset) const thread");
  7298. begin_scope();
  7299. if (msl_options.swizzle_texture_samples)
  7300. statement("return spvTextureSwizzle(plane0.sample(samp, coord, options, offset), swizzle);");
  7301. else
  7302. statement("return plane0.sample(samp, coord, options, offset);");
  7303. end_scope();
  7304. statement("#if __HAVE_MIN_LOD_CLAMP__");
  7305. statement("vec<T, 4> sample(float2 coord, bias b, min_lod_clamp min_lod, int2 offset) const thread");
  7306. begin_scope();
  7307. statement("return plane0.sample(samp, coord, b, min_lod, offset);");
  7308. end_scope();
  7309. statement(
  7310. "vec<T, 4> sample(float2 coord, gradient2d grad, min_lod_clamp min_lod, int2 offset) const thread");
  7311. begin_scope();
  7312. statement("return plane0.sample(samp, coord, grad, min_lod, offset);");
  7313. end_scope();
  7314. statement("#endif");
  7315. statement("");
  7316. // Y'CbCr conversion forbids all operations but sampling.
  7317. statement("vec<T, 4> read(uint2 coord, uint lod = 0) const thread");
  7318. begin_scope();
  7319. statement("return plane0.read(coord, lod);");
  7320. end_scope();
  7321. statement("");
  7322. statement("vec<T, 4> gather(float2 coord, int2 offset = int2(0), component c = component::x) const thread");
  7323. begin_scope();
  7324. if (msl_options.swizzle_texture_samples)
  7325. statement("return spvGatherSwizzle(plane0, samp, swizzle, c, coord, offset);");
  7326. else
  7327. statement("return plane0.gather(samp, coord, offset, c);");
  7328. end_scope();
  7329. end_scope_decl();
  7330. statement("");
  7331. break;
  7332. case SPVFuncImplRayQueryIntersectionParams:
  7333. statement("intersection_params spvMakeIntersectionParams(uint flags)");
  7334. begin_scope();
  7335. statement("intersection_params ip;");
  7336. statement("if ((flags & ", RayFlagsOpaqueKHRMask, ") != 0)");
  7337. statement(" ip.force_opacity(forced_opacity::opaque);");
  7338. statement("if ((flags & ", RayFlagsNoOpaqueKHRMask, ") != 0)");
  7339. statement(" ip.force_opacity(forced_opacity::non_opaque);");
  7340. statement("if ((flags & ", RayFlagsTerminateOnFirstHitKHRMask, ") != 0)");
  7341. statement(" ip.accept_any_intersection(true);");
  7342. // RayFlagsSkipClosestHitShaderKHRMask is not available in MSL
  7343. statement("if ((flags & ", RayFlagsCullBackFacingTrianglesKHRMask, ") != 0)");
  7344. statement(" ip.set_triangle_cull_mode(triangle_cull_mode::back);");
  7345. statement("if ((flags & ", RayFlagsCullFrontFacingTrianglesKHRMask, ") != 0)");
  7346. statement(" ip.set_triangle_cull_mode(triangle_cull_mode::front);");
  7347. statement("if ((flags & ", RayFlagsCullOpaqueKHRMask, ") != 0)");
  7348. statement(" ip.set_opacity_cull_mode(opacity_cull_mode::opaque);");
  7349. statement("if ((flags & ", RayFlagsCullNoOpaqueKHRMask, ") != 0)");
  7350. statement(" ip.set_opacity_cull_mode(opacity_cull_mode::non_opaque);");
  7351. statement("if ((flags & ", RayFlagsSkipTrianglesKHRMask, ") != 0)");
  7352. statement(" ip.set_geometry_cull_mode(geometry_cull_mode::triangle);");
  7353. statement("if ((flags & ", RayFlagsSkipAABBsKHRMask, ") != 0)");
  7354. statement(" ip.set_geometry_cull_mode(geometry_cull_mode::bounding_box);");
  7355. statement("return ip;");
  7356. end_scope();
  7357. statement("");
  7358. break;
  7359. case SPVFuncImplVariableDescriptor:
  7360. statement("template<typename T>");
  7361. statement("struct spvDescriptor");
  7362. begin_scope();
  7363. statement("T value;");
  7364. end_scope_decl();
  7365. statement("");
  7366. break;
  7367. case SPVFuncImplVariableSizedDescriptor:
  7368. statement("template<typename T>");
  7369. statement("struct spvBufferDescriptor;");
  7370. statement("");
  7371. statement("template<typename T>");
  7372. statement("struct spvBufferDescriptor<device T*>");
  7373. begin_scope();
  7374. statement("device T* value;");
  7375. statement("int length;");
  7376. statement("int padding;");
  7377. end_scope_decl();
  7378. statement("");
  7379. break;
  7380. case SPVFuncImplVariableDescriptorArray:
  7381. if (spv_function_implementations.count(SPVFuncImplVariableDescriptor) != 0)
  7382. {
  7383. statement("template<typename T>");
  7384. statement("struct spvDescriptorArray");
  7385. begin_scope();
  7386. statement("spvDescriptorArray(const device spvDescriptor<T>* ptr_) : ptr(&ptr_->value) {}");
  7387. statement("spvDescriptorArray(const device void *ptr_) : spvDescriptorArray(static_cast<const device spvDescriptor<T>*>(ptr_)) {}");
  7388. statement("const device T& operator [] (size_t i) const { return ptr[i]; }");
  7389. statement("const device T* ptr;");
  7390. end_scope_decl();
  7391. statement("");
  7392. }
  7393. else
  7394. {
  7395. statement("template<typename T>");
  7396. statement("struct spvDescriptorArray;");
  7397. statement("");
  7398. }
  7399. if (msl_options.runtime_array_rich_descriptor &&
  7400. spv_function_implementations.count(SPVFuncImplVariableSizedDescriptor) != 0)
  7401. {
  7402. statement("template<typename T>");
  7403. statement("struct spvDescriptorArray<device T*>");
  7404. begin_scope();
  7405. statement("spvDescriptorArray(const device spvBufferDescriptor<device T*>* ptr_) : ptr(ptr_) {}");
  7406. statement("spvDescriptorArray(const device void *ptr_) : spvDescriptorArray(static_cast<const device spvBufferDescriptor<device T*>*>(ptr_)) {}");
  7407. statement("device T* operator [] (size_t i) const { return ptr[i].value; }");
  7408. statement("int length(int i) const { return ptr[i].length; }");
  7409. statement("const device spvBufferDescriptor<device T*>* ptr;");
  7410. end_scope_decl();
  7411. statement("");
  7412. }
  7413. break;
  7414. case SPVFuncImplPaddedStd140:
  7415. // .data is used in access chain.
  7416. statement("template <typename T>");
  7417. statement("struct spvPaddedStd140 { alignas(16) T data; };");
  7418. statement("template <typename T, int n>");
  7419. statement("using spvPaddedStd140Matrix = spvPaddedStd140<T>[n];");
  7420. statement("");
  7421. break;
  7422. case SPVFuncImplReduceAdd:
  7423. // Metal doesn't support __builtin_reduce_add or simd_reduce_add, so we need this.
  7424. // Metal also doesn't support the other vector builtins, which would have been useful to make this a single template.
  7425. statement("template <typename T>");
  7426. statement("T reduce_add(vec<T, 2> v) { return v.x + v.y; }");
  7427. statement("template <typename T>");
  7428. statement("T reduce_add(vec<T, 3> v) { return v.x + v.y + v.z; }");
  7429. statement("template <typename T>");
  7430. statement("T reduce_add(vec<T, 4> v) { return v.x + v.y + v.z + v.w; }");
  7431. statement("");
  7432. break;
  7433. case SPVFuncImplImageFence:
  7434. statement("template <typename ImageT>");
  7435. statement("void spvImageFence(ImageT img) { img.fence(); }");
  7436. statement("");
  7437. break;
  7438. case SPVFuncImplTextureCast:
  7439. statement("template <typename T, typename U>");
  7440. statement("T spvTextureCast(U img)");
  7441. begin_scope();
  7442. // MSL complains if you try to cast the texture itself, but casting the reference type is ... ok? *shrug*
  7443. // Gotta go what you gotta do I suppose.
  7444. statement("return reinterpret_cast<thread const T &>(img);");
  7445. end_scope();
  7446. statement("");
  7447. break;
  7448. case SPVFuncImplMulExtended:
  7449. // Compiler may hit an internal error with mulhi, but doesn't when encapsulated for some reason.
  7450. statement("template<typename T, typename U, typename V>");
  7451. statement("[[clang::optnone]] T spvMulExtended(V l, V r)");
  7452. begin_scope();
  7453. statement("return T{U(l * r), U(mulhi(l, r))};");
  7454. end_scope();
  7455. statement("");
  7456. break;
  7457. case SPVFuncImplSetMeshOutputsEXT:
  7458. statement("void spvSetMeshOutputsEXT(uint gl_LocalInvocationIndex, threadgroup uint2& spvMeshSizes, uint vertexCount, uint primitiveCount)");
  7459. begin_scope();
  7460. statement("if (gl_LocalInvocationIndex == 0)");
  7461. begin_scope();
  7462. statement("spvMeshSizes.x = vertexCount;");
  7463. statement("spvMeshSizes.y = primitiveCount;");
  7464. end_scope();
  7465. end_scope();
  7466. statement("");
  7467. break;
  7468. case SPVFuncImplAssume:
  7469. statement_no_indent("#if defined(__has_builtin)");
  7470. statement_no_indent("#if !defined(SPV_ASSUME) && __has_builtin(__builtin_assume)");
  7471. statement_no_indent("#define SPV_ASSUME(x) __builtin_assume(x);");
  7472. statement_no_indent("#endif");
  7473. statement_no_indent("#if !defined(SPV_EXPECT) && __has_builtin(__builtin_expect)");
  7474. statement_no_indent("#define SPV_EXPECT(x, y) __builtin_expect(x, y);");
  7475. statement_no_indent("#endif");
  7476. statement_no_indent("#endif");
  7477. statement_no_indent("#ifndef SPV_ASSUME");
  7478. statement_no_indent("#define SPV_ASSUME(x)");
  7479. statement_no_indent("#endif");
  7480. statement_no_indent("#ifndef SPV_EXPECT");
  7481. statement_no_indent("#define SPV_EXPECT(x, y) x");
  7482. statement_no_indent("#endif");
  7483. break;
  7484. default:
  7485. break;
  7486. }
  7487. }
  7488. }
  7489. static string inject_top_level_storage_qualifier(const string &expr, const string &qualifier)
  7490. {
  7491. // Easier to do this through text munging since the qualifier does not exist in the type system at all,
  7492. // and plumbing in all that information is not very helpful.
  7493. size_t last_reference = expr.find_last_of('&');
  7494. size_t last_pointer = expr.find_last_of('*');
  7495. size_t last_significant = string::npos;
  7496. if (last_reference == string::npos)
  7497. last_significant = last_pointer;
  7498. else if (last_pointer == string::npos)
  7499. last_significant = last_reference;
  7500. else
  7501. last_significant = max<size_t>(last_reference, last_pointer);
  7502. if (last_significant == string::npos)
  7503. return join(qualifier, " ", expr);
  7504. else
  7505. {
  7506. return join(expr.substr(0, last_significant + 1), " ",
  7507. qualifier, expr.substr(last_significant + 1, string::npos));
  7508. }
  7509. }
  7510. void CompilerMSL::declare_constant_arrays()
  7511. {
  7512. bool fully_inlined = ir.ids_for_type[TypeFunction].size() == 1;
  7513. // MSL cannot declare arrays inline (except when declaring a variable), so we must move them out to
  7514. // global constants directly, so we are able to use constants as variable expressions.
  7515. bool emitted = false;
  7516. ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) {
  7517. if (c.specialization)
  7518. return;
  7519. auto &type = this->get<SPIRType>(c.constant_type);
  7520. // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries.
  7521. // FIXME: However, hoisting constants to main() means we need to pass down constant arrays to leaf functions if they are used there.
  7522. // If there are multiple functions in the module, drop this case to avoid breaking use cases which do not need to
  7523. // link into Metal libraries. This is hacky.
  7524. if (is_array(type) && (!fully_inlined || is_scalar(type) || is_vector(type)))
  7525. {
  7526. add_resource_name(c.self);
  7527. auto name = to_name(c.self);
  7528. statement(inject_top_level_storage_qualifier(variable_decl(type, name), "constant"),
  7529. " = ", constant_expression(c), ";");
  7530. emitted = true;
  7531. }
  7532. });
  7533. if (emitted)
  7534. statement("");
  7535. }
  7536. // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries
  7537. void CompilerMSL::declare_complex_constant_arrays()
  7538. {
  7539. // If we do not have a fully inlined module, we did not opt in to
  7540. // declaring constant arrays of complex types. See CompilerMSL::declare_constant_arrays().
  7541. bool fully_inlined = ir.ids_for_type[TypeFunction].size() == 1;
  7542. if (!fully_inlined)
  7543. return;
  7544. // MSL cannot declare arrays inline (except when declaring a variable), so we must move them out to
  7545. // global constants directly, so we are able to use constants as variable expressions.
  7546. bool emitted = false;
  7547. ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) {
  7548. if (c.specialization)
  7549. return;
  7550. auto &type = this->get<SPIRType>(c.constant_type);
  7551. if (is_array(type) && !(is_scalar(type) || is_vector(type)))
  7552. {
  7553. add_resource_name(c.self);
  7554. auto name = to_name(c.self);
  7555. statement("", variable_decl(type, name), " = ", constant_expression(c), ";");
  7556. emitted = true;
  7557. }
  7558. });
  7559. if (emitted)
  7560. statement("");
  7561. }
  7562. void CompilerMSL::emit_resources()
  7563. {
  7564. declare_constant_arrays();
  7565. // Emit the special [[stage_in]] and [[stage_out]] interface blocks which we created.
  7566. emit_interface_block(stage_out_var_id);
  7567. emit_interface_block(patch_stage_out_var_id);
  7568. emit_interface_block(stage_in_var_id);
  7569. emit_interface_block(patch_stage_in_var_id);
  7570. if (get_execution_model() == ExecutionModelMeshEXT)
  7571. {
  7572. auto &execution = get_entry_point();
  7573. const char *topology = "";
  7574. if (execution.flags.get(ExecutionModeOutputTrianglesEXT))
  7575. topology = "topology::triangle";
  7576. else if (execution.flags.get(ExecutionModeOutputLinesEXT))
  7577. topology = "topology::line";
  7578. else if (execution.flags.get(ExecutionModeOutputPoints))
  7579. topology = "topology::point";
  7580. const char *per_vertex = mesh_out_per_vertex ? "spvPerVertex" : "float4";
  7581. const char *per_primitive = mesh_out_per_primitive ? "spvPerPrimitive" : "void";
  7582. statement("using spvMesh_t = mesh<", per_vertex, ", ", per_primitive, ", ", execution.output_vertices, ", ",
  7583. execution.output_primitives, ", ", topology, ">;");
  7584. statement("");
  7585. }
  7586. }
  7587. // Emit declarations for the specialization Metal function constants
  7588. void CompilerMSL::emit_specialization_constants_and_structs()
  7589. {
  7590. SpecializationConstant wg_x, wg_y, wg_z;
  7591. ID workgroup_size_id = get_work_group_size_specialization_constants(wg_x, wg_y, wg_z);
  7592. if (workgroup_size_id == 0 && is_mesh_shader())
  7593. {
  7594. auto &execution = get_entry_point();
  7595. statement("constant uint3 ", builtin_to_glsl(BuiltInWorkgroupSize, StorageClassWorkgroup),
  7596. " [[maybe_unused]] = ", "uint3(", execution.workgroup_size.x, ", ", execution.workgroup_size.y, ", ",
  7597. execution.workgroup_size.z, ");");
  7598. statement("");
  7599. }
  7600. bool emitted = false;
  7601. unordered_set<uint32_t> declared_structs;
  7602. unordered_set<uint32_t> aligned_structs;
  7603. // First, we need to deal with scalar block layout.
  7604. // It is possible that a struct may have to be placed at an alignment which does not match the innate alignment of the struct itself.
  7605. // In that case, if such a case exists for a struct, we must force that all elements of the struct become packed_ types.
  7606. // This makes the struct alignment as small as physically possible.
  7607. // When we actually align the struct later, we can insert padding as necessary to make the packed members behave like normally aligned types.
  7608. ir.for_each_typed_id<SPIRType>([&](uint32_t type_id, const SPIRType &type) {
  7609. if (type.basetype == SPIRType::Struct &&
  7610. has_extended_decoration(type_id, SPIRVCrossDecorationBufferBlockRepacked))
  7611. mark_scalar_layout_structs(type);
  7612. });
  7613. bool builtin_block_type_is_required = is_mesh_shader();
  7614. // Very special case. If gl_PerVertex is initialized as an array (tessellation)
  7615. // we have to potentially emit the gl_PerVertex struct type so that we can emit a constant LUT.
  7616. ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) {
  7617. auto &type = this->get<SPIRType>(c.constant_type);
  7618. if (is_array(type) && has_decoration(type.self, DecorationBlock) && is_builtin_type(type))
  7619. builtin_block_type_is_required = true;
  7620. });
  7621. // Very particular use of the soft loop lock.
  7622. // align_struct may need to create custom types on the fly, but we don't care about
  7623. // these types for purpose of iterating over them in ir.ids_for_type and friends.
  7624. auto loop_lock = ir.create_loop_soft_lock();
  7625. // Physical storage buffer pointers can have cyclical references,
  7626. // so emit forward declarations of them before other structs.
  7627. // Ignore type_id because we want the underlying struct type from the pointer.
  7628. ir.for_each_typed_id<SPIRType>([&](uint32_t /* type_id */, const SPIRType &type) {
  7629. if (type.basetype == SPIRType::Struct &&
  7630. type.pointer && type.storage == StorageClassPhysicalStorageBuffer &&
  7631. declared_structs.count(type.self) == 0)
  7632. {
  7633. statement("struct ", to_name(type.self), ";");
  7634. declared_structs.insert(type.self);
  7635. emitted = true;
  7636. }
  7637. });
  7638. if (emitted)
  7639. statement("");
  7640. emitted = false;
  7641. declared_structs.clear();
  7642. // It is possible to have multiple spec constants that use the same spec constant ID.
  7643. // The most common cause of this is defining spec constants in GLSL while also declaring
  7644. // the workgroup size to use those spec constants. But, Metal forbids declaring more than
  7645. // one variable with the same function constant ID.
  7646. // In this case, we must only declare one variable with the [[function_constant(id)]]
  7647. // attribute, and use its initializer to initialize all the spec constants with
  7648. // that ID.
  7649. std::unordered_map<uint32_t, ConstantID> unique_func_constants;
  7650. for (auto &id_ : ir.ids_for_constant_undef_or_type)
  7651. {
  7652. auto &id = ir.ids[id_];
  7653. if (id.get_type() == TypeConstant)
  7654. {
  7655. auto &c = id.get<SPIRConstant>();
  7656. if (c.self == workgroup_size_id)
  7657. {
  7658. // TODO: This can be expressed as a [[threads_per_threadgroup]] input semantic, but we need to know
  7659. // the work group size at compile time in SPIR-V, and [[threads_per_threadgroup]] would need to be passed around as a global.
  7660. // The work group size may be a specialization constant.
  7661. statement("constant uint3 ", builtin_to_glsl(BuiltInWorkgroupSize, StorageClassWorkgroup),
  7662. " [[maybe_unused]] = ", constant_expression(get<SPIRConstant>(workgroup_size_id)), ";");
  7663. emitted = true;
  7664. }
  7665. else if (c.specialization)
  7666. {
  7667. auto &type = get<SPIRType>(c.constant_type);
  7668. string sc_type_name = type_to_glsl(type);
  7669. add_resource_name(c.self);
  7670. string sc_name = to_name(c.self);
  7671. // Function constants are only supported in MSL 1.2 and later.
  7672. // If we don't support it just declare the "default" directly.
  7673. // This "default" value can be overridden to the true specialization constant by the API user.
  7674. // Specialization constants which are used as array length expressions cannot be function constants in MSL,
  7675. // so just fall back to macros.
  7676. if (msl_options.supports_msl_version(1, 2) && has_decoration(c.self, DecorationSpecId) &&
  7677. !c.is_used_as_array_length)
  7678. {
  7679. // Only scalar, non-composite values can be function constants.
  7680. uint32_t constant_id = get_decoration(c.self, DecorationSpecId);
  7681. if (!unique_func_constants.count(constant_id))
  7682. unique_func_constants.insert(make_pair(constant_id, c.self));
  7683. SPIRType::BaseType sc_tmp_type = expression_type(unique_func_constants[constant_id]).basetype;
  7684. string sc_tmp_name = to_name(unique_func_constants[constant_id]) + "_tmp";
  7685. if (unique_func_constants[constant_id] == c.self)
  7686. statement("constant ", sc_type_name, " ", sc_tmp_name, " [[function_constant(", constant_id,
  7687. ")]];");
  7688. // RenderDoc and other instrumentation may reuse the same SpecId with different base types.
  7689. // We deduplicate to one [[function_constant(id)]] temp and then initialize all variants from it.
  7690. // Metal forbids as_type to/from 'bool', so if either side is Boolean, avoid bitcasting here and
  7691. // prefer a value cast via a constructor instead (e.g. uint(tmp) / float(tmp) / bool(tmp)).
  7692. // This preserves expected toggle semantics and prevents illegal MSL like as_type<uint>(bool_tmp).
  7693. {
  7694. string sc_true_expr;
  7695. if (sc_tmp_type == type.basetype)
  7696. sc_true_expr = sc_tmp_name;
  7697. else if (sc_tmp_type == SPIRType::Boolean || type.basetype == SPIRType::Boolean)
  7698. sc_true_expr = join(sc_type_name, "(", sc_tmp_name, ")");
  7699. else
  7700. sc_true_expr = bitcast_expression(type, sc_tmp_type, sc_tmp_name);
  7701. statement("constant ", sc_type_name, " ", sc_name, " = is_function_constant_defined(", sc_tmp_name,
  7702. ") ? ", sc_true_expr, " : ", constant_expression(c), ";");
  7703. }
  7704. }
  7705. else if (has_decoration(c.self, DecorationSpecId))
  7706. {
  7707. // Fallback to macro overrides.
  7708. uint32_t constant_id = get_decoration(c.self, DecorationSpecId);
  7709. c.specialization_constant_macro_name =
  7710. constant_value_macro_name(constant_id);
  7711. statement("#ifndef ", c.specialization_constant_macro_name);
  7712. statement("#define ", c.specialization_constant_macro_name, " ", constant_expression(c));
  7713. statement("#endif");
  7714. statement("constant ", sc_type_name, " ", sc_name, " = ", c.specialization_constant_macro_name,
  7715. ";");
  7716. // Record the usage of macro
  7717. constant_macro_ids.insert(constant_id);
  7718. }
  7719. else
  7720. {
  7721. // Composite specialization constants must be built from other specialization constants.
  7722. statement("constant ", sc_type_name, " ", sc_name, " = ", constant_expression(c), ";");
  7723. }
  7724. emitted = true;
  7725. }
  7726. }
  7727. else if (id.get_type() == TypeConstantOp)
  7728. {
  7729. auto &c = id.get<SPIRConstantOp>();
  7730. auto &type = get<SPIRType>(c.basetype);
  7731. add_resource_name(c.self);
  7732. auto name = to_name(c.self);
  7733. statement("constant ", variable_decl(type, name), " = ", constant_op_expression(c), ";");
  7734. emitted = true;
  7735. }
  7736. else if (id.get_type() == TypeType)
  7737. {
  7738. // Output non-builtin interface structs. These include local function structs
  7739. // and structs nested within uniform and read-write buffers.
  7740. auto &type = id.get<SPIRType>();
  7741. TypeID type_id = type.self;
  7742. bool is_struct = (type.basetype == SPIRType::Struct) && type.array.empty() && !type.pointer;
  7743. bool is_block =
  7744. has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock);
  7745. bool is_builtin_block = is_block && is_builtin_type(type);
  7746. bool is_declarable_struct = is_struct && (!is_builtin_block || builtin_block_type_is_required);
  7747. // We'll declare this later.
  7748. if (stage_out_var_id && get_stage_out_struct_type().self == type_id)
  7749. is_declarable_struct = false;
  7750. if (patch_stage_out_var_id && get_patch_stage_out_struct_type().self == type_id)
  7751. is_declarable_struct = false;
  7752. if (stage_in_var_id && get_stage_in_struct_type().self == type_id)
  7753. is_declarable_struct = false;
  7754. if (patch_stage_in_var_id && get_patch_stage_in_struct_type().self == type_id)
  7755. is_declarable_struct = false;
  7756. // Special case. Declare builtin struct anyways if we need to emit a threadgroup version of it.
  7757. if (stage_out_masked_builtin_type_id == type_id)
  7758. is_declarable_struct = true;
  7759. // Align and emit declarable structs...but avoid declaring each more than once.
  7760. if (is_declarable_struct && declared_structs.count(type_id) == 0)
  7761. {
  7762. if (emitted)
  7763. statement("");
  7764. emitted = false;
  7765. declared_structs.insert(type_id);
  7766. if (has_extended_decoration(type_id, SPIRVCrossDecorationBufferBlockRepacked))
  7767. align_struct(type, aligned_structs);
  7768. // Make sure we declare the underlying struct type, and not the "decorated" type with pointers, etc.
  7769. emit_struct(get<SPIRType>(type_id));
  7770. }
  7771. }
  7772. else if (id.get_type() == TypeUndef)
  7773. {
  7774. auto &undef = id.get<SPIRUndef>();
  7775. auto &type = get<SPIRType>(undef.basetype);
  7776. // OpUndef can be void for some reason ...
  7777. if (type.basetype == SPIRType::Void)
  7778. return;
  7779. // Undefined global memory is not allowed in MSL.
  7780. // Declare constant and init to zeros. Use {}, as global constructors can break Metal.
  7781. statement(
  7782. inject_top_level_storage_qualifier(variable_decl(type, to_name(undef.self), undef.self), "constant"),
  7783. " = {};");
  7784. emitted = true;
  7785. }
  7786. }
  7787. if (emitted)
  7788. statement("");
  7789. }
  7790. void CompilerMSL::emit_binary_ptr_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op)
  7791. {
  7792. bool forward = should_forward(op0) && should_forward(op1);
  7793. emit_op(result_type, result_id, join(to_ptr_expression(op0), " ", op, " ", to_ptr_expression(op1)), forward);
  7794. inherit_expression_dependencies(result_id, op0);
  7795. inherit_expression_dependencies(result_id, op1);
  7796. }
  7797. string CompilerMSL::to_ptr_expression(uint32_t id, bool register_expression_read)
  7798. {
  7799. auto *e = maybe_get<SPIRExpression>(id);
  7800. auto expr = enclose_expression(e && e->need_transpose ? e->expression : to_expression(id, register_expression_read));
  7801. if (!should_dereference(id))
  7802. expr = address_of_expression(expr);
  7803. return expr;
  7804. }
  7805. void CompilerMSL::emit_binary_unord_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
  7806. const char *op)
  7807. {
  7808. bool forward = should_forward(op0) && should_forward(op1);
  7809. emit_op(result_type, result_id,
  7810. join("(isunordered(", to_enclosed_unpacked_expression(op0), ", ", to_enclosed_unpacked_expression(op1),
  7811. ") || ", to_enclosed_unpacked_expression(op0), " ", op, " ", to_enclosed_unpacked_expression(op1),
  7812. ")"),
  7813. forward);
  7814. inherit_expression_dependencies(result_id, op0);
  7815. inherit_expression_dependencies(result_id, op1);
  7816. }
  7817. bool CompilerMSL::emit_tessellation_io_load(uint32_t result_type_id, uint32_t id, uint32_t ptr)
  7818. {
  7819. auto &ptr_type = expression_type(ptr);
  7820. auto &result_type = get<SPIRType>(result_type_id);
  7821. if (ptr_type.storage != StorageClassInput && ptr_type.storage != StorageClassOutput)
  7822. return false;
  7823. if (ptr_type.storage == StorageClassOutput && is_tese_shader())
  7824. return false;
  7825. if (has_decoration(ptr, DecorationPatch))
  7826. return false;
  7827. bool ptr_is_io_variable = ir.ids[ptr].get_type() == TypeVariable;
  7828. bool flattened_io = variable_storage_requires_stage_io(ptr_type.storage);
  7829. bool flat_data_type = flattened_io &&
  7830. (is_matrix(result_type) || is_array(result_type) || result_type.basetype == SPIRType::Struct);
  7831. // Edge case, even with multi-patch workgroups, we still need to unroll load
  7832. // if we're loading control points directly.
  7833. if (ptr_is_io_variable && is_array(result_type))
  7834. flat_data_type = true;
  7835. if (!flat_data_type)
  7836. return false;
  7837. // Now, we must unflatten a composite type and take care of interleaving array access with gl_in/gl_out.
  7838. // Lots of painful code duplication since we *really* should not unroll these kinds of loads in entry point fixup
  7839. // unless we're forced to do this when the code is emitting inoptimal OpLoads.
  7840. string expr;
  7841. uint32_t interface_index = get_extended_decoration(ptr, SPIRVCrossDecorationInterfaceMemberIndex);
  7842. auto *var = maybe_get_backing_variable(ptr);
  7843. auto &expr_type = get_pointee_type(ptr_type.self);
  7844. const auto &iface_type = expression_type(stage_in_ptr_var_id);
  7845. if (!flattened_io)
  7846. {
  7847. // Simplest case for multi-patch workgroups, just unroll array as-is.
  7848. if (interface_index == uint32_t(-1))
  7849. return false;
  7850. expr += type_to_glsl(result_type) + "({ ";
  7851. uint32_t num_control_points = to_array_size_literal(result_type, uint32_t(result_type.array.size()) - 1);
  7852. for (uint32_t i = 0; i < num_control_points; i++)
  7853. {
  7854. const uint32_t indices[2] = { i, interface_index };
  7855. AccessChainMeta meta;
  7856. expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
  7857. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
  7858. if (i + 1 < num_control_points)
  7859. expr += ", ";
  7860. }
  7861. expr += " })";
  7862. }
  7863. else if (result_type.array.size() > 2)
  7864. {
  7865. SPIRV_CROSS_THROW("Cannot load tessellation IO variables with more than 2 dimensions.");
  7866. }
  7867. else if (result_type.array.size() == 2)
  7868. {
  7869. if (!ptr_is_io_variable)
  7870. SPIRV_CROSS_THROW("Loading an array-of-array must be loaded directly from an IO variable.");
  7871. if (interface_index == uint32_t(-1))
  7872. SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
  7873. if (result_type.basetype == SPIRType::Struct || is_matrix(result_type))
  7874. SPIRV_CROSS_THROW("Cannot load array-of-array of composite type in tessellation IO.");
  7875. expr += type_to_glsl(result_type) + "({ ";
  7876. uint32_t num_control_points = to_array_size_literal(result_type, 1);
  7877. uint32_t base_interface_index = interface_index;
  7878. auto &sub_type = get<SPIRType>(result_type.parent_type);
  7879. for (uint32_t i = 0; i < num_control_points; i++)
  7880. {
  7881. expr += type_to_glsl(sub_type) + "({ ";
  7882. interface_index = base_interface_index;
  7883. uint32_t array_size = to_array_size_literal(result_type, 0);
  7884. for (uint32_t j = 0; j < array_size; j++, interface_index++)
  7885. {
  7886. const uint32_t indices[2] = { i, interface_index };
  7887. AccessChainMeta meta;
  7888. expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
  7889. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
  7890. if (!is_matrix(sub_type) && sub_type.basetype != SPIRType::Struct &&
  7891. expr_type.vecsize > sub_type.vecsize)
  7892. expr += vector_swizzle(sub_type.vecsize, 0);
  7893. if (j + 1 < array_size)
  7894. expr += ", ";
  7895. }
  7896. expr += " })";
  7897. if (i + 1 < num_control_points)
  7898. expr += ", ";
  7899. }
  7900. expr += " })";
  7901. }
  7902. else if (result_type.basetype == SPIRType::Struct)
  7903. {
  7904. bool is_array_of_struct = is_array(result_type);
  7905. if (is_array_of_struct && !ptr_is_io_variable)
  7906. SPIRV_CROSS_THROW("Loading array of struct from IO variable must come directly from IO variable.");
  7907. uint32_t num_control_points = 1;
  7908. if (is_array_of_struct)
  7909. {
  7910. num_control_points = to_array_size_literal(result_type, 0);
  7911. expr += type_to_glsl(result_type) + "({ ";
  7912. }
  7913. auto &struct_type = is_array_of_struct ? get<SPIRType>(result_type.parent_type) : result_type;
  7914. assert(struct_type.array.empty());
  7915. for (uint32_t i = 0; i < num_control_points; i++)
  7916. {
  7917. expr += type_to_glsl(struct_type) + "{ ";
  7918. for (uint32_t j = 0; j < uint32_t(struct_type.member_types.size()); j++)
  7919. {
  7920. // The base interface index is stored per variable for structs.
  7921. if (var)
  7922. {
  7923. interface_index =
  7924. get_extended_member_decoration(var->self, j, SPIRVCrossDecorationInterfaceMemberIndex);
  7925. }
  7926. if (interface_index == uint32_t(-1))
  7927. SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
  7928. const auto &mbr_type = get<SPIRType>(struct_type.member_types[j]);
  7929. const auto &expr_mbr_type = get<SPIRType>(expr_type.member_types[j]);
  7930. if (is_matrix(mbr_type) && ptr_type.storage == StorageClassInput)
  7931. {
  7932. expr += type_to_glsl(mbr_type) + "(";
  7933. for (uint32_t k = 0; k < mbr_type.columns; k++, interface_index++)
  7934. {
  7935. if (is_array_of_struct)
  7936. {
  7937. const uint32_t indices[2] = { i, interface_index };
  7938. AccessChainMeta meta;
  7939. expr += access_chain_internal(
  7940. stage_in_ptr_var_id, indices, 2,
  7941. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
  7942. }
  7943. else
  7944. expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
  7945. if (expr_mbr_type.vecsize > mbr_type.vecsize)
  7946. expr += vector_swizzle(mbr_type.vecsize, 0);
  7947. if (k + 1 < mbr_type.columns)
  7948. expr += ", ";
  7949. }
  7950. expr += ")";
  7951. }
  7952. else if (is_array(mbr_type))
  7953. {
  7954. expr += type_to_glsl(mbr_type) + "({ ";
  7955. uint32_t array_size = to_array_size_literal(mbr_type, 0);
  7956. for (uint32_t k = 0; k < array_size; k++, interface_index++)
  7957. {
  7958. if (is_array_of_struct)
  7959. {
  7960. const uint32_t indices[2] = { i, interface_index };
  7961. AccessChainMeta meta;
  7962. expr += access_chain_internal(
  7963. stage_in_ptr_var_id, indices, 2,
  7964. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
  7965. }
  7966. else
  7967. expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
  7968. if (expr_mbr_type.vecsize > mbr_type.vecsize)
  7969. expr += vector_swizzle(mbr_type.vecsize, 0);
  7970. if (k + 1 < array_size)
  7971. expr += ", ";
  7972. }
  7973. expr += " })";
  7974. }
  7975. else
  7976. {
  7977. if (is_array_of_struct)
  7978. {
  7979. const uint32_t indices[2] = { i, interface_index };
  7980. AccessChainMeta meta;
  7981. expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
  7982. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT,
  7983. &meta);
  7984. }
  7985. else
  7986. expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
  7987. if (expr_mbr_type.vecsize > mbr_type.vecsize)
  7988. expr += vector_swizzle(mbr_type.vecsize, 0);
  7989. }
  7990. if (j + 1 < struct_type.member_types.size())
  7991. expr += ", ";
  7992. }
  7993. expr += " }";
  7994. if (i + 1 < num_control_points)
  7995. expr += ", ";
  7996. }
  7997. if (is_array_of_struct)
  7998. expr += " })";
  7999. }
  8000. else if (is_matrix(result_type))
  8001. {
  8002. bool is_array_of_matrix = is_array(result_type);
  8003. if (is_array_of_matrix && !ptr_is_io_variable)
  8004. SPIRV_CROSS_THROW("Loading array of matrix from IO variable must come directly from IO variable.");
  8005. if (interface_index == uint32_t(-1))
  8006. SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
  8007. if (is_array_of_matrix)
  8008. {
  8009. // Loading a matrix from each control point.
  8010. uint32_t base_interface_index = interface_index;
  8011. uint32_t num_control_points = to_array_size_literal(result_type, 0);
  8012. expr += type_to_glsl(result_type) + "({ ";
  8013. auto &matrix_type = get_variable_element_type(get<SPIRVariable>(ptr));
  8014. for (uint32_t i = 0; i < num_control_points; i++)
  8015. {
  8016. interface_index = base_interface_index;
  8017. expr += type_to_glsl(matrix_type) + "(";
  8018. for (uint32_t j = 0; j < result_type.columns; j++, interface_index++)
  8019. {
  8020. const uint32_t indices[2] = { i, interface_index };
  8021. AccessChainMeta meta;
  8022. expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
  8023. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
  8024. if (expr_type.vecsize > result_type.vecsize)
  8025. expr += vector_swizzle(result_type.vecsize, 0);
  8026. if (j + 1 < result_type.columns)
  8027. expr += ", ";
  8028. }
  8029. expr += ")";
  8030. if (i + 1 < num_control_points)
  8031. expr += ", ";
  8032. }
  8033. expr += " })";
  8034. }
  8035. else
  8036. {
  8037. expr += type_to_glsl(result_type) + "(";
  8038. for (uint32_t i = 0; i < result_type.columns; i++, interface_index++)
  8039. {
  8040. expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
  8041. if (expr_type.vecsize > result_type.vecsize)
  8042. expr += vector_swizzle(result_type.vecsize, 0);
  8043. if (i + 1 < result_type.columns)
  8044. expr += ", ";
  8045. }
  8046. expr += ")";
  8047. }
  8048. }
  8049. else if (ptr_is_io_variable)
  8050. {
  8051. assert(is_array(result_type));
  8052. assert(result_type.array.size() == 1);
  8053. if (interface_index == uint32_t(-1))
  8054. SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
  8055. // We're loading an array directly from a global variable.
  8056. // This means we're loading one member from each control point.
  8057. expr += type_to_glsl(result_type) + "({ ";
  8058. uint32_t num_control_points = to_array_size_literal(result_type, 0);
  8059. for (uint32_t i = 0; i < num_control_points; i++)
  8060. {
  8061. const uint32_t indices[2] = { i, interface_index };
  8062. AccessChainMeta meta;
  8063. expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
  8064. ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
  8065. if (expr_type.vecsize > result_type.vecsize)
  8066. expr += vector_swizzle(result_type.vecsize, 0);
  8067. if (i + 1 < num_control_points)
  8068. expr += ", ";
  8069. }
  8070. expr += " })";
  8071. }
  8072. else
  8073. {
  8074. // We're loading an array from a concrete control point.
  8075. assert(is_array(result_type));
  8076. assert(result_type.array.size() == 1);
  8077. if (interface_index == uint32_t(-1))
  8078. SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
  8079. expr += type_to_glsl(result_type) + "({ ";
  8080. uint32_t array_size = to_array_size_literal(result_type, 0);
  8081. for (uint32_t i = 0; i < array_size; i++, interface_index++)
  8082. {
  8083. expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
  8084. if (expr_type.vecsize > result_type.vecsize)
  8085. expr += vector_swizzle(result_type.vecsize, 0);
  8086. if (i + 1 < array_size)
  8087. expr += ", ";
  8088. }
  8089. expr += " })";
  8090. }
  8091. emit_op(result_type_id, id, expr, false);
  8092. register_read(id, ptr, false);
  8093. return true;
  8094. }
  8095. bool CompilerMSL::emit_tessellation_access_chain(const uint32_t *ops, uint32_t length)
  8096. {
  8097. // If this is a per-vertex output, remap it to the I/O array buffer.
  8098. // Any object which did not go through IO flattening shenanigans will go there instead.
  8099. // We will unflatten on-demand instead as needed, but not all possible cases can be supported, especially with arrays.
  8100. auto *var = maybe_get_backing_variable(ops[2]);
  8101. bool patch = false;
  8102. bool flat_data = false;
  8103. bool ptr_is_chain = false;
  8104. bool flatten_composites = false;
  8105. bool is_block = false;
  8106. bool is_arrayed = false;
  8107. if (var)
  8108. {
  8109. auto &type = get_variable_data_type(*var);
  8110. is_block = has_decoration(type.self, DecorationBlock);
  8111. is_arrayed = !type.array.empty();
  8112. flatten_composites = variable_storage_requires_stage_io(var->storage);
  8113. patch = has_decoration(ops[2], DecorationPatch) || is_patch_block(type);
  8114. // Should match strip_array in add_interface_block.
  8115. flat_data = var->storage == StorageClassInput || (var->storage == StorageClassOutput && is_tesc_shader());
  8116. // Patch inputs are treated as normal block IO variables, so they don't deal with this path at all.
  8117. if (patch && (!is_block || is_arrayed || var->storage == StorageClassInput))
  8118. flat_data = false;
  8119. // We might have a chained access chain, where
  8120. // we first take the access chain to the control point, and then we chain into a member or something similar.
  8121. // In this case, we need to skip gl_in/gl_out remapping.
  8122. // Also, skip ptr chain for patches.
  8123. ptr_is_chain = var->self != ID(ops[2]);
  8124. }
  8125. bool builtin_variable = false;
  8126. bool variable_is_flat = false;
  8127. if (var && flat_data)
  8128. {
  8129. builtin_variable = is_builtin_variable(*var);
  8130. BuiltIn bi_type = BuiltInMax;
  8131. if (builtin_variable && !is_block)
  8132. bi_type = BuiltIn(get_decoration(var->self, DecorationBuiltIn));
  8133. variable_is_flat = !builtin_variable || is_block ||
  8134. bi_type == BuiltInPosition || bi_type == BuiltInPointSize ||
  8135. bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance;
  8136. }
  8137. if (variable_is_flat)
  8138. {
  8139. // If output is masked, it is emitted as a "normal" variable, just go through normal code paths.
  8140. // Only check this for the first level of access chain.
  8141. // Dealing with this for partial access chains should be possible, but awkward.
  8142. if (var->storage == StorageClassOutput && !ptr_is_chain)
  8143. {
  8144. bool masked = false;
  8145. if (is_block)
  8146. {
  8147. uint32_t relevant_member_index = patch ? 3 : 4;
  8148. // FIXME: This won't work properly if the application first access chains into gl_out element,
  8149. // then access chains into the member. Super weird, but theoretically possible ...
  8150. if (length > relevant_member_index)
  8151. {
  8152. uint32_t mbr_idx = get<SPIRConstant>(ops[relevant_member_index]).scalar();
  8153. masked = is_stage_output_block_member_masked(*var, mbr_idx, true);
  8154. }
  8155. }
  8156. else if (var)
  8157. masked = is_stage_output_variable_masked(*var);
  8158. if (masked)
  8159. return false;
  8160. }
  8161. AccessChainMeta meta;
  8162. SmallVector<uint32_t> indices;
  8163. uint32_t next_id = ir.increase_bound_by(1);
  8164. indices.reserve(length - 3 + 1);
  8165. uint32_t first_non_array_index = (ptr_is_chain ? 3 : 4) - (patch ? 1 : 0);
  8166. VariableID stage_var_id;
  8167. if (patch)
  8168. stage_var_id = var->storage == StorageClassInput ? patch_stage_in_var_id : patch_stage_out_var_id;
  8169. else
  8170. stage_var_id = var->storage == StorageClassInput ? stage_in_ptr_var_id : stage_out_ptr_var_id;
  8171. VariableID ptr = ptr_is_chain ? VariableID(ops[2]) : stage_var_id;
  8172. if (!ptr_is_chain && !patch)
  8173. {
  8174. // Index into gl_in/gl_out with first array index.
  8175. indices.push_back(ops[first_non_array_index - 1]);
  8176. }
  8177. auto &result_ptr_type = get<SPIRType>(ops[0]);
  8178. uint32_t const_mbr_id = next_id++;
  8179. uint32_t index = get_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex);
  8180. // If we have a pointer chain expression, and we are no longer pointing to a composite
  8181. // object, we are in the clear. There is no longer a need to flatten anything.
  8182. bool further_access_chain_is_trivial = false;
  8183. if (ptr_is_chain && flatten_composites)
  8184. {
  8185. auto &ptr_type = expression_type(ptr);
  8186. if (!is_array(ptr_type) && !is_matrix(ptr_type) && ptr_type.basetype != SPIRType::Struct)
  8187. further_access_chain_is_trivial = true;
  8188. }
  8189. if (!further_access_chain_is_trivial && (flatten_composites || is_block))
  8190. {
  8191. uint32_t i = first_non_array_index;
  8192. auto *type = &get_variable_element_type(*var);
  8193. if (index == uint32_t(-1) && length >= (first_non_array_index + 1))
  8194. {
  8195. // Maybe this is a struct type in the input class, in which case
  8196. // we put it as a decoration on the corresponding member.
  8197. uint32_t mbr_idx = get_constant(ops[first_non_array_index]).scalar();
  8198. index = get_extended_member_decoration(var->self, mbr_idx,
  8199. SPIRVCrossDecorationInterfaceMemberIndex);
  8200. assert(index != uint32_t(-1));
  8201. i++;
  8202. type = &get<SPIRType>(type->member_types[mbr_idx]);
  8203. }
  8204. // In this case, we're poking into flattened structures and arrays, so now we have to
  8205. // combine the following indices. If we encounter a non-constant index,
  8206. // we're hosed.
  8207. for (; flatten_composites && i < length; ++i)
  8208. {
  8209. if (!is_array(*type) && !is_matrix(*type) && type->basetype != SPIRType::Struct)
  8210. break;
  8211. auto *c = maybe_get<SPIRConstant>(ops[i]);
  8212. if (!c || c->specialization)
  8213. SPIRV_CROSS_THROW("Trying to dynamically index into an array interface variable in tessellation. "
  8214. "This is currently unsupported.");
  8215. // We're in flattened space, so just increment the member index into IO block.
  8216. // We can only do this once in the current implementation, so either:
  8217. // Struct, Matrix or 1-dimensional array for a control point.
  8218. if (type->basetype == SPIRType::Struct && var->storage == StorageClassOutput)
  8219. {
  8220. // Need to consider holes, since individual block members might be masked away.
  8221. uint32_t mbr_idx = c->scalar();
  8222. for (uint32_t j = 0; j < mbr_idx; j++)
  8223. if (!is_stage_output_block_member_masked(*var, j, true))
  8224. index++;
  8225. }
  8226. else
  8227. index += c->scalar();
  8228. if (type->parent_type)
  8229. type = &get<SPIRType>(type->parent_type);
  8230. else if (type->basetype == SPIRType::Struct)
  8231. type = &get<SPIRType>(type->member_types[c->scalar()]);
  8232. }
  8233. // We're not going to emit the actual member name, we let any further OpLoad take care of that.
  8234. // Tag the access chain with the member index we're referencing.
  8235. auto &result_pointee_type = get_pointee_type(result_ptr_type);
  8236. bool defer_access_chain = flatten_composites && (is_matrix(result_pointee_type) || is_array(result_pointee_type) ||
  8237. result_pointee_type.basetype == SPIRType::Struct);
  8238. if (!defer_access_chain)
  8239. {
  8240. // Access the appropriate member of gl_in/gl_out.
  8241. set<SPIRConstant>(const_mbr_id, get_uint_type_id(), index, false);
  8242. indices.push_back(const_mbr_id);
  8243. // Member index is now irrelevant.
  8244. index = uint32_t(-1);
  8245. // Append any straggling access chain indices.
  8246. if (i < length)
  8247. indices.insert(indices.end(), ops + i, ops + length);
  8248. }
  8249. else
  8250. {
  8251. // We must have consumed the entire access chain if we're deferring it.
  8252. assert(i == length);
  8253. }
  8254. if (index != uint32_t(-1))
  8255. set_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex, index);
  8256. else
  8257. unset_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex);
  8258. }
  8259. else
  8260. {
  8261. if (index != uint32_t(-1))
  8262. {
  8263. set<SPIRConstant>(const_mbr_id, get_uint_type_id(), index, false);
  8264. indices.push_back(const_mbr_id);
  8265. }
  8266. // Member index is now irrelevant.
  8267. index = uint32_t(-1);
  8268. unset_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex);
  8269. indices.insert(indices.end(), ops + first_non_array_index, ops + length);
  8270. }
  8271. // We use the pointer to the base of the input/output array here,
  8272. // so this is always a pointer chain.
  8273. string e;
  8274. if (!ptr_is_chain)
  8275. {
  8276. // This is the start of an access chain, use ptr_chain to index into control point array.
  8277. e = access_chain(ptr, indices.data(), uint32_t(indices.size()), result_ptr_type, &meta, !patch);
  8278. }
  8279. else
  8280. {
  8281. // If we're accessing a struct, we need to use member indices which are based on the IO block,
  8282. // not actual struct type, so we have to use a split access chain here where
  8283. // first path resolves the control point index, i.e. gl_in[index], and second half deals with
  8284. // looking up flattened member name.
  8285. // However, it is possible that we partially accessed a struct,
  8286. // by taking pointer to member inside the control-point array.
  8287. // For this case, we fall back to a natural access chain since we have already dealt with remapping struct members.
  8288. // One way to check this here is if we have 2 implied read expressions.
  8289. // First one is the gl_in/gl_out struct itself, then an index into that array.
  8290. // If we have traversed further, we use a normal access chain formulation.
  8291. auto *ptr_expr = maybe_get<SPIRExpression>(ptr);
  8292. bool split_access_chain_formulation = flatten_composites && ptr_expr &&
  8293. ptr_expr->implied_read_expressions.size() == 2 &&
  8294. !further_access_chain_is_trivial;
  8295. if (split_access_chain_formulation)
  8296. {
  8297. e = join(to_expression(ptr),
  8298. access_chain_internal(stage_var_id, indices.data(), uint32_t(indices.size()),
  8299. ACCESS_CHAIN_CHAIN_ONLY_BIT, &meta));
  8300. }
  8301. else
  8302. {
  8303. e = access_chain_internal(ptr, indices.data(), uint32_t(indices.size()), 0, &meta);
  8304. }
  8305. }
  8306. // Get the actual type of the object that was accessed. If it's a vector type and we changed it,
  8307. // then we'll need to add a swizzle.
  8308. // For this, we can't necessarily rely on the type of the base expression, because it might be
  8309. // another access chain, and it will therefore already have the "correct" type.
  8310. auto *expr_type = &get_variable_data_type(*var);
  8311. if (has_extended_decoration(ops[2], SPIRVCrossDecorationTessIOOriginalInputTypeID))
  8312. expr_type = &get<SPIRType>(get_extended_decoration(ops[2], SPIRVCrossDecorationTessIOOriginalInputTypeID));
  8313. for (uint32_t i = 3; i < length; i++)
  8314. {
  8315. if (!is_array(*expr_type) && expr_type->basetype == SPIRType::Struct)
  8316. expr_type = &get<SPIRType>(expr_type->member_types[get<SPIRConstant>(ops[i]).scalar()]);
  8317. else
  8318. expr_type = &get<SPIRType>(expr_type->parent_type);
  8319. }
  8320. if (!is_array(*expr_type) && !is_matrix(*expr_type) && expr_type->basetype != SPIRType::Struct &&
  8321. expr_type->vecsize > result_ptr_type.vecsize)
  8322. e += vector_swizzle(result_ptr_type.vecsize, 0);
  8323. auto &expr = set<SPIRExpression>(ops[1], std::move(e), ops[0], should_forward(ops[2]));
  8324. expr.loaded_from = var->self;
  8325. expr.need_transpose = meta.need_transpose;
  8326. expr.access_chain = true;
  8327. // Mark the result as being packed if necessary.
  8328. if (meta.storage_is_packed)
  8329. set_extended_decoration(ops[1], SPIRVCrossDecorationPhysicalTypePacked);
  8330. if (meta.storage_physical_type != 0)
  8331. set_extended_decoration(ops[1], SPIRVCrossDecorationPhysicalTypeID, meta.storage_physical_type);
  8332. if (meta.storage_is_invariant)
  8333. set_decoration(ops[1], DecorationInvariant);
  8334. // Save the type we found in case the result is used in another access chain.
  8335. set_extended_decoration(ops[1], SPIRVCrossDecorationTessIOOriginalInputTypeID, expr_type->self);
  8336. // If we have some expression dependencies in our access chain, this access chain is technically a forwarded
  8337. // temporary which could be subject to invalidation.
  8338. // Need to assume we're forwarded while calling inherit_expression_depdendencies.
  8339. forwarded_temporaries.insert(ops[1]);
  8340. // The access chain itself is never forced to a temporary, but its dependencies might.
  8341. suppressed_usage_tracking.insert(ops[1]);
  8342. for (uint32_t i = 2; i < length; i++)
  8343. {
  8344. inherit_expression_dependencies(ops[1], ops[i]);
  8345. add_implied_read_expression(expr, ops[i]);
  8346. }
  8347. // If we have no dependencies after all, i.e., all indices in the access chain are immutable temporaries,
  8348. // we're not forwarded after all.
  8349. if (expr.expression_dependencies.empty())
  8350. forwarded_temporaries.erase(ops[1]);
  8351. return true;
  8352. }
  8353. // If this is the inner tessellation level, and we're tessellating triangles,
  8354. // drop the last index. It isn't an array in this case, so we can't have an
  8355. // array reference here. We need to make this ID a variable instead of an
  8356. // expression so we don't try to dereference it as a variable pointer.
  8357. // Don't do this if the index is a constant 1, though. We need to drop stores
  8358. // to that one.
  8359. auto *m = ir.find_meta(var ? var->self : ID(0));
  8360. if (is_tesc_shader() && var && m && m->decoration.builtin_type == BuiltInTessLevelInner &&
  8361. is_tessellating_triangles())
  8362. {
  8363. auto *c = maybe_get<SPIRConstant>(ops[3]);
  8364. if (c && c->scalar() == 1)
  8365. return false;
  8366. auto &dest_var = set<SPIRVariable>(ops[1], *var);
  8367. dest_var.basetype = ops[0];
  8368. ir.meta[ops[1]] = ir.meta[ops[2]];
  8369. inherit_expression_dependencies(ops[1], ops[2]);
  8370. return true;
  8371. }
  8372. return false;
  8373. }
  8374. bool CompilerMSL::is_out_of_bounds_tessellation_level(uint32_t id_lhs)
  8375. {
  8376. if (!is_tessellating_triangles())
  8377. return false;
  8378. // In SPIR-V, TessLevelInner always has two elements and TessLevelOuter always has
  8379. // four. This is true even if we are tessellating triangles. This allows clients
  8380. // to use a single tessellation control shader with multiple tessellation evaluation
  8381. // shaders.
  8382. // In Metal, however, only the first element of TessLevelInner and the first three
  8383. // of TessLevelOuter are accessible. This stems from how in Metal, the tessellation
  8384. // levels must be stored to a dedicated buffer in a particular format that depends
  8385. // on the patch type. Therefore, in Triangles mode, any store to the second
  8386. // inner level or the fourth outer level must be dropped.
  8387. const auto *e = maybe_get<SPIRExpression>(id_lhs);
  8388. if (!e || !e->access_chain)
  8389. return false;
  8390. BuiltIn builtin = BuiltIn(get_decoration(e->loaded_from, DecorationBuiltIn));
  8391. if (builtin != BuiltInTessLevelInner && builtin != BuiltInTessLevelOuter)
  8392. return false;
  8393. auto *c = maybe_get<SPIRConstant>(e->implied_read_expressions[1]);
  8394. if (!c)
  8395. return false;
  8396. return (builtin == BuiltInTessLevelInner && c->scalar() == 1) ||
  8397. (builtin == BuiltInTessLevelOuter && c->scalar() == 3);
  8398. }
  8399. bool CompilerMSL::prepare_access_chain_for_scalar_access(std::string &expr, const SPIRType &type,
  8400. StorageClass storage, bool &is_packed)
  8401. {
  8402. // If there is any risk of writes happening with the access chain in question,
  8403. // and there is a risk of concurrent write access to other components,
  8404. // we must cast the access chain to a plain pointer to ensure we only access the exact scalars we expect.
  8405. // The MSL compiler refuses to allow component-level access for any non-packed vector types.
  8406. // MSL refuses to take address or reference to vector component, even for packed types, so just force
  8407. // through the pointer cast. No much we can do sadly.
  8408. // For packed types, we could technically omit this if we know the reference does not have to turn into a pointer
  8409. // of some kind, but that requires external analysis passes to figure out, and
  8410. // this case is likely rare enough that we don't need to bother.
  8411. if (storage == StorageClassStorageBuffer || storage == StorageClassWorkgroup)
  8412. {
  8413. const char *addr_space = storage == StorageClassWorkgroup ? "threadgroup" : "device";
  8414. expr = join("((", addr_space, " ", type_to_glsl(type), "*)&", enclose_expression(expr), ")");
  8415. // Further indexing should happen with packed rules (array index, not swizzle).
  8416. is_packed = true;
  8417. return true;
  8418. }
  8419. else
  8420. return false;
  8421. }
  8422. bool CompilerMSL::access_chain_needs_stage_io_builtin_translation(uint32_t base)
  8423. {
  8424. auto *var = maybe_get_backing_variable(base);
  8425. if (!var || !is_tessellation_shader())
  8426. return true;
  8427. // We only need to rewrite builtin access chains when accessing flattened builtins like gl_ClipDistance_N.
  8428. // Avoid overriding it back to just gl_ClipDistance.
  8429. // This can only happen in scenarios where we cannot flatten/unflatten access chains, so, the only case
  8430. // where this triggers is evaluation shader inputs.
  8431. bool redirect_builtin = is_tese_shader() ? var->storage == StorageClassOutput : false;
  8432. return redirect_builtin;
  8433. }
  8434. // Sets the interface member index for an access chain to a pull-model interpolant.
  8435. void CompilerMSL::fix_up_interpolant_access_chain(const uint32_t *ops, uint32_t length)
  8436. {
  8437. auto *var = maybe_get_backing_variable(ops[2]);
  8438. if (!var || !pull_model_inputs.count(var->self))
  8439. return;
  8440. // Get the base index.
  8441. uint32_t interface_index;
  8442. auto &var_type = get_variable_data_type(*var);
  8443. auto &result_type = get<SPIRType>(ops[0]);
  8444. auto *type = &var_type;
  8445. if (has_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex))
  8446. {
  8447. interface_index = get_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex);
  8448. }
  8449. else
  8450. {
  8451. // Assume an access chain into a struct variable.
  8452. assert(var_type.basetype == SPIRType::Struct);
  8453. auto &c = get<SPIRConstant>(ops[3 + var_type.array.size()]);
  8454. interface_index =
  8455. get_extended_member_decoration(var->self, c.scalar(), SPIRVCrossDecorationInterfaceMemberIndex);
  8456. }
  8457. // Accumulate indices. We'll have to skip over the one for the struct, if present, because we already accounted
  8458. // for that getting the base index.
  8459. for (uint32_t i = 3; i < length; ++i)
  8460. {
  8461. if (is_vector(*type) && !is_array(*type) && is_scalar(result_type))
  8462. {
  8463. // We don't want to combine the next index. Actually, we need to save it
  8464. // so we know to apply a swizzle to the result of the interpolation.
  8465. set_extended_decoration(ops[1], SPIRVCrossDecorationInterpolantComponentExpr, ops[i]);
  8466. break;
  8467. }
  8468. auto *c = maybe_get<SPIRConstant>(ops[i]);
  8469. if (!c || c->specialization)
  8470. SPIRV_CROSS_THROW("Trying to dynamically index into an array interface variable using pull-model "
  8471. "interpolation. This is currently unsupported.");
  8472. if (type->parent_type)
  8473. type = &get<SPIRType>(type->parent_type);
  8474. else if (type->basetype == SPIRType::Struct)
  8475. type = &get<SPIRType>(type->member_types[c->scalar()]);
  8476. if (!has_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex) &&
  8477. i - 3 == var_type.array.size())
  8478. continue;
  8479. interface_index += c->scalar();
  8480. }
  8481. // Save this to the access chain itself so we can recover it later when calling an interpolation function.
  8482. set_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex, interface_index);
  8483. }
  8484. // If the physical type of a physical buffer pointer has been changed
  8485. // to a ulong or ulongn vector, add a cast back to the pointer type.
  8486. bool CompilerMSL::check_physical_type_cast(std::string &expr, const SPIRType *type, uint32_t physical_type)
  8487. {
  8488. auto *p_physical_type = maybe_get<SPIRType>(physical_type);
  8489. if (p_physical_type &&
  8490. p_physical_type->storage == StorageClassPhysicalStorageBuffer &&
  8491. p_physical_type->basetype == to_unsigned_basetype(64))
  8492. {
  8493. if (p_physical_type->vecsize > 1)
  8494. expr += ".x";
  8495. expr = join("((", type_to_glsl(*type), ")", expr, ")");
  8496. return true;
  8497. }
  8498. return false;
  8499. }
  8500. // Override for MSL-specific syntax instructions
  8501. void CompilerMSL::emit_instruction(const Instruction &instruction)
  8502. {
  8503. #define MSL_BOP(op) emit_binary_op(ops[0], ops[1], ops[2], ops[3], #op)
  8504. #define MSL_PTR_BOP(op) emit_binary_ptr_op(ops[0], ops[1], ops[2], ops[3], #op)
  8505. // MSL does care about implicit integer promotion, but those cases are all handled in common code.
  8506. #define MSL_BOP_CAST(op, type) \
  8507. emit_binary_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, opcode_is_sign_invariant(opcode), false)
  8508. #define MSL_UOP(op) emit_unary_op(ops[0], ops[1], ops[2], #op)
  8509. #define MSL_QFOP(op) emit_quaternary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], ops[5], #op)
  8510. #define MSL_TFOP(op) emit_trinary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], #op)
  8511. #define MSL_BFOP(op) emit_binary_func_op(ops[0], ops[1], ops[2], ops[3], #op)
  8512. #define MSL_BFOP_CAST(op, type) \
  8513. emit_binary_func_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, opcode_is_sign_invariant(opcode))
  8514. #define MSL_UFOP(op) emit_unary_func_op(ops[0], ops[1], ops[2], #op)
  8515. #define MSL_UNORD_BOP(op) emit_binary_unord_op(ops[0], ops[1], ops[2], ops[3], #op)
  8516. auto ops = stream(instruction);
  8517. auto opcode = static_cast<Op>(instruction.op);
  8518. opcode = get_remapped_spirv_op(opcode);
  8519. // If we need to do implicit bitcasts, make sure we do it with the correct type.
  8520. uint32_t integer_width = get_integer_width_for_instruction(instruction);
  8521. auto int_type = to_signed_basetype(integer_width);
  8522. auto uint_type = to_unsigned_basetype(integer_width);
  8523. switch (opcode)
  8524. {
  8525. case OpLoad:
  8526. {
  8527. uint32_t id = ops[1];
  8528. uint32_t ptr = ops[2];
  8529. if (is_tessellation_shader())
  8530. {
  8531. if (!emit_tessellation_io_load(ops[0], id, ptr))
  8532. CompilerGLSL::emit_instruction(instruction);
  8533. }
  8534. else
  8535. {
  8536. // Sample mask input for Metal is not an array
  8537. if (BuiltIn(get_decoration(ptr, DecorationBuiltIn)) == BuiltInSampleMask)
  8538. set_decoration(id, DecorationBuiltIn, BuiltInSampleMask);
  8539. CompilerGLSL::emit_instruction(instruction);
  8540. }
  8541. break;
  8542. }
  8543. // Comparisons
  8544. case OpIEqual:
  8545. MSL_BOP_CAST(==, int_type);
  8546. break;
  8547. case OpLogicalEqual:
  8548. case OpFOrdEqual:
  8549. MSL_BOP(==);
  8550. break;
  8551. case OpINotEqual:
  8552. MSL_BOP_CAST(!=, int_type);
  8553. break;
  8554. case OpLogicalNotEqual:
  8555. case OpFOrdNotEqual:
  8556. // TODO: Should probably negate the == result here.
  8557. // Typically OrdNotEqual comes from GLSL which itself does not really specify what
  8558. // happens with NaN.
  8559. // Consider fixing this if we run into real issues.
  8560. MSL_BOP(!=);
  8561. break;
  8562. case OpUGreaterThan:
  8563. MSL_BOP_CAST(>, uint_type);
  8564. break;
  8565. case OpSGreaterThan:
  8566. MSL_BOP_CAST(>, int_type);
  8567. break;
  8568. case OpFOrdGreaterThan:
  8569. MSL_BOP(>);
  8570. break;
  8571. case OpUGreaterThanEqual:
  8572. MSL_BOP_CAST(>=, uint_type);
  8573. break;
  8574. case OpSGreaterThanEqual:
  8575. MSL_BOP_CAST(>=, int_type);
  8576. break;
  8577. case OpFOrdGreaterThanEqual:
  8578. MSL_BOP(>=);
  8579. break;
  8580. case OpULessThan:
  8581. MSL_BOP_CAST(<, uint_type);
  8582. break;
  8583. case OpSLessThan:
  8584. MSL_BOP_CAST(<, int_type);
  8585. break;
  8586. case OpFOrdLessThan:
  8587. MSL_BOP(<);
  8588. break;
  8589. case OpULessThanEqual:
  8590. MSL_BOP_CAST(<=, uint_type);
  8591. break;
  8592. case OpSLessThanEqual:
  8593. MSL_BOP_CAST(<=, int_type);
  8594. break;
  8595. case OpFOrdLessThanEqual:
  8596. MSL_BOP(<=);
  8597. break;
  8598. case OpFUnordEqual:
  8599. MSL_UNORD_BOP(==);
  8600. break;
  8601. case OpFUnordNotEqual:
  8602. // not equal in MSL generates une opcodes to begin with.
  8603. // Since unordered not equal is how it works in C, just inherit that behavior.
  8604. MSL_BOP(!=);
  8605. break;
  8606. case OpFUnordGreaterThan:
  8607. MSL_UNORD_BOP(>);
  8608. break;
  8609. case OpFUnordGreaterThanEqual:
  8610. MSL_UNORD_BOP(>=);
  8611. break;
  8612. case OpFUnordLessThan:
  8613. MSL_UNORD_BOP(<);
  8614. break;
  8615. case OpFUnordLessThanEqual:
  8616. MSL_UNORD_BOP(<=);
  8617. break;
  8618. // Pointer math
  8619. case OpPtrEqual:
  8620. MSL_PTR_BOP(==);
  8621. break;
  8622. case OpPtrNotEqual:
  8623. MSL_PTR_BOP(!=);
  8624. break;
  8625. case OpPtrDiff:
  8626. MSL_PTR_BOP(-);
  8627. break;
  8628. // Derivatives
  8629. case OpDPdx:
  8630. case OpDPdxFine:
  8631. case OpDPdxCoarse:
  8632. MSL_UFOP(dfdx);
  8633. register_control_dependent_expression(ops[1]);
  8634. break;
  8635. case OpDPdy:
  8636. case OpDPdyFine:
  8637. case OpDPdyCoarse:
  8638. MSL_UFOP(dfdy);
  8639. register_control_dependent_expression(ops[1]);
  8640. break;
  8641. case OpFwidth:
  8642. case OpFwidthCoarse:
  8643. case OpFwidthFine:
  8644. MSL_UFOP(fwidth);
  8645. register_control_dependent_expression(ops[1]);
  8646. break;
  8647. // Bitfield
  8648. case OpBitFieldInsert:
  8649. {
  8650. emit_bitfield_insert_op(ops[0], ops[1], ops[2], ops[3], ops[4], ops[5], "insert_bits", SPIRType::UInt);
  8651. break;
  8652. }
  8653. case OpBitFieldSExtract:
  8654. {
  8655. emit_trinary_func_op_bitextract(ops[0], ops[1], ops[2], ops[3], ops[4], "extract_bits", int_type, int_type,
  8656. SPIRType::UInt, SPIRType::UInt);
  8657. break;
  8658. }
  8659. case OpBitFieldUExtract:
  8660. {
  8661. emit_trinary_func_op_bitextract(ops[0], ops[1], ops[2], ops[3], ops[4], "extract_bits", uint_type, uint_type,
  8662. SPIRType::UInt, SPIRType::UInt);
  8663. break;
  8664. }
  8665. case OpBitReverse:
  8666. // BitReverse does not have issues with sign since result type must match input type.
  8667. MSL_UFOP(reverse_bits);
  8668. break;
  8669. case OpBitCount:
  8670. {
  8671. auto basetype = expression_type(ops[2]).basetype;
  8672. emit_unary_func_op_cast(ops[0], ops[1], ops[2], "popcount", basetype, basetype);
  8673. break;
  8674. }
  8675. case OpSMod:
  8676. MSL_BFOP(spvSMod);
  8677. break;
  8678. case OpFRem:
  8679. MSL_BFOP(fmod);
  8680. break;
  8681. case OpFMul:
  8682. if (msl_options.invariant_float_math || has_legacy_nocontract(ops[0], ops[1]))
  8683. MSL_BFOP(spvFMul);
  8684. else
  8685. MSL_BOP(*);
  8686. break;
  8687. case OpFAdd:
  8688. if (msl_options.invariant_float_math || has_legacy_nocontract(ops[0], ops[1]))
  8689. MSL_BFOP(spvFAdd);
  8690. else
  8691. MSL_BOP(+);
  8692. break;
  8693. case OpFSub:
  8694. if (msl_options.invariant_float_math || has_legacy_nocontract(ops[0], ops[1]))
  8695. MSL_BFOP(spvFSub);
  8696. else
  8697. MSL_BOP(-);
  8698. break;
  8699. case OpFmaKHR:
  8700. MSL_TFOP(fma);
  8701. break;
  8702. // Atomics
  8703. case OpAtomicExchange:
  8704. {
  8705. uint32_t result_type = ops[0];
  8706. uint32_t id = ops[1];
  8707. uint32_t ptr = ops[2];
  8708. uint32_t mem_sem = ops[4];
  8709. uint32_t val = ops[5];
  8710. emit_atomic_func_op(result_type, id, "atomic_exchange", opcode, mem_sem, mem_sem, false, ptr, val);
  8711. break;
  8712. }
  8713. case OpAtomicCompareExchange:
  8714. {
  8715. uint32_t result_type = ops[0];
  8716. uint32_t id = ops[1];
  8717. uint32_t ptr = ops[2];
  8718. uint32_t mem_sem_pass = ops[4];
  8719. uint32_t mem_sem_fail = ops[5];
  8720. uint32_t val = ops[6];
  8721. uint32_t comp = ops[7];
  8722. emit_atomic_func_op(result_type, id, "atomic_compare_exchange_weak", opcode,
  8723. mem_sem_pass, mem_sem_fail, true,
  8724. ptr, comp, true, false, val);
  8725. break;
  8726. }
  8727. case OpAtomicCompareExchangeWeak:
  8728. SPIRV_CROSS_THROW("OpAtomicCompareExchangeWeak is only supported in kernel profile.");
  8729. case OpAtomicLoad:
  8730. {
  8731. uint32_t result_type = ops[0];
  8732. uint32_t id = ops[1];
  8733. uint32_t ptr = ops[2];
  8734. uint32_t mem_sem = ops[4];
  8735. check_atomic_image(ptr);
  8736. emit_atomic_func_op(result_type, id, "atomic_load", opcode, mem_sem, mem_sem, false, ptr, 0);
  8737. break;
  8738. }
  8739. case OpAtomicStore:
  8740. {
  8741. uint32_t result_type = expression_type(ops[0]).self;
  8742. uint32_t id = ops[0];
  8743. uint32_t ptr = ops[0];
  8744. uint32_t mem_sem = ops[2];
  8745. uint32_t val = ops[3];
  8746. check_atomic_image(ptr);
  8747. emit_atomic_func_op(result_type, id, "atomic_store", opcode, mem_sem, mem_sem, false, ptr, val);
  8748. break;
  8749. }
  8750. #define MSL_AFMO_IMPL(op, valsrc, valconst) \
  8751. do \
  8752. { \
  8753. uint32_t result_type = ops[0]; \
  8754. uint32_t id = ops[1]; \
  8755. uint32_t ptr = ops[2]; \
  8756. uint32_t mem_sem = ops[4]; \
  8757. uint32_t val = valsrc; \
  8758. emit_atomic_func_op(result_type, id, "atomic_fetch_" #op, opcode, \
  8759. mem_sem, mem_sem, false, ptr, val, \
  8760. false, valconst); \
  8761. } while (false)
  8762. #define MSL_AFMO(op) MSL_AFMO_IMPL(op, ops[5], false)
  8763. #define MSL_AFMIO(op) MSL_AFMO_IMPL(op, 1, true)
  8764. case OpAtomicIIncrement:
  8765. MSL_AFMIO(add);
  8766. break;
  8767. case OpAtomicIDecrement:
  8768. MSL_AFMIO(sub);
  8769. break;
  8770. case OpAtomicIAdd:
  8771. case OpAtomicFAddEXT:
  8772. MSL_AFMO(add);
  8773. break;
  8774. case OpAtomicISub:
  8775. MSL_AFMO(sub);
  8776. break;
  8777. case OpAtomicSMin:
  8778. case OpAtomicUMin:
  8779. MSL_AFMO(min);
  8780. break;
  8781. case OpAtomicSMax:
  8782. case OpAtomicUMax:
  8783. MSL_AFMO(max);
  8784. break;
  8785. case OpAtomicAnd:
  8786. MSL_AFMO(and);
  8787. break;
  8788. case OpAtomicOr:
  8789. MSL_AFMO(or);
  8790. break;
  8791. case OpAtomicXor:
  8792. MSL_AFMO(xor);
  8793. break;
  8794. // Images
  8795. // Reads == Fetches in Metal
  8796. case OpImageRead:
  8797. {
  8798. // Mark that this shader reads from this image
  8799. uint32_t img_id = ops[2];
  8800. auto &type = expression_type(img_id);
  8801. auto *p_var = maybe_get_backing_variable(img_id);
  8802. if (type.image.dim != DimSubpassData)
  8803. {
  8804. if (p_var && has_decoration(p_var->self, DecorationNonReadable))
  8805. {
  8806. unset_decoration(p_var->self, DecorationNonReadable);
  8807. force_recompile();
  8808. }
  8809. }
  8810. // Metal requires explicit fences to break up RAW hazards, even within the same shader invocation
  8811. if (msl_options.readwrite_texture_fences && p_var && !has_decoration(p_var->self, DecorationNonWritable))
  8812. {
  8813. add_spv_func_and_recompile(SPVFuncImplImageFence);
  8814. // Need to wrap this with a value type,
  8815. // since the Metal headers are broken and do not consider case when the image is a reference.
  8816. statement("spvImageFence(", to_expression(img_id), ");");
  8817. }
  8818. emit_texture_op(instruction, false);
  8819. break;
  8820. }
  8821. // Emulate texture2D atomic operations
  8822. case OpImageTexelPointer:
  8823. {
  8824. // When using the pointer, we need to know which variable it is actually loaded from.
  8825. auto *var = maybe_get_backing_variable(ops[2]);
  8826. if (var && atomic_image_vars_emulated.count(var->self))
  8827. {
  8828. uint32_t result_type = ops[0];
  8829. uint32_t id = ops[1];
  8830. std::string coord = to_expression(ops[3]);
  8831. auto &type = expression_type(ops[2]);
  8832. if (type.image.dim == Dim2D)
  8833. {
  8834. coord = join("spvImage2DAtomicCoord(", coord, ", ", to_expression(ops[2]), ")");
  8835. }
  8836. auto &e = set<SPIRExpression>(id, join(to_expression(ops[2]), "_atomic[", coord, "]"), result_type, true);
  8837. e.loaded_from = var ? var->self : ID(0);
  8838. inherit_expression_dependencies(id, ops[3]);
  8839. }
  8840. else
  8841. {
  8842. uint32_t result_type = ops[0];
  8843. uint32_t id = ops[1];
  8844. // Virtual expression. Split this up in the actual image atomic.
  8845. // In GLSL and HLSL we are able to resolve the dereference inline, but MSL has
  8846. // image.op(coord, ...) syntax.
  8847. auto &e =
  8848. set<SPIRExpression>(id, join(to_expression(ops[2]), "@",
  8849. bitcast_expression(SPIRType::UInt, ops[3])),
  8850. result_type, true);
  8851. // When using the pointer, we need to know which variable it is actually loaded from.
  8852. e.loaded_from = var ? var->self : ID(0);
  8853. inherit_expression_dependencies(id, ops[3]);
  8854. }
  8855. break;
  8856. }
  8857. case OpImageWrite:
  8858. {
  8859. uint32_t img_id = ops[0];
  8860. uint32_t coord_id = ops[1];
  8861. uint32_t texel_id = ops[2];
  8862. const uint32_t *opt = &ops[3];
  8863. uint32_t length = instruction.length - 3;
  8864. // Bypass pointers because we need the real image struct
  8865. auto &type = expression_type(img_id);
  8866. auto &img_type = get<SPIRType>(type.self);
  8867. // Ensure this image has been marked as being written to and force a
  8868. // recommpile so that the image type output will include write access
  8869. auto *p_var = maybe_get_backing_variable(img_id);
  8870. if (p_var && has_decoration(p_var->self, DecorationNonWritable))
  8871. {
  8872. unset_decoration(p_var->self, DecorationNonWritable);
  8873. force_recompile();
  8874. }
  8875. bool forward = false;
  8876. uint32_t bias = 0;
  8877. uint32_t lod = 0;
  8878. uint32_t flags = 0;
  8879. if (length)
  8880. {
  8881. flags = *opt++;
  8882. length--;
  8883. }
  8884. auto test = [&](uint32_t &v, uint32_t flag) {
  8885. if (length && (flags & flag))
  8886. {
  8887. v = *opt++;
  8888. length--;
  8889. }
  8890. };
  8891. test(bias, ImageOperandsBiasMask);
  8892. test(lod, ImageOperandsLodMask);
  8893. auto &texel_type = expression_type(texel_id);
  8894. auto store_type = texel_type;
  8895. store_type.vecsize = 4;
  8896. TextureFunctionArguments args = {};
  8897. args.base.img = img_id;
  8898. args.base.imgtype = &img_type;
  8899. args.base.is_fetch = true;
  8900. args.coord = coord_id;
  8901. args.lod = lod;
  8902. string expr;
  8903. if (needs_frag_discard_checks())
  8904. expr = join("(", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), " ? ((void)0) : ");
  8905. expr += join(to_expression(img_id), ".write(",
  8906. remap_swizzle(store_type, texel_type.vecsize, to_expression(texel_id)), ", ",
  8907. CompilerMSL::to_function_args(args, &forward), ")");
  8908. if (needs_frag_discard_checks())
  8909. expr += ")";
  8910. statement(expr, ";");
  8911. if (p_var && variable_storage_is_aliased(*p_var))
  8912. flush_all_aliased_variables();
  8913. break;
  8914. }
  8915. case OpImageQuerySize:
  8916. case OpImageQuerySizeLod:
  8917. {
  8918. uint32_t rslt_type_id = ops[0];
  8919. auto &rslt_type = get<SPIRType>(rslt_type_id);
  8920. uint32_t id = ops[1];
  8921. uint32_t img_id = ops[2];
  8922. string img_exp = to_expression(img_id);
  8923. auto &img_type = expression_type(img_id);
  8924. Dim img_dim = img_type.image.dim;
  8925. bool img_is_array = img_type.image.arrayed;
  8926. if (img_type.basetype != SPIRType::Image)
  8927. SPIRV_CROSS_THROW("Invalid type for OpImageQuerySize.");
  8928. string lod;
  8929. if (opcode == OpImageQuerySizeLod)
  8930. {
  8931. // LOD index defaults to zero, so don't bother outputing level zero index
  8932. string decl_lod = to_expression(ops[3]);
  8933. if (decl_lod != "0")
  8934. lod = decl_lod;
  8935. }
  8936. string expr = type_to_glsl(rslt_type) + "(";
  8937. expr += img_exp + ".get_width(" + lod + ")";
  8938. if (img_dim == Dim2D || img_dim == DimCube || img_dim == Dim3D)
  8939. expr += ", " + img_exp + ".get_height(" + lod + ")";
  8940. if (img_dim == Dim3D)
  8941. expr += ", " + img_exp + ".get_depth(" + lod + ")";
  8942. if (img_is_array)
  8943. {
  8944. expr += ", " + img_exp + ".get_array_size()";
  8945. if (img_dim == DimCube && msl_options.emulate_cube_array)
  8946. expr += " / 6";
  8947. }
  8948. expr += ")";
  8949. emit_op(rslt_type_id, id, expr, should_forward(img_id));
  8950. break;
  8951. }
  8952. case OpImageQueryLod:
  8953. {
  8954. if (!msl_options.supports_msl_version(2, 2))
  8955. SPIRV_CROSS_THROW("ImageQueryLod is only supported on MSL 2.2 and up.");
  8956. uint32_t result_type = ops[0];
  8957. uint32_t id = ops[1];
  8958. uint32_t image_id = ops[2];
  8959. uint32_t coord_id = ops[3];
  8960. emit_uninitialized_temporary_expression(result_type, id);
  8961. std::string coord_expr = to_expression(coord_id);
  8962. auto sampler_expr = to_sampler_expression(image_id);
  8963. auto *combined = maybe_get<SPIRCombinedImageSampler>(image_id);
  8964. auto image_expr = combined ? to_expression(combined->image) : to_expression(image_id);
  8965. const SPIRType &image_type = expression_type(image_id);
  8966. const SPIRType &coord_type = expression_type(coord_id);
  8967. switch (image_type.image.dim)
  8968. {
  8969. case Dim1D:
  8970. if (!msl_options.texture_1D_as_2D)
  8971. SPIRV_CROSS_THROW("ImageQueryLod is not supported on 1D textures.");
  8972. [[fallthrough]];
  8973. case Dim2D:
  8974. if (coord_type.vecsize > 2)
  8975. coord_expr = enclose_expression(coord_expr) + ".xy";
  8976. break;
  8977. case DimCube:
  8978. case Dim3D:
  8979. if (coord_type.vecsize > 3)
  8980. coord_expr = enclose_expression(coord_expr) + ".xyz";
  8981. break;
  8982. default:
  8983. SPIRV_CROSS_THROW("Bad image type given to OpImageQueryLod");
  8984. }
  8985. // TODO: It is unclear if calculcate_clamped_lod also conditionally rounds
  8986. // the reported LOD based on the sampler. NEAREST miplevel should
  8987. // round the LOD, but LINEAR miplevel should not round.
  8988. // Let's hope this does not become an issue ...
  8989. statement(to_expression(id), ".x = ", image_expr, ".calculate_clamped_lod(", sampler_expr, ", ",
  8990. coord_expr, ");");
  8991. statement(to_expression(id), ".y = ", image_expr, ".calculate_unclamped_lod(", sampler_expr, ", ",
  8992. coord_expr, ");");
  8993. register_control_dependent_expression(id);
  8994. break;
  8995. }
  8996. #define MSL_ImgQry(qrytype) \
  8997. do \
  8998. { \
  8999. uint32_t rslt_type_id = ops[0]; \
  9000. auto &rslt_type = get<SPIRType>(rslt_type_id); \
  9001. uint32_t id = ops[1]; \
  9002. uint32_t img_id = ops[2]; \
  9003. string img_exp = to_expression(img_id); \
  9004. string expr = type_to_glsl(rslt_type) + "(" + img_exp + ".get_num_" #qrytype "())"; \
  9005. emit_op(rslt_type_id, id, expr, should_forward(img_id)); \
  9006. } while (false)
  9007. case OpImageQueryLevels:
  9008. MSL_ImgQry(mip_levels);
  9009. break;
  9010. case OpImageQuerySamples:
  9011. MSL_ImgQry(samples);
  9012. break;
  9013. case OpImage:
  9014. {
  9015. uint32_t result_type = ops[0];
  9016. uint32_t id = ops[1];
  9017. auto *combined = maybe_get<SPIRCombinedImageSampler>(ops[2]);
  9018. if (combined)
  9019. {
  9020. auto &e = emit_op(result_type, id, to_expression(combined->image), true, true);
  9021. auto *var = maybe_get_backing_variable(combined->image);
  9022. if (var)
  9023. e.loaded_from = var->self;
  9024. }
  9025. else
  9026. {
  9027. auto *var = maybe_get_backing_variable(ops[2]);
  9028. SPIRExpression *e;
  9029. if (var && has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler))
  9030. e = &emit_op(result_type, id, join(to_expression(ops[2]), ".plane0"), true, true);
  9031. else
  9032. e = &emit_op(result_type, id, to_expression(ops[2]), true, true);
  9033. if (var)
  9034. e->loaded_from = var->self;
  9035. }
  9036. break;
  9037. }
  9038. // Casting
  9039. case OpQuantizeToF16:
  9040. {
  9041. uint32_t result_type = ops[0];
  9042. uint32_t id = ops[1];
  9043. uint32_t arg = ops[2];
  9044. string exp = join("spvQuantizeToF16(", to_expression(arg), ")");
  9045. emit_op(result_type, id, exp, should_forward(arg));
  9046. break;
  9047. }
  9048. case OpInBoundsAccessChain:
  9049. case OpAccessChain:
  9050. case OpPtrAccessChain:
  9051. if (is_tessellation_shader())
  9052. {
  9053. if (!emit_tessellation_access_chain(ops, instruction.length))
  9054. CompilerGLSL::emit_instruction(instruction);
  9055. }
  9056. else
  9057. CompilerGLSL::emit_instruction(instruction);
  9058. fix_up_interpolant_access_chain(ops, instruction.length);
  9059. break;
  9060. case OpStore:
  9061. {
  9062. const auto &type = expression_type(ops[0]);
  9063. if (is_out_of_bounds_tessellation_level(ops[0]))
  9064. break;
  9065. if (needs_frag_discard_checks() &&
  9066. (type.storage == StorageClassStorageBuffer || type.storage == StorageClassUniform))
  9067. {
  9068. // If we're in a continue block, this kludge will make the block too complex
  9069. // to emit normally.
  9070. assert(current_emitting_block);
  9071. auto cont_type = continue_block_type(*current_emitting_block);
  9072. if (cont_type != SPIRBlock::ContinueNone && cont_type != SPIRBlock::ComplexLoop)
  9073. {
  9074. current_emitting_block->complex_continue = true;
  9075. force_recompile();
  9076. }
  9077. statement("if (!", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), ")");
  9078. begin_scope();
  9079. }
  9080. if (!maybe_emit_array_assignment(ops[0], ops[1]))
  9081. CompilerGLSL::emit_instruction(instruction);
  9082. if (needs_frag_discard_checks() &&
  9083. (type.storage == StorageClassStorageBuffer || type.storage == StorageClassUniform))
  9084. end_scope();
  9085. if (has_decoration(ops[0], DecorationBuiltIn) && get_decoration(ops[0], DecorationBuiltIn) == BuiltInPointSize)
  9086. writes_to_point_size = true;
  9087. break;
  9088. }
  9089. // Compute barriers
  9090. case OpMemoryBarrier:
  9091. emit_barrier(0, ops[0], ops[1]);
  9092. break;
  9093. case OpControlBarrier:
  9094. // In GLSL a memory barrier is often followed by a control barrier.
  9095. // But in MSL, memory barriers are also control barriers (before MSL 3.2), so don't
  9096. // emit a simple control barrier if a memory barrier has just been emitted.
  9097. if (previous_instruction_opcode != OpMemoryBarrier || msl_options.supports_msl_version(3, 2))
  9098. emit_barrier(ops[0], ops[1], ops[2]);
  9099. break;
  9100. case OpOuterProduct:
  9101. {
  9102. uint32_t result_type = ops[0];
  9103. uint32_t id = ops[1];
  9104. uint32_t a = ops[2];
  9105. uint32_t b = ops[3];
  9106. auto &type = get<SPIRType>(result_type);
  9107. string expr = type_to_glsl_constructor(type);
  9108. expr += "(";
  9109. for (uint32_t col = 0; col < type.columns; col++)
  9110. {
  9111. expr += to_enclosed_unpacked_expression(a);
  9112. expr += " * ";
  9113. expr += to_extract_component_expression(b, col);
  9114. if (col + 1 < type.columns)
  9115. expr += ", ";
  9116. }
  9117. expr += ")";
  9118. emit_op(result_type, id, expr, should_forward(a) && should_forward(b));
  9119. inherit_expression_dependencies(id, a);
  9120. inherit_expression_dependencies(id, b);
  9121. break;
  9122. }
  9123. case OpVectorTimesMatrix:
  9124. case OpMatrixTimesVector:
  9125. {
  9126. if (!msl_options.invariant_float_math && !has_legacy_nocontract(ops[0], ops[1]))
  9127. {
  9128. CompilerGLSL::emit_instruction(instruction);
  9129. break;
  9130. }
  9131. // If the matrix needs transpose, just flip the multiply order.
  9132. auto *e = maybe_get<SPIRExpression>(ops[opcode == OpMatrixTimesVector ? 2 : 3]);
  9133. if (e && e->need_transpose)
  9134. {
  9135. e->need_transpose = false;
  9136. string expr;
  9137. if (opcode == OpMatrixTimesVector)
  9138. {
  9139. expr = join("spvFMulVectorMatrix(", to_enclosed_unpacked_expression(ops[3]), ", ",
  9140. to_unpacked_row_major_matrix_expression(ops[2]), ")");
  9141. }
  9142. else
  9143. {
  9144. expr = join("spvFMulMatrixVector(", to_unpacked_row_major_matrix_expression(ops[3]), ", ",
  9145. to_enclosed_unpacked_expression(ops[2]), ")");
  9146. }
  9147. bool forward = should_forward(ops[2]) && should_forward(ops[3]);
  9148. emit_op(ops[0], ops[1], expr, forward);
  9149. e->need_transpose = true;
  9150. inherit_expression_dependencies(ops[1], ops[2]);
  9151. inherit_expression_dependencies(ops[1], ops[3]);
  9152. }
  9153. else
  9154. {
  9155. if (opcode == OpMatrixTimesVector)
  9156. MSL_BFOP(spvFMulMatrixVector);
  9157. else
  9158. MSL_BFOP(spvFMulVectorMatrix);
  9159. }
  9160. break;
  9161. }
  9162. case OpMatrixTimesMatrix:
  9163. {
  9164. if (!msl_options.invariant_float_math && !has_legacy_nocontract(ops[0], ops[1]))
  9165. {
  9166. CompilerGLSL::emit_instruction(instruction);
  9167. break;
  9168. }
  9169. auto *a = maybe_get<SPIRExpression>(ops[2]);
  9170. auto *b = maybe_get<SPIRExpression>(ops[3]);
  9171. // If both matrices need transpose, we can multiply in flipped order and tag the expression as transposed.
  9172. // a^T * b^T = (b * a)^T.
  9173. if (a && b && a->need_transpose && b->need_transpose)
  9174. {
  9175. a->need_transpose = false;
  9176. b->need_transpose = false;
  9177. auto expr =
  9178. join("spvFMulMatrixMatrix(", enclose_expression(to_unpacked_row_major_matrix_expression(ops[3])), ", ",
  9179. enclose_expression(to_unpacked_row_major_matrix_expression(ops[2])), ")");
  9180. bool forward = should_forward(ops[2]) && should_forward(ops[3]);
  9181. emit_transposed_op(ops[0], ops[1], expr, forward);
  9182. a->need_transpose = true;
  9183. b->need_transpose = true;
  9184. inherit_expression_dependencies(ops[1], ops[2]);
  9185. inherit_expression_dependencies(ops[1], ops[3]);
  9186. }
  9187. else
  9188. MSL_BFOP(spvFMulMatrixMatrix);
  9189. break;
  9190. }
  9191. case OpIAddCarry:
  9192. case OpISubBorrow:
  9193. {
  9194. uint32_t result_type = ops[0];
  9195. uint32_t result_id = ops[1];
  9196. uint32_t op0 = ops[2];
  9197. uint32_t op1 = ops[3];
  9198. auto &type = get<SPIRType>(result_type);
  9199. emit_uninitialized_temporary_expression(result_type, result_id);
  9200. auto &res_type = get<SPIRType>(type.member_types[1]);
  9201. if (opcode == OpIAddCarry)
  9202. {
  9203. statement(to_expression(result_id), ".", to_member_name(type, 0), " = ",
  9204. to_enclosed_unpacked_expression(op0), " + ", to_enclosed_unpacked_expression(op1), ";");
  9205. statement(to_expression(result_id), ".", to_member_name(type, 1), " = select(", type_to_glsl(res_type),
  9206. "(1), ", type_to_glsl(res_type), "(0), ", to_unpacked_expression(result_id), ".", to_member_name(type, 0),
  9207. " >= max(", to_unpacked_expression(op0), ", ", to_unpacked_expression(op1), "));");
  9208. }
  9209. else
  9210. {
  9211. statement(to_expression(result_id), ".", to_member_name(type, 0), " = ", to_enclosed_unpacked_expression(op0), " - ",
  9212. to_enclosed_unpacked_expression(op1), ";");
  9213. statement(to_expression(result_id), ".", to_member_name(type, 1), " = select(", type_to_glsl(res_type),
  9214. "(1), ", type_to_glsl(res_type), "(0), ", to_enclosed_unpacked_expression(op0),
  9215. " >= ", to_enclosed_unpacked_expression(op1), ");");
  9216. }
  9217. break;
  9218. }
  9219. case OpUMulExtended:
  9220. case OpSMulExtended:
  9221. {
  9222. uint32_t result_type = ops[0];
  9223. uint32_t result_id = ops[1];
  9224. uint32_t op0 = ops[2];
  9225. uint32_t op1 = ops[3];
  9226. auto &type = get<SPIRType>(result_type);
  9227. auto &op_type = get<SPIRType>(type.member_types[0]);
  9228. auto input_type = opcode == OpSMulExtended ? int_type : uint_type;
  9229. string cast_op0, cast_op1;
  9230. binary_op_bitcast_helper(cast_op0, cast_op1, input_type, op0, op1, false);
  9231. auto expr = join("spvMulExtended<", type_to_glsl(type), ", ", type_to_glsl(op_type), ">(", cast_op0, ", ", cast_op1, ")");
  9232. emit_op(result_type, result_id, expr, true);
  9233. break;
  9234. }
  9235. case OpArrayLength:
  9236. {
  9237. auto &type = expression_type(ops[2]);
  9238. uint32_t offset = type_struct_member_offset(type, ops[3]);
  9239. uint32_t stride = type_struct_member_array_stride(type, ops[3]);
  9240. auto expr = join("(", to_buffer_size_expression(ops[2]), " - ", offset, ") / ", stride);
  9241. emit_op(ops[0], ops[1], expr, true);
  9242. break;
  9243. }
  9244. // Legacy sub-group stuff ...
  9245. case OpSubgroupBallotKHR:
  9246. case OpSubgroupFirstInvocationKHR:
  9247. case OpSubgroupReadInvocationKHR:
  9248. case OpSubgroupAllKHR:
  9249. case OpSubgroupAnyKHR:
  9250. case OpSubgroupAllEqualKHR:
  9251. emit_subgroup_op(instruction);
  9252. break;
  9253. // SPV_INTEL_shader_integer_functions2
  9254. case OpUCountLeadingZerosINTEL:
  9255. MSL_UFOP(clz);
  9256. break;
  9257. case OpUCountTrailingZerosINTEL:
  9258. MSL_UFOP(ctz);
  9259. break;
  9260. case OpAbsISubINTEL:
  9261. case OpAbsUSubINTEL:
  9262. MSL_BFOP(absdiff);
  9263. break;
  9264. case OpIAddSatINTEL:
  9265. case OpUAddSatINTEL:
  9266. MSL_BFOP(addsat);
  9267. break;
  9268. case OpIAverageINTEL:
  9269. case OpUAverageINTEL:
  9270. MSL_BFOP(hadd);
  9271. break;
  9272. case OpIAverageRoundedINTEL:
  9273. case OpUAverageRoundedINTEL:
  9274. MSL_BFOP(rhadd);
  9275. break;
  9276. case OpISubSatINTEL:
  9277. case OpUSubSatINTEL:
  9278. MSL_BFOP(subsat);
  9279. break;
  9280. case OpIMul32x16INTEL:
  9281. {
  9282. uint32_t result_type = ops[0];
  9283. uint32_t id = ops[1];
  9284. uint32_t a = ops[2], b = ops[3];
  9285. bool forward = should_forward(a) && should_forward(b);
  9286. emit_op(result_type, id, join("int(short(", to_unpacked_expression(a), ")) * int(short(", to_unpacked_expression(b), "))"), forward);
  9287. inherit_expression_dependencies(id, a);
  9288. inherit_expression_dependencies(id, b);
  9289. break;
  9290. }
  9291. case OpUMul32x16INTEL:
  9292. {
  9293. uint32_t result_type = ops[0];
  9294. uint32_t id = ops[1];
  9295. uint32_t a = ops[2], b = ops[3];
  9296. bool forward = should_forward(a) && should_forward(b);
  9297. emit_op(result_type, id, join("uint(ushort(", to_unpacked_expression(a), ")) * uint(ushort(", to_unpacked_expression(b), "))"), forward);
  9298. inherit_expression_dependencies(id, a);
  9299. inherit_expression_dependencies(id, b);
  9300. break;
  9301. }
  9302. // SPV_EXT_demote_to_helper_invocation
  9303. case OpDemoteToHelperInvocationEXT:
  9304. if (!msl_options.supports_msl_version(2, 3))
  9305. SPIRV_CROSS_THROW("discard_fragment() does not formally have demote semantics until MSL 2.3.");
  9306. CompilerGLSL::emit_instruction(instruction);
  9307. break;
  9308. case OpIsHelperInvocationEXT:
  9309. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
  9310. SPIRV_CROSS_THROW("simd_is_helper_thread() requires MSL 2.3 on iOS.");
  9311. else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1))
  9312. SPIRV_CROSS_THROW("simd_is_helper_thread() requires MSL 2.1 on macOS.");
  9313. emit_op(ops[0], ops[1],
  9314. needs_manual_helper_invocation_updates() ? builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput) :
  9315. "simd_is_helper_thread()",
  9316. false);
  9317. break;
  9318. case OpBeginInvocationInterlockEXT:
  9319. case OpEndInvocationInterlockEXT:
  9320. if (!msl_options.supports_msl_version(2, 0))
  9321. SPIRV_CROSS_THROW("Raster order groups require MSL 2.0.");
  9322. break; // Nothing to do in the body
  9323. case OpConvertUToAccelerationStructureKHR:
  9324. SPIRV_CROSS_THROW("ConvertUToAccelerationStructure is not supported in MSL.");
  9325. case OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR:
  9326. SPIRV_CROSS_THROW("BindingTableRecordOffset is not supported in MSL.");
  9327. case OpRayQueryInitializeKHR:
  9328. {
  9329. flush_variable_declaration(ops[0]);
  9330. register_write(ops[0]);
  9331. add_spv_func_and_recompile(SPVFuncImplRayQueryIntersectionParams);
  9332. statement(to_expression(ops[0]), ".reset(", "ray(", to_expression(ops[4]), ", ", to_expression(ops[6]), ", ",
  9333. to_expression(ops[5]), ", ", to_expression(ops[7]), "), ", to_expression(ops[1]), ", ", to_expression(ops[3]),
  9334. ", spvMakeIntersectionParams(", to_expression(ops[2]), "));");
  9335. break;
  9336. }
  9337. case OpRayQueryProceedKHR:
  9338. {
  9339. flush_variable_declaration(ops[0]);
  9340. register_write(ops[2]);
  9341. emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".next()"), false);
  9342. break;
  9343. }
  9344. #define MSL_RAY_QUERY_IS_CANDIDATE get<SPIRConstant>(ops[3]).scalar_i32() == 0
  9345. #define MSL_RAY_QUERY_GET_OP(op, msl_op) \
  9346. case OpRayQueryGet##op##KHR: \
  9347. flush_variable_declaration(ops[2]); \
  9348. emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_" #msl_op "()"), false); \
  9349. break
  9350. #define MSL_RAY_QUERY_OP_INNER2(op, msl_prefix, msl_op) \
  9351. case OpRayQueryGet##op##KHR: \
  9352. flush_variable_declaration(ops[2]); \
  9353. if (MSL_RAY_QUERY_IS_CANDIDATE) \
  9354. emit_op(ops[0], ops[1], join(to_expression(ops[2]), #msl_prefix "_candidate_" #msl_op "()"), false); \
  9355. else \
  9356. emit_op(ops[0], ops[1], join(to_expression(ops[2]), #msl_prefix "_committed_" #msl_op "()"), false); \
  9357. break
  9358. #define MSL_RAY_QUERY_GET_OP2(op, msl_op) MSL_RAY_QUERY_OP_INNER2(op, .get, msl_op)
  9359. #define MSL_RAY_QUERY_IS_OP2(op, msl_op) MSL_RAY_QUERY_OP_INNER2(op, .is, msl_op)
  9360. MSL_RAY_QUERY_GET_OP(RayTMin, ray_min_distance);
  9361. MSL_RAY_QUERY_GET_OP(WorldRayOrigin, world_space_ray_origin);
  9362. MSL_RAY_QUERY_GET_OP(WorldRayDirection, world_space_ray_direction);
  9363. MSL_RAY_QUERY_GET_OP2(IntersectionInstanceId, instance_id);
  9364. MSL_RAY_QUERY_GET_OP2(IntersectionInstanceCustomIndex, user_instance_id);
  9365. MSL_RAY_QUERY_GET_OP2(IntersectionBarycentrics, triangle_barycentric_coord);
  9366. MSL_RAY_QUERY_GET_OP2(IntersectionPrimitiveIndex, primitive_id);
  9367. MSL_RAY_QUERY_GET_OP2(IntersectionGeometryIndex, geometry_id);
  9368. MSL_RAY_QUERY_GET_OP2(IntersectionObjectRayOrigin, ray_origin);
  9369. MSL_RAY_QUERY_GET_OP2(IntersectionObjectRayDirection, ray_direction);
  9370. MSL_RAY_QUERY_GET_OP2(IntersectionObjectToWorld, object_to_world_transform);
  9371. MSL_RAY_QUERY_GET_OP2(IntersectionWorldToObject, world_to_object_transform);
  9372. MSL_RAY_QUERY_IS_OP2(IntersectionFrontFace, triangle_front_facing);
  9373. case OpRayQueryGetIntersectionTypeKHR:
  9374. flush_variable_declaration(ops[2]);
  9375. if (MSL_RAY_QUERY_IS_CANDIDATE)
  9376. emit_op(ops[0], ops[1], join("uint(", to_expression(ops[2]), ".get_candidate_intersection_type()) - 1"),
  9377. false);
  9378. else
  9379. emit_op(ops[0], ops[1], join("uint(", to_expression(ops[2]), ".get_committed_intersection_type())"), false);
  9380. break;
  9381. case OpRayQueryGetIntersectionTKHR:
  9382. flush_variable_declaration(ops[2]);
  9383. if (MSL_RAY_QUERY_IS_CANDIDATE)
  9384. emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_candidate_triangle_distance()"), false);
  9385. else
  9386. emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_committed_distance()"), false);
  9387. break;
  9388. case OpRayQueryGetIntersectionCandidateAABBOpaqueKHR:
  9389. {
  9390. flush_variable_declaration(ops[0]);
  9391. emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".is_candidate_non_opaque_bounding_box()"), false);
  9392. break;
  9393. }
  9394. case OpRayQueryConfirmIntersectionKHR:
  9395. flush_variable_declaration(ops[0]);
  9396. register_write(ops[0]);
  9397. statement(to_expression(ops[0]), ".commit_triangle_intersection();");
  9398. break;
  9399. case OpRayQueryGenerateIntersectionKHR:
  9400. flush_variable_declaration(ops[0]);
  9401. register_write(ops[0]);
  9402. statement(to_expression(ops[0]), ".commit_bounding_box_intersection(", to_expression(ops[1]), ");");
  9403. break;
  9404. case OpRayQueryTerminateKHR:
  9405. flush_variable_declaration(ops[0]);
  9406. register_write(ops[0]);
  9407. statement(to_expression(ops[0]), ".abort();");
  9408. break;
  9409. #undef MSL_RAY_QUERY_GET_OP
  9410. #undef MSL_RAY_QUERY_IS_CANDIDATE
  9411. #undef MSL_RAY_QUERY_IS_OP2
  9412. #undef MSL_RAY_QUERY_GET_OP2
  9413. #undef MSL_RAY_QUERY_OP_INNER2
  9414. case OpConvertPtrToU:
  9415. case OpConvertUToPtr:
  9416. case OpBitcast:
  9417. {
  9418. auto &type = get<SPIRType>(ops[0]);
  9419. auto &input_type = expression_type(ops[2]);
  9420. if (opcode != OpBitcast || is_pointer(type) || is_pointer(input_type))
  9421. {
  9422. string op;
  9423. if ((type.vecsize == 1 || is_pointer(type)) && (input_type.vecsize == 1 || is_pointer(input_type)))
  9424. op = join("reinterpret_cast<", type_to_glsl(type), ">(", to_unpacked_expression(ops[2]), ")");
  9425. else if (input_type.vecsize == 2)
  9426. op = join("reinterpret_cast<", type_to_glsl(type), ">(as_type<ulong>(", to_unpacked_expression(ops[2]), "))");
  9427. else
  9428. op = join("as_type<", type_to_glsl(type), ">(reinterpret_cast<ulong>(", to_unpacked_expression(ops[2]), "))");
  9429. emit_op(ops[0], ops[1], op, should_forward(ops[2]));
  9430. inherit_expression_dependencies(ops[1], ops[2]);
  9431. }
  9432. else
  9433. CompilerGLSL::emit_instruction(instruction);
  9434. break;
  9435. }
  9436. case OpSDot:
  9437. case OpUDot:
  9438. case OpSUDot:
  9439. {
  9440. uint32_t result_type = ops[0];
  9441. uint32_t id = ops[1];
  9442. uint32_t vec1 = ops[2];
  9443. uint32_t vec2 = ops[3];
  9444. auto &input_type1 = expression_type(vec1);
  9445. auto &input_type2 = expression_type(vec2);
  9446. string vec1input, vec2input;
  9447. auto input_size = input_type1.vecsize;
  9448. if (instruction.length == 5)
  9449. {
  9450. if (ops[4] == PackedVectorFormatPackedVectorFormat4x8Bit)
  9451. {
  9452. string type = opcode == OpSDot || opcode == OpSUDot ? "char4" : "uchar4";
  9453. vec1input = join("as_type<", type, ">(", to_expression(vec1), ")");
  9454. type = opcode == OpSDot ? "char4" : "uchar4";
  9455. vec2input = join("as_type<", type, ">(", to_expression(vec2), ")");
  9456. input_size = 4;
  9457. }
  9458. else
  9459. SPIRV_CROSS_THROW("Packed vector formats other than 4x8Bit for integer dot product is not supported.");
  9460. }
  9461. else
  9462. {
  9463. // Inputs are sign or zero-extended to their target width.
  9464. SPIRType::BaseType vec1_expected_type =
  9465. opcode != OpUDot ?
  9466. to_signed_basetype(input_type1.width) :
  9467. to_unsigned_basetype(input_type1.width);
  9468. SPIRType::BaseType vec2_expected_type =
  9469. opcode != OpSDot ?
  9470. to_unsigned_basetype(input_type2.width) :
  9471. to_signed_basetype(input_type2.width);
  9472. vec1input = bitcast_expression(vec1_expected_type, vec1);
  9473. vec2input = bitcast_expression(vec2_expected_type, vec2);
  9474. }
  9475. auto &type = get<SPIRType>(result_type);
  9476. // We'll get the appropriate sign-extend or zero-extend, no matter which type we cast to here.
  9477. // The addition in reduce_add is sign-invariant.
  9478. auto result_type_cast = join(type_to_glsl(type), input_size);
  9479. string exp = join("reduce_add(",
  9480. result_type_cast, "(", vec1input, ") * ",
  9481. result_type_cast, "(", vec2input, "))");
  9482. emit_op(result_type, id, exp, should_forward(vec1) && should_forward(vec2));
  9483. inherit_expression_dependencies(id, vec1);
  9484. inherit_expression_dependencies(id, vec2);
  9485. break;
  9486. }
  9487. case OpSDotAccSat:
  9488. case OpUDotAccSat:
  9489. case OpSUDotAccSat:
  9490. {
  9491. uint32_t result_type = ops[0];
  9492. uint32_t id = ops[1];
  9493. uint32_t vec1 = ops[2];
  9494. uint32_t vec2 = ops[3];
  9495. uint32_t acc = ops[4];
  9496. auto input_type1 = expression_type(vec1);
  9497. auto input_type2 = expression_type(vec2);
  9498. string vec1input, vec2input;
  9499. if (instruction.length == 6)
  9500. {
  9501. if (ops[5] == PackedVectorFormatPackedVectorFormat4x8Bit)
  9502. {
  9503. string type = opcode == OpSDotAccSat || opcode == OpSUDotAccSat ? "char4" : "uchar4";
  9504. vec1input = join("as_type<", type, ">(", to_expression(vec1), ")");
  9505. type = opcode == OpSDotAccSat ? "char4" : "uchar4";
  9506. vec2input = join("as_type<", type, ">(", to_expression(vec2), ")");
  9507. input_type1.vecsize = 4;
  9508. input_type2.vecsize = 4;
  9509. }
  9510. else
  9511. SPIRV_CROSS_THROW("Packed vector formats other than 4x8Bit for integer dot product is not supported.");
  9512. }
  9513. else
  9514. {
  9515. // Inputs are sign or zero-extended to their target width.
  9516. SPIRType::BaseType vec1_expected_type =
  9517. opcode != OpUDotAccSat ?
  9518. to_signed_basetype(input_type1.width) :
  9519. to_unsigned_basetype(input_type1.width);
  9520. SPIRType::BaseType vec2_expected_type =
  9521. opcode != OpSDotAccSat ?
  9522. to_unsigned_basetype(input_type2.width) :
  9523. to_signed_basetype(input_type2.width);
  9524. vec1input = bitcast_expression(vec1_expected_type, vec1);
  9525. vec2input = bitcast_expression(vec2_expected_type, vec2);
  9526. }
  9527. auto &type = get<SPIRType>(result_type);
  9528. SPIRType::BaseType pre_saturate_type =
  9529. opcode != OpUDotAccSat ?
  9530. to_signed_basetype(type.width) :
  9531. to_unsigned_basetype(type.width);
  9532. input_type1.basetype = pre_saturate_type;
  9533. input_type2.basetype = pre_saturate_type;
  9534. string exp = join(type_to_glsl(type), "(addsat(reduce_add(",
  9535. type_to_glsl(input_type1), "(", vec1input, ") * ",
  9536. type_to_glsl(input_type2), "(", vec2input, ")), ",
  9537. bitcast_expression(pre_saturate_type, acc), "))");
  9538. emit_op(result_type, id, exp, should_forward(vec1) && should_forward(vec2));
  9539. inherit_expression_dependencies(id, vec1);
  9540. inherit_expression_dependencies(id, vec2);
  9541. break;
  9542. }
  9543. case OpSetMeshOutputsEXT:
  9544. {
  9545. flush_variable_declaration(builtin_mesh_primitive_indices_id);
  9546. add_spv_func_and_recompile(SPVFuncImplSetMeshOutputsEXT);
  9547. statement("spvSetMeshOutputsEXT(gl_LocalInvocationIndex, spvMeshSizes, ", to_unpacked_expression(ops[0]), ", ", to_unpacked_expression(ops[1]), ");");
  9548. break;
  9549. }
  9550. case OpAssumeTrueKHR:
  9551. {
  9552. auto condition = ops[0];
  9553. statement(join("SPV_ASSUME(", to_unpacked_expression(condition), ")"));
  9554. break;
  9555. }
  9556. case OpExpectKHR:
  9557. {
  9558. auto result_type = ops[0];
  9559. auto ret = ops[1];
  9560. auto value = ops[2];
  9561. auto exp_value = ops[3];
  9562. auto exp = join("SPV_EXPECT(", to_unpacked_expression(value), ", ", to_unpacked_expression(exp_value), ")");
  9563. emit_op(result_type, ret, exp, should_forward(value), should_forward(exp_value));
  9564. inherit_expression_dependencies(ret, value);
  9565. inherit_expression_dependencies(ret, exp_value);
  9566. break;
  9567. }
  9568. default:
  9569. CompilerGLSL::emit_instruction(instruction);
  9570. break;
  9571. }
  9572. previous_instruction_opcode = opcode;
  9573. }
  9574. void CompilerMSL::emit_texture_op(const Instruction &i, bool sparse)
  9575. {
  9576. if (sparse)
  9577. SPIRV_CROSS_THROW("Sparse feedback not yet supported in MSL.");
  9578. if (msl_options.use_framebuffer_fetch_subpasses)
  9579. {
  9580. auto *ops = stream(i);
  9581. uint32_t result_type_id = ops[0];
  9582. uint32_t id = ops[1];
  9583. uint32_t img = ops[2];
  9584. auto &type = expression_type(img);
  9585. auto &imgtype = get<SPIRType>(type.self);
  9586. // Use Metal's native frame-buffer fetch API for subpass inputs.
  9587. if (imgtype.image.dim == DimSubpassData)
  9588. {
  9589. // Subpass inputs cannot be invalidated,
  9590. // so just forward the expression directly.
  9591. string expr = to_expression(img);
  9592. emit_op(result_type_id, id, expr, true);
  9593. return;
  9594. }
  9595. }
  9596. // Fallback to default implementation
  9597. CompilerGLSL::emit_texture_op(i, sparse);
  9598. }
  9599. void CompilerMSL::emit_barrier(uint32_t id_exe_scope, uint32_t id_mem_scope, uint32_t id_mem_sem)
  9600. {
  9601. auto model = get_execution_model();
  9602. if (model != ExecutionModelGLCompute && model != ExecutionModelTaskEXT &&
  9603. model != ExecutionModelMeshEXT && !is_tesc_shader())
  9604. {
  9605. return;
  9606. }
  9607. uint32_t exe_scope = id_exe_scope ? evaluate_constant_u32(id_exe_scope) : uint32_t(ScopeInvocation);
  9608. uint32_t mem_scope = id_mem_scope ? evaluate_constant_u32(id_mem_scope) : uint32_t(ScopeInvocation);
  9609. // Use the wider of the two scopes (smaller value)
  9610. exe_scope = min(exe_scope, mem_scope);
  9611. if (msl_options.emulate_subgroups && exe_scope >= ScopeSubgroup && !id_mem_sem)
  9612. // In this case, we assume a "subgroup" size of 1. The barrier, then, is a noop.
  9613. return;
  9614. string bar_stmt;
  9615. if (!id_exe_scope && msl_options.supports_msl_version(3, 2))
  9616. {
  9617. // Just took 10 years to get a proper barrier, but hey!
  9618. bar_stmt = "atomic_thread_fence";
  9619. }
  9620. else
  9621. {
  9622. if ((msl_options.is_ios() && msl_options.supports_msl_version(1, 2)) || msl_options.supports_msl_version(2))
  9623. bar_stmt = exe_scope < ScopeSubgroup ? "threadgroup_barrier" : "simdgroup_barrier";
  9624. else
  9625. bar_stmt = "threadgroup_barrier";
  9626. }
  9627. bar_stmt += "(";
  9628. uint32_t mem_sem = id_mem_sem ? evaluate_constant_u32(id_mem_sem) : uint32_t(MemorySemanticsMaskNone);
  9629. // Use the | operator to combine flags if we can.
  9630. if (msl_options.supports_msl_version(1, 2))
  9631. {
  9632. string mem_flags;
  9633. // For tesc shaders, this also affects objects in the Output storage class.
  9634. // Since in Metal, these are placed in a device buffer, we have to sync device memory here.
  9635. if (is_tesc_shader() ||
  9636. (mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask)))
  9637. mem_flags += "mem_flags::mem_device";
  9638. // Fix tessellation patch function processing
  9639. if (is_tesc_shader() || (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask)))
  9640. {
  9641. if (!mem_flags.empty())
  9642. mem_flags += " | ";
  9643. mem_flags += "mem_flags::mem_threadgroup";
  9644. }
  9645. if (mem_sem & MemorySemanticsImageMemoryMask)
  9646. {
  9647. if (!mem_flags.empty())
  9648. mem_flags += " | ";
  9649. mem_flags += "mem_flags::mem_texture";
  9650. }
  9651. if (mem_flags.empty())
  9652. mem_flags = "mem_flags::mem_none";
  9653. bar_stmt += mem_flags;
  9654. }
  9655. else
  9656. {
  9657. if ((mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask)) &&
  9658. (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask)))
  9659. bar_stmt += "mem_flags::mem_device_and_threadgroup";
  9660. else if (mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask))
  9661. bar_stmt += "mem_flags::mem_device";
  9662. else if (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask))
  9663. bar_stmt += "mem_flags::mem_threadgroup";
  9664. else if (mem_sem & MemorySemanticsImageMemoryMask)
  9665. bar_stmt += "mem_flags::mem_texture";
  9666. else
  9667. bar_stmt += "mem_flags::mem_none";
  9668. }
  9669. if (!id_exe_scope && msl_options.supports_msl_version(3, 2))
  9670. {
  9671. // If there's no device-related memory in the barrier, demote to workgroup scope.
  9672. // glslang seems to emit device scope even for memoryBarrierShared().
  9673. if (mem_scope == ScopeDevice &&
  9674. (mem_sem & (MemorySemanticsUniformMemoryMask |
  9675. MemorySemanticsImageMemoryMask |
  9676. MemorySemanticsCrossWorkgroupMemoryMask)) == 0)
  9677. {
  9678. mem_scope = ScopeWorkgroup;
  9679. }
  9680. // MSL 3.2 only supports seq_cst or relaxed.
  9681. if (mem_sem & (MemorySemanticsAcquireReleaseMask |
  9682. MemorySemanticsAcquireMask |
  9683. MemorySemanticsReleaseMask |
  9684. MemorySemanticsSequentiallyConsistentMask))
  9685. {
  9686. bar_stmt += ", memory_order_seq_cst";
  9687. }
  9688. else
  9689. {
  9690. bar_stmt += ", memory_order_relaxed";
  9691. }
  9692. switch (mem_scope)
  9693. {
  9694. case ScopeDevice:
  9695. bar_stmt += ", thread_scope_device";
  9696. break;
  9697. case ScopeWorkgroup:
  9698. bar_stmt += ", thread_scope_threadgroup";
  9699. break;
  9700. case ScopeSubgroup:
  9701. bar_stmt += ", thread_scope_subgroup";
  9702. break;
  9703. case ScopeInvocation:
  9704. bar_stmt += ", thread_scope_thread";
  9705. break;
  9706. default:
  9707. // The default argument is device, which is conservative.
  9708. break;
  9709. }
  9710. }
  9711. bar_stmt += ");";
  9712. statement(bar_stmt);
  9713. assert(current_emitting_block);
  9714. flush_control_dependent_expressions(current_emitting_block->self);
  9715. flush_all_active_variables();
  9716. }
  9717. static bool storage_class_array_is_thread(StorageClass storage)
  9718. {
  9719. switch (storage)
  9720. {
  9721. case StorageClassInput:
  9722. case StorageClassOutput:
  9723. case StorageClassGeneric:
  9724. case StorageClassFunction:
  9725. case StorageClassPrivate:
  9726. return true;
  9727. default:
  9728. return false;
  9729. }
  9730. }
  9731. bool CompilerMSL::emit_array_copy(const char *expr, uint32_t lhs_id, uint32_t rhs_id,
  9732. StorageClass lhs_storage, StorageClass rhs_storage)
  9733. {
  9734. // Allow Metal to use the array<T> template to make arrays a value type.
  9735. // This, however, cannot be used for threadgroup address specifiers, so consider the custom array copy as fallback.
  9736. bool lhs_is_thread_storage = storage_class_array_is_thread(lhs_storage);
  9737. bool rhs_is_thread_storage = storage_class_array_is_thread(rhs_storage);
  9738. bool lhs_is_array_template = lhs_is_thread_storage || lhs_storage == StorageClassWorkgroup;
  9739. bool rhs_is_array_template = rhs_is_thread_storage || rhs_storage == StorageClassWorkgroup;
  9740. // Special considerations for stage IO variables.
  9741. // If the variable is actually backed by non-user visible device storage, we use array templates for those.
  9742. //
  9743. // Another special consideration is given to thread local variables which happen to have Offset decorations
  9744. // applied to them. Block-like types do not use array templates, so we need to force POD path if we detect
  9745. // these scenarios. This check isn't perfect since it would be technically possible to mix and match these things,
  9746. // and for a fully correct solution we might have to track array template state through access chains as well,
  9747. // but for all reasonable use cases, this should suffice.
  9748. // This special case should also only apply to Function/Private storage classes.
  9749. // We should not check backing variable for temporaries.
  9750. auto *lhs_var = maybe_get_backing_variable(lhs_id);
  9751. if (lhs_var && lhs_storage == StorageClassStorageBuffer && storage_class_array_is_thread(lhs_var->storage))
  9752. lhs_is_array_template = true;
  9753. else if (lhs_var && lhs_storage != StorageClassGeneric && type_is_explicit_layout(get<SPIRType>(lhs_var->basetype)))
  9754. lhs_is_array_template = false;
  9755. auto *rhs_var = maybe_get_backing_variable(rhs_id);
  9756. if (rhs_var && rhs_storage == StorageClassStorageBuffer && storage_class_array_is_thread(rhs_var->storage))
  9757. rhs_is_array_template = true;
  9758. else if (rhs_var && rhs_storage != StorageClassGeneric && type_is_explicit_layout(get<SPIRType>(rhs_var->basetype)))
  9759. rhs_is_array_template = false;
  9760. // If threadgroup storage qualifiers are *not* used:
  9761. // Avoid spvCopy* wrapper functions; Otherwise, spvUnsafeArray<> template cannot be used with that storage qualifier.
  9762. if (lhs_is_array_template && rhs_is_array_template && !using_builtin_array())
  9763. {
  9764. // Fall back to normal copy path.
  9765. return false;
  9766. }
  9767. else
  9768. {
  9769. // Ensure the LHS variable has been declared
  9770. if (lhs_var)
  9771. flush_variable_declaration(lhs_var->self);
  9772. string lhs;
  9773. if (expr)
  9774. lhs = expr;
  9775. else
  9776. lhs = to_expression(lhs_id);
  9777. // Assignment from an array initializer is fine.
  9778. auto &type = expression_type(rhs_id);
  9779. auto *var = maybe_get_backing_variable(rhs_id);
  9780. // Unfortunately, we cannot template on address space in MSL,
  9781. // so explicit address space redirection it is ...
  9782. bool is_constant = false;
  9783. if (ir.ids[rhs_id].get_type() == TypeConstant)
  9784. {
  9785. is_constant = true;
  9786. }
  9787. else if (var && var->remapped_variable && var->statically_assigned &&
  9788. ir.ids[var->static_expression].get_type() == TypeConstant)
  9789. {
  9790. is_constant = true;
  9791. }
  9792. else if (rhs_storage == StorageClassUniform || rhs_storage == StorageClassUniformConstant)
  9793. {
  9794. is_constant = true;
  9795. }
  9796. // For the case where we have OpLoad triggering an array copy,
  9797. // we cannot easily detect this case ahead of time since it's
  9798. // context dependent. We might have to force a recompile here
  9799. // if this is the only use of array copies in our shader.
  9800. add_spv_func_and_recompile(type.array.size() > 1 ? SPVFuncImplArrayCopyMultidim : SPVFuncImplArrayCopy);
  9801. const char *tag = nullptr;
  9802. if (lhs_is_thread_storage && is_constant)
  9803. tag = "FromConstantToStack";
  9804. else if (lhs_storage == StorageClassWorkgroup && is_constant)
  9805. tag = "FromConstantToThreadGroup";
  9806. else if (lhs_is_thread_storage && rhs_is_thread_storage)
  9807. tag = "FromStackToStack";
  9808. else if (lhs_storage == StorageClassWorkgroup && rhs_is_thread_storage)
  9809. tag = "FromStackToThreadGroup";
  9810. else if (lhs_is_thread_storage && rhs_storage == StorageClassWorkgroup)
  9811. tag = "FromThreadGroupToStack";
  9812. else if (lhs_storage == StorageClassWorkgroup && rhs_storage == StorageClassWorkgroup)
  9813. tag = "FromThreadGroupToThreadGroup";
  9814. else if (lhs_storage == StorageClassStorageBuffer && rhs_storage == StorageClassStorageBuffer)
  9815. tag = "FromDeviceToDevice";
  9816. else if (lhs_storage == StorageClassStorageBuffer && is_constant)
  9817. tag = "FromConstantToDevice";
  9818. else if (lhs_storage == StorageClassStorageBuffer && rhs_storage == StorageClassWorkgroup)
  9819. tag = "FromThreadGroupToDevice";
  9820. else if (lhs_storage == StorageClassStorageBuffer && rhs_is_thread_storage)
  9821. tag = "FromStackToDevice";
  9822. else if (lhs_storage == StorageClassWorkgroup && rhs_storage == StorageClassStorageBuffer)
  9823. tag = "FromDeviceToThreadGroup";
  9824. else if (lhs_is_thread_storage && rhs_storage == StorageClassStorageBuffer)
  9825. tag = "FromDeviceToStack";
  9826. else
  9827. SPIRV_CROSS_THROW("Unknown storage class used for copying arrays.");
  9828. // Should be very rare, but mark if we need extra magic template overloads.
  9829. if (has_extended_decoration(lhs_id, SPIRVCrossDecorationPhysicalTypeID))
  9830. add_spv_func_and_recompile(SPVFuncImplArrayCopyExtendedDst);
  9831. if (has_extended_decoration(rhs_id, SPIRVCrossDecorationPhysicalTypeID))
  9832. add_spv_func_and_recompile(SPVFuncImplArrayCopyExtendedSrc);
  9833. // Pass internal array of spvUnsafeArray<> into wrapper functions
  9834. if (lhs_is_array_template && rhs_is_array_template && !msl_options.force_native_arrays)
  9835. statement("spvArrayCopy", tag, "(", lhs, ".elements, ", to_expression(rhs_id), ".elements);");
  9836. if (lhs_is_array_template && !msl_options.force_native_arrays)
  9837. statement("spvArrayCopy", tag, "(", lhs, ".elements, ", to_expression(rhs_id), ");");
  9838. else if (rhs_is_array_template && !msl_options.force_native_arrays)
  9839. statement("spvArrayCopy", tag, "(", lhs, ", ", to_expression(rhs_id), ".elements);");
  9840. else
  9841. statement("spvArrayCopy", tag, "(", lhs, ", ", to_expression(rhs_id), ");");
  9842. }
  9843. return true;
  9844. }
  9845. uint32_t CompilerMSL::get_physical_tess_level_array_size(BuiltIn builtin) const
  9846. {
  9847. if (is_tessellating_triangles())
  9848. return builtin == BuiltInTessLevelInner ? 1 : 3;
  9849. else
  9850. return builtin == BuiltInTessLevelInner ? 2 : 4;
  9851. }
  9852. // Since MSL does not allow arrays to be copied via simple variable assignment,
  9853. // if the LHS and RHS represent an assignment of an entire array, it must be
  9854. // implemented by calling an array copy function.
  9855. // Returns whether the struct assignment was emitted.
  9856. bool CompilerMSL::maybe_emit_array_assignment(uint32_t id_lhs, uint32_t id_rhs)
  9857. {
  9858. // We only care about assignments of an entire array
  9859. auto &type = expression_type(id_lhs);
  9860. if (!is_array(get_pointee_type(type)))
  9861. return false;
  9862. auto *var = maybe_get<SPIRVariable>(id_lhs);
  9863. // Is this a remapped, static constant? Don't do anything.
  9864. if (var && var->remapped_variable && var->statically_assigned)
  9865. return true;
  9866. if (ir.ids[id_rhs].get_type() == TypeConstant && var && var->deferred_declaration)
  9867. {
  9868. // Special case, if we end up declaring a variable when assigning the constant array,
  9869. // we can avoid the copy by directly assigning the constant expression.
  9870. // This is likely necessary to be able to use a variable as a true look-up table, as it is unlikely
  9871. // the compiler will be able to optimize the spvArrayCopy() into a constant LUT.
  9872. // After a variable has been declared, we can no longer assign constant arrays in MSL unfortunately.
  9873. statement(to_expression(id_lhs), " = ", constant_expression(get<SPIRConstant>(id_rhs)), ";");
  9874. return true;
  9875. }
  9876. if (is_tesc_shader() && has_decoration(id_lhs, DecorationBuiltIn))
  9877. {
  9878. auto builtin = BuiltIn(get_decoration(id_lhs, DecorationBuiltIn));
  9879. // Need to manually unroll the array store.
  9880. if (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter)
  9881. {
  9882. uint32_t array_size = get_physical_tess_level_array_size(builtin);
  9883. if (array_size == 1)
  9884. statement(to_expression(id_lhs), " = half(", to_expression(id_rhs), "[0]);");
  9885. else
  9886. {
  9887. for (uint32_t i = 0; i < array_size; i++)
  9888. statement(to_expression(id_lhs), "[", i, "] = half(", to_expression(id_rhs), "[", i, "]);");
  9889. }
  9890. return true;
  9891. }
  9892. }
  9893. auto lhs_storage = get_expression_effective_storage_class(id_lhs);
  9894. auto rhs_storage = get_expression_effective_storage_class(id_rhs);
  9895. if (!emit_array_copy(nullptr, id_lhs, id_rhs, lhs_storage, rhs_storage))
  9896. return false;
  9897. register_write(id_lhs);
  9898. return true;
  9899. }
  9900. // Emits one of the atomic functions. In MSL, the atomic functions operate on pointers
  9901. void CompilerMSL::emit_atomic_func_op(uint32_t result_type, uint32_t result_id, const char *op, Op opcode,
  9902. uint32_t mem_order_1, uint32_t mem_order_2, bool has_mem_order_2, uint32_t obj, uint32_t op1,
  9903. bool op1_is_pointer, bool op1_is_literal, uint32_t op2)
  9904. {
  9905. string exp;
  9906. auto &ptr_type = expression_type(obj);
  9907. auto &type = get_pointee_type(ptr_type);
  9908. auto expected_type = type.basetype;
  9909. if (opcode == OpAtomicUMax || opcode == OpAtomicUMin)
  9910. expected_type = to_unsigned_basetype(type.width);
  9911. else if (opcode == OpAtomicSMax || opcode == OpAtomicSMin)
  9912. expected_type = to_signed_basetype(type.width);
  9913. bool use_native_image_atomic;
  9914. if (msl_options.supports_msl_version(3, 1))
  9915. use_native_image_atomic = check_atomic_image(obj);
  9916. else
  9917. use_native_image_atomic = false;
  9918. if (type.width == 64)
  9919. SPIRV_CROSS_THROW("MSL currently does not support 64-bit atomics.");
  9920. auto remapped_type = type;
  9921. remapped_type.basetype = expected_type;
  9922. auto *var = maybe_get_backing_variable(obj);
  9923. const auto *res_type = var ? &get<SPIRType>(var->basetype) : nullptr;
  9924. assert(type.storage != StorageClassImage || res_type);
  9925. bool is_atomic_compare_exchange_strong = op1_is_pointer && op1;
  9926. bool check_discard = opcode != OpAtomicLoad && needs_frag_discard_checks() &&
  9927. ptr_type.storage != StorageClassWorkgroup;
  9928. // Even compare exchange atomics are vec4 on metal for ... reasons :v
  9929. uint32_t vec4_temporary_id = 0;
  9930. if (use_native_image_atomic && is_atomic_compare_exchange_strong)
  9931. {
  9932. uint32_t &tmp_id = extra_sub_expressions[result_id];
  9933. if (!tmp_id)
  9934. {
  9935. tmp_id = ir.increase_bound_by(2);
  9936. auto vec4_type = get<SPIRType>(result_type);
  9937. vec4_type.vecsize = 4;
  9938. set<SPIRType>(tmp_id + 1, vec4_type);
  9939. }
  9940. vec4_temporary_id = tmp_id;
  9941. }
  9942. if (check_discard)
  9943. {
  9944. if (is_atomic_compare_exchange_strong)
  9945. {
  9946. // We're already emitting a CAS loop here; a conditional won't hurt.
  9947. emit_uninitialized_temporary_expression(result_type, result_id);
  9948. if (vec4_temporary_id)
  9949. emit_uninitialized_temporary_expression(vec4_temporary_id + 1, vec4_temporary_id);
  9950. statement("if (!", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), ")");
  9951. begin_scope();
  9952. }
  9953. else
  9954. exp = join("(!", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), " ? ");
  9955. }
  9956. if (use_native_image_atomic)
  9957. {
  9958. auto obj_expression = to_expression(obj);
  9959. auto split_index = obj_expression.find_first_of('@');
  9960. bool needs_reinterpret = opcode == OpAtomicUMax || opcode == OpAtomicUMin || opcode == OpAtomicSMax || opcode == OpAtomicSMin;
  9961. needs_reinterpret &= type.basetype != expected_type;
  9962. SPIRVariable *backing_var = nullptr;
  9963. // Try to avoid waiting until not force recompile later mode to enable force recompile later
  9964. if (needs_reinterpret && (backing_var = maybe_get_backing_variable(obj)))
  9965. add_spv_func_and_recompile(SPVFuncImplTextureCast);
  9966. // Will only be false if we're in "force recompile later" mode.
  9967. if (split_index != string::npos)
  9968. {
  9969. auto coord = obj_expression.substr(split_index + 1);
  9970. auto image_expr = obj_expression.substr(0, split_index);
  9971. // Handle problem cases with sign where we need signed min/max on a uint image for example.
  9972. // It seems to work to cast the texture type itself, even if it is probably wildly outside of spec,
  9973. // but SPIR-V requires this to work.
  9974. if (needs_reinterpret && backing_var)
  9975. {
  9976. assert(spv_function_implementations.count(SPVFuncImplTextureCast) && "Should have been added above");
  9977. const auto *backing_type = &get<SPIRType>(backing_var->basetype);
  9978. while (backing_type->op != OpTypeImage)
  9979. backing_type = &get<SPIRType>(backing_type->parent_type);
  9980. auto img_type = *backing_type;
  9981. auto tmp_type = type;
  9982. tmp_type.basetype = expected_type;
  9983. img_type.image.type = ir.increase_bound_by(1);
  9984. set<SPIRType>(img_type.image.type, tmp_type);
  9985. image_expr = join("spvTextureCast<", type_to_glsl(img_type, obj), ">(", image_expr, ")");
  9986. }
  9987. exp += join(image_expr, ".", op, "(");
  9988. if (ptr_type.storage == StorageClassImage && (res_type->image.arrayed || res_type->image.dim == DimCube))
  9989. {
  9990. switch (res_type->image.dim)
  9991. {
  9992. case Dim1D:
  9993. if (msl_options.texture_1D_as_2D)
  9994. exp += join("uint2(", coord, ".x, 0), ", coord, ".y");
  9995. else
  9996. exp += join(coord, ".x, ", coord, ".y");
  9997. break;
  9998. case Dim2D:
  9999. exp += join(coord, ".xy, ", coord, ".z");
  10000. break;
  10001. case DimCube:
  10002. if (!msl_options.supports_msl_version(4, 0))
  10003. SPIRV_CROSS_THROW("Cannot do atomics on Cube textures before 4.0.");
  10004. if (res_type->image.arrayed)
  10005. exp += join(coord, ".xy, ", coord, ".z % 6u, ", coord, ".z / 6u");
  10006. else
  10007. exp += join(coord, ".xy, ", coord, ".z");
  10008. break;
  10009. default:
  10010. SPIRV_CROSS_THROW("Cannot do atomics on unknown dimension.");
  10011. }
  10012. }
  10013. else if (ptr_type.storage == StorageClassImage && res_type->image.dim == Dim1D && msl_options.texture_1D_as_2D)
  10014. exp += join("uint2(", coord, ", 0)");
  10015. else
  10016. exp += coord;
  10017. }
  10018. else
  10019. {
  10020. exp += obj_expression;
  10021. }
  10022. }
  10023. else
  10024. {
  10025. exp += string(op) + "_explicit(";
  10026. exp += "(";
  10027. // Emulate texture2D atomic operations
  10028. if (ptr_type.storage == StorageClassImage)
  10029. {
  10030. auto &flags = ir.get_decoration_bitset(var->self);
  10031. if (decoration_flags_signal_volatile(flags))
  10032. exp += "volatile ";
  10033. exp += "device";
  10034. }
  10035. else if (var && ptr_type.storage != StorageClassPhysicalStorageBuffer)
  10036. {
  10037. exp += get_variable_address_space(*var);
  10038. }
  10039. else
  10040. {
  10041. // Fallback scenario, could happen for raw pointers.
  10042. exp += ptr_type.storage == StorageClassWorkgroup ? "threadgroup" : "device";
  10043. }
  10044. exp += " atomic_";
  10045. // For signed and unsigned min/max, we can signal this through the pointer type.
  10046. // There is no other way, since C++ does not have explicit signage for atomics.
  10047. exp += type_to_glsl(remapped_type);
  10048. exp += "*)";
  10049. exp += "&";
  10050. exp += to_enclosed_expression(obj);
  10051. }
  10052. if (is_atomic_compare_exchange_strong)
  10053. {
  10054. assert(strcmp(op, "atomic_compare_exchange_weak") == 0);
  10055. assert(op2);
  10056. assert(has_mem_order_2);
  10057. exp += ", &";
  10058. exp += to_name(vec4_temporary_id ? vec4_temporary_id : result_id);
  10059. exp += ", ";
  10060. exp += to_expression(op2);
  10061. if (!use_native_image_atomic)
  10062. {
  10063. exp += ", ";
  10064. exp += get_memory_order(mem_order_1);
  10065. exp += ", ";
  10066. exp += get_memory_order(mem_order_2);
  10067. }
  10068. exp += ")";
  10069. // MSL only supports the weak atomic compare exchange, so emit a CAS loop here.
  10070. // The MSL function returns false if the atomic write fails OR the comparison test fails,
  10071. // so we must validate that it wasn't the comparison test that failed before continuing
  10072. // the CAS loop, otherwise it will loop infinitely, with the comparison test always failing.
  10073. // The function updates the comparator value from the memory value, so the additional
  10074. // comparison test evaluates the memory value against the expected value.
  10075. if (!check_discard)
  10076. {
  10077. emit_uninitialized_temporary_expression(result_type, result_id);
  10078. if (vec4_temporary_id)
  10079. emit_uninitialized_temporary_expression(vec4_temporary_id + 1, vec4_temporary_id);
  10080. }
  10081. statement("do");
  10082. begin_scope();
  10083. string scalar_expression;
  10084. if (vec4_temporary_id)
  10085. scalar_expression = join(to_expression(vec4_temporary_id), ".x");
  10086. else
  10087. scalar_expression = to_expression(result_id);
  10088. statement(scalar_expression, " = ", to_expression(op1), ";");
  10089. end_scope_decl(join("while (!", exp, " && ", scalar_expression, " == ", to_enclosed_expression(op1), ")"));
  10090. if (vec4_temporary_id)
  10091. statement(to_expression(result_id), " = ", scalar_expression, ";");
  10092. // Vulkan: (section 9.29: ... and values returned by atomic instructions in helper invocations are undefined)
  10093. if (check_discard)
  10094. {
  10095. end_scope();
  10096. statement("else");
  10097. begin_scope();
  10098. statement(to_expression(result_id), " = {};");
  10099. end_scope();
  10100. }
  10101. }
  10102. else
  10103. {
  10104. assert(strcmp(op, "atomic_compare_exchange_weak") != 0);
  10105. if (op1)
  10106. {
  10107. exp += ", ";
  10108. if (op1_is_literal)
  10109. exp += to_string(op1);
  10110. else
  10111. exp += bitcast_expression(expected_type, op1);
  10112. }
  10113. if (op2)
  10114. exp += ", " + to_expression(op2);
  10115. if (!use_native_image_atomic)
  10116. {
  10117. exp += string(", ") + get_memory_order(mem_order_1);
  10118. if (has_mem_order_2)
  10119. exp += string(", ") + get_memory_order(mem_order_2);
  10120. }
  10121. exp += ")";
  10122. // For some particular reason, atomics return vec4 in Metal ...
  10123. if (use_native_image_atomic)
  10124. exp += ".x";
  10125. // Vulkan: (section 9.29: ... and values returned by atomic instructions in helper invocations are undefined)
  10126. if (check_discard)
  10127. {
  10128. exp += " : ";
  10129. if (strcmp(op, "atomic_store") != 0)
  10130. exp += join(type_to_glsl(get<SPIRType>(result_type)), "{}");
  10131. else
  10132. exp += "((void)0)";
  10133. exp += ")";
  10134. }
  10135. if (expected_type != type.basetype)
  10136. exp = bitcast_expression(type, expected_type, exp);
  10137. if (strcmp(op, "atomic_store") != 0)
  10138. emit_op(result_type, result_id, exp, false);
  10139. else
  10140. statement(exp, ";");
  10141. }
  10142. flush_all_atomic_capable_variables();
  10143. }
  10144. // Metal only supports relaxed memory order for now
  10145. const char *CompilerMSL::get_memory_order(uint32_t)
  10146. {
  10147. return "memory_order_relaxed";
  10148. }
  10149. // Override for MSL-specific extension syntax instructions.
  10150. // In some cases, deliberately select either the fast or precise versions of the MSL functions to match Vulkan math precision results.
  10151. void CompilerMSL::emit_glsl_op(uint32_t result_type, uint32_t id, uint32_t eop, const uint32_t *args, uint32_t count)
  10152. {
  10153. auto op = static_cast<GLSLstd450>(eop);
  10154. // If we need to do implicit bitcasts, make sure we do it with the correct type.
  10155. uint32_t integer_width = get_integer_width_for_glsl_instruction(op, args, count);
  10156. auto int_type = to_signed_basetype(integer_width);
  10157. auto uint_type = to_unsigned_basetype(integer_width);
  10158. op = get_remapped_glsl_op(op);
  10159. auto &restype = get<SPIRType>(result_type);
  10160. // Only precise:: preserves NaN in trancendentals (supposedly, cannot find documentation for this).
  10161. const auto drop_nan_inf = FPFastMathModeNotInfMask | FPFastMathModeNotNaNMask;
  10162. bool preserve_nan = (get_fp_fast_math_flags_for_op(result_type, id) & drop_nan_inf) != drop_nan_inf;
  10163. const char *preserve_str = preserve_nan ? "precise" : "fast";
  10164. // TODO: Emit the default behavior to match existing code. Might need to be revisited.
  10165. // Only fp32 has the precise:: override.
  10166. #define EMIT_PRECISE_OVERRIDE(glsl_op, op) \
  10167. case GLSLstd450##glsl_op: \
  10168. if (restype.basetype == SPIRType::Float && preserve_nan) \
  10169. emit_unary_func_op(result_type, id, args[0], "precise::" op); \
  10170. else \
  10171. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count); \
  10172. break
  10173. switch (op)
  10174. {
  10175. EMIT_PRECISE_OVERRIDE(Cos, "cos");
  10176. EMIT_PRECISE_OVERRIDE(Sin, "sin");
  10177. EMIT_PRECISE_OVERRIDE(Tan, "tan");
  10178. EMIT_PRECISE_OVERRIDE(Acos, "acos");
  10179. EMIT_PRECISE_OVERRIDE(Asin, "asin");
  10180. EMIT_PRECISE_OVERRIDE(Atan, "atan");
  10181. EMIT_PRECISE_OVERRIDE(Exp, "exp");
  10182. EMIT_PRECISE_OVERRIDE(Exp2, "exp2");
  10183. EMIT_PRECISE_OVERRIDE(Log, "log");
  10184. EMIT_PRECISE_OVERRIDE(Log2, "log2");
  10185. EMIT_PRECISE_OVERRIDE(Sqrt, "sqrt");
  10186. #undef EMIT_PRECISE_OVERRIDE
  10187. case GLSLstd450Sinh:
  10188. if (restype.basetype == SPIRType::Half)
  10189. {
  10190. auto ftype = restype;
  10191. ftype.basetype = SPIRType::Float;
  10192. // MSL does not have overload for half. Force-cast back to half.
  10193. auto expr = join(type_to_glsl(restype), "(", preserve_str, "::sinh(", type_to_glsl(ftype), "(", to_unpacked_expression(args[0]), ")))");
  10194. emit_op(result_type, id, expr, should_forward(args[0]));
  10195. inherit_expression_dependencies(id, args[0]);
  10196. }
  10197. else if (preserve_nan)
  10198. emit_unary_func_op(result_type, id, args[0], "precise::sinh");
  10199. else
  10200. emit_unary_func_op(result_type, id, args[0], "fast::sinh");
  10201. break;
  10202. case GLSLstd450Cosh:
  10203. if (restype.basetype == SPIRType::Half)
  10204. {
  10205. auto ftype = restype;
  10206. ftype.basetype = SPIRType::Float;
  10207. // MSL does not have overload for half. Force-cast back to half.
  10208. auto expr = join(type_to_glsl(restype), "(", preserve_str, "::cosh(", type_to_glsl(ftype), "(", to_unpacked_expression(args[0]), ")))");
  10209. emit_op(result_type, id, expr, should_forward(args[0]));
  10210. inherit_expression_dependencies(id, args[0]);
  10211. }
  10212. else if (preserve_nan)
  10213. emit_unary_func_op(result_type, id, args[0], "precise::cosh");
  10214. else
  10215. emit_unary_func_op(result_type, id, args[0], "fast::cosh");
  10216. break;
  10217. case GLSLstd450Tanh:
  10218. if (restype.basetype == SPIRType::Half)
  10219. {
  10220. auto ftype = restype;
  10221. ftype.basetype = SPIRType::Float;
  10222. // MSL does not have overload for half. Force-cast back to half.
  10223. auto expr = join(type_to_glsl(restype), "(", preserve_str, "::tanh(", type_to_glsl(ftype), "(", to_unpacked_expression(args[0]), ")))");
  10224. emit_op(result_type, id, expr, should_forward(args[0]));
  10225. inherit_expression_dependencies(id, args[0]);
  10226. }
  10227. else
  10228. emit_unary_func_op(result_type, id, args[0], "precise::tanh");
  10229. break;
  10230. case GLSLstd450Atan2:
  10231. if (restype.basetype == SPIRType::Half)
  10232. {
  10233. // MSL does not have overload for half. Force-cast back to half.
  10234. auto ftype = restype;
  10235. ftype.basetype = SPIRType::Float;
  10236. auto expr = join(type_to_glsl(restype),
  10237. "(", preserve_str, "::atan2(",
  10238. type_to_glsl(ftype), "(", to_unpacked_expression(args[0]), "), ",
  10239. type_to_glsl(ftype), "(", to_unpacked_expression(args[1]), ")))");
  10240. emit_op(result_type, id, expr, should_forward(args[0]) && should_forward(args[1]));
  10241. inherit_expression_dependencies(id, args[0]);
  10242. inherit_expression_dependencies(id, args[1]);
  10243. }
  10244. else
  10245. emit_binary_func_op(result_type, id, args[0], args[1], "precise::atan2");
  10246. break;
  10247. case GLSLstd450InverseSqrt:
  10248. if (restype.basetype == SPIRType::Float && preserve_nan)
  10249. emit_unary_func_op(result_type, id, args[0], "precise::rsqrt");
  10250. else
  10251. emit_unary_func_op(result_type, id, args[0], "rsqrt");
  10252. break;
  10253. case GLSLstd450RoundEven:
  10254. emit_unary_func_op(result_type, id, args[0], "rint");
  10255. break;
  10256. case GLSLstd450FindILsb:
  10257. {
  10258. // In this template version of findLSB, we return T.
  10259. auto basetype = expression_type(args[0]).basetype;
  10260. emit_unary_func_op_cast(result_type, id, args[0], "spvFindLSB", basetype, basetype);
  10261. break;
  10262. }
  10263. case GLSLstd450FindSMsb:
  10264. emit_unary_func_op_cast(result_type, id, args[0], "spvFindSMSB", int_type, int_type);
  10265. break;
  10266. case GLSLstd450FindUMsb:
  10267. emit_unary_func_op_cast(result_type, id, args[0], "spvFindUMSB", uint_type, uint_type);
  10268. break;
  10269. case GLSLstd450PackSnorm4x8:
  10270. emit_unary_func_op(result_type, id, args[0], "pack_float_to_snorm4x8");
  10271. break;
  10272. case GLSLstd450PackUnorm4x8:
  10273. emit_unary_func_op(result_type, id, args[0], "pack_float_to_unorm4x8");
  10274. break;
  10275. case GLSLstd450PackSnorm2x16:
  10276. emit_unary_func_op(result_type, id, args[0], "pack_float_to_snorm2x16");
  10277. break;
  10278. case GLSLstd450PackUnorm2x16:
  10279. emit_unary_func_op(result_type, id, args[0], "pack_float_to_unorm2x16");
  10280. break;
  10281. case GLSLstd450PackHalf2x16:
  10282. {
  10283. auto expr = join("as_type<uint>(half2(", to_expression(args[0]), "))");
  10284. emit_op(result_type, id, expr, should_forward(args[0]));
  10285. inherit_expression_dependencies(id, args[0]);
  10286. break;
  10287. }
  10288. case GLSLstd450UnpackSnorm4x8:
  10289. emit_unary_func_op(result_type, id, args[0], "unpack_snorm4x8_to_float");
  10290. break;
  10291. case GLSLstd450UnpackUnorm4x8:
  10292. emit_unary_func_op(result_type, id, args[0], "unpack_unorm4x8_to_float");
  10293. break;
  10294. case GLSLstd450UnpackSnorm2x16:
  10295. emit_unary_func_op(result_type, id, args[0], "unpack_snorm2x16_to_float");
  10296. break;
  10297. case GLSLstd450UnpackUnorm2x16:
  10298. emit_unary_func_op(result_type, id, args[0], "unpack_unorm2x16_to_float");
  10299. break;
  10300. case GLSLstd450UnpackHalf2x16:
  10301. {
  10302. auto expr = join("float2(as_type<half2>(", to_expression(args[0]), "))");
  10303. emit_op(result_type, id, expr, should_forward(args[0]));
  10304. inherit_expression_dependencies(id, args[0]);
  10305. break;
  10306. }
  10307. case GLSLstd450PackDouble2x32:
  10308. emit_unary_func_op(result_type, id, args[0], "unsupported_GLSLstd450PackDouble2x32"); // Currently unsupported
  10309. break;
  10310. case GLSLstd450UnpackDouble2x32:
  10311. emit_unary_func_op(result_type, id, args[0], "unsupported_GLSLstd450UnpackDouble2x32"); // Currently unsupported
  10312. break;
  10313. case GLSLstd450MatrixInverse:
  10314. {
  10315. auto &mat_type = get<SPIRType>(result_type);
  10316. switch (mat_type.columns)
  10317. {
  10318. case 2:
  10319. emit_unary_func_op(result_type, id, args[0], "spvInverse2x2");
  10320. break;
  10321. case 3:
  10322. emit_unary_func_op(result_type, id, args[0], "spvInverse3x3");
  10323. break;
  10324. case 4:
  10325. emit_unary_func_op(result_type, id, args[0], "spvInverse4x4");
  10326. break;
  10327. default:
  10328. break;
  10329. }
  10330. break;
  10331. }
  10332. case GLSLstd450FMin:
  10333. // If the result type isn't float, don't bother calling the specific
  10334. // precise::/fast:: version. Metal doesn't have those for half and
  10335. // double types.
  10336. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10337. emit_binary_func_op(result_type, id, args[0], args[1], "min");
  10338. else
  10339. emit_binary_func_op(result_type, id, args[0], args[1], "fast::min");
  10340. break;
  10341. case GLSLstd450FMax:
  10342. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10343. emit_binary_func_op(result_type, id, args[0], args[1], "max");
  10344. else
  10345. emit_binary_func_op(result_type, id, args[0], args[1], "fast::max");
  10346. break;
  10347. case GLSLstd450FClamp:
  10348. // TODO: If args[1] is 0 and args[2] is 1, emit a saturate() call.
  10349. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10350. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "clamp");
  10351. else
  10352. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "fast::clamp");
  10353. break;
  10354. case GLSLstd450NMin:
  10355. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10356. emit_binary_func_op(result_type, id, args[0], args[1], "min");
  10357. else
  10358. emit_binary_func_op(result_type, id, args[0], args[1], "precise::min");
  10359. break;
  10360. case GLSLstd450NMax:
  10361. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10362. emit_binary_func_op(result_type, id, args[0], args[1], "max");
  10363. else
  10364. emit_binary_func_op(result_type, id, args[0], args[1], "precise::max");
  10365. break;
  10366. case GLSLstd450NClamp:
  10367. // TODO: If args[1] is 0 and args[2] is 1, emit a saturate() call.
  10368. if (get<SPIRType>(result_type).basetype != SPIRType::Float)
  10369. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "clamp");
  10370. else
  10371. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "precise::clamp");
  10372. break;
  10373. case GLSLstd450InterpolateAtCentroid:
  10374. {
  10375. // We can't just emit the expression normally, because the qualified name contains a call to the default
  10376. // interpolate method, or refers to a local variable. We saved the interface index we need; use it to construct
  10377. // the base for the method call.
  10378. uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex);
  10379. string component;
  10380. if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr))
  10381. {
  10382. uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr);
  10383. auto *c = maybe_get<SPIRConstant>(index_expr);
  10384. if (!c || c->specialization)
  10385. component = join("[", to_expression(index_expr), "]");
  10386. else
  10387. component = join(".", index_to_swizzle(c->scalar()));
  10388. }
  10389. emit_op(result_type, id,
  10390. join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index),
  10391. ".interpolate_at_centroid()", component),
  10392. should_forward(args[0]));
  10393. break;
  10394. }
  10395. case GLSLstd450InterpolateAtSample:
  10396. {
  10397. uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex);
  10398. string component;
  10399. if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr))
  10400. {
  10401. uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr);
  10402. auto *c = maybe_get<SPIRConstant>(index_expr);
  10403. if (!c || c->specialization)
  10404. component = join("[", to_expression(index_expr), "]");
  10405. else
  10406. component = join(".", index_to_swizzle(c->scalar()));
  10407. }
  10408. emit_op(result_type, id,
  10409. join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index),
  10410. ".interpolate_at_sample(", to_expression(args[1]), ")", component),
  10411. should_forward(args[0]) && should_forward(args[1]));
  10412. break;
  10413. }
  10414. case GLSLstd450InterpolateAtOffset:
  10415. {
  10416. uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex);
  10417. string component;
  10418. if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr))
  10419. {
  10420. uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr);
  10421. auto *c = maybe_get<SPIRConstant>(index_expr);
  10422. if (!c || c->specialization)
  10423. component = join("[", to_expression(index_expr), "]");
  10424. else
  10425. component = join(".", index_to_swizzle(c->scalar()));
  10426. }
  10427. // Like Direct3D, Metal puts the (0, 0) at the upper-left corner, not the center as SPIR-V and GLSL do.
  10428. // Offset the offset by (1/2 - 1/16), or 0.4375, to compensate for this.
  10429. // It has to be (1/2 - 1/16) and not 1/2, or several CTS tests subtly break on Intel.
  10430. emit_op(result_type, id,
  10431. join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index),
  10432. ".interpolate_at_offset(", to_expression(args[1]), " + 0.4375)", component),
  10433. should_forward(args[0]) && should_forward(args[1]));
  10434. break;
  10435. }
  10436. case GLSLstd450Distance:
  10437. // MSL does not support scalar versions here.
  10438. if (expression_type(args[0]).vecsize == 1)
  10439. {
  10440. // Equivalent to length(a - b) -> abs(a - b).
  10441. emit_op(result_type, id,
  10442. join("abs(", to_enclosed_unpacked_expression(args[0]), " - ",
  10443. to_enclosed_unpacked_expression(args[1]), ")"),
  10444. should_forward(args[0]) && should_forward(args[1]));
  10445. inherit_expression_dependencies(id, args[0]);
  10446. inherit_expression_dependencies(id, args[1]);
  10447. }
  10448. else
  10449. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10450. break;
  10451. case GLSLstd450Length:
  10452. // MSL does not support scalar versions, so use abs().
  10453. if (expression_type(args[0]).vecsize == 1)
  10454. emit_unary_func_op(result_type, id, args[0], "abs");
  10455. else
  10456. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10457. break;
  10458. case GLSLstd450Normalize:
  10459. {
  10460. auto &exp_type = expression_type(args[0]);
  10461. // MSL does not support scalar versions here.
  10462. // MSL has no implementation for normalize in the fast:: namespace for half
  10463. // Returns -1 or 1 for valid input, sign() does the job.
  10464. // precise::normalize asm looks ridiculous.
  10465. // Don't think this actually matters unless proven otherwise.
  10466. if (exp_type.vecsize == 1)
  10467. emit_unary_func_op(result_type, id, args[0], "sign");
  10468. else if (exp_type.basetype == SPIRType::Half)
  10469. emit_unary_func_op(result_type, id, args[0], "normalize");
  10470. else
  10471. emit_unary_func_op(result_type, id, args[0], "fast::normalize");
  10472. break;
  10473. }
  10474. case GLSLstd450Reflect:
  10475. if (get<SPIRType>(result_type).vecsize == 1)
  10476. emit_binary_func_op(result_type, id, args[0], args[1], "spvReflect");
  10477. else
  10478. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10479. break;
  10480. case GLSLstd450Refract:
  10481. if (get<SPIRType>(result_type).vecsize == 1)
  10482. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "spvRefract");
  10483. else
  10484. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10485. break;
  10486. case GLSLstd450FaceForward:
  10487. if (get<SPIRType>(result_type).vecsize == 1)
  10488. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "spvFaceForward");
  10489. else
  10490. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10491. break;
  10492. case GLSLstd450Modf:
  10493. case GLSLstd450Frexp:
  10494. {
  10495. // Special case. If the variable is a scalar access chain, we cannot use it directly. We have to emit a temporary.
  10496. // Another special case is if the variable is in a storage class which is not thread.
  10497. auto *ptr = maybe_get<SPIRExpression>(args[1]);
  10498. auto &type = expression_type(args[1]);
  10499. bool is_thread_storage = storage_class_array_is_thread(type.storage);
  10500. if (type.storage == StorageClassOutput && capture_output_to_buffer)
  10501. is_thread_storage = false;
  10502. if (!is_thread_storage ||
  10503. (ptr && ptr->access_chain && is_scalar(expression_type(args[1]))))
  10504. {
  10505. register_call_out_argument(args[1]);
  10506. forced_temporaries.insert(id);
  10507. // Need to create temporaries and copy over to access chain after.
  10508. // We cannot directly take the reference of a vector swizzle in MSL, even if it's scalar ...
  10509. uint32_t &tmp_id = extra_sub_expressions[id];
  10510. if (!tmp_id)
  10511. tmp_id = ir.increase_bound_by(1);
  10512. uint32_t tmp_type_id = get_pointee_type_id(expression_type_id(args[1]));
  10513. emit_uninitialized_temporary_expression(tmp_type_id, tmp_id);
  10514. emit_binary_func_op(result_type, id, args[0], tmp_id, eop == GLSLstd450Modf ? "modf" : "frexp");
  10515. statement(to_expression(args[1]), " = ", to_expression(tmp_id), ";");
  10516. }
  10517. else
  10518. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10519. break;
  10520. }
  10521. case GLSLstd450Pow:
  10522. // powr makes x < 0.0 undefined, just like SPIR-V.
  10523. if (restype.basetype == SPIRType::Float && preserve_nan)
  10524. emit_binary_func_op(result_type, id, args[0], args[1], "precise::powr");
  10525. else
  10526. emit_binary_func_op(result_type, id, args[0], args[1], "powr");
  10527. break;
  10528. default:
  10529. CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
  10530. break;
  10531. }
  10532. }
  10533. void CompilerMSL::emit_spv_amd_shader_trinary_minmax_op(uint32_t result_type, uint32_t id, uint32_t eop,
  10534. const uint32_t *args, uint32_t count)
  10535. {
  10536. enum AMDShaderTrinaryMinMax
  10537. {
  10538. FMin3AMD = 1,
  10539. UMin3AMD = 2,
  10540. SMin3AMD = 3,
  10541. FMax3AMD = 4,
  10542. UMax3AMD = 5,
  10543. SMax3AMD = 6,
  10544. FMid3AMD = 7,
  10545. UMid3AMD = 8,
  10546. SMid3AMD = 9
  10547. };
  10548. if (!msl_options.supports_msl_version(2, 1))
  10549. SPIRV_CROSS_THROW("Trinary min/max functions require MSL 2.1.");
  10550. auto op = static_cast<AMDShaderTrinaryMinMax>(eop);
  10551. switch (op)
  10552. {
  10553. case FMid3AMD:
  10554. case UMid3AMD:
  10555. case SMid3AMD:
  10556. emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "median3");
  10557. break;
  10558. default:
  10559. CompilerGLSL::emit_spv_amd_shader_trinary_minmax_op(result_type, id, eop, args, count);
  10560. break;
  10561. }
  10562. }
  10563. // Emit a structure declaration for the specified interface variable.
  10564. void CompilerMSL::emit_interface_block(uint32_t ib_var_id)
  10565. {
  10566. if (ib_var_id)
  10567. {
  10568. auto &ib_var = get<SPIRVariable>(ib_var_id);
  10569. auto &ib_type = get_variable_data_type(ib_var);
  10570. //assert(ib_type.basetype == SPIRType::Struct && !ib_type.member_types.empty());
  10571. assert(ib_type.basetype == SPIRType::Struct);
  10572. emit_struct(ib_type);
  10573. }
  10574. }
  10575. // Emits the declaration signature of the specified function.
  10576. // If this is the entry point function, Metal-specific return value and function arguments are added.
  10577. void CompilerMSL::emit_function_prototype(SPIRFunction &func, const Bitset &)
  10578. {
  10579. if (func.self != ir.default_entry_point)
  10580. add_function_overload(func);
  10581. local_variable_names = resource_names;
  10582. string decl;
  10583. processing_entry_point = func.self == ir.default_entry_point;
  10584. // Metal helper functions must be static force-inline otherwise they will cause problems when linked together in a single Metallib.
  10585. if (!processing_entry_point)
  10586. statement(force_inline);
  10587. auto &type = get<SPIRType>(func.return_type);
  10588. if (!type.array.empty() && msl_options.force_native_arrays)
  10589. {
  10590. // We cannot return native arrays in MSL, so "return" through an out variable.
  10591. decl += "void";
  10592. }
  10593. else
  10594. {
  10595. decl += func_type_decl(type);
  10596. }
  10597. decl += " ";
  10598. decl += to_name(func.self);
  10599. decl += "(";
  10600. if (!type.array.empty() && msl_options.force_native_arrays)
  10601. {
  10602. // Fake arrays returns by writing to an out array instead.
  10603. decl += "thread ";
  10604. decl += type_to_glsl(type);
  10605. decl += " (&spvReturnValue)";
  10606. decl += type_to_array_glsl(type, 0);
  10607. if (!func.arguments.empty())
  10608. decl += ", ";
  10609. }
  10610. if (processing_entry_point)
  10611. {
  10612. if (msl_options.argument_buffers)
  10613. decl += entry_point_args_argument_buffer(!func.arguments.empty());
  10614. else
  10615. decl += entry_point_args_classic(!func.arguments.empty());
  10616. // append entry point args to avoid conflicts in local variable names.
  10617. local_variable_names.insert(resource_names.begin(), resource_names.end());
  10618. // If entry point function has variables that require early declaration,
  10619. // ensure they each have an empty initializer, creating one if needed.
  10620. // This is done at this late stage because the initialization expression
  10621. // is cleared after each compilation pass.
  10622. for (auto var_id : vars_needing_early_declaration)
  10623. {
  10624. auto &ed_var = get<SPIRVariable>(var_id);
  10625. ID &initializer = ed_var.initializer;
  10626. if (!initializer)
  10627. initializer = ir.increase_bound_by(1);
  10628. // Do not override proper initializers.
  10629. if (ir.ids[initializer].get_type() == TypeNone || ir.ids[initializer].get_type() == TypeExpression)
  10630. set<SPIRExpression>(ed_var.initializer, "{}", ed_var.basetype, true);
  10631. }
  10632. // add `taskPayloadSharedEXT` variable to entry-point arguments
  10633. for (auto &v : func.local_variables)
  10634. {
  10635. auto &var = get<SPIRVariable>(v);
  10636. if (var.storage != StorageClassTaskPayloadWorkgroupEXT)
  10637. continue;
  10638. add_local_variable_name(v);
  10639. SPIRFunction::Parameter arg = {};
  10640. arg.id = v;
  10641. arg.type = var.basetype;
  10642. arg.alias_global_variable = true;
  10643. decl += join(", ", argument_decl(arg), " [[payload]]");
  10644. }
  10645. }
  10646. for (auto &arg : func.arguments)
  10647. {
  10648. uint32_t name_id = arg.id;
  10649. auto *var = maybe_get<SPIRVariable>(arg.id);
  10650. if (var)
  10651. {
  10652. // If we need to modify the name of the variable, make sure we modify the original variable.
  10653. // Our alias is just a shadow variable.
  10654. if (arg.alias_global_variable && var->basevariable)
  10655. name_id = var->basevariable;
  10656. var->parameter = &arg; // Hold a pointer to the parameter so we can invalidate the readonly field if needed.
  10657. }
  10658. add_local_variable_name(name_id);
  10659. decl += argument_decl(arg);
  10660. bool is_dynamic_img_sampler = has_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler);
  10661. auto &arg_type = get<SPIRType>(arg.type);
  10662. if (arg_type.basetype == SPIRType::SampledImage && !is_dynamic_img_sampler)
  10663. {
  10664. // Manufacture automatic plane args for multiplanar texture
  10665. uint32_t planes = 1;
  10666. if (auto *constexpr_sampler = find_constexpr_sampler(name_id))
  10667. if (constexpr_sampler->ycbcr_conversion_enable)
  10668. planes = constexpr_sampler->planes;
  10669. for (uint32_t i = 1; i < planes; i++)
  10670. decl += join(", ", argument_decl(arg), plane_name_suffix, i);
  10671. // Manufacture automatic sampler arg for SampledImage texture
  10672. if (arg_type.image.dim != DimBuffer)
  10673. {
  10674. if (arg_type.array.empty() || (var ? is_var_runtime_size_array(*var) : is_runtime_size_array(arg_type)))
  10675. {
  10676. decl += join(", ", sampler_type(arg_type, arg.id, false), " ", to_sampler_expression(name_id));
  10677. }
  10678. else
  10679. {
  10680. const char *sampler_address_space =
  10681. descriptor_address_space(name_id,
  10682. StorageClassUniformConstant,
  10683. "thread const");
  10684. decl += join(", ", sampler_address_space, " ", sampler_type(arg_type, name_id, false), "& ",
  10685. to_sampler_expression(name_id));
  10686. }
  10687. }
  10688. }
  10689. // Manufacture automatic swizzle arg.
  10690. if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(arg_type) &&
  10691. !is_dynamic_img_sampler)
  10692. {
  10693. bool arg_is_array = !arg_type.array.empty();
  10694. decl += join(", constant uint", arg_is_array ? "* " : "& ", to_swizzle_expression(name_id));
  10695. }
  10696. if (buffer_requires_array_length(name_id))
  10697. {
  10698. bool arg_is_array = !arg_type.array.empty();
  10699. decl += join(", constant uint", arg_is_array ? "* " : "& ", to_buffer_size_expression(name_id));
  10700. }
  10701. if (&arg != &func.arguments.back())
  10702. decl += ", ";
  10703. }
  10704. decl += ")";
  10705. statement(decl);
  10706. }
  10707. static bool needs_chroma_reconstruction(const MSLConstexprSampler *constexpr_sampler)
  10708. {
  10709. // For now, only multiplanar images need explicit reconstruction. GBGR and BGRG images
  10710. // use implicit reconstruction.
  10711. return constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && constexpr_sampler->planes > 1;
  10712. }
  10713. // Returns the texture sampling function string for the specified image and sampling characteristics.
  10714. string CompilerMSL::to_function_name(const TextureFunctionNameArguments &args)
  10715. {
  10716. VariableID img = args.base.img;
  10717. const MSLConstexprSampler *constexpr_sampler = nullptr;
  10718. bool is_dynamic_img_sampler = false;
  10719. if (auto *var = maybe_get_backing_variable(img))
  10720. {
  10721. constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self));
  10722. is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler);
  10723. }
  10724. // Special-case gather. We have to alter the component being looked up in the swizzle case.
  10725. if (msl_options.swizzle_texture_samples && args.base.is_gather && !is_dynamic_img_sampler &&
  10726. (!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable))
  10727. {
  10728. bool is_compare = comparison_ids.count(img);
  10729. add_spv_func_and_recompile(is_compare ? SPVFuncImplGatherCompareSwizzle : SPVFuncImplGatherSwizzle);
  10730. return is_compare ? "spvGatherCompareSwizzle" : "spvGatherSwizzle";
  10731. }
  10732. // Special-case gather with an array of offsets. We have to lower into 4 separate gathers.
  10733. if (args.has_array_offsets && !is_dynamic_img_sampler &&
  10734. (!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable))
  10735. {
  10736. bool is_compare = comparison_ids.count(img);
  10737. add_spv_func_and_recompile(is_compare ? SPVFuncImplGatherCompareConstOffsets : SPVFuncImplGatherConstOffsets);
  10738. return is_compare ? "spvGatherCompareConstOffsets" : "spvGatherConstOffsets";
  10739. }
  10740. auto *combined = maybe_get<SPIRCombinedImageSampler>(img);
  10741. // Texture reference
  10742. string fname;
  10743. if (needs_chroma_reconstruction(constexpr_sampler) && !is_dynamic_img_sampler)
  10744. {
  10745. if (constexpr_sampler->planes != 2 && constexpr_sampler->planes != 3)
  10746. SPIRV_CROSS_THROW("Unhandled number of color image planes!");
  10747. // 444 images aren't downsampled, so we don't need to do linear filtering.
  10748. if (constexpr_sampler->resolution == MSL_FORMAT_RESOLUTION_444 ||
  10749. constexpr_sampler->chroma_filter == MSL_SAMPLER_FILTER_NEAREST)
  10750. {
  10751. if (constexpr_sampler->planes == 2)
  10752. add_spv_func_and_recompile(SPVFuncImplChromaReconstructNearest2Plane);
  10753. else
  10754. add_spv_func_and_recompile(SPVFuncImplChromaReconstructNearest3Plane);
  10755. fname = "spvChromaReconstructNearest";
  10756. }
  10757. else // Linear with a downsampled format
  10758. {
  10759. fname = "spvChromaReconstructLinear";
  10760. switch (constexpr_sampler->resolution)
  10761. {
  10762. case MSL_FORMAT_RESOLUTION_444:
  10763. assert(false);
  10764. break; // not reached
  10765. case MSL_FORMAT_RESOLUTION_422:
  10766. switch (constexpr_sampler->x_chroma_offset)
  10767. {
  10768. case MSL_CHROMA_LOCATION_COSITED_EVEN:
  10769. if (constexpr_sampler->planes == 2)
  10770. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422CositedEven2Plane);
  10771. else
  10772. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422CositedEven3Plane);
  10773. fname += "422CositedEven";
  10774. break;
  10775. case MSL_CHROMA_LOCATION_MIDPOINT:
  10776. if (constexpr_sampler->planes == 2)
  10777. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422Midpoint2Plane);
  10778. else
  10779. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422Midpoint3Plane);
  10780. fname += "422Midpoint";
  10781. break;
  10782. default:
  10783. SPIRV_CROSS_THROW("Invalid chroma location.");
  10784. }
  10785. break;
  10786. case MSL_FORMAT_RESOLUTION_420:
  10787. fname += "420";
  10788. switch (constexpr_sampler->x_chroma_offset)
  10789. {
  10790. case MSL_CHROMA_LOCATION_COSITED_EVEN:
  10791. switch (constexpr_sampler->y_chroma_offset)
  10792. {
  10793. case MSL_CHROMA_LOCATION_COSITED_EVEN:
  10794. if (constexpr_sampler->planes == 2)
  10795. add_spv_func_and_recompile(
  10796. SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven2Plane);
  10797. else
  10798. add_spv_func_and_recompile(
  10799. SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven3Plane);
  10800. fname += "XCositedEvenYCositedEven";
  10801. break;
  10802. case MSL_CHROMA_LOCATION_MIDPOINT:
  10803. if (constexpr_sampler->planes == 2)
  10804. add_spv_func_and_recompile(
  10805. SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint2Plane);
  10806. else
  10807. add_spv_func_and_recompile(
  10808. SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint3Plane);
  10809. fname += "XCositedEvenYMidpoint";
  10810. break;
  10811. default:
  10812. SPIRV_CROSS_THROW("Invalid Y chroma location.");
  10813. }
  10814. break;
  10815. case MSL_CHROMA_LOCATION_MIDPOINT:
  10816. switch (constexpr_sampler->y_chroma_offset)
  10817. {
  10818. case MSL_CHROMA_LOCATION_COSITED_EVEN:
  10819. if (constexpr_sampler->planes == 2)
  10820. add_spv_func_and_recompile(
  10821. SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven2Plane);
  10822. else
  10823. add_spv_func_and_recompile(
  10824. SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven3Plane);
  10825. fname += "XMidpointYCositedEven";
  10826. break;
  10827. case MSL_CHROMA_LOCATION_MIDPOINT:
  10828. if (constexpr_sampler->planes == 2)
  10829. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint2Plane);
  10830. else
  10831. add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane);
  10832. fname += "XMidpointYMidpoint";
  10833. break;
  10834. default:
  10835. SPIRV_CROSS_THROW("Invalid Y chroma location.");
  10836. }
  10837. break;
  10838. default:
  10839. SPIRV_CROSS_THROW("Invalid X chroma location.");
  10840. }
  10841. break;
  10842. default:
  10843. SPIRV_CROSS_THROW("Invalid format resolution.");
  10844. }
  10845. }
  10846. }
  10847. else
  10848. {
  10849. fname = to_expression(combined ? combined->image : img) + ".";
  10850. // Texture function and sampler
  10851. if (args.base.is_fetch)
  10852. fname += "read";
  10853. else if (args.base.is_gather)
  10854. fname += "gather";
  10855. else
  10856. fname += "sample";
  10857. if (args.has_dref)
  10858. fname += "_compare";
  10859. }
  10860. return fname;
  10861. }
  10862. string CompilerMSL::convert_to_f32(const string &expr, uint32_t components)
  10863. {
  10864. SPIRType t { components > 1 ? OpTypeVector : OpTypeFloat };
  10865. t.basetype = SPIRType::Float;
  10866. t.vecsize = components;
  10867. t.columns = 1;
  10868. return join(type_to_glsl_constructor(t), "(", expr, ")");
  10869. }
  10870. static inline bool sampling_type_needs_f32_conversion(const SPIRType &type)
  10871. {
  10872. // Double is not supported to begin with, but doesn't hurt to check for completion.
  10873. return type.basetype == SPIRType::Half || type.basetype == SPIRType::Double;
  10874. }
  10875. // Returns the function args for a texture sampling function for the specified image and sampling characteristics.
  10876. string CompilerMSL::to_function_args(const TextureFunctionArguments &args, bool *p_forward)
  10877. {
  10878. VariableID img = args.base.img;
  10879. auto &imgtype = *args.base.imgtype;
  10880. uint32_t lod = args.lod;
  10881. uint32_t grad_x = args.grad_x;
  10882. uint32_t grad_y = args.grad_y;
  10883. uint32_t bias = args.bias;
  10884. const MSLConstexprSampler *constexpr_sampler = nullptr;
  10885. bool is_dynamic_img_sampler = false;
  10886. if (auto *var = maybe_get_backing_variable(img))
  10887. {
  10888. constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self));
  10889. is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler);
  10890. }
  10891. string farg_str;
  10892. bool forward = true;
  10893. if (!is_dynamic_img_sampler)
  10894. {
  10895. // Texture reference (for some cases)
  10896. if (needs_chroma_reconstruction(constexpr_sampler))
  10897. {
  10898. // Multiplanar images need two or three textures.
  10899. farg_str += to_expression(img);
  10900. for (uint32_t i = 1; i < constexpr_sampler->planes; i++)
  10901. farg_str += join(", ", to_expression(img), plane_name_suffix, i);
  10902. }
  10903. else if ((!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable) &&
  10904. msl_options.swizzle_texture_samples && args.base.is_gather)
  10905. {
  10906. auto *combined = maybe_get<SPIRCombinedImageSampler>(img);
  10907. farg_str += to_expression(combined ? combined->image : img);
  10908. }
  10909. // Gathers with constant offsets call a special function, so include the texture.
  10910. if (args.has_array_offsets)
  10911. farg_str += to_expression(img);
  10912. // Sampler reference
  10913. if (!args.base.is_fetch)
  10914. {
  10915. if (!farg_str.empty())
  10916. farg_str += ", ";
  10917. farg_str += to_sampler_expression(img);
  10918. }
  10919. if ((!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable) &&
  10920. msl_options.swizzle_texture_samples && args.base.is_gather)
  10921. {
  10922. // Add the swizzle constant from the swizzle buffer.
  10923. farg_str += ", " + to_swizzle_expression(img);
  10924. used_swizzle_buffer = true;
  10925. }
  10926. // Const offsets gather puts the const offsets before the other args.
  10927. if (args.has_array_offsets)
  10928. {
  10929. forward = forward && should_forward(args.offset);
  10930. farg_str += ", " + to_unpacked_expression(args.offset);
  10931. }
  10932. // Const offsets gather or swizzled gather puts the component before the other args.
  10933. if (args.component && (args.has_array_offsets || msl_options.swizzle_texture_samples))
  10934. {
  10935. forward = forward && should_forward(args.component);
  10936. farg_str += ", " + to_component_argument(args.component);
  10937. }
  10938. }
  10939. // Texture coordinates
  10940. forward = forward && should_forward(args.coord);
  10941. auto coord_expr = to_enclosed_unpacked_expression(args.coord);
  10942. auto &coord_type = expression_type(args.coord);
  10943. bool coord_is_fp = type_is_floating_point(coord_type);
  10944. bool is_cube_fetch = false;
  10945. string tex_coords = coord_expr;
  10946. uint32_t alt_coord_component = 0;
  10947. switch (imgtype.image.dim)
  10948. {
  10949. case Dim1D:
  10950. if (coord_type.vecsize > 1)
  10951. tex_coords = enclose_expression(tex_coords) + ".x";
  10952. if (args.base.is_fetch)
  10953. tex_coords = "uint(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  10954. else if (sampling_type_needs_f32_conversion(coord_type))
  10955. tex_coords = convert_to_f32(tex_coords, 1);
  10956. if (msl_options.texture_1D_as_2D)
  10957. {
  10958. if (args.base.is_fetch)
  10959. tex_coords = "uint2(" + tex_coords + ", 0)";
  10960. else
  10961. tex_coords = "float2(" + tex_coords + ", 0.5)";
  10962. }
  10963. alt_coord_component = 1;
  10964. break;
  10965. case DimBuffer:
  10966. if (coord_type.vecsize > 1)
  10967. tex_coords = enclose_expression(tex_coords) + ".x";
  10968. if (msl_options.texture_buffer_native)
  10969. {
  10970. tex_coords = "uint(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  10971. }
  10972. else
  10973. {
  10974. // Metal texel buffer textures are 2D, so convert 1D coord to 2D.
  10975. // Support for Metal 2.1's new texture_buffer type.
  10976. if (args.base.is_fetch)
  10977. {
  10978. if (msl_options.texel_buffer_texture_width > 0)
  10979. {
  10980. tex_coords = "spvTexelBufferCoord(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  10981. }
  10982. else
  10983. {
  10984. tex_coords = "spvTexelBufferCoord(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ", " +
  10985. to_expression(img) + ")";
  10986. }
  10987. }
  10988. }
  10989. alt_coord_component = 1;
  10990. break;
  10991. case DimSubpassData:
  10992. // If we're using Metal's native frame-buffer fetch API for subpass inputs,
  10993. // this path will not be hit.
  10994. tex_coords = "uint2(gl_FragCoord.xy)";
  10995. alt_coord_component = 2;
  10996. break;
  10997. case Dim2D:
  10998. if (coord_type.vecsize > 2)
  10999. tex_coords = enclose_expression(tex_coords) + ".xy";
  11000. if (args.base.is_fetch)
  11001. tex_coords = "uint2(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  11002. else if (sampling_type_needs_f32_conversion(coord_type))
  11003. tex_coords = convert_to_f32(tex_coords, 2);
  11004. alt_coord_component = 2;
  11005. break;
  11006. case Dim3D:
  11007. if (coord_type.vecsize > 3)
  11008. tex_coords = enclose_expression(tex_coords) + ".xyz";
  11009. if (args.base.is_fetch)
  11010. tex_coords = "uint3(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  11011. else if (sampling_type_needs_f32_conversion(coord_type))
  11012. tex_coords = convert_to_f32(tex_coords, 3);
  11013. alt_coord_component = 3;
  11014. break;
  11015. case DimCube:
  11016. if (args.base.is_fetch)
  11017. {
  11018. is_cube_fetch = true;
  11019. tex_coords += ".xy";
  11020. tex_coords = "uint2(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
  11021. }
  11022. else
  11023. {
  11024. if (coord_type.vecsize > 3)
  11025. tex_coords = enclose_expression(tex_coords) + ".xyz";
  11026. }
  11027. if (sampling_type_needs_f32_conversion(coord_type))
  11028. tex_coords = convert_to_f32(tex_coords, 3);
  11029. alt_coord_component = 3;
  11030. break;
  11031. default:
  11032. break;
  11033. }
  11034. if (args.base.is_fetch && args.offset)
  11035. {
  11036. // Fetch offsets must be applied directly to the coordinate.
  11037. forward = forward && should_forward(args.offset);
  11038. auto &type = expression_type(args.offset);
  11039. if (imgtype.image.dim == Dim1D && msl_options.texture_1D_as_2D)
  11040. {
  11041. if (type.basetype != SPIRType::UInt)
  11042. tex_coords += join(" + uint2(", bitcast_expression(SPIRType::UInt, args.offset), ", 0)");
  11043. else
  11044. tex_coords += join(" + uint2(", to_enclosed_unpacked_expression(args.offset), ", 0)");
  11045. }
  11046. else
  11047. {
  11048. if (type.basetype != SPIRType::UInt)
  11049. tex_coords += " + " + bitcast_expression(SPIRType::UInt, args.offset);
  11050. else
  11051. tex_coords += " + " + to_enclosed_unpacked_expression(args.offset);
  11052. }
  11053. }
  11054. // If projection, use alt coord as divisor
  11055. if (args.base.is_proj)
  11056. {
  11057. if (sampling_type_needs_f32_conversion(coord_type))
  11058. tex_coords += " / " + convert_to_f32(to_extract_component_expression(args.coord, alt_coord_component), 1);
  11059. else
  11060. tex_coords += " / " + to_extract_component_expression(args.coord, alt_coord_component);
  11061. }
  11062. if (!farg_str.empty())
  11063. farg_str += ", ";
  11064. if (imgtype.image.dim == DimCube && imgtype.image.arrayed && msl_options.emulate_cube_array)
  11065. {
  11066. farg_str += "spvCubemapTo2DArrayFace(" + tex_coords + ").xy";
  11067. if (is_cube_fetch)
  11068. farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ")";
  11069. else
  11070. farg_str +=
  11071. ", uint(spvCubemapTo2DArrayFace(" + tex_coords + ").z) + (uint(" +
  11072. round_fp_tex_coords(to_extract_component_expression(args.coord, alt_coord_component), coord_is_fp) +
  11073. ") * 6u)";
  11074. add_spv_func_and_recompile(SPVFuncImplCubemapTo2DArrayFace);
  11075. }
  11076. else
  11077. {
  11078. farg_str += tex_coords;
  11079. // If fetch from cube, add face explicitly
  11080. if (is_cube_fetch)
  11081. {
  11082. // Special case for cube arrays, face and layer are packed in one dimension.
  11083. if (imgtype.image.arrayed)
  11084. farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ") % 6u";
  11085. else
  11086. farg_str +=
  11087. ", uint(" + round_fp_tex_coords(to_extract_component_expression(args.coord, 2), coord_is_fp) + ")";
  11088. }
  11089. // If array, use alt coord
  11090. if (imgtype.image.arrayed)
  11091. {
  11092. // Special case for cube arrays, face and layer are packed in one dimension.
  11093. if (imgtype.image.dim == DimCube && args.base.is_fetch)
  11094. {
  11095. farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ") / 6u";
  11096. }
  11097. else
  11098. {
  11099. farg_str +=
  11100. ", uint(" +
  11101. round_fp_tex_coords(to_extract_component_expression(args.coord, alt_coord_component), coord_is_fp) +
  11102. ")";
  11103. if (imgtype.image.dim == DimSubpassData)
  11104. {
  11105. if (msl_options.multiview)
  11106. farg_str += " + gl_ViewIndex";
  11107. else if (msl_options.arrayed_subpass_input)
  11108. farg_str += " + gl_Layer";
  11109. }
  11110. }
  11111. }
  11112. else if (imgtype.image.dim == DimSubpassData)
  11113. {
  11114. if (msl_options.multiview)
  11115. farg_str += ", gl_ViewIndex";
  11116. else if (msl_options.arrayed_subpass_input)
  11117. farg_str += ", gl_Layer";
  11118. }
  11119. }
  11120. // Depth compare reference value
  11121. if (args.dref)
  11122. {
  11123. forward = forward && should_forward(args.dref);
  11124. farg_str += ", ";
  11125. auto &dref_type = expression_type(args.dref);
  11126. string dref_expr;
  11127. if (args.base.is_proj)
  11128. dref_expr = join(to_enclosed_unpacked_expression(args.dref), " / ",
  11129. to_extract_component_expression(args.coord, alt_coord_component));
  11130. else
  11131. dref_expr = to_unpacked_expression(args.dref);
  11132. if (sampling_type_needs_f32_conversion(dref_type))
  11133. dref_expr = convert_to_f32(dref_expr, 1);
  11134. farg_str += dref_expr;
  11135. if (msl_options.is_macos() && (grad_x || grad_y))
  11136. {
  11137. // For sample compare, MSL does not support gradient2d for all targets (only iOS apparently according to docs).
  11138. // However, the most common case here is to have a constant gradient of 0, as that is the only way to express
  11139. // LOD == 0 in GLSL with sampler2DArrayShadow (cascaded shadow mapping).
  11140. // We will detect a compile-time constant 0 value for gradient and promote that to level(0) on MSL.
  11141. bool constant_zero_x = !grad_x || expression_is_constant_null(grad_x);
  11142. bool constant_zero_y = !grad_y || expression_is_constant_null(grad_y);
  11143. if (constant_zero_x && constant_zero_y &&
  11144. (!imgtype.image.arrayed || !msl_options.sample_dref_lod_array_as_grad))
  11145. {
  11146. lod = 0;
  11147. grad_x = 0;
  11148. grad_y = 0;
  11149. farg_str += ", level(0)";
  11150. }
  11151. else if (!msl_options.supports_msl_version(2, 3))
  11152. {
  11153. SPIRV_CROSS_THROW("Using non-constant 0.0 gradient() qualifier for sample_compare. This is not "
  11154. "supported on macOS prior to MSL 2.3.");
  11155. }
  11156. }
  11157. if (msl_options.is_macos() && bias)
  11158. {
  11159. // Bias is not supported either on macOS with sample_compare.
  11160. // Verify it is compile-time zero, and drop the argument.
  11161. if (expression_is_constant_null(bias))
  11162. {
  11163. bias = 0;
  11164. }
  11165. else if (!msl_options.supports_msl_version(2, 3))
  11166. {
  11167. SPIRV_CROSS_THROW("Using non-constant 0.0 bias() qualifier for sample_compare. This is not supported "
  11168. "on macOS prior to MSL 2.3.");
  11169. }
  11170. }
  11171. }
  11172. // LOD Options
  11173. // Metal does not support LOD for 1D textures.
  11174. if (bias && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D))
  11175. {
  11176. forward = forward && should_forward(bias);
  11177. farg_str += ", bias(" + to_unpacked_expression(bias) + ")";
  11178. }
  11179. // Metal does not support LOD for 1D textures.
  11180. if (lod && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D))
  11181. {
  11182. forward = forward && should_forward(lod);
  11183. if (args.base.is_fetch)
  11184. {
  11185. farg_str += ", " + to_unpacked_expression(lod);
  11186. }
  11187. else if (msl_options.sample_dref_lod_array_as_grad && args.dref && imgtype.image.arrayed)
  11188. {
  11189. if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 3))
  11190. SPIRV_CROSS_THROW("Using non-constant 0.0 gradient() qualifier for sample_compare. This is not "
  11191. "supported on macOS prior to MSL 2.3.");
  11192. // Some Metal devices have a bug where the LoD is erroneously biased upward
  11193. // when using a level() argument. Since this doesn't happen as much with gradient2d(),
  11194. // if we perform the LoD calculation in reverse, we can pass a gradient
  11195. // instead.
  11196. // lod = log2(rhoMax/eta) -> exp2(lod) = rhoMax/eta
  11197. // If we make all of the scale factors the same, eta will be 1 and
  11198. // exp2(lod) = rho.
  11199. // rhoX = dP/dx * extent; rhoY = dP/dy * extent
  11200. // Therefore, dP/dx = dP/dy = exp2(lod)/extent.
  11201. // (Subtracting 0.5 before exponentiation gives better results.)
  11202. string grad_opt, extent, grad_coord;
  11203. VariableID base_img = img;
  11204. if (auto *combined = maybe_get<SPIRCombinedImageSampler>(img))
  11205. base_img = combined->image;
  11206. switch (imgtype.image.dim)
  11207. {
  11208. case Dim1D:
  11209. grad_opt = "gradient2d";
  11210. extent = join("float2(", to_expression(base_img), ".get_width(), 1.0)");
  11211. break;
  11212. case Dim2D:
  11213. grad_opt = "gradient2d";
  11214. extent = join("float2(", to_expression(base_img), ".get_width(), ", to_expression(base_img), ".get_height())");
  11215. break;
  11216. case DimCube:
  11217. if (imgtype.image.arrayed && msl_options.emulate_cube_array)
  11218. {
  11219. grad_opt = "gradient2d";
  11220. extent = join("float2(", to_expression(base_img), ".get_width())");
  11221. }
  11222. else
  11223. {
  11224. if (msl_options.agx_manual_cube_grad_fixup)
  11225. {
  11226. add_spv_func_and_recompile(SPVFuncImplGradientCube);
  11227. grad_opt = "spvGradientCube";
  11228. grad_coord = tex_coords + ", ";
  11229. }
  11230. else
  11231. {
  11232. grad_opt = "gradientcube";
  11233. }
  11234. extent = join("float3(", to_expression(base_img), ".get_width())");
  11235. }
  11236. break;
  11237. default:
  11238. grad_opt = "unsupported_gradient_dimension";
  11239. extent = "float3(1.0)";
  11240. break;
  11241. }
  11242. farg_str += join(", ", grad_opt, "(", grad_coord, "exp2(", to_unpacked_expression(lod), " - 0.5) / ", extent,
  11243. ", exp2(", to_unpacked_expression(lod), " - 0.5) / ", extent, ")");
  11244. }
  11245. else
  11246. {
  11247. farg_str += ", level(" + to_unpacked_expression(lod) + ")";
  11248. }
  11249. }
  11250. else if (args.base.is_fetch && !lod && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D) &&
  11251. imgtype.image.dim != DimBuffer && !imgtype.image.ms && imgtype.image.sampled != 2)
  11252. {
  11253. // Lod argument is optional in OpImageFetch, but we require a LOD value, pick 0 as the default.
  11254. // Check for sampled type as well, because is_fetch is also used for OpImageRead in MSL.
  11255. farg_str += ", 0";
  11256. }
  11257. // Metal does not support LOD for 1D textures.
  11258. if ((grad_x || grad_y) && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D))
  11259. {
  11260. forward = forward && should_forward(grad_x);
  11261. forward = forward && should_forward(grad_y);
  11262. string grad_opt, grad_coord;
  11263. switch (imgtype.image.dim)
  11264. {
  11265. case Dim1D:
  11266. case Dim2D:
  11267. grad_opt = "gradient2d";
  11268. break;
  11269. case Dim3D:
  11270. grad_opt = "gradient3d";
  11271. break;
  11272. case DimCube:
  11273. if (imgtype.image.arrayed && msl_options.emulate_cube_array)
  11274. {
  11275. grad_opt = "gradient2d";
  11276. }
  11277. else if (msl_options.agx_manual_cube_grad_fixup)
  11278. {
  11279. add_spv_func_and_recompile(SPVFuncImplGradientCube);
  11280. grad_opt = "spvGradientCube";
  11281. grad_coord = tex_coords + ", ";
  11282. }
  11283. else
  11284. {
  11285. grad_opt = "gradientcube";
  11286. }
  11287. break;
  11288. default:
  11289. grad_opt = "unsupported_gradient_dimension";
  11290. break;
  11291. }
  11292. farg_str += join(", ", grad_opt, "(", grad_coord, to_unpacked_expression(grad_x), ", ", to_unpacked_expression(grad_y), ")");
  11293. }
  11294. if (args.min_lod)
  11295. {
  11296. if (!msl_options.supports_msl_version(2, 2))
  11297. SPIRV_CROSS_THROW("min_lod_clamp() is only supported in MSL 2.2+ and up.");
  11298. forward = forward && should_forward(args.min_lod);
  11299. farg_str += ", min_lod_clamp(" + to_unpacked_expression(args.min_lod) + ")";
  11300. }
  11301. // Add offsets
  11302. string offset_expr;
  11303. const SPIRType *offset_type = nullptr;
  11304. if (args.offset && !args.base.is_fetch && !args.has_array_offsets)
  11305. {
  11306. forward = forward && should_forward(args.offset);
  11307. offset_expr = to_unpacked_expression(args.offset);
  11308. offset_type = &expression_type(args.offset);
  11309. }
  11310. if (!offset_expr.empty())
  11311. {
  11312. switch (imgtype.image.dim)
  11313. {
  11314. case Dim1D:
  11315. if (!msl_options.texture_1D_as_2D)
  11316. break;
  11317. if (offset_type->vecsize > 1)
  11318. offset_expr = enclose_expression(offset_expr) + ".x";
  11319. farg_str += join(", int2(", offset_expr, ", 0)");
  11320. break;
  11321. case Dim2D:
  11322. if (offset_type->vecsize > 2)
  11323. offset_expr = enclose_expression(offset_expr) + ".xy";
  11324. farg_str += ", " + offset_expr;
  11325. break;
  11326. case Dim3D:
  11327. if (offset_type->vecsize > 3)
  11328. offset_expr = enclose_expression(offset_expr) + ".xyz";
  11329. farg_str += ", " + offset_expr;
  11330. break;
  11331. default:
  11332. break;
  11333. }
  11334. }
  11335. if (args.component && !args.has_array_offsets)
  11336. {
  11337. // If 2D has gather component, ensure it also has an offset arg
  11338. if (imgtype.image.dim == Dim2D && offset_expr.empty())
  11339. farg_str += ", int2(0)";
  11340. if (!msl_options.swizzle_texture_samples || is_dynamic_img_sampler)
  11341. {
  11342. forward = forward && should_forward(args.component);
  11343. uint32_t image_var = 0;
  11344. if (const auto *combined = maybe_get<SPIRCombinedImageSampler>(img))
  11345. {
  11346. if (const auto *img_var = maybe_get_backing_variable(combined->image))
  11347. image_var = img_var->self;
  11348. }
  11349. else if (const auto *var = maybe_get_backing_variable(img))
  11350. {
  11351. image_var = var->self;
  11352. }
  11353. if (image_var == 0 || !is_depth_image(expression_type(image_var), image_var))
  11354. farg_str += ", " + to_component_argument(args.component);
  11355. }
  11356. }
  11357. if (args.sample)
  11358. {
  11359. forward = forward && should_forward(args.sample);
  11360. farg_str += ", ";
  11361. farg_str += to_unpacked_expression(args.sample);
  11362. }
  11363. *p_forward = forward;
  11364. return farg_str;
  11365. }
  11366. // If the texture coordinates are floating point, invokes MSL round() function to round them.
  11367. string CompilerMSL::round_fp_tex_coords(string tex_coords, bool coord_is_fp)
  11368. {
  11369. return coord_is_fp ? ("rint(" + tex_coords + ")") : tex_coords;
  11370. }
  11371. // Returns a string to use in an image sampling function argument.
  11372. // The ID must be a scalar constant.
  11373. string CompilerMSL::to_component_argument(uint32_t id)
  11374. {
  11375. uint32_t component_index = evaluate_constant_u32(id);
  11376. switch (component_index)
  11377. {
  11378. case 0:
  11379. return "component::x";
  11380. case 1:
  11381. return "component::y";
  11382. case 2:
  11383. return "component::z";
  11384. case 3:
  11385. return "component::w";
  11386. default:
  11387. SPIRV_CROSS_THROW("The value (" + to_string(component_index) + ") of OpConstant ID " + to_string(id) +
  11388. " is not a valid Component index, which must be one of 0, 1, 2, or 3.");
  11389. }
  11390. }
  11391. // Establish sampled image as expression object and assign the sampler to it.
  11392. void CompilerMSL::emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id)
  11393. {
  11394. set<SPIRCombinedImageSampler>(result_id, result_type, image_id, samp_id);
  11395. }
  11396. string CompilerMSL::to_texture_op(const Instruction &i, bool sparse, bool *forward,
  11397. SmallVector<uint32_t> &inherited_expressions)
  11398. {
  11399. auto *ops = stream(i);
  11400. uint32_t result_type_id = ops[0];
  11401. uint32_t img = ops[2];
  11402. auto &result_type = get<SPIRType>(result_type_id);
  11403. auto op = static_cast<Op>(i.op);
  11404. bool is_gather = (op == OpImageGather || op == OpImageDrefGather);
  11405. // Bypass pointers because we need the real image struct
  11406. auto &type = expression_type(img);
  11407. auto &imgtype = get<SPIRType>(type.self);
  11408. const MSLConstexprSampler *constexpr_sampler = nullptr;
  11409. bool is_dynamic_img_sampler = false;
  11410. if (auto *var = maybe_get_backing_variable(img))
  11411. {
  11412. constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self));
  11413. is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler);
  11414. }
  11415. string expr;
  11416. if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && !is_dynamic_img_sampler)
  11417. {
  11418. // If this needs sampler Y'CbCr conversion, we need to do some additional
  11419. // processing.
  11420. switch (constexpr_sampler->ycbcr_model)
  11421. {
  11422. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY:
  11423. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY:
  11424. // Default
  11425. break;
  11426. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709:
  11427. add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT709);
  11428. expr += "spvConvertYCbCrBT709(";
  11429. break;
  11430. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601:
  11431. add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT601);
  11432. expr += "spvConvertYCbCrBT601(";
  11433. break;
  11434. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020:
  11435. add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT2020);
  11436. expr += "spvConvertYCbCrBT2020(";
  11437. break;
  11438. default:
  11439. SPIRV_CROSS_THROW("Invalid Y'CbCr model conversion.");
  11440. }
  11441. if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY)
  11442. {
  11443. switch (constexpr_sampler->ycbcr_range)
  11444. {
  11445. case MSL_SAMPLER_YCBCR_RANGE_ITU_FULL:
  11446. add_spv_func_and_recompile(SPVFuncImplExpandITUFullRange);
  11447. expr += "spvExpandITUFullRange(";
  11448. break;
  11449. case MSL_SAMPLER_YCBCR_RANGE_ITU_NARROW:
  11450. add_spv_func_and_recompile(SPVFuncImplExpandITUNarrowRange);
  11451. expr += "spvExpandITUNarrowRange(";
  11452. break;
  11453. default:
  11454. SPIRV_CROSS_THROW("Invalid Y'CbCr range.");
  11455. }
  11456. }
  11457. }
  11458. else if (msl_options.swizzle_texture_samples && !is_gather && is_sampled_image_type(imgtype) &&
  11459. !is_dynamic_img_sampler)
  11460. {
  11461. add_spv_func_and_recompile(SPVFuncImplTextureSwizzle);
  11462. expr += "spvTextureSwizzle(";
  11463. }
  11464. string inner_expr = CompilerGLSL::to_texture_op(i, sparse, forward, inherited_expressions);
  11465. if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && !is_dynamic_img_sampler)
  11466. {
  11467. if (!constexpr_sampler->swizzle_is_identity())
  11468. {
  11469. static const char swizzle_names[] = "rgba";
  11470. if (!constexpr_sampler->swizzle_has_one_or_zero())
  11471. {
  11472. // If we can, do it inline.
  11473. expr += inner_expr + ".";
  11474. for (uint32_t c = 0; c < 4; c++)
  11475. {
  11476. switch (constexpr_sampler->swizzle[c])
  11477. {
  11478. case MSL_COMPONENT_SWIZZLE_IDENTITY:
  11479. expr += swizzle_names[c];
  11480. break;
  11481. case MSL_COMPONENT_SWIZZLE_R:
  11482. case MSL_COMPONENT_SWIZZLE_G:
  11483. case MSL_COMPONENT_SWIZZLE_B:
  11484. case MSL_COMPONENT_SWIZZLE_A:
  11485. expr += swizzle_names[constexpr_sampler->swizzle[c] - MSL_COMPONENT_SWIZZLE_R];
  11486. break;
  11487. default:
  11488. SPIRV_CROSS_THROW("Invalid component swizzle.");
  11489. }
  11490. }
  11491. }
  11492. else
  11493. {
  11494. // Otherwise, we need to emit a temporary and swizzle that.
  11495. uint32_t temp_id = ir.increase_bound_by(1);
  11496. emit_op(result_type_id, temp_id, inner_expr, false);
  11497. for (auto &inherit : inherited_expressions)
  11498. inherit_expression_dependencies(temp_id, inherit);
  11499. inherited_expressions.clear();
  11500. inherited_expressions.push_back(temp_id);
  11501. switch (op)
  11502. {
  11503. case OpImageSampleDrefImplicitLod:
  11504. case OpImageSampleImplicitLod:
  11505. case OpImageSampleProjImplicitLod:
  11506. case OpImageSampleProjDrefImplicitLod:
  11507. register_control_dependent_expression(temp_id);
  11508. break;
  11509. default:
  11510. break;
  11511. }
  11512. expr += type_to_glsl(result_type) + "(";
  11513. for (uint32_t c = 0; c < 4; c++)
  11514. {
  11515. switch (constexpr_sampler->swizzle[c])
  11516. {
  11517. case MSL_COMPONENT_SWIZZLE_IDENTITY:
  11518. expr += to_expression(temp_id) + "." + swizzle_names[c];
  11519. break;
  11520. case MSL_COMPONENT_SWIZZLE_ZERO:
  11521. expr += "0";
  11522. break;
  11523. case MSL_COMPONENT_SWIZZLE_ONE:
  11524. expr += "1";
  11525. break;
  11526. case MSL_COMPONENT_SWIZZLE_R:
  11527. case MSL_COMPONENT_SWIZZLE_G:
  11528. case MSL_COMPONENT_SWIZZLE_B:
  11529. case MSL_COMPONENT_SWIZZLE_A:
  11530. expr += to_expression(temp_id) + "." +
  11531. swizzle_names[constexpr_sampler->swizzle[c] - MSL_COMPONENT_SWIZZLE_R];
  11532. break;
  11533. default:
  11534. SPIRV_CROSS_THROW("Invalid component swizzle.");
  11535. }
  11536. if (c < 3)
  11537. expr += ", ";
  11538. }
  11539. expr += ")";
  11540. }
  11541. }
  11542. else
  11543. expr += inner_expr;
  11544. if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY)
  11545. {
  11546. expr += join(", ", constexpr_sampler->bpc, ")");
  11547. if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY)
  11548. expr += ")";
  11549. }
  11550. }
  11551. else
  11552. {
  11553. expr += inner_expr;
  11554. if (msl_options.swizzle_texture_samples && !is_gather && is_sampled_image_type(imgtype) &&
  11555. !is_dynamic_img_sampler)
  11556. {
  11557. // Add the swizzle constant from the swizzle buffer.
  11558. expr += ", " + to_swizzle_expression(img) + ")";
  11559. used_swizzle_buffer = true;
  11560. }
  11561. }
  11562. return expr;
  11563. }
  11564. static string create_swizzle(MSLComponentSwizzle swizzle)
  11565. {
  11566. switch (swizzle)
  11567. {
  11568. case MSL_COMPONENT_SWIZZLE_IDENTITY:
  11569. return "spvSwizzle::none";
  11570. case MSL_COMPONENT_SWIZZLE_ZERO:
  11571. return "spvSwizzle::zero";
  11572. case MSL_COMPONENT_SWIZZLE_ONE:
  11573. return "spvSwizzle::one";
  11574. case MSL_COMPONENT_SWIZZLE_R:
  11575. return "spvSwizzle::red";
  11576. case MSL_COMPONENT_SWIZZLE_G:
  11577. return "spvSwizzle::green";
  11578. case MSL_COMPONENT_SWIZZLE_B:
  11579. return "spvSwizzle::blue";
  11580. case MSL_COMPONENT_SWIZZLE_A:
  11581. return "spvSwizzle::alpha";
  11582. default:
  11583. SPIRV_CROSS_THROW("Invalid component swizzle.");
  11584. }
  11585. }
  11586. // Returns a string representation of the ID, usable as a function arg.
  11587. // Manufacture automatic sampler arg for SampledImage texture.
  11588. string CompilerMSL::to_func_call_arg(const SPIRFunction::Parameter &arg, uint32_t id)
  11589. {
  11590. string arg_str;
  11591. auto &type = expression_type(id);
  11592. bool is_dynamic_img_sampler = has_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler);
  11593. // If the argument *itself* is a "dynamic" combined-image sampler, then we can just pass that around.
  11594. bool arg_is_dynamic_img_sampler = has_extended_decoration(id, SPIRVCrossDecorationDynamicImageSampler);
  11595. if (is_dynamic_img_sampler && !arg_is_dynamic_img_sampler)
  11596. arg_str = join("spvDynamicImageSampler<", type_to_glsl(get<SPIRType>(type.image.type)), ">(");
  11597. auto *c = maybe_get<SPIRConstant>(id);
  11598. if (msl_options.force_native_arrays && c && !get<SPIRType>(c->constant_type).array.empty())
  11599. {
  11600. // If we are passing a constant array directly to a function for some reason,
  11601. // the callee will expect an argument in thread const address space
  11602. // (since we can only bind to arrays with references in MSL).
  11603. // To resolve this, we must emit a copy in this address space.
  11604. // This kind of code gen should be rare enough that performance is not a real concern.
  11605. // Inline the SPIR-V to avoid this kind of suboptimal codegen.
  11606. //
  11607. // We risk calling this inside a continue block (invalid code),
  11608. // so just create a thread local copy in the current function.
  11609. arg_str = join("_", id, "_array_copy");
  11610. auto &constants = current_function->constant_arrays_needed_on_stack;
  11611. auto itr = find(begin(constants), end(constants), ID(id));
  11612. if (itr == end(constants))
  11613. {
  11614. force_recompile();
  11615. constants.push_back(id);
  11616. }
  11617. }
  11618. // Dereference pointer variables where needed.
  11619. // FIXME: This dereference is actually backwards. We should really just support passing pointer variables between functions.
  11620. else if (should_dereference_caller_param(id))
  11621. arg_str += dereference_expression(type, CompilerGLSL::to_func_call_arg(arg, id));
  11622. else
  11623. arg_str += CompilerGLSL::to_func_call_arg(arg, id);
  11624. // Need to check the base variable in case we need to apply a qualified alias.
  11625. uint32_t var_id = 0;
  11626. auto *var = maybe_get<SPIRVariable>(id);
  11627. if (var)
  11628. var_id = var->basevariable;
  11629. if (!arg_is_dynamic_img_sampler)
  11630. {
  11631. auto *constexpr_sampler = find_constexpr_sampler(var_id ? var_id : id);
  11632. if (type.basetype == SPIRType::SampledImage)
  11633. {
  11634. // Manufacture automatic plane args for multiplanar texture
  11635. uint32_t planes = 1;
  11636. if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
  11637. {
  11638. planes = constexpr_sampler->planes;
  11639. // If this parameter isn't aliasing a global, then we need to use
  11640. // the special "dynamic image-sampler" class to pass it--and we need
  11641. // to use it for *every* non-alias parameter, in case a combined
  11642. // image-sampler with a Y'CbCr conversion is passed. Hopefully, this
  11643. // pathological case is so rare that it should never be hit in practice.
  11644. if (!arg.alias_global_variable)
  11645. add_spv_func_and_recompile(SPVFuncImplDynamicImageSampler);
  11646. }
  11647. for (uint32_t i = 1; i < planes; i++)
  11648. arg_str += join(", ", CompilerGLSL::to_func_call_arg(arg, id), plane_name_suffix, i);
  11649. // Manufacture automatic sampler arg if the arg is a SampledImage texture.
  11650. if (type.image.dim != DimBuffer)
  11651. arg_str += ", " + to_sampler_expression(var_id ? var_id : id);
  11652. // Add sampler Y'CbCr conversion info if we have it
  11653. if (is_dynamic_img_sampler && constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
  11654. {
  11655. SmallVector<string> samp_args;
  11656. switch (constexpr_sampler->resolution)
  11657. {
  11658. case MSL_FORMAT_RESOLUTION_444:
  11659. // Default
  11660. break;
  11661. case MSL_FORMAT_RESOLUTION_422:
  11662. samp_args.push_back("spvFormatResolution::_422");
  11663. break;
  11664. case MSL_FORMAT_RESOLUTION_420:
  11665. samp_args.push_back("spvFormatResolution::_420");
  11666. break;
  11667. default:
  11668. SPIRV_CROSS_THROW("Invalid format resolution.");
  11669. }
  11670. if (constexpr_sampler->chroma_filter != MSL_SAMPLER_FILTER_NEAREST)
  11671. samp_args.push_back("spvChromaFilter::linear");
  11672. if (constexpr_sampler->x_chroma_offset != MSL_CHROMA_LOCATION_COSITED_EVEN)
  11673. samp_args.push_back("spvXChromaLocation::midpoint");
  11674. if (constexpr_sampler->y_chroma_offset != MSL_CHROMA_LOCATION_COSITED_EVEN)
  11675. samp_args.push_back("spvYChromaLocation::midpoint");
  11676. switch (constexpr_sampler->ycbcr_model)
  11677. {
  11678. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY:
  11679. // Default
  11680. break;
  11681. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY:
  11682. samp_args.push_back("spvYCbCrModelConversion::ycbcr_identity");
  11683. break;
  11684. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709:
  11685. samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_709");
  11686. break;
  11687. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601:
  11688. samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_601");
  11689. break;
  11690. case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020:
  11691. samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_2020");
  11692. break;
  11693. default:
  11694. SPIRV_CROSS_THROW("Invalid Y'CbCr model conversion.");
  11695. }
  11696. if (constexpr_sampler->ycbcr_range != MSL_SAMPLER_YCBCR_RANGE_ITU_FULL)
  11697. samp_args.push_back("spvYCbCrRange::itu_narrow");
  11698. samp_args.push_back(join("spvComponentBits(", constexpr_sampler->bpc, ")"));
  11699. arg_str += join(", spvYCbCrSampler(", merge(samp_args), ")");
  11700. }
  11701. }
  11702. if (is_dynamic_img_sampler && constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
  11703. arg_str += join(", (uint(", create_swizzle(constexpr_sampler->swizzle[3]), ") << 24) | (uint(",
  11704. create_swizzle(constexpr_sampler->swizzle[2]), ") << 16) | (uint(",
  11705. create_swizzle(constexpr_sampler->swizzle[1]), ") << 8) | uint(",
  11706. create_swizzle(constexpr_sampler->swizzle[0]), ")");
  11707. else if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(type))
  11708. arg_str += ", " + to_swizzle_expression(var_id ? var_id : id);
  11709. if (buffer_requires_array_length(var_id))
  11710. arg_str += ", " + to_buffer_size_expression(var_id ? var_id : id);
  11711. if (is_dynamic_img_sampler)
  11712. arg_str += ")";
  11713. }
  11714. // Emulate texture2D atomic operations
  11715. auto *backing_var = maybe_get_backing_variable(var_id);
  11716. if (backing_var && atomic_image_vars_emulated.count(backing_var->self))
  11717. {
  11718. arg_str += ", " + to_expression(var_id) + "_atomic";
  11719. }
  11720. return arg_str;
  11721. }
  11722. // If the ID represents a sampled image that has been assigned a sampler already,
  11723. // generate an expression for the sampler, otherwise generate a fake sampler name
  11724. // by appending a suffix to the expression constructed from the ID.
  11725. string CompilerMSL::to_sampler_expression(uint32_t id)
  11726. {
  11727. auto *combined = maybe_get<SPIRCombinedImageSampler>(id);
  11728. if (combined && combined->sampler)
  11729. return to_expression(combined->sampler);
  11730. uint32_t expr_id = combined ? uint32_t(combined->image) : id;
  11731. // Constexpr samplers are declared as local variables,
  11732. // so exclude any qualifier names on the image expression.
  11733. if (auto *var = maybe_get_backing_variable(expr_id))
  11734. {
  11735. uint32_t img_id = var->basevariable ? var->basevariable : VariableID(var->self);
  11736. if (find_constexpr_sampler(img_id))
  11737. return Compiler::to_name(img_id) + sampler_name_suffix;
  11738. }
  11739. auto img_expr = to_expression(expr_id);
  11740. auto index = img_expr.find_first_of('[');
  11741. if (index == string::npos)
  11742. return img_expr + sampler_name_suffix;
  11743. else
  11744. return img_expr.substr(0, index) + sampler_name_suffix + img_expr.substr(index);
  11745. }
  11746. string CompilerMSL::to_swizzle_expression(uint32_t id)
  11747. {
  11748. auto *combined = maybe_get<SPIRCombinedImageSampler>(id);
  11749. auto expr = to_expression(combined ? combined->image : VariableID(id));
  11750. auto index = expr.find_first_of('[');
  11751. // If an image is part of an argument buffer translate this to a legal identifier.
  11752. string::size_type period = 0;
  11753. while ((period = expr.find_first_of('.', period)) != string::npos && period < index)
  11754. expr[period] = '_';
  11755. if (index == string::npos)
  11756. return expr + swizzle_name_suffix;
  11757. else
  11758. {
  11759. auto image_expr = expr.substr(0, index);
  11760. auto array_expr = expr.substr(index);
  11761. return image_expr + swizzle_name_suffix + array_expr;
  11762. }
  11763. }
  11764. string CompilerMSL::to_buffer_size_expression(uint32_t id)
  11765. {
  11766. auto expr = to_expression(id);
  11767. // This is quite crude, but we need to translate the reference name (*spvDescriptorSetN.name) to
  11768. // the pointer expression spvDescriptorSetN.name to make a reasonable expression here.
  11769. // This only happens if we have argument buffers and we are using OpArrayLength on a lone SSBO in that set.
  11770. if (expr.size() >= 3 && expr[0] == '(' && expr[1] == '*')
  11771. expr = address_of_expression(expr);
  11772. auto index = expr.find_first_of('[');
  11773. string buffer_expr, array_expr;
  11774. if (index != string::npos)
  11775. {
  11776. buffer_expr = expr.substr(0, index);
  11777. array_expr = expr.substr(index);
  11778. }
  11779. // If a buffer is part of an argument buffer translate this to a legal identifier.
  11780. for (auto &c : expr)
  11781. if (c == '.')
  11782. c = '_';
  11783. if (index == string::npos)
  11784. {
  11785. return expr + buffer_size_name_suffix;
  11786. }
  11787. else
  11788. {
  11789. if (auto var = maybe_get_backing_variable(id))
  11790. {
  11791. if (is_var_runtime_size_array(*var))
  11792. {
  11793. if (!msl_options.runtime_array_rich_descriptor)
  11794. SPIRV_CROSS_THROW("OpArrayLength requires rich descriptor format");
  11795. auto last_pos = array_expr.find_last_of(']');
  11796. if (last_pos != std::string::npos)
  11797. return buffer_expr + ".length(" + array_expr.substr(1, last_pos - 1) + ")";
  11798. }
  11799. }
  11800. for (auto &c : buffer_expr)
  11801. if (c == '.')
  11802. c = '_';
  11803. return buffer_expr + buffer_size_name_suffix + array_expr;
  11804. }
  11805. }
  11806. // Checks whether the type is a Block all of whose members have DecorationPatch.
  11807. bool CompilerMSL::is_patch_block(const SPIRType &type)
  11808. {
  11809. if (!has_decoration(type.self, DecorationBlock))
  11810. return false;
  11811. for (uint32_t i = 0; i < type.member_types.size(); i++)
  11812. {
  11813. if (!has_member_decoration(type.self, i, DecorationPatch))
  11814. return false;
  11815. }
  11816. return true;
  11817. }
  11818. // Checks whether the ID is a row_major matrix that requires conversion before use
  11819. bool CompilerMSL::is_non_native_row_major_matrix(uint32_t id)
  11820. {
  11821. auto *e = maybe_get<SPIRExpression>(id);
  11822. if (e)
  11823. return e->need_transpose;
  11824. else
  11825. return has_decoration(id, DecorationRowMajor);
  11826. }
  11827. // Checks whether the member is a row_major matrix that requires conversion before use
  11828. bool CompilerMSL::member_is_non_native_row_major_matrix(const SPIRType &type, uint32_t index)
  11829. {
  11830. return has_member_decoration(type.self, index, DecorationRowMajor);
  11831. }
  11832. string CompilerMSL::convert_row_major_matrix(string exp_str, const SPIRType &exp_type, uint32_t physical_type_id,
  11833. bool is_packed, bool relaxed)
  11834. {
  11835. if (!is_matrix(exp_type))
  11836. {
  11837. return CompilerGLSL::convert_row_major_matrix(std::move(exp_str), exp_type, physical_type_id, is_packed, relaxed);
  11838. }
  11839. else
  11840. {
  11841. strip_enclosed_expression(exp_str);
  11842. if (physical_type_id != 0 || is_packed)
  11843. exp_str = unpack_expression_type(exp_str, exp_type, physical_type_id, is_packed, true);
  11844. return join("transpose(", exp_str, ")");
  11845. }
  11846. }
  11847. // Called automatically at the end of the entry point function
  11848. void CompilerMSL::emit_fixup()
  11849. {
  11850. if (stage_out_var_id && !capture_output_to_buffer)
  11851. {
  11852. if (needs_point_size_output && !writes_to_point_size)
  11853. statement(builtin_to_glsl(BuiltInPointSize, StorageClassOutput), " = ", format_float(msl_options.default_point_size), ";");
  11854. if (is_vertex_like_shader() && !qual_pos_var_name.empty())
  11855. {
  11856. if (options.vertex.fixup_clipspace)
  11857. statement(qual_pos_var_name, ".z = (", qual_pos_var_name, ".z + ", qual_pos_var_name,
  11858. ".w) * 0.5; // Adjust clip-space for Metal");
  11859. if (options.vertex.flip_vert_y)
  11860. statement(qual_pos_var_name, ".y = -(", qual_pos_var_name, ".y);", " // Invert Y-axis for Metal");
  11861. }
  11862. }
  11863. }
  11864. // Return a string defining a structure member, with padding and packing.
  11865. string CompilerMSL::to_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
  11866. const string &qualifier)
  11867. {
  11868. uint32_t orig_member_type_id = member_type_id;
  11869. if (member_is_remapped_physical_type(type, index))
  11870. member_type_id = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPhysicalTypeID);
  11871. auto &physical_type = get<SPIRType>(member_type_id);
  11872. // If this member is packed, mark it as so.
  11873. string pack_pfx;
  11874. // Allow Metal to use the array<T> template to make arrays a value type
  11875. uint32_t orig_id = 0;
  11876. if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID))
  11877. orig_id = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID);
  11878. bool row_major = false;
  11879. if (is_matrix(physical_type))
  11880. row_major = has_member_decoration(type.self, index, DecorationRowMajor);
  11881. SPIRType row_major_physical_type { OpTypeMatrix };
  11882. const SPIRType *declared_type = &physical_type;
  11883. // If a struct is being declared with physical layout,
  11884. // do not use array<T> wrappers.
  11885. // This avoids a lot of complicated cases with packed vectors and matrices,
  11886. // and generally we cannot copy full arrays in and out of buffers into Function
  11887. // address space.
  11888. // Array of resources should also be declared as builtin arrays.
  11889. if (has_member_decoration(type.self, index, DecorationOffset))
  11890. is_using_builtin_array = true;
  11891. else if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary))
  11892. is_using_builtin_array = true;
  11893. if (member_is_packed_physical_type(type, index))
  11894. {
  11895. // If we're packing a matrix, output an appropriate typedef
  11896. if (physical_type.basetype == SPIRType::Struct)
  11897. {
  11898. SPIRV_CROSS_THROW("Cannot emit a packed struct currently.");
  11899. }
  11900. else if (is_matrix(physical_type))
  11901. {
  11902. uint32_t rows = physical_type.vecsize;
  11903. uint32_t cols = physical_type.columns;
  11904. pack_pfx = "packed_";
  11905. if (row_major)
  11906. {
  11907. // These are stored transposed.
  11908. rows = physical_type.columns;
  11909. cols = physical_type.vecsize;
  11910. pack_pfx = "packed_rm_";
  11911. }
  11912. string base_type = physical_type.width == 16 ? "half" : "float";
  11913. string td_line = "typedef ";
  11914. td_line += "packed_" + base_type + to_string(rows);
  11915. td_line += " " + pack_pfx;
  11916. // Use the actual matrix size here.
  11917. td_line += base_type + to_string(physical_type.columns) + "x" + to_string(physical_type.vecsize);
  11918. td_line += "[" + to_string(cols) + "]";
  11919. td_line += ";";
  11920. add_typedef_line(td_line);
  11921. }
  11922. else if (!is_scalar(physical_type)) // scalar type is already packed.
  11923. pack_pfx = "packed_";
  11924. }
  11925. else if (is_matrix(physical_type))
  11926. {
  11927. if (!msl_options.supports_msl_version(3, 0) &&
  11928. has_extended_decoration(type.self, SPIRVCrossDecorationWorkgroupStruct))
  11929. {
  11930. pack_pfx = "spvStorage_";
  11931. add_spv_func_and_recompile(SPVFuncImplStorageMatrix);
  11932. // The pack prefix causes problems with array<T> wrappers.
  11933. is_using_builtin_array = true;
  11934. }
  11935. if (row_major)
  11936. {
  11937. // Need to declare type with flipped vecsize/columns.
  11938. row_major_physical_type = physical_type;
  11939. swap(row_major_physical_type.vecsize, row_major_physical_type.columns);
  11940. declared_type = &row_major_physical_type;
  11941. }
  11942. }
  11943. // iOS Tier 1 argument buffers do not support writable images.
  11944. if (physical_type.basetype == SPIRType::Image &&
  11945. physical_type.image.sampled == 2 &&
  11946. msl_options.is_ios() &&
  11947. msl_options.argument_buffers_tier <= Options::ArgumentBuffersTier::Tier1 &&
  11948. !has_decoration(orig_id, DecorationNonWritable))
  11949. {
  11950. SPIRV_CROSS_THROW("Writable images are not allowed on Tier1 argument buffers on iOS.");
  11951. }
  11952. // Array information is baked into these types.
  11953. string array_type;
  11954. if (physical_type.basetype != SPIRType::Image && physical_type.basetype != SPIRType::Sampler &&
  11955. physical_type.basetype != SPIRType::SampledImage)
  11956. {
  11957. BuiltIn builtin = BuiltInMax;
  11958. // Special handling. In [[stage_out]] or [[stage_in]] blocks,
  11959. // we need flat arrays, but if we're somehow declaring gl_PerVertex for constant array reasons, we want
  11960. // template array types to be declared.
  11961. bool is_ib_in_out =
  11962. ((stage_out_var_id && get_stage_out_struct_type().self == type.self &&
  11963. variable_storage_requires_stage_io(StorageClassOutput)) ||
  11964. (stage_in_var_id && get_stage_in_struct_type().self == type.self &&
  11965. variable_storage_requires_stage_io(StorageClassInput))) ||
  11966. is_mesh_shader();
  11967. if (is_ib_in_out && is_member_builtin(type, index, &builtin))
  11968. is_using_builtin_array = true;
  11969. array_type = type_to_array_glsl(physical_type, orig_id);
  11970. }
  11971. if (is_mesh_shader())
  11972. {
  11973. BuiltIn builtin = BuiltInMax;
  11974. if (is_member_builtin(type, index, &builtin))
  11975. {
  11976. if (builtin == BuiltInPrimitiveShadingRateKHR)
  11977. {
  11978. // not supported in metal 3.0
  11979. is_using_builtin_array = false;
  11980. return "";
  11981. }
  11982. SPIRType metallic_type = *declared_type;
  11983. if (builtin == BuiltInCullPrimitiveEXT)
  11984. metallic_type.basetype = SPIRType::Boolean;
  11985. else if (builtin == BuiltInPrimitiveId || builtin == BuiltInLayer || builtin == BuiltInViewportIndex)
  11986. metallic_type.basetype = SPIRType::UInt;
  11987. is_using_builtin_array = true;
  11988. std::string result;
  11989. if (has_member_decoration(type.self, orig_id, DecorationBuiltIn))
  11990. {
  11991. // avoid '_RESERVED_IDENTIFIER_FIXUP_' in variable name
  11992. result = join(type_to_glsl(metallic_type, orig_id, false), " ", qualifier,
  11993. builtin_to_glsl(builtin, StorageClassOutput), member_attribute_qualifier(type, index),
  11994. array_type, ";");
  11995. }
  11996. else
  11997. {
  11998. result = join(type_to_glsl(metallic_type, orig_id, false), " ", qualifier,
  11999. to_member_name(type, index), member_attribute_qualifier(type, index), array_type, ";");
  12000. }
  12001. is_using_builtin_array = false;
  12002. return result;
  12003. }
  12004. }
  12005. if (orig_id)
  12006. {
  12007. auto *data_type = declared_type;
  12008. if (is_pointer(*data_type))
  12009. data_type = &get_pointee_type(*data_type);
  12010. if (is_array(*data_type) && get_resource_array_size(*data_type, orig_id) == 0)
  12011. {
  12012. // Hack for declaring unsized array of resources. Need to declare dummy sized array by value inline.
  12013. // This can then be wrapped in spvDescriptorArray as usual.
  12014. array_type = "[1] /* unsized array hack */";
  12015. }
  12016. }
  12017. string decl_type;
  12018. if (declared_type->vecsize > 4)
  12019. {
  12020. auto orig_type = get<SPIRType>(orig_member_type_id);
  12021. if (is_matrix(orig_type) && row_major)
  12022. swap(orig_type.vecsize, orig_type.columns);
  12023. orig_type.columns = 1;
  12024. decl_type = type_to_glsl(orig_type, orig_id, true);
  12025. if (declared_type->columns > 1)
  12026. decl_type = join("spvPaddedStd140Matrix<", decl_type, ", ", declared_type->columns, ">");
  12027. else
  12028. decl_type = join("spvPaddedStd140<", decl_type, ">");
  12029. }
  12030. else
  12031. decl_type = type_to_glsl(*declared_type, orig_id, true);
  12032. const char *overlapping_binding_tag =
  12033. has_extended_member_decoration(type.self, index, SPIRVCrossDecorationOverlappingBinding) ?
  12034. "// Overlapping binding: " : "";
  12035. auto result = join(overlapping_binding_tag, pack_pfx, decl_type, " ", qualifier,
  12036. to_member_name(type, index), member_attribute_qualifier(type, index), array_type, ";");
  12037. is_using_builtin_array = false;
  12038. return result;
  12039. }
  12040. // Emit a structure member, padding and packing to maintain the correct memeber alignments.
  12041. void CompilerMSL::emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
  12042. const string &qualifier, uint32_t)
  12043. {
  12044. // If this member requires padding to maintain its declared offset, emit a dummy padding member before it.
  12045. if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationPaddingTarget))
  12046. {
  12047. uint32_t pad_len = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPaddingTarget);
  12048. statement("char _m", index, "_pad", "[", pad_len, "];");
  12049. }
  12050. BuiltIn builtin = BuiltInMax;
  12051. if (is_mesh_shader() && is_member_builtin(type, index, &builtin))
  12052. {
  12053. if (!has_active_builtin(builtin, StorageClassOutput) && !has_active_builtin(builtin, StorageClassInput))
  12054. {
  12055. // Do not emit unused builtins in mesh-output blocks
  12056. return;
  12057. }
  12058. }
  12059. // Handle HLSL-style 0-based vertex/instance index.
  12060. builtin_declaration = true;
  12061. statement(to_struct_member(type, member_type_id, index, qualifier));
  12062. builtin_declaration = false;
  12063. }
  12064. void CompilerMSL::emit_struct_padding_target(const SPIRType &type)
  12065. {
  12066. uint32_t struct_size = get_declared_struct_size_msl(type, true, true);
  12067. uint32_t target_size = get_extended_decoration(type.self, SPIRVCrossDecorationPaddingTarget);
  12068. if (target_size < struct_size)
  12069. SPIRV_CROSS_THROW("Cannot pad with negative bytes.");
  12070. else if (target_size > struct_size)
  12071. statement("char _m0_final_padding[", target_size - struct_size, "];");
  12072. }
  12073. // Return a MSL qualifier for the specified function attribute member
  12074. string CompilerMSL::member_attribute_qualifier(const SPIRType &type, uint32_t index)
  12075. {
  12076. auto &execution = get_entry_point();
  12077. uint32_t mbr_type_id = type.member_types[index];
  12078. auto &mbr_type = get<SPIRType>(mbr_type_id);
  12079. BuiltIn builtin = BuiltInMax;
  12080. bool is_builtin = is_member_builtin(type, index, &builtin);
  12081. if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary))
  12082. {
  12083. string quals = join(
  12084. " [[id(", get_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary), ")");
  12085. if (interlocked_resources.count(
  12086. get_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID)))
  12087. quals += ", raster_order_group(0)";
  12088. quals += "]]";
  12089. return quals;
  12090. }
  12091. // Vertex function inputs
  12092. if (execution.model == ExecutionModelVertex && type.storage == StorageClassInput)
  12093. {
  12094. if (is_builtin)
  12095. {
  12096. switch (builtin)
  12097. {
  12098. case BuiltInVertexId:
  12099. case BuiltInVertexIndex:
  12100. case BuiltInBaseVertex:
  12101. case BuiltInInstanceId:
  12102. case BuiltInInstanceIndex:
  12103. case BuiltInBaseInstance:
  12104. if (msl_options.vertex_for_tessellation)
  12105. return "";
  12106. return string(" [[") + builtin_qualifier(builtin) + "]]";
  12107. case BuiltInDrawIndex:
  12108. SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
  12109. default:
  12110. return "";
  12111. }
  12112. }
  12113. uint32_t locn;
  12114. if (is_builtin)
  12115. locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index);
  12116. else
  12117. locn = get_member_location(type.self, index);
  12118. if (locn != k_unknown_location)
  12119. return string(" [[attribute(") + convert_to_string(locn) + ")]]";
  12120. }
  12121. bool use_semantic_stage_output = is_mesh_shader() || is_tese_shader() ||
  12122. (execution.model == ExecutionModelVertex && !msl_options.vertex_for_tessellation);
  12123. // Vertex, mesh and tessellation evaluation function outputs
  12124. if ((type.storage == StorageClassOutput || is_mesh_shader()) && use_semantic_stage_output)
  12125. {
  12126. if (is_builtin)
  12127. {
  12128. switch (builtin)
  12129. {
  12130. case BuiltInPointSize:
  12131. // Only mark the PointSize builtin if really rendering points.
  12132. // Some shaders may include a PointSize builtin even when used to render
  12133. // non-point topologies, and Metal will reject this builtin when compiling
  12134. // the shader into a render pipeline that uses a non-point topology.
  12135. return msl_options.enable_point_size_builtin ? (string(" [[") + builtin_qualifier(builtin) + "]]") : "";
  12136. case BuiltInViewportIndex:
  12137. if (!msl_options.supports_msl_version(2, 0))
  12138. SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
  12139. /* fallthrough */
  12140. case BuiltInPosition:
  12141. case BuiltInLayer:
  12142. case BuiltInCullPrimitiveEXT:
  12143. case BuiltInPrimitiveShadingRateKHR:
  12144. case BuiltInPrimitiveId:
  12145. return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
  12146. case BuiltInClipDistance:
  12147. if (has_member_decoration(type.self, index, DecorationIndex))
  12148. return join(" [[user(clip", get_member_decoration(type.self, index, DecorationIndex), ")]]");
  12149. else
  12150. return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
  12151. case BuiltInCullDistance:
  12152. if (has_member_decoration(type.self, index, DecorationIndex))
  12153. return join(" [[user(cull", get_member_decoration(type.self, index, DecorationIndex), ")]]");
  12154. else
  12155. return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
  12156. default:
  12157. return "";
  12158. }
  12159. }
  12160. string loc_qual = member_location_attribute_qualifier(type, index);
  12161. if (!loc_qual.empty())
  12162. return join(" [[", loc_qual, "]]");
  12163. }
  12164. if (execution.model == ExecutionModelVertex && msl_options.vertex_for_tessellation && type.storage == StorageClassOutput)
  12165. {
  12166. // For this type of shader, we always arrange for it to capture its
  12167. // output to a buffer. For this reason, qualifiers are irrelevant here.
  12168. if (is_builtin)
  12169. // We still have to assign a location so the output struct will sort correctly.
  12170. get_or_allocate_builtin_output_member_location(builtin, type.self, index);
  12171. return "";
  12172. }
  12173. // Tessellation control function inputs
  12174. if (is_tesc_shader() && type.storage == StorageClassInput)
  12175. {
  12176. if (is_builtin)
  12177. {
  12178. switch (builtin)
  12179. {
  12180. case BuiltInInvocationId:
  12181. case BuiltInPrimitiveId:
  12182. if (msl_options.multi_patch_workgroup)
  12183. return "";
  12184. return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
  12185. case BuiltInSubgroupLocalInvocationId: // FIXME: Should work in any stage
  12186. case BuiltInSubgroupSize: // FIXME: Should work in any stage
  12187. if (msl_options.emulate_subgroups)
  12188. return "";
  12189. return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
  12190. case BuiltInPatchVertices:
  12191. return "";
  12192. // Others come from stage input.
  12193. default:
  12194. break;
  12195. }
  12196. }
  12197. if (msl_options.multi_patch_workgroup)
  12198. return "";
  12199. uint32_t locn;
  12200. if (is_builtin)
  12201. locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index);
  12202. else
  12203. locn = get_member_location(type.self, index);
  12204. if (locn != k_unknown_location)
  12205. return string(" [[attribute(") + convert_to_string(locn) + ")]]";
  12206. }
  12207. // Tessellation control function outputs
  12208. if (is_tesc_shader() && type.storage == StorageClassOutput)
  12209. {
  12210. // For this type of shader, we always arrange for it to capture its
  12211. // output to a buffer. For this reason, qualifiers are irrelevant here.
  12212. if (is_builtin)
  12213. // We still have to assign a location so the output struct will sort correctly.
  12214. get_or_allocate_builtin_output_member_location(builtin, type.self, index);
  12215. return "";
  12216. }
  12217. // Tessellation evaluation function inputs
  12218. if (is_tese_shader() && type.storage == StorageClassInput)
  12219. {
  12220. if (is_builtin)
  12221. {
  12222. switch (builtin)
  12223. {
  12224. case BuiltInPrimitiveId:
  12225. case BuiltInTessCoord:
  12226. return string(" [[") + builtin_qualifier(builtin) + "]]";
  12227. case BuiltInPatchVertices:
  12228. return "";
  12229. // Others come from stage input.
  12230. default:
  12231. break;
  12232. }
  12233. }
  12234. if (msl_options.raw_buffer_tese_input)
  12235. return "";
  12236. // The special control point array must not be marked with an attribute.
  12237. if (get_type(type.member_types[index]).basetype == SPIRType::ControlPointArray)
  12238. return "";
  12239. uint32_t locn;
  12240. if (is_builtin)
  12241. locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index);
  12242. else
  12243. locn = get_member_location(type.self, index);
  12244. if (locn != k_unknown_location)
  12245. return string(" [[attribute(") + convert_to_string(locn) + ")]]";
  12246. }
  12247. // Tessellation evaluation function outputs were handled above.
  12248. // Fragment function inputs
  12249. if (execution.model == ExecutionModelFragment && type.storage == StorageClassInput)
  12250. {
  12251. string quals;
  12252. if (is_builtin)
  12253. {
  12254. switch (builtin)
  12255. {
  12256. case BuiltInViewIndex:
  12257. if (!msl_options.multiview || !msl_options.multiview_layered_rendering)
  12258. break;
  12259. /* fallthrough */
  12260. case BuiltInFrontFacing:
  12261. case BuiltInPointCoord:
  12262. case BuiltInFragCoord:
  12263. case BuiltInSampleId:
  12264. case BuiltInSampleMask:
  12265. case BuiltInLayer:
  12266. case BuiltInBaryCoordKHR:
  12267. case BuiltInBaryCoordNoPerspKHR:
  12268. quals = builtin_qualifier(builtin);
  12269. break;
  12270. case BuiltInClipDistance:
  12271. return join(" [[user(clip", get_member_decoration(type.self, index, DecorationIndex), ")]]");
  12272. case BuiltInCullDistance:
  12273. return join(" [[user(cull", get_member_decoration(type.self, index, DecorationIndex), ")]]");
  12274. default:
  12275. break;
  12276. }
  12277. }
  12278. else
  12279. quals = member_location_attribute_qualifier(type, index);
  12280. if (builtin == BuiltInBaryCoordKHR && has_member_decoration(type.self, index, DecorationNoPerspective))
  12281. {
  12282. // NoPerspective is baked into the builtin type.
  12283. SPIRV_CROSS_THROW("NoPerspective decorations are not supported for BaryCoord inputs.");
  12284. }
  12285. // Don't bother decorating integers with the 'flat' attribute; it's
  12286. // the default (in fact, the only option). Also don't bother with the
  12287. // FragCoord builtin; it's always noperspective on Metal.
  12288. if (!type_is_integral(mbr_type) && (!is_builtin || builtin != BuiltInFragCoord))
  12289. {
  12290. if (has_member_decoration(type.self, index, DecorationFlat))
  12291. {
  12292. if (!quals.empty())
  12293. quals += ", ";
  12294. quals += "flat";
  12295. }
  12296. else if (has_member_decoration(type.self, index, DecorationCentroid))
  12297. {
  12298. if (!quals.empty())
  12299. quals += ", ";
  12300. if (builtin == BuiltInBaryCoordNoPerspKHR || builtin == BuiltInBaryCoordKHR)
  12301. SPIRV_CROSS_THROW("Centroid interpolation not supported for barycentrics in MSL.");
  12302. if (has_member_decoration(type.self, index, DecorationNoPerspective))
  12303. quals += "centroid_no_perspective";
  12304. else
  12305. quals += "centroid_perspective";
  12306. }
  12307. else if (has_member_decoration(type.self, index, DecorationSample))
  12308. {
  12309. if (!quals.empty())
  12310. quals += ", ";
  12311. if (builtin == BuiltInBaryCoordNoPerspKHR || builtin == BuiltInBaryCoordKHR)
  12312. SPIRV_CROSS_THROW("Sample interpolation not supported for barycentrics in MSL.");
  12313. if (has_member_decoration(type.self, index, DecorationNoPerspective))
  12314. quals += "sample_no_perspective";
  12315. else
  12316. quals += "sample_perspective";
  12317. }
  12318. else if (has_member_decoration(type.self, index, DecorationNoPerspective) || builtin == BuiltInBaryCoordNoPerspKHR)
  12319. {
  12320. if (!quals.empty())
  12321. quals += ", ";
  12322. quals += "center_no_perspective";
  12323. }
  12324. else if (builtin == BuiltInBaryCoordKHR)
  12325. {
  12326. if (!quals.empty())
  12327. quals += ", ";
  12328. quals += "center_perspective";
  12329. }
  12330. }
  12331. if (!quals.empty())
  12332. return " [[" + quals + "]]";
  12333. }
  12334. // Fragment function outputs
  12335. if (execution.model == ExecutionModelFragment && type.storage == StorageClassOutput)
  12336. {
  12337. if (is_builtin)
  12338. {
  12339. switch (builtin)
  12340. {
  12341. case BuiltInFragStencilRefEXT:
  12342. // Similar to PointSize, only mark FragStencilRef if there's a stencil buffer.
  12343. // Some shaders may include a FragStencilRef builtin even when used to render
  12344. // without a stencil attachment, and Metal will reject this builtin
  12345. // when compiling the shader into a render pipeline that does not set
  12346. // stencilAttachmentPixelFormat.
  12347. if (!msl_options.enable_frag_stencil_ref_builtin)
  12348. return "";
  12349. if (!msl_options.supports_msl_version(2, 1))
  12350. SPIRV_CROSS_THROW("Stencil export only supported in MSL 2.1 and up.");
  12351. return string(" [[") + builtin_qualifier(builtin) + "]]";
  12352. case BuiltInFragDepth:
  12353. // Ditto FragDepth.
  12354. if (!msl_options.enable_frag_depth_builtin)
  12355. return "";
  12356. /* fallthrough */
  12357. case BuiltInSampleMask:
  12358. return string(" [[") + builtin_qualifier(builtin) + "]]";
  12359. default:
  12360. return "";
  12361. }
  12362. }
  12363. uint32_t locn = get_member_location(type.self, index);
  12364. // Metal will likely complain about missing color attachments, too.
  12365. if (locn != k_unknown_location && !(msl_options.enable_frag_output_mask & (1 << locn)))
  12366. return "";
  12367. if (locn != k_unknown_location && has_member_decoration(type.self, index, DecorationIndex))
  12368. return join(" [[color(", locn, "), index(", get_member_decoration(type.self, index, DecorationIndex),
  12369. ")]]");
  12370. else if (locn != k_unknown_location)
  12371. return join(" [[color(", locn, ")]]");
  12372. else if (has_member_decoration(type.self, index, DecorationIndex))
  12373. return join(" [[index(", get_member_decoration(type.self, index, DecorationIndex), ")]]");
  12374. else
  12375. return "";
  12376. }
  12377. // Compute function inputs
  12378. if (execution.model == ExecutionModelGLCompute && type.storage == StorageClassInput)
  12379. {
  12380. if (is_builtin)
  12381. {
  12382. switch (builtin)
  12383. {
  12384. case BuiltInNumSubgroups:
  12385. case BuiltInSubgroupId:
  12386. case BuiltInSubgroupLocalInvocationId: // FIXME: Should work in any stage
  12387. case BuiltInSubgroupSize: // FIXME: Should work in any stage
  12388. if (msl_options.emulate_subgroups)
  12389. break;
  12390. /* fallthrough */
  12391. case BuiltInGlobalInvocationId:
  12392. case BuiltInWorkgroupId:
  12393. case BuiltInNumWorkgroups:
  12394. case BuiltInLocalInvocationId:
  12395. case BuiltInLocalInvocationIndex:
  12396. return string(" [[") + builtin_qualifier(builtin) + "]]";
  12397. default:
  12398. return "";
  12399. }
  12400. }
  12401. }
  12402. return "";
  12403. }
  12404. // A user-defined output variable is considered to match an input variable in the subsequent
  12405. // stage if the two variables are declared with the same Location and Component decoration and
  12406. // match in type and decoration, except that interpolation decorations are not required to match.
  12407. // For the purposes of interface matching, variables declared without a Component decoration are
  12408. // considered to have a Component decoration of zero.
  12409. string CompilerMSL::member_location_attribute_qualifier(const SPIRType &type, uint32_t index)
  12410. {
  12411. string quals;
  12412. uint32_t comp;
  12413. uint32_t locn = get_member_location(type.self, index, &comp);
  12414. if (locn != k_unknown_location)
  12415. {
  12416. quals += "user(locn";
  12417. quals += convert_to_string(locn);
  12418. if (comp != k_unknown_component && comp != 0)
  12419. {
  12420. quals += "_";
  12421. quals += convert_to_string(comp);
  12422. }
  12423. quals += ")";
  12424. }
  12425. return quals;
  12426. }
  12427. // Returns the location decoration of the member with the specified index in the specified type.
  12428. // If the location of the member has been explicitly set, that location is used. If not, this
  12429. // function assumes the members are ordered in their location order, and simply returns the
  12430. // index as the location.
  12431. uint32_t CompilerMSL::get_member_location(uint32_t type_id, uint32_t index, uint32_t *comp) const
  12432. {
  12433. if (comp)
  12434. {
  12435. if (has_member_decoration(type_id, index, DecorationComponent))
  12436. *comp = get_member_decoration(type_id, index, DecorationComponent);
  12437. else
  12438. *comp = k_unknown_component;
  12439. }
  12440. if (has_member_decoration(type_id, index, DecorationLocation))
  12441. return get_member_decoration(type_id, index, DecorationLocation);
  12442. else
  12443. return k_unknown_location;
  12444. }
  12445. uint32_t CompilerMSL::get_or_allocate_builtin_input_member_location(BuiltIn builtin,
  12446. uint32_t type_id, uint32_t index,
  12447. uint32_t *comp)
  12448. {
  12449. uint32_t loc = get_member_location(type_id, index, comp);
  12450. if (loc != k_unknown_location)
  12451. return loc;
  12452. if (comp)
  12453. *comp = k_unknown_component;
  12454. // Late allocation. Find a location which is unused by the application.
  12455. // This can happen for built-in inputs in tessellation which are mixed and matched with user inputs.
  12456. auto &mbr_type = get<SPIRType>(get<SPIRType>(type_id).member_types[index]);
  12457. uint32_t count = type_to_location_count(mbr_type);
  12458. loc = 0;
  12459. const auto location_range_in_use = [this](uint32_t location, uint32_t location_count) -> bool {
  12460. for (uint32_t i = 0; i < location_count; i++)
  12461. if (location_inputs_in_use.count(location + i) != 0)
  12462. return true;
  12463. return false;
  12464. };
  12465. while (location_range_in_use(loc, count))
  12466. loc++;
  12467. set_member_decoration(type_id, index, DecorationLocation, loc);
  12468. // Triangle tess level inputs are shared in one packed float4,
  12469. // mark both builtins as sharing one location.
  12470. if (!msl_options.raw_buffer_tese_input && is_tessellating_triangles() &&
  12471. (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter))
  12472. {
  12473. builtin_to_automatic_input_location[BuiltInTessLevelInner] = loc;
  12474. builtin_to_automatic_input_location[BuiltInTessLevelOuter] = loc;
  12475. }
  12476. else
  12477. builtin_to_automatic_input_location[builtin] = loc;
  12478. mark_location_as_used_by_shader(loc, mbr_type, StorageClassInput, true);
  12479. return loc;
  12480. }
  12481. uint32_t CompilerMSL::get_or_allocate_builtin_output_member_location(BuiltIn builtin,
  12482. uint32_t type_id, uint32_t index,
  12483. uint32_t *comp)
  12484. {
  12485. uint32_t loc = get_member_location(type_id, index, comp);
  12486. if (loc != k_unknown_location)
  12487. return loc;
  12488. loc = 0;
  12489. if (comp)
  12490. *comp = k_unknown_component;
  12491. // Late allocation. Find a location which is unused by the application.
  12492. // This can happen for built-in outputs in tessellation which are mixed and matched with user inputs.
  12493. auto &mbr_type = get<SPIRType>(get<SPIRType>(type_id).member_types[index]);
  12494. uint32_t count = type_to_location_count(mbr_type);
  12495. const auto location_range_in_use = [this](uint32_t location, uint32_t location_count) -> bool {
  12496. for (uint32_t i = 0; i < location_count; i++)
  12497. if (location_outputs_in_use.count(location + i) != 0)
  12498. return true;
  12499. return false;
  12500. };
  12501. while (location_range_in_use(loc, count))
  12502. loc++;
  12503. set_member_decoration(type_id, index, DecorationLocation, loc);
  12504. // Triangle tess level inputs are shared in one packed float4;
  12505. // mark both builtins as sharing one location.
  12506. if (is_tessellating_triangles() && (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter))
  12507. {
  12508. builtin_to_automatic_output_location[BuiltInTessLevelInner] = loc;
  12509. builtin_to_automatic_output_location[BuiltInTessLevelOuter] = loc;
  12510. }
  12511. else
  12512. builtin_to_automatic_output_location[builtin] = loc;
  12513. mark_location_as_used_by_shader(loc, mbr_type, StorageClassOutput, true);
  12514. return loc;
  12515. }
  12516. bool CompilerMSL::entry_point_is_vertex() const
  12517. {
  12518. // MSL vertex entrypoint is used for non-tessellation vertex stage or tessellation evaluation stage.
  12519. return (get_execution_model() == ExecutionModelVertex && !msl_options.vertex_for_tessellation) ||
  12520. get_execution_model() == ExecutionModelTessellationEvaluation;
  12521. }
  12522. bool CompilerMSL::entry_point_returns_stage_output() const
  12523. {
  12524. if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation)
  12525. return false;
  12526. bool ep_should_return_output = !get_is_rasterization_disabled();
  12527. return stage_out_var_id && ep_should_return_output;
  12528. }
  12529. bool CompilerMSL::entry_point_requires_const_device_buffers() const
  12530. {
  12531. return !has_descriptor_side_effects_buffer && !capture_output_to_buffer;
  12532. }
  12533. // Returns the type declaration for a function, including the
  12534. // entry type if the current function is the entry point function
  12535. string CompilerMSL::func_type_decl(SPIRType &type)
  12536. {
  12537. // The regular function return type. If not processing the entry point function, that's all we need
  12538. string return_type = type_to_glsl(type) + type_to_array_glsl(type, 0);
  12539. if (!processing_entry_point)
  12540. return return_type;
  12541. // If an outgoing interface block has been defined, and it should be returned, override the entry point return type
  12542. if (entry_point_returns_stage_output())
  12543. return_type = type_to_glsl(get_stage_out_struct_type()) + type_to_array_glsl(type, 0);
  12544. // Prepend a entry type, based on the execution model
  12545. string entry_type;
  12546. auto &execution = get_entry_point();
  12547. switch (execution.model)
  12548. {
  12549. case ExecutionModelVertex:
  12550. if (msl_options.vertex_for_tessellation && !msl_options.supports_msl_version(1, 2))
  12551. SPIRV_CROSS_THROW("Tessellation requires Metal 1.2.");
  12552. entry_type = msl_options.vertex_for_tessellation ? "kernel" : "vertex";
  12553. break;
  12554. case ExecutionModelTessellationEvaluation:
  12555. if (!msl_options.supports_msl_version(1, 2))
  12556. SPIRV_CROSS_THROW("Tessellation requires Metal 1.2.");
  12557. if (execution.flags.get(ExecutionModeIsolines))
  12558. SPIRV_CROSS_THROW("Metal does not support isoline tessellation.");
  12559. if (msl_options.is_ios())
  12560. entry_type = join("[[ patch(", is_tessellating_triangles() ? "triangle" : "quad", ") ]] vertex");
  12561. else
  12562. entry_type = join("[[ patch(", is_tessellating_triangles() ? "triangle" : "quad", ", ",
  12563. execution.output_vertices, ") ]] vertex");
  12564. break;
  12565. case ExecutionModelFragment:
  12566. entry_type = uses_explicit_early_fragment_test() ? "[[ early_fragment_tests ]] fragment" : "fragment";
  12567. break;
  12568. case ExecutionModelTessellationControl:
  12569. if (!msl_options.supports_msl_version(1, 2))
  12570. SPIRV_CROSS_THROW("Tessellation requires Metal 1.2.");
  12571. if (execution.flags.get(ExecutionModeIsolines))
  12572. SPIRV_CROSS_THROW("Metal does not support isoline tessellation.");
  12573. /* fallthrough */
  12574. case ExecutionModelGLCompute:
  12575. case ExecutionModelKernel:
  12576. entry_type = "kernel";
  12577. break;
  12578. case ExecutionModelMeshEXT:
  12579. entry_type = "[[mesh]]";
  12580. break;
  12581. case ExecutionModelTaskEXT:
  12582. entry_type = "[[object]]";
  12583. break;
  12584. default:
  12585. entry_type = "unknown";
  12586. break;
  12587. }
  12588. return entry_type + " " + return_type;
  12589. }
  12590. bool CompilerMSL::is_tesc_shader() const
  12591. {
  12592. return get_execution_model() == ExecutionModelTessellationControl;
  12593. }
  12594. bool CompilerMSL::is_tese_shader() const
  12595. {
  12596. return get_execution_model() == ExecutionModelTessellationEvaluation;
  12597. }
  12598. bool CompilerMSL::is_mesh_shader() const
  12599. {
  12600. return get_execution_model() == ExecutionModelMeshEXT;
  12601. }
  12602. bool CompilerMSL::uses_explicit_early_fragment_test()
  12603. {
  12604. auto &ep_flags = get_entry_point().flags;
  12605. return ep_flags.get(ExecutionModeEarlyFragmentTests) || ep_flags.get(ExecutionModePostDepthCoverage);
  12606. }
  12607. // In MSL, address space qualifiers are required for all pointer or reference variables
  12608. string CompilerMSL::get_variable_address_space(const SPIRVariable &argument)
  12609. {
  12610. const auto &type = get<SPIRType>(argument.basetype);
  12611. return get_type_address_space(type, argument.self, true);
  12612. }
  12613. string CompilerMSL::get_leaf_argument_address_space(const SPIRVariable &argument)
  12614. {
  12615. const auto &type = get<SPIRType>(argument.basetype);
  12616. // BDA and variable buffer pointer is always passed around by (pointer) value. There is no storage class for the argument itself.
  12617. if (is_physical_or_buffer_pointer(type))
  12618. return "";
  12619. return get_type_address_space(type, argument.self, true);
  12620. }
  12621. bool CompilerMSL::decoration_flags_signal_volatile(const Bitset &flags) const
  12622. {
  12623. // Using volatile for coherent pre-3.2 is definitely not correct, but it's something.
  12624. // MSL 3.2 adds actual coherent qualifiers.
  12625. return flags.get(DecorationVolatile) ||
  12626. (flags.get(DecorationCoherent) && !msl_options.supports_msl_version(3, 2));
  12627. }
  12628. bool CompilerMSL::decoration_flags_signal_coherent(const Bitset &flags) const
  12629. {
  12630. return flags.get(DecorationCoherent) && msl_options.supports_msl_version(3, 2);
  12631. }
  12632. string CompilerMSL::get_type_address_space(const SPIRType &type, uint32_t id, bool argument)
  12633. {
  12634. // This can be called for variable pointer contexts as well, so be very careful about which method we choose.
  12635. Bitset flags;
  12636. auto *var = maybe_get<SPIRVariable>(id);
  12637. if (var && type.basetype == SPIRType::Struct &&
  12638. (has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock)))
  12639. flags = get_buffer_block_flags(id);
  12640. else
  12641. {
  12642. flags = get_decoration_bitset(id);
  12643. if (type.basetype == SPIRType::Struct &&
  12644. (has_decoration(type.self, DecorationBlock) ||
  12645. has_decoration(type.self, DecorationBufferBlock)))
  12646. {
  12647. flags.merge_or(ir.get_buffer_block_type_flags(type));
  12648. }
  12649. }
  12650. const char *addr_space = nullptr;
  12651. switch (type.storage)
  12652. {
  12653. case StorageClassWorkgroup:
  12654. addr_space = "threadgroup";
  12655. break;
  12656. case StorageClassStorageBuffer:
  12657. case StorageClassPhysicalStorageBuffer:
  12658. {
  12659. // When dealing with descriptor aliasing, it becomes very problematic to make use of
  12660. // readonly qualifiers.
  12661. // If rasterization is not disabled in vertex/tese, Metal does not allow side effects and refuses to compile "device",
  12662. // even if there are no writes. Just force const device.
  12663. if (entry_point_requires_const_device_buffers() && type.basetype != SPIRType::AtomicCounter)
  12664. addr_space = "const device";
  12665. else
  12666. addr_space = "device";
  12667. break;
  12668. }
  12669. case StorageClassUniform:
  12670. case StorageClassUniformConstant:
  12671. case StorageClassPushConstant:
  12672. if (type.basetype == SPIRType::Struct)
  12673. {
  12674. bool ssbo = has_decoration(type.self, DecorationBufferBlock);
  12675. if (ssbo)
  12676. {
  12677. if (entry_point_requires_const_device_buffers() && type.basetype != SPIRType::AtomicCounter)
  12678. addr_space = "const device";
  12679. else
  12680. addr_space = "device";
  12681. }
  12682. else
  12683. addr_space = "constant";
  12684. }
  12685. else if (!argument)
  12686. {
  12687. // This is used for helper UBOs we insert ourselves.
  12688. addr_space = "constant";
  12689. }
  12690. else if (type_is_msl_framebuffer_fetch(type))
  12691. {
  12692. // Subpass inputs are passed around by value.
  12693. addr_space = "";
  12694. }
  12695. break;
  12696. case StorageClassFunction:
  12697. case StorageClassGeneric:
  12698. break;
  12699. case StorageClassInput:
  12700. if (is_tesc_shader() && var && var->basevariable == stage_in_ptr_var_id)
  12701. addr_space = msl_options.multi_patch_workgroup ? "const device" : "threadgroup";
  12702. // Don't pass tessellation levels in the device AS; we load and convert them
  12703. // to float manually.
  12704. if (is_tese_shader() && msl_options.raw_buffer_tese_input && var)
  12705. {
  12706. bool is_stage_in = var->basevariable == stage_in_ptr_var_id;
  12707. bool is_patch_stage_in = has_decoration(var->self, DecorationPatch);
  12708. bool is_builtin = has_decoration(var->self, DecorationBuiltIn);
  12709. BuiltIn builtin = (BuiltIn)get_decoration(var->self, DecorationBuiltIn);
  12710. bool is_tess_level = is_builtin && (builtin == BuiltInTessLevelOuter || builtin == BuiltInTessLevelInner);
  12711. if (is_stage_in || (is_patch_stage_in && !is_tess_level))
  12712. addr_space = "const device";
  12713. }
  12714. if (get_execution_model() == ExecutionModelFragment && var && var->basevariable == stage_in_var_id)
  12715. addr_space = "thread";
  12716. break;
  12717. case StorageClassOutput:
  12718. if (capture_output_to_buffer)
  12719. {
  12720. if (var && type.storage == StorageClassOutput)
  12721. {
  12722. bool is_masked = is_stage_output_variable_masked(*var);
  12723. if (is_masked)
  12724. {
  12725. if (is_tessellation_shader())
  12726. addr_space = "threadgroup";
  12727. else
  12728. addr_space = "thread";
  12729. }
  12730. else if (variable_decl_is_remapped_storage(*var, StorageClassWorkgroup))
  12731. addr_space = "threadgroup";
  12732. }
  12733. // BlockIO is passed as thread and lowered on return from main.
  12734. if (get_execution_model() == ExecutionModelVertex && has_decoration(type.self, DecorationBlock))
  12735. addr_space = "thread";
  12736. if (!addr_space)
  12737. addr_space = "device";
  12738. }
  12739. if (is_mesh_shader())
  12740. addr_space = "threadgroup";
  12741. break;
  12742. case StorageClassTaskPayloadWorkgroupEXT:
  12743. if (is_mesh_shader())
  12744. addr_space = "const object_data";
  12745. else
  12746. addr_space = "object_data";
  12747. break;
  12748. default:
  12749. break;
  12750. }
  12751. if (!addr_space && var && is_var_runtime_size_array(*var))
  12752. addr_space = "device";
  12753. if (!addr_space)
  12754. {
  12755. // No address space for plain values.
  12756. addr_space = type.pointer || (argument && type.basetype == SPIRType::ControlPointArray) ? "thread" : "";
  12757. }
  12758. if (decoration_flags_signal_coherent(flags) && strcmp(addr_space, "device") == 0)
  12759. return join("coherent device");
  12760. else if (decoration_flags_signal_volatile(flags) && strcmp(addr_space, "thread") != 0)
  12761. return join("volatile ", addr_space);
  12762. else
  12763. return addr_space;
  12764. }
  12765. const char *CompilerMSL::to_restrict(uint32_t id, bool space)
  12766. {
  12767. // This can be called for variable pointer contexts as well, so be very careful about which method we choose.
  12768. Bitset flags;
  12769. if (ir.ids[id].get_type() == TypeVariable)
  12770. {
  12771. uint32_t type_id = expression_type_id(id);
  12772. auto &type = expression_type(id);
  12773. if (type.basetype == SPIRType::Struct &&
  12774. (has_decoration(type_id, DecorationBlock) || has_decoration(type_id, DecorationBufferBlock)))
  12775. flags = get_buffer_block_flags(id);
  12776. else
  12777. flags = get_decoration_bitset(id);
  12778. }
  12779. else
  12780. flags = get_decoration_bitset(id);
  12781. return flags.get(DecorationRestrict) || flags.get(DecorationRestrictPointerEXT) ?
  12782. (space ? "__restrict " : "__restrict") : "";
  12783. }
  12784. string CompilerMSL::entry_point_arg_stage_in()
  12785. {
  12786. string decl;
  12787. if ((is_tesc_shader() && msl_options.multi_patch_workgroup) ||
  12788. (is_tese_shader() && msl_options.raw_buffer_tese_input))
  12789. return decl;
  12790. // Stage-in structure
  12791. uint32_t stage_in_id;
  12792. if (is_tese_shader())
  12793. stage_in_id = patch_stage_in_var_id;
  12794. else
  12795. stage_in_id = stage_in_var_id;
  12796. if (stage_in_id)
  12797. {
  12798. auto &var = get<SPIRVariable>(stage_in_id);
  12799. auto &type = get_variable_data_type(var);
  12800. add_resource_name(var.self);
  12801. decl = join(type_to_glsl(type), " ", to_name(var.self), " [[stage_in]]");
  12802. }
  12803. return decl;
  12804. }
  12805. // Returns true if this input builtin should be a direct parameter on a shader function parameter list,
  12806. // and false for builtins that should be passed or calculated some other way.
  12807. bool CompilerMSL::is_direct_input_builtin(BuiltIn bi_type)
  12808. {
  12809. switch (bi_type)
  12810. {
  12811. // Vertex function in
  12812. case BuiltInVertexId:
  12813. case BuiltInVertexIndex:
  12814. case BuiltInBaseVertex:
  12815. case BuiltInInstanceId:
  12816. case BuiltInInstanceIndex:
  12817. case BuiltInBaseInstance:
  12818. return get_execution_model() != ExecutionModelVertex || !msl_options.vertex_for_tessellation;
  12819. // Tess. control function in
  12820. case BuiltInPosition:
  12821. case BuiltInPointSize:
  12822. case BuiltInClipDistance:
  12823. case BuiltInCullDistance:
  12824. case BuiltInPatchVertices:
  12825. return false;
  12826. case BuiltInInvocationId:
  12827. case BuiltInPrimitiveId:
  12828. return !is_tesc_shader() || !msl_options.multi_patch_workgroup;
  12829. // Tess. evaluation function in
  12830. case BuiltInTessLevelInner:
  12831. case BuiltInTessLevelOuter:
  12832. return false;
  12833. // Fragment function in
  12834. case BuiltInSamplePosition:
  12835. case BuiltInHelperInvocation:
  12836. case BuiltInBaryCoordKHR:
  12837. case BuiltInBaryCoordNoPerspKHR:
  12838. return false;
  12839. case BuiltInViewIndex:
  12840. return get_execution_model() == ExecutionModelFragment && msl_options.multiview &&
  12841. msl_options.multiview_layered_rendering;
  12842. // Compute function in
  12843. case BuiltInSubgroupId:
  12844. case BuiltInNumSubgroups:
  12845. return !msl_options.emulate_subgroups;
  12846. // Any stage function in
  12847. case BuiltInDeviceIndex:
  12848. case BuiltInSubgroupEqMask:
  12849. case BuiltInSubgroupGeMask:
  12850. case BuiltInSubgroupGtMask:
  12851. case BuiltInSubgroupLeMask:
  12852. case BuiltInSubgroupLtMask:
  12853. return false;
  12854. case BuiltInSubgroupSize:
  12855. if (msl_options.fixed_subgroup_size != 0)
  12856. return false;
  12857. /* fallthrough */
  12858. case BuiltInSubgroupLocalInvocationId:
  12859. return !msl_options.emulate_subgroups;
  12860. default:
  12861. return true;
  12862. }
  12863. }
  12864. // Returns true if this is a fragment shader that runs per sample, and false otherwise.
  12865. bool CompilerMSL::is_sample_rate() const
  12866. {
  12867. auto &caps = get_declared_capabilities();
  12868. return get_execution_model() == ExecutionModelFragment &&
  12869. (msl_options.force_sample_rate_shading ||
  12870. std::find(caps.begin(), caps.end(), CapabilitySampleRateShading) != caps.end() ||
  12871. (msl_options.use_framebuffer_fetch_subpasses && need_subpass_input_ms));
  12872. }
  12873. bool CompilerMSL::is_intersection_query() const
  12874. {
  12875. auto &caps = get_declared_capabilities();
  12876. return std::find(caps.begin(), caps.end(), CapabilityRayQueryKHR) != caps.end();
  12877. }
  12878. void CompilerMSL::entry_point_args_builtin(string &ep_args)
  12879. {
  12880. // Builtin variables
  12881. SmallVector<pair<SPIRVariable *, BuiltIn>, 8> active_builtins;
  12882. ir.for_each_typed_id<SPIRVariable>([&](uint32_t var_id, SPIRVariable &var) {
  12883. if (var.storage != StorageClassInput)
  12884. return;
  12885. auto bi_type = BuiltIn(get_decoration(var_id, DecorationBuiltIn));
  12886. // Don't emit SamplePosition as a separate parameter. In the entry
  12887. // point, we get that by calling get_sample_position() on the sample ID.
  12888. if (is_builtin_variable(var) &&
  12889. get_variable_data_type(var).basetype != SPIRType::Struct &&
  12890. get_variable_data_type(var).basetype != SPIRType::ControlPointArray)
  12891. {
  12892. // If the builtin is not part of the active input builtin set, don't emit it.
  12893. // Relevant for multiple entry-point modules which might declare unused builtins.
  12894. if (!active_input_builtins.get(bi_type) || !interface_variable_exists_in_entry_point(var_id))
  12895. return;
  12896. // Remember this variable. We may need to correct its type.
  12897. active_builtins.push_back(make_pair(&var, bi_type));
  12898. if (is_direct_input_builtin(bi_type))
  12899. {
  12900. if (!ep_args.empty())
  12901. ep_args += ", ";
  12902. // Handle HLSL-style 0-based vertex/instance index.
  12903. builtin_declaration = true;
  12904. // Handle different MSL gl_TessCoord types. (float2, float3)
  12905. if (bi_type == BuiltInTessCoord && get_entry_point().flags.get(ExecutionModeQuads))
  12906. ep_args += "float2 " + to_expression(var_id) + "In";
  12907. else
  12908. ep_args += builtin_type_decl(bi_type, var_id) + " " + to_expression(var_id);
  12909. ep_args += string(" [[") + builtin_qualifier(bi_type);
  12910. if (bi_type == BuiltInSampleMask && get_entry_point().flags.get(ExecutionModePostDepthCoverage))
  12911. {
  12912. if (!msl_options.supports_msl_version(2))
  12913. SPIRV_CROSS_THROW("Post-depth coverage requires MSL 2.0.");
  12914. if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 3))
  12915. SPIRV_CROSS_THROW("Post-depth coverage on Mac requires MSL 2.3.");
  12916. ep_args += ", post_depth_coverage";
  12917. }
  12918. ep_args += "]]";
  12919. builtin_declaration = false;
  12920. }
  12921. }
  12922. if (has_extended_decoration(var_id, SPIRVCrossDecorationBuiltInDispatchBase))
  12923. {
  12924. // This is a special implicit builtin, not corresponding to any SPIR-V builtin,
  12925. // which holds the base that was passed to vkCmdDispatchBase() or vkCmdDrawIndexed(). If it's present,
  12926. // assume we emitted it for a good reason.
  12927. assert(msl_options.supports_msl_version(1, 2));
  12928. if (!ep_args.empty())
  12929. ep_args += ", ";
  12930. ep_args += type_to_glsl(get_variable_data_type(var)) + " " + to_expression(var_id) + " [[grid_origin]]";
  12931. }
  12932. if (has_extended_decoration(var_id, SPIRVCrossDecorationBuiltInStageInputSize))
  12933. {
  12934. // This is another special implicit builtin, not corresponding to any SPIR-V builtin,
  12935. // which holds the number of vertices and instances to draw. If it's present,
  12936. // assume we emitted it for a good reason.
  12937. assert(msl_options.supports_msl_version(1, 2));
  12938. if (!ep_args.empty())
  12939. ep_args += ", ";
  12940. ep_args += type_to_glsl(get_variable_data_type(var)) + " " + to_expression(var_id) + " [[grid_size]]";
  12941. }
  12942. });
  12943. // Correct the types of all encountered active builtins. We couldn't do this before
  12944. // because ensure_correct_builtin_type() may increase the bound, which isn't allowed
  12945. // while iterating over IDs.
  12946. for (auto &var : active_builtins)
  12947. var.first->basetype = ensure_correct_builtin_type(var.first->basetype, var.second);
  12948. // Handle HLSL-style 0-based vertex/instance index.
  12949. if (needs_base_vertex_arg == TriState::Yes)
  12950. ep_args += built_in_func_arg(BuiltInBaseVertex, !ep_args.empty());
  12951. if (needs_base_instance_arg == TriState::Yes)
  12952. ep_args += built_in_func_arg(BuiltInBaseInstance, !ep_args.empty());
  12953. if (capture_output_to_buffer)
  12954. {
  12955. // Add parameters to hold the indirect draw parameters and the shader output. This has to be handled
  12956. // specially because it needs to be a pointer, not a reference.
  12957. if (stage_out_var_id)
  12958. {
  12959. if (!ep_args.empty())
  12960. ep_args += ", ";
  12961. ep_args += join("device ", type_to_glsl(get_stage_out_struct_type()), "* ", output_buffer_var_name,
  12962. " [[buffer(", msl_options.shader_output_buffer_index, ")]]");
  12963. }
  12964. if (is_tesc_shader())
  12965. {
  12966. if (!ep_args.empty())
  12967. ep_args += ", ";
  12968. ep_args +=
  12969. join("constant uint* spvIndirectParams [[buffer(", msl_options.indirect_params_buffer_index, ")]]");
  12970. }
  12971. else if (stage_out_var_id &&
  12972. !(get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation))
  12973. {
  12974. if (!ep_args.empty())
  12975. ep_args += ", ";
  12976. ep_args +=
  12977. join("device uint* spvIndirectParams [[buffer(", msl_options.indirect_params_buffer_index, ")]]");
  12978. }
  12979. if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation &&
  12980. (active_input_builtins.get(BuiltInVertexIndex) || active_input_builtins.get(BuiltInVertexId)) &&
  12981. msl_options.vertex_index_type != Options::IndexType::None)
  12982. {
  12983. // Add the index buffer so we can set gl_VertexIndex correctly.
  12984. if (!ep_args.empty())
  12985. ep_args += ", ";
  12986. switch (msl_options.vertex_index_type)
  12987. {
  12988. case Options::IndexType::None:
  12989. break;
  12990. case Options::IndexType::UInt16:
  12991. ep_args += join("const device ushort* ", index_buffer_var_name, " [[buffer(",
  12992. msl_options.shader_index_buffer_index, ")]]");
  12993. break;
  12994. case Options::IndexType::UInt32:
  12995. ep_args += join("const device uint* ", index_buffer_var_name, " [[buffer(",
  12996. msl_options.shader_index_buffer_index, ")]]");
  12997. break;
  12998. }
  12999. }
  13000. // Tessellation control shaders get three additional parameters:
  13001. // a buffer to hold the per-patch data, a buffer to hold the per-patch
  13002. // tessellation levels, and a block of workgroup memory to hold the
  13003. // input control point data.
  13004. if (is_tesc_shader())
  13005. {
  13006. if (patch_stage_out_var_id)
  13007. {
  13008. if (!ep_args.empty())
  13009. ep_args += ", ";
  13010. ep_args +=
  13011. join("device ", type_to_glsl(get_patch_stage_out_struct_type()), "* ", patch_output_buffer_var_name,
  13012. " [[buffer(", convert_to_string(msl_options.shader_patch_output_buffer_index), ")]]");
  13013. }
  13014. if (!ep_args.empty())
  13015. ep_args += ", ";
  13016. ep_args += join("device ", get_tess_factor_struct_name(), "* ", tess_factor_buffer_var_name, " [[buffer(",
  13017. convert_to_string(msl_options.shader_tess_factor_buffer_index), ")]]");
  13018. // Initializer for tess factors must be handled specially since it's never declared as a normal variable.
  13019. uint32_t outer_factor_initializer_id = 0;
  13020. uint32_t inner_factor_initializer_id = 0;
  13021. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
  13022. if (!has_decoration(var.self, DecorationBuiltIn) || var.storage != StorageClassOutput || !var.initializer)
  13023. return;
  13024. BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
  13025. if (builtin == BuiltInTessLevelInner)
  13026. inner_factor_initializer_id = var.initializer;
  13027. else if (builtin == BuiltInTessLevelOuter)
  13028. outer_factor_initializer_id = var.initializer;
  13029. });
  13030. const SPIRConstant *c = nullptr;
  13031. if (outer_factor_initializer_id && (c = maybe_get<SPIRConstant>(outer_factor_initializer_id)))
  13032. {
  13033. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  13034. entry_func.fixup_hooks_in.push_back(
  13035. [=]()
  13036. {
  13037. uint32_t components = is_tessellating_triangles() ? 3 : 4;
  13038. for (uint32_t i = 0; i < components; i++)
  13039. {
  13040. statement(builtin_to_glsl(BuiltInTessLevelOuter, StorageClassOutput), "[", i,
  13041. "] = ", "half(", to_expression(c->subconstants[i]), ");");
  13042. }
  13043. });
  13044. }
  13045. if (inner_factor_initializer_id && (c = maybe_get<SPIRConstant>(inner_factor_initializer_id)))
  13046. {
  13047. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  13048. if (is_tessellating_triangles())
  13049. {
  13050. entry_func.fixup_hooks_in.push_back([=]() {
  13051. statement(builtin_to_glsl(BuiltInTessLevelInner, StorageClassOutput), " = ", "half(",
  13052. to_expression(c->subconstants[0]), ");");
  13053. });
  13054. }
  13055. else
  13056. {
  13057. entry_func.fixup_hooks_in.push_back([=]() {
  13058. for (uint32_t i = 0; i < 2; i++)
  13059. {
  13060. statement(builtin_to_glsl(BuiltInTessLevelInner, StorageClassOutput), "[", i, "] = ",
  13061. "half(", to_expression(c->subconstants[i]), ");");
  13062. }
  13063. });
  13064. }
  13065. }
  13066. if (stage_in_var_id)
  13067. {
  13068. if (!ep_args.empty())
  13069. ep_args += ", ";
  13070. if (msl_options.multi_patch_workgroup)
  13071. {
  13072. ep_args += join("device ", type_to_glsl(get_stage_in_struct_type()), "* ", input_buffer_var_name,
  13073. " [[buffer(", convert_to_string(msl_options.shader_input_buffer_index), ")]]");
  13074. }
  13075. else
  13076. {
  13077. ep_args += join("threadgroup ", type_to_glsl(get_stage_in_struct_type()), "* ", input_wg_var_name,
  13078. " [[threadgroup(", convert_to_string(msl_options.shader_input_wg_index), ")]]");
  13079. }
  13080. }
  13081. }
  13082. }
  13083. // Tessellation evaluation shaders get three additional parameters:
  13084. // a buffer for the per-patch data, a buffer for the per-patch
  13085. // tessellation levels, and a buffer for the control point data.
  13086. if (is_tese_shader() && msl_options.raw_buffer_tese_input)
  13087. {
  13088. if (patch_stage_in_var_id)
  13089. {
  13090. if (!ep_args.empty())
  13091. ep_args += ", ";
  13092. ep_args +=
  13093. join("const device ", type_to_glsl(get_patch_stage_in_struct_type()), "* ", patch_input_buffer_var_name,
  13094. " [[buffer(", convert_to_string(msl_options.shader_patch_input_buffer_index), ")]]");
  13095. }
  13096. if (tess_level_inner_var_id || tess_level_outer_var_id)
  13097. {
  13098. if (!ep_args.empty())
  13099. ep_args += ", ";
  13100. ep_args += join("const device ", get_tess_factor_struct_name(), "* ", tess_factor_buffer_var_name,
  13101. " [[buffer(", convert_to_string(msl_options.shader_tess_factor_buffer_index), ")]]");
  13102. }
  13103. if (stage_in_var_id)
  13104. {
  13105. if (!ep_args.empty())
  13106. ep_args += ", ";
  13107. ep_args += join("const device ", type_to_glsl(get_stage_in_struct_type()), "* ", input_buffer_var_name,
  13108. " [[buffer(", convert_to_string(msl_options.shader_input_buffer_index), ")]]");
  13109. }
  13110. }
  13111. if (is_mesh_shader())
  13112. {
  13113. if (!ep_args.empty())
  13114. ep_args += ", ";
  13115. ep_args += join("spvMesh_t spvMesh");
  13116. }
  13117. if (get_execution_model() == ExecutionModelTaskEXT)
  13118. {
  13119. if (!ep_args.empty())
  13120. ep_args += ", ";
  13121. ep_args += join("mesh_grid_properties spvMgp");
  13122. }
  13123. }
  13124. string CompilerMSL::entry_point_args_argument_buffer(bool append_comma)
  13125. {
  13126. string ep_args = entry_point_arg_stage_in();
  13127. Bitset claimed_bindings;
  13128. for (uint32_t i = 0; i < kMaxArgumentBuffers; i++)
  13129. {
  13130. uint32_t id = argument_buffer_ids[i];
  13131. if (id == 0)
  13132. continue;
  13133. add_resource_name(id);
  13134. auto &var = get<SPIRVariable>(id);
  13135. auto &type = get_variable_data_type(var);
  13136. if (!ep_args.empty())
  13137. ep_args += ", ";
  13138. // Check if the argument buffer binding itself has been remapped.
  13139. uint32_t buffer_binding;
  13140. auto itr = resource_bindings.find({ get_entry_point().model, i, kArgumentBufferBinding });
  13141. if (itr != end(resource_bindings))
  13142. {
  13143. buffer_binding = itr->second.first.msl_buffer;
  13144. itr->second.second = true;
  13145. }
  13146. else
  13147. {
  13148. // As a fallback, directly map desc set <-> binding.
  13149. // If that was taken, take the next buffer binding.
  13150. if (claimed_bindings.get(i))
  13151. buffer_binding = next_metal_resource_index_buffer;
  13152. else
  13153. buffer_binding = i;
  13154. }
  13155. claimed_bindings.set(buffer_binding);
  13156. ep_args += get_variable_address_space(var) + " ";
  13157. if (recursive_inputs.count(type.self))
  13158. ep_args += string("void* ") + to_restrict(id, true) + to_name(id) + "_vp";
  13159. else
  13160. ep_args += type_to_glsl(type) + "& " + to_restrict(id, true) + to_name(id);
  13161. ep_args += " [[buffer(" + convert_to_string(buffer_binding) + ")]]";
  13162. next_metal_resource_index_buffer = max(next_metal_resource_index_buffer, buffer_binding + 1);
  13163. }
  13164. entry_point_args_discrete_descriptors(ep_args);
  13165. entry_point_args_builtin(ep_args);
  13166. if (!ep_args.empty() && append_comma)
  13167. ep_args += ", ";
  13168. return ep_args;
  13169. }
  13170. const MSLConstexprSampler *CompilerMSL::find_constexpr_sampler(uint32_t id) const
  13171. {
  13172. // Try by ID.
  13173. {
  13174. auto itr = constexpr_samplers_by_id.find(id);
  13175. if (itr != end(constexpr_samplers_by_id))
  13176. return &itr->second;
  13177. }
  13178. // Try by binding.
  13179. {
  13180. uint32_t desc_set = get_decoration(id, DecorationDescriptorSet);
  13181. uint32_t binding = get_decoration(id, DecorationBinding);
  13182. auto itr = constexpr_samplers_by_binding.find({ desc_set, binding });
  13183. if (itr != end(constexpr_samplers_by_binding))
  13184. return &itr->second;
  13185. }
  13186. return nullptr;
  13187. }
  13188. void CompilerMSL::entry_point_args_discrete_descriptors(string &ep_args)
  13189. {
  13190. // Output resources, sorted by resource index & type
  13191. // We need to sort to work around a bug on macOS 10.13 with NVidia drivers where switching between shaders
  13192. // with different order of buffers can result in issues with buffer assignments inside the driver.
  13193. struct Resource
  13194. {
  13195. SPIRVariable *var;
  13196. SPIRVariable *discrete_descriptor_alias;
  13197. string name;
  13198. SPIRType::BaseType basetype;
  13199. uint32_t index;
  13200. uint32_t plane;
  13201. uint32_t secondary_index;
  13202. };
  13203. SmallVector<Resource> resources;
  13204. entry_point_bindings.clear();
  13205. ir.for_each_typed_id<SPIRVariable>([&](uint32_t var_id, SPIRVariable &var) {
  13206. if ((var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant ||
  13207. var.storage == StorageClassPushConstant || var.storage == StorageClassStorageBuffer) &&
  13208. !is_hidden_variable(var))
  13209. {
  13210. auto &type = get_variable_data_type(var);
  13211. uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
  13212. if (is_supported_argument_buffer_type(type) && var.storage != StorageClassPushConstant)
  13213. {
  13214. if (descriptor_set_is_argument_buffer(desc_set))
  13215. {
  13216. if (is_var_runtime_size_array(var))
  13217. {
  13218. // Runtime arrays need to be wrapped in spvDescriptorArray from argument buffer payload.
  13219. entry_point_bindings.push_back(&var);
  13220. // We'll wrap this, so to_name() will always use non-qualified name.
  13221. // We'll need the qualified name to create temporary variable instead.
  13222. ir.meta[var_id].decoration.qualified_alias_explicit_override = true;
  13223. }
  13224. return;
  13225. }
  13226. }
  13227. // Handle descriptor aliasing of simple discrete cases.
  13228. // We can handle aliasing of buffers by casting pointers.
  13229. // The amount of aliasing we can perform for discrete descriptors is very limited.
  13230. // For fully mutable-style aliasing, we need argument buffers where we can exploit the fact
  13231. // that descriptors are all 8 bytes.
  13232. SPIRVariable *discrete_descriptor_alias = nullptr;
  13233. const auto resource_is_aliasing_candidate = [this](const SPIRVariable &var_) {
  13234. return is_var_runtime_size_array(var_) || var_.storage == StorageClassUniform ||
  13235. var_.storage == StorageClassStorageBuffer;
  13236. };
  13237. if (resource_is_aliasing_candidate(var))
  13238. {
  13239. for (auto &resource : resources)
  13240. {
  13241. if (resource_is_aliasing_candidate(*resource.var) &&
  13242. get_decoration(resource.var->self, DecorationDescriptorSet) ==
  13243. get_decoration(var_id, DecorationDescriptorSet) &&
  13244. get_decoration(resource.var->self, DecorationBinding) ==
  13245. get_decoration(var_id, DecorationBinding))
  13246. {
  13247. discrete_descriptor_alias = resource.var;
  13248. // Self-reference marks that we should declare the resource,
  13249. // and it's being used as an alias (so we can emit void* instead).
  13250. resource.discrete_descriptor_alias = resource.var;
  13251. // Need to promote interlocked usage so that the primary declaration is correct.
  13252. if (interlocked_resources.count(var_id))
  13253. interlocked_resources.insert(resource.var->self);
  13254. // Aliasing with unroll just gets too messy to deal with. I sure hope this never comes up ...
  13255. if ((is_array(get_variable_data_type(*resource.var)) && !is_var_runtime_size_array(*resource.var)) ||
  13256. (is_array(get_variable_data_type(var)) && !is_var_runtime_size_array(var)))
  13257. {
  13258. SPIRV_CROSS_THROW("Attempting to alias same binding with a descriptor array which is not implemented through argument buffers. This is unsupported.");
  13259. }
  13260. break;
  13261. }
  13262. }
  13263. }
  13264. const MSLConstexprSampler *constexpr_sampler = nullptr;
  13265. if (type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::Sampler)
  13266. {
  13267. constexpr_sampler = find_constexpr_sampler(var_id);
  13268. if (constexpr_sampler)
  13269. {
  13270. // Mark this ID as a constexpr sampler for later in case it came from set/bindings.
  13271. constexpr_samplers_by_id[var_id] = *constexpr_sampler;
  13272. }
  13273. }
  13274. // Emulate texture2D atomic operations
  13275. uint32_t secondary_index = 0;
  13276. if (atomic_image_vars_emulated.count(var.self))
  13277. {
  13278. secondary_index = get_metal_resource_index(var, SPIRType::AtomicCounter, 0);
  13279. }
  13280. if (type.basetype == SPIRType::SampledImage)
  13281. {
  13282. add_resource_name(var_id);
  13283. uint32_t plane_count = 1;
  13284. if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
  13285. plane_count = constexpr_sampler->planes;
  13286. entry_point_bindings.push_back(&var);
  13287. for (uint32_t i = 0; i < plane_count; i++)
  13288. resources.push_back({&var, discrete_descriptor_alias, to_name(var_id), SPIRType::Image,
  13289. get_metal_resource_index(var, SPIRType::Image, i), i, secondary_index });
  13290. if (type.image.dim != DimBuffer && !constexpr_sampler)
  13291. {
  13292. resources.push_back({&var, discrete_descriptor_alias, to_sampler_expression(var_id), SPIRType::Sampler,
  13293. get_metal_resource_index(var, SPIRType::Sampler), 0, 0 });
  13294. }
  13295. }
  13296. else if (!constexpr_sampler)
  13297. {
  13298. // constexpr samplers are not declared as resources.
  13299. add_resource_name(var_id);
  13300. // Don't allocate resource indices for aliases.
  13301. uint32_t resource_index = ~0u;
  13302. if (!discrete_descriptor_alias)
  13303. resource_index = get_metal_resource_index(var, type.basetype);
  13304. entry_point_bindings.push_back(&var);
  13305. resources.push_back({&var, discrete_descriptor_alias, to_name(var_id), type.basetype,
  13306. resource_index, 0, secondary_index });
  13307. }
  13308. }
  13309. });
  13310. stable_sort(resources.begin(), resources.end(),
  13311. [](const Resource &lhs, const Resource &rhs)
  13312. { return tie(lhs.basetype, lhs.index) < tie(rhs.basetype, rhs.index); });
  13313. for (auto &r : resources)
  13314. {
  13315. auto &var = *r.var;
  13316. auto &type = get_variable_data_type(var);
  13317. uint32_t var_id = var.self;
  13318. if (is_var_runtime_size_array(var))
  13319. {
  13320. add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray);
  13321. const bool ssbo = has_decoration(type.self, DecorationBufferBlock);
  13322. if ((var.storage == StorageClassStorageBuffer || ssbo) && msl_options.runtime_array_rich_descriptor)
  13323. add_spv_func_and_recompile(SPVFuncImplVariableSizedDescriptor);
  13324. else
  13325. add_spv_func_and_recompile(SPVFuncImplVariableDescriptor);
  13326. }
  13327. if (r.discrete_descriptor_alias)
  13328. {
  13329. if (r.var == r.discrete_descriptor_alias)
  13330. {
  13331. auto primary_name = join("spvBufferAliasSet",
  13332. get_decoration(var_id, DecorationDescriptorSet),
  13333. "Binding",
  13334. get_decoration(var_id, DecorationBinding));
  13335. // Declare the primary alias as void*
  13336. if (!ep_args.empty())
  13337. ep_args += ", ";
  13338. ep_args += get_variable_address_space(var) + " void* " + primary_name;
  13339. ep_args += " [[buffer(" + convert_to_string(r.index) + ")";
  13340. if (interlocked_resources.count(var_id))
  13341. ep_args += ", raster_order_group(0)";
  13342. ep_args += "]]";
  13343. }
  13344. buffer_aliases_discrete.push_back(r.var->self);
  13345. continue;
  13346. }
  13347. uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
  13348. uint32_t desc_binding = get_decoration(var_id, DecorationBinding);
  13349. if (is_var_runtime_size_array(var))
  13350. {
  13351. // This must be implemented as an argument buffer. Cast to intended descriptor array type on-demand.
  13352. if (!ep_args.empty())
  13353. ep_args += ", ";
  13354. ep_args += join("device const void* spvDescriptorSet", desc_set, "Binding", desc_binding);
  13355. if (type.basetype == SPIRType::SampledImage && r.basetype == SPIRType::Sampler)
  13356. ep_args += "Smplr";
  13357. ep_args += " [[buffer(" + convert_to_string(r.index) + ")";
  13358. if (interlocked_resources.count(var_id))
  13359. ep_args += ", raster_order_group(0)";
  13360. ep_args += "]]";
  13361. continue;
  13362. }
  13363. switch (r.basetype)
  13364. {
  13365. case SPIRType::Struct:
  13366. {
  13367. auto &m = ir.meta[type.self];
  13368. if (m.members.size() == 0)
  13369. break;
  13370. if (!type.array.empty())
  13371. {
  13372. if (type.array.size() > 1)
  13373. SPIRV_CROSS_THROW("Arrays of arrays of buffers are not supported.");
  13374. is_using_builtin_array = true;
  13375. uint32_t array_size = get_resource_array_size(type, var_id);
  13376. for (uint32_t i = 0; i < array_size; ++i)
  13377. {
  13378. if (!ep_args.empty())
  13379. ep_args += ", ";
  13380. ep_args += get_variable_address_space(var) + " " + type_to_glsl(type) + "* " +
  13381. to_restrict(var_id, true) + r.name + "_" + convert_to_string(i);
  13382. ep_args += " [[buffer(" + convert_to_string(r.index + i) + ")";
  13383. if (interlocked_resources.count(var_id))
  13384. ep_args += ", raster_order_group(0)";
  13385. ep_args += "]]";
  13386. }
  13387. is_using_builtin_array = false;
  13388. }
  13389. else
  13390. {
  13391. if (!ep_args.empty())
  13392. ep_args += ", ";
  13393. ep_args += get_variable_address_space(var) + " ";
  13394. if (recursive_inputs.count(type.self))
  13395. ep_args += string("void* ") + to_restrict(var_id, true) + r.name + "_vp";
  13396. else
  13397. ep_args += type_to_glsl(type) + "& " + to_restrict(var_id, true) + r.name;
  13398. ep_args += " [[buffer(" + convert_to_string(r.index) + ")";
  13399. if (interlocked_resources.count(var_id))
  13400. ep_args += ", raster_order_group(0)";
  13401. ep_args += "]]";
  13402. }
  13403. break;
  13404. }
  13405. case SPIRType::Sampler:
  13406. if (!ep_args.empty())
  13407. ep_args += ", ";
  13408. ep_args += sampler_type(type, var_id, false) + " " + r.name;
  13409. ep_args += " [[sampler(" + convert_to_string(r.index) + ")]]";
  13410. break;
  13411. case SPIRType::Image:
  13412. {
  13413. if (!ep_args.empty())
  13414. ep_args += ", ";
  13415. // Use Metal's native frame-buffer fetch API for subpass inputs.
  13416. const auto &basetype = get<SPIRType>(var.basetype);
  13417. if (!type_is_msl_framebuffer_fetch(basetype))
  13418. {
  13419. ep_args += image_type_glsl(type, var_id, false) + " " + r.name;
  13420. if (r.plane > 0)
  13421. ep_args += join(plane_name_suffix, r.plane);
  13422. ep_args += " [[texture(" + convert_to_string(r.index) + ")";
  13423. if (interlocked_resources.count(var_id))
  13424. ep_args += ", raster_order_group(0)";
  13425. ep_args += "]]";
  13426. }
  13427. else
  13428. {
  13429. if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 3))
  13430. SPIRV_CROSS_THROW("Framebuffer fetch on Mac is not supported before MSL 2.3.");
  13431. ep_args += image_type_glsl(type, var_id, false) + " " + r.name;
  13432. ep_args += " [[color(" + convert_to_string(r.index) + ")]]";
  13433. }
  13434. // Emulate texture2D atomic operations
  13435. if (atomic_image_vars_emulated.count(var.self))
  13436. {
  13437. auto &flags = ir.get_decoration_bitset(var.self);
  13438. const char *cv_flags = decoration_flags_signal_volatile(flags) ? "volatile " : "";
  13439. ep_args += join(", ", cv_flags, "device atomic_", type_to_glsl(get<SPIRType>(basetype.image.type), 0));
  13440. ep_args += "* " + r.name + "_atomic";
  13441. ep_args += " [[buffer(" + convert_to_string(r.secondary_index) + ")";
  13442. if (interlocked_resources.count(var_id))
  13443. ep_args += ", raster_order_group(0)";
  13444. ep_args += "]]";
  13445. }
  13446. break;
  13447. }
  13448. case SPIRType::AccelerationStructure:
  13449. {
  13450. if (!ep_args.empty())
  13451. ep_args += ", ";
  13452. ep_args += type_to_glsl(type, var_id) + " " + r.name;
  13453. ep_args += " [[buffer(" + convert_to_string(r.index) + ")]]";
  13454. break;
  13455. }
  13456. default:
  13457. if (!ep_args.empty())
  13458. ep_args += ", ";
  13459. if (!type.pointer)
  13460. ep_args += get_type_address_space(get<SPIRType>(var.basetype), var_id) + " " +
  13461. type_to_glsl(type, var_id) + "& " + r.name;
  13462. else
  13463. ep_args += type_to_glsl(type, var_id) + " " + r.name;
  13464. ep_args += " [[buffer(" + convert_to_string(r.index) + ")";
  13465. if (interlocked_resources.count(var_id))
  13466. ep_args += ", raster_order_group(0)";
  13467. ep_args += "]]";
  13468. break;
  13469. }
  13470. }
  13471. }
  13472. // Returns a string containing a comma-delimited list of args for the entry point function
  13473. // This is the "classic" method of MSL 1 when we don't have argument buffer support.
  13474. string CompilerMSL::entry_point_args_classic(bool append_comma)
  13475. {
  13476. string ep_args = entry_point_arg_stage_in();
  13477. entry_point_args_discrete_descriptors(ep_args);
  13478. entry_point_args_builtin(ep_args);
  13479. if (!ep_args.empty() && append_comma)
  13480. ep_args += ", ";
  13481. return ep_args;
  13482. }
  13483. void CompilerMSL::fix_up_shader_inputs_outputs()
  13484. {
  13485. auto &entry_func = this->get<SPIRFunction>(ir.default_entry_point);
  13486. // Emit a guard to ensure we don't execute beyond the last vertex.
  13487. // Vertex shaders shouldn't have the problems with barriers in non-uniform control flow that
  13488. // tessellation control shaders do, so early returns should be OK. We may need to revisit this
  13489. // if it ever becomes possible to use barriers from a vertex shader.
  13490. if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation)
  13491. {
  13492. entry_func.fixup_hooks_in.push_back([this]() {
  13493. statement("if (any(", to_expression(builtin_invocation_id_id),
  13494. " >= ", to_expression(builtin_stage_input_size_id), "))");
  13495. statement(" return;");
  13496. });
  13497. }
  13498. if (is_mesh_shader())
  13499. {
  13500. // If shader doesn't call SetMeshOutputsEXT, nothing should be rendered.
  13501. // No need to barrier after this, because only thread 0 writes to this later.
  13502. entry_func.fixup_hooks_in.push_back([this]() { statement("if (gl_LocalInvocationIndex == 0) spvMeshSizes.y = 0u;"); });
  13503. entry_func.fixup_hooks_out.push_back([this]() { emit_mesh_outputs(); });
  13504. }
  13505. // Look for sampled images and buffer. Add hooks to set up the swizzle constants or array lengths.
  13506. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
  13507. auto &type = get_variable_data_type(var);
  13508. uint32_t var_id = var.self;
  13509. bool ssbo = has_decoration(type.self, DecorationBufferBlock);
  13510. if (var.storage == StorageClassUniformConstant && !is_hidden_variable(var))
  13511. {
  13512. if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(type))
  13513. {
  13514. entry_func.fixup_hooks_in.push_back([this, &type, &var, var_id]() {
  13515. bool is_array_type = !type.array.empty();
  13516. uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
  13517. if (descriptor_set_is_argument_buffer(desc_set))
  13518. {
  13519. statement("constant uint", is_array_type ? "* " : "& ", to_swizzle_expression(var_id),
  13520. is_array_type ? " = &" : " = ", to_name(argument_buffer_ids[desc_set]),
  13521. ".spvSwizzleConstants", "[",
  13522. convert_to_string(get_metal_resource_index(var, SPIRType::Image)), "];");
  13523. }
  13524. else
  13525. {
  13526. // If we have an array of images, we need to be able to index into it, so take a pointer instead.
  13527. statement("constant uint", is_array_type ? "* " : "& ", to_swizzle_expression(var_id),
  13528. is_array_type ? " = &" : " = ", to_name(swizzle_buffer_id), "[",
  13529. convert_to_string(get_metal_resource_index(var, SPIRType::Image)), "];");
  13530. }
  13531. });
  13532. }
  13533. }
  13534. else if ((var.storage == StorageClassStorageBuffer || (var.storage == StorageClassUniform && ssbo)) &&
  13535. !is_hidden_variable(var))
  13536. {
  13537. if (buffer_requires_array_length(var.self))
  13538. {
  13539. entry_func.fixup_hooks_in.push_back(
  13540. [this, &type, &var, var_id]()
  13541. {
  13542. bool is_array_type = !type.array.empty() && !is_var_runtime_size_array(var);
  13543. uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
  13544. if (descriptor_set_is_argument_buffer(desc_set))
  13545. {
  13546. statement("constant uint", is_array_type ? "* " : "& ", to_buffer_size_expression(var_id),
  13547. is_array_type ? " = &" : " = ", to_name(argument_buffer_ids[desc_set]),
  13548. ".spvBufferSizeConstants", "[",
  13549. convert_to_string(get_metal_resource_index(var, SPIRType::UInt)), "];");
  13550. }
  13551. else
  13552. {
  13553. // If we have an array of images, we need to be able to index into it, so take a pointer instead.
  13554. statement("constant uint", is_array_type ? "* " : "& ", to_buffer_size_expression(var_id),
  13555. is_array_type ? " = &" : " = ", to_name(buffer_size_buffer_id), "[",
  13556. convert_to_string(get_metal_resource_index(var, type.basetype)), "];");
  13557. }
  13558. });
  13559. }
  13560. }
  13561. if (!msl_options.argument_buffers &&
  13562. msl_options.replace_recursive_inputs && type_contains_recursion(type) &&
  13563. (var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant ||
  13564. var.storage == StorageClassPushConstant || var.storage == StorageClassStorageBuffer))
  13565. {
  13566. recursive_inputs.insert(type.self);
  13567. entry_func.fixup_hooks_in.push_back([this, &type, &var, var_id]() {
  13568. auto addr_space = get_variable_address_space(var);
  13569. auto var_name = to_name(var_id);
  13570. statement(addr_space, " auto& ", to_restrict(var_id, true), var_name,
  13571. " = *(", addr_space, " ", type_to_glsl(type), "*)", var_name, "_vp;");
  13572. });
  13573. }
  13574. });
  13575. // Builtin variables
  13576. ir.for_each_typed_id<SPIRVariable>([this, &entry_func](uint32_t, SPIRVariable &var) {
  13577. uint32_t var_id = var.self;
  13578. BuiltIn bi_type = ir.meta[var_id].decoration.builtin_type;
  13579. if (var.storage != StorageClassInput && var.storage != StorageClassOutput)
  13580. return;
  13581. if (!interface_variable_exists_in_entry_point(var.self))
  13582. return;
  13583. if (var.storage == StorageClassInput && is_builtin_variable(var) && active_input_builtins.get(bi_type))
  13584. {
  13585. switch (bi_type)
  13586. {
  13587. case BuiltInSamplePosition:
  13588. entry_func.fixup_hooks_in.push_back([=]() {
  13589. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = get_sample_position(",
  13590. to_expression(builtin_sample_id_id), ");");
  13591. });
  13592. break;
  13593. case BuiltInFragCoord:
  13594. if (is_sample_rate())
  13595. {
  13596. entry_func.fixup_hooks_in.push_back([=]() {
  13597. statement(to_expression(var_id), ".xy += get_sample_position(",
  13598. to_expression(builtin_sample_id_id), ") - 0.5;");
  13599. });
  13600. }
  13601. break;
  13602. case BuiltInInvocationId:
  13603. // This is direct-mapped without multi-patch workgroups.
  13604. if (!is_tesc_shader() || !msl_options.multi_patch_workgroup)
  13605. break;
  13606. entry_func.fixup_hooks_in.push_back([=]() {
  13607. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13608. to_expression(builtin_invocation_id_id), ".x % ", this->get_entry_point().output_vertices,
  13609. ";");
  13610. });
  13611. break;
  13612. case BuiltInPrimitiveId:
  13613. // This is natively supported by fragment and tessellation evaluation shaders.
  13614. // In tessellation control shaders, this is direct-mapped without multi-patch workgroups.
  13615. if (!is_tesc_shader() || !msl_options.multi_patch_workgroup)
  13616. break;
  13617. entry_func.fixup_hooks_in.push_back([=]() {
  13618. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = min(",
  13619. to_expression(builtin_invocation_id_id), ".x / ", this->get_entry_point().output_vertices,
  13620. ", spvIndirectParams[1] - 1);");
  13621. });
  13622. break;
  13623. case BuiltInPatchVertices:
  13624. if (is_tese_shader())
  13625. {
  13626. if (msl_options.raw_buffer_tese_input)
  13627. {
  13628. entry_func.fixup_hooks_in.push_back(
  13629. [=]() {
  13630. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13631. get_entry_point().output_vertices, ";");
  13632. });
  13633. }
  13634. else
  13635. {
  13636. entry_func.fixup_hooks_in.push_back(
  13637. [=]()
  13638. {
  13639. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13640. to_expression(patch_stage_in_var_id), ".gl_in.size();");
  13641. });
  13642. }
  13643. }
  13644. else
  13645. {
  13646. entry_func.fixup_hooks_in.push_back([=]() {
  13647. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = spvIndirectParams[0];");
  13648. });
  13649. }
  13650. break;
  13651. case BuiltInTessCoord:
  13652. if (get_entry_point().flags.get(ExecutionModeQuads))
  13653. {
  13654. // The entry point will only have a float2 TessCoord variable.
  13655. // Pad to float3.
  13656. entry_func.fixup_hooks_in.push_back([=]() {
  13657. auto name = builtin_to_glsl(BuiltInTessCoord, StorageClassInput);
  13658. statement("float3 " + name + " = float3(" + name + "In.x, " + name + "In.y, 0.0);");
  13659. });
  13660. }
  13661. // Emit a fixup to account for the shifted domain. Don't do this for triangles;
  13662. // MoltenVK will just reverse the winding order instead.
  13663. if (msl_options.tess_domain_origin_lower_left && !is_tessellating_triangles())
  13664. {
  13665. string tc = to_expression(var_id);
  13666. entry_func.fixup_hooks_in.push_back([=]() { statement(tc, ".y = 1.0 - ", tc, ".y;"); });
  13667. }
  13668. break;
  13669. case BuiltInSubgroupId:
  13670. if (!msl_options.emulate_subgroups)
  13671. break;
  13672. // For subgroup emulation, this is the same as the local invocation index.
  13673. entry_func.fixup_hooks_in.push_back([=]() {
  13674. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13675. to_expression(builtin_local_invocation_index_id), ";");
  13676. });
  13677. break;
  13678. case BuiltInNumSubgroups:
  13679. if (!msl_options.emulate_subgroups)
  13680. break;
  13681. // For subgroup emulation, this is the same as the workgroup size.
  13682. entry_func.fixup_hooks_in.push_back([=]() {
  13683. auto &type = expression_type(builtin_workgroup_size_id);
  13684. string size_expr = to_expression(builtin_workgroup_size_id);
  13685. if (type.vecsize >= 3)
  13686. size_expr = join(size_expr, ".x * ", size_expr, ".y * ", size_expr, ".z");
  13687. else if (type.vecsize == 2)
  13688. size_expr = join(size_expr, ".x * ", size_expr, ".y");
  13689. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", size_expr, ";");
  13690. });
  13691. break;
  13692. case BuiltInSubgroupLocalInvocationId:
  13693. if (!msl_options.emulate_subgroups)
  13694. break;
  13695. // For subgroup emulation, assume subgroups of size 1.
  13696. entry_func.fixup_hooks_in.push_back(
  13697. [=]() { statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = 0;"); });
  13698. break;
  13699. case BuiltInSubgroupSize:
  13700. if (msl_options.emulate_subgroups)
  13701. {
  13702. // For subgroup emulation, assume subgroups of size 1.
  13703. entry_func.fixup_hooks_in.push_back(
  13704. [=]() { statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = 1;"); });
  13705. }
  13706. else if (msl_options.fixed_subgroup_size != 0)
  13707. {
  13708. entry_func.fixup_hooks_in.push_back([=]() {
  13709. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13710. msl_options.fixed_subgroup_size, ";");
  13711. });
  13712. }
  13713. break;
  13714. case BuiltInSubgroupEqMask:
  13715. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
  13716. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
  13717. if (!msl_options.supports_msl_version(2, 1))
  13718. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
  13719. entry_func.fixup_hooks_in.push_back([=]() {
  13720. if (msl_options.is_ios())
  13721. {
  13722. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", "uint4(1 << ",
  13723. to_expression(builtin_subgroup_invocation_id_id), ", uint3(0));");
  13724. }
  13725. else
  13726. {
  13727. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13728. to_expression(builtin_subgroup_invocation_id_id), " >= 32 ? uint4(0, (1 << (",
  13729. to_expression(builtin_subgroup_invocation_id_id), " - 32)), uint2(0)) : uint4(1 << ",
  13730. to_expression(builtin_subgroup_invocation_id_id), ", uint3(0));");
  13731. }
  13732. });
  13733. break;
  13734. case BuiltInSubgroupGeMask:
  13735. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
  13736. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
  13737. if (!msl_options.supports_msl_version(2, 1))
  13738. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
  13739. if (msl_options.fixed_subgroup_size != 0)
  13740. add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
  13741. entry_func.fixup_hooks_in.push_back([=]() {
  13742. // Case where index < 32, size < 32:
  13743. // mask0 = bfi(0, 0xFFFFFFFF, index, size - index);
  13744. // mask1 = bfi(0, 0xFFFFFFFF, 0, 0); // Gives 0
  13745. // Case where index < 32 but size >= 32:
  13746. // mask0 = bfi(0, 0xFFFFFFFF, index, 32 - index);
  13747. // mask1 = bfi(0, 0xFFFFFFFF, 0, size - 32);
  13748. // Case where index >= 32:
  13749. // mask0 = bfi(0, 0xFFFFFFFF, 32, 0); // Gives 0
  13750. // mask1 = bfi(0, 0xFFFFFFFF, index - 32, size - index);
  13751. // This is expressed without branches to avoid divergent
  13752. // control flow--hence the complicated min/max expressions.
  13753. // This is further complicated by the fact that if you attempt
  13754. // to bfi/bfe out-of-bounds on Metal, undefined behavior is the
  13755. // result.
  13756. if (msl_options.fixed_subgroup_size > 32)
  13757. {
  13758. // Don't use the subgroup size variable with fixed subgroup sizes,
  13759. // since the variables could be defined in the wrong order.
  13760. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13761. " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
  13762. to_expression(builtin_subgroup_invocation_id_id), ", 32u), (uint)max(32 - (int)",
  13763. to_expression(builtin_subgroup_invocation_id_id),
  13764. ", 0)), insert_bits(0u, 0xFFFFFFFF,"
  13765. " (uint)max((int)",
  13766. to_expression(builtin_subgroup_invocation_id_id), " - 32, 0), ",
  13767. msl_options.fixed_subgroup_size, " - max(",
  13768. to_expression(builtin_subgroup_invocation_id_id),
  13769. ", 32u)), uint2(0));");
  13770. }
  13771. else if (msl_options.fixed_subgroup_size != 0)
  13772. {
  13773. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13774. " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
  13775. to_expression(builtin_subgroup_invocation_id_id), ", ",
  13776. msl_options.fixed_subgroup_size, " - ",
  13777. to_expression(builtin_subgroup_invocation_id_id),
  13778. "), uint3(0));");
  13779. }
  13780. else if (msl_options.is_ios())
  13781. {
  13782. // On iOS, the SIMD-group size will currently never exceed 32.
  13783. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13784. " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
  13785. to_expression(builtin_subgroup_invocation_id_id), ", ",
  13786. to_expression(builtin_subgroup_size_id), " - ",
  13787. to_expression(builtin_subgroup_invocation_id_id), "), uint3(0));");
  13788. }
  13789. else
  13790. {
  13791. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13792. " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
  13793. to_expression(builtin_subgroup_invocation_id_id), ", 32u), (uint)max(min((int)",
  13794. to_expression(builtin_subgroup_size_id), ", 32) - (int)",
  13795. to_expression(builtin_subgroup_invocation_id_id),
  13796. ", 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)",
  13797. to_expression(builtin_subgroup_invocation_id_id), " - 32, 0), (uint)max((int)",
  13798. to_expression(builtin_subgroup_size_id), " - (int)max(",
  13799. to_expression(builtin_subgroup_invocation_id_id), ", 32u), 0)), uint2(0));");
  13800. }
  13801. });
  13802. break;
  13803. case BuiltInSubgroupGtMask:
  13804. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
  13805. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
  13806. if (!msl_options.supports_msl_version(2, 1))
  13807. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
  13808. add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
  13809. entry_func.fixup_hooks_in.push_back([=]() {
  13810. // The same logic applies here, except now the index is one
  13811. // more than the subgroup invocation ID.
  13812. if (msl_options.fixed_subgroup_size > 32)
  13813. {
  13814. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13815. " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
  13816. to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), (uint)max(32 - (int)",
  13817. to_expression(builtin_subgroup_invocation_id_id),
  13818. " - 1, 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)",
  13819. to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0), ",
  13820. msl_options.fixed_subgroup_size, " - max(",
  13821. to_expression(builtin_subgroup_invocation_id_id),
  13822. " + 1, 32u)), uint2(0));");
  13823. }
  13824. else if (msl_options.fixed_subgroup_size != 0)
  13825. {
  13826. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13827. " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
  13828. to_expression(builtin_subgroup_invocation_id_id), " + 1, ",
  13829. msl_options.fixed_subgroup_size, " - ",
  13830. to_expression(builtin_subgroup_invocation_id_id),
  13831. " - 1), uint3(0));");
  13832. }
  13833. else if (msl_options.is_ios())
  13834. {
  13835. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13836. " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
  13837. to_expression(builtin_subgroup_invocation_id_id), " + 1, ",
  13838. to_expression(builtin_subgroup_size_id), " - ",
  13839. to_expression(builtin_subgroup_invocation_id_id), " - 1), uint3(0));");
  13840. }
  13841. else
  13842. {
  13843. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13844. " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
  13845. to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), (uint)max(min((int)",
  13846. to_expression(builtin_subgroup_size_id), ", 32) - (int)",
  13847. to_expression(builtin_subgroup_invocation_id_id),
  13848. " - 1, 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)",
  13849. to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0), (uint)max((int)",
  13850. to_expression(builtin_subgroup_size_id), " - (int)max(",
  13851. to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), 0)), uint2(0));");
  13852. }
  13853. });
  13854. break;
  13855. case BuiltInSubgroupLeMask:
  13856. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
  13857. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
  13858. if (!msl_options.supports_msl_version(2, 1))
  13859. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
  13860. add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
  13861. entry_func.fixup_hooks_in.push_back([=]() {
  13862. if (msl_options.is_ios())
  13863. {
  13864. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13865. " = uint4(extract_bits(0xFFFFFFFF, 0, ",
  13866. to_expression(builtin_subgroup_invocation_id_id), " + 1), uint3(0));");
  13867. }
  13868. else
  13869. {
  13870. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13871. " = uint4(extract_bits(0xFFFFFFFF, 0, min(",
  13872. to_expression(builtin_subgroup_invocation_id_id),
  13873. " + 1, 32u)), extract_bits(0xFFFFFFFF, 0, (uint)max((int)",
  13874. to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0)), uint2(0));");
  13875. }
  13876. });
  13877. break;
  13878. case BuiltInSubgroupLtMask:
  13879. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
  13880. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
  13881. if (!msl_options.supports_msl_version(2, 1))
  13882. SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
  13883. add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
  13884. entry_func.fixup_hooks_in.push_back([=]() {
  13885. if (msl_options.is_ios())
  13886. {
  13887. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13888. " = uint4(extract_bits(0xFFFFFFFF, 0, ",
  13889. to_expression(builtin_subgroup_invocation_id_id), "), uint3(0));");
  13890. }
  13891. else
  13892. {
  13893. statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
  13894. " = uint4(extract_bits(0xFFFFFFFF, 0, min(",
  13895. to_expression(builtin_subgroup_invocation_id_id),
  13896. ", 32u)), extract_bits(0xFFFFFFFF, 0, (uint)max((int)",
  13897. to_expression(builtin_subgroup_invocation_id_id), " - 32, 0)), uint2(0));");
  13898. }
  13899. });
  13900. break;
  13901. case BuiltInViewIndex:
  13902. if (!msl_options.multiview)
  13903. {
  13904. // According to the Vulkan spec, when not running under a multiview
  13905. // render pass, ViewIndex is 0.
  13906. entry_func.fixup_hooks_in.push_back([=]() {
  13907. statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = 0;");
  13908. });
  13909. }
  13910. else if (msl_options.view_index_from_device_index)
  13911. {
  13912. // In this case, we take the view index from that of the device we're running on.
  13913. entry_func.fixup_hooks_in.push_back([=]() {
  13914. statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13915. msl_options.device_index, ";");
  13916. });
  13917. // We actually don't want to set the render_target_array_index here.
  13918. // Since every physical device is rendering a different view,
  13919. // there's no need for layered rendering here.
  13920. }
  13921. else if (!msl_options.multiview_layered_rendering)
  13922. {
  13923. // In this case, the views are rendered one at a time. The view index, then,
  13924. // is just the first part of the "view mask".
  13925. entry_func.fixup_hooks_in.push_back([=]() {
  13926. statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13927. to_expression(view_mask_buffer_id), "[0];");
  13928. });
  13929. }
  13930. else if (get_execution_model() == ExecutionModelFragment)
  13931. {
  13932. // Because we adjusted the view index in the vertex shader, we have to
  13933. // adjust it back here.
  13934. entry_func.fixup_hooks_in.push_back([=]() {
  13935. statement(to_expression(var_id), " += ", to_expression(view_mask_buffer_id), "[0];");
  13936. });
  13937. }
  13938. else if (get_execution_model() == ExecutionModelVertex)
  13939. {
  13940. // Metal provides no special support for multiview, so we smuggle
  13941. // the view index in the instance index.
  13942. entry_func.fixup_hooks_in.push_back([=]() {
  13943. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13944. to_expression(view_mask_buffer_id), "[0] + (", to_expression(builtin_instance_idx_id),
  13945. " - ", to_expression(builtin_base_instance_id), ") % ",
  13946. to_expression(view_mask_buffer_id), "[1];");
  13947. statement(to_expression(builtin_instance_idx_id), " = (",
  13948. to_expression(builtin_instance_idx_id), " - ",
  13949. to_expression(builtin_base_instance_id), ") / ", to_expression(view_mask_buffer_id),
  13950. "[1] + ", to_expression(builtin_base_instance_id), ";");
  13951. });
  13952. // In addition to setting the variable itself, we also need to
  13953. // set the render_target_array_index with it on output. We have to
  13954. // offset this by the base view index, because Metal isn't in on
  13955. // our little game here.
  13956. entry_func.fixup_hooks_out.push_back([=]() {
  13957. statement(to_expression(builtin_layer_id), " = ", to_expression(var_id), " - ",
  13958. to_expression(view_mask_buffer_id), "[0];");
  13959. });
  13960. }
  13961. break;
  13962. case BuiltInDeviceIndex:
  13963. // Metal pipelines belong to the devices which create them, so we'll
  13964. // need to create a MTLPipelineState for every MTLDevice in a grouped
  13965. // VkDevice. We can assume, then, that the device index is constant.
  13966. entry_func.fixup_hooks_in.push_back([=]() {
  13967. statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  13968. msl_options.device_index, ";");
  13969. });
  13970. break;
  13971. case BuiltInWorkgroupId:
  13972. if (!msl_options.dispatch_base || !active_input_builtins.get(BuiltInWorkgroupId))
  13973. break;
  13974. // The vkCmdDispatchBase() command lets the client set the base value
  13975. // of WorkgroupId. Metal has no direct equivalent; we must make this
  13976. // adjustment ourselves.
  13977. entry_func.fixup_hooks_in.push_back([=]() {
  13978. statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id), ";");
  13979. });
  13980. break;
  13981. case BuiltInGlobalInvocationId:
  13982. if (!msl_options.dispatch_base || !active_input_builtins.get(BuiltInGlobalInvocationId))
  13983. break;
  13984. // GlobalInvocationId is defined as LocalInvocationId + WorkgroupId * WorkgroupSize.
  13985. // This needs to be adjusted too.
  13986. entry_func.fixup_hooks_in.push_back([=]() {
  13987. auto &execution = this->get_entry_point();
  13988. uint32_t workgroup_size_id = execution.workgroup_size.constant;
  13989. if (workgroup_size_id)
  13990. statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id),
  13991. " * ", to_expression(workgroup_size_id), ";");
  13992. else
  13993. statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id),
  13994. " * uint3(", execution.workgroup_size.x, ", ", execution.workgroup_size.y, ", ",
  13995. execution.workgroup_size.z, ");");
  13996. });
  13997. break;
  13998. case BuiltInVertexId:
  13999. case BuiltInVertexIndex:
  14000. // This is direct-mapped normally.
  14001. if (!msl_options.vertex_for_tessellation)
  14002. break;
  14003. entry_func.fixup_hooks_in.push_back([=]() {
  14004. builtin_declaration = true;
  14005. switch (msl_options.vertex_index_type)
  14006. {
  14007. case Options::IndexType::None:
  14008. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  14009. to_expression(builtin_invocation_id_id), ".x + ",
  14010. to_expression(builtin_dispatch_base_id), ".x;");
  14011. break;
  14012. case Options::IndexType::UInt16:
  14013. case Options::IndexType::UInt32:
  14014. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", index_buffer_var_name,
  14015. "[", to_expression(builtin_invocation_id_id), ".x] + ",
  14016. to_expression(builtin_dispatch_base_id), ".x;");
  14017. break;
  14018. }
  14019. builtin_declaration = false;
  14020. });
  14021. break;
  14022. case BuiltInBaseVertex:
  14023. // This is direct-mapped normally.
  14024. if (!msl_options.vertex_for_tessellation)
  14025. break;
  14026. entry_func.fixup_hooks_in.push_back([=]() {
  14027. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  14028. to_expression(builtin_dispatch_base_id), ".x;");
  14029. });
  14030. break;
  14031. case BuiltInInstanceId:
  14032. case BuiltInInstanceIndex:
  14033. // This is direct-mapped normally.
  14034. if (!msl_options.vertex_for_tessellation)
  14035. break;
  14036. entry_func.fixup_hooks_in.push_back([=]() {
  14037. builtin_declaration = true;
  14038. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  14039. to_expression(builtin_invocation_id_id), ".y + ", to_expression(builtin_dispatch_base_id),
  14040. ".y;");
  14041. builtin_declaration = false;
  14042. });
  14043. break;
  14044. case BuiltInBaseInstance:
  14045. // This is direct-mapped normally.
  14046. if (!msl_options.vertex_for_tessellation)
  14047. break;
  14048. entry_func.fixup_hooks_in.push_back([=]() {
  14049. statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
  14050. to_expression(builtin_dispatch_base_id), ".y;");
  14051. });
  14052. break;
  14053. default:
  14054. break;
  14055. }
  14056. }
  14057. else if (var.storage == StorageClassOutput && get_execution_model() == ExecutionModelFragment &&
  14058. is_builtin_variable(var) && active_output_builtins.get(bi_type))
  14059. {
  14060. switch (bi_type)
  14061. {
  14062. case BuiltInSampleMask:
  14063. if (has_additional_fixed_sample_mask())
  14064. {
  14065. // If the additional fixed sample mask was set, we need to adjust the sample_mask
  14066. // output to reflect that. If the shader outputs the sample_mask itself too, we need
  14067. // to AND the two masks to get the final one.
  14068. string op_str = does_shader_write_sample_mask ? " &= " : " = ";
  14069. entry_func.fixup_hooks_out.push_back([=]() {
  14070. statement(to_expression(builtin_sample_mask_id), op_str, additional_fixed_sample_mask_str(), ";");
  14071. });
  14072. }
  14073. break;
  14074. case BuiltInFragDepth:
  14075. if (msl_options.input_attachment_is_ds_attachment && !writes_to_depth)
  14076. {
  14077. entry_func.fixup_hooks_out.push_back([=]() {
  14078. statement(to_expression(builtin_frag_depth_id), " = ", to_expression(builtin_frag_coord_id), ".z;");
  14079. });
  14080. }
  14081. break;
  14082. default:
  14083. break;
  14084. }
  14085. }
  14086. });
  14087. }
  14088. // Returns the Metal index of the resource of the specified type as used by the specified variable.
  14089. uint32_t CompilerMSL::get_metal_resource_index(SPIRVariable &var, SPIRType::BaseType basetype, uint32_t plane)
  14090. {
  14091. auto &execution = get_entry_point();
  14092. auto &var_dec = ir.meta[var.self].decoration;
  14093. auto &var_type = get<SPIRType>(var.basetype);
  14094. uint32_t var_desc_set = (var.storage == StorageClassPushConstant) ? kPushConstDescSet : var_dec.set;
  14095. uint32_t var_binding = (var.storage == StorageClassPushConstant) ? kPushConstBinding : var_dec.binding;
  14096. // If a matching binding has been specified, find and use it.
  14097. auto itr = resource_bindings.find({ execution.model, var_desc_set, var_binding });
  14098. // Atomic helper buffers for image atomics need to use secondary bindings as well.
  14099. bool use_secondary_binding = (var_type.basetype == SPIRType::SampledImage && basetype == SPIRType::Sampler) ||
  14100. basetype == SPIRType::AtomicCounter;
  14101. auto resource_decoration =
  14102. use_secondary_binding ? SPIRVCrossDecorationResourceIndexSecondary : SPIRVCrossDecorationResourceIndexPrimary;
  14103. if (plane == 1)
  14104. resource_decoration = SPIRVCrossDecorationResourceIndexTertiary;
  14105. if (plane == 2)
  14106. resource_decoration = SPIRVCrossDecorationResourceIndexQuaternary;
  14107. if (itr != end(resource_bindings))
  14108. {
  14109. auto &remap = itr->second;
  14110. remap.second = true;
  14111. switch (basetype)
  14112. {
  14113. case SPIRType::Image:
  14114. set_extended_decoration(var.self, resource_decoration, remap.first.msl_texture + plane);
  14115. return remap.first.msl_texture + plane;
  14116. case SPIRType::Sampler:
  14117. set_extended_decoration(var.self, resource_decoration, remap.first.msl_sampler);
  14118. return remap.first.msl_sampler;
  14119. default:
  14120. set_extended_decoration(var.self, resource_decoration, remap.first.msl_buffer);
  14121. return remap.first.msl_buffer;
  14122. }
  14123. }
  14124. // If we have already allocated an index, keep using it.
  14125. if (has_extended_decoration(var.self, resource_decoration))
  14126. return get_extended_decoration(var.self, resource_decoration);
  14127. auto &type = get<SPIRType>(var.basetype);
  14128. if (type_is_msl_framebuffer_fetch(type))
  14129. {
  14130. // Frame-buffer fetch gets its fallback resource index from the input attachment index,
  14131. // which is then treated as color index.
  14132. return get_decoration(var.self, DecorationInputAttachmentIndex);
  14133. }
  14134. else if (msl_options.enable_decoration_binding)
  14135. {
  14136. // Allow user to enable decoration binding.
  14137. // If there is no explicit mapping of bindings to MSL, use the declared binding as a fallback.
  14138. if (has_decoration(var.self, DecorationBinding))
  14139. {
  14140. var_binding = get_decoration(var.self, DecorationBinding);
  14141. // Avoid emitting sentinel bindings.
  14142. if (var_binding < 0x80000000u)
  14143. return var_binding;
  14144. }
  14145. }
  14146. // If we did not explicitly remap, allocate bindings on demand.
  14147. // We cannot reliably use Binding decorations since SPIR-V and MSL's binding models are very different.
  14148. bool allocate_argument_buffer_ids = false;
  14149. if (var.storage != StorageClassPushConstant)
  14150. allocate_argument_buffer_ids = descriptor_set_is_argument_buffer(var_desc_set);
  14151. uint32_t binding_stride = 1;
  14152. for (uint32_t i = 0; i < uint32_t(type.array.size()); i++)
  14153. binding_stride *= to_array_size_literal(type, i);
  14154. // If a binding has not been specified, revert to incrementing resource indices.
  14155. uint32_t resource_index;
  14156. if (allocate_argument_buffer_ids)
  14157. {
  14158. // Allocate from a flat ID binding space.
  14159. resource_index = next_metal_resource_ids[var_desc_set];
  14160. next_metal_resource_ids[var_desc_set] += binding_stride;
  14161. }
  14162. else
  14163. {
  14164. if (is_var_runtime_size_array(var))
  14165. {
  14166. basetype = SPIRType::Struct;
  14167. binding_stride = 1;
  14168. }
  14169. // Allocate from plain bindings which are allocated per resource type.
  14170. switch (basetype)
  14171. {
  14172. case SPIRType::Image:
  14173. resource_index = next_metal_resource_index_texture;
  14174. next_metal_resource_index_texture += binding_stride;
  14175. break;
  14176. case SPIRType::Sampler:
  14177. resource_index = next_metal_resource_index_sampler;
  14178. next_metal_resource_index_sampler += binding_stride;
  14179. break;
  14180. default:
  14181. resource_index = next_metal_resource_index_buffer;
  14182. next_metal_resource_index_buffer += binding_stride;
  14183. break;
  14184. }
  14185. }
  14186. set_extended_decoration(var.self, resource_decoration, resource_index);
  14187. return resource_index;
  14188. }
  14189. bool CompilerMSL::type_is_msl_framebuffer_fetch(const SPIRType &type) const
  14190. {
  14191. return type.basetype == SPIRType::Image && type.image.dim == DimSubpassData &&
  14192. msl_options.use_framebuffer_fetch_subpasses;
  14193. }
  14194. const char *CompilerMSL::descriptor_address_space(uint32_t id, StorageClass storage, const char *plain_address_space) const
  14195. {
  14196. if (msl_options.argument_buffers)
  14197. {
  14198. bool storage_class_is_descriptor = storage == StorageClassUniform ||
  14199. storage == StorageClassStorageBuffer ||
  14200. storage == StorageClassUniformConstant;
  14201. uint32_t desc_set = get_decoration(id, DecorationDescriptorSet);
  14202. if (storage_class_is_descriptor && descriptor_set_is_argument_buffer(desc_set))
  14203. {
  14204. // An awkward case where we need to emit *more* address space declarations (yay!).
  14205. // An example is where we pass down an array of buffer pointers to leaf functions.
  14206. // It's a constant array containing pointers to constants.
  14207. // The pointer array is always constant however. E.g.
  14208. // device SSBO * constant (&array)[N].
  14209. // const device SSBO * constant (&array)[N].
  14210. // constant SSBO * constant (&array)[N].
  14211. // However, this only matters for argument buffers, since for MSL 1.0 style codegen,
  14212. // we emit the buffer array on stack instead, and that seems to work just fine apparently.
  14213. // If the argument was marked as being in device address space, any pointer to member would
  14214. // be const device, not constant.
  14215. if (argument_buffer_device_storage_mask & (1u << desc_set))
  14216. return "const device";
  14217. else
  14218. return "constant";
  14219. }
  14220. }
  14221. return plain_address_space;
  14222. }
  14223. string CompilerMSL::argument_decl(const SPIRFunction::Parameter &arg)
  14224. {
  14225. auto &var = get<SPIRVariable>(arg.id);
  14226. auto &var_type = get<SPIRType>(arg.type);
  14227. StorageClass type_storage = var_type.storage;
  14228. // Physical pointer types are passed by pointer, not reference.
  14229. auto &data_type = get_variable_data_type(var);
  14230. bool passed_by_value = arg.alias_global_variable ? false : is_physical_or_buffer_pointer(var_type);
  14231. auto &type = passed_by_value ? var_type : data_type;
  14232. // If we need to modify the name of the variable, make sure we use the original variable.
  14233. // Our alias is just a shadow variable.
  14234. uint32_t name_id = var.self;
  14235. if (arg.alias_global_variable && var.basevariable)
  14236. name_id = var.basevariable;
  14237. bool constref = !arg.alias_global_variable && !passed_by_value && is_pointer(var_type) && arg.write_count == 0;
  14238. // Framebuffer fetch is plain value, const looks out of place, but it is not wrong.
  14239. // readonly coming from glslang is not reliable in all cases.
  14240. // For UBOs, readonly is implied, and for SSBOs we use global check.
  14241. if (type_is_msl_framebuffer_fetch(type) ||
  14242. type_storage == StorageClassStorageBuffer ||
  14243. type_storage == StorageClassUniform ||
  14244. type_storage == StorageClassPhysicalStorageBuffer)
  14245. {
  14246. constref = false;
  14247. }
  14248. else if (type_storage == StorageClassUniformConstant)
  14249. {
  14250. constref = true;
  14251. }
  14252. bool type_is_image = type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage ||
  14253. type.basetype == SPIRType::Sampler;
  14254. bool type_is_tlas = type.basetype == SPIRType::AccelerationStructure;
  14255. // For opaque types we handle const later due to descriptor address spaces.
  14256. const char *cv_qualifier = (constref && !type_is_image) ? "const " : "";
  14257. string decl;
  14258. // If this is a combined image-sampler for a 2D image with floating-point type,
  14259. // we emitted the 'spvDynamicImageSampler' type, and this is *not* an alias parameter
  14260. // for a global, then we need to emit a "dynamic" combined image-sampler.
  14261. // Unfortunately, this is necessary to properly support passing around
  14262. // combined image-samplers with Y'CbCr conversions on them.
  14263. bool is_dynamic_img_sampler = !arg.alias_global_variable && type.basetype == SPIRType::SampledImage &&
  14264. type.image.dim == Dim2D && type_is_floating_point(get<SPIRType>(type.image.type)) &&
  14265. spv_function_implementations.count(SPVFuncImplDynamicImageSampler);
  14266. // Allow Metal to use the array<T> template to make arrays a value type
  14267. string address_space = arg.alias_global_variable ? get_variable_address_space(var) : get_leaf_argument_address_space(var);
  14268. bool builtin = has_decoration(var.self, DecorationBuiltIn);
  14269. auto builtin_type = BuiltIn(get_decoration(arg.id, DecorationBuiltIn));
  14270. if (var.basevariable && (var.basevariable == stage_in_ptr_var_id || var.basevariable == stage_out_ptr_var_id))
  14271. decl = join(cv_qualifier, type_to_glsl(type, arg.id));
  14272. else if (builtin && !is_mesh_shader())
  14273. {
  14274. // Only use templated array for Clip/Cull distance when feasible.
  14275. // In other scenarios, we need need to override array length for tess levels (if used as outputs),
  14276. // or we need to emit the expected type for builtins (uint vs int).
  14277. auto storage = get<SPIRType>(var.basetype).storage;
  14278. if (storage == StorageClassInput &&
  14279. (builtin_type == BuiltInTessLevelInner || builtin_type == BuiltInTessLevelOuter))
  14280. {
  14281. is_using_builtin_array = false;
  14282. }
  14283. else if (builtin_type != BuiltInClipDistance && builtin_type != BuiltInCullDistance)
  14284. {
  14285. is_using_builtin_array = true;
  14286. }
  14287. if (storage == StorageClassOutput && variable_storage_requires_stage_io(storage) &&
  14288. !is_stage_output_builtin_masked(builtin_type))
  14289. is_using_builtin_array = true;
  14290. if (is_using_builtin_array)
  14291. decl = join(cv_qualifier, builtin_type_decl(builtin_type, arg.id));
  14292. else
  14293. decl = join(cv_qualifier, type_to_glsl(type, arg.id));
  14294. }
  14295. else if (is_var_runtime_size_array(var))
  14296. {
  14297. const auto *parent_type = &get<SPIRType>(type.parent_type);
  14298. auto type_name = type_to_glsl(*parent_type, arg.id);
  14299. if (type.basetype == SPIRType::AccelerationStructure)
  14300. decl = join("spvDescriptorArray<", type_name, ">");
  14301. else if (type_is_image)
  14302. decl = join("spvDescriptorArray<", cv_qualifier, type_name, ">");
  14303. else
  14304. decl = join("spvDescriptorArray<", address_space, " ", type_name, "*>");
  14305. address_space = "const";
  14306. }
  14307. else if ((type_storage == StorageClassUniform || type_storage == StorageClassStorageBuffer) && is_array(type))
  14308. {
  14309. is_using_builtin_array = true;
  14310. decl += join(cv_qualifier, type_to_glsl(type, arg.id), "*");
  14311. }
  14312. else if (is_dynamic_img_sampler)
  14313. {
  14314. decl = join(cv_qualifier, "spvDynamicImageSampler<", type_to_glsl(get<SPIRType>(type.image.type)), ">");
  14315. // Mark the variable so that we can handle passing it to another function.
  14316. set_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler);
  14317. }
  14318. else
  14319. {
  14320. // The type is a pointer type we need to emit cv_qualifier late.
  14321. if (is_pointer(data_type))
  14322. {
  14323. decl = type_to_glsl(type, arg.id);
  14324. if (*cv_qualifier != '\0')
  14325. decl += join(" ", cv_qualifier);
  14326. }
  14327. else
  14328. {
  14329. decl = join(cv_qualifier, type_to_glsl(type, arg.id));
  14330. }
  14331. }
  14332. if (passed_by_value || (!builtin && !is_pointer(var_type) &&
  14333. (type_storage == StorageClassFunction || type_storage == StorageClassGeneric)))
  14334. {
  14335. // If the argument is a pure value and not an opaque type, we will pass by value.
  14336. if (msl_options.force_native_arrays && is_array(type))
  14337. {
  14338. // We are receiving an array by value. This is problematic.
  14339. // We cannot be sure of the target address space since we are supposed to receive a copy,
  14340. // but this is not possible with MSL without some extra work.
  14341. // We will have to assume we're getting a reference in thread address space.
  14342. // If we happen to get a reference in constant address space, the caller must emit a copy and pass that.
  14343. // Thread const therefore becomes the only logical choice, since we cannot "create" a constant array from
  14344. // non-constant arrays, but we can create thread const from constant.
  14345. decl = string("thread const ") + decl;
  14346. decl += " (&";
  14347. const char *restrict_kw = to_restrict(name_id, true);
  14348. if (*restrict_kw)
  14349. {
  14350. decl += " ";
  14351. decl += restrict_kw;
  14352. }
  14353. decl += to_expression(name_id);
  14354. decl += ")";
  14355. decl += type_to_array_glsl(type, name_id);
  14356. }
  14357. else
  14358. {
  14359. // Variable pointer to array is kinda awkward ...
  14360. bool pointer_to_logical_buffer_array =
  14361. !is_physical_pointer(type) && is_pointer(type) &&
  14362. has_decoration(type.parent_type, DecorationArrayStride);
  14363. if (pointer_to_logical_buffer_array)
  14364. {
  14365. decl.pop_back();
  14366. decl += " (*";
  14367. decl += to_expression(name_id);
  14368. decl += ")";
  14369. bool old_is_using_builtin_array = is_using_builtin_array;
  14370. is_using_builtin_array = true;
  14371. decl += type_to_array_glsl(type, name_id);
  14372. is_using_builtin_array = old_is_using_builtin_array;
  14373. }
  14374. else
  14375. {
  14376. if (!address_space.empty())
  14377. decl = join(address_space, " ", decl);
  14378. decl += " ";
  14379. decl += to_expression(name_id);
  14380. }
  14381. }
  14382. }
  14383. else if (is_array(type) && !type_is_image)
  14384. {
  14385. // Arrays of opaque types are special cased.
  14386. if (!address_space.empty())
  14387. decl = join(address_space, " ", decl);
  14388. // spvDescriptorArray absorbs the address space inside the template.
  14389. if (!is_var_runtime_size_array(var))
  14390. {
  14391. const char *argument_buffer_space = descriptor_address_space(name_id, type_storage, nullptr);
  14392. if (argument_buffer_space)
  14393. {
  14394. decl += " ";
  14395. decl += argument_buffer_space;
  14396. }
  14397. }
  14398. // Special case, need to override the array size here if we're using tess level as an argument.
  14399. if (is_tesc_shader() && builtin &&
  14400. (builtin_type == BuiltInTessLevelInner || builtin_type == BuiltInTessLevelOuter))
  14401. {
  14402. uint32_t array_size = get_physical_tess_level_array_size(builtin_type);
  14403. if (array_size == 1)
  14404. {
  14405. decl += " &";
  14406. decl += to_expression(name_id);
  14407. }
  14408. else
  14409. {
  14410. decl += " (&";
  14411. decl += to_expression(name_id);
  14412. decl += ")";
  14413. decl += join("[", array_size, "]");
  14414. }
  14415. }
  14416. else if (is_var_runtime_size_array(var))
  14417. {
  14418. decl += " " + to_expression(name_id);
  14419. }
  14420. else
  14421. {
  14422. auto array_size_decl = type_to_array_glsl(type, name_id);
  14423. if (array_size_decl.empty())
  14424. decl += "& ";
  14425. else
  14426. decl += " (&";
  14427. const char *restrict_kw = to_restrict(name_id, true);
  14428. if (*restrict_kw)
  14429. {
  14430. decl += " ";
  14431. decl += restrict_kw;
  14432. }
  14433. decl += to_expression(name_id);
  14434. if (!array_size_decl.empty())
  14435. {
  14436. decl += ")";
  14437. decl += array_size_decl;
  14438. }
  14439. }
  14440. }
  14441. else if (!type_is_image && !type_is_tlas &&
  14442. (!pull_model_inputs.count(var.basevariable) || type.basetype == SPIRType::Struct))
  14443. {
  14444. // If this is going to be a reference to a variable pointer, the address space
  14445. // for the reference has to go before the '&', but after the '*'.
  14446. if (!address_space.empty())
  14447. {
  14448. if (is_pointer(data_type))
  14449. {
  14450. if (*cv_qualifier == '\0')
  14451. decl += ' ';
  14452. decl += join(address_space, " ");
  14453. }
  14454. else
  14455. decl = join(address_space, " ", decl);
  14456. }
  14457. decl += "&";
  14458. decl += " ";
  14459. decl += to_restrict(name_id, true);
  14460. decl += to_expression(name_id);
  14461. }
  14462. else if (type_is_image || type_is_tlas)
  14463. {
  14464. if (is_var_runtime_size_array(var))
  14465. {
  14466. decl = address_space + " " + decl + " " + to_expression(name_id);
  14467. }
  14468. else if (type.array.empty())
  14469. {
  14470. // For non-arrayed types we can just pass opaque descriptors by value.
  14471. // This fixes problems if descriptors are passed by value from argument buffers and plain descriptors
  14472. // in same shader.
  14473. // There is no address space we can actually use, but value will work.
  14474. // This will break if applications attempt to pass down descriptor arrays as arguments, but
  14475. // fortunately that is extremely unlikely ...
  14476. decl += " ";
  14477. decl += to_expression(name_id);
  14478. }
  14479. else
  14480. {
  14481. const char *img_address_space = descriptor_address_space(name_id, type_storage, "thread const");
  14482. decl = join(img_address_space, " ", decl);
  14483. decl += "& ";
  14484. decl += to_expression(name_id);
  14485. }
  14486. }
  14487. else
  14488. {
  14489. if (!address_space.empty())
  14490. decl = join(address_space, " ", decl);
  14491. decl += " ";
  14492. decl += to_expression(name_id);
  14493. }
  14494. // Emulate texture2D atomic operations
  14495. auto *backing_var = maybe_get_backing_variable(name_id);
  14496. if (backing_var && atomic_image_vars_emulated.count(backing_var->self))
  14497. {
  14498. auto &flags = ir.get_decoration_bitset(backing_var->self);
  14499. const char *cv_flags = decoration_flags_signal_volatile(flags) ? "volatile " : "";
  14500. decl += join(", ", cv_flags, "device atomic_", type_to_glsl(get<SPIRType>(var_type.image.type), 0));
  14501. decl += "* " + to_expression(name_id) + "_atomic";
  14502. }
  14503. is_using_builtin_array = false;
  14504. return decl;
  14505. }
  14506. // If we're currently in the entry point function, and the object
  14507. // has a qualified name, use it, otherwise use the standard name.
  14508. string CompilerMSL::to_name(uint32_t id, bool allow_alias) const
  14509. {
  14510. if (current_function && (current_function->self == ir.default_entry_point))
  14511. {
  14512. auto *m = ir.find_meta(id);
  14513. if (m && !m->decoration.qualified_alias_explicit_override && !m->decoration.qualified_alias.empty())
  14514. return m->decoration.qualified_alias;
  14515. }
  14516. return Compiler::to_name(id, allow_alias);
  14517. }
  14518. // Appends the name of the member to the variable qualifier string, except for Builtins.
  14519. string CompilerMSL::append_member_name(const string &qualifier, const SPIRType &type, uint32_t index)
  14520. {
  14521. // Don't qualify Builtin names because they are unique and are treated as such when building expressions
  14522. BuiltIn builtin = BuiltInMax;
  14523. if (is_member_builtin(type, index, &builtin))
  14524. return builtin_to_glsl(builtin, type.storage);
  14525. // Strip any underscore prefix from member name
  14526. string mbr_name = to_member_name(type, index);
  14527. size_t startPos = mbr_name.find_first_not_of("_");
  14528. mbr_name = (startPos != string::npos) ? mbr_name.substr(startPos) : "";
  14529. return join(qualifier, "_", mbr_name);
  14530. }
  14531. // Ensures that the specified name is permanently usable by prepending a prefix
  14532. // if the first chars are _ and a digit, which indicate a transient name.
  14533. string CompilerMSL::ensure_valid_name(string name, string pfx)
  14534. {
  14535. return (name.size() >= 2 && name[0] == '_' && isdigit(name[1])) ? (pfx + name) : name;
  14536. }
  14537. const std::unordered_set<std::string> &CompilerMSL::get_reserved_keyword_set()
  14538. {
  14539. static const unordered_set<string> keywords = {
  14540. "kernel",
  14541. "vertex",
  14542. "fragment",
  14543. "compute",
  14544. "constant",
  14545. "device",
  14546. "bias",
  14547. "level",
  14548. "gradient2d",
  14549. "gradientcube",
  14550. "gradient3d",
  14551. "min_lod_clamp",
  14552. "assert",
  14553. "VARIABLE_TRACEPOINT",
  14554. "STATIC_DATA_TRACEPOINT",
  14555. "STATIC_DATA_TRACEPOINT_V",
  14556. "METAL_ALIGN",
  14557. "METAL_ASM",
  14558. "METAL_CONST",
  14559. "METAL_DEPRECATED",
  14560. "METAL_ENABLE_IF",
  14561. "METAL_FUNC",
  14562. "METAL_INTERNAL",
  14563. "METAL_NON_NULL_RETURN",
  14564. "METAL_NORETURN",
  14565. "METAL_NOTHROW",
  14566. "METAL_PURE",
  14567. "METAL_UNAVAILABLE",
  14568. "METAL_IMPLICIT",
  14569. "METAL_EXPLICIT",
  14570. "METAL_CONST_ARG",
  14571. "METAL_ARG_UNIFORM",
  14572. "METAL_ZERO_ARG",
  14573. "METAL_VALID_LOD_ARG",
  14574. "METAL_VALID_LEVEL_ARG",
  14575. "METAL_VALID_STORE_ORDER",
  14576. "METAL_VALID_LOAD_ORDER",
  14577. "METAL_VALID_COMPARE_EXCHANGE_FAILURE_ORDER",
  14578. "METAL_COMPATIBLE_COMPARE_EXCHANGE_ORDERS",
  14579. "METAL_VALID_RENDER_TARGET",
  14580. "is_function_constant_defined",
  14581. "CHAR_BIT",
  14582. "SCHAR_MAX",
  14583. "SCHAR_MIN",
  14584. "UCHAR_MAX",
  14585. "CHAR_MAX",
  14586. "CHAR_MIN",
  14587. "USHRT_MAX",
  14588. "SHRT_MAX",
  14589. "SHRT_MIN",
  14590. "UINT_MAX",
  14591. "INT_MAX",
  14592. "INT_MIN",
  14593. "FLT_DIG",
  14594. "FLT_MANT_DIG",
  14595. "FLT_MAX_10_EXP",
  14596. "FLT_MAX_EXP",
  14597. "FLT_MIN_10_EXP",
  14598. "FLT_MIN_EXP",
  14599. "FLT_RADIX",
  14600. "FLT_MAX",
  14601. "FLT_MIN",
  14602. "FLT_EPSILON",
  14603. "FP_ILOGB0",
  14604. "FP_ILOGBNAN",
  14605. "MAXFLOAT",
  14606. "HUGE_VALF",
  14607. "INFINITY",
  14608. "NAN",
  14609. "M_E_F",
  14610. "M_LOG2E_F",
  14611. "M_LOG10E_F",
  14612. "M_LN2_F",
  14613. "M_LN10_F",
  14614. "M_PI_F",
  14615. "M_PI_2_F",
  14616. "M_PI_4_F",
  14617. "M_1_PI_F",
  14618. "M_2_PI_F",
  14619. "M_2_SQRTPI_F",
  14620. "M_SQRT2_F",
  14621. "M_SQRT1_2_F",
  14622. "HALF_DIG",
  14623. "HALF_MANT_DIG",
  14624. "HALF_MAX_10_EXP",
  14625. "HALF_MAX_EXP",
  14626. "HALF_MIN_10_EXP",
  14627. "HALF_MIN_EXP",
  14628. "HALF_RADIX",
  14629. "HALF_MAX",
  14630. "HALF_MIN",
  14631. "HALF_EPSILON",
  14632. "MAXHALF",
  14633. "HUGE_VALH",
  14634. "M_E_H",
  14635. "M_LOG2E_H",
  14636. "M_LOG10E_H",
  14637. "M_LN2_H",
  14638. "M_LN10_H",
  14639. "M_PI_H",
  14640. "M_PI_2_H",
  14641. "M_PI_4_H",
  14642. "M_1_PI_H",
  14643. "M_2_PI_H",
  14644. "M_2_SQRTPI_H",
  14645. "M_SQRT2_H",
  14646. "M_SQRT1_2_H",
  14647. "DBL_DIG",
  14648. "DBL_MANT_DIG",
  14649. "DBL_MAX_10_EXP",
  14650. "DBL_MAX_EXP",
  14651. "DBL_MIN_10_EXP",
  14652. "DBL_MIN_EXP",
  14653. "DBL_RADIX",
  14654. "DBL_MAX",
  14655. "DBL_MIN",
  14656. "DBL_EPSILON",
  14657. "HUGE_VAL",
  14658. "M_E",
  14659. "M_LOG2E",
  14660. "M_LOG10E",
  14661. "M_LN2",
  14662. "M_LN10",
  14663. "M_PI",
  14664. "M_PI_2",
  14665. "M_PI_4",
  14666. "M_1_PI",
  14667. "M_2_PI",
  14668. "M_2_SQRTPI",
  14669. "M_SQRT2",
  14670. "M_SQRT1_2",
  14671. "quad_broadcast",
  14672. "thread",
  14673. "threadgroup",
  14674. "signed",
  14675. };
  14676. return keywords;
  14677. }
  14678. const std::unordered_set<std::string> &CompilerMSL::get_illegal_func_names()
  14679. {
  14680. static const unordered_set<string> illegal_func_names = {
  14681. "main",
  14682. "fragment",
  14683. "vertex",
  14684. "kernel",
  14685. "saturate",
  14686. "assert",
  14687. "fmin3",
  14688. "fmax3",
  14689. "divide",
  14690. "fmod",
  14691. "median3",
  14692. "VARIABLE_TRACEPOINT",
  14693. "STATIC_DATA_TRACEPOINT",
  14694. "STATIC_DATA_TRACEPOINT_V",
  14695. "METAL_ALIGN",
  14696. "METAL_ASM",
  14697. "METAL_CONST",
  14698. "METAL_DEPRECATED",
  14699. "METAL_ENABLE_IF",
  14700. "METAL_FUNC",
  14701. "METAL_INTERNAL",
  14702. "METAL_NON_NULL_RETURN",
  14703. "METAL_NORETURN",
  14704. "METAL_NOTHROW",
  14705. "METAL_PURE",
  14706. "METAL_UNAVAILABLE",
  14707. "METAL_IMPLICIT",
  14708. "METAL_EXPLICIT",
  14709. "METAL_CONST_ARG",
  14710. "METAL_ARG_UNIFORM",
  14711. "METAL_ZERO_ARG",
  14712. "METAL_VALID_LOD_ARG",
  14713. "METAL_VALID_LEVEL_ARG",
  14714. "METAL_VALID_STORE_ORDER",
  14715. "METAL_VALID_LOAD_ORDER",
  14716. "METAL_VALID_COMPARE_EXCHANGE_FAILURE_ORDER",
  14717. "METAL_COMPATIBLE_COMPARE_EXCHANGE_ORDERS",
  14718. "METAL_VALID_RENDER_TARGET",
  14719. "is_function_constant_defined",
  14720. "CHAR_BIT",
  14721. "SCHAR_MAX",
  14722. "SCHAR_MIN",
  14723. "UCHAR_MAX",
  14724. "CHAR_MAX",
  14725. "CHAR_MIN",
  14726. "USHRT_MAX",
  14727. "SHRT_MAX",
  14728. "SHRT_MIN",
  14729. "UINT_MAX",
  14730. "INT_MAX",
  14731. "INT_MIN",
  14732. "FLT_DIG",
  14733. "FLT_MANT_DIG",
  14734. "FLT_MAX_10_EXP",
  14735. "FLT_MAX_EXP",
  14736. "FLT_MIN_10_EXP",
  14737. "FLT_MIN_EXP",
  14738. "FLT_RADIX",
  14739. "FLT_MAX",
  14740. "FLT_MIN",
  14741. "FLT_EPSILON",
  14742. "FP_ILOGB0",
  14743. "FP_ILOGBNAN",
  14744. "MAXFLOAT",
  14745. "HUGE_VALF",
  14746. "INFINITY",
  14747. "NAN",
  14748. "M_E_F",
  14749. "M_LOG2E_F",
  14750. "M_LOG10E_F",
  14751. "M_LN2_F",
  14752. "M_LN10_F",
  14753. "M_PI_F",
  14754. "M_PI_2_F",
  14755. "M_PI_4_F",
  14756. "M_1_PI_F",
  14757. "M_2_PI_F",
  14758. "M_2_SQRTPI_F",
  14759. "M_SQRT2_F",
  14760. "M_SQRT1_2_F",
  14761. "HALF_DIG",
  14762. "HALF_MANT_DIG",
  14763. "HALF_MAX_10_EXP",
  14764. "HALF_MAX_EXP",
  14765. "HALF_MIN_10_EXP",
  14766. "HALF_MIN_EXP",
  14767. "HALF_RADIX",
  14768. "HALF_MAX",
  14769. "HALF_MIN",
  14770. "HALF_EPSILON",
  14771. "MAXHALF",
  14772. "HUGE_VALH",
  14773. "M_E_H",
  14774. "M_LOG2E_H",
  14775. "M_LOG10E_H",
  14776. "M_LN2_H",
  14777. "M_LN10_H",
  14778. "M_PI_H",
  14779. "M_PI_2_H",
  14780. "M_PI_4_H",
  14781. "M_1_PI_H",
  14782. "M_2_PI_H",
  14783. "M_2_SQRTPI_H",
  14784. "M_SQRT2_H",
  14785. "M_SQRT1_2_H",
  14786. "DBL_DIG",
  14787. "DBL_MANT_DIG",
  14788. "DBL_MAX_10_EXP",
  14789. "DBL_MAX_EXP",
  14790. "DBL_MIN_10_EXP",
  14791. "DBL_MIN_EXP",
  14792. "DBL_RADIX",
  14793. "DBL_MAX",
  14794. "DBL_MIN",
  14795. "DBL_EPSILON",
  14796. "HUGE_VAL",
  14797. "M_E",
  14798. "M_LOG2E",
  14799. "M_LOG10E",
  14800. "M_LN2",
  14801. "M_LN10",
  14802. "M_PI",
  14803. "M_PI_2",
  14804. "M_PI_4",
  14805. "M_1_PI",
  14806. "M_2_PI",
  14807. "M_2_SQRTPI",
  14808. "M_SQRT2",
  14809. "M_SQRT1_2",
  14810. "int8",
  14811. "uint8",
  14812. "int16",
  14813. "uint16",
  14814. "float8",
  14815. "float16",
  14816. "signed",
  14817. };
  14818. return illegal_func_names;
  14819. }
  14820. // Replace all names that match MSL keywords or Metal Standard Library functions.
  14821. void CompilerMSL::replace_illegal_names()
  14822. {
  14823. // FIXME: MSL and GLSL are doing two different things here.
  14824. // Agree on convention and remove this override.
  14825. auto &keywords = get_reserved_keyword_set();
  14826. auto &illegal_func_names = get_illegal_func_names();
  14827. ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, SPIRVariable &) {
  14828. auto *meta = ir.find_meta(self);
  14829. if (!meta)
  14830. return;
  14831. auto &dec = meta->decoration;
  14832. if (keywords.find(dec.alias) != end(keywords))
  14833. dec.alias += "0";
  14834. });
  14835. ir.for_each_typed_id<SPIRFunction>([&](uint32_t self, SPIRFunction &) {
  14836. auto *meta = ir.find_meta(self);
  14837. if (!meta)
  14838. return;
  14839. auto &dec = meta->decoration;
  14840. if (illegal_func_names.find(dec.alias) != end(illegal_func_names))
  14841. dec.alias += "0";
  14842. });
  14843. ir.for_each_typed_id<SPIRType>([&](uint32_t self, SPIRType &) {
  14844. auto *meta = ir.find_meta(self);
  14845. if (!meta)
  14846. return;
  14847. for (auto &mbr_dec : meta->members)
  14848. if (keywords.find(mbr_dec.alias) != end(keywords))
  14849. mbr_dec.alias += "0";
  14850. });
  14851. CompilerGLSL::replace_illegal_names();
  14852. }
  14853. void CompilerMSL::replace_illegal_entry_point_names()
  14854. {
  14855. auto &illegal_func_names = get_illegal_func_names();
  14856. // It is important to this before we fixup identifiers,
  14857. // since if ep_name is reserved, we will need to fix that up,
  14858. // and then copy alias back into entry.name after the fixup.
  14859. for (auto &entry : ir.entry_points)
  14860. {
  14861. // Change both the entry point name and the alias, to keep them synced.
  14862. string &ep_name = entry.second.name;
  14863. if (illegal_func_names.find(ep_name) != end(illegal_func_names))
  14864. ep_name += "0";
  14865. ir.meta[entry.first].decoration.alias = ep_name;
  14866. }
  14867. }
  14868. void CompilerMSL::sync_entry_point_aliases_and_names()
  14869. {
  14870. for (auto &entry : ir.entry_points)
  14871. entry.second.name = ir.meta[entry.first].decoration.alias;
  14872. }
  14873. string CompilerMSL::to_member_reference(uint32_t base, const SPIRType &type, uint32_t index, bool ptr_chain_is_resolved)
  14874. {
  14875. auto *var = maybe_get_backing_variable(base);
  14876. // If this is a buffer array, we have to dereference the buffer pointers.
  14877. // Otherwise, if this is a pointer expression, dereference it.
  14878. bool declared_as_pointer = false;
  14879. if (var)
  14880. {
  14881. // Only allow -> dereference for block types. This is so we get expressions like
  14882. // buffer[i]->first_member.second_member, rather than buffer[i]->first->second.
  14883. const bool is_block =
  14884. has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock);
  14885. bool is_buffer_variable =
  14886. is_block && (var->storage == StorageClassUniform || var->storage == StorageClassStorageBuffer);
  14887. declared_as_pointer = is_buffer_variable && is_array(get_pointee_type(var->basetype));
  14888. }
  14889. if (declared_as_pointer || (!ptr_chain_is_resolved && should_dereference(base)))
  14890. return join("->", to_member_name(type, index));
  14891. else
  14892. return join(".", to_member_name(type, index));
  14893. }
  14894. string CompilerMSL::to_qualifiers_glsl(uint32_t id)
  14895. {
  14896. string quals;
  14897. auto *var = maybe_get<SPIRVariable>(id);
  14898. auto &type = expression_type(id);
  14899. if (type.storage == StorageClassTaskPayloadWorkgroupEXT)
  14900. quals += "object_data ";
  14901. if (type.storage == StorageClassWorkgroup || (var && variable_decl_is_remapped_storage(*var, StorageClassWorkgroup)))
  14902. quals += "threadgroup ";
  14903. return quals;
  14904. }
  14905. // The optional id parameter indicates the object whose type we are trying
  14906. // to find the description for. It is optional. Most type descriptions do not
  14907. // depend on a specific object's use of that type.
  14908. string CompilerMSL::type_to_glsl(const SPIRType &type, uint32_t id, bool member)
  14909. {
  14910. string type_name;
  14911. // Pointer?
  14912. if (is_pointer(type) || type_is_array_of_pointers(type))
  14913. {
  14914. assert(type.pointer_depth > 0);
  14915. const char *restrict_kw;
  14916. auto type_address_space = get_type_address_space(type, id);
  14917. const auto *p_parent_type = &get<SPIRType>(type.parent_type);
  14918. // If we're wrapping buffer descriptors in a spvDescriptorArray, we'll have to handle it as a special case.
  14919. if (member && id)
  14920. {
  14921. auto &var = get<SPIRVariable>(id);
  14922. if (is_var_runtime_size_array(var) && is_runtime_size_array(*p_parent_type))
  14923. {
  14924. const bool ssbo = has_decoration(p_parent_type->self, DecorationBufferBlock);
  14925. bool buffer_desc =
  14926. (var.storage == StorageClassStorageBuffer || ssbo) &&
  14927. msl_options.runtime_array_rich_descriptor;
  14928. const char *wrapper_type = buffer_desc ? "spvBufferDescriptor" : "spvDescriptor";
  14929. add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray);
  14930. add_spv_func_and_recompile(buffer_desc ? SPVFuncImplVariableSizedDescriptor : SPVFuncImplVariableDescriptor);
  14931. type_name = join(wrapper_type, "<", type_address_space, " ", type_to_glsl(*p_parent_type, id), " *>");
  14932. return type_name;
  14933. }
  14934. }
  14935. // Work around C pointer qualifier rules. If glsl_type is a pointer type as well
  14936. // we'll need to emit the address space to the right.
  14937. // We could always go this route, but it makes the code unnatural.
  14938. // Prefer emitting thread T *foo over T thread* foo since it's more readable,
  14939. // but we'll have to emit thread T * thread * T constant bar; for example.
  14940. if (is_pointer(type) && is_pointer(*p_parent_type))
  14941. type_name = join(type_to_glsl(*p_parent_type, id), " ", type_address_space, " ");
  14942. else
  14943. {
  14944. // Since this is not a pointer-to-pointer, ensure we've dug down to the base type.
  14945. // Some situations chain pointers even though they are not formally pointers-of-pointers.
  14946. while (is_pointer(*p_parent_type))
  14947. p_parent_type = &get<SPIRType>(p_parent_type->parent_type);
  14948. // If we're emitting BDA, just use the templated type.
  14949. // Emitting builtin arrays need a lot of cooperation with other code to ensure
  14950. // the C-style nesting works right.
  14951. // FIXME: This is somewhat of a hack.
  14952. bool old_is_using_builtin_array = is_using_builtin_array;
  14953. bool pointer_to_buffer_array = is_pointer(type) && has_decoration(type.parent_type, DecorationArrayStride);
  14954. if (is_physical_pointer(type))
  14955. is_using_builtin_array = false;
  14956. else if (pointer_to_buffer_array)
  14957. is_using_builtin_array = true;
  14958. type_name = join(type_address_space, " ", type_to_glsl(*p_parent_type, id));
  14959. is_using_builtin_array = old_is_using_builtin_array;
  14960. }
  14961. switch (type.basetype)
  14962. {
  14963. case SPIRType::Image:
  14964. case SPIRType::SampledImage:
  14965. case SPIRType::Sampler:
  14966. // These are handles.
  14967. break;
  14968. default:
  14969. // Anything else can be a raw pointer.
  14970. type_name += "*";
  14971. restrict_kw = to_restrict(id, false);
  14972. if (*restrict_kw)
  14973. {
  14974. type_name += " ";
  14975. type_name += restrict_kw;
  14976. }
  14977. break;
  14978. }
  14979. return type_name;
  14980. }
  14981. switch (type.basetype)
  14982. {
  14983. case SPIRType::Struct:
  14984. // Need OpName lookup here to get a "sensible" name for a struct.
  14985. // Allow Metal to use the array<T> template to make arrays a value type
  14986. type_name = to_name(type.self);
  14987. break;
  14988. case SPIRType::Image:
  14989. case SPIRType::SampledImage:
  14990. return image_type_glsl(type, id, member);
  14991. case SPIRType::Sampler:
  14992. return sampler_type(type, id, member);
  14993. case SPIRType::Void:
  14994. return "void";
  14995. case SPIRType::AtomicCounter:
  14996. return "atomic_uint";
  14997. case SPIRType::ControlPointArray:
  14998. return join("patch_control_point<", type_to_glsl(get<SPIRType>(type.parent_type), id), ">");
  14999. case SPIRType::Interpolant:
  15000. return join("interpolant<", type_to_glsl(get<SPIRType>(type.parent_type), id), ", interpolation::",
  15001. has_decoration(type.self, DecorationNoPerspective) ? "no_perspective" : "perspective", ">");
  15002. // Scalars
  15003. case SPIRType::Boolean:
  15004. {
  15005. auto *var = maybe_get_backing_variable(id);
  15006. if (var && var->basevariable)
  15007. var = &get<SPIRVariable>(var->basevariable);
  15008. // Need to special-case threadgroup booleans. They are supposed to be logical
  15009. // storage, but MSL compilers will sometimes crash if you use threadgroup bool.
  15010. // Workaround this by using 16-bit types instead and fixup on load-store to this data.
  15011. if ((var && var->storage == StorageClassWorkgroup) || type.storage == StorageClassWorkgroup || member)
  15012. type_name = "short";
  15013. else
  15014. type_name = "bool";
  15015. break;
  15016. }
  15017. case SPIRType::Char:
  15018. case SPIRType::SByte:
  15019. type_name = "char";
  15020. break;
  15021. case SPIRType::UByte:
  15022. type_name = "uchar";
  15023. break;
  15024. case SPIRType::Short:
  15025. type_name = "short";
  15026. break;
  15027. case SPIRType::UShort:
  15028. type_name = "ushort";
  15029. break;
  15030. case SPIRType::Int:
  15031. type_name = "int";
  15032. break;
  15033. case SPIRType::UInt:
  15034. type_name = "uint";
  15035. break;
  15036. case SPIRType::Int64:
  15037. if (!msl_options.supports_msl_version(2, 2))
  15038. SPIRV_CROSS_THROW("64-bit integers are only supported in MSL 2.2 and above.");
  15039. type_name = "long";
  15040. break;
  15041. case SPIRType::UInt64:
  15042. if (!msl_options.supports_msl_version(2, 2))
  15043. SPIRV_CROSS_THROW("64-bit integers are only supported in MSL 2.2 and above.");
  15044. type_name = "ulong";
  15045. break;
  15046. case SPIRType::Half:
  15047. type_name = "half";
  15048. break;
  15049. case SPIRType::Float:
  15050. type_name = "float";
  15051. break;
  15052. case SPIRType::Double:
  15053. type_name = "double"; // Currently unsupported
  15054. break;
  15055. case SPIRType::AccelerationStructure:
  15056. if (msl_options.supports_msl_version(2, 4))
  15057. type_name = "raytracing::acceleration_structure<raytracing::instancing>";
  15058. else if (msl_options.supports_msl_version(2, 3))
  15059. type_name = "raytracing::instance_acceleration_structure";
  15060. else
  15061. SPIRV_CROSS_THROW("Acceleration Structure Type is supported in MSL 2.3 and above.");
  15062. break;
  15063. case SPIRType::RayQuery:
  15064. return "raytracing::intersection_query<raytracing::instancing, raytracing::triangle_data>";
  15065. case SPIRType::MeshGridProperties:
  15066. return "mesh_grid_properties";
  15067. default:
  15068. return "unknown_type";
  15069. }
  15070. // Matrix?
  15071. if (type.columns > 1)
  15072. {
  15073. auto *var = maybe_get_backing_variable(id);
  15074. if (var && var->basevariable)
  15075. var = &get<SPIRVariable>(var->basevariable);
  15076. // Need to special-case threadgroup matrices. Due to an oversight, Metal's
  15077. // matrix struct prior to Metal 3 lacks constructors in the threadgroup AS,
  15078. // preventing us from default-constructing or initializing matrices in threadgroup storage.
  15079. // Work around this by using our own type as storage.
  15080. if (((var && var->storage == StorageClassWorkgroup) || type.storage == StorageClassWorkgroup) &&
  15081. !msl_options.supports_msl_version(3, 0))
  15082. {
  15083. add_spv_func_and_recompile(SPVFuncImplStorageMatrix);
  15084. type_name = "spvStorage_" + type_name;
  15085. }
  15086. type_name += to_string(type.columns) + "x";
  15087. }
  15088. // Vector or Matrix?
  15089. if (type.vecsize > 1)
  15090. type_name += to_string(type.vecsize);
  15091. if (type.array.empty() || using_builtin_array())
  15092. {
  15093. return type_name;
  15094. }
  15095. else
  15096. {
  15097. // Allow Metal to use the array<T> template to make arrays a value type
  15098. add_spv_func_and_recompile(SPVFuncImplUnsafeArray);
  15099. string res;
  15100. string sizes;
  15101. for (uint32_t i = 0; i < uint32_t(type.array.size()); i++)
  15102. {
  15103. res += "spvUnsafeArray<";
  15104. sizes += ", ";
  15105. sizes += to_array_size(type, i);
  15106. sizes += ">";
  15107. }
  15108. res += type_name + sizes;
  15109. return res;
  15110. }
  15111. }
  15112. string CompilerMSL::type_to_glsl(const SPIRType &type, uint32_t id)
  15113. {
  15114. return type_to_glsl(type, id, false);
  15115. }
  15116. string CompilerMSL::type_to_array_glsl(const SPIRType &type, uint32_t variable_id)
  15117. {
  15118. // Allow Metal to use the array<T> template to make arrays a value type
  15119. switch (type.basetype)
  15120. {
  15121. case SPIRType::AtomicCounter:
  15122. case SPIRType::ControlPointArray:
  15123. case SPIRType::RayQuery:
  15124. return CompilerGLSL::type_to_array_glsl(type, variable_id);
  15125. default:
  15126. if (type_is_array_of_pointers(type) || using_builtin_array())
  15127. {
  15128. const SPIRVariable *var = variable_id ? maybe_get<SPIRVariable>(variable_id) : nullptr;
  15129. if (var && (var->storage == StorageClassUniform || var->storage == StorageClassStorageBuffer) &&
  15130. is_array(get_variable_data_type(*var)))
  15131. {
  15132. return join("[", get_resource_array_size(type, variable_id), "]");
  15133. }
  15134. else
  15135. return CompilerGLSL::type_to_array_glsl(type, variable_id);
  15136. }
  15137. else
  15138. return "";
  15139. }
  15140. }
  15141. string CompilerMSL::constant_op_expression(const SPIRConstantOp &cop)
  15142. {
  15143. switch (cop.opcode)
  15144. {
  15145. case OpSMod:
  15146. add_spv_func_and_recompile(SPVFuncImplSMod);
  15147. return join("spvSMod(", to_expression(cop.arguments[0]), ", ", to_expression(cop.arguments[1]), ")");
  15148. case OpQuantizeToF16:
  15149. add_spv_func_and_recompile(SPVFuncImplQuantizeToF16);
  15150. return join("spvQuantizeToF16(", to_expression(cop.arguments[0]), ")");
  15151. default:
  15152. return CompilerGLSL::constant_op_expression(cop);
  15153. }
  15154. }
  15155. bool CompilerMSL::variable_decl_is_remapped_storage(const SPIRVariable &variable, StorageClass storage) const
  15156. {
  15157. if (variable.storage == storage)
  15158. return true;
  15159. if (storage == StorageClassWorkgroup)
  15160. {
  15161. // Specially masked IO block variable.
  15162. // Normally, we will never access IO blocks directly here.
  15163. // The only scenario which that should occur is with a masked IO block.
  15164. if (is_tesc_shader() && variable.storage == StorageClassOutput &&
  15165. has_decoration(get<SPIRType>(variable.basetype).self, DecorationBlock))
  15166. {
  15167. return true;
  15168. }
  15169. if (is_mesh_shader())
  15170. return variable.storage == StorageClassOutput;
  15171. return variable.storage == StorageClassOutput && is_tesc_shader() && is_stage_output_variable_masked(variable);
  15172. }
  15173. else if (storage == StorageClassStorageBuffer)
  15174. {
  15175. // These builtins are passed directly; we don't want to use remapping
  15176. // for them.
  15177. auto builtin = (BuiltIn)get_decoration(variable.self, DecorationBuiltIn);
  15178. if (is_tese_shader() && is_builtin_variable(variable) && (builtin == BuiltInTessCoord || builtin == BuiltInPrimitiveId))
  15179. return false;
  15180. // We won't be able to catch writes to control point outputs here since variable
  15181. // refers to a function local pointer.
  15182. // This is fine, as there cannot be concurrent writers to that memory anyways,
  15183. // so we just ignore that case.
  15184. return (variable.storage == StorageClassOutput || variable.storage == StorageClassInput) &&
  15185. !variable_storage_requires_stage_io(variable.storage) &&
  15186. (variable.storage != StorageClassOutput || !is_stage_output_variable_masked(variable));
  15187. }
  15188. else
  15189. {
  15190. return false;
  15191. }
  15192. }
  15193. // GCC workaround of lambdas calling protected funcs
  15194. std::string CompilerMSL::variable_decl(const SPIRType &type, const std::string &name, uint32_t id)
  15195. {
  15196. return CompilerGLSL::variable_decl(type, name, id);
  15197. }
  15198. std::string CompilerMSL::sampler_type(const SPIRType &type, uint32_t id, bool member)
  15199. {
  15200. auto *var = maybe_get<SPIRVariable>(id);
  15201. if (var && var->basevariable)
  15202. {
  15203. // Check against the base variable, and not a fake ID which might have been generated for this variable.
  15204. id = var->basevariable;
  15205. }
  15206. if (!type.array.empty())
  15207. {
  15208. if (!msl_options.supports_msl_version(2))
  15209. SPIRV_CROSS_THROW("MSL 2.0 or greater is required for arrays of samplers.");
  15210. if (type.array.size() > 1)
  15211. SPIRV_CROSS_THROW("Arrays of arrays of samplers are not supported in MSL.");
  15212. // Arrays of samplers in MSL must be declared with a special array<T, N> syntax ala C++11 std::array.
  15213. // If we have a runtime array, it could be a variable-count descriptor set binding.
  15214. auto &parent = get<SPIRType>(get_pointee_type(type).parent_type);
  15215. uint32_t array_size = get_resource_array_size(type, id);
  15216. if (array_size == 0)
  15217. {
  15218. add_spv_func_and_recompile(SPVFuncImplVariableDescriptor);
  15219. add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray);
  15220. const char *descriptor_wrapper = processing_entry_point ? "const device spvDescriptor" : "const spvDescriptorArray";
  15221. if (member)
  15222. descriptor_wrapper = "spvDescriptor";
  15223. return join(descriptor_wrapper, "<", sampler_type(parent, id, false), ">",
  15224. processing_entry_point ? "*" : "");
  15225. }
  15226. else
  15227. {
  15228. return join("array<", sampler_type(parent, id, false), ", ", array_size, ">");
  15229. }
  15230. }
  15231. else
  15232. return "sampler";
  15233. }
  15234. // Returns an MSL string describing the SPIR-V image type
  15235. string CompilerMSL::image_type_glsl(const SPIRType &type, uint32_t id, bool member)
  15236. {
  15237. auto *var = maybe_get<SPIRVariable>(id);
  15238. if (var && var->basevariable)
  15239. {
  15240. // For comparison images, check against the base variable,
  15241. // and not the fake ID which might have been generated for this variable.
  15242. id = var->basevariable;
  15243. }
  15244. if (!type.array.empty())
  15245. {
  15246. uint32_t major = 2, minor = 0;
  15247. if (msl_options.is_ios())
  15248. {
  15249. major = 1;
  15250. minor = 2;
  15251. }
  15252. if (!msl_options.supports_msl_version(major, minor))
  15253. {
  15254. if (msl_options.is_ios())
  15255. SPIRV_CROSS_THROW("MSL 1.2 or greater is required for arrays of textures.");
  15256. else
  15257. SPIRV_CROSS_THROW("MSL 2.0 or greater is required for arrays of textures.");
  15258. }
  15259. if (type.array.size() > 1)
  15260. SPIRV_CROSS_THROW("Arrays of arrays of textures are not supported in MSL.");
  15261. // Arrays of images in MSL must be declared with a special array<T, N> syntax ala C++11 std::array.
  15262. // If we have a runtime array, it could be a variable-count descriptor set binding.
  15263. auto &parent = get<SPIRType>(get_pointee_type(type).parent_type);
  15264. uint32_t array_size = get_resource_array_size(type, id);
  15265. if (array_size == 0)
  15266. {
  15267. add_spv_func_and_recompile(SPVFuncImplVariableDescriptor);
  15268. add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray);
  15269. const char *descriptor_wrapper = processing_entry_point ? "const device spvDescriptor" : "const spvDescriptorArray";
  15270. if (member)
  15271. {
  15272. descriptor_wrapper = "spvDescriptor";
  15273. // This requires a specialized wrapper type that packs image and sampler side by side.
  15274. // It is possible in theory.
  15275. if (type.basetype == SPIRType::SampledImage)
  15276. SPIRV_CROSS_THROW("Argument buffer runtime array currently not supported for combined image sampler.");
  15277. }
  15278. return join(descriptor_wrapper, "<", image_type_glsl(parent, id, false), ">",
  15279. processing_entry_point ? "*" : "");
  15280. }
  15281. else
  15282. {
  15283. return join("array<", image_type_glsl(parent, id, false), ", ", array_size, ">");
  15284. }
  15285. }
  15286. string img_type_name;
  15287. auto &img_type = type.image;
  15288. if (is_depth_image(type, id))
  15289. {
  15290. switch (img_type.dim)
  15291. {
  15292. case Dim1D:
  15293. case Dim2D:
  15294. if (img_type.dim == Dim1D && !msl_options.texture_1D_as_2D)
  15295. {
  15296. // Use a native Metal 1D texture
  15297. img_type_name += "depth1d_unsupported_by_metal";
  15298. break;
  15299. }
  15300. if (img_type.ms && img_type.arrayed)
  15301. {
  15302. if (!msl_options.supports_msl_version(2, 1))
  15303. SPIRV_CROSS_THROW("Multisampled array textures are supported from 2.1.");
  15304. img_type_name += "depth2d_ms_array";
  15305. }
  15306. else if (img_type.ms)
  15307. img_type_name += "depth2d_ms";
  15308. else if (img_type.arrayed)
  15309. img_type_name += "depth2d_array";
  15310. else
  15311. img_type_name += "depth2d";
  15312. break;
  15313. case Dim3D:
  15314. img_type_name += "depth3d_unsupported_by_metal";
  15315. break;
  15316. case DimCube:
  15317. if (!msl_options.emulate_cube_array)
  15318. img_type_name += (img_type.arrayed ? "depthcube_array" : "depthcube");
  15319. else
  15320. img_type_name += (img_type.arrayed ? "depth2d_array" : "depthcube");
  15321. break;
  15322. default:
  15323. img_type_name += "unknown_depth_texture_type";
  15324. break;
  15325. }
  15326. }
  15327. else
  15328. {
  15329. switch (img_type.dim)
  15330. {
  15331. case DimBuffer:
  15332. if (img_type.ms || img_type.arrayed)
  15333. SPIRV_CROSS_THROW("Cannot use texel buffers with multisampling or array layers.");
  15334. if (msl_options.texture_buffer_native)
  15335. {
  15336. if (!msl_options.supports_msl_version(2, 1))
  15337. SPIRV_CROSS_THROW("Native texture_buffer type is only supported in MSL 2.1.");
  15338. img_type_name = "texture_buffer";
  15339. }
  15340. else
  15341. img_type_name += "texture2d";
  15342. break;
  15343. case Dim1D:
  15344. case Dim2D:
  15345. case DimSubpassData:
  15346. {
  15347. bool subpass_array =
  15348. img_type.dim == DimSubpassData && (msl_options.multiview || msl_options.arrayed_subpass_input);
  15349. if (img_type.dim == Dim1D && !msl_options.texture_1D_as_2D)
  15350. {
  15351. // Use a native Metal 1D texture
  15352. img_type_name += (img_type.arrayed ? "texture1d_array" : "texture1d");
  15353. break;
  15354. }
  15355. // Use Metal's native frame-buffer fetch API for subpass inputs.
  15356. if (type_is_msl_framebuffer_fetch(type))
  15357. {
  15358. auto img_type_4 = get<SPIRType>(img_type.type);
  15359. img_type_4.vecsize = 4;
  15360. return type_to_glsl(img_type_4);
  15361. }
  15362. if (img_type.ms && (img_type.arrayed || subpass_array))
  15363. {
  15364. if (!msl_options.supports_msl_version(2, 1))
  15365. SPIRV_CROSS_THROW("Multisampled array textures are supported from 2.1.");
  15366. img_type_name += "texture2d_ms_array";
  15367. }
  15368. else if (img_type.ms)
  15369. img_type_name += "texture2d_ms";
  15370. else if (img_type.arrayed || subpass_array)
  15371. img_type_name += "texture2d_array";
  15372. else
  15373. img_type_name += "texture2d";
  15374. break;
  15375. }
  15376. case Dim3D:
  15377. img_type_name += "texture3d";
  15378. break;
  15379. case DimCube:
  15380. if (!msl_options.emulate_cube_array)
  15381. img_type_name += (img_type.arrayed ? "texturecube_array" : "texturecube");
  15382. else
  15383. img_type_name += (img_type.arrayed ? "texture2d_array" : "texturecube");
  15384. break;
  15385. default:
  15386. img_type_name += "unknown_texture_type";
  15387. break;
  15388. }
  15389. }
  15390. // Append the pixel type
  15391. img_type_name += "<";
  15392. img_type_name += type_to_glsl(get<SPIRType>(img_type.type));
  15393. // For unsampled images, append the sample/read/write access qualifier.
  15394. // For kernel images, the access qualifier my be supplied directly by SPIR-V.
  15395. // Otherwise it may be set based on whether the image is read from or written to within the shader.
  15396. if (type.basetype == SPIRType::Image && type.image.sampled == 2 && type.image.dim != DimSubpassData)
  15397. {
  15398. auto *p_var = maybe_get_backing_variable(id);
  15399. if (p_var && p_var->basevariable)
  15400. p_var = maybe_get<SPIRVariable>(p_var->basevariable);
  15401. bool has_access_qualifier = true;
  15402. switch (img_type.access)
  15403. {
  15404. case AccessQualifierReadOnly:
  15405. img_type_name += ", access::read";
  15406. break;
  15407. case AccessQualifierWriteOnly:
  15408. img_type_name += ", access::write";
  15409. break;
  15410. case AccessQualifierReadWrite:
  15411. img_type_name += ", access::read_write";
  15412. break;
  15413. default:
  15414. {
  15415. if (p_var && !has_decoration(p_var->self, DecorationNonWritable))
  15416. {
  15417. img_type_name += ", access::";
  15418. if (!has_decoration(p_var->self, DecorationNonReadable))
  15419. img_type_name += "read_";
  15420. img_type_name += "write";
  15421. }
  15422. else
  15423. {
  15424. has_access_qualifier = false;
  15425. }
  15426. break;
  15427. }
  15428. }
  15429. if (p_var && has_decoration(p_var->self, DecorationCoherent) && msl_options.supports_msl_version(3, 2))
  15430. {
  15431. // Cannot declare memory_coherence_device without access qualifier.
  15432. if (!has_access_qualifier)
  15433. img_type_name += ", access::read";
  15434. img_type_name += ", memory_coherence_device";
  15435. }
  15436. }
  15437. img_type_name += ">";
  15438. return img_type_name;
  15439. }
  15440. void CompilerMSL::emit_subgroup_op(const Instruction &i)
  15441. {
  15442. const uint32_t *ops = stream(i);
  15443. auto op = static_cast<Op>(i.op);
  15444. if (msl_options.emulate_subgroups)
  15445. {
  15446. // In this mode, only the GroupNonUniform cap is supported. The only op
  15447. // we need to handle, then, is OpGroupNonUniformElect.
  15448. if (op != OpGroupNonUniformElect)
  15449. SPIRV_CROSS_THROW("Subgroup emulation does not support operations other than Elect.");
  15450. // In this mode, the subgroup size is assumed to be one, so every invocation
  15451. // is elected.
  15452. emit_op(ops[0], ops[1], "true", true);
  15453. return;
  15454. }
  15455. // Metal 2.0 is required. iOS only supports quad ops on 11.0 (2.0), with
  15456. // full support in 13.0 (2.2). macOS only supports broadcast and shuffle on
  15457. // 10.13 (2.0), with full support in 10.14 (2.1).
  15458. // Note that Apple GPUs before A13 make no distinction between a quad-group
  15459. // and a SIMD-group; all SIMD-groups are quad-groups on those.
  15460. if (!msl_options.supports_msl_version(2))
  15461. SPIRV_CROSS_THROW("Subgroups are only supported in Metal 2.0 and up.");
  15462. // If we need to do implicit bitcasts, make sure we do it with the correct type.
  15463. uint32_t integer_width = get_integer_width_for_instruction(i);
  15464. auto int_type = to_signed_basetype(integer_width);
  15465. auto uint_type = to_unsigned_basetype(integer_width);
  15466. if (msl_options.is_ios() && (!msl_options.supports_msl_version(2, 3) || !msl_options.ios_use_simdgroup_functions))
  15467. {
  15468. switch (op)
  15469. {
  15470. default:
  15471. SPIRV_CROSS_THROW("Subgroup ops beyond broadcast, ballot, and shuffle on iOS require Metal 2.3 and up.");
  15472. case OpGroupNonUniformBroadcastFirst:
  15473. if (!msl_options.supports_msl_version(2, 2))
  15474. SPIRV_CROSS_THROW("BroadcastFirst on iOS requires Metal 2.2 and up.");
  15475. break;
  15476. case OpGroupNonUniformElect:
  15477. if (!msl_options.supports_msl_version(2, 2))
  15478. SPIRV_CROSS_THROW("Elect on iOS requires Metal 2.2 and up.");
  15479. break;
  15480. case OpGroupNonUniformAny:
  15481. case OpGroupNonUniformAll:
  15482. case OpGroupNonUniformAllEqual:
  15483. case OpGroupNonUniformBallot:
  15484. case OpGroupNonUniformInverseBallot:
  15485. case OpGroupNonUniformBallotBitExtract:
  15486. case OpGroupNonUniformBallotFindLSB:
  15487. case OpGroupNonUniformBallotFindMSB:
  15488. case OpGroupNonUniformBallotBitCount:
  15489. case OpSubgroupBallotKHR:
  15490. case OpSubgroupAllKHR:
  15491. case OpSubgroupAnyKHR:
  15492. case OpSubgroupAllEqualKHR:
  15493. if (!msl_options.supports_msl_version(2, 2))
  15494. SPIRV_CROSS_THROW("Ballot ops on iOS requires Metal 2.2 and up.");
  15495. break;
  15496. case OpGroupNonUniformRotateKHR:
  15497. if (!msl_options.supports_msl_version(2, 2))
  15498. SPIRV_CROSS_THROW("Rotate on iOS requires Metal 2.2 and up.");
  15499. break;
  15500. case OpGroupNonUniformBroadcast:
  15501. case OpGroupNonUniformShuffle:
  15502. case OpGroupNonUniformShuffleXor:
  15503. case OpGroupNonUniformShuffleUp:
  15504. case OpGroupNonUniformShuffleDown:
  15505. case OpGroupNonUniformQuadSwap:
  15506. case OpGroupNonUniformQuadBroadcast:
  15507. case OpSubgroupReadInvocationKHR:
  15508. break;
  15509. }
  15510. }
  15511. if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1))
  15512. {
  15513. switch (op)
  15514. {
  15515. default:
  15516. SPIRV_CROSS_THROW("Subgroup ops beyond broadcast and shuffle on macOS require Metal 2.1 and up.");
  15517. case OpGroupNonUniformBroadcast:
  15518. case OpGroupNonUniformShuffle:
  15519. case OpGroupNonUniformShuffleXor:
  15520. case OpGroupNonUniformShuffleUp:
  15521. case OpGroupNonUniformShuffleDown:
  15522. case OpSubgroupReadInvocationKHR:
  15523. break;
  15524. }
  15525. }
  15526. uint32_t op_idx = 0;
  15527. uint32_t result_type = ops[op_idx++];
  15528. uint32_t id = ops[op_idx++];
  15529. Scope scope;
  15530. switch (op)
  15531. {
  15532. // These earlier instructions don't have the scope operand.
  15533. case OpSubgroupBallotKHR:
  15534. case OpSubgroupFirstInvocationKHR:
  15535. case OpSubgroupReadInvocationKHR:
  15536. case OpSubgroupAllKHR:
  15537. case OpSubgroupAnyKHR:
  15538. case OpSubgroupAllEqualKHR:
  15539. // These instructions are always quad-scoped and thus do not have a scope operand.
  15540. case OpGroupNonUniformQuadAllKHR:
  15541. case OpGroupNonUniformQuadAnyKHR:
  15542. scope = ScopeSubgroup;
  15543. break;
  15544. default:
  15545. scope = static_cast<Scope>(evaluate_constant_u32(ops[op_idx++]));
  15546. break;
  15547. }
  15548. if (scope != ScopeSubgroup)
  15549. SPIRV_CROSS_THROW("Only subgroup scope is supported.");
  15550. switch (op)
  15551. {
  15552. case OpGroupNonUniformElect:
  15553. if (msl_options.use_quadgroup_operation())
  15554. emit_op(result_type, id, "quad_is_first()", false);
  15555. else
  15556. emit_op(result_type, id, "simd_is_first()", false);
  15557. break;
  15558. case OpGroupNonUniformBroadcast:
  15559. case OpSubgroupReadInvocationKHR:
  15560. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupBroadcast");
  15561. break;
  15562. case OpGroupNonUniformBroadcastFirst:
  15563. case OpSubgroupFirstInvocationKHR:
  15564. emit_unary_func_op(result_type, id, ops[op_idx], "spvSubgroupBroadcastFirst");
  15565. break;
  15566. case OpGroupNonUniformBallot:
  15567. case OpSubgroupBallotKHR:
  15568. emit_unary_func_op(result_type, id, ops[op_idx], "spvSubgroupBallot");
  15569. break;
  15570. case OpGroupNonUniformInverseBallot:
  15571. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_invocation_id_id, "spvSubgroupBallotBitExtract");
  15572. break;
  15573. case OpGroupNonUniformBallotBitExtract:
  15574. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupBallotBitExtract");
  15575. break;
  15576. case OpGroupNonUniformBallotFindLSB:
  15577. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_size_id, "spvSubgroupBallotFindLSB");
  15578. break;
  15579. case OpGroupNonUniformBallotFindMSB:
  15580. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_size_id, "spvSubgroupBallotFindMSB");
  15581. break;
  15582. case OpGroupNonUniformBallotBitCount:
  15583. {
  15584. auto operation = static_cast<GroupOperation>(ops[op_idx++]);
  15585. switch (operation)
  15586. {
  15587. case GroupOperationReduce:
  15588. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_size_id, "spvSubgroupBallotBitCount");
  15589. break;
  15590. case GroupOperationInclusiveScan:
  15591. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_invocation_id_id,
  15592. "spvSubgroupBallotInclusiveBitCount");
  15593. break;
  15594. case GroupOperationExclusiveScan:
  15595. emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_invocation_id_id,
  15596. "spvSubgroupBallotExclusiveBitCount");
  15597. break;
  15598. default:
  15599. SPIRV_CROSS_THROW("Invalid BitCount operation.");
  15600. }
  15601. break;
  15602. }
  15603. case OpGroupNonUniformShuffle:
  15604. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffle");
  15605. break;
  15606. case OpGroupNonUniformShuffleXor:
  15607. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffleXor");
  15608. break;
  15609. case OpGroupNonUniformShuffleUp:
  15610. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffleUp");
  15611. break;
  15612. case OpGroupNonUniformShuffleDown:
  15613. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffleDown");
  15614. break;
  15615. case OpGroupNonUniformRotateKHR:
  15616. {
  15617. if (i.length > 5)
  15618. {
  15619. // MSL does not have a cluster size parameter, so calculate the invocation ID manually and using a shuffle.
  15620. auto delta_expr = enclose_expression(to_unpacked_expression(ops[op_idx + 1]));
  15621. auto cluster_size_minus_one = evaluate_constant_u32(ops[op_idx + 2]) - 1;
  15622. auto local_id_expr = to_unpacked_expression(scope == ScopeSubgroup
  15623. ? builtin_subgroup_invocation_id_id : builtin_local_invocation_index_id);
  15624. auto shuffle_idx = join("((", local_id_expr, " + ", delta_expr, ")", " & ", std::to_string(cluster_size_minus_one),
  15625. ") + (", local_id_expr, " & ", std::to_string(~cluster_size_minus_one), ")");
  15626. emit_op(result_type, id, join("spvSubgroupShuffle(", to_unpacked_expression(ops[op_idx]), ", ", shuffle_idx, ")"), false);
  15627. } else
  15628. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupRotate");
  15629. break;
  15630. }
  15631. case OpGroupNonUniformAll:
  15632. case OpSubgroupAllKHR:
  15633. if (msl_options.use_quadgroup_operation())
  15634. emit_unary_func_op(result_type, id, ops[op_idx], "quad_all");
  15635. else
  15636. emit_unary_func_op(result_type, id, ops[op_idx], "simd_all");
  15637. break;
  15638. case OpGroupNonUniformAny:
  15639. case OpSubgroupAnyKHR:
  15640. if (msl_options.use_quadgroup_operation())
  15641. emit_unary_func_op(result_type, id, ops[op_idx], "quad_any");
  15642. else
  15643. emit_unary_func_op(result_type, id, ops[op_idx], "simd_any");
  15644. break;
  15645. case OpGroupNonUniformAllEqual:
  15646. case OpSubgroupAllEqualKHR:
  15647. emit_unary_func_op(result_type, id, ops[op_idx], "spvSubgroupAllEqual");
  15648. break;
  15649. // clang-format off
  15650. #define MSL_GROUP_OP(op, msl_op) \
  15651. case OpGroupNonUniform##op: \
  15652. { \
  15653. auto operation = static_cast<GroupOperation>(ops[op_idx++]); \
  15654. if (operation == GroupOperationReduce) \
  15655. emit_unary_func_op(result_type, id, ops[op_idx], "simd_" #msl_op); \
  15656. else if (operation == GroupOperationInclusiveScan) \
  15657. emit_unary_func_op(result_type, id, ops[op_idx], "simd_prefix_inclusive_" #msl_op); \
  15658. else if (operation == GroupOperationExclusiveScan) \
  15659. emit_unary_func_op(result_type, id, ops[op_idx], "simd_prefix_exclusive_" #msl_op); \
  15660. else if (operation == GroupOperationClusteredReduce) \
  15661. { \
  15662. uint32_t cluster_size = evaluate_constant_u32(ops[op_idx + 1]); \
  15663. if (get_execution_model() != ExecutionModelFragment || msl_options.supports_msl_version(2, 2)) \
  15664. add_spv_func_and_recompile(SPVFuncImplSubgroupClustered##op); \
  15665. emit_subgroup_cluster_op(result_type, id, cluster_size, ops[op_idx], #msl_op); \
  15666. } \
  15667. else \
  15668. SPIRV_CROSS_THROW("Invalid group operation."); \
  15669. break; \
  15670. }
  15671. MSL_GROUP_OP(FAdd, sum)
  15672. MSL_GROUP_OP(FMul, product)
  15673. MSL_GROUP_OP(IAdd, sum)
  15674. MSL_GROUP_OP(IMul, product)
  15675. #undef MSL_GROUP_OP
  15676. // The others, unfortunately, don't support InclusiveScan or ExclusiveScan.
  15677. #define MSL_GROUP_OP(op, msl_op) \
  15678. case OpGroupNonUniform##op: \
  15679. { \
  15680. auto operation = static_cast<GroupOperation>(ops[op_idx++]); \
  15681. if (operation == GroupOperationReduce) \
  15682. emit_unary_func_op(result_type, id, ops[op_idx], "simd_" #msl_op); \
  15683. else if (operation == GroupOperationInclusiveScan) \
  15684. SPIRV_CROSS_THROW("Metal doesn't support InclusiveScan for OpGroupNonUniform" #op "."); \
  15685. else if (operation == GroupOperationExclusiveScan) \
  15686. SPIRV_CROSS_THROW("Metal doesn't support ExclusiveScan for OpGroupNonUniform" #op "."); \
  15687. else if (operation == GroupOperationClusteredReduce) \
  15688. { \
  15689. uint32_t cluster_size = evaluate_constant_u32(ops[op_idx + 1]); \
  15690. if (get_execution_model() != ExecutionModelFragment || msl_options.supports_msl_version(2, 2)) \
  15691. add_spv_func_and_recompile(SPVFuncImplSubgroupClustered##op); \
  15692. emit_subgroup_cluster_op(result_type, id, cluster_size, ops[op_idx], #msl_op); \
  15693. } \
  15694. else \
  15695. SPIRV_CROSS_THROW("Invalid group operation."); \
  15696. break; \
  15697. }
  15698. #define MSL_GROUP_OP_CAST(op, msl_op, type) \
  15699. case OpGroupNonUniform##op: \
  15700. { \
  15701. auto operation = static_cast<GroupOperation>(ops[op_idx++]); \
  15702. if (operation == GroupOperationReduce) \
  15703. emit_unary_func_op_cast(result_type, id, ops[op_idx], "simd_" #msl_op, type, type); \
  15704. else if (operation == GroupOperationInclusiveScan) \
  15705. SPIRV_CROSS_THROW("Metal doesn't support InclusiveScan for OpGroupNonUniform" #op "."); \
  15706. else if (operation == GroupOperationExclusiveScan) \
  15707. SPIRV_CROSS_THROW("Metal doesn't support ExclusiveScan for OpGroupNonUniform" #op "."); \
  15708. else if (operation == GroupOperationClusteredReduce) \
  15709. { \
  15710. uint32_t cluster_size = evaluate_constant_u32(ops[op_idx + 1]); \
  15711. if (get_execution_model() != ExecutionModelFragment || msl_options.supports_msl_version(2, 2)) \
  15712. add_spv_func_and_recompile(SPVFuncImplSubgroupClustered##op); \
  15713. emit_subgroup_cluster_op_cast(result_type, id, cluster_size, ops[op_idx], #msl_op, type, type); \
  15714. } \
  15715. else \
  15716. SPIRV_CROSS_THROW("Invalid group operation."); \
  15717. break; \
  15718. }
  15719. MSL_GROUP_OP(FMin, min)
  15720. MSL_GROUP_OP(FMax, max)
  15721. MSL_GROUP_OP_CAST(SMin, min, int_type)
  15722. MSL_GROUP_OP_CAST(SMax, max, int_type)
  15723. MSL_GROUP_OP_CAST(UMin, min, uint_type)
  15724. MSL_GROUP_OP_CAST(UMax, max, uint_type)
  15725. MSL_GROUP_OP(BitwiseAnd, and)
  15726. MSL_GROUP_OP(BitwiseOr, or)
  15727. MSL_GROUP_OP(BitwiseXor, xor)
  15728. // Metal doesn't support boolean types in SIMD-group operations, so we
  15729. // have to emit some casts.
  15730. MSL_GROUP_OP_CAST(LogicalAnd, and, SPIRType::UShort)
  15731. MSL_GROUP_OP_CAST(LogicalOr, or, SPIRType::UShort)
  15732. MSL_GROUP_OP_CAST(LogicalXor, xor, SPIRType::UShort)
  15733. // clang-format on
  15734. #undef MSL_GROUP_OP
  15735. #undef MSL_GROUP_OP_CAST
  15736. case OpGroupNonUniformQuadSwap:
  15737. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvQuadSwap");
  15738. break;
  15739. case OpGroupNonUniformQuadBroadcast:
  15740. emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvQuadBroadcast");
  15741. break;
  15742. case OpGroupNonUniformQuadAllKHR:
  15743. emit_unary_func_op(result_type, id, ops[op_idx], "quad_all");
  15744. break;
  15745. case OpGroupNonUniformQuadAnyKHR:
  15746. emit_unary_func_op(result_type, id, ops[op_idx], "quad_any");
  15747. break;
  15748. default:
  15749. SPIRV_CROSS_THROW("Invalid opcode for subgroup.");
  15750. }
  15751. register_control_dependent_expression(id);
  15752. }
  15753. void CompilerMSL::emit_subgroup_cluster_op(uint32_t result_type, uint32_t result_id, uint32_t cluster_size,
  15754. uint32_t op0, const char *op)
  15755. {
  15756. if (get_execution_model() == ExecutionModelFragment && !msl_options.supports_msl_version(2, 2))
  15757. {
  15758. if (cluster_size == 4)
  15759. {
  15760. emit_unary_func_op(result_type, result_id, op0, join("quad_", op).c_str());
  15761. return;
  15762. }
  15763. SPIRV_CROSS_THROW("Cluster sizes other than 4 in fragment shaders require MSL 2.2.");
  15764. }
  15765. bool forward = should_forward(op0);
  15766. emit_op(result_type, result_id,
  15767. join("spvClustered_", op, "<", cluster_size, ">(", to_unpacked_expression(op0), ", ",
  15768. to_expression(builtin_subgroup_invocation_id_id), ")"),
  15769. forward);
  15770. inherit_expression_dependencies(result_id, op0);
  15771. }
  15772. void CompilerMSL::emit_subgroup_cluster_op_cast(uint32_t result_type, uint32_t result_id, uint32_t cluster_size,
  15773. uint32_t op0, const char *op, SPIRType::BaseType input_type,
  15774. SPIRType::BaseType expected_result_type)
  15775. {
  15776. if (get_execution_model() == ExecutionModelFragment && !msl_options.supports_msl_version(2, 2))
  15777. {
  15778. if (cluster_size == 4)
  15779. {
  15780. emit_unary_func_op_cast(result_type, result_id, op0, join("quad_", op).c_str(), input_type,
  15781. expected_result_type);
  15782. return;
  15783. }
  15784. SPIRV_CROSS_THROW("Cluster sizes other than 4 in fragment shaders require MSL 2.2.");
  15785. }
  15786. auto &out_type = get<SPIRType>(result_type);
  15787. auto &expr_type = expression_type(op0);
  15788. auto expected_type = out_type;
  15789. // Bit-widths might be different in unary cases because we use it for SConvert/UConvert and friends.
  15790. expected_type.basetype = input_type;
  15791. expected_type.width = expr_type.width;
  15792. string cast_op;
  15793. if (expr_type.basetype != input_type)
  15794. {
  15795. if (expr_type.basetype == SPIRType::Boolean)
  15796. cast_op = join(type_to_glsl(expected_type), "(", to_unpacked_expression(op0), ")");
  15797. else
  15798. cast_op = bitcast_glsl(expected_type, op0);
  15799. }
  15800. else
  15801. cast_op = to_unpacked_expression(op0);
  15802. string sg_op = join("spvClustered_", op, "<", cluster_size, ">");
  15803. string expr;
  15804. if (out_type.basetype != expected_result_type)
  15805. {
  15806. expected_type.basetype = expected_result_type;
  15807. expected_type.width = out_type.width;
  15808. if (out_type.basetype == SPIRType::Boolean)
  15809. expr = type_to_glsl(out_type);
  15810. else
  15811. expr = bitcast_glsl_op(out_type, expected_type);
  15812. expr += '(';
  15813. expr += join(sg_op, "(", cast_op, ", ", to_expression(builtin_subgroup_invocation_id_id), ")");
  15814. expr += ')';
  15815. }
  15816. else
  15817. {
  15818. expr += join(sg_op, "(", cast_op, ", ", to_expression(builtin_subgroup_invocation_id_id), ")");
  15819. }
  15820. emit_op(result_type, result_id, expr, should_forward(op0));
  15821. inherit_expression_dependencies(result_id, op0);
  15822. }
  15823. // Note: Metal forbids bitcasting to/from 'bool' using as_type. This function is used widely
  15824. // for generating casts in the backend. To avoid generating illegal MSL when the canonical
  15825. // function constant type (from deduplicated SpecId) is Boolean, fall back to value-cast in
  15826. // that case by returning type_to_glsl(out_type) instead of as_type<...>.
  15827. string CompilerMSL::bitcast_glsl_op(const SPIRType &out_type, const SPIRType &in_type)
  15828. {
  15829. if (out_type.basetype == in_type.basetype)
  15830. return "";
  15831. // Avoid bitcasting to/from booleans in MSL; use value cast instead.
  15832. if (out_type.basetype == SPIRType::Boolean || in_type.basetype == SPIRType::Boolean)
  15833. return type_to_glsl(out_type);
  15834. bool integral_cast = type_is_integral(out_type) && type_is_integral(in_type) && (out_type.vecsize == in_type.vecsize);
  15835. bool same_size_cast = (out_type.width * out_type.vecsize) == (in_type.width * in_type.vecsize);
  15836. // Bitcasting can only be used between types of the same overall size.
  15837. // And always formally cast between integers, because it's trivial, and also
  15838. // because Metal can internally cast the results of some integer ops to a larger
  15839. // size (eg. short shift right becomes int), which means chaining integer ops
  15840. // together may introduce size variations that SPIR-V doesn't know about.
  15841. if (same_size_cast && !integral_cast)
  15842. return "as_type<" + type_to_glsl(out_type) + ">";
  15843. else
  15844. return type_to_glsl(out_type);
  15845. }
  15846. bool CompilerMSL::emit_complex_bitcast(uint32_t, uint32_t, uint32_t)
  15847. {
  15848. // This is handled from the outside where we deal with PtrToU/UToPtr and friends.
  15849. return false;
  15850. }
  15851. // Returns an MSL string identifying the name of a SPIR-V builtin.
  15852. // Output builtins are qualified with the name of the stage out structure.
  15853. string CompilerMSL::builtin_to_glsl(BuiltIn builtin, StorageClass storage)
  15854. {
  15855. switch (builtin)
  15856. {
  15857. // Handle HLSL-style 0-based vertex/instance index.
  15858. // Override GLSL compiler strictness
  15859. case BuiltInVertexId:
  15860. ensure_builtin(StorageClassInput, BuiltInVertexId);
  15861. if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
  15862. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15863. {
  15864. if (builtin_declaration)
  15865. {
  15866. if (needs_base_vertex_arg != TriState::No)
  15867. needs_base_vertex_arg = TriState::Yes;
  15868. return "gl_VertexID";
  15869. }
  15870. else
  15871. {
  15872. ensure_builtin(StorageClassInput, BuiltInBaseVertex);
  15873. return "(gl_VertexID - gl_BaseVertex)";
  15874. }
  15875. }
  15876. else
  15877. {
  15878. return "gl_VertexID";
  15879. }
  15880. case BuiltInInstanceId:
  15881. ensure_builtin(StorageClassInput, BuiltInInstanceId);
  15882. if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
  15883. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15884. {
  15885. if (builtin_declaration)
  15886. {
  15887. if (needs_base_instance_arg != TriState::No)
  15888. needs_base_instance_arg = TriState::Yes;
  15889. return "gl_InstanceID";
  15890. }
  15891. else
  15892. {
  15893. ensure_builtin(StorageClassInput, BuiltInBaseInstance);
  15894. return "(gl_InstanceID - gl_BaseInstance)";
  15895. }
  15896. }
  15897. else
  15898. {
  15899. return "gl_InstanceID";
  15900. }
  15901. case BuiltInVertexIndex:
  15902. ensure_builtin(StorageClassInput, BuiltInVertexIndex);
  15903. if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
  15904. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15905. {
  15906. if (builtin_declaration)
  15907. {
  15908. if (needs_base_vertex_arg != TriState::No)
  15909. needs_base_vertex_arg = TriState::Yes;
  15910. return "gl_VertexIndex";
  15911. }
  15912. else
  15913. {
  15914. ensure_builtin(StorageClassInput, BuiltInBaseVertex);
  15915. return "(gl_VertexIndex - gl_BaseVertex)";
  15916. }
  15917. }
  15918. else
  15919. {
  15920. return "gl_VertexIndex";
  15921. }
  15922. case BuiltInInstanceIndex:
  15923. ensure_builtin(StorageClassInput, BuiltInInstanceIndex);
  15924. if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
  15925. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15926. {
  15927. if (builtin_declaration)
  15928. {
  15929. if (needs_base_instance_arg != TriState::No)
  15930. needs_base_instance_arg = TriState::Yes;
  15931. return "gl_InstanceIndex";
  15932. }
  15933. else
  15934. {
  15935. ensure_builtin(StorageClassInput, BuiltInBaseInstance);
  15936. return "(gl_InstanceIndex - gl_BaseInstance)";
  15937. }
  15938. }
  15939. else
  15940. {
  15941. return "gl_InstanceIndex";
  15942. }
  15943. case BuiltInBaseVertex:
  15944. if (msl_options.supports_msl_version(1, 1) &&
  15945. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15946. {
  15947. needs_base_vertex_arg = TriState::No;
  15948. return "gl_BaseVertex";
  15949. }
  15950. else
  15951. {
  15952. SPIRV_CROSS_THROW("BaseVertex requires Metal 1.1 and Mac or Apple A9+ hardware.");
  15953. }
  15954. case BuiltInBaseInstance:
  15955. if (msl_options.supports_msl_version(1, 1) &&
  15956. (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
  15957. {
  15958. needs_base_instance_arg = TriState::No;
  15959. return "gl_BaseInstance";
  15960. }
  15961. else
  15962. {
  15963. SPIRV_CROSS_THROW("BaseInstance requires Metal 1.1 and Mac or Apple A9+ hardware.");
  15964. }
  15965. case BuiltInDrawIndex:
  15966. SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
  15967. // When used in the entry function, output builtins are qualified with output struct name.
  15968. // Test storage class as NOT Input, as output builtins might be part of generic type.
  15969. // Also don't do this for tessellation control shaders.
  15970. case BuiltInViewportIndex:
  15971. if (!msl_options.supports_msl_version(2, 0))
  15972. SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
  15973. /* fallthrough */
  15974. case BuiltInFragDepth:
  15975. case BuiltInFragStencilRefEXT:
  15976. if ((builtin == BuiltInFragDepth && !msl_options.enable_frag_depth_builtin) ||
  15977. (builtin == BuiltInFragStencilRefEXT && !msl_options.enable_frag_stencil_ref_builtin))
  15978. break;
  15979. /* fallthrough */
  15980. case BuiltInPosition:
  15981. case BuiltInPointSize:
  15982. case BuiltInClipDistance:
  15983. case BuiltInCullDistance:
  15984. case BuiltInLayer:
  15985. if (is_tesc_shader())
  15986. break;
  15987. if (is_mesh_shader())
  15988. break;
  15989. if (storage != StorageClassInput && current_function && (current_function->self == ir.default_entry_point) &&
  15990. !is_stage_output_builtin_masked(builtin))
  15991. return stage_out_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage);
  15992. break;
  15993. case BuiltInSampleMask:
  15994. if (storage == StorageClassInput && current_function && (current_function->self == ir.default_entry_point) &&
  15995. (has_additional_fixed_sample_mask() || needs_sample_id))
  15996. {
  15997. string samp_mask_in;
  15998. samp_mask_in += "(" + CompilerGLSL::builtin_to_glsl(builtin, storage);
  15999. if (has_additional_fixed_sample_mask())
  16000. samp_mask_in += " & " + additional_fixed_sample_mask_str();
  16001. if (needs_sample_id)
  16002. samp_mask_in += " & (1 << gl_SampleID)";
  16003. samp_mask_in += ")";
  16004. return samp_mask_in;
  16005. }
  16006. if (storage != StorageClassInput && current_function && (current_function->self == ir.default_entry_point) &&
  16007. !is_stage_output_builtin_masked(builtin))
  16008. return stage_out_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage);
  16009. break;
  16010. case BuiltInBaryCoordKHR:
  16011. case BuiltInBaryCoordNoPerspKHR:
  16012. if (storage == StorageClassInput && current_function && (current_function->self == ir.default_entry_point))
  16013. return stage_in_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage);
  16014. break;
  16015. case BuiltInTessLevelOuter:
  16016. if (is_tesc_shader() && storage != StorageClassInput && current_function &&
  16017. (current_function->self == ir.default_entry_point))
  16018. {
  16019. return join(tess_factor_buffer_var_name, "[", to_expression(builtin_primitive_id_id),
  16020. "].edgeTessellationFactor");
  16021. }
  16022. break;
  16023. case BuiltInTessLevelInner:
  16024. if (is_tesc_shader() && storage != StorageClassInput && current_function &&
  16025. (current_function->self == ir.default_entry_point))
  16026. {
  16027. return join(tess_factor_buffer_var_name, "[", to_expression(builtin_primitive_id_id),
  16028. "].insideTessellationFactor");
  16029. }
  16030. break;
  16031. case BuiltInHelperInvocation:
  16032. if (needs_manual_helper_invocation_updates())
  16033. break;
  16034. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
  16035. SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.3 on iOS.");
  16036. else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1))
  16037. SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.1 on macOS.");
  16038. // In SPIR-V 1.6 with Volatile HelperInvocation, we cannot emit a fixup early.
  16039. return "simd_is_helper_thread()";
  16040. case BuiltInPrimitiveId:
  16041. return "gl_PrimitiveID";
  16042. default:
  16043. break;
  16044. }
  16045. return CompilerGLSL::builtin_to_glsl(builtin, storage);
  16046. }
  16047. // Returns an MSL string attribute qualifer for a SPIR-V builtin
  16048. string CompilerMSL::builtin_qualifier(BuiltIn builtin)
  16049. {
  16050. auto &execution = get_entry_point();
  16051. switch (builtin)
  16052. {
  16053. // Vertex function in
  16054. case BuiltInVertexId:
  16055. return "vertex_id";
  16056. case BuiltInVertexIndex:
  16057. return "vertex_id";
  16058. case BuiltInBaseVertex:
  16059. return "base_vertex";
  16060. case BuiltInInstanceId:
  16061. return "instance_id";
  16062. case BuiltInInstanceIndex:
  16063. return "instance_id";
  16064. case BuiltInBaseInstance:
  16065. return "base_instance";
  16066. case BuiltInDrawIndex:
  16067. SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
  16068. // Vertex function out
  16069. case BuiltInClipDistance:
  16070. return "clip_distance";
  16071. case BuiltInCullDistance:
  16072. return "cull_distance";
  16073. case BuiltInPointSize:
  16074. return "point_size";
  16075. case BuiltInPosition:
  16076. if (position_invariant)
  16077. {
  16078. if (!msl_options.supports_msl_version(2, 1))
  16079. SPIRV_CROSS_THROW("Invariant position is only supported on MSL 2.1 and up.");
  16080. return "position, invariant";
  16081. }
  16082. else
  16083. return "position";
  16084. case BuiltInLayer:
  16085. return "render_target_array_index";
  16086. case BuiltInViewportIndex:
  16087. if (!msl_options.supports_msl_version(2, 0))
  16088. SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
  16089. return "viewport_array_index";
  16090. // Tess. control function in
  16091. case BuiltInInvocationId:
  16092. if (msl_options.multi_patch_workgroup)
  16093. {
  16094. // Shouldn't be reached.
  16095. SPIRV_CROSS_THROW("InvocationId is computed manually with multi-patch workgroups in MSL.");
  16096. }
  16097. return "thread_index_in_threadgroup";
  16098. case BuiltInPatchVertices:
  16099. // Shouldn't be reached.
  16100. SPIRV_CROSS_THROW("PatchVertices is derived from the auxiliary buffer in MSL.");
  16101. case BuiltInPrimitiveId:
  16102. switch (execution.model)
  16103. {
  16104. case ExecutionModelTessellationControl:
  16105. if (msl_options.multi_patch_workgroup)
  16106. {
  16107. // Shouldn't be reached.
  16108. SPIRV_CROSS_THROW("PrimitiveId is computed manually with multi-patch workgroups in MSL.");
  16109. }
  16110. return "threadgroup_position_in_grid";
  16111. case ExecutionModelTessellationEvaluation:
  16112. return "patch_id";
  16113. case ExecutionModelFragment:
  16114. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
  16115. SPIRV_CROSS_THROW("PrimitiveId on iOS requires MSL 2.3.");
  16116. else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 2))
  16117. SPIRV_CROSS_THROW("PrimitiveId on macOS requires MSL 2.2.");
  16118. return "primitive_id";
  16119. case ExecutionModelMeshEXT:
  16120. return "primitive_id";
  16121. default:
  16122. SPIRV_CROSS_THROW("PrimitiveId is not supported in this execution model.");
  16123. }
  16124. // Tess. control function out
  16125. case BuiltInTessLevelOuter:
  16126. case BuiltInTessLevelInner:
  16127. // Shouldn't be reached.
  16128. SPIRV_CROSS_THROW("Tessellation levels are handled specially in MSL.");
  16129. // Tess. evaluation function in
  16130. case BuiltInTessCoord:
  16131. return "position_in_patch";
  16132. // Fragment function in
  16133. case BuiltInFrontFacing:
  16134. return "front_facing";
  16135. case BuiltInPointCoord:
  16136. return "point_coord";
  16137. case BuiltInFragCoord:
  16138. return "position";
  16139. case BuiltInSampleId:
  16140. return "sample_id";
  16141. case BuiltInSampleMask:
  16142. return "sample_mask";
  16143. case BuiltInSamplePosition:
  16144. // Shouldn't be reached.
  16145. SPIRV_CROSS_THROW("Sample position is retrieved by a function in MSL.");
  16146. case BuiltInViewIndex:
  16147. if (execution.model != ExecutionModelFragment && execution.model != ExecutionModelMeshEXT)
  16148. SPIRV_CROSS_THROW("ViewIndex is handled specially outside fragment shaders.");
  16149. // The ViewIndex was implicitly used in the prior stages to set the render_target_array_index,
  16150. // so we can get it from there.
  16151. return "render_target_array_index";
  16152. // Fragment function out
  16153. case BuiltInFragDepth:
  16154. if (execution.flags.get(ExecutionModeDepthGreater))
  16155. return "depth(greater)";
  16156. else if (execution.flags.get(ExecutionModeDepthLess))
  16157. return "depth(less)";
  16158. else
  16159. return "depth(any)";
  16160. case BuiltInFragStencilRefEXT:
  16161. return "stencil";
  16162. // Compute function in
  16163. case BuiltInGlobalInvocationId:
  16164. return "thread_position_in_grid";
  16165. case BuiltInWorkgroupSize:
  16166. return "threads_per_threadgroup";
  16167. case BuiltInWorkgroupId:
  16168. return "threadgroup_position_in_grid";
  16169. case BuiltInNumWorkgroups:
  16170. return "threadgroups_per_grid";
  16171. case BuiltInLocalInvocationId:
  16172. return "thread_position_in_threadgroup";
  16173. case BuiltInLocalInvocationIndex:
  16174. return "thread_index_in_threadgroup";
  16175. case BuiltInSubgroupSize:
  16176. if (msl_options.emulate_subgroups || msl_options.fixed_subgroup_size != 0)
  16177. // Shouldn't be reached.
  16178. SPIRV_CROSS_THROW("Emitting threads_per_simdgroup attribute with fixed subgroup size??");
  16179. if (execution.model == ExecutionModelFragment)
  16180. {
  16181. if (!msl_options.supports_msl_version(2, 2))
  16182. SPIRV_CROSS_THROW("threads_per_simdgroup requires Metal 2.2 in fragment shaders.");
  16183. return "threads_per_simdgroup";
  16184. }
  16185. else
  16186. {
  16187. // thread_execution_width is an alias for threads_per_simdgroup, and it's only available since 1.0,
  16188. // but not in fragment.
  16189. if (msl_options.supports_msl_version(3, 0))
  16190. return "threads_per_simdgroup";
  16191. else
  16192. return "thread_execution_width";
  16193. }
  16194. case BuiltInNumSubgroups:
  16195. if (msl_options.emulate_subgroups)
  16196. // Shouldn't be reached.
  16197. SPIRV_CROSS_THROW("NumSubgroups is handled specially with emulation.");
  16198. if (!msl_options.supports_msl_version(2))
  16199. SPIRV_CROSS_THROW("Subgroup builtins require Metal 2.0.");
  16200. return msl_options.use_quadgroup_operation() ? "quadgroups_per_threadgroup" : "simdgroups_per_threadgroup";
  16201. case BuiltInSubgroupId:
  16202. if (msl_options.emulate_subgroups)
  16203. // Shouldn't be reached.
  16204. SPIRV_CROSS_THROW("SubgroupId is handled specially with emulation.");
  16205. if (!msl_options.supports_msl_version(2))
  16206. SPIRV_CROSS_THROW("Subgroup builtins require Metal 2.0.");
  16207. return msl_options.use_quadgroup_operation() ? "quadgroup_index_in_threadgroup" : "simdgroup_index_in_threadgroup";
  16208. case BuiltInSubgroupLocalInvocationId:
  16209. if (msl_options.emulate_subgroups)
  16210. // Shouldn't be reached.
  16211. SPIRV_CROSS_THROW("SubgroupLocalInvocationId is handled specially with emulation.");
  16212. if (execution.model == ExecutionModelFragment)
  16213. {
  16214. if (!msl_options.supports_msl_version(2, 2))
  16215. SPIRV_CROSS_THROW("thread_index_in_simdgroup requires Metal 2.2 in fragment shaders.");
  16216. return "thread_index_in_simdgroup";
  16217. }
  16218. else if (execution.model == ExecutionModelKernel || execution.model == ExecutionModelGLCompute ||
  16219. execution.model == ExecutionModelTaskEXT || execution.model == ExecutionModelMeshEXT ||
  16220. execution.model == ExecutionModelTessellationControl ||
  16221. (execution.model == ExecutionModelVertex && msl_options.vertex_for_tessellation))
  16222. {
  16223. // We are generating a Metal kernel function.
  16224. if (!msl_options.supports_msl_version(2))
  16225. SPIRV_CROSS_THROW("Subgroup builtins in kernel functions require Metal 2.0.");
  16226. return msl_options.use_quadgroup_operation() ? "thread_index_in_quadgroup" : "thread_index_in_simdgroup";
  16227. }
  16228. else
  16229. SPIRV_CROSS_THROW("Subgroup builtins are not available in this type of function.");
  16230. case BuiltInSubgroupEqMask:
  16231. case BuiltInSubgroupGeMask:
  16232. case BuiltInSubgroupGtMask:
  16233. case BuiltInSubgroupLeMask:
  16234. case BuiltInSubgroupLtMask:
  16235. // Shouldn't be reached.
  16236. SPIRV_CROSS_THROW("Subgroup ballot masks are handled specially in MSL.");
  16237. case BuiltInBaryCoordKHR:
  16238. case BuiltInBaryCoordNoPerspKHR:
  16239. if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
  16240. SPIRV_CROSS_THROW("Barycentrics are only supported in MSL 2.3 and above on iOS.");
  16241. else if (!msl_options.supports_msl_version(2, 2))
  16242. SPIRV_CROSS_THROW("Barycentrics are only supported in MSL 2.2 and above on macOS.");
  16243. return "barycentric_coord";
  16244. case BuiltInCullPrimitiveEXT:
  16245. return "primitive_culled";
  16246. default:
  16247. return "unsupported-built-in";
  16248. }
  16249. }
  16250. // Returns an MSL string type declaration for a SPIR-V builtin
  16251. string CompilerMSL::builtin_type_decl(BuiltIn builtin, uint32_t id)
  16252. {
  16253. switch (builtin)
  16254. {
  16255. // Vertex function in
  16256. case BuiltInVertexId:
  16257. return "uint";
  16258. case BuiltInVertexIndex:
  16259. return "uint";
  16260. case BuiltInBaseVertex:
  16261. return "uint";
  16262. case BuiltInInstanceId:
  16263. return "uint";
  16264. case BuiltInInstanceIndex:
  16265. return "uint";
  16266. case BuiltInBaseInstance:
  16267. return "uint";
  16268. case BuiltInDrawIndex:
  16269. SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
  16270. // Vertex function out
  16271. case BuiltInClipDistance:
  16272. case BuiltInCullDistance:
  16273. return "float";
  16274. case BuiltInPointSize:
  16275. return "float";
  16276. case BuiltInPosition:
  16277. return "float4";
  16278. case BuiltInLayer:
  16279. return "uint";
  16280. case BuiltInViewportIndex:
  16281. if (!msl_options.supports_msl_version(2, 0))
  16282. SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
  16283. return "uint";
  16284. // Tess. control function in
  16285. case BuiltInInvocationId:
  16286. return "uint";
  16287. case BuiltInPatchVertices:
  16288. return "uint";
  16289. case BuiltInPrimitiveId:
  16290. return "uint";
  16291. // Tess. control function out
  16292. case BuiltInTessLevelInner:
  16293. if (is_tese_shader())
  16294. return (msl_options.raw_buffer_tese_input || is_tessellating_triangles()) ? "float" : "float2";
  16295. return "half";
  16296. case BuiltInTessLevelOuter:
  16297. if (is_tese_shader())
  16298. return (msl_options.raw_buffer_tese_input || is_tessellating_triangles()) ? "float" : "float4";
  16299. return "half";
  16300. // Tess. evaluation function in
  16301. case BuiltInTessCoord:
  16302. return "float3";
  16303. // Fragment function in
  16304. case BuiltInFrontFacing:
  16305. return "bool";
  16306. case BuiltInPointCoord:
  16307. return "float2";
  16308. case BuiltInFragCoord:
  16309. return "float4";
  16310. case BuiltInSampleId:
  16311. return "uint";
  16312. case BuiltInSampleMask:
  16313. return "uint";
  16314. case BuiltInSamplePosition:
  16315. return "float2";
  16316. case BuiltInViewIndex:
  16317. return "uint";
  16318. case BuiltInHelperInvocation:
  16319. return "bool";
  16320. case BuiltInBaryCoordKHR:
  16321. case BuiltInBaryCoordNoPerspKHR:
  16322. // Use the type as declared, can be 1, 2 or 3 components.
  16323. return type_to_glsl(get_variable_data_type(get<SPIRVariable>(id)));
  16324. // Fragment function out
  16325. case BuiltInFragDepth:
  16326. return "float";
  16327. case BuiltInFragStencilRefEXT:
  16328. return "uint";
  16329. // Compute function in
  16330. case BuiltInGlobalInvocationId:
  16331. case BuiltInLocalInvocationId:
  16332. case BuiltInNumWorkgroups:
  16333. case BuiltInWorkgroupId:
  16334. case BuiltInWorkgroupSize:
  16335. return "uint3";
  16336. case BuiltInLocalInvocationIndex:
  16337. case BuiltInNumSubgroups:
  16338. case BuiltInSubgroupId:
  16339. case BuiltInSubgroupSize:
  16340. case BuiltInSubgroupLocalInvocationId:
  16341. return "uint";
  16342. case BuiltInSubgroupEqMask:
  16343. case BuiltInSubgroupGeMask:
  16344. case BuiltInSubgroupGtMask:
  16345. case BuiltInSubgroupLeMask:
  16346. case BuiltInSubgroupLtMask:
  16347. return "uint4";
  16348. case BuiltInDeviceIndex:
  16349. return "int";
  16350. case BuiltInPrimitivePointIndicesEXT:
  16351. return "uint";
  16352. case BuiltInPrimitiveLineIndicesEXT:
  16353. return "uint2";
  16354. case BuiltInPrimitiveTriangleIndicesEXT:
  16355. return "uint3";
  16356. default:
  16357. return "unsupported-built-in-type";
  16358. }
  16359. }
  16360. // Returns the declaration of a built-in argument to a function
  16361. string CompilerMSL::built_in_func_arg(BuiltIn builtin, bool prefix_comma)
  16362. {
  16363. string bi_arg;
  16364. if (prefix_comma)
  16365. bi_arg += ", ";
  16366. // Handle HLSL-style 0-based vertex/instance index.
  16367. builtin_declaration = true;
  16368. bi_arg += builtin_type_decl(builtin);
  16369. bi_arg += string(" ") + builtin_to_glsl(builtin, StorageClassInput);
  16370. bi_arg += string(" [[") + builtin_qualifier(builtin) + string("]]");
  16371. builtin_declaration = false;
  16372. return bi_arg;
  16373. }
  16374. const SPIRType &CompilerMSL::get_physical_member_type(const SPIRType &type, uint32_t index) const
  16375. {
  16376. if (member_is_remapped_physical_type(type, index))
  16377. return get<SPIRType>(get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPhysicalTypeID));
  16378. else
  16379. return get<SPIRType>(type.member_types[index]);
  16380. }
  16381. SPIRType CompilerMSL::get_presumed_input_type(const SPIRType &ib_type, uint32_t index) const
  16382. {
  16383. SPIRType type = get_physical_member_type(ib_type, index);
  16384. uint32_t loc = get_member_decoration(ib_type.self, index, DecorationLocation);
  16385. uint32_t cmp = get_member_decoration(ib_type.self, index, DecorationComponent);
  16386. auto p_va = inputs_by_location.find({loc, cmp});
  16387. if (p_va != end(inputs_by_location) && p_va->second.vecsize > type.vecsize)
  16388. type.vecsize = p_va->second.vecsize;
  16389. return type;
  16390. }
  16391. uint32_t CompilerMSL::get_declared_type_array_stride_msl(const SPIRType &type, bool is_packed, bool row_major) const
  16392. {
  16393. // Array stride in MSL is always size * array_size. sizeof(float3) == 16,
  16394. // unlike GLSL and HLSL where array stride would be 16 and size 12.
  16395. // We could use parent type here and recurse, but that makes creating physical type remappings
  16396. // far more complicated. We'd rather just create the final type, and ignore having to create the entire type
  16397. // hierarchy in order to compute this value, so make a temporary type on the stack.
  16398. auto basic_type = type;
  16399. basic_type.array.clear();
  16400. basic_type.array_size_literal.clear();
  16401. uint32_t value_size = get_declared_type_size_msl(basic_type, is_packed, row_major);
  16402. uint32_t dimensions = uint32_t(type.array.size());
  16403. assert(dimensions > 0);
  16404. dimensions--;
  16405. // Multiply together every dimension, except the last one.
  16406. for (uint32_t dim = 0; dim < dimensions; dim++)
  16407. {
  16408. uint32_t array_size = to_array_size_literal(type, dim);
  16409. value_size *= max<uint32_t>(array_size, 1u);
  16410. }
  16411. return value_size;
  16412. }
  16413. uint32_t CompilerMSL::get_declared_struct_member_array_stride_msl(const SPIRType &type, uint32_t index) const
  16414. {
  16415. return get_declared_type_array_stride_msl(get_physical_member_type(type, index),
  16416. member_is_packed_physical_type(type, index),
  16417. has_member_decoration(type.self, index, DecorationRowMajor));
  16418. }
  16419. uint32_t CompilerMSL::get_declared_input_array_stride_msl(const SPIRType &type, uint32_t index) const
  16420. {
  16421. return get_declared_type_array_stride_msl(get_presumed_input_type(type, index), false,
  16422. has_member_decoration(type.self, index, DecorationRowMajor));
  16423. }
  16424. uint32_t CompilerMSL::get_declared_type_matrix_stride_msl(const SPIRType &type, bool packed, bool row_major) const
  16425. {
  16426. // For packed matrices, we just use the size of the vector type.
  16427. // Otherwise, MatrixStride == alignment, which is the size of the underlying vector type.
  16428. if (packed)
  16429. return (type.width / 8) * ((row_major && type.columns > 1) ? type.columns : type.vecsize);
  16430. else
  16431. return get_declared_type_alignment_msl(type, false, row_major);
  16432. }
  16433. uint32_t CompilerMSL::get_declared_struct_member_matrix_stride_msl(const SPIRType &type, uint32_t index) const
  16434. {
  16435. return get_declared_type_matrix_stride_msl(get_physical_member_type(type, index),
  16436. member_is_packed_physical_type(type, index),
  16437. has_member_decoration(type.self, index, DecorationRowMajor));
  16438. }
  16439. uint32_t CompilerMSL::get_declared_input_matrix_stride_msl(const SPIRType &type, uint32_t index) const
  16440. {
  16441. return get_declared_type_matrix_stride_msl(get_presumed_input_type(type, index), false,
  16442. has_member_decoration(type.self, index, DecorationRowMajor));
  16443. }
  16444. uint32_t CompilerMSL::get_declared_struct_size_msl(const SPIRType &struct_type, bool ignore_alignment,
  16445. bool ignore_padding) const
  16446. {
  16447. // If we have a target size, that is the declared size as well.
  16448. if (!ignore_padding && has_extended_decoration(struct_type.self, SPIRVCrossDecorationPaddingTarget))
  16449. return get_extended_decoration(struct_type.self, SPIRVCrossDecorationPaddingTarget);
  16450. if (struct_type.member_types.empty())
  16451. return 0;
  16452. uint32_t mbr_cnt = uint32_t(struct_type.member_types.size());
  16453. // In MSL, a struct's alignment is equal to the maximum alignment of any of its members.
  16454. uint32_t alignment = 1;
  16455. if (!ignore_alignment)
  16456. {
  16457. for (uint32_t i = 0; i < mbr_cnt; i++)
  16458. {
  16459. uint32_t mbr_alignment = get_declared_struct_member_alignment_msl(struct_type, i);
  16460. alignment = max(alignment, mbr_alignment);
  16461. }
  16462. }
  16463. // Last member will always be matched to the final Offset decoration, but size of struct in MSL now depends
  16464. // on physical size in MSL, and the size of the struct itself is then aligned to struct alignment.
  16465. uint32_t spirv_offset = type_struct_member_offset(struct_type, mbr_cnt - 1);
  16466. uint32_t msl_size = spirv_offset + get_declared_struct_member_size_msl(struct_type, mbr_cnt - 1);
  16467. msl_size = (msl_size + alignment - 1) & ~(alignment - 1);
  16468. return msl_size;
  16469. }
  16470. uint32_t CompilerMSL::get_physical_type_stride(const SPIRType &type) const
  16471. {
  16472. // This should only be relevant for plain types such as scalars and vectors?
  16473. // If we're pointing to a struct, it will recursively pick up packed/row-major state.
  16474. return get_declared_type_size_msl(type, false, false);
  16475. }
  16476. // Returns the byte size of a struct member.
  16477. uint32_t CompilerMSL::get_declared_type_size_msl(const SPIRType &type, bool is_packed, bool row_major) const
  16478. {
  16479. // Pointers take 8 bytes each
  16480. // Match both pointer and array-of-pointer here.
  16481. if (type.pointer && type.storage == StorageClassPhysicalStorageBuffer)
  16482. {
  16483. uint32_t type_size = 8;
  16484. // Work our way through potentially layered arrays,
  16485. // stopping when we hit a pointer that is not also an array.
  16486. int32_t dim_idx = (int32_t)type.array.size() - 1;
  16487. auto *p_type = &type;
  16488. while (!is_pointer(*p_type) && dim_idx >= 0)
  16489. {
  16490. type_size *= to_array_size_literal(*p_type, dim_idx);
  16491. p_type = &get<SPIRType>(p_type->parent_type);
  16492. dim_idx--;
  16493. }
  16494. return type_size;
  16495. }
  16496. switch (type.basetype)
  16497. {
  16498. case SPIRType::Unknown:
  16499. case SPIRType::Void:
  16500. case SPIRType::AtomicCounter:
  16501. case SPIRType::Image:
  16502. case SPIRType::SampledImage:
  16503. case SPIRType::Sampler:
  16504. SPIRV_CROSS_THROW("Querying size of opaque object.");
  16505. default:
  16506. {
  16507. if (!type.array.empty())
  16508. {
  16509. uint32_t array_size = to_array_size_literal(type);
  16510. return get_declared_type_array_stride_msl(type, is_packed, row_major) * max<uint32_t>(array_size, 1u);
  16511. }
  16512. if (type.basetype == SPIRType::Struct)
  16513. return get_declared_struct_size_msl(type);
  16514. if (is_packed)
  16515. {
  16516. return type.vecsize * type.columns * (type.width / 8);
  16517. }
  16518. else
  16519. {
  16520. // An unpacked 3-element vector or matrix column is the same memory size as a 4-element.
  16521. uint32_t vecsize = type.vecsize;
  16522. uint32_t columns = type.columns;
  16523. if (row_major && columns > 1)
  16524. swap(vecsize, columns);
  16525. if (vecsize == 3)
  16526. vecsize = 4;
  16527. return vecsize * columns * (type.width / 8);
  16528. }
  16529. }
  16530. }
  16531. }
  16532. uint32_t CompilerMSL::get_declared_struct_member_size_msl(const SPIRType &type, uint32_t index) const
  16533. {
  16534. return get_declared_type_size_msl(get_physical_member_type(type, index),
  16535. member_is_packed_physical_type(type, index),
  16536. has_member_decoration(type.self, index, DecorationRowMajor));
  16537. }
  16538. uint32_t CompilerMSL::get_declared_input_size_msl(const SPIRType &type, uint32_t index) const
  16539. {
  16540. return get_declared_type_size_msl(get_presumed_input_type(type, index), false,
  16541. has_member_decoration(type.self, index, DecorationRowMajor));
  16542. }
  16543. // Returns the byte alignment of a type.
  16544. uint32_t CompilerMSL::get_declared_type_alignment_msl(const SPIRType &type, bool is_packed, bool row_major) const
  16545. {
  16546. // Pointers align on multiples of 8 bytes.
  16547. // Deliberately ignore array-ness here. It's not relevant for alignment.
  16548. if (type.pointer && type.storage == StorageClassPhysicalStorageBuffer)
  16549. return 8;
  16550. switch (type.basetype)
  16551. {
  16552. case SPIRType::Unknown:
  16553. case SPIRType::Void:
  16554. case SPIRType::AtomicCounter:
  16555. case SPIRType::Image:
  16556. case SPIRType::SampledImage:
  16557. case SPIRType::Sampler:
  16558. SPIRV_CROSS_THROW("Querying alignment of opaque object.");
  16559. case SPIRType::Double:
  16560. SPIRV_CROSS_THROW("double types are not supported in buffers in MSL.");
  16561. case SPIRType::Struct:
  16562. {
  16563. // In MSL, a struct's alignment is equal to the maximum alignment of any of its members.
  16564. uint32_t alignment = 1;
  16565. for (uint32_t i = 0; i < type.member_types.size(); i++)
  16566. alignment = max(alignment, uint32_t(get_declared_struct_member_alignment_msl(type, i)));
  16567. return alignment;
  16568. }
  16569. default:
  16570. {
  16571. if (type.basetype == SPIRType::Int64 && !msl_options.supports_msl_version(2, 3))
  16572. SPIRV_CROSS_THROW("long types in buffers are only supported in MSL 2.3 and above.");
  16573. if (type.basetype == SPIRType::UInt64 && !msl_options.supports_msl_version(2, 3))
  16574. SPIRV_CROSS_THROW("ulong types in buffers are only supported in MSL 2.3 and above.");
  16575. // Alignment of packed type is the same as the underlying component or column size.
  16576. // Alignment of unpacked type is the same as the vector size.
  16577. // Alignment of 3-elements vector is the same as 4-elements (including packed using column).
  16578. if (is_packed)
  16579. {
  16580. // If we have packed_T and friends, the alignment is always scalar.
  16581. return type.width / 8;
  16582. }
  16583. else
  16584. {
  16585. // This is the general rule for MSL. Size == alignment.
  16586. uint32_t vecsize = (row_major && type.columns > 1) ? type.columns : type.vecsize;
  16587. return (type.width / 8) * (vecsize == 3 ? 4 : vecsize);
  16588. }
  16589. }
  16590. }
  16591. }
  16592. uint32_t CompilerMSL::get_declared_struct_member_alignment_msl(const SPIRType &type, uint32_t index) const
  16593. {
  16594. return get_declared_type_alignment_msl(get_physical_member_type(type, index),
  16595. member_is_packed_physical_type(type, index),
  16596. has_member_decoration(type.self, index, DecorationRowMajor));
  16597. }
  16598. uint32_t CompilerMSL::get_declared_input_alignment_msl(const SPIRType &type, uint32_t index) const
  16599. {
  16600. return get_declared_type_alignment_msl(get_presumed_input_type(type, index), false,
  16601. has_member_decoration(type.self, index, DecorationRowMajor));
  16602. }
  16603. bool CompilerMSL::skip_argument(uint32_t) const
  16604. {
  16605. return false;
  16606. }
  16607. void CompilerMSL::analyze_sampled_image_usage()
  16608. {
  16609. if (msl_options.swizzle_texture_samples)
  16610. {
  16611. SampledImageScanner scanner(*this);
  16612. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), scanner);
  16613. }
  16614. }
  16615. void CompilerMSL::analyze_workgroup_variables()
  16616. {
  16617. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
  16618. // If workgroup variables have initializer, it can only be ConstantNull (zero init)
  16619. if (var.storage == StorageClassWorkgroup && var.initializer)
  16620. {
  16621. needs_workgroup_zero_init = true;
  16622. // MSL compiler does not like the routine to initialize simple threadgroup variables,
  16623. // falsely claiming it is "sometimes uninitialized". Suppress it.
  16624. auto &type = get_variable_data_type(var);
  16625. if (type.array.empty() && type.member_types.empty())
  16626. suppress_sometimes_unitialized = true;
  16627. }
  16628. });
  16629. }
  16630. bool CompilerMSL::SampledImageScanner::handle(Op opcode, const uint32_t *args, uint32_t length)
  16631. {
  16632. switch (opcode)
  16633. {
  16634. case OpLoad:
  16635. case OpImage:
  16636. case OpSampledImage:
  16637. {
  16638. if (length < 3)
  16639. return false;
  16640. uint32_t result_type = args[0];
  16641. auto &type = get<SPIRType>(result_type);
  16642. if ((type.basetype != SPIRType::Image && type.basetype != SPIRType::SampledImage) || type.image.sampled != 1)
  16643. return true;
  16644. uint32_t id = args[1];
  16645. set<SPIRExpression>(id, "", result_type, true);
  16646. break;
  16647. }
  16648. case OpImageSampleExplicitLod:
  16649. case OpImageSampleProjExplicitLod:
  16650. case OpImageSampleDrefExplicitLod:
  16651. case OpImageSampleProjDrefExplicitLod:
  16652. case OpImageSampleImplicitLod:
  16653. case OpImageSampleProjImplicitLod:
  16654. case OpImageSampleDrefImplicitLod:
  16655. case OpImageSampleProjDrefImplicitLod:
  16656. case OpImageFetch:
  16657. case OpImageGather:
  16658. case OpImageDrefGather:
  16659. self.has_sampled_images =
  16660. self.has_sampled_images || self.is_sampled_image_type(self.expression_type(args[2]));
  16661. self.needs_swizzle_buffer_def = self.needs_swizzle_buffer_def || self.has_sampled_images;
  16662. break;
  16663. default:
  16664. break;
  16665. }
  16666. return true;
  16667. }
  16668. // If a needed custom function wasn't added before, add it and force a recompile.
  16669. void CompilerMSL::add_spv_func_and_recompile(SPVFuncImpl spv_func)
  16670. {
  16671. if (spv_function_implementations.count(spv_func) == 0)
  16672. {
  16673. spv_function_implementations.insert(spv_func);
  16674. suppress_missing_prototypes = true;
  16675. force_recompile();
  16676. }
  16677. }
  16678. bool CompilerMSL::OpCodePreprocessor::handle(Op opcode, const uint32_t *args, uint32_t length)
  16679. {
  16680. // Since MSL exists in a single execution scope, function prototype declarations are not
  16681. // needed, and clutter the output. If secondary functions are output (either as a SPIR-V
  16682. // function implementation or as indicated by the presence of OpFunctionCall), then set
  16683. // suppress_missing_prototypes to suppress compiler warnings of missing function prototypes.
  16684. // Mark if the input requires the implementation of an SPIR-V function that does not exist in Metal.
  16685. SPVFuncImpl spv_func = get_spv_func_impl(opcode, args, length);
  16686. if (spv_func != SPVFuncImplNone)
  16687. {
  16688. self.spv_function_implementations.insert(spv_func);
  16689. suppress_missing_prototypes = true;
  16690. }
  16691. switch (opcode)
  16692. {
  16693. case OpFunctionCall:
  16694. suppress_missing_prototypes = true;
  16695. break;
  16696. case OpDemoteToHelperInvocationEXT:
  16697. uses_discard = true;
  16698. break;
  16699. // Emulate texture2D atomic operations
  16700. case OpImageTexelPointer:
  16701. {
  16702. if (!self.msl_options.supports_msl_version(3, 1))
  16703. {
  16704. auto *var = self.maybe_get_backing_variable(args[2]);
  16705. image_pointers_emulated[args[1]] = var ? var->self : ID(0);
  16706. }
  16707. break;
  16708. }
  16709. case OpImageWrite:
  16710. uses_image_write = true;
  16711. break;
  16712. case OpStore:
  16713. check_resource_write(args[0]);
  16714. break;
  16715. // Emulate texture2D atomic operations
  16716. case OpAtomicExchange:
  16717. case OpAtomicCompareExchange:
  16718. case OpAtomicCompareExchangeWeak:
  16719. case OpAtomicIIncrement:
  16720. case OpAtomicIDecrement:
  16721. case OpAtomicIAdd:
  16722. case OpAtomicFAddEXT:
  16723. case OpAtomicISub:
  16724. case OpAtomicSMin:
  16725. case OpAtomicUMin:
  16726. case OpAtomicSMax:
  16727. case OpAtomicUMax:
  16728. case OpAtomicAnd:
  16729. case OpAtomicOr:
  16730. case OpAtomicXor:
  16731. {
  16732. uses_atomics = true;
  16733. auto it = image_pointers_emulated.find(args[2]);
  16734. if (it != image_pointers_emulated.end())
  16735. {
  16736. uses_image_write = true;
  16737. self.atomic_image_vars_emulated.insert(it->second);
  16738. }
  16739. else
  16740. check_resource_write(args[2]);
  16741. break;
  16742. }
  16743. case OpAtomicStore:
  16744. {
  16745. uses_atomics = true;
  16746. auto it = image_pointers_emulated.find(args[0]);
  16747. if (it != image_pointers_emulated.end())
  16748. {
  16749. self.atomic_image_vars_emulated.insert(it->second);
  16750. uses_image_write = true;
  16751. }
  16752. else
  16753. check_resource_write(args[0]);
  16754. break;
  16755. }
  16756. case OpAtomicLoad:
  16757. {
  16758. uses_atomics = true;
  16759. auto it = image_pointers_emulated.find(args[2]);
  16760. if (it != image_pointers_emulated.end())
  16761. {
  16762. self.atomic_image_vars_emulated.insert(it->second);
  16763. }
  16764. break;
  16765. }
  16766. case OpGroupNonUniformInverseBallot:
  16767. needs_subgroup_invocation_id = true;
  16768. break;
  16769. case OpGroupNonUniformBallotFindLSB:
  16770. case OpGroupNonUniformBallotFindMSB:
  16771. needs_subgroup_size = true;
  16772. break;
  16773. case OpGroupNonUniformBallotBitCount:
  16774. if (args[3] == GroupOperationReduce)
  16775. needs_subgroup_size = true;
  16776. else
  16777. needs_subgroup_invocation_id = true;
  16778. break;
  16779. case OpGroupNonUniformRotateKHR:
  16780. // Add the correct invocation ID for calculating clustered rotate case.
  16781. if (length > 5)
  16782. {
  16783. if (static_cast<Scope>(self.evaluate_constant_u32(args[2])) == ScopeSubgroup)
  16784. needs_subgroup_invocation_id = true;
  16785. else
  16786. needs_local_invocation_index = true;
  16787. }
  16788. break;
  16789. case OpGroupNonUniformFAdd:
  16790. case OpGroupNonUniformFMul:
  16791. case OpGroupNonUniformFMin:
  16792. case OpGroupNonUniformFMax:
  16793. case OpGroupNonUniformIAdd:
  16794. case OpGroupNonUniformIMul:
  16795. case OpGroupNonUniformSMin:
  16796. case OpGroupNonUniformSMax:
  16797. case OpGroupNonUniformUMin:
  16798. case OpGroupNonUniformUMax:
  16799. case OpGroupNonUniformBitwiseAnd:
  16800. case OpGroupNonUniformBitwiseOr:
  16801. case OpGroupNonUniformBitwiseXor:
  16802. case OpGroupNonUniformLogicalAnd:
  16803. case OpGroupNonUniformLogicalOr:
  16804. case OpGroupNonUniformLogicalXor:
  16805. if ((compiler.get_execution_model() != ExecutionModelFragment ||
  16806. self.msl_options.supports_msl_version(2, 2)) &&
  16807. args[3] == GroupOperationClusteredReduce)
  16808. needs_subgroup_invocation_id = true;
  16809. break;
  16810. case OpArrayLength:
  16811. {
  16812. auto *var = self.maybe_get_backing_variable(args[2]);
  16813. if (var != nullptr)
  16814. {
  16815. if (!self.is_var_runtime_size_array(*var))
  16816. self.buffers_requiring_array_length.insert(var->self);
  16817. }
  16818. break;
  16819. }
  16820. case OpInBoundsAccessChain:
  16821. case OpAccessChain:
  16822. case OpPtrAccessChain:
  16823. {
  16824. // OpArrayLength might want to know if taking ArrayLength of an array of SSBOs.
  16825. uint32_t result_type = args[0];
  16826. uint32_t id = args[1];
  16827. uint32_t ptr = args[2];
  16828. set<SPIRExpression>(id, "", result_type, true);
  16829. self.register_read(id, ptr, true);
  16830. self.ir.ids[id].set_allow_type_rewrite();
  16831. break;
  16832. }
  16833. case OpExtInst:
  16834. {
  16835. uint32_t extension_set = args[2];
  16836. SPIRExtension::Extension ext = get<SPIRExtension>(extension_set).ext;
  16837. if (ext == SPIRExtension::GLSL)
  16838. {
  16839. auto op_450 = static_cast<GLSLstd450>(args[3]);
  16840. switch (op_450)
  16841. {
  16842. case GLSLstd450InterpolateAtCentroid:
  16843. case GLSLstd450InterpolateAtSample:
  16844. case GLSLstd450InterpolateAtOffset:
  16845. {
  16846. if (!self.msl_options.supports_msl_version(2, 3))
  16847. SPIRV_CROSS_THROW("Pull-model interpolation requires MSL 2.3.");
  16848. // Fragment varyings used with pull-model interpolation need special handling,
  16849. // due to the way pull-model interpolation works in Metal.
  16850. auto *var = self.maybe_get_backing_variable(args[4]);
  16851. if (var)
  16852. {
  16853. self.pull_model_inputs.insert(var->self);
  16854. auto &var_type = self.get_variable_element_type(*var);
  16855. // In addition, if this variable has a 'Sample' decoration, we need the sample ID
  16856. // in order to do default interpolation.
  16857. if (compiler.has_decoration(var->self, DecorationSample))
  16858. {
  16859. needs_sample_id = true;
  16860. }
  16861. else if (var_type.basetype == SPIRType::Struct)
  16862. {
  16863. // Now we need to check each member and see if it has this decoration.
  16864. for (uint32_t i = 0; i < var_type.member_types.size(); ++i)
  16865. {
  16866. if (compiler.has_member_decoration(var_type.self, i, DecorationSample))
  16867. {
  16868. needs_sample_id = true;
  16869. break;
  16870. }
  16871. }
  16872. }
  16873. }
  16874. break;
  16875. }
  16876. default:
  16877. break;
  16878. }
  16879. }
  16880. else if (ext == SPIRExtension::NonSemanticDebugPrintf)
  16881. {
  16882. // Operation 1 is printf.
  16883. if (args[3] == 1 && !self.msl_options.supports_msl_version(3, 2))
  16884. SPIRV_CROSS_THROW("Debug printf requires MSL 3.2.");
  16885. }
  16886. break;
  16887. }
  16888. case OpIsHelperInvocationEXT:
  16889. if (self.needs_manual_helper_invocation_updates())
  16890. needs_helper_invocation = true;
  16891. break;
  16892. default:
  16893. break;
  16894. }
  16895. return true;
  16896. }
  16897. // If the variable is a Uniform or StorageBuffer, mark that a resource has been written to.
  16898. void CompilerMSL::OpCodePreprocessor::check_resource_write(uint32_t var_id)
  16899. {
  16900. auto *type = get_expression_result_type(var_id);
  16901. auto sc = StorageClassMax;
  16902. if (type)
  16903. {
  16904. sc = type->storage;
  16905. }
  16906. else
  16907. {
  16908. auto *var = self.maybe_get_backing_variable(var_id);
  16909. if (var)
  16910. sc = var->storage;
  16911. }
  16912. if (sc == StorageClassUniform || sc == StorageClassStorageBuffer || sc == StorageClassPhysicalStorageBuffer)
  16913. uses_buffer_write = true;
  16914. }
  16915. // Returns an enumeration of a SPIR-V function that needs to be output for certain Op codes.
  16916. CompilerMSL::SPVFuncImpl CompilerMSL::OpCodePreprocessor::get_spv_func_impl(Op opcode, const uint32_t *args, uint32_t length)
  16917. {
  16918. switch (opcode)
  16919. {
  16920. case OpSMod:
  16921. return SPVFuncImplSMod;
  16922. case OpFMod:
  16923. return SPVFuncImplMod;
  16924. case OpFAdd:
  16925. case OpFSub:
  16926. if (self.msl_options.invariant_float_math || self.has_legacy_nocontract(args[0], args[1]))
  16927. return opcode == OpFAdd ? SPVFuncImplFAdd : SPVFuncImplFSub;
  16928. break;
  16929. case OpFMul:
  16930. case OpOuterProduct:
  16931. case OpMatrixTimesVector:
  16932. case OpVectorTimesMatrix:
  16933. case OpMatrixTimesMatrix:
  16934. if (self.msl_options.invariant_float_math || self.has_legacy_nocontract(args[0], args[1]))
  16935. return SPVFuncImplFMul;
  16936. break;
  16937. case OpQuantizeToF16:
  16938. return SPVFuncImplQuantizeToF16;
  16939. case OpTypeArray:
  16940. {
  16941. // Allow Metal to use the array<T> template to make arrays a value type
  16942. return SPVFuncImplUnsafeArray;
  16943. }
  16944. // Emulate texture2D atomic operations
  16945. case OpAtomicExchange:
  16946. case OpAtomicCompareExchange:
  16947. case OpAtomicCompareExchangeWeak:
  16948. case OpAtomicIIncrement:
  16949. case OpAtomicIDecrement:
  16950. case OpAtomicIAdd:
  16951. case OpAtomicFAddEXT:
  16952. case OpAtomicISub:
  16953. case OpAtomicSMin:
  16954. case OpAtomicUMin:
  16955. case OpAtomicSMax:
  16956. case OpAtomicUMax:
  16957. case OpAtomicAnd:
  16958. case OpAtomicOr:
  16959. case OpAtomicXor:
  16960. case OpAtomicLoad:
  16961. case OpAtomicStore:
  16962. {
  16963. auto it = image_pointers_emulated.find(args[opcode == OpAtomicStore ? 0 : 2]);
  16964. if (it != image_pointers_emulated.end())
  16965. {
  16966. uint32_t tid = get<SPIRVariable>(it->second).basetype;
  16967. if (tid && get<SPIRType>(tid).image.dim == Dim2D)
  16968. return SPVFuncImplImage2DAtomicCoords;
  16969. }
  16970. break;
  16971. }
  16972. case OpImageFetch:
  16973. case OpImageRead:
  16974. case OpImageWrite:
  16975. {
  16976. // Retrieve the image type, and if it's a Buffer, emit a texel coordinate function
  16977. uint32_t tid = result_types[args[opcode == OpImageWrite ? 0 : 2]];
  16978. if (tid && get<SPIRType>(tid).image.dim == DimBuffer && !self.msl_options.texture_buffer_native)
  16979. return SPVFuncImplTexelBufferCoords;
  16980. break;
  16981. }
  16982. case OpExtInst:
  16983. {
  16984. uint32_t extension_set = args[2];
  16985. if (get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
  16986. {
  16987. auto op_450 = static_cast<GLSLstd450>(args[3]);
  16988. switch (op_450)
  16989. {
  16990. case GLSLstd450Radians:
  16991. return SPVFuncImplRadians;
  16992. case GLSLstd450Degrees:
  16993. return SPVFuncImplDegrees;
  16994. case GLSLstd450FindILsb:
  16995. return SPVFuncImplFindILsb;
  16996. case GLSLstd450FindSMsb:
  16997. return SPVFuncImplFindSMsb;
  16998. case GLSLstd450FindUMsb:
  16999. return SPVFuncImplFindUMsb;
  17000. case GLSLstd450SSign:
  17001. return SPVFuncImplSSign;
  17002. case GLSLstd450Reflect:
  17003. {
  17004. auto &type = get<SPIRType>(args[0]);
  17005. if (type.vecsize == 1)
  17006. return SPVFuncImplReflectScalar;
  17007. break;
  17008. }
  17009. case GLSLstd450Refract:
  17010. {
  17011. auto &type = get<SPIRType>(args[0]);
  17012. if (type.vecsize == 1)
  17013. return SPVFuncImplRefractScalar;
  17014. break;
  17015. }
  17016. case GLSLstd450FaceForward:
  17017. {
  17018. auto &type = get<SPIRType>(args[0]);
  17019. if (type.vecsize == 1)
  17020. return SPVFuncImplFaceForwardScalar;
  17021. break;
  17022. }
  17023. case GLSLstd450MatrixInverse:
  17024. {
  17025. auto &mat_type = get<SPIRType>(args[0]);
  17026. switch (mat_type.columns)
  17027. {
  17028. case 2:
  17029. return SPVFuncImplInverse2x2;
  17030. case 3:
  17031. return SPVFuncImplInverse3x3;
  17032. case 4:
  17033. return SPVFuncImplInverse4x4;
  17034. default:
  17035. break;
  17036. }
  17037. break;
  17038. }
  17039. default:
  17040. break;
  17041. }
  17042. }
  17043. break;
  17044. }
  17045. case OpGroupNonUniformBroadcast:
  17046. case OpSubgroupReadInvocationKHR:
  17047. return SPVFuncImplSubgroupBroadcast;
  17048. case OpGroupNonUniformBroadcastFirst:
  17049. case OpSubgroupFirstInvocationKHR:
  17050. return SPVFuncImplSubgroupBroadcastFirst;
  17051. case OpGroupNonUniformBallot:
  17052. case OpSubgroupBallotKHR:
  17053. return SPVFuncImplSubgroupBallot;
  17054. case OpGroupNonUniformInverseBallot:
  17055. case OpGroupNonUniformBallotBitExtract:
  17056. return SPVFuncImplSubgroupBallotBitExtract;
  17057. case OpGroupNonUniformBallotFindLSB:
  17058. return SPVFuncImplSubgroupBallotFindLSB;
  17059. case OpGroupNonUniformBallotFindMSB:
  17060. return SPVFuncImplSubgroupBallotFindMSB;
  17061. case OpGroupNonUniformBallotBitCount:
  17062. return SPVFuncImplSubgroupBallotBitCount;
  17063. case OpGroupNonUniformAllEqual:
  17064. case OpSubgroupAllEqualKHR:
  17065. return SPVFuncImplSubgroupAllEqual;
  17066. case OpGroupNonUniformShuffle:
  17067. return SPVFuncImplSubgroupShuffle;
  17068. case OpGroupNonUniformShuffleXor:
  17069. return SPVFuncImplSubgroupShuffleXor;
  17070. case OpGroupNonUniformShuffleUp:
  17071. return SPVFuncImplSubgroupShuffleUp;
  17072. case OpGroupNonUniformShuffleDown:
  17073. return SPVFuncImplSubgroupShuffleDown;
  17074. case OpGroupNonUniformRotateKHR:
  17075. // Clustered rotate is performed using shuffle.
  17076. if (length > 5)
  17077. return SPVFuncImplSubgroupShuffle;
  17078. return SPVFuncImplSubgroupRotate;
  17079. case OpGroupNonUniformQuadBroadcast:
  17080. return SPVFuncImplQuadBroadcast;
  17081. case OpGroupNonUniformQuadSwap:
  17082. return SPVFuncImplQuadSwap;
  17083. case OpSDot:
  17084. case OpUDot:
  17085. case OpSUDot:
  17086. case OpSDotAccSat:
  17087. case OpUDotAccSat:
  17088. case OpSUDotAccSat:
  17089. return SPVFuncImplReduceAdd;
  17090. case OpSMulExtended:
  17091. case OpUMulExtended:
  17092. return SPVFuncImplMulExtended;
  17093. case OpAssumeTrueKHR:
  17094. case OpExpectKHR:
  17095. return SPVFuncImplAssume;
  17096. default:
  17097. break;
  17098. }
  17099. return SPVFuncImplNone;
  17100. }
  17101. // Sort both type and meta member content based on builtin status (put builtins at end),
  17102. // then by the required sorting aspect.
  17103. void CompilerMSL::MemberSorter::sort()
  17104. {
  17105. // Create a temporary array of consecutive member indices and sort it based on how
  17106. // the members should be reordered, based on builtin and sorting aspect meta info.
  17107. size_t mbr_cnt = type.member_types.size();
  17108. SmallVector<uint32_t> mbr_idxs(mbr_cnt);
  17109. std::iota(mbr_idxs.begin(), mbr_idxs.end(), 0); // Fill with consecutive indices
  17110. std::stable_sort(mbr_idxs.begin(), mbr_idxs.end(), *this); // Sort member indices based on sorting aspect
  17111. bool sort_is_identity = true;
  17112. for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
  17113. {
  17114. if (mbr_idx != mbr_idxs[mbr_idx])
  17115. {
  17116. sort_is_identity = false;
  17117. break;
  17118. }
  17119. }
  17120. if (sort_is_identity)
  17121. return;
  17122. if (meta.members.size() < type.member_types.size())
  17123. {
  17124. // This should never trigger in normal circumstances, but to be safe.
  17125. meta.members.resize(type.member_types.size());
  17126. }
  17127. // Move type and meta member info to the order defined by the sorted member indices.
  17128. // This is done by creating temporary copies of both member types and meta, and then
  17129. // copying back to the original content at the sorted indices.
  17130. auto mbr_types_cpy = type.member_types;
  17131. auto mbr_meta_cpy = meta.members;
  17132. for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
  17133. {
  17134. type.member_types[mbr_idx] = mbr_types_cpy[mbr_idxs[mbr_idx]];
  17135. meta.members[mbr_idx] = mbr_meta_cpy[mbr_idxs[mbr_idx]];
  17136. }
  17137. // If we're sorting by Offset, this might affect user code which accesses a buffer block.
  17138. // We will need to redirect member indices from defined index to sorted index using reverse lookup.
  17139. if (sort_aspect == SortAspect::Offset)
  17140. {
  17141. type.member_type_index_redirection.resize(mbr_cnt);
  17142. for (uint32_t map_idx = 0; map_idx < mbr_cnt; map_idx++)
  17143. type.member_type_index_redirection[mbr_idxs[map_idx]] = map_idx;
  17144. }
  17145. }
  17146. bool CompilerMSL::MemberSorter::operator()(uint32_t mbr_idx1, uint32_t mbr_idx2)
  17147. {
  17148. auto &mbr_meta1 = meta.members[mbr_idx1];
  17149. auto &mbr_meta2 = meta.members[mbr_idx2];
  17150. if (sort_aspect == LocationThenBuiltInType)
  17151. {
  17152. // Sort first by builtin status (put builtins at end), then by the sorting aspect.
  17153. if (mbr_meta1.builtin != mbr_meta2.builtin)
  17154. return mbr_meta2.builtin;
  17155. else if (mbr_meta1.builtin)
  17156. return mbr_meta1.builtin_type < mbr_meta2.builtin_type;
  17157. else if (mbr_meta1.location == mbr_meta2.location)
  17158. return mbr_meta1.component < mbr_meta2.component;
  17159. else
  17160. return mbr_meta1.location < mbr_meta2.location;
  17161. }
  17162. else
  17163. return mbr_meta1.offset < mbr_meta2.offset;
  17164. }
  17165. CompilerMSL::MemberSorter::MemberSorter(SPIRType &t, Meta &m, SortAspect sa)
  17166. : type(t)
  17167. , meta(m)
  17168. , sort_aspect(sa)
  17169. {
  17170. // Ensure enough meta info is available
  17171. meta.members.resize(max(type.member_types.size(), meta.members.size()));
  17172. }
  17173. void CompilerMSL::remap_constexpr_sampler(VariableID id, const MSLConstexprSampler &sampler)
  17174. {
  17175. auto &type = get<SPIRType>(get<SPIRVariable>(id).basetype);
  17176. if (type.basetype != SPIRType::SampledImage && type.basetype != SPIRType::Sampler)
  17177. SPIRV_CROSS_THROW("Can only remap SampledImage and Sampler type.");
  17178. if (!type.array.empty())
  17179. SPIRV_CROSS_THROW("Can not remap array of samplers.");
  17180. constexpr_samplers_by_id[id] = sampler;
  17181. }
  17182. void CompilerMSL::remap_constexpr_sampler_by_binding(uint32_t desc_set, uint32_t binding,
  17183. const MSLConstexprSampler &sampler)
  17184. {
  17185. constexpr_samplers_by_binding[{ desc_set, binding }] = sampler;
  17186. }
  17187. void CompilerMSL::cast_from_variable_load(uint32_t source_id, std::string &expr, const SPIRType &expr_type)
  17188. {
  17189. bool is_packed = has_extended_decoration(source_id, SPIRVCrossDecorationPhysicalTypePacked);
  17190. auto *source_expr = maybe_get<SPIRExpression>(source_id);
  17191. auto *var = maybe_get_backing_variable(source_id);
  17192. const SPIRType *var_type = nullptr, *phys_type = nullptr;
  17193. if (uint32_t phys_id = get_extended_decoration(source_id, SPIRVCrossDecorationPhysicalTypeID))
  17194. phys_type = &get<SPIRType>(phys_id);
  17195. else
  17196. phys_type = &expr_type;
  17197. if (var)
  17198. {
  17199. source_id = var->self;
  17200. var_type = &get_variable_data_type(*var);
  17201. }
  17202. bool rewrite_boolean_load =
  17203. expr_type.basetype == SPIRType::Boolean &&
  17204. (var && (var->storage == StorageClassWorkgroup || var_type->basetype == SPIRType::Struct));
  17205. // Type fixups for workgroup variables if they are booleans.
  17206. if (rewrite_boolean_load)
  17207. {
  17208. if (is_array(expr_type))
  17209. expr = to_rerolled_array_expression(expr_type, expr, expr_type);
  17210. else
  17211. expr = join(type_to_glsl(expr_type), "(", expr, ")");
  17212. }
  17213. // Type fixups for workgroup variables if they are matrices.
  17214. // Don't do fixup for packed types; those are handled specially.
  17215. // FIXME: Maybe use a type like spvStorageMatrix for packed matrices?
  17216. if (!msl_options.supports_msl_version(3, 0) && var &&
  17217. (var->storage == StorageClassWorkgroup ||
  17218. (var_type->basetype == SPIRType::Struct &&
  17219. has_extended_decoration(var_type->self, SPIRVCrossDecorationWorkgroupStruct) && !is_packed)) &&
  17220. expr_type.columns > 1)
  17221. {
  17222. SPIRType matrix_type = *phys_type;
  17223. if (source_expr && source_expr->need_transpose)
  17224. swap(matrix_type.vecsize, matrix_type.columns);
  17225. matrix_type.array.clear();
  17226. matrix_type.array_size_literal.clear();
  17227. expr = join(type_to_glsl(matrix_type), "(", expr, ")");
  17228. }
  17229. // Only interested in standalone builtin variables in the switch below.
  17230. if (!has_decoration(source_id, DecorationBuiltIn))
  17231. {
  17232. // If the backing variable does not match our expected sign, we can fix it up here.
  17233. // See ensure_correct_input_type().
  17234. if (var && var->storage == StorageClassInput)
  17235. {
  17236. auto &base_type = get<SPIRType>(var->basetype);
  17237. if (base_type.basetype != SPIRType::Struct && expr_type.basetype != base_type.basetype)
  17238. expr = join(type_to_glsl(expr_type), "(", expr, ")");
  17239. }
  17240. return;
  17241. }
  17242. auto builtin = static_cast<BuiltIn>(get_decoration(source_id, DecorationBuiltIn));
  17243. auto expected_type = expr_type.basetype;
  17244. auto expected_width = expr_type.width;
  17245. switch (builtin)
  17246. {
  17247. case BuiltInGlobalInvocationId:
  17248. case BuiltInLocalInvocationId:
  17249. case BuiltInWorkgroupId:
  17250. case BuiltInLocalInvocationIndex:
  17251. case BuiltInWorkgroupSize:
  17252. case BuiltInNumWorkgroups:
  17253. case BuiltInLayer:
  17254. case BuiltInViewportIndex:
  17255. case BuiltInFragStencilRefEXT:
  17256. case BuiltInPrimitiveId:
  17257. case BuiltInSubgroupSize:
  17258. case BuiltInSubgroupLocalInvocationId:
  17259. case BuiltInViewIndex:
  17260. case BuiltInVertexIndex:
  17261. case BuiltInInstanceIndex:
  17262. case BuiltInBaseInstance:
  17263. case BuiltInBaseVertex:
  17264. case BuiltInSampleMask:
  17265. expected_type = SPIRType::UInt;
  17266. expected_width = 32;
  17267. break;
  17268. case BuiltInTessLevelInner:
  17269. case BuiltInTessLevelOuter:
  17270. if (is_tesc_shader())
  17271. {
  17272. expected_type = SPIRType::Half;
  17273. expected_width = 16;
  17274. }
  17275. break;
  17276. default:
  17277. break;
  17278. }
  17279. if (is_array(expr_type) && builtin == BuiltInSampleMask)
  17280. {
  17281. // Needs special handling.
  17282. auto wrap_expr = join(type_to_glsl(expr_type), "({ ");
  17283. wrap_expr += join(type_to_glsl(get<SPIRType>(expr_type.parent_type)), "(", expr, ")");
  17284. wrap_expr += " })";
  17285. expr = std::move(wrap_expr);
  17286. }
  17287. else if (expected_type != expr_type.basetype)
  17288. {
  17289. if (is_array(expr_type) && (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter))
  17290. {
  17291. // Triggers when loading TessLevel directly as an array.
  17292. // Need explicit padding + cast.
  17293. auto wrap_expr = join(type_to_glsl(expr_type), "({ ");
  17294. uint32_t array_size = get_physical_tess_level_array_size(builtin);
  17295. for (uint32_t i = 0; i < array_size; i++)
  17296. {
  17297. if (array_size > 1)
  17298. wrap_expr += join("float(", expr, "[", i, "])");
  17299. else
  17300. wrap_expr += join("float(", expr, ")");
  17301. if (i + 1 < array_size)
  17302. wrap_expr += ", ";
  17303. }
  17304. if (is_tessellating_triangles())
  17305. wrap_expr += ", 0.0";
  17306. wrap_expr += " })";
  17307. expr = std::move(wrap_expr);
  17308. }
  17309. else
  17310. {
  17311. // These are of different widths, so we cannot do a straight bitcast.
  17312. if (expected_width != expr_type.width)
  17313. expr = join(type_to_glsl(expr_type), "(", expr, ")");
  17314. else
  17315. expr = bitcast_expression(expr_type, expected_type, expr);
  17316. }
  17317. }
  17318. }
  17319. void CompilerMSL::cast_to_variable_store(uint32_t target_id, std::string &expr, const SPIRType &expr_type)
  17320. {
  17321. bool is_packed = has_extended_decoration(target_id, SPIRVCrossDecorationPhysicalTypePacked);
  17322. auto *target_expr = maybe_get<SPIRExpression>(target_id);
  17323. auto *var = maybe_get_backing_variable(target_id);
  17324. const SPIRType *var_type = nullptr, *phys_type = nullptr;
  17325. if (uint32_t phys_id = get_extended_decoration(target_id, SPIRVCrossDecorationPhysicalTypeID))
  17326. phys_type = &get<SPIRType>(phys_id);
  17327. else
  17328. phys_type = &expr_type;
  17329. if (var)
  17330. {
  17331. target_id = var->self;
  17332. var_type = &get_variable_data_type(*var);
  17333. }
  17334. bool rewrite_boolean_store =
  17335. expr_type.basetype == SPIRType::Boolean &&
  17336. (var && (var->storage == StorageClassWorkgroup || var_type->basetype == SPIRType::Struct));
  17337. // Type fixups for workgroup variables or struct members if they are booleans.
  17338. if (rewrite_boolean_store)
  17339. {
  17340. if (is_array(expr_type))
  17341. {
  17342. expr = to_rerolled_array_expression(*var_type, expr, expr_type);
  17343. }
  17344. else
  17345. {
  17346. auto short_type = expr_type;
  17347. short_type.basetype = SPIRType::Short;
  17348. expr = join(type_to_glsl(short_type), "(", expr, ")");
  17349. }
  17350. }
  17351. // Type fixups for workgroup variables if they are matrices.
  17352. // Don't do fixup for packed types; those are handled specially.
  17353. // FIXME: Maybe use a type like spvStorageMatrix for packed matrices?
  17354. if (!msl_options.supports_msl_version(3, 0) && var &&
  17355. (var->storage == StorageClassWorkgroup ||
  17356. (var_type->basetype == SPIRType::Struct &&
  17357. has_extended_decoration(var_type->self, SPIRVCrossDecorationWorkgroupStruct) && !is_packed)) &&
  17358. expr_type.columns > 1)
  17359. {
  17360. SPIRType matrix_type = *phys_type;
  17361. if (target_expr && target_expr->need_transpose)
  17362. swap(matrix_type.vecsize, matrix_type.columns);
  17363. expr = join("spvStorage_", type_to_glsl(matrix_type), "(", expr, ")");
  17364. }
  17365. // Only interested in standalone builtin variables.
  17366. if (!has_decoration(target_id, DecorationBuiltIn))
  17367. return;
  17368. auto builtin = static_cast<BuiltIn>(get_decoration(target_id, DecorationBuiltIn));
  17369. auto expected_type = expr_type.basetype;
  17370. auto expected_width = expr_type.width;
  17371. switch (builtin)
  17372. {
  17373. case BuiltInLayer:
  17374. case BuiltInViewportIndex:
  17375. case BuiltInFragStencilRefEXT:
  17376. case BuiltInPrimitiveId:
  17377. case BuiltInViewIndex:
  17378. expected_type = SPIRType::UInt;
  17379. expected_width = 32;
  17380. break;
  17381. case BuiltInTessLevelInner:
  17382. case BuiltInTessLevelOuter:
  17383. expected_type = SPIRType::Half;
  17384. expected_width = 16;
  17385. break;
  17386. default:
  17387. break;
  17388. }
  17389. if (expected_type != expr_type.basetype)
  17390. {
  17391. if (expected_width != expr_type.width)
  17392. {
  17393. // These are of different widths, so we cannot do a straight bitcast.
  17394. auto type = expr_type;
  17395. type.basetype = expected_type;
  17396. type.width = expected_width;
  17397. expr = join(type_to_glsl(type), "(", expr, ")");
  17398. }
  17399. else
  17400. {
  17401. auto type = expr_type;
  17402. type.basetype = expected_type;
  17403. expr = bitcast_expression(type, expr_type.basetype, expr);
  17404. }
  17405. }
  17406. }
  17407. string CompilerMSL::to_initializer_expression(const SPIRVariable &var)
  17408. {
  17409. // We risk getting an array initializer here with MSL. If we have an array.
  17410. // FIXME: We cannot handle non-constant arrays being initialized.
  17411. // We will need to inject spvArrayCopy here somehow ...
  17412. auto &type = get<SPIRType>(var.basetype);
  17413. string expr;
  17414. if (ir.ids[var.initializer].get_type() == TypeConstant &&
  17415. (!type.array.empty() || type.basetype == SPIRType::Struct))
  17416. expr = constant_expression(get<SPIRConstant>(var.initializer));
  17417. else
  17418. expr = CompilerGLSL::to_initializer_expression(var);
  17419. // If the initializer has more vector components than the variable, add a swizzle.
  17420. // FIXME: This can't handle arrays or structs.
  17421. auto &init_type = expression_type(var.initializer);
  17422. if (type.array.empty() && type.basetype != SPIRType::Struct && init_type.vecsize > type.vecsize)
  17423. expr = enclose_expression(expr + vector_swizzle(type.vecsize, 0));
  17424. return expr;
  17425. }
  17426. string CompilerMSL::to_zero_initialized_expression(uint32_t)
  17427. {
  17428. return "{}";
  17429. }
  17430. bool CompilerMSL::descriptor_set_is_argument_buffer(uint32_t desc_set) const
  17431. {
  17432. if (!msl_options.argument_buffers)
  17433. return false;
  17434. if (desc_set >= kMaxArgumentBuffers)
  17435. return false;
  17436. return (argument_buffer_discrete_mask & (1u << desc_set)) == 0;
  17437. }
  17438. bool CompilerMSL::is_supported_argument_buffer_type(const SPIRType &type) const
  17439. {
  17440. // iOS Tier 1 argument buffers do not support writable images.
  17441. // When the argument buffer is encoded, we don't know whether this image will have a
  17442. // NonWritable decoration, so just use discrete arguments for all storage images on iOS.
  17443. bool is_supported_type = !(type.basetype == SPIRType::Image &&
  17444. type.image.sampled == 2 &&
  17445. msl_options.is_ios() &&
  17446. msl_options.argument_buffers_tier <= Options::ArgumentBuffersTier::Tier1);
  17447. return is_supported_type && !type_is_msl_framebuffer_fetch(type);
  17448. }
  17449. void CompilerMSL::emit_argument_buffer_aliased_descriptor(const SPIRVariable &aliased_var,
  17450. const SPIRVariable &base_var)
  17451. {
  17452. // To deal with buffer <-> image aliasing, we need to perform an unholy UB ritual.
  17453. // A texture type in Metal 3.0 is a pointer. However, we cannot simply cast a pointer to texture.
  17454. // What we *can* do is to cast pointer-to-pointer to pointer-to-texture.
  17455. // We need to explicitly reach into the descriptor buffer lvalue, not any spvDescriptorArray wrapper.
  17456. auto *var_meta = ir.find_meta(base_var.self);
  17457. bool old_explicit_qualifier = var_meta && var_meta->decoration.qualified_alias_explicit_override;
  17458. if (var_meta)
  17459. var_meta->decoration.qualified_alias_explicit_override = false;
  17460. auto unqualified_name = to_name(base_var.self, false);
  17461. if (var_meta)
  17462. var_meta->decoration.qualified_alias_explicit_override = old_explicit_qualifier;
  17463. // For non-arrayed buffers, we have already performed a de-reference.
  17464. // We need a proper lvalue to cast, so strip away the de-reference.
  17465. if (unqualified_name.size() > 2 && unqualified_name[0] == '(' && unqualified_name[1] == '*')
  17466. {
  17467. unqualified_name.erase(unqualified_name.begin(), unqualified_name.begin() + 2);
  17468. unqualified_name.pop_back();
  17469. }
  17470. string name;
  17471. auto &var_type = get<SPIRType>(aliased_var.basetype);
  17472. auto &data_type = get_variable_data_type(aliased_var);
  17473. string descriptor_storage = descriptor_address_space(aliased_var.self, aliased_var.storage, "");
  17474. if (aliased_var.storage == StorageClassUniformConstant)
  17475. {
  17476. if (is_var_runtime_size_array(aliased_var))
  17477. {
  17478. // This becomes a plain pointer to spvDescriptor.
  17479. name = join("reinterpret_cast<", descriptor_storage, " ",
  17480. type_to_glsl(get_variable_data_type(aliased_var), aliased_var.self, true), ">(&",
  17481. unqualified_name, ")");
  17482. }
  17483. else
  17484. {
  17485. name = join("reinterpret_cast<", descriptor_storage, " ",
  17486. type_to_glsl(get_variable_data_type(aliased_var), aliased_var.self, true), " &>(",
  17487. unqualified_name, ");");
  17488. }
  17489. }
  17490. else
  17491. {
  17492. // Buffer types.
  17493. bool old_is_using_builtin_array = is_using_builtin_array;
  17494. is_using_builtin_array = true;
  17495. bool needs_post_cast_deref = !is_array(data_type);
  17496. string ref_type = needs_post_cast_deref ? "&" : join("(&)", type_to_array_glsl(var_type, aliased_var.self));
  17497. if (is_var_runtime_size_array(aliased_var))
  17498. {
  17499. name = join("reinterpret_cast<",
  17500. type_to_glsl(var_type, aliased_var.self, true), " ", descriptor_storage, " *>(&",
  17501. unqualified_name, ")");
  17502. }
  17503. else
  17504. {
  17505. name = join(needs_post_cast_deref ? "*" : "", "reinterpret_cast<",
  17506. type_to_glsl(var_type, aliased_var.self, true), " ", descriptor_storage, " ",
  17507. ref_type,
  17508. ">(", unqualified_name, ");");
  17509. }
  17510. if (needs_post_cast_deref)
  17511. descriptor_storage = get_type_address_space(var_type, aliased_var.self, false);
  17512. // These kinds of ridiculous casts trigger warnings in compiler. Just ignore them.
  17513. if (!suppress_incompatible_pointer_types_discard_qualifiers)
  17514. {
  17515. suppress_incompatible_pointer_types_discard_qualifiers = true;
  17516. force_recompile_guarantee_forward_progress();
  17517. }
  17518. is_using_builtin_array = old_is_using_builtin_array;
  17519. }
  17520. if (!is_var_runtime_size_array(aliased_var))
  17521. {
  17522. // Lower to temporary, so drop the qualification.
  17523. set_qualified_name(aliased_var.self, "");
  17524. statement(descriptor_storage, " auto &", to_name(aliased_var.self), " = ", name);
  17525. }
  17526. else
  17527. {
  17528. // This alias may have already been used to emit an entry point declaration. If there is a mismatch, we need a recompile.
  17529. // Moving this code to be run earlier will also conflict,
  17530. // because we need the qualified alias for the base resource,
  17531. // so forcing recompile until things sync up is the least invasive method for now.
  17532. if (ir.meta[aliased_var.self].decoration.qualified_alias != name)
  17533. force_recompile();
  17534. // This will get wrapped in a separate temporary when a spvDescriptorArray wrapper is emitted.
  17535. set_qualified_name(aliased_var.self, name);
  17536. }
  17537. }
  17538. void CompilerMSL::analyze_argument_buffers()
  17539. {
  17540. // Gather all used resources and sort them out into argument buffers.
  17541. // Each argument buffer corresponds to a descriptor set in SPIR-V.
  17542. // The [[id(N)]] values used correspond to the resource mapping we have for MSL.
  17543. // Otherwise, the binding number is used, but this is generally not safe some types like
  17544. // combined image samplers and arrays of resources. Metal needs different indices here,
  17545. // while SPIR-V can have one descriptor set binding. To use argument buffers in practice,
  17546. // you will need to use the remapping from the API.
  17547. for (auto &id : argument_buffer_ids)
  17548. id = 0;
  17549. // Output resources, sorted by resource index & type.
  17550. struct Resource
  17551. {
  17552. SPIRVariable *var;
  17553. string name;
  17554. SPIRType::BaseType basetype;
  17555. uint32_t index;
  17556. uint32_t plane_count;
  17557. uint32_t plane;
  17558. uint32_t overlapping_var_id;
  17559. };
  17560. SmallVector<Resource> resources_in_set[kMaxArgumentBuffers];
  17561. SmallVector<uint32_t> inline_block_vars;
  17562. bool set_needs_swizzle_buffer[kMaxArgumentBuffers] = {};
  17563. bool set_needs_buffer_sizes[kMaxArgumentBuffers] = {};
  17564. bool needs_buffer_sizes = false;
  17565. ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, SPIRVariable &var) {
  17566. if ((var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant ||
  17567. var.storage == StorageClassStorageBuffer) &&
  17568. !is_hidden_variable(var))
  17569. {
  17570. uint32_t desc_set = get_decoration(self, DecorationDescriptorSet);
  17571. // Ignore if it's part of a push descriptor set.
  17572. if (!descriptor_set_is_argument_buffer(desc_set))
  17573. return;
  17574. uint32_t var_id = var.self;
  17575. auto &type = get_variable_data_type(var);
  17576. if (desc_set >= kMaxArgumentBuffers)
  17577. SPIRV_CROSS_THROW("Descriptor set index is out of range.");
  17578. const MSLConstexprSampler *constexpr_sampler = nullptr;
  17579. if (type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::Sampler)
  17580. {
  17581. constexpr_sampler = find_constexpr_sampler(var_id);
  17582. if (constexpr_sampler)
  17583. {
  17584. // Mark this ID as a constexpr sampler for later in case it came from set/bindings.
  17585. constexpr_samplers_by_id[var_id] = *constexpr_sampler;
  17586. }
  17587. }
  17588. uint32_t binding = get_decoration(var_id, DecorationBinding);
  17589. if (type.basetype == SPIRType::SampledImage)
  17590. {
  17591. add_resource_name(var_id);
  17592. uint32_t plane_count = 1;
  17593. if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
  17594. plane_count = constexpr_sampler->planes;
  17595. for (uint32_t i = 0; i < plane_count; i++)
  17596. {
  17597. uint32_t image_resource_index = get_metal_resource_index(var, SPIRType::Image, i);
  17598. resources_in_set[desc_set].push_back(
  17599. { &var, to_name(var_id), SPIRType::Image, image_resource_index, plane_count, i, 0 });
  17600. }
  17601. if (type.image.dim != DimBuffer && !constexpr_sampler)
  17602. {
  17603. uint32_t sampler_resource_index = get_metal_resource_index(var, SPIRType::Sampler);
  17604. resources_in_set[desc_set].push_back(
  17605. { &var, to_sampler_expression(var_id), SPIRType::Sampler, sampler_resource_index, 1, 0, 0 });
  17606. }
  17607. }
  17608. else if (inline_uniform_blocks.count(SetBindingPair{ desc_set, binding }))
  17609. {
  17610. inline_block_vars.push_back(var_id);
  17611. }
  17612. else if (!constexpr_sampler && is_supported_argument_buffer_type(type))
  17613. {
  17614. // constexpr samplers are not declared as resources.
  17615. // Inline uniform blocks are always emitted at the end.
  17616. add_resource_name(var_id);
  17617. uint32_t resource_index = get_metal_resource_index(var, type.basetype);
  17618. resources_in_set[desc_set].push_back(
  17619. { &var, to_name(var_id), type.basetype, resource_index, 1, 0, 0 });
  17620. // Emulate texture2D atomic operations
  17621. if (atomic_image_vars_emulated.count(var.self))
  17622. {
  17623. uint32_t buffer_resource_index = get_metal_resource_index(var, SPIRType::AtomicCounter, 0);
  17624. resources_in_set[desc_set].push_back(
  17625. { &var, to_name(var_id) + "_atomic", SPIRType::Struct, buffer_resource_index, 1, 0, 0 });
  17626. }
  17627. }
  17628. // Check if this descriptor set needs a swizzle buffer.
  17629. if (needs_swizzle_buffer_def && is_sampled_image_type(type))
  17630. set_needs_swizzle_buffer[desc_set] = true;
  17631. else if (buffer_requires_array_length(var_id))
  17632. {
  17633. set_needs_buffer_sizes[desc_set] = true;
  17634. needs_buffer_sizes = true;
  17635. }
  17636. }
  17637. });
  17638. if (needs_swizzle_buffer_def || needs_buffer_sizes)
  17639. {
  17640. uint32_t uint_ptr_type_id = 0;
  17641. // We might have to add a swizzle buffer resource to the set.
  17642. for (uint32_t desc_set = 0; desc_set < kMaxArgumentBuffers; desc_set++)
  17643. {
  17644. if (!set_needs_swizzle_buffer[desc_set] && !set_needs_buffer_sizes[desc_set])
  17645. continue;
  17646. if (uint_ptr_type_id == 0)
  17647. {
  17648. uint_ptr_type_id = ir.increase_bound_by(1);
  17649. // Create a buffer to hold extra data, including the swizzle constants.
  17650. SPIRType uint_type_pointer = get_uint_type();
  17651. uint_type_pointer.op = OpTypePointer;
  17652. uint_type_pointer.pointer = true;
  17653. uint_type_pointer.pointer_depth++;
  17654. uint_type_pointer.parent_type = get_uint_type_id();
  17655. uint_type_pointer.storage = StorageClassUniform;
  17656. set<SPIRType>(uint_ptr_type_id, uint_type_pointer);
  17657. set_decoration(uint_ptr_type_id, DecorationArrayStride, 4);
  17658. }
  17659. if (set_needs_swizzle_buffer[desc_set])
  17660. {
  17661. uint32_t var_id = ir.increase_bound_by(1);
  17662. auto &var = set<SPIRVariable>(var_id, uint_ptr_type_id, StorageClassUniformConstant);
  17663. set_name(var_id, "spvSwizzleConstants");
  17664. set_decoration(var_id, DecorationDescriptorSet, desc_set);
  17665. set_decoration(var_id, DecorationBinding, kSwizzleBufferBinding);
  17666. resources_in_set[desc_set].push_back(
  17667. { &var, to_name(var_id), SPIRType::UInt, get_metal_resource_index(var, SPIRType::UInt), 1, 0, 0 });
  17668. }
  17669. if (set_needs_buffer_sizes[desc_set])
  17670. {
  17671. uint32_t var_id = ir.increase_bound_by(1);
  17672. auto &var = set<SPIRVariable>(var_id, uint_ptr_type_id, StorageClassUniformConstant);
  17673. set_name(var_id, "spvBufferSizeConstants");
  17674. set_decoration(var_id, DecorationDescriptorSet, desc_set);
  17675. set_decoration(var_id, DecorationBinding, kBufferSizeBufferBinding);
  17676. resources_in_set[desc_set].push_back(
  17677. { &var, to_name(var_id), SPIRType::UInt, get_metal_resource_index(var, SPIRType::UInt), 1, 0, 0 });
  17678. }
  17679. }
  17680. }
  17681. // Now add inline uniform blocks.
  17682. for (uint32_t var_id : inline_block_vars)
  17683. {
  17684. auto &var = get<SPIRVariable>(var_id);
  17685. uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
  17686. add_resource_name(var_id);
  17687. resources_in_set[desc_set].push_back(
  17688. { &var, to_name(var_id), SPIRType::Struct, get_metal_resource_index(var, SPIRType::Struct), 1, 0, 0 });
  17689. }
  17690. for (uint32_t desc_set = 0; desc_set < kMaxArgumentBuffers; desc_set++)
  17691. {
  17692. auto &resources = resources_in_set[desc_set];
  17693. if (resources.empty())
  17694. continue;
  17695. assert(descriptor_set_is_argument_buffer(desc_set));
  17696. uint32_t next_id = ir.increase_bound_by(3);
  17697. uint32_t type_id = next_id + 1;
  17698. uint32_t ptr_type_id = next_id + 2;
  17699. argument_buffer_ids[desc_set] = next_id;
  17700. auto &buffer_type = set<SPIRType>(type_id, OpTypeStruct);
  17701. buffer_type.basetype = SPIRType::Struct;
  17702. if ((argument_buffer_device_storage_mask & (1u << desc_set)) != 0)
  17703. {
  17704. buffer_type.storage = StorageClassStorageBuffer;
  17705. // Make sure the argument buffer gets marked as const device.
  17706. set_decoration(next_id, DecorationNonWritable);
  17707. // Need to mark the type as a Block to enable this.
  17708. set_decoration(type_id, DecorationBlock);
  17709. }
  17710. else
  17711. buffer_type.storage = StorageClassUniform;
  17712. auto buffer_type_name = join("spvDescriptorSetBuffer", desc_set);
  17713. set_name(type_id, buffer_type_name);
  17714. auto &ptr_type = set<SPIRType>(ptr_type_id, OpTypePointer);
  17715. ptr_type = buffer_type;
  17716. ptr_type.op = OpTypePointer;
  17717. ptr_type.pointer = true;
  17718. ptr_type.pointer_depth++;
  17719. ptr_type.parent_type = type_id;
  17720. uint32_t buffer_variable_id = next_id;
  17721. auto &buffer_var = set<SPIRVariable>(buffer_variable_id, ptr_type_id, StorageClassUniform);
  17722. auto buffer_name = join("spvDescriptorSet", desc_set);
  17723. set_name(buffer_variable_id, buffer_name);
  17724. // Ids must be emitted in ID order.
  17725. stable_sort(begin(resources), end(resources), [&](const Resource &lhs, const Resource &rhs) -> bool {
  17726. return tie(lhs.index, lhs.basetype) < tie(rhs.index, rhs.basetype);
  17727. });
  17728. for (size_t i = 0; i < resources.size() - 1; i++)
  17729. {
  17730. auto &r1 = resources[i];
  17731. auto &r2 = resources[i + 1];
  17732. if (r1.index == r2.index)
  17733. {
  17734. if (r1.overlapping_var_id)
  17735. r2.overlapping_var_id = r1.overlapping_var_id;
  17736. else
  17737. r2.overlapping_var_id = r1.var->self;
  17738. set_extended_decoration(r2.var->self, SPIRVCrossDecorationOverlappingBinding, r2.overlapping_var_id);
  17739. }
  17740. }
  17741. uint32_t member_index = 0;
  17742. uint32_t next_arg_buff_index = 0;
  17743. uint32_t prev_was_scalar_on_array_offset = 0;
  17744. for (auto &resource : resources)
  17745. {
  17746. auto &var = *resource.var;
  17747. auto &type = get_variable_data_type(var);
  17748. if (is_var_runtime_size_array(var) && (argument_buffer_device_storage_mask & (1u << desc_set)) == 0)
  17749. SPIRV_CROSS_THROW("Runtime sized variables must be in device storage argument buffers.");
  17750. // If needed, synthesize and add padding members.
  17751. // member_index and next_arg_buff_index are incremented when padding members are added.
  17752. if (msl_options.pad_argument_buffer_resources && resource.plane == 0 && resource.overlapping_var_id == 0)
  17753. {
  17754. auto rez_bind = get_argument_buffer_resource(desc_set, next_arg_buff_index - prev_was_scalar_on_array_offset);
  17755. rez_bind.count -= prev_was_scalar_on_array_offset;
  17756. while (resource.index > next_arg_buff_index)
  17757. {
  17758. switch (rez_bind.basetype)
  17759. {
  17760. case SPIRType::Void:
  17761. case SPIRType::Boolean:
  17762. case SPIRType::SByte:
  17763. case SPIRType::UByte:
  17764. case SPIRType::Short:
  17765. case SPIRType::UShort:
  17766. case SPIRType::Int:
  17767. case SPIRType::UInt:
  17768. case SPIRType::Int64:
  17769. case SPIRType::UInt64:
  17770. case SPIRType::AtomicCounter:
  17771. case SPIRType::Half:
  17772. case SPIRType::Float:
  17773. case SPIRType::Double:
  17774. add_argument_buffer_padding_buffer_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
  17775. break;
  17776. case SPIRType::Image:
  17777. add_argument_buffer_padding_image_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
  17778. break;
  17779. case SPIRType::Sampler:
  17780. add_argument_buffer_padding_sampler_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
  17781. break;
  17782. case SPIRType::SampledImage:
  17783. if (next_arg_buff_index == rez_bind.msl_sampler)
  17784. add_argument_buffer_padding_sampler_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
  17785. else
  17786. add_argument_buffer_padding_image_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
  17787. break;
  17788. default:
  17789. break;
  17790. }
  17791. // After padding, retrieve the resource again. It will either be more padding, or the actual resource.
  17792. rez_bind = get_argument_buffer_resource(desc_set, next_arg_buff_index);
  17793. prev_was_scalar_on_array_offset = 0;
  17794. }
  17795. uint32_t count = rez_bind.count;
  17796. // If the current resource is an array in the descriptor, but is a scalar
  17797. // in the shader, only the first element will be consumed. The next pass
  17798. // will add a padding member to consume the remaining array elements.
  17799. if (count > 1 && type.array.empty())
  17800. count = prev_was_scalar_on_array_offset = 1;
  17801. // Adjust the number of slots consumed by current member itself.
  17802. next_arg_buff_index += resource.plane_count * count;
  17803. }
  17804. // Here we're locking down the member name early before compilation loops, so ensure that
  17805. // the resource name is not reused, even through a reset().
  17806. string mbr_name = ensure_valid_name(resource.name, "m");
  17807. if (resource.plane > 0)
  17808. mbr_name += join(plane_name_suffix, resource.plane);
  17809. set_member_name(buffer_type.self, member_index, mbr_name);
  17810. if (resource.basetype == SPIRType::Sampler && type.basetype != SPIRType::Sampler)
  17811. {
  17812. // Have to synthesize a sampler type here.
  17813. bool type_is_array = !type.array.empty();
  17814. uint32_t sampler_type_id = ir.increase_bound_by(type_is_array ? 2 : 1);
  17815. auto &new_sampler_type = set<SPIRType>(sampler_type_id, OpTypeSampler);
  17816. new_sampler_type.basetype = SPIRType::Sampler;
  17817. new_sampler_type.storage = StorageClassUniformConstant;
  17818. if (type_is_array)
  17819. {
  17820. uint32_t sampler_type_array_id = sampler_type_id + 1;
  17821. auto &sampler_type_array = set<SPIRType>(sampler_type_array_id, OpTypeArray);
  17822. sampler_type_array = new_sampler_type;
  17823. sampler_type_array.array = type.array;
  17824. sampler_type_array.array_size_literal = type.array_size_literal;
  17825. sampler_type_array.parent_type = sampler_type_id;
  17826. buffer_type.member_types.push_back(sampler_type_array_id);
  17827. }
  17828. else
  17829. buffer_type.member_types.push_back(sampler_type_id);
  17830. }
  17831. else
  17832. {
  17833. uint32_t binding = get_decoration(var.self, DecorationBinding);
  17834. SetBindingPair pair = { desc_set, binding };
  17835. if (resource.basetype == SPIRType::Image || resource.basetype == SPIRType::Sampler ||
  17836. resource.basetype == SPIRType::SampledImage || resource.basetype == SPIRType::AccelerationStructure)
  17837. {
  17838. // Drop pointer information when we emit the resources into a struct.
  17839. buffer_type.member_types.push_back(get_variable_data_type_id(var));
  17840. if (has_extended_decoration(var.self, SPIRVCrossDecorationOverlappingBinding))
  17841. {
  17842. if (!msl_options.supports_msl_version(3, 0))
  17843. SPIRV_CROSS_THROW("Full mutable aliasing of argument buffer descriptors only works on Metal 3+.");
  17844. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  17845. entry_func.fixup_hooks_in.push_back([this, resource]() {
  17846. emit_argument_buffer_aliased_descriptor(*resource.var, this->get<SPIRVariable>(resource.overlapping_var_id));
  17847. });
  17848. }
  17849. else if (resource.plane == 0)
  17850. {
  17851. set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name));
  17852. }
  17853. }
  17854. else if (buffers_requiring_dynamic_offset.count(pair))
  17855. {
  17856. // Don't set the qualified name here; we'll define a variable holding the corrected buffer address later.
  17857. buffer_type.member_types.push_back(var.basetype);
  17858. auto &dynamic_buffer = buffers_requiring_dynamic_offset[pair];
  17859. dynamic_buffer.var_id = var.self;
  17860. dynamic_buffer.mbr_name = mbr_name;
  17861. }
  17862. else if (inline_uniform_blocks.count(pair))
  17863. {
  17864. // Put the buffer block itself into the argument buffer.
  17865. buffer_type.member_types.push_back(get_variable_data_type_id(var));
  17866. set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name));
  17867. }
  17868. else if (atomic_image_vars_emulated.count(var.self))
  17869. {
  17870. // Emulate texture2D atomic operations.
  17871. // Don't set the qualified name: it's already set for this variable,
  17872. // and the code that references the buffer manually appends "_atomic"
  17873. // to the name.
  17874. uint32_t offset = ir.increase_bound_by(2);
  17875. uint32_t atomic_type_id = offset;
  17876. uint32_t type_ptr_id = offset + 1;
  17877. SPIRType atomic_type { OpTypeInt };
  17878. atomic_type.basetype = SPIRType::AtomicCounter;
  17879. atomic_type.width = 32;
  17880. atomic_type.vecsize = 1;
  17881. set<SPIRType>(atomic_type_id, atomic_type);
  17882. atomic_type.op = OpTypePointer;
  17883. atomic_type.pointer = true;
  17884. atomic_type.pointer_depth++;
  17885. atomic_type.parent_type = atomic_type_id;
  17886. atomic_type.storage = StorageClassStorageBuffer;
  17887. auto &atomic_ptr_type = set<SPIRType>(type_ptr_id, atomic_type);
  17888. atomic_ptr_type.self = atomic_type_id;
  17889. buffer_type.member_types.push_back(type_ptr_id);
  17890. }
  17891. else
  17892. {
  17893. buffer_type.member_types.push_back(var.basetype);
  17894. if (has_extended_decoration(var.self, SPIRVCrossDecorationOverlappingBinding))
  17895. {
  17896. // Casting raw pointers is fine since their ABI is fixed, but anything opaque is deeply questionable on Metal 2.
  17897. if (get<SPIRVariable>(resource.overlapping_var_id).storage == StorageClassUniformConstant &&
  17898. !msl_options.supports_msl_version(3, 0))
  17899. {
  17900. SPIRV_CROSS_THROW("Full mutable aliasing of argument buffer descriptors only works on Metal 3+.");
  17901. }
  17902. auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
  17903. entry_func.fixup_hooks_in.push_back([this, resource]() {
  17904. emit_argument_buffer_aliased_descriptor(*resource.var, this->get<SPIRVariable>(resource.overlapping_var_id));
  17905. });
  17906. }
  17907. else if (type.array.empty())
  17908. set_qualified_name(var.self, join("(*", to_name(buffer_variable_id), ".", mbr_name, ")"));
  17909. else
  17910. set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name));
  17911. }
  17912. }
  17913. set_extended_member_decoration(buffer_type.self, member_index, SPIRVCrossDecorationResourceIndexPrimary,
  17914. resource.index);
  17915. set_extended_member_decoration(buffer_type.self, member_index, SPIRVCrossDecorationInterfaceOrigID,
  17916. var.self);
  17917. if (has_extended_decoration(var.self, SPIRVCrossDecorationOverlappingBinding))
  17918. set_extended_member_decoration(buffer_type.self, member_index, SPIRVCrossDecorationOverlappingBinding);
  17919. member_index++;
  17920. }
  17921. if (msl_options.replace_recursive_inputs && type_contains_recursion(buffer_type))
  17922. {
  17923. recursive_inputs.insert(type_id);
  17924. auto &entry_func = this->get<SPIRFunction>(ir.default_entry_point);
  17925. auto addr_space = get_variable_address_space(buffer_var);
  17926. entry_func.fixup_hooks_in.push_back([this, addr_space, buffer_name, buffer_type_name]() {
  17927. statement(addr_space, " auto& ", buffer_name, " = *(", addr_space, " ", buffer_type_name, "*)", buffer_name, "_vp;");
  17928. });
  17929. }
  17930. }
  17931. }
  17932. // Return the resource type of the app-provided resources for the descriptor set,
  17933. // that matches the resource index of the argument buffer index.
  17934. // This is a two-step lookup, first lookup the resource binding number from the argument buffer index,
  17935. // then lookup the resource binding using the binding number.
  17936. const MSLResourceBinding &CompilerMSL::get_argument_buffer_resource(uint32_t desc_set, uint32_t arg_idx) const
  17937. {
  17938. auto stage = get_entry_point().model;
  17939. StageSetBinding arg_idx_tuple = { stage, desc_set, arg_idx };
  17940. auto arg_itr = resource_arg_buff_idx_to_binding_number.find(arg_idx_tuple);
  17941. if (arg_itr != end(resource_arg_buff_idx_to_binding_number))
  17942. {
  17943. StageSetBinding bind_tuple = { stage, desc_set, arg_itr->second };
  17944. auto bind_itr = resource_bindings.find(bind_tuple);
  17945. if (bind_itr != end(resource_bindings))
  17946. return bind_itr->second.first;
  17947. }
  17948. SPIRV_CROSS_THROW("Argument buffer resource base type could not be determined. When padding argument buffer "
  17949. "elements, all descriptor set resources must be supplied with a base type by the app.");
  17950. }
  17951. // Adds an argument buffer padding argument buffer type as one or more members of the struct type at the member index.
  17952. // Metal does not support arrays of buffers, so these are emitted as multiple struct members.
  17953. void CompilerMSL::add_argument_buffer_padding_buffer_type(SPIRType &struct_type, uint32_t &mbr_idx,
  17954. uint32_t &arg_buff_index, MSLResourceBinding &rez_bind)
  17955. {
  17956. if (!argument_buffer_padding_buffer_type_id)
  17957. {
  17958. uint32_t buff_type_id = ir.increase_bound_by(2);
  17959. auto &buff_type = set<SPIRType>(buff_type_id, OpNop);
  17960. buff_type.basetype = rez_bind.basetype;
  17961. buff_type.storage = StorageClassUniformConstant;
  17962. uint32_t ptr_type_id = buff_type_id + 1;
  17963. auto &ptr_type = set<SPIRType>(ptr_type_id, OpTypePointer);
  17964. ptr_type = buff_type;
  17965. ptr_type.op = OpTypePointer;
  17966. ptr_type.pointer = true;
  17967. ptr_type.pointer_depth++;
  17968. ptr_type.parent_type = buff_type_id;
  17969. argument_buffer_padding_buffer_type_id = ptr_type_id;
  17970. }
  17971. add_argument_buffer_padding_type(argument_buffer_padding_buffer_type_id, struct_type, mbr_idx, arg_buff_index, rez_bind.count);
  17972. }
  17973. // Adds an argument buffer padding argument image type as a member of the struct type at the member index.
  17974. void CompilerMSL::add_argument_buffer_padding_image_type(SPIRType &struct_type, uint32_t &mbr_idx,
  17975. uint32_t &arg_buff_index, MSLResourceBinding &rez_bind)
  17976. {
  17977. if (!argument_buffer_padding_image_type_id)
  17978. {
  17979. uint32_t base_type_id = ir.increase_bound_by(2);
  17980. auto &base_type = set<SPIRType>(base_type_id, OpTypeFloat);
  17981. base_type.basetype = SPIRType::Float;
  17982. base_type.width = 32;
  17983. uint32_t img_type_id = base_type_id + 1;
  17984. auto &img_type = set<SPIRType>(img_type_id, OpTypeImage);
  17985. img_type.basetype = SPIRType::Image;
  17986. img_type.storage = StorageClassUniformConstant;
  17987. img_type.image.type = base_type_id;
  17988. img_type.image.dim = Dim2D;
  17989. img_type.image.depth = false;
  17990. img_type.image.arrayed = false;
  17991. img_type.image.ms = false;
  17992. img_type.image.sampled = 1;
  17993. img_type.image.format = ImageFormatUnknown;
  17994. img_type.image.access = AccessQualifierMax;
  17995. argument_buffer_padding_image_type_id = img_type_id;
  17996. }
  17997. add_argument_buffer_padding_type(argument_buffer_padding_image_type_id, struct_type, mbr_idx, arg_buff_index, rez_bind.count);
  17998. }
  17999. // Adds an argument buffer padding argument sampler type as a member of the struct type at the member index.
  18000. void CompilerMSL::add_argument_buffer_padding_sampler_type(SPIRType &struct_type, uint32_t &mbr_idx,
  18001. uint32_t &arg_buff_index, MSLResourceBinding &rez_bind)
  18002. {
  18003. if (!argument_buffer_padding_sampler_type_id)
  18004. {
  18005. uint32_t samp_type_id = ir.increase_bound_by(1);
  18006. auto &samp_type = set<SPIRType>(samp_type_id, OpTypeSampler);
  18007. samp_type.basetype = SPIRType::Sampler;
  18008. samp_type.storage = StorageClassUniformConstant;
  18009. argument_buffer_padding_sampler_type_id = samp_type_id;
  18010. }
  18011. add_argument_buffer_padding_type(argument_buffer_padding_sampler_type_id, struct_type, mbr_idx, arg_buff_index, rez_bind.count);
  18012. }
  18013. // Adds the argument buffer padding argument type as a member of the struct type at the member index.
  18014. // Advances both arg_buff_index and mbr_idx to next argument slots.
  18015. void CompilerMSL::add_argument_buffer_padding_type(uint32_t mbr_type_id, SPIRType &struct_type, uint32_t &mbr_idx,
  18016. uint32_t &arg_buff_index, uint32_t count)
  18017. {
  18018. uint32_t type_id = mbr_type_id;
  18019. if (count > 1)
  18020. {
  18021. uint32_t ary_type_id = ir.increase_bound_by(1);
  18022. auto &ary_type = set<SPIRType>(ary_type_id, get<SPIRType>(type_id));
  18023. ary_type.op = OpTypeArray;
  18024. ary_type.array.push_back(count);
  18025. ary_type.array_size_literal.push_back(true);
  18026. ary_type.parent_type = type_id;
  18027. type_id = ary_type_id;
  18028. }
  18029. set_member_name(struct_type.self, mbr_idx, join("_m", arg_buff_index, "_pad"));
  18030. set_extended_member_decoration(struct_type.self, mbr_idx, SPIRVCrossDecorationResourceIndexPrimary, arg_buff_index);
  18031. struct_type.member_types.push_back(type_id);
  18032. arg_buff_index += count;
  18033. mbr_idx++;
  18034. }
  18035. void CompilerMSL::activate_argument_buffer_resources()
  18036. {
  18037. // For ABI compatibility, force-enable all resources which are part of argument buffers.
  18038. ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, const SPIRVariable &) {
  18039. if (!has_decoration(self, DecorationDescriptorSet))
  18040. return;
  18041. uint32_t desc_set = get_decoration(self, DecorationDescriptorSet);
  18042. if (descriptor_set_is_argument_buffer(desc_set))
  18043. add_active_interface_variable(self);
  18044. });
  18045. }
  18046. bool CompilerMSL::using_builtin_array() const
  18047. {
  18048. return msl_options.force_native_arrays || is_using_builtin_array;
  18049. }
  18050. void CompilerMSL::set_combined_sampler_suffix(const char *suffix)
  18051. {
  18052. sampler_name_suffix = suffix;
  18053. }
  18054. const char *CompilerMSL::get_combined_sampler_suffix() const
  18055. {
  18056. return sampler_name_suffix.c_str();
  18057. }
  18058. bool CompilerMSL::specialization_constant_is_macro(uint32_t const_id) const
  18059. {
  18060. return constant_macro_ids.find(const_id) != constant_macro_ids.end();
  18061. }
  18062. // Start with all fast math flags enabled, and selectively disable based execution modes and float controls
  18063. uint32_t CompilerMSL::get_fp_fast_math_flags(bool incl_ops) const
  18064. {
  18065. uint32_t fp_flags = ~0;
  18066. auto &ep = get_entry_point();
  18067. if (ep.flags.get(ExecutionModeSignedZeroInfNanPreserve))
  18068. fp_flags &= ~(FPFastMathModeNSZMask | FPFastMathModeNotInfMask | FPFastMathModeNotNaNMask);
  18069. if (ep.flags.get(ExecutionModeContractionOff))
  18070. fp_flags &= ~(FPFastMathModeAllowContractMask);
  18071. for (auto &fp_pair : ep.fp_fast_math_defaults)
  18072. if (fp_pair.second)
  18073. fp_flags &= get<SPIRConstant>(fp_pair.second).scalar();
  18074. if (incl_ops)
  18075. for (auto &p_m : ir.meta)
  18076. if (p_m.second.decoration.decoration_flags.get(DecorationFPFastMathMode))
  18077. fp_flags &= p_m.second.decoration.fp_fast_math_mode;
  18078. return fp_flags;
  18079. }
  18080. void CompilerMSL::emit_block_hints(const SPIRBlock &)
  18081. {
  18082. }
  18083. void CompilerMSL::emit_mesh_entry_point()
  18084. {
  18085. auto &ep = get_entry_point();
  18086. auto &f = get<SPIRFunction>(ir.default_entry_point);
  18087. const uint32_t func_id = ir.increase_bound_by(3);
  18088. const uint32_t block_id = func_id + 1;
  18089. const uint32_t ret_id = func_id + 2;
  18090. auto &wrapped_main = set<SPIRFunction>(func_id, f.return_type, f.function_type);
  18091. wrapped_main.blocks.push_back(block_id);
  18092. wrapped_main.entry_block = block_id;
  18093. auto &wrapped_entry = set<SPIRBlock>(block_id);
  18094. wrapped_entry.terminator = SPIRBlock::Return;
  18095. // Push call to original 'main'
  18096. Instruction ix = {};
  18097. ix.op = OpFunctionCall;
  18098. ix.offset = uint32_t(ir.spirv.size());
  18099. ix.length = 3;
  18100. ir.spirv.push_back(f.return_type);
  18101. ir.spirv.push_back(ret_id);
  18102. ir.spirv.push_back(ep.self);
  18103. wrapped_entry.ops.push_back(ix);
  18104. // relace entry-point for new one
  18105. SPIREntryPoint proxy_ep = ep;
  18106. proxy_ep.self = func_id;
  18107. ir.entry_points.insert(std::make_pair(func_id, proxy_ep));
  18108. ir.meta[func_id] = ir.meta[ir.default_entry_point];
  18109. ir.meta[ir.default_entry_point].decoration.alias.clear();
  18110. ir.default_entry_point = func_id;
  18111. }
  18112. void CompilerMSL::emit_mesh_outputs()
  18113. {
  18114. auto &mode = get_entry_point();
  18115. // predefined thread count or zero, if specialization constant is in use
  18116. uint32_t num_invocations = 0;
  18117. if (mode.workgroup_size.id_x == 0 && mode.workgroup_size.id_y == 0 && mode.workgroup_size.id_z == 0)
  18118. num_invocations = mode.workgroup_size.x * mode.workgroup_size.y * mode.workgroup_size.z;
  18119. statement("threadgroup_barrier(mem_flags::mem_threadgroup);");
  18120. statement("if (spvMeshSizes.y == 0)");
  18121. begin_scope();
  18122. statement("return;");
  18123. end_scope();
  18124. statement("spvMesh.set_primitive_count(spvMeshSizes.y);");
  18125. statement("const uint spvThreadCount [[maybe_unused]] = (gl_WorkGroupSize.x * gl_WorkGroupSize.y * gl_WorkGroupSize.z);");
  18126. if (mesh_out_per_vertex != 0)
  18127. {
  18128. auto &type_vert = get<SPIRType>(mesh_out_per_vertex);
  18129. if (num_invocations < mode.output_vertices)
  18130. {
  18131. statement("for (uint spvVI = gl_LocalInvocationIndex; spvVI < spvMeshSizes.x; spvVI += spvThreadCount)");
  18132. }
  18133. else
  18134. {
  18135. statement("const uint spvVI = gl_LocalInvocationIndex;");
  18136. statement("if (gl_LocalInvocationIndex < spvMeshSizes.x)");
  18137. }
  18138. begin_scope();
  18139. statement("spvPerVertex spvV = {};");
  18140. for (uint32_t index = 0; index < uint32_t(type_vert.member_types.size()); ++index)
  18141. {
  18142. uint32_t orig_var = get_extended_member_decoration(type_vert.self, index, SPIRVCrossDecorationInterfaceOrigID);
  18143. uint32_t orig_id = get_extended_member_decoration(type_vert.self, index, SPIRVCrossDecorationInterfaceMemberIndex);
  18144. // Clip/cull distances are special-case
  18145. if (orig_var == 0 && orig_id == (~0u))
  18146. continue;
  18147. auto &orig = get<SPIRVariable>(orig_var);
  18148. auto &orig_type = get<SPIRType>(orig.basetype);
  18149. // FIXME: Need to deal with complex composite IO types. These may need extra unroll, etc.
  18150. BuiltIn builtin = BuiltInMax;
  18151. std::string access;
  18152. if (orig_type.basetype == SPIRType::Struct)
  18153. {
  18154. if (has_member_decoration(orig_type.self, orig_id, DecorationBuiltIn))
  18155. builtin = BuiltIn(get_member_decoration(orig_type.self, orig_id, DecorationBuiltIn));
  18156. switch (builtin)
  18157. {
  18158. case BuiltInPosition:
  18159. case BuiltInPointSize:
  18160. case BuiltInClipDistance:
  18161. case BuiltInCullDistance:
  18162. access = "." + builtin_to_glsl(builtin, StorageClassOutput);
  18163. break;
  18164. default:
  18165. access = "." + to_member_name(orig_type, orig_id);
  18166. break;
  18167. }
  18168. if (has_member_decoration(type_vert.self, index, DecorationIndex))
  18169. {
  18170. // Declare the Clip/CullDistance as [[user(clip/cullN)]].
  18171. const uint32_t orig_index = get_member_decoration(type_vert.self, index, DecorationIndex);
  18172. access += "[" + to_string(orig_index) + "]";
  18173. statement("spvV.", builtin_to_glsl(builtin, StorageClassOutput), "[", orig_index, "] = ", to_name(orig_var), "[spvVI]", access, ";");
  18174. }
  18175. }
  18176. statement("spvV.", to_member_name(type_vert, index), " = ", to_name(orig_var), "[spvVI]", access, ";");
  18177. if (options.vertex.flip_vert_y && builtin == BuiltInPosition)
  18178. {
  18179. statement("spvV.", to_member_name(type_vert, index), ".y = -(", "spvV.",
  18180. to_member_name(type_vert, index), ".y);", " // Invert Y-axis for Metal");
  18181. }
  18182. }
  18183. statement("spvMesh.set_vertex(spvVI, spvV);");
  18184. end_scope();
  18185. }
  18186. if (mesh_out_per_primitive != 0 || builtin_mesh_primitive_indices_id != 0)
  18187. {
  18188. if (num_invocations < mode.output_primitives)
  18189. {
  18190. statement("for (uint spvPI = gl_LocalInvocationIndex; spvPI < spvMeshSizes.y; spvPI += spvThreadCount)");
  18191. }
  18192. else
  18193. {
  18194. statement("const uint spvPI = gl_LocalInvocationIndex;");
  18195. statement("if (gl_LocalInvocationIndex < spvMeshSizes.y)");
  18196. }
  18197. // FIXME: Need to deal with complex composite IO types. These may need extra unroll, etc.
  18198. begin_scope();
  18199. if (builtin_mesh_primitive_indices_id != 0)
  18200. {
  18201. if (mode.flags.get(ExecutionModeOutputTrianglesEXT))
  18202. {
  18203. statement("spvMesh.set_index(spvPI * 3u + 0u, gl_PrimitiveTriangleIndicesEXT[spvPI].x);");
  18204. statement("spvMesh.set_index(spvPI * 3u + 1u, gl_PrimitiveTriangleIndicesEXT[spvPI].y);");
  18205. statement("spvMesh.set_index(spvPI * 3u + 2u, gl_PrimitiveTriangleIndicesEXT[spvPI].z);");
  18206. }
  18207. else if (mode.flags.get(ExecutionModeOutputLinesEXT))
  18208. {
  18209. statement("spvMesh.set_index(spvPI * 2u + 0u, gl_PrimitiveLineIndicesEXT[spvPI].x);");
  18210. statement("spvMesh.set_index(spvPI * 2u + 1u, gl_PrimitiveLineIndicesEXT[spvPI].y);");
  18211. }
  18212. else
  18213. {
  18214. statement("spvMesh.set_index(spvPI, gl_PrimitivePointIndicesEXT[spvPI]);");
  18215. }
  18216. }
  18217. if (mesh_out_per_primitive != 0)
  18218. {
  18219. auto &type_prim = get<SPIRType>(mesh_out_per_primitive);
  18220. statement("spvPerPrimitive spvP = {};");
  18221. for (uint32_t index = 0; index < uint32_t(type_prim.member_types.size()); ++index)
  18222. {
  18223. uint32_t orig_var =
  18224. get_extended_member_decoration(type_prim.self, index, SPIRVCrossDecorationInterfaceOrigID);
  18225. uint32_t orig_id =
  18226. get_extended_member_decoration(type_prim.self, index, SPIRVCrossDecorationInterfaceMemberIndex);
  18227. auto &orig = get<SPIRVariable>(orig_var);
  18228. auto &orig_type = get<SPIRType>(orig.basetype);
  18229. BuiltIn builtin = BuiltInMax;
  18230. std::string access;
  18231. if (orig_type.basetype == SPIRType::Struct)
  18232. {
  18233. if (has_member_decoration(orig_type.self, orig_id, DecorationBuiltIn))
  18234. builtin = BuiltIn(get_member_decoration(orig_type.self, orig_id, DecorationBuiltIn));
  18235. switch (builtin)
  18236. {
  18237. case BuiltInPrimitiveId:
  18238. case BuiltInLayer:
  18239. case BuiltInViewportIndex:
  18240. case BuiltInCullPrimitiveEXT:
  18241. case BuiltInPrimitiveShadingRateKHR:
  18242. access = "." + builtin_to_glsl(builtin, StorageClassOutput);
  18243. break;
  18244. default:
  18245. access = "." + to_member_name(orig_type, orig_id);
  18246. }
  18247. }
  18248. statement("spvP.", to_member_name(type_prim, index), " = ", to_name(orig_var), "[spvPI]", access, ";");
  18249. }
  18250. statement("spvMesh.set_primitive(spvPI, spvP);");
  18251. }
  18252. end_scope();
  18253. }
  18254. }
  18255. void CompilerMSL::emit_mesh_tasks(SPIRBlock &block)
  18256. {
  18257. // GLSL: Once this instruction is called, the workgroup must be terminated immediately, and the mesh shaders are launched.
  18258. // TODO: find relieble and clean of terminating shader.
  18259. flush_variable_declaration(builtin_task_grid_id);
  18260. statement("spvMgp.set_threadgroups_per_grid(uint3(", to_unpacked_expression(block.mesh.groups[0]), ", ",
  18261. to_unpacked_expression(block.mesh.groups[1]), ", ", to_unpacked_expression(block.mesh.groups[2]), "));");
  18262. // This is correct if EmitMeshTasks is called in the entry function for shader.
  18263. // Only viable solutions would be:
  18264. // - Caller ensures the SPIR-V is inlined, then this always holds true.
  18265. // - Pass down a "should terminate" bool to leaf functions and chain return (horrible and disgusting, let's not).
  18266. statement("return;");
  18267. }
  18268. void CompilerMSL::emit_workgroup_initialization(const SPIRVariable &var)
  18269. {
  18270. auto &type = get_variable_data_type(var);
  18271. begin_scope();
  18272. if (type.array.empty() && type.member_types.empty())
  18273. {
  18274. // For simple shared variables, we just initialize it in thread 0 of the block
  18275. // We use short to represent bool for threadgroup variable to workaround compiler bug,
  18276. // so we do a temporary fixup here. Alas. (see the type_to_glsl method)
  18277. bool is_boolean = type.basetype == SPIRType::Boolean;
  18278. if (is_boolean)
  18279. type.basetype = SPIRType::Short;
  18280. statement("if (gl_LocalInvocationIndex == 0)");
  18281. begin_scope();
  18282. statement(to_name(var.self), " = ", to_initializer_expression(var), ";");
  18283. end_scope();
  18284. if (is_boolean)
  18285. type.basetype = SPIRType::Boolean;
  18286. }
  18287. else
  18288. {
  18289. // Otherwise, we use a loop to cooperatively initialize the memory within the group
  18290. // First, we define a few variable names;
  18291. string var_name = to_name(var.self);
  18292. string var_ptr_name = join(var_name, "_ptr");
  18293. string var_size_name = join(var_name, "_sz");
  18294. string var_pos_name = join(var_name, "_pos");
  18295. string var_stride_name = join(var_name, "_stride");
  18296. string var_ptr2_name = join(var_name, "_ptr2");
  18297. statement("threadgroup uint *", var_ptr_name, " = (threadgroup uint *)&", var_name, ";");
  18298. statement("uint ", var_size_name, " = ", "sizeof(", var_name, ");");
  18299. statement("uint ", var_pos_name, " = gl_LocalInvocationIndex;");
  18300. statement("uint ", var_stride_name, " = gl_WorkGroupSize.x * gl_WorkGroupSize.y * gl_WorkGroupSize.z;");
  18301. statement("while (sizeof(uint) * ", var_pos_name, " < ", var_size_name, ")");
  18302. begin_scope();
  18303. statement(var_ptr_name, "[", var_pos_name, "] = 0u;");
  18304. statement(var_pos_name, " += ", var_stride_name, ";");
  18305. end_scope();
  18306. statement("if (gl_LocalInvocationIndex == 0)");
  18307. begin_scope();
  18308. statement(var_pos_name, " = (", var_size_name, " / sizeof(uint)) * sizeof(uint);");
  18309. statement("threadgroup uchar *", var_ptr2_name, " = (threadgroup uchar *)&", var_name, ";");
  18310. statement("while (", var_pos_name, " < ", var_size_name, ")");
  18311. begin_scope();
  18312. statement(var_ptr2_name, "[", var_pos_name, "] = '\\0';");
  18313. statement(var_pos_name, "++;");
  18314. end_scope();
  18315. end_scope();
  18316. }
  18317. statement("threadgroup_barrier(mem_flags::mem_threadgroup);");
  18318. end_scope();
  18319. }
  18320. string CompilerMSL::additional_fixed_sample_mask_str() const
  18321. {
  18322. char print_buffer[32];
  18323. #ifdef _MSC_VER
  18324. // snprintf does not exist or is buggy on older MSVC versions, some of
  18325. // them being used by MinGW. Use sprintf instead and disable
  18326. // corresponding warning.
  18327. #pragma warning(push)
  18328. #pragma warning(disable : 4996)
  18329. #endif
  18330. #if defined(_WIN32)
  18331. sprintf(print_buffer, "0x%x", msl_options.additional_fixed_sample_mask);
  18332. #else
  18333. snprintf(print_buffer, sizeof(print_buffer), "0x%x", msl_options.additional_fixed_sample_mask);
  18334. #endif
  18335. #ifdef _MSC_VER
  18336. #pragma warning(pop)
  18337. #endif
  18338. return print_buffer;
  18339. }